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::{hash_map, 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::{
   55    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   56};
   57use futures::FutureExt;
   58use fuzzy::{StringMatch, StringMatchCandidate};
   59use git::diff_hunk_to_display;
   60use gpui::{
   61    div, impl_actions, point, prelude::*, px, relative, rems, size, uniform_list, Action,
   62    AnyElement, AppContext, AsyncWindowContext, BackgroundExecutor, Bounds, ClipboardItem, Context,
   63    DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusableView, FontId, FontStyle,
   64    FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, MouseButton,
   65    ParentElement, Pixels, Render, SharedString, StrikethroughStyle, Styled, StyledText,
   66    Subscription, Task, TextStyle, UnderlineStyle, UniformListScrollHandle, View, ViewContext,
   67    ViewInputHandler, VisualContext, WeakView, WhiteSpace, WindowContext,
   68};
   69use highlight_matching_bracket::refresh_matching_bracket_highlights;
   70use hover_popover::{hide_hover, HoverState};
   71use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   72pub use items::MAX_TAB_TITLE_LEN;
   73use itertools::Itertools;
   74use language::{char_kind, CharKind};
   75use language::{
   76    language_settings::{self, all_language_settings, InlayHintSettings},
   77    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CodeAction,
   78    CodeLabel, Completion, CursorShape, Diagnostic, Documentation, IndentKind, IndentSize,
   79    Language, OffsetRangeExt, Point, Selection, SelectionGoal, TransactionId,
   80};
   81
   82use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
   83use lsp::{DiagnosticSeverity, LanguageServerId};
   84use mouse_context_menu::MouseContextMenu;
   85use movement::TextLayoutDetails;
   86use multi_buffer::ToOffsetUtf16;
   87pub use multi_buffer::{
   88    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
   89    ToPoint,
   90};
   91use ordered_float::OrderedFloat;
   92use parking_lot::{Mutex, RwLock};
   93use project::project_settings::{GitGutterSetting, ProjectSettings};
   94use project::Item;
   95use project::{FormatTrigger, Location, Project, ProjectPath, ProjectTransaction};
   96use rand::prelude::*;
   97use rpc::proto::*;
   98use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
   99use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  100use serde::{Deserialize, Serialize};
  101use settings::{Settings, SettingsStore};
  102use smallvec::SmallVec;
  103use snippet::Snippet;
  104use std::{
  105    any::TypeId,
  106    borrow::Cow,
  107    cmp::{self, Ordering, Reverse},
  108    mem,
  109    num::NonZeroU32,
  110    ops::{ControlFlow, Deref, DerefMut, Range, RangeInclusive},
  111    path::Path,
  112    sync::Arc,
  113    time::{Duration, Instant},
  114};
  115pub use sum_tree::Bias;
  116use text::{BufferId, OffsetUtf16, Rope};
  117use theme::{
  118    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  119    ThemeColors, ThemeSettings,
  120};
  121use ui::{
  122    h_flex, prelude::*, ButtonSize, ButtonStyle, IconButton, IconName, IconSize, ListItem, Popover,
  123    Tooltip,
  124};
  125use util::{maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  126use workspace::Toast;
  127use workspace::{searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace};
  128
  129use crate::hover_links::find_url;
  130
  131const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  132const MAX_LINE_LEN: usize = 1024;
  133const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  134const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  135const COPILOT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  136pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  137#[doc(hidden)]
  138pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  139#[doc(hidden)]
  140pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  141
  142pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  143
  144pub fn render_parsed_markdown(
  145    element_id: impl Into<ElementId>,
  146    parsed: &language::ParsedMarkdown,
  147    editor_style: &EditorStyle,
  148    workspace: Option<WeakView<Workspace>>,
  149    cx: &mut ViewContext<Editor>,
  150) -> InteractiveText {
  151    let code_span_background_color = cx
  152        .theme()
  153        .colors()
  154        .editor_document_highlight_read_background;
  155
  156    let highlights = gpui::combine_highlights(
  157        parsed.highlights.iter().filter_map(|(range, highlight)| {
  158            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  159            Some((range.clone(), highlight))
  160        }),
  161        parsed
  162            .regions
  163            .iter()
  164            .zip(&parsed.region_ranges)
  165            .filter_map(|(region, range)| {
  166                if region.code {
  167                    Some((
  168                        range.clone(),
  169                        HighlightStyle {
  170                            background_color: Some(code_span_background_color),
  171                            ..Default::default()
  172                        },
  173                    ))
  174                } else {
  175                    None
  176                }
  177            }),
  178    );
  179
  180    let mut links = Vec::new();
  181    let mut link_ranges = Vec::new();
  182    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  183        if let Some(link) = region.link.clone() {
  184            links.push(link);
  185            link_ranges.push(range.clone());
  186        }
  187    }
  188
  189    InteractiveText::new(
  190        element_id,
  191        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  192    )
  193    .on_click(link_ranges, move |clicked_range_ix, cx| {
  194        match &links[clicked_range_ix] {
  195            markdown::Link::Web { url } => cx.open_url(url),
  196            markdown::Link::Path { path } => {
  197                if let Some(workspace) = &workspace {
  198                    _ = workspace.update(cx, |workspace, cx| {
  199                        workspace.open_abs_path(path.clone(), false, cx).detach();
  200                    });
  201                }
  202            }
  203        }
  204    })
  205}
  206
  207#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  208pub(crate) enum InlayId {
  209    Suggestion(usize),
  210    Hint(usize),
  211}
  212
  213impl InlayId {
  214    fn id(&self) -> usize {
  215        match self {
  216            Self::Suggestion(id) => *id,
  217            Self::Hint(id) => *id,
  218        }
  219    }
  220}
  221
  222enum DocumentHighlightRead {}
  223enum DocumentHighlightWrite {}
  224enum InputComposition {}
  225
  226#[derive(Copy, Clone, PartialEq, Eq)]
  227pub enum Direction {
  228    Prev,
  229    Next,
  230}
  231
  232pub fn init_settings(cx: &mut AppContext) {
  233    EditorSettings::register(cx);
  234}
  235
  236pub fn init(cx: &mut AppContext) {
  237    init_settings(cx);
  238
  239    workspace::register_project_item::<Editor>(cx);
  240    workspace::register_followable_item::<Editor>(cx);
  241    workspace::register_deserializable_item::<Editor>(cx);
  242    cx.observe_new_views(
  243        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  244            workspace.register_action(Editor::new_file);
  245            workspace.register_action(Editor::new_file_in_direction);
  246        },
  247    )
  248    .detach();
  249
  250    cx.on_action(move |_: &workspace::NewFile, cx| {
  251        let app_state = workspace::AppState::global(cx);
  252        if let Some(app_state) = app_state.upgrade() {
  253            workspace::open_new(app_state, cx, |workspace, cx| {
  254                Editor::new_file(workspace, &Default::default(), cx)
  255            })
  256            .detach();
  257        }
  258    });
  259    cx.on_action(move |_: &workspace::NewWindow, cx| {
  260        let app_state = workspace::AppState::global(cx);
  261        if let Some(app_state) = app_state.upgrade() {
  262            workspace::open_new(app_state, cx, |workspace, cx| {
  263                Editor::new_file(workspace, &Default::default(), cx)
  264            })
  265            .detach();
  266        }
  267    });
  268}
  269
  270trait InvalidationRegion {
  271    fn ranges(&self) -> &[Range<Anchor>];
  272}
  273
  274#[derive(Clone, Debug, PartialEq)]
  275pub enum SelectPhase {
  276    Begin {
  277        position: DisplayPoint,
  278        add: bool,
  279        click_count: usize,
  280    },
  281    BeginColumnar {
  282        position: DisplayPoint,
  283        goal_column: u32,
  284    },
  285    Extend {
  286        position: DisplayPoint,
  287        click_count: usize,
  288    },
  289    Update {
  290        position: DisplayPoint,
  291        goal_column: u32,
  292        scroll_delta: gpui::Point<f32>,
  293    },
  294    End,
  295}
  296
  297#[derive(Clone, Debug)]
  298pub enum SelectMode {
  299    Character,
  300    Word(Range<Anchor>),
  301    Line(Range<Anchor>),
  302    All,
  303}
  304
  305#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  306pub enum EditorMode {
  307    SingleLine,
  308    AutoHeight { max_lines: usize },
  309    Full,
  310}
  311
  312#[derive(Clone, Debug)]
  313pub enum SoftWrap {
  314    None,
  315    EditorWidth,
  316    Column(u32),
  317}
  318
  319#[derive(Clone)]
  320pub struct EditorStyle {
  321    pub background: Hsla,
  322    pub local_player: PlayerColor,
  323    pub text: TextStyle,
  324    pub scrollbar_width: Pixels,
  325    pub syntax: Arc<SyntaxTheme>,
  326    pub status: StatusColors,
  327    pub inlay_hints_style: HighlightStyle,
  328    pub suggestions_style: HighlightStyle,
  329}
  330
  331impl Default for EditorStyle {
  332    fn default() -> Self {
  333        Self {
  334            background: Hsla::default(),
  335            local_player: PlayerColor::default(),
  336            text: TextStyle::default(),
  337            scrollbar_width: Pixels::default(),
  338            syntax: Default::default(),
  339            // HACK: Status colors don't have a real default.
  340            // We should look into removing the status colors from the editor
  341            // style and retrieve them directly from the theme.
  342            status: StatusColors::dark(),
  343            inlay_hints_style: HighlightStyle::default(),
  344            suggestions_style: HighlightStyle::default(),
  345        }
  346    }
  347}
  348
  349type CompletionId = usize;
  350
  351// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  352// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  353
  354type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Vec<Range<Anchor>>);
  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    highlight_order: usize,
  392    highlighted_rows: HashMap<TypeId, Vec<(usize, Range<Anchor>, Hsla)>>,
  393    background_highlights: BTreeMap<TypeId, BackgroundHighlight>,
  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            highlight_order: 0,
 1530            highlighted_rows: HashMap::default(),
 1531            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        &mut 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        cx: &mut ViewContext<Self>,
 4214    ) -> Vec<Option<AnyElement>> {
 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(cx.listener(move |this, _e, cx| match fold_status {
 4224                                    FoldStatus::Folded => {
 4225                                        this.unfold_at(&UnfoldAt { buffer_row }, cx);
 4226                                    }
 4227                                    FoldStatus::Foldable => {
 4228                                        this.fold_at(&FoldAt { buffer_row }, cx);
 4229                                    }
 4230                                }))
 4231                                .icon_color(ui::Color::Muted)
 4232                                .icon_size(ui::IconSize::Small)
 4233                                .selected(fold_status == FoldStatus::Folded)
 4234                                .selected_icon(ui::IconName::ChevronRight)
 4235                                .size(ui::ButtonSize::None)
 4236                                .into_any_element()
 4237                        })
 4238                    })
 4239                    .flatten()
 4240            })
 4241            .collect()
 4242    }
 4243
 4244    pub fn context_menu_visible(&self) -> bool {
 4245        self.context_menu
 4246            .read()
 4247            .as_ref()
 4248            .map_or(false, |menu| menu.visible())
 4249    }
 4250
 4251    pub fn render_context_menu(
 4252        &self,
 4253        cursor_position: DisplayPoint,
 4254        style: &EditorStyle,
 4255        max_height: Pixels,
 4256        cx: &mut ViewContext<Editor>,
 4257    ) -> Option<(DisplayPoint, AnyElement)> {
 4258        self.context_menu.read().as_ref().map(|menu| {
 4259            menu.render(
 4260                cursor_position,
 4261                style,
 4262                max_height,
 4263                self.workspace.as_ref().map(|(w, _)| w.clone()),
 4264                cx,
 4265            )
 4266        })
 4267    }
 4268
 4269    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 4270        cx.notify();
 4271        self.completion_tasks.clear();
 4272        let context_menu = self.context_menu.write().take();
 4273        if context_menu.is_some() {
 4274            self.update_visible_copilot_suggestion(cx);
 4275        }
 4276        context_menu
 4277    }
 4278
 4279    pub fn insert_snippet(
 4280        &mut self,
 4281        insertion_ranges: &[Range<usize>],
 4282        snippet: Snippet,
 4283        cx: &mut ViewContext<Self>,
 4284    ) -> Result<()> {
 4285        let tabstops = self.buffer.update(cx, |buffer, cx| {
 4286            let snippet_text: Arc<str> = snippet.text.clone().into();
 4287            buffer.edit(
 4288                insertion_ranges
 4289                    .iter()
 4290                    .cloned()
 4291                    .map(|range| (range, snippet_text.clone())),
 4292                Some(AutoindentMode::EachLine),
 4293                cx,
 4294            );
 4295
 4296            let snapshot = &*buffer.read(cx);
 4297            let snippet = &snippet;
 4298            snippet
 4299                .tabstops
 4300                .iter()
 4301                .map(|tabstop| {
 4302                    let mut tabstop_ranges = tabstop
 4303                        .iter()
 4304                        .flat_map(|tabstop_range| {
 4305                            let mut delta = 0_isize;
 4306                            insertion_ranges.iter().map(move |insertion_range| {
 4307                                let insertion_start = insertion_range.start as isize + delta;
 4308                                delta +=
 4309                                    snippet.text.len() as isize - insertion_range.len() as isize;
 4310
 4311                                let start = snapshot.anchor_before(
 4312                                    (insertion_start + tabstop_range.start) as usize,
 4313                                );
 4314                                let end = snapshot
 4315                                    .anchor_after((insertion_start + tabstop_range.end) as usize);
 4316                                start..end
 4317                            })
 4318                        })
 4319                        .collect::<Vec<_>>();
 4320                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 4321                    tabstop_ranges
 4322                })
 4323                .collect::<Vec<_>>()
 4324        });
 4325
 4326        if let Some(tabstop) = tabstops.first() {
 4327            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4328                s.select_ranges(tabstop.iter().cloned());
 4329            });
 4330            self.snippet_stack.push(SnippetState {
 4331                active_index: 0,
 4332                ranges: tabstops,
 4333            });
 4334
 4335            // Check whether the just-entered snippet ends with an auto-closable bracket.
 4336            if self.autoclose_regions.is_empty() {
 4337                let snapshot = self.buffer.read(cx).snapshot(cx);
 4338                for selection in &mut self.selections.all::<Point>(cx) {
 4339                    let selection_head = selection.head();
 4340                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 4341                        continue;
 4342                    };
 4343
 4344                    let mut bracket_pair = None;
 4345                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 4346                    let prev_chars = snapshot
 4347                        .reversed_chars_at(selection_head)
 4348                        .collect::<String>();
 4349                    for (pair, enabled) in scope.brackets() {
 4350                        if enabled
 4351                            && pair.close
 4352                            && prev_chars.starts_with(pair.start.as_str())
 4353                            && next_chars.starts_with(pair.end.as_str())
 4354                        {
 4355                            bracket_pair = Some(pair.clone());
 4356                            break;
 4357                        }
 4358                    }
 4359                    if let Some(pair) = bracket_pair {
 4360                        let start = snapshot.anchor_after(selection_head);
 4361                        let end = snapshot.anchor_after(selection_head);
 4362                        self.autoclose_regions.push(AutocloseRegion {
 4363                            selection_id: selection.id,
 4364                            range: start..end,
 4365                            pair,
 4366                        });
 4367                    }
 4368                }
 4369            }
 4370        }
 4371        Ok(())
 4372    }
 4373
 4374    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 4375        self.move_to_snippet_tabstop(Bias::Right, cx)
 4376    }
 4377
 4378    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 4379        self.move_to_snippet_tabstop(Bias::Left, cx)
 4380    }
 4381
 4382    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 4383        if let Some(mut snippet) = self.snippet_stack.pop() {
 4384            match bias {
 4385                Bias::Left => {
 4386                    if snippet.active_index > 0 {
 4387                        snippet.active_index -= 1;
 4388                    } else {
 4389                        self.snippet_stack.push(snippet);
 4390                        return false;
 4391                    }
 4392                }
 4393                Bias::Right => {
 4394                    if snippet.active_index + 1 < snippet.ranges.len() {
 4395                        snippet.active_index += 1;
 4396                    } else {
 4397                        self.snippet_stack.push(snippet);
 4398                        return false;
 4399                    }
 4400                }
 4401            }
 4402            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 4403                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4404                    s.select_anchor_ranges(current_ranges.iter().cloned())
 4405                });
 4406                // If snippet state is not at the last tabstop, push it back on the stack
 4407                if snippet.active_index + 1 < snippet.ranges.len() {
 4408                    self.snippet_stack.push(snippet);
 4409                }
 4410                return true;
 4411            }
 4412        }
 4413
 4414        false
 4415    }
 4416
 4417    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 4418        self.transact(cx, |this, cx| {
 4419            this.select_all(&SelectAll, cx);
 4420            this.insert("", cx);
 4421        });
 4422    }
 4423
 4424    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 4425        self.transact(cx, |this, cx| {
 4426            this.select_autoclose_pair(cx);
 4427            let mut selections = this.selections.all::<Point>(cx);
 4428            if !this.selections.line_mode {
 4429                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 4430                for selection in &mut selections {
 4431                    if selection.is_empty() {
 4432                        let old_head = selection.head();
 4433                        let mut new_head =
 4434                            movement::left(&display_map, old_head.to_display_point(&display_map))
 4435                                .to_point(&display_map);
 4436                        if let Some((buffer, line_buffer_range)) = display_map
 4437                            .buffer_snapshot
 4438                            .buffer_line_for_row(old_head.row)
 4439                        {
 4440                            let indent_size =
 4441                                buffer.indent_size_for_line(line_buffer_range.start.row);
 4442                            let indent_len = match indent_size.kind {
 4443                                IndentKind::Space => {
 4444                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 4445                                }
 4446                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 4447                            };
 4448                            if old_head.column <= indent_size.len && old_head.column > 0 {
 4449                                let indent_len = indent_len.get();
 4450                                new_head = cmp::min(
 4451                                    new_head,
 4452                                    Point::new(
 4453                                        old_head.row,
 4454                                        ((old_head.column - 1) / indent_len) * indent_len,
 4455                                    ),
 4456                                );
 4457                            }
 4458                        }
 4459
 4460                        selection.set_head(new_head, SelectionGoal::None);
 4461                    }
 4462                }
 4463            }
 4464
 4465            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 4466            this.insert("", cx);
 4467            this.refresh_copilot_suggestions(true, cx);
 4468        });
 4469    }
 4470
 4471    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 4472        self.transact(cx, |this, cx| {
 4473            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4474                let line_mode = s.line_mode;
 4475                s.move_with(|map, selection| {
 4476                    if selection.is_empty() && !line_mode {
 4477                        let cursor = movement::right(map, selection.head());
 4478                        selection.end = cursor;
 4479                        selection.reversed = true;
 4480                        selection.goal = SelectionGoal::None;
 4481                    }
 4482                })
 4483            });
 4484            this.insert("", cx);
 4485            this.refresh_copilot_suggestions(true, cx);
 4486        });
 4487    }
 4488
 4489    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 4490        if self.move_to_prev_snippet_tabstop(cx) {
 4491            return;
 4492        }
 4493
 4494        self.outdent(&Outdent, cx);
 4495    }
 4496
 4497    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 4498        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 4499            return;
 4500        }
 4501
 4502        let mut selections = self.selections.all_adjusted(cx);
 4503        let buffer = self.buffer.read(cx);
 4504        let snapshot = buffer.snapshot(cx);
 4505        let rows_iter = selections.iter().map(|s| s.head().row);
 4506        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 4507
 4508        let mut edits = Vec::new();
 4509        let mut prev_edited_row = 0;
 4510        let mut row_delta = 0;
 4511        for selection in &mut selections {
 4512            if selection.start.row != prev_edited_row {
 4513                row_delta = 0;
 4514            }
 4515            prev_edited_row = selection.end.row;
 4516
 4517            // If the selection is non-empty, then increase the indentation of the selected lines.
 4518            if !selection.is_empty() {
 4519                row_delta =
 4520                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 4521                continue;
 4522            }
 4523
 4524            // If the selection is empty and the cursor is in the leading whitespace before the
 4525            // suggested indentation, then auto-indent the line.
 4526            let cursor = selection.head();
 4527            let current_indent = snapshot.indent_size_for_line(cursor.row);
 4528            if let Some(suggested_indent) = suggested_indents.get(&cursor.row).copied() {
 4529                if cursor.column < suggested_indent.len
 4530                    && cursor.column <= current_indent.len
 4531                    && current_indent.len <= suggested_indent.len
 4532                {
 4533                    selection.start = Point::new(cursor.row, suggested_indent.len);
 4534                    selection.end = selection.start;
 4535                    if row_delta == 0 {
 4536                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 4537                            cursor.row,
 4538                            current_indent,
 4539                            suggested_indent,
 4540                        ));
 4541                        row_delta = suggested_indent.len - current_indent.len;
 4542                    }
 4543                    continue;
 4544                }
 4545            }
 4546
 4547            // Accept copilot suggestion if there is only one selection and the cursor is not
 4548            // in the leading whitespace.
 4549            if self.selections.count() == 1
 4550                && cursor.column >= current_indent.len
 4551                && self.has_active_copilot_suggestion(cx)
 4552            {
 4553                self.accept_copilot_suggestion(cx);
 4554                return;
 4555            }
 4556
 4557            // Otherwise, insert a hard or soft tab.
 4558            let settings = buffer.settings_at(cursor, cx);
 4559            let tab_size = if settings.hard_tabs {
 4560                IndentSize::tab()
 4561            } else {
 4562                let tab_size = settings.tab_size.get();
 4563                let char_column = snapshot
 4564                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 4565                    .flat_map(str::chars)
 4566                    .count()
 4567                    + row_delta as usize;
 4568                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 4569                IndentSize::spaces(chars_to_next_tab_stop)
 4570            };
 4571            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 4572            selection.end = selection.start;
 4573            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 4574            row_delta += tab_size.len;
 4575        }
 4576
 4577        self.transact(cx, |this, cx| {
 4578            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 4579            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 4580            this.refresh_copilot_suggestions(true, cx);
 4581        });
 4582    }
 4583
 4584    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 4585        if self.read_only(cx) {
 4586            return;
 4587        }
 4588        let mut selections = self.selections.all::<Point>(cx);
 4589        let mut prev_edited_row = 0;
 4590        let mut row_delta = 0;
 4591        let mut edits = Vec::new();
 4592        let buffer = self.buffer.read(cx);
 4593        let snapshot = buffer.snapshot(cx);
 4594        for selection in &mut selections {
 4595            if selection.start.row != prev_edited_row {
 4596                row_delta = 0;
 4597            }
 4598            prev_edited_row = selection.end.row;
 4599
 4600            row_delta =
 4601                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 4602        }
 4603
 4604        self.transact(cx, |this, cx| {
 4605            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 4606            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 4607        });
 4608    }
 4609
 4610    fn indent_selection(
 4611        buffer: &MultiBuffer,
 4612        snapshot: &MultiBufferSnapshot,
 4613        selection: &mut Selection<Point>,
 4614        edits: &mut Vec<(Range<Point>, String)>,
 4615        delta_for_start_row: u32,
 4616        cx: &AppContext,
 4617    ) -> u32 {
 4618        let settings = buffer.settings_at(selection.start, cx);
 4619        let tab_size = settings.tab_size.get();
 4620        let indent_kind = if settings.hard_tabs {
 4621            IndentKind::Tab
 4622        } else {
 4623            IndentKind::Space
 4624        };
 4625        let mut start_row = selection.start.row;
 4626        let mut end_row = selection.end.row + 1;
 4627
 4628        // If a selection ends at the beginning of a line, don't indent
 4629        // that last line.
 4630        if selection.end.column == 0 && selection.end.row > selection.start.row {
 4631            end_row -= 1;
 4632        }
 4633
 4634        // Avoid re-indenting a row that has already been indented by a
 4635        // previous selection, but still update this selection's column
 4636        // to reflect that indentation.
 4637        if delta_for_start_row > 0 {
 4638            start_row += 1;
 4639            selection.start.column += delta_for_start_row;
 4640            if selection.end.row == selection.start.row {
 4641                selection.end.column += delta_for_start_row;
 4642            }
 4643        }
 4644
 4645        let mut delta_for_end_row = 0;
 4646        for row in start_row..end_row {
 4647            let current_indent = snapshot.indent_size_for_line(row);
 4648            let indent_delta = match (current_indent.kind, indent_kind) {
 4649                (IndentKind::Space, IndentKind::Space) => {
 4650                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 4651                    IndentSize::spaces(columns_to_next_tab_stop)
 4652                }
 4653                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 4654                (_, IndentKind::Tab) => IndentSize::tab(),
 4655            };
 4656
 4657            let row_start = Point::new(row, 0);
 4658            edits.push((
 4659                row_start..row_start,
 4660                indent_delta.chars().collect::<String>(),
 4661            ));
 4662
 4663            // Update this selection's endpoints to reflect the indentation.
 4664            if row == selection.start.row {
 4665                selection.start.column += indent_delta.len;
 4666            }
 4667            if row == selection.end.row {
 4668                selection.end.column += indent_delta.len;
 4669                delta_for_end_row = indent_delta.len;
 4670            }
 4671        }
 4672
 4673        if selection.start.row == selection.end.row {
 4674            delta_for_start_row + delta_for_end_row
 4675        } else {
 4676            delta_for_end_row
 4677        }
 4678    }
 4679
 4680    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 4681        if self.read_only(cx) {
 4682            return;
 4683        }
 4684        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 4685        let selections = self.selections.all::<Point>(cx);
 4686        let mut deletion_ranges = Vec::new();
 4687        let mut last_outdent = None;
 4688        {
 4689            let buffer = self.buffer.read(cx);
 4690            let snapshot = buffer.snapshot(cx);
 4691            for selection in &selections {
 4692                let settings = buffer.settings_at(selection.start, cx);
 4693                let tab_size = settings.tab_size.get();
 4694                let mut rows = selection.spanned_rows(false, &display_map);
 4695
 4696                // Avoid re-outdenting a row that has already been outdented by a
 4697                // previous selection.
 4698                if let Some(last_row) = last_outdent {
 4699                    if last_row == rows.start {
 4700                        rows.start += 1;
 4701                    }
 4702                }
 4703
 4704                for row in rows {
 4705                    let indent_size = snapshot.indent_size_for_line(row);
 4706                    if indent_size.len > 0 {
 4707                        let deletion_len = match indent_size.kind {
 4708                            IndentKind::Space => {
 4709                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 4710                                if columns_to_prev_tab_stop == 0 {
 4711                                    tab_size
 4712                                } else {
 4713                                    columns_to_prev_tab_stop
 4714                                }
 4715                            }
 4716                            IndentKind::Tab => 1,
 4717                        };
 4718                        deletion_ranges.push(Point::new(row, 0)..Point::new(row, deletion_len));
 4719                        last_outdent = Some(row);
 4720                    }
 4721                }
 4722            }
 4723        }
 4724
 4725        self.transact(cx, |this, cx| {
 4726            this.buffer.update(cx, |buffer, cx| {
 4727                let empty_str: Arc<str> = "".into();
 4728                buffer.edit(
 4729                    deletion_ranges
 4730                        .into_iter()
 4731                        .map(|range| (range, empty_str.clone())),
 4732                    None,
 4733                    cx,
 4734                );
 4735            });
 4736            let selections = this.selections.all::<usize>(cx);
 4737            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 4738        });
 4739    }
 4740
 4741    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 4742        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 4743        let selections = self.selections.all::<Point>(cx);
 4744
 4745        let mut new_cursors = Vec::new();
 4746        let mut edit_ranges = Vec::new();
 4747        let mut selections = selections.iter().peekable();
 4748        while let Some(selection) = selections.next() {
 4749            let mut rows = selection.spanned_rows(false, &display_map);
 4750            let goal_display_column = selection.head().to_display_point(&display_map).column();
 4751
 4752            // Accumulate contiguous regions of rows that we want to delete.
 4753            while let Some(next_selection) = selections.peek() {
 4754                let next_rows = next_selection.spanned_rows(false, &display_map);
 4755                if next_rows.start <= rows.end {
 4756                    rows.end = next_rows.end;
 4757                    selections.next().unwrap();
 4758                } else {
 4759                    break;
 4760                }
 4761            }
 4762
 4763            let buffer = &display_map.buffer_snapshot;
 4764            let mut edit_start = Point::new(rows.start, 0).to_offset(buffer);
 4765            let edit_end;
 4766            let cursor_buffer_row;
 4767            if buffer.max_point().row >= rows.end {
 4768                // If there's a line after the range, delete the \n from the end of the row range
 4769                // and position the cursor on the next line.
 4770                edit_end = Point::new(rows.end, 0).to_offset(buffer);
 4771                cursor_buffer_row = rows.end;
 4772            } else {
 4773                // If there isn't a line after the range, delete the \n from the line before the
 4774                // start of the row range and position the cursor there.
 4775                edit_start = edit_start.saturating_sub(1);
 4776                edit_end = buffer.len();
 4777                cursor_buffer_row = rows.start.saturating_sub(1);
 4778            }
 4779
 4780            let mut cursor = Point::new(cursor_buffer_row, 0).to_display_point(&display_map);
 4781            *cursor.column_mut() =
 4782                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 4783
 4784            new_cursors.push((
 4785                selection.id,
 4786                buffer.anchor_after(cursor.to_point(&display_map)),
 4787            ));
 4788            edit_ranges.push(edit_start..edit_end);
 4789        }
 4790
 4791        self.transact(cx, |this, cx| {
 4792            let buffer = this.buffer.update(cx, |buffer, cx| {
 4793                let empty_str: Arc<str> = "".into();
 4794                buffer.edit(
 4795                    edit_ranges
 4796                        .into_iter()
 4797                        .map(|range| (range, empty_str.clone())),
 4798                    None,
 4799                    cx,
 4800                );
 4801                buffer.snapshot(cx)
 4802            });
 4803            let new_selections = new_cursors
 4804                .into_iter()
 4805                .map(|(id, cursor)| {
 4806                    let cursor = cursor.to_point(&buffer);
 4807                    Selection {
 4808                        id,
 4809                        start: cursor,
 4810                        end: cursor,
 4811                        reversed: false,
 4812                        goal: SelectionGoal::None,
 4813                    }
 4814                })
 4815                .collect();
 4816
 4817            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4818                s.select(new_selections);
 4819            });
 4820        });
 4821    }
 4822
 4823    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 4824        if self.read_only(cx) {
 4825            return;
 4826        }
 4827        let mut row_ranges = Vec::<Range<u32>>::new();
 4828        for selection in self.selections.all::<Point>(cx) {
 4829            let start = selection.start.row;
 4830            let end = if selection.start.row == selection.end.row {
 4831                selection.start.row + 1
 4832            } else {
 4833                selection.end.row
 4834            };
 4835
 4836            if let Some(last_row_range) = row_ranges.last_mut() {
 4837                if start <= last_row_range.end {
 4838                    last_row_range.end = end;
 4839                    continue;
 4840                }
 4841            }
 4842            row_ranges.push(start..end);
 4843        }
 4844
 4845        let snapshot = self.buffer.read(cx).snapshot(cx);
 4846        let mut cursor_positions = Vec::new();
 4847        for row_range in &row_ranges {
 4848            let anchor = snapshot.anchor_before(Point::new(
 4849                row_range.end - 1,
 4850                snapshot.line_len(row_range.end - 1),
 4851            ));
 4852            cursor_positions.push(anchor..anchor);
 4853        }
 4854
 4855        self.transact(cx, |this, cx| {
 4856            for row_range in row_ranges.into_iter().rev() {
 4857                for row in row_range.rev() {
 4858                    let end_of_line = Point::new(row, snapshot.line_len(row));
 4859                    let indent = snapshot.indent_size_for_line(row + 1);
 4860                    let start_of_next_line = Point::new(row + 1, indent.len);
 4861
 4862                    let replace = if snapshot.line_len(row + 1) > indent.len {
 4863                        " "
 4864                    } else {
 4865                        ""
 4866                    };
 4867
 4868                    this.buffer.update(cx, |buffer, cx| {
 4869                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 4870                    });
 4871                }
 4872            }
 4873
 4874            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 4875                s.select_anchor_ranges(cursor_positions)
 4876            });
 4877        });
 4878    }
 4879
 4880    pub fn sort_lines_case_sensitive(
 4881        &mut self,
 4882        _: &SortLinesCaseSensitive,
 4883        cx: &mut ViewContext<Self>,
 4884    ) {
 4885        self.manipulate_lines(cx, |lines| lines.sort())
 4886    }
 4887
 4888    pub fn sort_lines_case_insensitive(
 4889        &mut self,
 4890        _: &SortLinesCaseInsensitive,
 4891        cx: &mut ViewContext<Self>,
 4892    ) {
 4893        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 4894    }
 4895
 4896    pub fn unique_lines_case_insensitive(
 4897        &mut self,
 4898        _: &UniqueLinesCaseInsensitive,
 4899        cx: &mut ViewContext<Self>,
 4900    ) {
 4901        self.manipulate_lines(cx, |lines| {
 4902            let mut seen = HashSet::default();
 4903            lines.retain(|line| seen.insert(line.to_lowercase()));
 4904        })
 4905    }
 4906
 4907    pub fn unique_lines_case_sensitive(
 4908        &mut self,
 4909        _: &UniqueLinesCaseSensitive,
 4910        cx: &mut ViewContext<Self>,
 4911    ) {
 4912        self.manipulate_lines(cx, |lines| {
 4913            let mut seen = HashSet::default();
 4914            lines.retain(|line| seen.insert(*line));
 4915        })
 4916    }
 4917
 4918    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 4919        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 4920        if !revert_changes.is_empty() {
 4921            self.transact(cx, |editor, cx| {
 4922                editor.buffer().update(cx, |multi_buffer, cx| {
 4923                    for (buffer_id, buffer_revert_ranges) in revert_changes {
 4924                        if let Some(buffer) = multi_buffer.buffer(buffer_id) {
 4925                            buffer.update(cx, |buffer, cx| {
 4926                                buffer.edit(buffer_revert_ranges, None, cx);
 4927                            });
 4928                        }
 4929                    }
 4930                });
 4931                editor.change_selections(None, cx, |selections| selections.refresh());
 4932            });
 4933        }
 4934    }
 4935
 4936    fn gather_revert_changes(
 4937        &mut self,
 4938        selections: &[Selection<Anchor>],
 4939        cx: &mut ViewContext<'_, Editor>,
 4940    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Arc<str>)>> {
 4941        let mut revert_changes = HashMap::default();
 4942        self.buffer.update(cx, |multi_buffer, cx| {
 4943            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4944            let selected_multi_buffer_rows = selections.iter().map(|selection| {
 4945                let head = selection.head();
 4946                let tail = selection.tail();
 4947                let start = tail.to_point(&multi_buffer_snapshot).row;
 4948                let end = head.to_point(&multi_buffer_snapshot).row;
 4949                if start > end {
 4950                    end..start
 4951                } else {
 4952                    start..end
 4953                }
 4954            });
 4955
 4956            let mut processed_buffer_rows =
 4957                HashMap::<BufferId, HashSet<Range<text::Anchor>>>::default();
 4958            for selected_multi_buffer_rows in selected_multi_buffer_rows {
 4959                let query_rows =
 4960                    selected_multi_buffer_rows.start..selected_multi_buffer_rows.end + 1;
 4961                for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
 4962                    // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
 4963                    // when the caret is just above or just below the deleted hunk.
 4964                    let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
 4965                    let related_to_selection = if allow_adjacent {
 4966                        hunk.associated_range.overlaps(&query_rows)
 4967                            || hunk.associated_range.start == query_rows.end
 4968                            || hunk.associated_range.end == query_rows.start
 4969                    } else {
 4970                        // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
 4971                        // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
 4972                        hunk.associated_range.overlaps(&selected_multi_buffer_rows)
 4973                            || selected_multi_buffer_rows.end == hunk.associated_range.start
 4974                    };
 4975                    if related_to_selection {
 4976                        if !processed_buffer_rows
 4977                            .entry(hunk.buffer_id)
 4978                            .or_default()
 4979                            .insert(hunk.buffer_range.start..hunk.buffer_range.end)
 4980                        {
 4981                            continue;
 4982                        }
 4983                        Self::prepare_revert_change(&mut revert_changes, &multi_buffer, &hunk, cx);
 4984                    }
 4985                }
 4986            }
 4987        });
 4988        revert_changes
 4989    }
 4990
 4991    fn prepare_revert_change(
 4992        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Arc<str>)>>,
 4993        multi_buffer: &MultiBuffer,
 4994        hunk: &DiffHunk<u32>,
 4995        cx: &mut AppContext,
 4996    ) -> Option<()> {
 4997        let buffer = multi_buffer.buffer(hunk.buffer_id)?;
 4998        let buffer = buffer.read(cx);
 4999        let original_text = buffer.diff_base()?.get(hunk.diff_base_byte_range.clone())?;
 5000        let buffer_snapshot = buffer.snapshot();
 5001        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5002        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5003            probe
 5004                .0
 5005                .start
 5006                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5007                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5008                .then(probe.1.as_ref().cmp(original_text))
 5009        }) {
 5010            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), Arc::from(original_text)));
 5011            Some(())
 5012        } else {
 5013            None
 5014        }
 5015    }
 5016
 5017    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5018        self.manipulate_lines(cx, |lines| lines.reverse())
 5019    }
 5020
 5021    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5022        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5023    }
 5024
 5025    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5026    where
 5027        Fn: FnMut(&mut Vec<&str>),
 5028    {
 5029        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5030        let buffer = self.buffer.read(cx).snapshot(cx);
 5031
 5032        let mut edits = Vec::new();
 5033
 5034        let selections = self.selections.all::<Point>(cx);
 5035        let mut selections = selections.iter().peekable();
 5036        let mut contiguous_row_selections = Vec::new();
 5037        let mut new_selections = Vec::new();
 5038        let mut added_lines = 0;
 5039        let mut removed_lines = 0;
 5040
 5041        while let Some(selection) = selections.next() {
 5042            let (start_row, end_row) = consume_contiguous_rows(
 5043                &mut contiguous_row_selections,
 5044                selection,
 5045                &display_map,
 5046                &mut selections,
 5047            );
 5048
 5049            let start_point = Point::new(start_row, 0);
 5050            let end_point = Point::new(end_row - 1, buffer.line_len(end_row - 1));
 5051            let text = buffer
 5052                .text_for_range(start_point..end_point)
 5053                .collect::<String>();
 5054
 5055            let mut lines = text.split('\n').collect_vec();
 5056
 5057            let lines_before = lines.len();
 5058            callback(&mut lines);
 5059            let lines_after = lines.len();
 5060
 5061            edits.push((start_point..end_point, lines.join("\n")));
 5062
 5063            // Selections must change based on added and removed line count
 5064            let start_row = start_point.row + added_lines as u32 - removed_lines as u32;
 5065            let end_row = start_row + lines_after.saturating_sub(1) as u32;
 5066            new_selections.push(Selection {
 5067                id: selection.id,
 5068                start: start_row,
 5069                end: end_row,
 5070                goal: SelectionGoal::None,
 5071                reversed: selection.reversed,
 5072            });
 5073
 5074            if lines_after > lines_before {
 5075                added_lines += lines_after - lines_before;
 5076            } else if lines_before > lines_after {
 5077                removed_lines += lines_before - lines_after;
 5078            }
 5079        }
 5080
 5081        self.transact(cx, |this, cx| {
 5082            let buffer = this.buffer.update(cx, |buffer, cx| {
 5083                buffer.edit(edits, None, cx);
 5084                buffer.snapshot(cx)
 5085            });
 5086
 5087            // Recalculate offsets on newly edited buffer
 5088            let new_selections = new_selections
 5089                .iter()
 5090                .map(|s| {
 5091                    let start_point = Point::new(s.start, 0);
 5092                    let end_point = Point::new(s.end, buffer.line_len(s.end));
 5093                    Selection {
 5094                        id: s.id,
 5095                        start: buffer.point_to_offset(start_point),
 5096                        end: buffer.point_to_offset(end_point),
 5097                        goal: s.goal,
 5098                        reversed: s.reversed,
 5099                    }
 5100                })
 5101                .collect();
 5102
 5103            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5104                s.select(new_selections);
 5105            });
 5106
 5107            this.request_autoscroll(Autoscroll::fit(), cx);
 5108        });
 5109    }
 5110
 5111    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 5112        self.manipulate_text(cx, |text| text.to_uppercase())
 5113    }
 5114
 5115    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 5116        self.manipulate_text(cx, |text| text.to_lowercase())
 5117    }
 5118
 5119    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 5120        self.manipulate_text(cx, |text| {
 5121            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 5122            // https://github.com/rutrum/convert-case/issues/16
 5123            text.split('\n')
 5124                .map(|line| line.to_case(Case::Title))
 5125                .join("\n")
 5126        })
 5127    }
 5128
 5129    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 5130        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 5131    }
 5132
 5133    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 5134        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 5135    }
 5136
 5137    pub fn convert_to_upper_camel_case(
 5138        &mut self,
 5139        _: &ConvertToUpperCamelCase,
 5140        cx: &mut ViewContext<Self>,
 5141    ) {
 5142        self.manipulate_text(cx, |text| {
 5143            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 5144            // https://github.com/rutrum/convert-case/issues/16
 5145            text.split('\n')
 5146                .map(|line| line.to_case(Case::UpperCamel))
 5147                .join("\n")
 5148        })
 5149    }
 5150
 5151    pub fn convert_to_lower_camel_case(
 5152        &mut self,
 5153        _: &ConvertToLowerCamelCase,
 5154        cx: &mut ViewContext<Self>,
 5155    ) {
 5156        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 5157    }
 5158
 5159    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5160    where
 5161        Fn: FnMut(&str) -> String,
 5162    {
 5163        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5164        let buffer = self.buffer.read(cx).snapshot(cx);
 5165
 5166        let mut new_selections = Vec::new();
 5167        let mut edits = Vec::new();
 5168        let mut selection_adjustment = 0i32;
 5169
 5170        for selection in self.selections.all::<usize>(cx) {
 5171            let selection_is_empty = selection.is_empty();
 5172
 5173            let (start, end) = if selection_is_empty {
 5174                let word_range = movement::surrounding_word(
 5175                    &display_map,
 5176                    selection.start.to_display_point(&display_map),
 5177                );
 5178                let start = word_range.start.to_offset(&display_map, Bias::Left);
 5179                let end = word_range.end.to_offset(&display_map, Bias::Left);
 5180                (start, end)
 5181            } else {
 5182                (selection.start, selection.end)
 5183            };
 5184
 5185            let text = buffer.text_for_range(start..end).collect::<String>();
 5186            let old_length = text.len() as i32;
 5187            let text = callback(&text);
 5188
 5189            new_selections.push(Selection {
 5190                start: (start as i32 - selection_adjustment) as usize,
 5191                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 5192                goal: SelectionGoal::None,
 5193                ..selection
 5194            });
 5195
 5196            selection_adjustment += old_length - text.len() as i32;
 5197
 5198            edits.push((start..end, text));
 5199        }
 5200
 5201        self.transact(cx, |this, cx| {
 5202            this.buffer.update(cx, |buffer, cx| {
 5203                buffer.edit(edits, None, cx);
 5204            });
 5205
 5206            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5207                s.select(new_selections);
 5208            });
 5209
 5210            this.request_autoscroll(Autoscroll::fit(), cx);
 5211        });
 5212    }
 5213
 5214    pub fn duplicate_line(&mut self, action: &DuplicateLine, cx: &mut ViewContext<Self>) {
 5215        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5216        let buffer = &display_map.buffer_snapshot;
 5217        let selections = self.selections.all::<Point>(cx);
 5218
 5219        let mut edits = Vec::new();
 5220        let mut selections_iter = selections.iter().peekable();
 5221        while let Some(selection) = selections_iter.next() {
 5222            // Avoid duplicating the same lines twice.
 5223            let mut rows = selection.spanned_rows(false, &display_map);
 5224
 5225            while let Some(next_selection) = selections_iter.peek() {
 5226                let next_rows = next_selection.spanned_rows(false, &display_map);
 5227                if next_rows.start < rows.end {
 5228                    rows.end = next_rows.end;
 5229                    selections_iter.next().unwrap();
 5230                } else {
 5231                    break;
 5232                }
 5233            }
 5234
 5235            // Copy the text from the selected row region and splice it either at the start
 5236            // or end of the region.
 5237            let start = Point::new(rows.start, 0);
 5238            let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
 5239            let text = buffer
 5240                .text_for_range(start..end)
 5241                .chain(Some("\n"))
 5242                .collect::<String>();
 5243            let insert_location = if action.move_upwards {
 5244                Point::new(rows.end, 0)
 5245            } else {
 5246                start
 5247            };
 5248            edits.push((insert_location..insert_location, text));
 5249        }
 5250
 5251        self.transact(cx, |this, cx| {
 5252            this.buffer.update(cx, |buffer, cx| {
 5253                buffer.edit(edits, None, cx);
 5254            });
 5255
 5256            this.request_autoscroll(Autoscroll::fit(), cx);
 5257        });
 5258    }
 5259
 5260    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 5261        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5262        let buffer = self.buffer.read(cx).snapshot(cx);
 5263
 5264        let mut edits = Vec::new();
 5265        let mut unfold_ranges = Vec::new();
 5266        let mut refold_ranges = Vec::new();
 5267
 5268        let selections = self.selections.all::<Point>(cx);
 5269        let mut selections = selections.iter().peekable();
 5270        let mut contiguous_row_selections = Vec::new();
 5271        let mut new_selections = Vec::new();
 5272
 5273        while let Some(selection) = selections.next() {
 5274            // Find all the selections that span a contiguous row range
 5275            let (start_row, end_row) = consume_contiguous_rows(
 5276                &mut contiguous_row_selections,
 5277                selection,
 5278                &display_map,
 5279                &mut selections,
 5280            );
 5281
 5282            // Move the text spanned by the row range to be before the line preceding the row range
 5283            if start_row > 0 {
 5284                let range_to_move = Point::new(start_row - 1, buffer.line_len(start_row - 1))
 5285                    ..Point::new(end_row - 1, buffer.line_len(end_row - 1));
 5286                let insertion_point = display_map
 5287                    .prev_line_boundary(Point::new(start_row - 1, 0))
 5288                    .0;
 5289
 5290                // Don't move lines across excerpts
 5291                if buffer
 5292                    .excerpt_boundaries_in_range((
 5293                        Bound::Excluded(insertion_point),
 5294                        Bound::Included(range_to_move.end),
 5295                    ))
 5296                    .next()
 5297                    .is_none()
 5298                {
 5299                    let text = buffer
 5300                        .text_for_range(range_to_move.clone())
 5301                        .flat_map(|s| s.chars())
 5302                        .skip(1)
 5303                        .chain(['\n'])
 5304                        .collect::<String>();
 5305
 5306                    edits.push((
 5307                        buffer.anchor_after(range_to_move.start)
 5308                            ..buffer.anchor_before(range_to_move.end),
 5309                        String::new(),
 5310                    ));
 5311                    let insertion_anchor = buffer.anchor_after(insertion_point);
 5312                    edits.push((insertion_anchor..insertion_anchor, text));
 5313
 5314                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 5315
 5316                    // Move selections up
 5317                    new_selections.extend(contiguous_row_selections.drain(..).map(
 5318                        |mut selection| {
 5319                            selection.start.row -= row_delta;
 5320                            selection.end.row -= row_delta;
 5321                            selection
 5322                        },
 5323                    ));
 5324
 5325                    // Move folds up
 5326                    unfold_ranges.push(range_to_move.clone());
 5327                    for fold in display_map.folds_in_range(
 5328                        buffer.anchor_before(range_to_move.start)
 5329                            ..buffer.anchor_after(range_to_move.end),
 5330                    ) {
 5331                        let mut start = fold.range.start.to_point(&buffer);
 5332                        let mut end = fold.range.end.to_point(&buffer);
 5333                        start.row -= row_delta;
 5334                        end.row -= row_delta;
 5335                        refold_ranges.push(start..end);
 5336                    }
 5337                }
 5338            }
 5339
 5340            // If we didn't move line(s), preserve the existing selections
 5341            new_selections.append(&mut contiguous_row_selections);
 5342        }
 5343
 5344        self.transact(cx, |this, cx| {
 5345            this.unfold_ranges(unfold_ranges, true, true, cx);
 5346            this.buffer.update(cx, |buffer, cx| {
 5347                for (range, text) in edits {
 5348                    buffer.edit([(range, text)], None, cx);
 5349                }
 5350            });
 5351            this.fold_ranges(refold_ranges, true, cx);
 5352            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5353                s.select(new_selections);
 5354            })
 5355        });
 5356    }
 5357
 5358    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 5359        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5360        let buffer = self.buffer.read(cx).snapshot(cx);
 5361
 5362        let mut edits = Vec::new();
 5363        let mut unfold_ranges = Vec::new();
 5364        let mut refold_ranges = Vec::new();
 5365
 5366        let selections = self.selections.all::<Point>(cx);
 5367        let mut selections = selections.iter().peekable();
 5368        let mut contiguous_row_selections = Vec::new();
 5369        let mut new_selections = Vec::new();
 5370
 5371        while let Some(selection) = selections.next() {
 5372            // Find all the selections that span a contiguous row range
 5373            let (start_row, end_row) = consume_contiguous_rows(
 5374                &mut contiguous_row_selections,
 5375                selection,
 5376                &display_map,
 5377                &mut selections,
 5378            );
 5379
 5380            // Move the text spanned by the row range to be after the last line of the row range
 5381            if end_row <= buffer.max_point().row {
 5382                let range_to_move = Point::new(start_row, 0)..Point::new(end_row, 0);
 5383                let insertion_point = display_map.next_line_boundary(Point::new(end_row, 0)).0;
 5384
 5385                // Don't move lines across excerpt boundaries
 5386                if buffer
 5387                    .excerpt_boundaries_in_range((
 5388                        Bound::Excluded(range_to_move.start),
 5389                        Bound::Included(insertion_point),
 5390                    ))
 5391                    .next()
 5392                    .is_none()
 5393                {
 5394                    let mut text = String::from("\n");
 5395                    text.extend(buffer.text_for_range(range_to_move.clone()));
 5396                    text.pop(); // Drop trailing newline
 5397                    edits.push((
 5398                        buffer.anchor_after(range_to_move.start)
 5399                            ..buffer.anchor_before(range_to_move.end),
 5400                        String::new(),
 5401                    ));
 5402                    let insertion_anchor = buffer.anchor_after(insertion_point);
 5403                    edits.push((insertion_anchor..insertion_anchor, text));
 5404
 5405                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 5406
 5407                    // Move selections down
 5408                    new_selections.extend(contiguous_row_selections.drain(..).map(
 5409                        |mut selection| {
 5410                            selection.start.row += row_delta;
 5411                            selection.end.row += row_delta;
 5412                            selection
 5413                        },
 5414                    ));
 5415
 5416                    // Move folds down
 5417                    unfold_ranges.push(range_to_move.clone());
 5418                    for fold in display_map.folds_in_range(
 5419                        buffer.anchor_before(range_to_move.start)
 5420                            ..buffer.anchor_after(range_to_move.end),
 5421                    ) {
 5422                        let mut start = fold.range.start.to_point(&buffer);
 5423                        let mut end = fold.range.end.to_point(&buffer);
 5424                        start.row += row_delta;
 5425                        end.row += row_delta;
 5426                        refold_ranges.push(start..end);
 5427                    }
 5428                }
 5429            }
 5430
 5431            // If we didn't move line(s), preserve the existing selections
 5432            new_selections.append(&mut contiguous_row_selections);
 5433        }
 5434
 5435        self.transact(cx, |this, cx| {
 5436            this.unfold_ranges(unfold_ranges, true, true, cx);
 5437            this.buffer.update(cx, |buffer, cx| {
 5438                for (range, text) in edits {
 5439                    buffer.edit([(range, text)], None, cx);
 5440                }
 5441            });
 5442            this.fold_ranges(refold_ranges, true, cx);
 5443            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 5444        });
 5445    }
 5446
 5447    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 5448        let text_layout_details = &self.text_layout_details(cx);
 5449        self.transact(cx, |this, cx| {
 5450            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5451                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 5452                let line_mode = s.line_mode;
 5453                s.move_with(|display_map, selection| {
 5454                    if !selection.is_empty() || line_mode {
 5455                        return;
 5456                    }
 5457
 5458                    let mut head = selection.head();
 5459                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 5460                    if head.column() == display_map.line_len(head.row()) {
 5461                        transpose_offset = display_map
 5462                            .buffer_snapshot
 5463                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 5464                    }
 5465
 5466                    if transpose_offset == 0 {
 5467                        return;
 5468                    }
 5469
 5470                    *head.column_mut() += 1;
 5471                    head = display_map.clip_point(head, Bias::Right);
 5472                    let goal = SelectionGoal::HorizontalPosition(
 5473                        display_map
 5474                            .x_for_display_point(head, &text_layout_details)
 5475                            .into(),
 5476                    );
 5477                    selection.collapse_to(head, goal);
 5478
 5479                    let transpose_start = display_map
 5480                        .buffer_snapshot
 5481                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 5482                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 5483                        let transpose_end = display_map
 5484                            .buffer_snapshot
 5485                            .clip_offset(transpose_offset + 1, Bias::Right);
 5486                        if let Some(ch) =
 5487                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 5488                        {
 5489                            edits.push((transpose_start..transpose_offset, String::new()));
 5490                            edits.push((transpose_end..transpose_end, ch.to_string()));
 5491                        }
 5492                    }
 5493                });
 5494                edits
 5495            });
 5496            this.buffer
 5497                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 5498            let selections = this.selections.all::<usize>(cx);
 5499            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5500                s.select(selections);
 5501            });
 5502        });
 5503    }
 5504
 5505    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 5506        let mut text = String::new();
 5507        let buffer = self.buffer.read(cx).snapshot(cx);
 5508        let mut selections = self.selections.all::<Point>(cx);
 5509        let mut clipboard_selections = Vec::with_capacity(selections.len());
 5510        {
 5511            let max_point = buffer.max_point();
 5512            let mut is_first = true;
 5513            for selection in &mut selections {
 5514                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 5515                if is_entire_line {
 5516                    selection.start = Point::new(selection.start.row, 0);
 5517                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 5518                    selection.goal = SelectionGoal::None;
 5519                }
 5520                if is_first {
 5521                    is_first = false;
 5522                } else {
 5523                    text += "\n";
 5524                }
 5525                let mut len = 0;
 5526                for chunk in buffer.text_for_range(selection.start..selection.end) {
 5527                    text.push_str(chunk);
 5528                    len += chunk.len();
 5529                }
 5530                clipboard_selections.push(ClipboardSelection {
 5531                    len,
 5532                    is_entire_line,
 5533                    first_line_indent: buffer.indent_size_for_line(selection.start.row).len,
 5534                });
 5535            }
 5536        }
 5537
 5538        self.transact(cx, |this, cx| {
 5539            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5540                s.select(selections);
 5541            });
 5542            this.insert("", cx);
 5543            cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 5544        });
 5545    }
 5546
 5547    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 5548        let selections = self.selections.all::<Point>(cx);
 5549        let buffer = self.buffer.read(cx).read(cx);
 5550        let mut text = String::new();
 5551
 5552        let mut clipboard_selections = Vec::with_capacity(selections.len());
 5553        {
 5554            let max_point = buffer.max_point();
 5555            let mut is_first = true;
 5556            for selection in selections.iter() {
 5557                let mut start = selection.start;
 5558                let mut end = selection.end;
 5559                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 5560                if is_entire_line {
 5561                    start = Point::new(start.row, 0);
 5562                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 5563                }
 5564                if is_first {
 5565                    is_first = false;
 5566                } else {
 5567                    text += "\n";
 5568                }
 5569                let mut len = 0;
 5570                for chunk in buffer.text_for_range(start..end) {
 5571                    text.push_str(chunk);
 5572                    len += chunk.len();
 5573                }
 5574                clipboard_selections.push(ClipboardSelection {
 5575                    len,
 5576                    is_entire_line,
 5577                    first_line_indent: buffer.indent_size_for_line(start.row).len,
 5578                });
 5579            }
 5580        }
 5581
 5582        cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 5583    }
 5584
 5585    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 5586        if self.read_only(cx) {
 5587            return;
 5588        }
 5589
 5590        self.transact(cx, |this, cx| {
 5591            if let Some(item) = cx.read_from_clipboard() {
 5592                let clipboard_text = Cow::Borrowed(item.text());
 5593                if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
 5594                    let old_selections = this.selections.all::<usize>(cx);
 5595                    let all_selections_were_entire_line =
 5596                        clipboard_selections.iter().all(|s| s.is_entire_line);
 5597                    let first_selection_indent_column =
 5598                        clipboard_selections.first().map(|s| s.first_line_indent);
 5599                    if clipboard_selections.len() != old_selections.len() {
 5600                        clipboard_selections.drain(..);
 5601                    }
 5602
 5603                    this.buffer.update(cx, |buffer, cx| {
 5604                        let snapshot = buffer.read(cx);
 5605                        let mut start_offset = 0;
 5606                        let mut edits = Vec::new();
 5607                        let mut original_indent_columns = Vec::new();
 5608                        let line_mode = this.selections.line_mode;
 5609                        for (ix, selection) in old_selections.iter().enumerate() {
 5610                            let to_insert;
 5611                            let entire_line;
 5612                            let original_indent_column;
 5613                            if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 5614                                let end_offset = start_offset + clipboard_selection.len;
 5615                                to_insert = &clipboard_text[start_offset..end_offset];
 5616                                entire_line = clipboard_selection.is_entire_line;
 5617                                start_offset = end_offset + 1;
 5618                                original_indent_column =
 5619                                    Some(clipboard_selection.first_line_indent);
 5620                            } else {
 5621                                to_insert = clipboard_text.as_str();
 5622                                entire_line = all_selections_were_entire_line;
 5623                                original_indent_column = first_selection_indent_column
 5624                            }
 5625
 5626                            // If the corresponding selection was empty when this slice of the
 5627                            // clipboard text was written, then the entire line containing the
 5628                            // selection was copied. If this selection is also currently empty,
 5629                            // then paste the line before the current line of the buffer.
 5630                            let range = if selection.is_empty() && !line_mode && entire_line {
 5631                                let column = selection.start.to_point(&snapshot).column as usize;
 5632                                let line_start = selection.start - column;
 5633                                line_start..line_start
 5634                            } else {
 5635                                selection.range()
 5636                            };
 5637
 5638                            edits.push((range, to_insert));
 5639                            original_indent_columns.extend(original_indent_column);
 5640                        }
 5641                        drop(snapshot);
 5642
 5643                        buffer.edit(
 5644                            edits,
 5645                            Some(AutoindentMode::Block {
 5646                                original_indent_columns,
 5647                            }),
 5648                            cx,
 5649                        );
 5650                    });
 5651
 5652                    let selections = this.selections.all::<usize>(cx);
 5653                    this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5654                } else {
 5655                    this.insert(&clipboard_text, cx);
 5656                }
 5657            }
 5658        });
 5659    }
 5660
 5661    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 5662        if self.read_only(cx) {
 5663            return;
 5664        }
 5665
 5666        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 5667            if let Some((selections, _)) = self.selection_history.transaction(tx_id).cloned() {
 5668                self.change_selections(None, cx, |s| {
 5669                    s.select_anchors(selections.to_vec());
 5670                });
 5671            }
 5672            self.request_autoscroll(Autoscroll::fit(), cx);
 5673            self.unmark_text(cx);
 5674            self.refresh_copilot_suggestions(true, cx);
 5675            cx.emit(EditorEvent::Edited);
 5676        }
 5677    }
 5678
 5679    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 5680        if self.read_only(cx) {
 5681            return;
 5682        }
 5683
 5684        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 5685            if let Some((_, Some(selections))) = self.selection_history.transaction(tx_id).cloned()
 5686            {
 5687                self.change_selections(None, cx, |s| {
 5688                    s.select_anchors(selections.to_vec());
 5689                });
 5690            }
 5691            self.request_autoscroll(Autoscroll::fit(), cx);
 5692            self.unmark_text(cx);
 5693            self.refresh_copilot_suggestions(true, cx);
 5694            cx.emit(EditorEvent::Edited);
 5695        }
 5696    }
 5697
 5698    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 5699        self.buffer
 5700            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 5701    }
 5702
 5703    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 5704        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5705            let line_mode = s.line_mode;
 5706            s.move_with(|map, selection| {
 5707                let cursor = if selection.is_empty() && !line_mode {
 5708                    movement::left(map, selection.start)
 5709                } else {
 5710                    selection.start
 5711                };
 5712                selection.collapse_to(cursor, SelectionGoal::None);
 5713            });
 5714        })
 5715    }
 5716
 5717    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 5718        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5719            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 5720        })
 5721    }
 5722
 5723    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 5724        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5725            let line_mode = s.line_mode;
 5726            s.move_with(|map, selection| {
 5727                let cursor = if selection.is_empty() && !line_mode {
 5728                    movement::right(map, selection.end)
 5729                } else {
 5730                    selection.end
 5731                };
 5732                selection.collapse_to(cursor, SelectionGoal::None)
 5733            });
 5734        })
 5735    }
 5736
 5737    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 5738        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5739            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 5740        })
 5741    }
 5742
 5743    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 5744        if self.take_rename(true, cx).is_some() {
 5745            return;
 5746        }
 5747
 5748        if matches!(self.mode, EditorMode::SingleLine) {
 5749            cx.propagate();
 5750            return;
 5751        }
 5752
 5753        let text_layout_details = &self.text_layout_details(cx);
 5754
 5755        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5756            let line_mode = s.line_mode;
 5757            s.move_with(|map, selection| {
 5758                if !selection.is_empty() && !line_mode {
 5759                    selection.goal = SelectionGoal::None;
 5760                }
 5761                let (cursor, goal) = movement::up(
 5762                    map,
 5763                    selection.start,
 5764                    selection.goal,
 5765                    false,
 5766                    &text_layout_details,
 5767                );
 5768                selection.collapse_to(cursor, goal);
 5769            });
 5770        })
 5771    }
 5772
 5773    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 5774        if self.take_rename(true, cx).is_some() {
 5775            return;
 5776        }
 5777
 5778        if matches!(self.mode, EditorMode::SingleLine) {
 5779            cx.propagate();
 5780            return;
 5781        }
 5782
 5783        let text_layout_details = &self.text_layout_details(cx);
 5784
 5785        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5786            let line_mode = s.line_mode;
 5787            s.move_with(|map, selection| {
 5788                if !selection.is_empty() && !line_mode {
 5789                    selection.goal = SelectionGoal::None;
 5790                }
 5791                let (cursor, goal) = movement::up_by_rows(
 5792                    map,
 5793                    selection.start,
 5794                    action.lines,
 5795                    selection.goal,
 5796                    false,
 5797                    &text_layout_details,
 5798                );
 5799                selection.collapse_to(cursor, goal);
 5800            });
 5801        })
 5802    }
 5803
 5804    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 5805        if self.take_rename(true, cx).is_some() {
 5806            return;
 5807        }
 5808
 5809        if matches!(self.mode, EditorMode::SingleLine) {
 5810            cx.propagate();
 5811            return;
 5812        }
 5813
 5814        let text_layout_details = &self.text_layout_details(cx);
 5815
 5816        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5817            let line_mode = s.line_mode;
 5818            s.move_with(|map, selection| {
 5819                if !selection.is_empty() && !line_mode {
 5820                    selection.goal = SelectionGoal::None;
 5821                }
 5822                let (cursor, goal) = movement::down_by_rows(
 5823                    map,
 5824                    selection.start,
 5825                    action.lines,
 5826                    selection.goal,
 5827                    false,
 5828                    &text_layout_details,
 5829                );
 5830                selection.collapse_to(cursor, goal);
 5831            });
 5832        })
 5833    }
 5834
 5835    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 5836        let text_layout_details = &self.text_layout_details(cx);
 5837        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5838            s.move_heads_with(|map, head, goal| {
 5839                movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 5840            })
 5841        })
 5842    }
 5843
 5844    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 5845        let text_layout_details = &self.text_layout_details(cx);
 5846        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5847            s.move_heads_with(|map, head, goal| {
 5848                movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 5849            })
 5850        })
 5851    }
 5852
 5853    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 5854        if self.take_rename(true, cx).is_some() {
 5855            return;
 5856        }
 5857
 5858        if matches!(self.mode, EditorMode::SingleLine) {
 5859            cx.propagate();
 5860            return;
 5861        }
 5862
 5863        let row_count = if let Some(row_count) = self.visible_line_count() {
 5864            row_count as u32 - 1
 5865        } else {
 5866            return;
 5867        };
 5868
 5869        let autoscroll = if action.center_cursor {
 5870            Autoscroll::center()
 5871        } else {
 5872            Autoscroll::fit()
 5873        };
 5874
 5875        let text_layout_details = &self.text_layout_details(cx);
 5876
 5877        self.change_selections(Some(autoscroll), cx, |s| {
 5878            let line_mode = s.line_mode;
 5879            s.move_with(|map, selection| {
 5880                if !selection.is_empty() && !line_mode {
 5881                    selection.goal = SelectionGoal::None;
 5882                }
 5883                let (cursor, goal) = movement::up_by_rows(
 5884                    map,
 5885                    selection.end,
 5886                    row_count,
 5887                    selection.goal,
 5888                    false,
 5889                    &text_layout_details,
 5890                );
 5891                selection.collapse_to(cursor, goal);
 5892            });
 5893        });
 5894    }
 5895
 5896    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 5897        let text_layout_details = &self.text_layout_details(cx);
 5898        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5899            s.move_heads_with(|map, head, goal| {
 5900                movement::up(map, head, goal, false, &text_layout_details)
 5901            })
 5902        })
 5903    }
 5904
 5905    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 5906        self.take_rename(true, cx);
 5907
 5908        if self.mode == EditorMode::SingleLine {
 5909            cx.propagate();
 5910            return;
 5911        }
 5912
 5913        let text_layout_details = &self.text_layout_details(cx);
 5914        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5915            let line_mode = s.line_mode;
 5916            s.move_with(|map, selection| {
 5917                if !selection.is_empty() && !line_mode {
 5918                    selection.goal = SelectionGoal::None;
 5919                }
 5920                let (cursor, goal) = movement::down(
 5921                    map,
 5922                    selection.end,
 5923                    selection.goal,
 5924                    false,
 5925                    &text_layout_details,
 5926                );
 5927                selection.collapse_to(cursor, goal);
 5928            });
 5929        });
 5930    }
 5931
 5932    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 5933        if self.take_rename(true, cx).is_some() {
 5934            return;
 5935        }
 5936
 5937        if self
 5938            .context_menu
 5939            .write()
 5940            .as_mut()
 5941            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 5942            .unwrap_or(false)
 5943        {
 5944            return;
 5945        }
 5946
 5947        if matches!(self.mode, EditorMode::SingleLine) {
 5948            cx.propagate();
 5949            return;
 5950        }
 5951
 5952        let row_count = if let Some(row_count) = self.visible_line_count() {
 5953            row_count as u32 - 1
 5954        } else {
 5955            return;
 5956        };
 5957
 5958        let autoscroll = if action.center_cursor {
 5959            Autoscroll::center()
 5960        } else {
 5961            Autoscroll::fit()
 5962        };
 5963
 5964        let text_layout_details = &self.text_layout_details(cx);
 5965        self.change_selections(Some(autoscroll), cx, |s| {
 5966            let line_mode = s.line_mode;
 5967            s.move_with(|map, selection| {
 5968                if !selection.is_empty() && !line_mode {
 5969                    selection.goal = SelectionGoal::None;
 5970                }
 5971                let (cursor, goal) = movement::down_by_rows(
 5972                    map,
 5973                    selection.end,
 5974                    row_count,
 5975                    selection.goal,
 5976                    false,
 5977                    &text_layout_details,
 5978                );
 5979                selection.collapse_to(cursor, goal);
 5980            });
 5981        });
 5982    }
 5983
 5984    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 5985        let text_layout_details = &self.text_layout_details(cx);
 5986        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5987            s.move_heads_with(|map, head, goal| {
 5988                movement::down(map, head, goal, false, &text_layout_details)
 5989            })
 5990        });
 5991    }
 5992
 5993    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 5994        if let Some(context_menu) = self.context_menu.write().as_mut() {
 5995            context_menu.select_first(self.project.as_ref(), cx);
 5996        }
 5997    }
 5998
 5999    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 6000        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6001            context_menu.select_prev(self.project.as_ref(), cx);
 6002        }
 6003    }
 6004
 6005    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 6006        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6007            context_menu.select_next(self.project.as_ref(), cx);
 6008        }
 6009    }
 6010
 6011    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 6012        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6013            context_menu.select_last(self.project.as_ref(), cx);
 6014        }
 6015    }
 6016
 6017    pub fn move_to_previous_word_start(
 6018        &mut self,
 6019        _: &MoveToPreviousWordStart,
 6020        cx: &mut ViewContext<Self>,
 6021    ) {
 6022        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6023            s.move_cursors_with(|map, head, _| {
 6024                (
 6025                    movement::previous_word_start(map, head),
 6026                    SelectionGoal::None,
 6027                )
 6028            });
 6029        })
 6030    }
 6031
 6032    pub fn move_to_previous_subword_start(
 6033        &mut self,
 6034        _: &MoveToPreviousSubwordStart,
 6035        cx: &mut ViewContext<Self>,
 6036    ) {
 6037        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6038            s.move_cursors_with(|map, head, _| {
 6039                (
 6040                    movement::previous_subword_start(map, head),
 6041                    SelectionGoal::None,
 6042                )
 6043            });
 6044        })
 6045    }
 6046
 6047    pub fn select_to_previous_word_start(
 6048        &mut self,
 6049        _: &SelectToPreviousWordStart,
 6050        cx: &mut ViewContext<Self>,
 6051    ) {
 6052        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6053            s.move_heads_with(|map, head, _| {
 6054                (
 6055                    movement::previous_word_start(map, head),
 6056                    SelectionGoal::None,
 6057                )
 6058            });
 6059        })
 6060    }
 6061
 6062    pub fn select_to_previous_subword_start(
 6063        &mut self,
 6064        _: &SelectToPreviousSubwordStart,
 6065        cx: &mut ViewContext<Self>,
 6066    ) {
 6067        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6068            s.move_heads_with(|map, head, _| {
 6069                (
 6070                    movement::previous_subword_start(map, head),
 6071                    SelectionGoal::None,
 6072                )
 6073            });
 6074        })
 6075    }
 6076
 6077    pub fn delete_to_previous_word_start(
 6078        &mut self,
 6079        _: &DeleteToPreviousWordStart,
 6080        cx: &mut ViewContext<Self>,
 6081    ) {
 6082        self.transact(cx, |this, cx| {
 6083            this.select_autoclose_pair(cx);
 6084            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6085                let line_mode = s.line_mode;
 6086                s.move_with(|map, selection| {
 6087                    if selection.is_empty() && !line_mode {
 6088                        let cursor = movement::previous_word_start(map, selection.head());
 6089                        selection.set_head(cursor, SelectionGoal::None);
 6090                    }
 6091                });
 6092            });
 6093            this.insert("", cx);
 6094        });
 6095    }
 6096
 6097    pub fn delete_to_previous_subword_start(
 6098        &mut self,
 6099        _: &DeleteToPreviousSubwordStart,
 6100        cx: &mut ViewContext<Self>,
 6101    ) {
 6102        self.transact(cx, |this, cx| {
 6103            this.select_autoclose_pair(cx);
 6104            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6105                let line_mode = s.line_mode;
 6106                s.move_with(|map, selection| {
 6107                    if selection.is_empty() && !line_mode {
 6108                        let cursor = movement::previous_subword_start(map, selection.head());
 6109                        selection.set_head(cursor, SelectionGoal::None);
 6110                    }
 6111                });
 6112            });
 6113            this.insert("", cx);
 6114        });
 6115    }
 6116
 6117    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 6118        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6119            s.move_cursors_with(|map, head, _| {
 6120                (movement::next_word_end(map, head), SelectionGoal::None)
 6121            });
 6122        })
 6123    }
 6124
 6125    pub fn move_to_next_subword_end(
 6126        &mut self,
 6127        _: &MoveToNextSubwordEnd,
 6128        cx: &mut ViewContext<Self>,
 6129    ) {
 6130        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6131            s.move_cursors_with(|map, head, _| {
 6132                (movement::next_subword_end(map, head), SelectionGoal::None)
 6133            });
 6134        })
 6135    }
 6136
 6137    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 6138        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6139            s.move_heads_with(|map, head, _| {
 6140                (movement::next_word_end(map, head), SelectionGoal::None)
 6141            });
 6142        })
 6143    }
 6144
 6145    pub fn select_to_next_subword_end(
 6146        &mut self,
 6147        _: &SelectToNextSubwordEnd,
 6148        cx: &mut ViewContext<Self>,
 6149    ) {
 6150        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6151            s.move_heads_with(|map, head, _| {
 6152                (movement::next_subword_end(map, head), SelectionGoal::None)
 6153            });
 6154        })
 6155    }
 6156
 6157    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
 6158        self.transact(cx, |this, cx| {
 6159            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6160                let line_mode = s.line_mode;
 6161                s.move_with(|map, selection| {
 6162                    if selection.is_empty() && !line_mode {
 6163                        let cursor = movement::next_word_end(map, selection.head());
 6164                        selection.set_head(cursor, SelectionGoal::None);
 6165                    }
 6166                });
 6167            });
 6168            this.insert("", cx);
 6169        });
 6170    }
 6171
 6172    pub fn delete_to_next_subword_end(
 6173        &mut self,
 6174        _: &DeleteToNextSubwordEnd,
 6175        cx: &mut ViewContext<Self>,
 6176    ) {
 6177        self.transact(cx, |this, cx| {
 6178            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6179                s.move_with(|map, selection| {
 6180                    if selection.is_empty() {
 6181                        let cursor = movement::next_subword_end(map, selection.head());
 6182                        selection.set_head(cursor, SelectionGoal::None);
 6183                    }
 6184                });
 6185            });
 6186            this.insert("", cx);
 6187        });
 6188    }
 6189
 6190    pub fn move_to_beginning_of_line(
 6191        &mut self,
 6192        _: &MoveToBeginningOfLine,
 6193        cx: &mut ViewContext<Self>,
 6194    ) {
 6195        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6196            s.move_cursors_with(|map, head, _| {
 6197                (
 6198                    movement::indented_line_beginning(map, head, true),
 6199                    SelectionGoal::None,
 6200                )
 6201            });
 6202        })
 6203    }
 6204
 6205    pub fn select_to_beginning_of_line(
 6206        &mut self,
 6207        action: &SelectToBeginningOfLine,
 6208        cx: &mut ViewContext<Self>,
 6209    ) {
 6210        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6211            s.move_heads_with(|map, head, _| {
 6212                (
 6213                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 6214                    SelectionGoal::None,
 6215                )
 6216            });
 6217        });
 6218    }
 6219
 6220    pub fn delete_to_beginning_of_line(
 6221        &mut self,
 6222        _: &DeleteToBeginningOfLine,
 6223        cx: &mut ViewContext<Self>,
 6224    ) {
 6225        self.transact(cx, |this, cx| {
 6226            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6227                s.move_with(|_, selection| {
 6228                    selection.reversed = true;
 6229                });
 6230            });
 6231
 6232            this.select_to_beginning_of_line(
 6233                &SelectToBeginningOfLine {
 6234                    stop_at_soft_wraps: false,
 6235                },
 6236                cx,
 6237            );
 6238            this.backspace(&Backspace, cx);
 6239        });
 6240    }
 6241
 6242    pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 6243        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6244            s.move_cursors_with(|map, head, _| {
 6245                (movement::line_end(map, head, true), SelectionGoal::None)
 6246            });
 6247        })
 6248    }
 6249
 6250    pub fn select_to_end_of_line(
 6251        &mut self,
 6252        action: &SelectToEndOfLine,
 6253        cx: &mut ViewContext<Self>,
 6254    ) {
 6255        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6256            s.move_heads_with(|map, head, _| {
 6257                (
 6258                    movement::line_end(map, head, action.stop_at_soft_wraps),
 6259                    SelectionGoal::None,
 6260                )
 6261            });
 6262        })
 6263    }
 6264
 6265    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 6266        self.transact(cx, |this, cx| {
 6267            this.select_to_end_of_line(
 6268                &SelectToEndOfLine {
 6269                    stop_at_soft_wraps: false,
 6270                },
 6271                cx,
 6272            );
 6273            this.delete(&Delete, cx);
 6274        });
 6275    }
 6276
 6277    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 6278        self.transact(cx, |this, cx| {
 6279            this.select_to_end_of_line(
 6280                &SelectToEndOfLine {
 6281                    stop_at_soft_wraps: false,
 6282                },
 6283                cx,
 6284            );
 6285            this.cut(&Cut, cx);
 6286        });
 6287    }
 6288
 6289    pub fn move_to_start_of_paragraph(
 6290        &mut self,
 6291        _: &MoveToStartOfParagraph,
 6292        cx: &mut ViewContext<Self>,
 6293    ) {
 6294        if matches!(self.mode, EditorMode::SingleLine) {
 6295            cx.propagate();
 6296            return;
 6297        }
 6298
 6299        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6300            s.move_with(|map, selection| {
 6301                selection.collapse_to(
 6302                    movement::start_of_paragraph(map, selection.head(), 1),
 6303                    SelectionGoal::None,
 6304                )
 6305            });
 6306        })
 6307    }
 6308
 6309    pub fn move_to_end_of_paragraph(
 6310        &mut self,
 6311        _: &MoveToEndOfParagraph,
 6312        cx: &mut ViewContext<Self>,
 6313    ) {
 6314        if matches!(self.mode, EditorMode::SingleLine) {
 6315            cx.propagate();
 6316            return;
 6317        }
 6318
 6319        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6320            s.move_with(|map, selection| {
 6321                selection.collapse_to(
 6322                    movement::end_of_paragraph(map, selection.head(), 1),
 6323                    SelectionGoal::None,
 6324                )
 6325            });
 6326        })
 6327    }
 6328
 6329    pub fn select_to_start_of_paragraph(
 6330        &mut self,
 6331        _: &SelectToStartOfParagraph,
 6332        cx: &mut ViewContext<Self>,
 6333    ) {
 6334        if matches!(self.mode, EditorMode::SingleLine) {
 6335            cx.propagate();
 6336            return;
 6337        }
 6338
 6339        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6340            s.move_heads_with(|map, head, _| {
 6341                (
 6342                    movement::start_of_paragraph(map, head, 1),
 6343                    SelectionGoal::None,
 6344                )
 6345            });
 6346        })
 6347    }
 6348
 6349    pub fn select_to_end_of_paragraph(
 6350        &mut self,
 6351        _: &SelectToEndOfParagraph,
 6352        cx: &mut ViewContext<Self>,
 6353    ) {
 6354        if matches!(self.mode, EditorMode::SingleLine) {
 6355            cx.propagate();
 6356            return;
 6357        }
 6358
 6359        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6360            s.move_heads_with(|map, head, _| {
 6361                (
 6362                    movement::end_of_paragraph(map, head, 1),
 6363                    SelectionGoal::None,
 6364                )
 6365            });
 6366        })
 6367    }
 6368
 6369    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 6370        if matches!(self.mode, EditorMode::SingleLine) {
 6371            cx.propagate();
 6372            return;
 6373        }
 6374
 6375        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6376            s.select_ranges(vec![0..0]);
 6377        });
 6378    }
 6379
 6380    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 6381        let mut selection = self.selections.last::<Point>(cx);
 6382        selection.set_head(Point::zero(), SelectionGoal::None);
 6383
 6384        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6385            s.select(vec![selection]);
 6386        });
 6387    }
 6388
 6389    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 6390        if matches!(self.mode, EditorMode::SingleLine) {
 6391            cx.propagate();
 6392            return;
 6393        }
 6394
 6395        let cursor = self.buffer.read(cx).read(cx).len();
 6396        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6397            s.select_ranges(vec![cursor..cursor])
 6398        });
 6399    }
 6400
 6401    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 6402        self.nav_history = nav_history;
 6403    }
 6404
 6405    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 6406        self.nav_history.as_ref()
 6407    }
 6408
 6409    fn push_to_nav_history(
 6410        &mut self,
 6411        cursor_anchor: Anchor,
 6412        new_position: Option<Point>,
 6413        cx: &mut ViewContext<Self>,
 6414    ) {
 6415        if let Some(nav_history) = self.nav_history.as_mut() {
 6416            let buffer = self.buffer.read(cx).read(cx);
 6417            let cursor_position = cursor_anchor.to_point(&buffer);
 6418            let scroll_state = self.scroll_manager.anchor();
 6419            let scroll_top_row = scroll_state.top_row(&buffer);
 6420            drop(buffer);
 6421
 6422            if let Some(new_position) = new_position {
 6423                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 6424                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 6425                    return;
 6426                }
 6427            }
 6428
 6429            nav_history.push(
 6430                Some(NavigationData {
 6431                    cursor_anchor,
 6432                    cursor_position,
 6433                    scroll_anchor: scroll_state,
 6434                    scroll_top_row,
 6435                }),
 6436                cx,
 6437            );
 6438        }
 6439    }
 6440
 6441    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 6442        let buffer = self.buffer.read(cx).snapshot(cx);
 6443        let mut selection = self.selections.first::<usize>(cx);
 6444        selection.set_head(buffer.len(), SelectionGoal::None);
 6445        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6446            s.select(vec![selection]);
 6447        });
 6448    }
 6449
 6450    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 6451        let end = self.buffer.read(cx).read(cx).len();
 6452        self.change_selections(None, cx, |s| {
 6453            s.select_ranges(vec![0..end]);
 6454        });
 6455    }
 6456
 6457    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 6458        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6459        let mut selections = self.selections.all::<Point>(cx);
 6460        let max_point = display_map.buffer_snapshot.max_point();
 6461        for selection in &mut selections {
 6462            let rows = selection.spanned_rows(true, &display_map);
 6463            selection.start = Point::new(rows.start, 0);
 6464            selection.end = cmp::min(max_point, Point::new(rows.end, 0));
 6465            selection.reversed = false;
 6466        }
 6467        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6468            s.select(selections);
 6469        });
 6470    }
 6471
 6472    pub fn split_selection_into_lines(
 6473        &mut self,
 6474        _: &SplitSelectionIntoLines,
 6475        cx: &mut ViewContext<Self>,
 6476    ) {
 6477        let mut to_unfold = Vec::new();
 6478        let mut new_selection_ranges = Vec::new();
 6479        {
 6480            let selections = self.selections.all::<Point>(cx);
 6481            let buffer = self.buffer.read(cx).read(cx);
 6482            for selection in selections {
 6483                for row in selection.start.row..selection.end.row {
 6484                    let cursor = Point::new(row, buffer.line_len(row));
 6485                    new_selection_ranges.push(cursor..cursor);
 6486                }
 6487                new_selection_ranges.push(selection.end..selection.end);
 6488                to_unfold.push(selection.start..selection.end);
 6489            }
 6490        }
 6491        self.unfold_ranges(to_unfold, true, true, cx);
 6492        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6493            s.select_ranges(new_selection_ranges);
 6494        });
 6495    }
 6496
 6497    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 6498        self.add_selection(true, cx);
 6499    }
 6500
 6501    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 6502        self.add_selection(false, cx);
 6503    }
 6504
 6505    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 6506        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6507        let mut selections = self.selections.all::<Point>(cx);
 6508        let text_layout_details = self.text_layout_details(cx);
 6509        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 6510            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 6511            let range = oldest_selection.display_range(&display_map).sorted();
 6512
 6513            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 6514            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 6515            let positions = start_x.min(end_x)..start_x.max(end_x);
 6516
 6517            selections.clear();
 6518            let mut stack = Vec::new();
 6519            for row in range.start.row()..=range.end.row() {
 6520                if let Some(selection) = self.selections.build_columnar_selection(
 6521                    &display_map,
 6522                    row,
 6523                    &positions,
 6524                    oldest_selection.reversed,
 6525                    &text_layout_details,
 6526                ) {
 6527                    stack.push(selection.id);
 6528                    selections.push(selection);
 6529                }
 6530            }
 6531
 6532            if above {
 6533                stack.reverse();
 6534            }
 6535
 6536            AddSelectionsState { above, stack }
 6537        });
 6538
 6539        let last_added_selection = *state.stack.last().unwrap();
 6540        let mut new_selections = Vec::new();
 6541        if above == state.above {
 6542            let end_row = if above {
 6543                0
 6544            } else {
 6545                display_map.max_point().row()
 6546            };
 6547
 6548            'outer: for selection in selections {
 6549                if selection.id == last_added_selection {
 6550                    let range = selection.display_range(&display_map).sorted();
 6551                    debug_assert_eq!(range.start.row(), range.end.row());
 6552                    let mut row = range.start.row();
 6553                    let positions =
 6554                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 6555                            px(start)..px(end)
 6556                        } else {
 6557                            let start_x =
 6558                                display_map.x_for_display_point(range.start, &text_layout_details);
 6559                            let end_x =
 6560                                display_map.x_for_display_point(range.end, &text_layout_details);
 6561                            start_x.min(end_x)..start_x.max(end_x)
 6562                        };
 6563
 6564                    while row != end_row {
 6565                        if above {
 6566                            row -= 1;
 6567                        } else {
 6568                            row += 1;
 6569                        }
 6570
 6571                        if let Some(new_selection) = self.selections.build_columnar_selection(
 6572                            &display_map,
 6573                            row,
 6574                            &positions,
 6575                            selection.reversed,
 6576                            &text_layout_details,
 6577                        ) {
 6578                            state.stack.push(new_selection.id);
 6579                            if above {
 6580                                new_selections.push(new_selection);
 6581                                new_selections.push(selection);
 6582                            } else {
 6583                                new_selections.push(selection);
 6584                                new_selections.push(new_selection);
 6585                            }
 6586
 6587                            continue 'outer;
 6588                        }
 6589                    }
 6590                }
 6591
 6592                new_selections.push(selection);
 6593            }
 6594        } else {
 6595            new_selections = selections;
 6596            new_selections.retain(|s| s.id != last_added_selection);
 6597            state.stack.pop();
 6598        }
 6599
 6600        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6601            s.select(new_selections);
 6602        });
 6603        if state.stack.len() > 1 {
 6604            self.add_selections_state = Some(state);
 6605        }
 6606    }
 6607
 6608    pub fn select_next_match_internal(
 6609        &mut self,
 6610        display_map: &DisplaySnapshot,
 6611        replace_newest: bool,
 6612        autoscroll: Option<Autoscroll>,
 6613        cx: &mut ViewContext<Self>,
 6614    ) -> Result<()> {
 6615        fn select_next_match_ranges(
 6616            this: &mut Editor,
 6617            range: Range<usize>,
 6618            replace_newest: bool,
 6619            auto_scroll: Option<Autoscroll>,
 6620            cx: &mut ViewContext<Editor>,
 6621        ) {
 6622            this.unfold_ranges([range.clone()], false, true, cx);
 6623            this.change_selections(auto_scroll, cx, |s| {
 6624                if replace_newest {
 6625                    s.delete(s.newest_anchor().id);
 6626                }
 6627                s.insert_range(range.clone());
 6628            });
 6629        }
 6630
 6631        let buffer = &display_map.buffer_snapshot;
 6632        let mut selections = self.selections.all::<usize>(cx);
 6633        if let Some(mut select_next_state) = self.select_next_state.take() {
 6634            let query = &select_next_state.query;
 6635            if !select_next_state.done {
 6636                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 6637                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 6638                let mut next_selected_range = None;
 6639
 6640                let bytes_after_last_selection =
 6641                    buffer.bytes_in_range(last_selection.end..buffer.len());
 6642                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 6643                let query_matches = query
 6644                    .stream_find_iter(bytes_after_last_selection)
 6645                    .map(|result| (last_selection.end, result))
 6646                    .chain(
 6647                        query
 6648                            .stream_find_iter(bytes_before_first_selection)
 6649                            .map(|result| (0, result)),
 6650                    );
 6651
 6652                for (start_offset, query_match) in query_matches {
 6653                    let query_match = query_match.unwrap(); // can only fail due to I/O
 6654                    let offset_range =
 6655                        start_offset + query_match.start()..start_offset + query_match.end();
 6656                    let display_range = offset_range.start.to_display_point(&display_map)
 6657                        ..offset_range.end.to_display_point(&display_map);
 6658
 6659                    if !select_next_state.wordwise
 6660                        || (!movement::is_inside_word(&display_map, display_range.start)
 6661                            && !movement::is_inside_word(&display_map, display_range.end))
 6662                    {
 6663                        // TODO: This is n^2, because we might check all the selections
 6664                        if !selections
 6665                            .iter()
 6666                            .any(|selection| selection.range().overlaps(&offset_range))
 6667                        {
 6668                            next_selected_range = Some(offset_range);
 6669                            break;
 6670                        }
 6671                    }
 6672                }
 6673
 6674                if let Some(next_selected_range) = next_selected_range {
 6675                    select_next_match_ranges(
 6676                        self,
 6677                        next_selected_range,
 6678                        replace_newest,
 6679                        autoscroll,
 6680                        cx,
 6681                    );
 6682                } else {
 6683                    select_next_state.done = true;
 6684                }
 6685            }
 6686
 6687            self.select_next_state = Some(select_next_state);
 6688        } else {
 6689            let mut only_carets = true;
 6690            let mut same_text_selected = true;
 6691            let mut selected_text = None;
 6692
 6693            let mut selections_iter = selections.iter().peekable();
 6694            while let Some(selection) = selections_iter.next() {
 6695                if selection.start != selection.end {
 6696                    only_carets = false;
 6697                }
 6698
 6699                if same_text_selected {
 6700                    if selected_text.is_none() {
 6701                        selected_text =
 6702                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 6703                    }
 6704
 6705                    if let Some(next_selection) = selections_iter.peek() {
 6706                        if next_selection.range().len() == selection.range().len() {
 6707                            let next_selected_text = buffer
 6708                                .text_for_range(next_selection.range())
 6709                                .collect::<String>();
 6710                            if Some(next_selected_text) != selected_text {
 6711                                same_text_selected = false;
 6712                                selected_text = None;
 6713                            }
 6714                        } else {
 6715                            same_text_selected = false;
 6716                            selected_text = None;
 6717                        }
 6718                    }
 6719                }
 6720            }
 6721
 6722            if only_carets {
 6723                for selection in &mut selections {
 6724                    let word_range = movement::surrounding_word(
 6725                        &display_map,
 6726                        selection.start.to_display_point(&display_map),
 6727                    );
 6728                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 6729                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 6730                    selection.goal = SelectionGoal::None;
 6731                    selection.reversed = false;
 6732                    select_next_match_ranges(
 6733                        self,
 6734                        selection.start..selection.end,
 6735                        replace_newest,
 6736                        autoscroll,
 6737                        cx,
 6738                    );
 6739                }
 6740
 6741                if selections.len() == 1 {
 6742                    let selection = selections
 6743                        .last()
 6744                        .expect("ensured that there's only one selection");
 6745                    let query = buffer
 6746                        .text_for_range(selection.start..selection.end)
 6747                        .collect::<String>();
 6748                    let is_empty = query.is_empty();
 6749                    let select_state = SelectNextState {
 6750                        query: AhoCorasick::new(&[query])?,
 6751                        wordwise: true,
 6752                        done: is_empty,
 6753                    };
 6754                    self.select_next_state = Some(select_state);
 6755                } else {
 6756                    self.select_next_state = None;
 6757                }
 6758            } else if let Some(selected_text) = selected_text {
 6759                self.select_next_state = Some(SelectNextState {
 6760                    query: AhoCorasick::new(&[selected_text])?,
 6761                    wordwise: false,
 6762                    done: false,
 6763                });
 6764                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 6765            }
 6766        }
 6767        Ok(())
 6768    }
 6769
 6770    pub fn select_all_matches(
 6771        &mut self,
 6772        _action: &SelectAllMatches,
 6773        cx: &mut ViewContext<Self>,
 6774    ) -> Result<()> {
 6775        self.push_to_selection_history();
 6776        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6777
 6778        self.select_next_match_internal(&display_map, false, None, cx)?;
 6779        let Some(select_next_state) = self.select_next_state.as_mut() else {
 6780            return Ok(());
 6781        };
 6782        if select_next_state.done {
 6783            return Ok(());
 6784        }
 6785
 6786        let mut new_selections = self.selections.all::<usize>(cx);
 6787
 6788        let buffer = &display_map.buffer_snapshot;
 6789        let query_matches = select_next_state
 6790            .query
 6791            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 6792
 6793        for query_match in query_matches {
 6794            let query_match = query_match.unwrap(); // can only fail due to I/O
 6795            let offset_range = query_match.start()..query_match.end();
 6796            let display_range = offset_range.start.to_display_point(&display_map)
 6797                ..offset_range.end.to_display_point(&display_map);
 6798
 6799            if !select_next_state.wordwise
 6800                || (!movement::is_inside_word(&display_map, display_range.start)
 6801                    && !movement::is_inside_word(&display_map, display_range.end))
 6802            {
 6803                self.selections.change_with(cx, |selections| {
 6804                    new_selections.push(Selection {
 6805                        id: selections.new_selection_id(),
 6806                        start: offset_range.start,
 6807                        end: offset_range.end,
 6808                        reversed: false,
 6809                        goal: SelectionGoal::None,
 6810                    });
 6811                });
 6812            }
 6813        }
 6814
 6815        new_selections.sort_by_key(|selection| selection.start);
 6816        let mut ix = 0;
 6817        while ix + 1 < new_selections.len() {
 6818            let current_selection = &new_selections[ix];
 6819            let next_selection = &new_selections[ix + 1];
 6820            if current_selection.range().overlaps(&next_selection.range()) {
 6821                if current_selection.id < next_selection.id {
 6822                    new_selections.remove(ix + 1);
 6823                } else {
 6824                    new_selections.remove(ix);
 6825                }
 6826            } else {
 6827                ix += 1;
 6828            }
 6829        }
 6830
 6831        select_next_state.done = true;
 6832        self.unfold_ranges(
 6833            new_selections.iter().map(|selection| selection.range()),
 6834            false,
 6835            false,
 6836            cx,
 6837        );
 6838        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 6839            selections.select(new_selections)
 6840        });
 6841
 6842        Ok(())
 6843    }
 6844
 6845    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 6846        self.push_to_selection_history();
 6847        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6848        self.select_next_match_internal(
 6849            &display_map,
 6850            action.replace_newest,
 6851            Some(Autoscroll::newest()),
 6852            cx,
 6853        )?;
 6854        Ok(())
 6855    }
 6856
 6857    pub fn select_previous(
 6858        &mut self,
 6859        action: &SelectPrevious,
 6860        cx: &mut ViewContext<Self>,
 6861    ) -> Result<()> {
 6862        self.push_to_selection_history();
 6863        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6864        let buffer = &display_map.buffer_snapshot;
 6865        let mut selections = self.selections.all::<usize>(cx);
 6866        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 6867            let query = &select_prev_state.query;
 6868            if !select_prev_state.done {
 6869                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 6870                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 6871                let mut next_selected_range = None;
 6872                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 6873                let bytes_before_last_selection =
 6874                    buffer.reversed_bytes_in_range(0..last_selection.start);
 6875                let bytes_after_first_selection =
 6876                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 6877                let query_matches = query
 6878                    .stream_find_iter(bytes_before_last_selection)
 6879                    .map(|result| (last_selection.start, result))
 6880                    .chain(
 6881                        query
 6882                            .stream_find_iter(bytes_after_first_selection)
 6883                            .map(|result| (buffer.len(), result)),
 6884                    );
 6885                for (end_offset, query_match) in query_matches {
 6886                    let query_match = query_match.unwrap(); // can only fail due to I/O
 6887                    let offset_range =
 6888                        end_offset - query_match.end()..end_offset - query_match.start();
 6889                    let display_range = offset_range.start.to_display_point(&display_map)
 6890                        ..offset_range.end.to_display_point(&display_map);
 6891
 6892                    if !select_prev_state.wordwise
 6893                        || (!movement::is_inside_word(&display_map, display_range.start)
 6894                            && !movement::is_inside_word(&display_map, display_range.end))
 6895                    {
 6896                        next_selected_range = Some(offset_range);
 6897                        break;
 6898                    }
 6899                }
 6900
 6901                if let Some(next_selected_range) = next_selected_range {
 6902                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 6903                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 6904                        if action.replace_newest {
 6905                            s.delete(s.newest_anchor().id);
 6906                        }
 6907                        s.insert_range(next_selected_range);
 6908                    });
 6909                } else {
 6910                    select_prev_state.done = true;
 6911                }
 6912            }
 6913
 6914            self.select_prev_state = Some(select_prev_state);
 6915        } else {
 6916            let mut only_carets = true;
 6917            let mut same_text_selected = true;
 6918            let mut selected_text = None;
 6919
 6920            let mut selections_iter = selections.iter().peekable();
 6921            while let Some(selection) = selections_iter.next() {
 6922                if selection.start != selection.end {
 6923                    only_carets = false;
 6924                }
 6925
 6926                if same_text_selected {
 6927                    if selected_text.is_none() {
 6928                        selected_text =
 6929                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 6930                    }
 6931
 6932                    if let Some(next_selection) = selections_iter.peek() {
 6933                        if next_selection.range().len() == selection.range().len() {
 6934                            let next_selected_text = buffer
 6935                                .text_for_range(next_selection.range())
 6936                                .collect::<String>();
 6937                            if Some(next_selected_text) != selected_text {
 6938                                same_text_selected = false;
 6939                                selected_text = None;
 6940                            }
 6941                        } else {
 6942                            same_text_selected = false;
 6943                            selected_text = None;
 6944                        }
 6945                    }
 6946                }
 6947            }
 6948
 6949            if only_carets {
 6950                for selection in &mut selections {
 6951                    let word_range = movement::surrounding_word(
 6952                        &display_map,
 6953                        selection.start.to_display_point(&display_map),
 6954                    );
 6955                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 6956                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 6957                    selection.goal = SelectionGoal::None;
 6958                    selection.reversed = false;
 6959                }
 6960                if selections.len() == 1 {
 6961                    let selection = selections
 6962                        .last()
 6963                        .expect("ensured that there's only one selection");
 6964                    let query = buffer
 6965                        .text_for_range(selection.start..selection.end)
 6966                        .collect::<String>();
 6967                    let is_empty = query.is_empty();
 6968                    let select_state = SelectNextState {
 6969                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 6970                        wordwise: true,
 6971                        done: is_empty,
 6972                    };
 6973                    self.select_prev_state = Some(select_state);
 6974                } else {
 6975                    self.select_prev_state = None;
 6976                }
 6977
 6978                self.unfold_ranges(
 6979                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 6980                    false,
 6981                    true,
 6982                    cx,
 6983                );
 6984                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 6985                    s.select(selections);
 6986                });
 6987            } else if let Some(selected_text) = selected_text {
 6988                self.select_prev_state = Some(SelectNextState {
 6989                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 6990                    wordwise: false,
 6991                    done: false,
 6992                });
 6993                self.select_previous(action, cx)?;
 6994            }
 6995        }
 6996        Ok(())
 6997    }
 6998
 6999    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 7000        let text_layout_details = &self.text_layout_details(cx);
 7001        self.transact(cx, |this, cx| {
 7002            let mut selections = this.selections.all::<Point>(cx);
 7003            let mut edits = Vec::new();
 7004            let mut selection_edit_ranges = Vec::new();
 7005            let mut last_toggled_row = None;
 7006            let snapshot = this.buffer.read(cx).read(cx);
 7007            let empty_str: Arc<str> = "".into();
 7008            let mut suffixes_inserted = Vec::new();
 7009
 7010            fn comment_prefix_range(
 7011                snapshot: &MultiBufferSnapshot,
 7012                row: u32,
 7013                comment_prefix: &str,
 7014                comment_prefix_whitespace: &str,
 7015            ) -> Range<Point> {
 7016                let start = Point::new(row, snapshot.indent_size_for_line(row).len);
 7017
 7018                let mut line_bytes = snapshot
 7019                    .bytes_in_range(start..snapshot.max_point())
 7020                    .flatten()
 7021                    .copied();
 7022
 7023                // If this line currently begins with the line comment prefix, then record
 7024                // the range containing the prefix.
 7025                if line_bytes
 7026                    .by_ref()
 7027                    .take(comment_prefix.len())
 7028                    .eq(comment_prefix.bytes())
 7029                {
 7030                    // Include any whitespace that matches the comment prefix.
 7031                    let matching_whitespace_len = line_bytes
 7032                        .zip(comment_prefix_whitespace.bytes())
 7033                        .take_while(|(a, b)| a == b)
 7034                        .count() as u32;
 7035                    let end = Point::new(
 7036                        start.row,
 7037                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 7038                    );
 7039                    start..end
 7040                } else {
 7041                    start..start
 7042                }
 7043            }
 7044
 7045            fn comment_suffix_range(
 7046                snapshot: &MultiBufferSnapshot,
 7047                row: u32,
 7048                comment_suffix: &str,
 7049                comment_suffix_has_leading_space: bool,
 7050            ) -> Range<Point> {
 7051                let end = Point::new(row, snapshot.line_len(row));
 7052                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 7053
 7054                let mut line_end_bytes = snapshot
 7055                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 7056                    .flatten()
 7057                    .copied();
 7058
 7059                let leading_space_len = if suffix_start_column > 0
 7060                    && line_end_bytes.next() == Some(b' ')
 7061                    && comment_suffix_has_leading_space
 7062                {
 7063                    1
 7064                } else {
 7065                    0
 7066                };
 7067
 7068                // If this line currently begins with the line comment prefix, then record
 7069                // the range containing the prefix.
 7070                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 7071                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 7072                    start..end
 7073                } else {
 7074                    end..end
 7075                }
 7076            }
 7077
 7078            // TODO: Handle selections that cross excerpts
 7079            for selection in &mut selections {
 7080                let start_column = snapshot.indent_size_for_line(selection.start.row).len;
 7081                let language = if let Some(language) =
 7082                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 7083                {
 7084                    language
 7085                } else {
 7086                    continue;
 7087                };
 7088
 7089                selection_edit_ranges.clear();
 7090
 7091                // If multiple selections contain a given row, avoid processing that
 7092                // row more than once.
 7093                let mut start_row = selection.start.row;
 7094                if last_toggled_row == Some(start_row) {
 7095                    start_row += 1;
 7096                }
 7097                let end_row =
 7098                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 7099                        selection.end.row - 1
 7100                    } else {
 7101                        selection.end.row
 7102                    };
 7103                last_toggled_row = Some(end_row);
 7104
 7105                if start_row > end_row {
 7106                    continue;
 7107                }
 7108
 7109                // If the language has line comments, toggle those.
 7110                if let Some(full_comment_prefix) = language
 7111                    .line_comment_prefixes()
 7112                    .and_then(|prefixes| prefixes.first())
 7113                {
 7114                    // Split the comment prefix's trailing whitespace into a separate string,
 7115                    // as that portion won't be used for detecting if a line is a comment.
 7116                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 7117                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 7118                    let mut all_selection_lines_are_comments = true;
 7119
 7120                    for row in start_row..=end_row {
 7121                        if start_row < end_row && snapshot.is_line_blank(row) {
 7122                            continue;
 7123                        }
 7124
 7125                        let prefix_range = comment_prefix_range(
 7126                            snapshot.deref(),
 7127                            row,
 7128                            comment_prefix,
 7129                            comment_prefix_whitespace,
 7130                        );
 7131                        if prefix_range.is_empty() {
 7132                            all_selection_lines_are_comments = false;
 7133                        }
 7134                        selection_edit_ranges.push(prefix_range);
 7135                    }
 7136
 7137                    if all_selection_lines_are_comments {
 7138                        edits.extend(
 7139                            selection_edit_ranges
 7140                                .iter()
 7141                                .cloned()
 7142                                .map(|range| (range, empty_str.clone())),
 7143                        );
 7144                    } else {
 7145                        let min_column = selection_edit_ranges
 7146                            .iter()
 7147                            .map(|r| r.start.column)
 7148                            .min()
 7149                            .unwrap_or(0);
 7150                        edits.extend(selection_edit_ranges.iter().map(|range| {
 7151                            let position = Point::new(range.start.row, min_column);
 7152                            (position..position, full_comment_prefix.clone())
 7153                        }));
 7154                    }
 7155                } else if let Some((full_comment_prefix, comment_suffix)) =
 7156                    language.block_comment_delimiters()
 7157                {
 7158                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 7159                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 7160                    let prefix_range = comment_prefix_range(
 7161                        snapshot.deref(),
 7162                        start_row,
 7163                        comment_prefix,
 7164                        comment_prefix_whitespace,
 7165                    );
 7166                    let suffix_range = comment_suffix_range(
 7167                        snapshot.deref(),
 7168                        end_row,
 7169                        comment_suffix.trim_start_matches(' '),
 7170                        comment_suffix.starts_with(' '),
 7171                    );
 7172
 7173                    if prefix_range.is_empty() || suffix_range.is_empty() {
 7174                        edits.push((
 7175                            prefix_range.start..prefix_range.start,
 7176                            full_comment_prefix.clone(),
 7177                        ));
 7178                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 7179                        suffixes_inserted.push((end_row, comment_suffix.len()));
 7180                    } else {
 7181                        edits.push((prefix_range, empty_str.clone()));
 7182                        edits.push((suffix_range, empty_str.clone()));
 7183                    }
 7184                } else {
 7185                    continue;
 7186                }
 7187            }
 7188
 7189            drop(snapshot);
 7190            this.buffer.update(cx, |buffer, cx| {
 7191                buffer.edit(edits, None, cx);
 7192            });
 7193
 7194            // Adjust selections so that they end before any comment suffixes that
 7195            // were inserted.
 7196            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 7197            let mut selections = this.selections.all::<Point>(cx);
 7198            let snapshot = this.buffer.read(cx).read(cx);
 7199            for selection in &mut selections {
 7200                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 7201                    match row.cmp(&selection.end.row) {
 7202                        Ordering::Less => {
 7203                            suffixes_inserted.next();
 7204                            continue;
 7205                        }
 7206                        Ordering::Greater => break,
 7207                        Ordering::Equal => {
 7208                            if selection.end.column == snapshot.line_len(row) {
 7209                                if selection.is_empty() {
 7210                                    selection.start.column -= suffix_len as u32;
 7211                                }
 7212                                selection.end.column -= suffix_len as u32;
 7213                            }
 7214                            break;
 7215                        }
 7216                    }
 7217                }
 7218            }
 7219
 7220            drop(snapshot);
 7221            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7222
 7223            let selections = this.selections.all::<Point>(cx);
 7224            let selections_on_single_row = selections.windows(2).all(|selections| {
 7225                selections[0].start.row == selections[1].start.row
 7226                    && selections[0].end.row == selections[1].end.row
 7227                    && selections[0].start.row == selections[0].end.row
 7228            });
 7229            let selections_selecting = selections
 7230                .iter()
 7231                .any(|selection| selection.start != selection.end);
 7232            let advance_downwards = action.advance_downwards
 7233                && selections_on_single_row
 7234                && !selections_selecting
 7235                && this.mode != EditorMode::SingleLine;
 7236
 7237            if advance_downwards {
 7238                let snapshot = this.buffer.read(cx).snapshot(cx);
 7239
 7240                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7241                    s.move_cursors_with(|display_snapshot, display_point, _| {
 7242                        let mut point = display_point.to_point(display_snapshot);
 7243                        point.row += 1;
 7244                        point = snapshot.clip_point(point, Bias::Left);
 7245                        let display_point = point.to_display_point(display_snapshot);
 7246                        let goal = SelectionGoal::HorizontalPosition(
 7247                            display_snapshot
 7248                                .x_for_display_point(display_point, &text_layout_details)
 7249                                .into(),
 7250                        );
 7251                        (display_point, goal)
 7252                    })
 7253                });
 7254            }
 7255        });
 7256    }
 7257
 7258    pub fn select_larger_syntax_node(
 7259        &mut self,
 7260        _: &SelectLargerSyntaxNode,
 7261        cx: &mut ViewContext<Self>,
 7262    ) {
 7263        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7264        let buffer = self.buffer.read(cx).snapshot(cx);
 7265        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 7266
 7267        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 7268        let mut selected_larger_node = false;
 7269        let new_selections = old_selections
 7270            .iter()
 7271            .map(|selection| {
 7272                let old_range = selection.start..selection.end;
 7273                let mut new_range = old_range.clone();
 7274                while let Some(containing_range) =
 7275                    buffer.range_for_syntax_ancestor(new_range.clone())
 7276                {
 7277                    new_range = containing_range;
 7278                    if !display_map.intersects_fold(new_range.start)
 7279                        && !display_map.intersects_fold(new_range.end)
 7280                    {
 7281                        break;
 7282                    }
 7283                }
 7284
 7285                selected_larger_node |= new_range != old_range;
 7286                Selection {
 7287                    id: selection.id,
 7288                    start: new_range.start,
 7289                    end: new_range.end,
 7290                    goal: SelectionGoal::None,
 7291                    reversed: selection.reversed,
 7292                }
 7293            })
 7294            .collect::<Vec<_>>();
 7295
 7296        if selected_larger_node {
 7297            stack.push(old_selections);
 7298            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7299                s.select(new_selections);
 7300            });
 7301        }
 7302        self.select_larger_syntax_node_stack = stack;
 7303    }
 7304
 7305    pub fn select_smaller_syntax_node(
 7306        &mut self,
 7307        _: &SelectSmallerSyntaxNode,
 7308        cx: &mut ViewContext<Self>,
 7309    ) {
 7310        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 7311        if let Some(selections) = stack.pop() {
 7312            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7313                s.select(selections.to_vec());
 7314            });
 7315        }
 7316        self.select_larger_syntax_node_stack = stack;
 7317    }
 7318
 7319    pub fn move_to_enclosing_bracket(
 7320        &mut self,
 7321        _: &MoveToEnclosingBracket,
 7322        cx: &mut ViewContext<Self>,
 7323    ) {
 7324        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7325            s.move_offsets_with(|snapshot, selection| {
 7326                let Some(enclosing_bracket_ranges) =
 7327                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 7328                else {
 7329                    return;
 7330                };
 7331
 7332                let mut best_length = usize::MAX;
 7333                let mut best_inside = false;
 7334                let mut best_in_bracket_range = false;
 7335                let mut best_destination = None;
 7336                for (open, close) in enclosing_bracket_ranges {
 7337                    let close = close.to_inclusive();
 7338                    let length = close.end() - open.start;
 7339                    let inside = selection.start >= open.end && selection.end <= *close.start();
 7340                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 7341                        || close.contains(&selection.head());
 7342
 7343                    // If best is next to a bracket and current isn't, skip
 7344                    if !in_bracket_range && best_in_bracket_range {
 7345                        continue;
 7346                    }
 7347
 7348                    // Prefer smaller lengths unless best is inside and current isn't
 7349                    if length > best_length && (best_inside || !inside) {
 7350                        continue;
 7351                    }
 7352
 7353                    best_length = length;
 7354                    best_inside = inside;
 7355                    best_in_bracket_range = in_bracket_range;
 7356                    best_destination = Some(
 7357                        if close.contains(&selection.start) && close.contains(&selection.end) {
 7358                            if inside {
 7359                                open.end
 7360                            } else {
 7361                                open.start
 7362                            }
 7363                        } else {
 7364                            if inside {
 7365                                *close.start()
 7366                            } else {
 7367                                *close.end()
 7368                            }
 7369                        },
 7370                    );
 7371                }
 7372
 7373                if let Some(destination) = best_destination {
 7374                    selection.collapse_to(destination, SelectionGoal::None);
 7375                }
 7376            })
 7377        });
 7378    }
 7379
 7380    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 7381        self.end_selection(cx);
 7382        self.selection_history.mode = SelectionHistoryMode::Undoing;
 7383        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 7384            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 7385            self.select_next_state = entry.select_next_state;
 7386            self.select_prev_state = entry.select_prev_state;
 7387            self.add_selections_state = entry.add_selections_state;
 7388            self.request_autoscroll(Autoscroll::newest(), cx);
 7389        }
 7390        self.selection_history.mode = SelectionHistoryMode::Normal;
 7391    }
 7392
 7393    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 7394        self.end_selection(cx);
 7395        self.selection_history.mode = SelectionHistoryMode::Redoing;
 7396        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 7397            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 7398            self.select_next_state = entry.select_next_state;
 7399            self.select_prev_state = entry.select_prev_state;
 7400            self.add_selections_state = entry.add_selections_state;
 7401            self.request_autoscroll(Autoscroll::newest(), cx);
 7402        }
 7403        self.selection_history.mode = SelectionHistoryMode::Normal;
 7404    }
 7405
 7406    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 7407        self.go_to_diagnostic_impl(Direction::Next, cx)
 7408    }
 7409
 7410    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 7411        self.go_to_diagnostic_impl(Direction::Prev, cx)
 7412    }
 7413
 7414    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 7415        let buffer = self.buffer.read(cx).snapshot(cx);
 7416        let selection = self.selections.newest::<usize>(cx);
 7417
 7418        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 7419        if direction == Direction::Next {
 7420            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 7421                let (group_id, jump_to) = popover.activation_info();
 7422                if self.activate_diagnostics(group_id, cx) {
 7423                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7424                        let mut new_selection = s.newest_anchor().clone();
 7425                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 7426                        s.select_anchors(vec![new_selection.clone()]);
 7427                    });
 7428                }
 7429                return;
 7430            }
 7431        }
 7432
 7433        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 7434            active_diagnostics
 7435                .primary_range
 7436                .to_offset(&buffer)
 7437                .to_inclusive()
 7438        });
 7439        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 7440            if active_primary_range.contains(&selection.head()) {
 7441                *active_primary_range.end()
 7442            } else {
 7443                selection.head()
 7444            }
 7445        } else {
 7446            selection.head()
 7447        };
 7448
 7449        loop {
 7450            let mut diagnostics = if direction == Direction::Prev {
 7451                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 7452            } else {
 7453                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 7454            };
 7455            let group = diagnostics.find_map(|entry| {
 7456                if entry.diagnostic.is_primary
 7457                    && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 7458                    && !entry.range.is_empty()
 7459                    && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
 7460                    && !entry.range.contains(&search_start)
 7461                {
 7462                    Some((entry.range, entry.diagnostic.group_id))
 7463                } else {
 7464                    None
 7465                }
 7466            });
 7467
 7468            if let Some((primary_range, group_id)) = group {
 7469                if self.activate_diagnostics(group_id, cx) {
 7470                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7471                        s.select(vec![Selection {
 7472                            id: selection.id,
 7473                            start: primary_range.start,
 7474                            end: primary_range.start,
 7475                            reversed: false,
 7476                            goal: SelectionGoal::None,
 7477                        }]);
 7478                    });
 7479                }
 7480                break;
 7481            } else {
 7482                // Cycle around to the start of the buffer, potentially moving back to the start of
 7483                // the currently active diagnostic.
 7484                active_primary_range.take();
 7485                if direction == Direction::Prev {
 7486                    if search_start == buffer.len() {
 7487                        break;
 7488                    } else {
 7489                        search_start = buffer.len();
 7490                    }
 7491                } else if search_start == 0 {
 7492                    break;
 7493                } else {
 7494                    search_start = 0;
 7495                }
 7496            }
 7497        }
 7498    }
 7499
 7500    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 7501        let snapshot = self
 7502            .display_map
 7503            .update(cx, |display_map, cx| display_map.snapshot(cx));
 7504        let selection = self.selections.newest::<Point>(cx);
 7505
 7506        if !self.seek_in_direction(
 7507            &snapshot,
 7508            selection.head(),
 7509            false,
 7510            snapshot
 7511                .buffer_snapshot
 7512                .git_diff_hunks_in_range((selection.head().row + 1)..u32::MAX),
 7513            cx,
 7514        ) {
 7515            let wrapped_point = Point::zero();
 7516            self.seek_in_direction(
 7517                &snapshot,
 7518                wrapped_point,
 7519                true,
 7520                snapshot
 7521                    .buffer_snapshot
 7522                    .git_diff_hunks_in_range((wrapped_point.row + 1)..u32::MAX),
 7523                cx,
 7524            );
 7525        }
 7526    }
 7527
 7528    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 7529        let snapshot = self
 7530            .display_map
 7531            .update(cx, |display_map, cx| display_map.snapshot(cx));
 7532        let selection = self.selections.newest::<Point>(cx);
 7533
 7534        if !self.seek_in_direction(
 7535            &snapshot,
 7536            selection.head(),
 7537            false,
 7538            snapshot
 7539                .buffer_snapshot
 7540                .git_diff_hunks_in_range_rev(0..selection.head().row),
 7541            cx,
 7542        ) {
 7543            let wrapped_point = snapshot.buffer_snapshot.max_point();
 7544            self.seek_in_direction(
 7545                &snapshot,
 7546                wrapped_point,
 7547                true,
 7548                snapshot
 7549                    .buffer_snapshot
 7550                    .git_diff_hunks_in_range_rev(0..wrapped_point.row),
 7551                cx,
 7552            );
 7553        }
 7554    }
 7555
 7556    fn seek_in_direction(
 7557        &mut self,
 7558        snapshot: &DisplaySnapshot,
 7559        initial_point: Point,
 7560        is_wrapped: bool,
 7561        hunks: impl Iterator<Item = DiffHunk<u32>>,
 7562        cx: &mut ViewContext<Editor>,
 7563    ) -> bool {
 7564        let display_point = initial_point.to_display_point(snapshot);
 7565        let mut hunks = hunks
 7566            .map(|hunk| diff_hunk_to_display(hunk, &snapshot))
 7567            .filter(|hunk| {
 7568                if is_wrapped {
 7569                    true
 7570                } else {
 7571                    !hunk.contains_display_row(display_point.row())
 7572                }
 7573            })
 7574            .dedup();
 7575
 7576        if let Some(hunk) = hunks.next() {
 7577            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7578                let row = hunk.start_display_row();
 7579                let point = DisplayPoint::new(row, 0);
 7580                s.select_display_ranges([point..point]);
 7581            });
 7582
 7583            true
 7584        } else {
 7585            false
 7586        }
 7587    }
 7588
 7589    pub fn go_to_definition(&mut self, _: &GoToDefinition, cx: &mut ViewContext<Self>) {
 7590        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 7591    }
 7592
 7593    pub fn go_to_implementation(&mut self, _: &GoToImplementation, cx: &mut ViewContext<Self>) {
 7594        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx);
 7595    }
 7596
 7597    pub fn go_to_implementation_split(
 7598        &mut self,
 7599        _: &GoToImplementationSplit,
 7600        cx: &mut ViewContext<Self>,
 7601    ) {
 7602        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx);
 7603    }
 7604
 7605    pub fn go_to_type_definition(&mut self, _: &GoToTypeDefinition, cx: &mut ViewContext<Self>) {
 7606        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx);
 7607    }
 7608
 7609    pub fn go_to_definition_split(&mut self, _: &GoToDefinitionSplit, cx: &mut ViewContext<Self>) {
 7610        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx);
 7611    }
 7612
 7613    pub fn go_to_type_definition_split(
 7614        &mut self,
 7615        _: &GoToTypeDefinitionSplit,
 7616        cx: &mut ViewContext<Self>,
 7617    ) {
 7618        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx);
 7619    }
 7620
 7621    fn go_to_definition_of_kind(
 7622        &mut self,
 7623        kind: GotoDefinitionKind,
 7624        split: bool,
 7625        cx: &mut ViewContext<Self>,
 7626    ) {
 7627        let Some(workspace) = self.workspace() else {
 7628            return;
 7629        };
 7630        let buffer = self.buffer.read(cx);
 7631        let head = self.selections.newest::<usize>(cx).head();
 7632        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 7633            text_anchor
 7634        } else {
 7635            return;
 7636        };
 7637
 7638        let project = workspace.read(cx).project().clone();
 7639        let definitions = project.update(cx, |project, cx| match kind {
 7640            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 7641            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 7642            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 7643        });
 7644
 7645        cx.spawn(|editor, mut cx| async move {
 7646            let definitions = definitions.await?;
 7647            editor.update(&mut cx, |editor, cx| {
 7648                editor.navigate_to_hover_links(
 7649                    Some(kind),
 7650                    definitions.into_iter().map(HoverLink::Text).collect(),
 7651                    split,
 7652                    cx,
 7653                );
 7654            })?;
 7655            Ok::<(), anyhow::Error>(())
 7656        })
 7657        .detach_and_log_err(cx);
 7658    }
 7659
 7660    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 7661        let position = self.selections.newest_anchor().head();
 7662        let Some((buffer, buffer_position)) =
 7663            self.buffer.read(cx).text_anchor_for_position(position, cx)
 7664        else {
 7665            return;
 7666        };
 7667
 7668        cx.spawn(|editor, mut cx| async move {
 7669            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 7670                editor.update(&mut cx, |_, cx| {
 7671                    cx.open_url(&url);
 7672                })
 7673            } else {
 7674                Ok(())
 7675            }
 7676        })
 7677        .detach();
 7678    }
 7679
 7680    pub(crate) fn navigate_to_hover_links(
 7681        &mut self,
 7682        kind: Option<GotoDefinitionKind>,
 7683        mut definitions: Vec<HoverLink>,
 7684        split: bool,
 7685        cx: &mut ViewContext<Editor>,
 7686    ) {
 7687        // If there is one definition, just open it directly
 7688        if definitions.len() == 1 {
 7689            let definition = definitions.pop().unwrap();
 7690            let target_task = match definition {
 7691                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 7692                HoverLink::InlayHint(lsp_location, server_id) => {
 7693                    self.compute_target_location(lsp_location, server_id, cx)
 7694                }
 7695                HoverLink::Url(url) => {
 7696                    cx.open_url(&url);
 7697                    Task::ready(Ok(None))
 7698                }
 7699            };
 7700            cx.spawn(|editor, mut cx| async move {
 7701                let target = target_task.await.context("target resolution task")?;
 7702                if let Some(target) = target {
 7703                    editor.update(&mut cx, |editor, cx| {
 7704                        let Some(workspace) = editor.workspace() else {
 7705                            return;
 7706                        };
 7707                        let pane = workspace.read(cx).active_pane().clone();
 7708
 7709                        let range = target.range.to_offset(target.buffer.read(cx));
 7710                        let range = editor.range_for_match(&range);
 7711                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 7712                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7713                                s.select_ranges([range]);
 7714                            });
 7715                        } else {
 7716                            cx.window_context().defer(move |cx| {
 7717                                let target_editor: View<Self> =
 7718                                    workspace.update(cx, |workspace, cx| {
 7719                                        let pane = if split {
 7720                                            workspace.adjacent_pane(cx)
 7721                                        } else {
 7722                                            workspace.active_pane().clone()
 7723                                        };
 7724
 7725                                        workspace.open_project_item(pane, target.buffer.clone(), cx)
 7726                                    });
 7727                                target_editor.update(cx, |target_editor, cx| {
 7728                                    // When selecting a definition in a different buffer, disable the nav history
 7729                                    // to avoid creating a history entry at the previous cursor location.
 7730                                    pane.update(cx, |pane, _| pane.disable_history());
 7731                                    target_editor.change_selections(
 7732                                        Some(Autoscroll::fit()),
 7733                                        cx,
 7734                                        |s| {
 7735                                            s.select_ranges([range]);
 7736                                        },
 7737                                    );
 7738                                    pane.update(cx, |pane, _| pane.enable_history());
 7739                                });
 7740                            });
 7741                        }
 7742                    })
 7743                } else {
 7744                    Ok(())
 7745                }
 7746            })
 7747            .detach_and_log_err(cx);
 7748        } else if !definitions.is_empty() {
 7749            let replica_id = self.replica_id(cx);
 7750            cx.spawn(|editor, mut cx| async move {
 7751                let (title, location_tasks, workspace) = editor
 7752                    .update(&mut cx, |editor, cx| {
 7753                        let tab_kind = match kind {
 7754                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 7755                            _ => "Definitions",
 7756                        };
 7757                        let title = definitions
 7758                            .iter()
 7759                            .find_map(|definition| match definition {
 7760                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 7761                                    let buffer = origin.buffer.read(cx);
 7762                                    format!(
 7763                                        "{} for {}",
 7764                                        tab_kind,
 7765                                        buffer
 7766                                            .text_for_range(origin.range.clone())
 7767                                            .collect::<String>()
 7768                                    )
 7769                                }),
 7770                                HoverLink::InlayHint(_, _) => None,
 7771                                HoverLink::Url(_) => None,
 7772                            })
 7773                            .unwrap_or(tab_kind.to_string());
 7774                        let location_tasks = definitions
 7775                            .into_iter()
 7776                            .map(|definition| match definition {
 7777                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 7778                                HoverLink::InlayHint(lsp_location, server_id) => {
 7779                                    editor.compute_target_location(lsp_location, server_id, cx)
 7780                                }
 7781                                HoverLink::Url(_) => Task::ready(Ok(None)),
 7782                            })
 7783                            .collect::<Vec<_>>();
 7784                        (title, location_tasks, editor.workspace().clone())
 7785                    })
 7786                    .context("location tasks preparation")?;
 7787
 7788                let locations = futures::future::join_all(location_tasks)
 7789                    .await
 7790                    .into_iter()
 7791                    .filter_map(|location| location.transpose())
 7792                    .collect::<Result<_>>()
 7793                    .context("location tasks")?;
 7794
 7795                let Some(workspace) = workspace else {
 7796                    return Ok(());
 7797                };
 7798                workspace
 7799                    .update(&mut cx, |workspace, cx| {
 7800                        Self::open_locations_in_multibuffer(
 7801                            workspace, locations, replica_id, title, split, cx,
 7802                        )
 7803                    })
 7804                    .ok();
 7805
 7806                anyhow::Ok(())
 7807            })
 7808            .detach_and_log_err(cx);
 7809        }
 7810    }
 7811
 7812    fn compute_target_location(
 7813        &self,
 7814        lsp_location: lsp::Location,
 7815        server_id: LanguageServerId,
 7816        cx: &mut ViewContext<Editor>,
 7817    ) -> Task<anyhow::Result<Option<Location>>> {
 7818        let Some(project) = self.project.clone() else {
 7819            return Task::Ready(Some(Ok(None)));
 7820        };
 7821
 7822        cx.spawn(move |editor, mut cx| async move {
 7823            let location_task = editor.update(&mut cx, |editor, cx| {
 7824                project.update(cx, |project, cx| {
 7825                    let language_server_name =
 7826                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 7827                            project
 7828                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 7829                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 7830                        });
 7831                    language_server_name.map(|language_server_name| {
 7832                        project.open_local_buffer_via_lsp(
 7833                            lsp_location.uri.clone(),
 7834                            server_id,
 7835                            language_server_name,
 7836                            cx,
 7837                        )
 7838                    })
 7839                })
 7840            })?;
 7841            let location = match location_task {
 7842                Some(task) => Some({
 7843                    let target_buffer_handle = task.await.context("open local buffer")?;
 7844                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 7845                        let target_start = target_buffer
 7846                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 7847                        let target_end = target_buffer
 7848                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 7849                        target_buffer.anchor_after(target_start)
 7850                            ..target_buffer.anchor_before(target_end)
 7851                    })?;
 7852                    Location {
 7853                        buffer: target_buffer_handle,
 7854                        range,
 7855                    }
 7856                }),
 7857                None => None,
 7858            };
 7859            Ok(location)
 7860        })
 7861    }
 7862
 7863    pub fn find_all_references(
 7864        &mut self,
 7865        _: &FindAllReferences,
 7866        cx: &mut ViewContext<Self>,
 7867    ) -> Option<Task<Result<()>>> {
 7868        let buffer = self.buffer.read(cx);
 7869        let head = self.selections.newest::<usize>(cx).head();
 7870        let (buffer, head) = buffer.text_anchor_for_position(head, cx)?;
 7871        let replica_id = self.replica_id(cx);
 7872
 7873        let workspace = self.workspace()?;
 7874        let project = workspace.read(cx).project().clone();
 7875        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 7876        Some(cx.spawn(|editor, mut cx| async move {
 7877            let mut locations = references.await?;
 7878            let snapshot = buffer.update(&mut cx, |buffer, _| buffer.snapshot())?;
 7879            let head_offset = text::ToOffset::to_offset(&head, &snapshot);
 7880
 7881            // LSP may return references that contain the item itself we requested `find_all_references` for (eg. rust-analyzer)
 7882            // So we will remove it from locations
 7883            // If there is only one reference, we will not do this filter cause it may make locations empty
 7884            if locations.len() > 1 {
 7885                cx.update(|cx| {
 7886                    locations.retain(|location| {
 7887                        // fn foo(x : i64) {
 7888                        //         ^
 7889                        //  println!(x);
 7890                        // }
 7891                        // It is ok to find reference when caret being at ^ (the end of the word)
 7892                        // So we turn offset into inclusive to include the end of the word
 7893                        !location
 7894                            .range
 7895                            .to_offset(location.buffer.read(cx))
 7896                            .to_inclusive()
 7897                            .contains(&head_offset)
 7898                    });
 7899                })?;
 7900            }
 7901
 7902            if locations.is_empty() {
 7903                return Ok(());
 7904            }
 7905
 7906            // If there is one reference, just open it directly
 7907            if locations.len() == 1 {
 7908                let target = locations.pop().unwrap();
 7909
 7910                return editor.update(&mut cx, |editor, cx| {
 7911                    let range = target.range.to_offset(target.buffer.read(cx));
 7912                    let range = editor.range_for_match(&range);
 7913
 7914                    if Some(&target.buffer) == editor.buffer().read(cx).as_singleton().as_ref() {
 7915                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7916                            s.select_ranges([range]);
 7917                        });
 7918                    } else {
 7919                        cx.window_context().defer(move |cx| {
 7920                            let target_editor: View<Self> =
 7921                                workspace.update(cx, |workspace, cx| {
 7922                                    workspace.open_project_item(
 7923                                        workspace.active_pane().clone(),
 7924                                        target.buffer.clone(),
 7925                                        cx,
 7926                                    )
 7927                                });
 7928                            target_editor.update(cx, |target_editor, cx| {
 7929                                target_editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7930                                    s.select_ranges([range]);
 7931                                })
 7932                            })
 7933                        })
 7934                    }
 7935                });
 7936            }
 7937
 7938            workspace.update(&mut cx, |workspace, cx| {
 7939                let title = locations
 7940                    .first()
 7941                    .as_ref()
 7942                    .map(|location| {
 7943                        let buffer = location.buffer.read(cx);
 7944                        format!(
 7945                            "References to `{}`",
 7946                            buffer
 7947                                .text_for_range(location.range.clone())
 7948                                .collect::<String>()
 7949                        )
 7950                    })
 7951                    .unwrap();
 7952                Self::open_locations_in_multibuffer(
 7953                    workspace, locations, replica_id, title, false, cx,
 7954                );
 7955            })?;
 7956
 7957            Ok(())
 7958        }))
 7959    }
 7960
 7961    /// Opens a multibuffer with the given project locations in it
 7962    pub fn open_locations_in_multibuffer(
 7963        workspace: &mut Workspace,
 7964        mut locations: Vec<Location>,
 7965        replica_id: ReplicaId,
 7966        title: String,
 7967        split: bool,
 7968        cx: &mut ViewContext<Workspace>,
 7969    ) {
 7970        // If there are multiple definitions, open them in a multibuffer
 7971        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 7972        let mut locations = locations.into_iter().peekable();
 7973        let mut ranges_to_highlight = Vec::new();
 7974        let capability = workspace.project().read(cx).capability();
 7975
 7976        let excerpt_buffer = cx.new_model(|cx| {
 7977            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 7978            while let Some(location) = locations.next() {
 7979                let buffer = location.buffer.read(cx);
 7980                let mut ranges_for_buffer = Vec::new();
 7981                let range = location.range.to_offset(buffer);
 7982                ranges_for_buffer.push(range.clone());
 7983
 7984                while let Some(next_location) = locations.peek() {
 7985                    if next_location.buffer == location.buffer {
 7986                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 7987                        locations.next();
 7988                    } else {
 7989                        break;
 7990                    }
 7991                }
 7992
 7993                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 7994                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 7995                    location.buffer.clone(),
 7996                    ranges_for_buffer,
 7997                    1,
 7998                    cx,
 7999                ))
 8000            }
 8001
 8002            multibuffer.with_title(title)
 8003        });
 8004
 8005        let editor = cx.new_view(|cx| {
 8006            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), cx)
 8007        });
 8008        editor.update(cx, |editor, cx| {
 8009            editor.highlight_background::<Self>(
 8010                ranges_to_highlight,
 8011                |theme| theme.editor_highlighted_line_background,
 8012                cx,
 8013            );
 8014        });
 8015        if split {
 8016            workspace.split_item(SplitDirection::Right, Box::new(editor), cx);
 8017        } else {
 8018            workspace.add_item_to_active_pane(Box::new(editor), cx);
 8019        }
 8020    }
 8021
 8022    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 8023        use language::ToOffset as _;
 8024
 8025        let project = self.project.clone()?;
 8026        let selection = self.selections.newest_anchor().clone();
 8027        let (cursor_buffer, cursor_buffer_position) = self
 8028            .buffer
 8029            .read(cx)
 8030            .text_anchor_for_position(selection.head(), cx)?;
 8031        let (tail_buffer, _) = self
 8032            .buffer
 8033            .read(cx)
 8034            .text_anchor_for_position(selection.tail(), cx)?;
 8035        if tail_buffer != cursor_buffer {
 8036            return None;
 8037        }
 8038
 8039        let snapshot = cursor_buffer.read(cx).snapshot();
 8040        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 8041        let prepare_rename = project.update(cx, |project, cx| {
 8042            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 8043        });
 8044        drop(snapshot);
 8045
 8046        Some(cx.spawn(|this, mut cx| async move {
 8047            let rename_range = if let Some(range) = prepare_rename.await? {
 8048                Some(range)
 8049            } else {
 8050                this.update(&mut cx, |this, cx| {
 8051                    let buffer = this.buffer.read(cx).snapshot(cx);
 8052                    let mut buffer_highlights = this
 8053                        .document_highlights_for_position(selection.head(), &buffer)
 8054                        .filter(|highlight| {
 8055                            highlight.start.excerpt_id == selection.head().excerpt_id
 8056                                && highlight.end.excerpt_id == selection.head().excerpt_id
 8057                        });
 8058                    buffer_highlights
 8059                        .next()
 8060                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 8061                })?
 8062            };
 8063            if let Some(rename_range) = rename_range {
 8064                this.update(&mut cx, |this, cx| {
 8065                    let snapshot = cursor_buffer.read(cx).snapshot();
 8066                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 8067                    let cursor_offset_in_rename_range =
 8068                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 8069
 8070                    this.take_rename(false, cx);
 8071                    let buffer = this.buffer.read(cx).read(cx);
 8072                    let cursor_offset = selection.head().to_offset(&buffer);
 8073                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 8074                    let rename_end = rename_start + rename_buffer_range.len();
 8075                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 8076                    let mut old_highlight_id = None;
 8077                    let old_name: Arc<str> = buffer
 8078                        .chunks(rename_start..rename_end, true)
 8079                        .map(|chunk| {
 8080                            if old_highlight_id.is_none() {
 8081                                old_highlight_id = chunk.syntax_highlight_id;
 8082                            }
 8083                            chunk.text
 8084                        })
 8085                        .collect::<String>()
 8086                        .into();
 8087
 8088                    drop(buffer);
 8089
 8090                    // Position the selection in the rename editor so that it matches the current selection.
 8091                    this.show_local_selections = false;
 8092                    let rename_editor = cx.new_view(|cx| {
 8093                        let mut editor = Editor::single_line(cx);
 8094                        editor.buffer.update(cx, |buffer, cx| {
 8095                            buffer.edit([(0..0, old_name.clone())], None, cx)
 8096                        });
 8097                        editor.select_all(&SelectAll, cx);
 8098                        editor
 8099                    });
 8100
 8101                    let ranges = this
 8102                        .clear_background_highlights::<DocumentHighlightWrite>(cx)
 8103                        .into_iter()
 8104                        .flat_map(|(_, ranges)| ranges.into_iter())
 8105                        .chain(
 8106                            this.clear_background_highlights::<DocumentHighlightRead>(cx)
 8107                                .into_iter()
 8108                                .flat_map(|(_, ranges)| ranges.into_iter()),
 8109                        )
 8110                        .collect();
 8111
 8112                    this.highlight_text::<Rename>(
 8113                        ranges,
 8114                        HighlightStyle {
 8115                            fade_out: Some(0.6),
 8116                            ..Default::default()
 8117                        },
 8118                        cx,
 8119                    );
 8120                    let rename_focus_handle = rename_editor.focus_handle(cx);
 8121                    cx.focus(&rename_focus_handle);
 8122                    let block_id = this.insert_blocks(
 8123                        [BlockProperties {
 8124                            style: BlockStyle::Flex,
 8125                            position: range.start,
 8126                            height: 1,
 8127                            render: Arc::new({
 8128                                let rename_editor = rename_editor.clone();
 8129                                move |cx: &mut BlockContext| {
 8130                                    let mut text_style = cx.editor_style.text.clone();
 8131                                    if let Some(highlight_style) = old_highlight_id
 8132                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 8133                                    {
 8134                                        text_style = text_style.highlight(highlight_style);
 8135                                    }
 8136                                    div()
 8137                                        .pl(cx.anchor_x)
 8138                                        .child(EditorElement::new(
 8139                                            &rename_editor,
 8140                                            EditorStyle {
 8141                                                background: cx.theme().system().transparent,
 8142                                                local_player: cx.editor_style.local_player,
 8143                                                text: text_style,
 8144                                                scrollbar_width: cx.editor_style.scrollbar_width,
 8145                                                syntax: cx.editor_style.syntax.clone(),
 8146                                                status: cx.editor_style.status.clone(),
 8147                                                inlay_hints_style: HighlightStyle {
 8148                                                    color: Some(cx.theme().status().hint),
 8149                                                    font_weight: Some(FontWeight::BOLD),
 8150                                                    ..HighlightStyle::default()
 8151                                                },
 8152                                                suggestions_style: HighlightStyle {
 8153                                                    color: Some(cx.theme().status().predictive),
 8154                                                    ..HighlightStyle::default()
 8155                                                },
 8156                                            },
 8157                                        ))
 8158                                        .into_any_element()
 8159                                }
 8160                            }),
 8161                            disposition: BlockDisposition::Below,
 8162                        }],
 8163                        Some(Autoscroll::fit()),
 8164                        cx,
 8165                    )[0];
 8166                    this.pending_rename = Some(RenameState {
 8167                        range,
 8168                        old_name,
 8169                        editor: rename_editor,
 8170                        block_id,
 8171                    });
 8172                })?;
 8173            }
 8174
 8175            Ok(())
 8176        }))
 8177    }
 8178
 8179    pub fn confirm_rename(
 8180        &mut self,
 8181        _: &ConfirmRename,
 8182        cx: &mut ViewContext<Self>,
 8183    ) -> Option<Task<Result<()>>> {
 8184        let rename = self.take_rename(false, cx)?;
 8185        let workspace = self.workspace()?;
 8186        let (start_buffer, start) = self
 8187            .buffer
 8188            .read(cx)
 8189            .text_anchor_for_position(rename.range.start, cx)?;
 8190        let (end_buffer, end) = self
 8191            .buffer
 8192            .read(cx)
 8193            .text_anchor_for_position(rename.range.end, cx)?;
 8194        if start_buffer != end_buffer {
 8195            return None;
 8196        }
 8197
 8198        let buffer = start_buffer;
 8199        let range = start..end;
 8200        let old_name = rename.old_name;
 8201        let new_name = rename.editor.read(cx).text(cx);
 8202
 8203        let rename = workspace
 8204            .read(cx)
 8205            .project()
 8206            .clone()
 8207            .update(cx, |project, cx| {
 8208                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 8209            });
 8210        let workspace = workspace.downgrade();
 8211
 8212        Some(cx.spawn(|editor, mut cx| async move {
 8213            let project_transaction = rename.await?;
 8214            Self::open_project_transaction(
 8215                &editor,
 8216                workspace,
 8217                project_transaction,
 8218                format!("Rename: {}{}", old_name, new_name),
 8219                cx.clone(),
 8220            )
 8221            .await?;
 8222
 8223            editor.update(&mut cx, |editor, cx| {
 8224                editor.refresh_document_highlights(cx);
 8225            })?;
 8226            Ok(())
 8227        }))
 8228    }
 8229
 8230    fn take_rename(
 8231        &mut self,
 8232        moving_cursor: bool,
 8233        cx: &mut ViewContext<Self>,
 8234    ) -> Option<RenameState> {
 8235        let rename = self.pending_rename.take()?;
 8236        if rename.editor.focus_handle(cx).is_focused(cx) {
 8237            cx.focus(&self.focus_handle);
 8238        }
 8239
 8240        self.remove_blocks(
 8241            [rename.block_id].into_iter().collect(),
 8242            Some(Autoscroll::fit()),
 8243            cx,
 8244        );
 8245        self.clear_highlights::<Rename>(cx);
 8246        self.show_local_selections = true;
 8247
 8248        if moving_cursor {
 8249            let rename_editor = rename.editor.read(cx);
 8250            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 8251
 8252            // Update the selection to match the position of the selection inside
 8253            // the rename editor.
 8254            let snapshot = self.buffer.read(cx).read(cx);
 8255            let rename_range = rename.range.to_offset(&snapshot);
 8256            let cursor_in_editor = snapshot
 8257                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 8258                .min(rename_range.end);
 8259            drop(snapshot);
 8260
 8261            self.change_selections(None, cx, |s| {
 8262                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 8263            });
 8264        } else {
 8265            self.refresh_document_highlights(cx);
 8266        }
 8267
 8268        Some(rename)
 8269    }
 8270
 8271    pub fn pending_rename(&self) -> Option<&RenameState> {
 8272        self.pending_rename.as_ref()
 8273    }
 8274
 8275    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 8276        let project = match &self.project {
 8277            Some(project) => project.clone(),
 8278            None => return None,
 8279        };
 8280
 8281        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 8282    }
 8283
 8284    fn perform_format(
 8285        &mut self,
 8286        project: Model<Project>,
 8287        trigger: FormatTrigger,
 8288        cx: &mut ViewContext<Self>,
 8289    ) -> Task<Result<()>> {
 8290        let buffer = self.buffer().clone();
 8291        let buffers = buffer.read(cx).all_buffers();
 8292
 8293        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 8294        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 8295
 8296        cx.spawn(|_, mut cx| async move {
 8297            let transaction = futures::select_biased! {
 8298                _ = timeout => {
 8299                    log::warn!("timed out waiting for formatting");
 8300                    None
 8301                }
 8302                transaction = format.log_err().fuse() => transaction,
 8303            };
 8304
 8305            buffer
 8306                .update(&mut cx, |buffer, cx| {
 8307                    if let Some(transaction) = transaction {
 8308                        if !buffer.is_singleton() {
 8309                            buffer.push_transaction(&transaction.0, cx);
 8310                        }
 8311                    }
 8312
 8313                    cx.notify();
 8314                })
 8315                .ok();
 8316
 8317            Ok(())
 8318        })
 8319    }
 8320
 8321    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
 8322        if let Some(project) = self.project.clone() {
 8323            self.buffer.update(cx, |multi_buffer, cx| {
 8324                project.update(cx, |project, cx| {
 8325                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
 8326                });
 8327            })
 8328        }
 8329    }
 8330
 8331    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 8332        cx.show_character_palette();
 8333    }
 8334
 8335    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
 8336        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
 8337            let buffer = self.buffer.read(cx).snapshot(cx);
 8338            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
 8339            let is_valid = buffer
 8340                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
 8341                .any(|entry| {
 8342                    entry.diagnostic.is_primary
 8343                        && !entry.range.is_empty()
 8344                        && entry.range.start == primary_range_start
 8345                        && entry.diagnostic.message == active_diagnostics.primary_message
 8346                });
 8347
 8348            if is_valid != active_diagnostics.is_valid {
 8349                active_diagnostics.is_valid = is_valid;
 8350                let mut new_styles = HashMap::default();
 8351                for (block_id, diagnostic) in &active_diagnostics.blocks {
 8352                    new_styles.insert(
 8353                        *block_id,
 8354                        diagnostic_block_renderer(diagnostic.clone(), is_valid),
 8355                    );
 8356                }
 8357                self.display_map
 8358                    .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
 8359            }
 8360        }
 8361    }
 8362
 8363    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
 8364        self.dismiss_diagnostics(cx);
 8365        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
 8366            let buffer = self.buffer.read(cx).snapshot(cx);
 8367
 8368            let mut primary_range = None;
 8369            let mut primary_message = None;
 8370            let mut group_end = Point::zero();
 8371            let diagnostic_group = buffer
 8372                .diagnostic_group::<Point>(group_id)
 8373                .map(|entry| {
 8374                    if entry.range.end > group_end {
 8375                        group_end = entry.range.end;
 8376                    }
 8377                    if entry.diagnostic.is_primary {
 8378                        primary_range = Some(entry.range.clone());
 8379                        primary_message = Some(entry.diagnostic.message.clone());
 8380                    }
 8381                    entry
 8382                })
 8383                .collect::<Vec<_>>();
 8384            let primary_range = primary_range?;
 8385            let primary_message = primary_message?;
 8386            let primary_range =
 8387                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
 8388
 8389            let blocks = display_map
 8390                .insert_blocks(
 8391                    diagnostic_group.iter().map(|entry| {
 8392                        let diagnostic = entry.diagnostic.clone();
 8393                        let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
 8394                        BlockProperties {
 8395                            style: BlockStyle::Fixed,
 8396                            position: buffer.anchor_after(entry.range.start),
 8397                            height: message_height,
 8398                            render: diagnostic_block_renderer(diagnostic, true),
 8399                            disposition: BlockDisposition::Below,
 8400                        }
 8401                    }),
 8402                    cx,
 8403                )
 8404                .into_iter()
 8405                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
 8406                .collect();
 8407
 8408            Some(ActiveDiagnosticGroup {
 8409                primary_range,
 8410                primary_message,
 8411                blocks,
 8412                is_valid: true,
 8413            })
 8414        });
 8415        self.active_diagnostics.is_some()
 8416    }
 8417
 8418    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
 8419        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
 8420            self.display_map.update(cx, |display_map, cx| {
 8421                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
 8422            });
 8423            cx.notify();
 8424        }
 8425    }
 8426
 8427    pub fn set_selections_from_remote(
 8428        &mut self,
 8429        selections: Vec<Selection<Anchor>>,
 8430        pending_selection: Option<Selection<Anchor>>,
 8431        cx: &mut ViewContext<Self>,
 8432    ) {
 8433        let old_cursor_position = self.selections.newest_anchor().head();
 8434        self.selections.change_with(cx, |s| {
 8435            s.select_anchors(selections);
 8436            if let Some(pending_selection) = pending_selection {
 8437                s.set_pending(pending_selection, SelectMode::Character);
 8438            } else {
 8439                s.clear_pending();
 8440            }
 8441        });
 8442        self.selections_did_change(false, &old_cursor_position, cx);
 8443    }
 8444
 8445    fn push_to_selection_history(&mut self) {
 8446        self.selection_history.push(SelectionHistoryEntry {
 8447            selections: self.selections.disjoint_anchors(),
 8448            select_next_state: self.select_next_state.clone(),
 8449            select_prev_state: self.select_prev_state.clone(),
 8450            add_selections_state: self.add_selections_state.clone(),
 8451        });
 8452    }
 8453
 8454    pub fn transact(
 8455        &mut self,
 8456        cx: &mut ViewContext<Self>,
 8457        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
 8458    ) -> Option<TransactionId> {
 8459        self.start_transaction_at(Instant::now(), cx);
 8460        update(self, cx);
 8461        self.end_transaction_at(Instant::now(), cx)
 8462    }
 8463
 8464    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
 8465        self.end_selection(cx);
 8466        if let Some(tx_id) = self
 8467            .buffer
 8468            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
 8469        {
 8470            self.selection_history
 8471                .insert_transaction(tx_id, self.selections.disjoint_anchors());
 8472        }
 8473    }
 8474
 8475    fn end_transaction_at(
 8476        &mut self,
 8477        now: Instant,
 8478        cx: &mut ViewContext<Self>,
 8479    ) -> Option<TransactionId> {
 8480        if let Some(tx_id) = self
 8481            .buffer
 8482            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 8483        {
 8484            if let Some((_, end_selections)) = self.selection_history.transaction_mut(tx_id) {
 8485                *end_selections = Some(self.selections.disjoint_anchors());
 8486            } else {
 8487                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
 8488            }
 8489
 8490            cx.emit(EditorEvent::Edited);
 8491            Some(tx_id)
 8492        } else {
 8493            None
 8494        }
 8495    }
 8496
 8497    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
 8498        let mut fold_ranges = Vec::new();
 8499
 8500        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8501
 8502        let selections = self.selections.all_adjusted(cx);
 8503        for selection in selections {
 8504            let range = selection.range().sorted();
 8505            let buffer_start_row = range.start.row;
 8506
 8507            for row in (0..=range.end.row).rev() {
 8508                let fold_range = display_map.foldable_range(row);
 8509
 8510                if let Some(fold_range) = fold_range {
 8511                    if fold_range.end.row >= buffer_start_row {
 8512                        fold_ranges.push(fold_range);
 8513                        if row <= range.start.row {
 8514                            break;
 8515                        }
 8516                    }
 8517                }
 8518            }
 8519        }
 8520
 8521        self.fold_ranges(fold_ranges, true, cx);
 8522    }
 8523
 8524    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
 8525        let buffer_row = fold_at.buffer_row;
 8526        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8527
 8528        if let Some(fold_range) = display_map.foldable_range(buffer_row) {
 8529            let autoscroll = self
 8530                .selections
 8531                .all::<Point>(cx)
 8532                .iter()
 8533                .any(|selection| fold_range.overlaps(&selection.range()));
 8534
 8535            self.fold_ranges(std::iter::once(fold_range), autoscroll, cx);
 8536        }
 8537    }
 8538
 8539    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
 8540        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8541        let buffer = &display_map.buffer_snapshot;
 8542        let selections = self.selections.all::<Point>(cx);
 8543        let ranges = selections
 8544            .iter()
 8545            .map(|s| {
 8546                let range = s.display_range(&display_map).sorted();
 8547                let mut start = range.start.to_point(&display_map);
 8548                let mut end = range.end.to_point(&display_map);
 8549                start.column = 0;
 8550                end.column = buffer.line_len(end.row);
 8551                start..end
 8552            })
 8553            .collect::<Vec<_>>();
 8554
 8555        self.unfold_ranges(ranges, true, true, cx);
 8556    }
 8557
 8558    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
 8559        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8560
 8561        let intersection_range = Point::new(unfold_at.buffer_row, 0)
 8562            ..Point::new(
 8563                unfold_at.buffer_row,
 8564                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
 8565            );
 8566
 8567        let autoscroll = self
 8568            .selections
 8569            .all::<Point>(cx)
 8570            .iter()
 8571            .any(|selection| selection.range().overlaps(&intersection_range));
 8572
 8573        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
 8574    }
 8575
 8576    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
 8577        let selections = self.selections.all::<Point>(cx);
 8578        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8579        let line_mode = self.selections.line_mode;
 8580        let ranges = selections.into_iter().map(|s| {
 8581            if line_mode {
 8582                let start = Point::new(s.start.row, 0);
 8583                let end = Point::new(s.end.row, display_map.buffer_snapshot.line_len(s.end.row));
 8584                start..end
 8585            } else {
 8586                s.start..s.end
 8587            }
 8588        });
 8589        self.fold_ranges(ranges, true, cx);
 8590    }
 8591
 8592    pub fn fold_ranges<T: ToOffset + Clone>(
 8593        &mut self,
 8594        ranges: impl IntoIterator<Item = Range<T>>,
 8595        auto_scroll: bool,
 8596        cx: &mut ViewContext<Self>,
 8597    ) {
 8598        let mut ranges = ranges.into_iter().peekable();
 8599        if ranges.peek().is_some() {
 8600            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
 8601
 8602            if auto_scroll {
 8603                self.request_autoscroll(Autoscroll::fit(), cx);
 8604            }
 8605
 8606            cx.notify();
 8607        }
 8608    }
 8609
 8610    pub fn unfold_ranges<T: ToOffset + Clone>(
 8611        &mut self,
 8612        ranges: impl IntoIterator<Item = Range<T>>,
 8613        inclusive: bool,
 8614        auto_scroll: bool,
 8615        cx: &mut ViewContext<Self>,
 8616    ) {
 8617        let mut ranges = ranges.into_iter().peekable();
 8618        if ranges.peek().is_some() {
 8619            self.display_map
 8620                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
 8621            if auto_scroll {
 8622                self.request_autoscroll(Autoscroll::fit(), cx);
 8623            }
 8624
 8625            cx.notify();
 8626        }
 8627    }
 8628
 8629    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
 8630        if hovered != self.gutter_hovered {
 8631            self.gutter_hovered = hovered;
 8632            cx.notify();
 8633        }
 8634    }
 8635
 8636    pub fn insert_blocks(
 8637        &mut self,
 8638        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
 8639        autoscroll: Option<Autoscroll>,
 8640        cx: &mut ViewContext<Self>,
 8641    ) -> Vec<BlockId> {
 8642        let blocks = self
 8643            .display_map
 8644            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
 8645        if let Some(autoscroll) = autoscroll {
 8646            self.request_autoscroll(autoscroll, cx);
 8647        }
 8648        blocks
 8649    }
 8650
 8651    pub fn replace_blocks(
 8652        &mut self,
 8653        blocks: HashMap<BlockId, RenderBlock>,
 8654        autoscroll: Option<Autoscroll>,
 8655        cx: &mut ViewContext<Self>,
 8656    ) {
 8657        self.display_map
 8658            .update(cx, |display_map, _| display_map.replace_blocks(blocks));
 8659        if let Some(autoscroll) = autoscroll {
 8660            self.request_autoscroll(autoscroll, cx);
 8661        }
 8662    }
 8663
 8664    pub fn remove_blocks(
 8665        &mut self,
 8666        block_ids: HashSet<BlockId>,
 8667        autoscroll: Option<Autoscroll>,
 8668        cx: &mut ViewContext<Self>,
 8669    ) {
 8670        self.display_map.update(cx, |display_map, cx| {
 8671            display_map.remove_blocks(block_ids, cx)
 8672        });
 8673        if let Some(autoscroll) = autoscroll {
 8674            self.request_autoscroll(autoscroll, cx);
 8675        }
 8676    }
 8677
 8678    pub fn longest_row(&self, cx: &mut AppContext) -> u32 {
 8679        self.display_map
 8680            .update(cx, |map, cx| map.snapshot(cx))
 8681            .longest_row()
 8682    }
 8683
 8684    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
 8685        self.display_map
 8686            .update(cx, |map, cx| map.snapshot(cx))
 8687            .max_point()
 8688    }
 8689
 8690    pub fn text(&self, cx: &AppContext) -> String {
 8691        self.buffer.read(cx).read(cx).text()
 8692    }
 8693
 8694    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
 8695        let text = self.text(cx);
 8696        let text = text.trim();
 8697
 8698        if text.is_empty() {
 8699            return None;
 8700        }
 8701
 8702        Some(text.to_string())
 8703    }
 8704
 8705    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
 8706        self.transact(cx, |this, cx| {
 8707            this.buffer
 8708                .read(cx)
 8709                .as_singleton()
 8710                .expect("you can only call set_text on editors for singleton buffers")
 8711                .update(cx, |buffer, cx| buffer.set_text(text, cx));
 8712        });
 8713    }
 8714
 8715    pub fn display_text(&self, cx: &mut AppContext) -> String {
 8716        self.display_map
 8717            .update(cx, |map, cx| map.snapshot(cx))
 8718            .text()
 8719    }
 8720
 8721    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
 8722        let mut wrap_guides = smallvec::smallvec![];
 8723
 8724        if self.show_wrap_guides == Some(false) {
 8725            return wrap_guides;
 8726        }
 8727
 8728        let settings = self.buffer.read(cx).settings_at(0, cx);
 8729        if settings.show_wrap_guides {
 8730            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
 8731                wrap_guides.push((soft_wrap as usize, true));
 8732            }
 8733            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
 8734        }
 8735
 8736        wrap_guides
 8737    }
 8738
 8739    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
 8740        let settings = self.buffer.read(cx).settings_at(0, cx);
 8741        let mode = self
 8742            .soft_wrap_mode_override
 8743            .unwrap_or_else(|| settings.soft_wrap);
 8744        match mode {
 8745            language_settings::SoftWrap::None => SoftWrap::None,
 8746            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
 8747            language_settings::SoftWrap::PreferredLineLength => {
 8748                SoftWrap::Column(settings.preferred_line_length)
 8749            }
 8750        }
 8751    }
 8752
 8753    pub fn set_soft_wrap_mode(
 8754        &mut self,
 8755        mode: language_settings::SoftWrap,
 8756        cx: &mut ViewContext<Self>,
 8757    ) {
 8758        self.soft_wrap_mode_override = Some(mode);
 8759        cx.notify();
 8760    }
 8761
 8762    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
 8763        let rem_size = cx.rem_size();
 8764        self.display_map.update(cx, |map, cx| {
 8765            map.set_font(
 8766                style.text.font(),
 8767                style.text.font_size.to_pixels(rem_size),
 8768                cx,
 8769            )
 8770        });
 8771        self.style = Some(style);
 8772    }
 8773
 8774    #[cfg(any(test, feature = "test-support"))]
 8775    pub fn style(&self) -> Option<&EditorStyle> {
 8776        self.style.as_ref()
 8777    }
 8778
 8779    // Called by the element. This method is not designed to be called outside of the editor
 8780    // element's layout code because it does not notify when rewrapping is computed synchronously.
 8781    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
 8782        self.display_map
 8783            .update(cx, |map, cx| map.set_wrap_width(width, cx))
 8784    }
 8785
 8786    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
 8787        if self.soft_wrap_mode_override.is_some() {
 8788            self.soft_wrap_mode_override.take();
 8789        } else {
 8790            let soft_wrap = match self.soft_wrap_mode(cx) {
 8791                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
 8792                SoftWrap::EditorWidth | SoftWrap::Column(_) => language_settings::SoftWrap::None,
 8793            };
 8794            self.soft_wrap_mode_override = Some(soft_wrap);
 8795        }
 8796        cx.notify();
 8797    }
 8798
 8799    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
 8800        let mut editor_settings = EditorSettings::get_global(cx).clone();
 8801        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
 8802        EditorSettings::override_global(editor_settings, cx);
 8803    }
 8804
 8805    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
 8806        self.show_gutter = show_gutter;
 8807        cx.notify();
 8808    }
 8809
 8810    pub fn set_show_wrap_guides(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
 8811        self.show_wrap_guides = Some(show_gutter);
 8812        cx.notify();
 8813    }
 8814
 8815    pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
 8816        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 8817            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 8818                cx.reveal_path(&file.abs_path(cx));
 8819            }
 8820        }
 8821    }
 8822
 8823    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
 8824        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 8825            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 8826                if let Some(path) = file.abs_path(cx).to_str() {
 8827                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
 8828                }
 8829            }
 8830        }
 8831    }
 8832
 8833    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
 8834        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
 8835            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
 8836                if let Some(path) = file.path().to_str() {
 8837                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
 8838                }
 8839            }
 8840        }
 8841    }
 8842
 8843    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
 8844        use git::permalink::{build_permalink, BuildPermalinkParams};
 8845
 8846        let (path, repo) = maybe!({
 8847            let project_handle = self.project.as_ref()?.clone();
 8848            let project = project_handle.read(cx);
 8849            let buffer = self.buffer().read(cx).as_singleton()?;
 8850            let path = buffer
 8851                .read(cx)
 8852                .file()?
 8853                .as_local()?
 8854                .path()
 8855                .to_str()?
 8856                .to_string();
 8857            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
 8858            Some((path, repo))
 8859        })
 8860        .ok_or_else(|| anyhow!("unable to open git repository"))?;
 8861
 8862        const REMOTE_NAME: &str = "origin";
 8863        let origin_url = repo
 8864            .lock()
 8865            .remote_url(REMOTE_NAME)
 8866            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
 8867        let sha = repo
 8868            .lock()
 8869            .head_sha()
 8870            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
 8871        let selections = self.selections.all::<Point>(cx);
 8872        let selection = selections.iter().peekable().next();
 8873
 8874        build_permalink(BuildPermalinkParams {
 8875            remote_url: &origin_url,
 8876            sha: &sha,
 8877            path: &path,
 8878            selection: selection.map(|selection| selection.range()),
 8879        })
 8880    }
 8881
 8882    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
 8883        let permalink = self.get_permalink_to_line(cx);
 8884
 8885        match permalink {
 8886            Ok(permalink) => {
 8887                cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
 8888            }
 8889            Err(err) => {
 8890                let message = format!("Failed to copy permalink: {err}");
 8891
 8892                Err::<(), anyhow::Error>(err).log_err();
 8893
 8894                if let Some(workspace) = self.workspace() {
 8895                    workspace.update(cx, |workspace, cx| {
 8896                        workspace.show_toast(Toast::new(0x156a5f9ee, message), cx)
 8897                    })
 8898                }
 8899            }
 8900        }
 8901    }
 8902
 8903    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
 8904        let permalink = self.get_permalink_to_line(cx);
 8905
 8906        match permalink {
 8907            Ok(permalink) => {
 8908                cx.open_url(permalink.as_ref());
 8909            }
 8910            Err(err) => {
 8911                let message = format!("Failed to open permalink: {err}");
 8912
 8913                Err::<(), anyhow::Error>(err).log_err();
 8914
 8915                if let Some(workspace) = self.workspace() {
 8916                    workspace.update(cx, |workspace, cx| {
 8917                        workspace.show_toast(Toast::new(0x45a8978, message), cx)
 8918                    })
 8919                }
 8920            }
 8921        }
 8922    }
 8923
 8924    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
 8925    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
 8926    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
 8927    pub fn highlight_rows<T: 'static>(
 8928        &mut self,
 8929        rows: Range<Anchor>,
 8930        color: Option<Hsla>,
 8931        cx: &mut ViewContext<Self>,
 8932    ) {
 8933        let multi_buffer_snapshot = self.buffer().read(cx).snapshot(cx);
 8934        match self.highlighted_rows.entry(TypeId::of::<T>()) {
 8935            hash_map::Entry::Occupied(o) => {
 8936                let row_highlights = o.into_mut();
 8937                let existing_highlight_index =
 8938                    row_highlights.binary_search_by(|(_, highlight_range, _)| {
 8939                        highlight_range
 8940                            .start
 8941                            .cmp(&rows.start, &multi_buffer_snapshot)
 8942                            .then(highlight_range.end.cmp(&rows.end, &multi_buffer_snapshot))
 8943                    });
 8944                match color {
 8945                    Some(color) => {
 8946                        let insert_index = match existing_highlight_index {
 8947                            Ok(i) => i,
 8948                            Err(i) => i,
 8949                        };
 8950                        row_highlights.insert(
 8951                            insert_index,
 8952                            (post_inc(&mut self.highlight_order), rows, color),
 8953                        );
 8954                    }
 8955                    None => {
 8956                        if let Ok(i) = existing_highlight_index {
 8957                            row_highlights.remove(i);
 8958                        }
 8959                    }
 8960                }
 8961            }
 8962            hash_map::Entry::Vacant(v) => {
 8963                if let Some(color) = color {
 8964                    v.insert(vec![(post_inc(&mut self.highlight_order), rows, color)]);
 8965                }
 8966            }
 8967        }
 8968    }
 8969
 8970    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
 8971    pub fn clear_row_highlights<T: 'static>(&mut self) {
 8972        self.highlighted_rows.remove(&TypeId::of::<T>());
 8973    }
 8974
 8975    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
 8976    pub fn highlighted_rows<T: 'static>(
 8977        &self,
 8978    ) -> Option<impl Iterator<Item = (&Range<Anchor>, &Hsla)>> {
 8979        Some(
 8980            self.highlighted_rows
 8981                .get(&TypeId::of::<T>())?
 8982                .iter()
 8983                .map(|(_, range, color)| (range, color)),
 8984        )
 8985    }
 8986
 8987    // Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
 8988    // Rerturns a map of display rows that are highlighted and their corresponding highlight color.
 8989    pub fn highlighted_display_rows(&mut self, cx: &mut WindowContext) -> BTreeMap<u32, Hsla> {
 8990        let snapshot = self.snapshot(cx);
 8991        let mut used_highlight_orders = HashMap::default();
 8992        self.highlighted_rows
 8993            .iter()
 8994            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
 8995            .fold(
 8996                BTreeMap::<u32, Hsla>::new(),
 8997                |mut unique_rows, (highlight_order, anchor_range, hsla)| {
 8998                    let start_row = anchor_range.start.to_display_point(&snapshot).row();
 8999                    let end_row = anchor_range.end.to_display_point(&snapshot).row();
 9000                    for row in start_row..=end_row {
 9001                        let used_index =
 9002                            used_highlight_orders.entry(row).or_insert(*highlight_order);
 9003                        if highlight_order >= used_index {
 9004                            *used_index = *highlight_order;
 9005                            unique_rows.insert(row, *hsla);
 9006                        }
 9007                    }
 9008                    unique_rows
 9009                },
 9010            )
 9011    }
 9012
 9013    pub fn highlight_background<T: 'static>(
 9014        &mut self,
 9015        ranges: Vec<Range<Anchor>>,
 9016        color_fetcher: fn(&ThemeColors) -> Hsla,
 9017        cx: &mut ViewContext<Self>,
 9018    ) {
 9019        let snapshot = self.snapshot(cx);
 9020        // this is to try and catch a panic sooner
 9021        for range in &ranges {
 9022            snapshot
 9023                .buffer_snapshot
 9024                .summary_for_anchor::<usize>(&range.start);
 9025            snapshot
 9026                .buffer_snapshot
 9027                .summary_for_anchor::<usize>(&range.end);
 9028        }
 9029
 9030        self.background_highlights
 9031            .insert(TypeId::of::<T>(), (color_fetcher, ranges));
 9032        cx.notify();
 9033    }
 9034
 9035    pub fn clear_background_highlights<T: 'static>(
 9036        &mut self,
 9037        _cx: &mut ViewContext<Self>,
 9038    ) -> Option<BackgroundHighlight> {
 9039        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>());
 9040        text_highlights
 9041    }
 9042
 9043    #[cfg(feature = "test-support")]
 9044    pub fn all_text_background_highlights(
 9045        &mut self,
 9046        cx: &mut ViewContext<Self>,
 9047    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
 9048        let snapshot = self.snapshot(cx);
 9049        let buffer = &snapshot.buffer_snapshot;
 9050        let start = buffer.anchor_before(0);
 9051        let end = buffer.anchor_after(buffer.len());
 9052        let theme = cx.theme().colors();
 9053        self.background_highlights_in_range(start..end, &snapshot, theme)
 9054    }
 9055
 9056    fn document_highlights_for_position<'a>(
 9057        &'a self,
 9058        position: Anchor,
 9059        buffer: &'a MultiBufferSnapshot,
 9060    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
 9061        let read_highlights = self
 9062            .background_highlights
 9063            .get(&TypeId::of::<DocumentHighlightRead>())
 9064            .map(|h| &h.1);
 9065        let write_highlights = self
 9066            .background_highlights
 9067            .get(&TypeId::of::<DocumentHighlightWrite>())
 9068            .map(|h| &h.1);
 9069        let left_position = position.bias_left(buffer);
 9070        let right_position = position.bias_right(buffer);
 9071        read_highlights
 9072            .into_iter()
 9073            .chain(write_highlights)
 9074            .flat_map(move |ranges| {
 9075                let start_ix = match ranges.binary_search_by(|probe| {
 9076                    let cmp = probe.end.cmp(&left_position, buffer);
 9077                    if cmp.is_ge() {
 9078                        Ordering::Greater
 9079                    } else {
 9080                        Ordering::Less
 9081                    }
 9082                }) {
 9083                    Ok(i) | Err(i) => i,
 9084                };
 9085
 9086                ranges[start_ix..]
 9087                    .iter()
 9088                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
 9089            })
 9090    }
 9091
 9092    pub fn has_background_highlights<T: 'static>(&self) -> bool {
 9093        self.background_highlights
 9094            .get(&TypeId::of::<T>())
 9095            .map_or(false, |(_, highlights)| !highlights.is_empty())
 9096    }
 9097
 9098    pub fn background_highlights_in_range(
 9099        &self,
 9100        search_range: Range<Anchor>,
 9101        display_snapshot: &DisplaySnapshot,
 9102        theme: &ThemeColors,
 9103    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
 9104        let mut results = Vec::new();
 9105        for (color_fetcher, ranges) in self.background_highlights.values() {
 9106            let color = color_fetcher(theme);
 9107            let start_ix = match ranges.binary_search_by(|probe| {
 9108                let cmp = probe
 9109                    .end
 9110                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
 9111                if cmp.is_gt() {
 9112                    Ordering::Greater
 9113                } else {
 9114                    Ordering::Less
 9115                }
 9116            }) {
 9117                Ok(i) | Err(i) => i,
 9118            };
 9119            for range in &ranges[start_ix..] {
 9120                if range
 9121                    .start
 9122                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
 9123                    .is_ge()
 9124                {
 9125                    break;
 9126                }
 9127
 9128                let start = range.start.to_display_point(&display_snapshot);
 9129                let end = range.end.to_display_point(&display_snapshot);
 9130                results.push((start..end, color))
 9131            }
 9132        }
 9133        results
 9134    }
 9135
 9136    pub fn background_highlight_row_ranges<T: 'static>(
 9137        &self,
 9138        search_range: Range<Anchor>,
 9139        display_snapshot: &DisplaySnapshot,
 9140        count: usize,
 9141    ) -> Vec<RangeInclusive<DisplayPoint>> {
 9142        let mut results = Vec::new();
 9143        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
 9144            return vec![];
 9145        };
 9146
 9147        let start_ix = match ranges.binary_search_by(|probe| {
 9148            let cmp = probe
 9149                .end
 9150                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
 9151            if cmp.is_gt() {
 9152                Ordering::Greater
 9153            } else {
 9154                Ordering::Less
 9155            }
 9156        }) {
 9157            Ok(i) | Err(i) => i,
 9158        };
 9159        let mut push_region = |start: Option<Point>, end: Option<Point>| {
 9160            if let (Some(start_display), Some(end_display)) = (start, end) {
 9161                results.push(
 9162                    start_display.to_display_point(display_snapshot)
 9163                        ..=end_display.to_display_point(display_snapshot),
 9164                );
 9165            }
 9166        };
 9167        let mut start_row: Option<Point> = None;
 9168        let mut end_row: Option<Point> = None;
 9169        if ranges.len() > count {
 9170            return Vec::new();
 9171        }
 9172        for range in &ranges[start_ix..] {
 9173            if range
 9174                .start
 9175                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
 9176                .is_ge()
 9177            {
 9178                break;
 9179            }
 9180            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
 9181            if let Some(current_row) = &end_row {
 9182                if end.row == current_row.row {
 9183                    continue;
 9184                }
 9185            }
 9186            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
 9187            if start_row.is_none() {
 9188                assert_eq!(end_row, None);
 9189                start_row = Some(start);
 9190                end_row = Some(end);
 9191                continue;
 9192            }
 9193            if let Some(current_end) = end_row.as_mut() {
 9194                if start.row > current_end.row + 1 {
 9195                    push_region(start_row, end_row);
 9196                    start_row = Some(start);
 9197                    end_row = Some(end);
 9198                } else {
 9199                    // Merge two hunks.
 9200                    *current_end = end;
 9201                }
 9202            } else {
 9203                unreachable!();
 9204            }
 9205        }
 9206        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
 9207        push_region(start_row, end_row);
 9208        results
 9209    }
 9210
 9211    /// Get the text ranges corresponding to the redaction query
 9212    pub fn redacted_ranges(
 9213        &self,
 9214        search_range: Range<Anchor>,
 9215        display_snapshot: &DisplaySnapshot,
 9216        cx: &WindowContext,
 9217    ) -> Vec<Range<DisplayPoint>> {
 9218        display_snapshot
 9219            .buffer_snapshot
 9220            .redacted_ranges(search_range, |file| {
 9221                if let Some(file) = file {
 9222                    file.is_private()
 9223                        && EditorSettings::get(Some((file.worktree_id(), file.path())), cx)
 9224                            .redact_private_values
 9225                } else {
 9226                    false
 9227                }
 9228            })
 9229            .map(|range| {
 9230                range.start.to_display_point(display_snapshot)
 9231                    ..range.end.to_display_point(display_snapshot)
 9232            })
 9233            .collect()
 9234    }
 9235
 9236    pub fn highlight_text<T: 'static>(
 9237        &mut self,
 9238        ranges: Vec<Range<Anchor>>,
 9239        style: HighlightStyle,
 9240        cx: &mut ViewContext<Self>,
 9241    ) {
 9242        self.display_map.update(cx, |map, _| {
 9243            map.highlight_text(TypeId::of::<T>(), ranges, style)
 9244        });
 9245        cx.notify();
 9246    }
 9247
 9248    pub(crate) fn highlight_inlays<T: 'static>(
 9249        &mut self,
 9250        highlights: Vec<InlayHighlight>,
 9251        style: HighlightStyle,
 9252        cx: &mut ViewContext<Self>,
 9253    ) {
 9254        self.display_map.update(cx, |map, _| {
 9255            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
 9256        });
 9257        cx.notify();
 9258    }
 9259
 9260    pub fn text_highlights<'a, T: 'static>(
 9261        &'a self,
 9262        cx: &'a AppContext,
 9263    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
 9264        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
 9265    }
 9266
 9267    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
 9268        let cleared = self
 9269            .display_map
 9270            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
 9271        if cleared {
 9272            cx.notify();
 9273        }
 9274    }
 9275
 9276    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
 9277        (self.read_only(cx) || self.blink_manager.read(cx).visible())
 9278            && self.focus_handle.is_focused(cx)
 9279    }
 9280
 9281    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
 9282        cx.notify();
 9283    }
 9284
 9285    fn on_buffer_event(
 9286        &mut self,
 9287        multibuffer: Model<MultiBuffer>,
 9288        event: &multi_buffer::Event,
 9289        cx: &mut ViewContext<Self>,
 9290    ) {
 9291        match event {
 9292            multi_buffer::Event::Edited {
 9293                singleton_buffer_edited,
 9294            } => {
 9295                self.refresh_active_diagnostics(cx);
 9296                self.refresh_code_actions(cx);
 9297                if self.has_active_copilot_suggestion(cx) {
 9298                    self.update_visible_copilot_suggestion(cx);
 9299                }
 9300                cx.emit(EditorEvent::BufferEdited);
 9301                cx.emit(SearchEvent::MatchesInvalidated);
 9302
 9303                if *singleton_buffer_edited {
 9304                    if let Some(project) = &self.project {
 9305                        let project = project.read(cx);
 9306                        let languages_affected = multibuffer
 9307                            .read(cx)
 9308                            .all_buffers()
 9309                            .into_iter()
 9310                            .filter_map(|buffer| {
 9311                                let buffer = buffer.read(cx);
 9312                                let language = buffer.language()?;
 9313                                if project.is_local()
 9314                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
 9315                                {
 9316                                    None
 9317                                } else {
 9318                                    Some(language)
 9319                                }
 9320                            })
 9321                            .cloned()
 9322                            .collect::<HashSet<_>>();
 9323                        if !languages_affected.is_empty() {
 9324                            self.refresh_inlay_hints(
 9325                                InlayHintRefreshReason::BufferEdited(languages_affected),
 9326                                cx,
 9327                            );
 9328                        }
 9329                    }
 9330                }
 9331
 9332                let Some(project) = &self.project else { return };
 9333                let telemetry = project.read(cx).client().telemetry().clone();
 9334                telemetry.log_edit_event("editor");
 9335            }
 9336            multi_buffer::Event::ExcerptsAdded {
 9337                buffer,
 9338                predecessor,
 9339                excerpts,
 9340            } => {
 9341                cx.emit(EditorEvent::ExcerptsAdded {
 9342                    buffer: buffer.clone(),
 9343                    predecessor: *predecessor,
 9344                    excerpts: excerpts.clone(),
 9345                });
 9346                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
 9347            }
 9348            multi_buffer::Event::ExcerptsRemoved { ids } => {
 9349                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
 9350                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
 9351            }
 9352            multi_buffer::Event::Reparsed => cx.emit(EditorEvent::Reparsed),
 9353            multi_buffer::Event::LanguageChanged => {
 9354                cx.emit(EditorEvent::Reparsed);
 9355                cx.notify();
 9356            }
 9357            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
 9358            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
 9359            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
 9360                cx.emit(EditorEvent::TitleChanged)
 9361            }
 9362            multi_buffer::Event::DiffBaseChanged => cx.emit(EditorEvent::DiffBaseChanged),
 9363            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
 9364            multi_buffer::Event::DiagnosticsUpdated => {
 9365                self.refresh_active_diagnostics(cx);
 9366            }
 9367            _ => {}
 9368        };
 9369    }
 9370
 9371    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
 9372        cx.notify();
 9373    }
 9374
 9375    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
 9376        self.refresh_copilot_suggestions(true, cx);
 9377        self.refresh_inlay_hints(
 9378            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
 9379                self.selections.newest_anchor().head(),
 9380                &self.buffer.read(cx).snapshot(cx),
 9381                cx,
 9382            )),
 9383            cx,
 9384        );
 9385        let editor_settings = EditorSettings::get_global(cx);
 9386        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
 9387        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
 9388        cx.notify();
 9389    }
 9390
 9391    pub fn set_searchable(&mut self, searchable: bool) {
 9392        self.searchable = searchable;
 9393    }
 9394
 9395    pub fn searchable(&self) -> bool {
 9396        self.searchable
 9397    }
 9398
 9399    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
 9400        self.open_excerpts_common(true, cx)
 9401    }
 9402
 9403    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
 9404        self.open_excerpts_common(false, cx)
 9405    }
 9406
 9407    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
 9408        let buffer = self.buffer.read(cx);
 9409        if buffer.is_singleton() {
 9410            cx.propagate();
 9411            return;
 9412        }
 9413
 9414        let Some(workspace) = self.workspace() else {
 9415            cx.propagate();
 9416            return;
 9417        };
 9418
 9419        let mut new_selections_by_buffer = HashMap::default();
 9420        for selection in self.selections.all::<usize>(cx) {
 9421            for (buffer, mut range, _) in
 9422                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
 9423            {
 9424                if selection.reversed {
 9425                    mem::swap(&mut range.start, &mut range.end);
 9426                }
 9427                new_selections_by_buffer
 9428                    .entry(buffer)
 9429                    .or_insert(Vec::new())
 9430                    .push(range)
 9431            }
 9432        }
 9433
 9434        // We defer the pane interaction because we ourselves are a workspace item
 9435        // and activating a new item causes the pane to call a method on us reentrantly,
 9436        // which panics if we're on the stack.
 9437        cx.window_context().defer(move |cx| {
 9438            workspace.update(cx, |workspace, cx| {
 9439                let pane = if split {
 9440                    workspace.adjacent_pane(cx)
 9441                } else {
 9442                    workspace.active_pane().clone()
 9443                };
 9444                pane.update(cx, |pane, _| pane.disable_history());
 9445
 9446                for (buffer, ranges) in new_selections_by_buffer.into_iter() {
 9447                    let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
 9448                    editor.update(cx, |editor, cx| {
 9449                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
 9450                            s.select_ranges(ranges);
 9451                        });
 9452                    });
 9453                }
 9454
 9455                pane.update(cx, |pane, _| pane.enable_history());
 9456            })
 9457        });
 9458    }
 9459
 9460    fn jump(
 9461        &mut self,
 9462        path: ProjectPath,
 9463        position: Point,
 9464        anchor: language::Anchor,
 9465        cx: &mut ViewContext<Self>,
 9466    ) {
 9467        let workspace = self.workspace();
 9468        cx.spawn(|_, mut cx| async move {
 9469            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
 9470            let editor = workspace.update(&mut cx, |workspace, cx| {
 9471                workspace.open_path(path, None, true, cx)
 9472            })?;
 9473            let editor = editor
 9474                .await?
 9475                .downcast::<Editor>()
 9476                .ok_or_else(|| anyhow!("opened item was not an editor"))?
 9477                .downgrade();
 9478            editor.update(&mut cx, |editor, cx| {
 9479                let buffer = editor
 9480                    .buffer()
 9481                    .read(cx)
 9482                    .as_singleton()
 9483                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
 9484                let buffer = buffer.read(cx);
 9485                let cursor = if buffer.can_resolve(&anchor) {
 9486                    language::ToPoint::to_point(&anchor, buffer)
 9487                } else {
 9488                    buffer.clip_point(position, Bias::Left)
 9489                };
 9490
 9491                let nav_history = editor.nav_history.take();
 9492                editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
 9493                    s.select_ranges([cursor..cursor]);
 9494                });
 9495                editor.nav_history = nav_history;
 9496
 9497                anyhow::Ok(())
 9498            })??;
 9499
 9500            anyhow::Ok(())
 9501        })
 9502        .detach_and_log_err(cx);
 9503    }
 9504
 9505    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
 9506        let snapshot = self.buffer.read(cx).read(cx);
 9507        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
 9508        Some(
 9509            ranges
 9510                .iter()
 9511                .map(move |range| {
 9512                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
 9513                })
 9514                .collect(),
 9515        )
 9516    }
 9517
 9518    fn selection_replacement_ranges(
 9519        &self,
 9520        range: Range<OffsetUtf16>,
 9521        cx: &AppContext,
 9522    ) -> Vec<Range<OffsetUtf16>> {
 9523        let selections = self.selections.all::<OffsetUtf16>(cx);
 9524        let newest_selection = selections
 9525            .iter()
 9526            .max_by_key(|selection| selection.id)
 9527            .unwrap();
 9528        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
 9529        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
 9530        let snapshot = self.buffer.read(cx).read(cx);
 9531        selections
 9532            .into_iter()
 9533            .map(|mut selection| {
 9534                selection.start.0 =
 9535                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
 9536                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
 9537                snapshot.clip_offset_utf16(selection.start, Bias::Left)
 9538                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
 9539            })
 9540            .collect()
 9541    }
 9542
 9543    fn report_copilot_event(
 9544        &self,
 9545        suggestion_id: Option<String>,
 9546        suggestion_accepted: bool,
 9547        cx: &AppContext,
 9548    ) {
 9549        let Some(project) = &self.project else { return };
 9550
 9551        // If None, we are either getting suggestions in a new, unsaved file, or in a file without an extension
 9552        let file_extension = self
 9553            .buffer
 9554            .read(cx)
 9555            .as_singleton()
 9556            .and_then(|b| b.read(cx).file())
 9557            .and_then(|file| Path::new(file.file_name(cx)).extension())
 9558            .and_then(|e| e.to_str())
 9559            .map(|a| a.to_string());
 9560
 9561        let telemetry = project.read(cx).client().telemetry().clone();
 9562
 9563        telemetry.report_copilot_event(suggestion_id, suggestion_accepted, file_extension)
 9564    }
 9565
 9566    #[cfg(any(test, feature = "test-support"))]
 9567    fn report_editor_event(
 9568        &self,
 9569        _operation: &'static str,
 9570        _file_extension: Option<String>,
 9571        _cx: &AppContext,
 9572    ) {
 9573    }
 9574
 9575    #[cfg(not(any(test, feature = "test-support")))]
 9576    fn report_editor_event(
 9577        &self,
 9578        operation: &'static str,
 9579        file_extension: Option<String>,
 9580        cx: &AppContext,
 9581    ) {
 9582        let Some(project) = &self.project else { return };
 9583
 9584        // If None, we are in a file without an extension
 9585        let file = self
 9586            .buffer
 9587            .read(cx)
 9588            .as_singleton()
 9589            .and_then(|b| b.read(cx).file());
 9590        let file_extension = file_extension.or(file
 9591            .as_ref()
 9592            .and_then(|file| Path::new(file.file_name(cx)).extension())
 9593            .and_then(|e| e.to_str())
 9594            .map(|a| a.to_string()));
 9595
 9596        let vim_mode = cx
 9597            .global::<SettingsStore>()
 9598            .raw_user_settings()
 9599            .get("vim_mode")
 9600            == Some(&serde_json::Value::Bool(true));
 9601        let copilot_enabled = all_language_settings(file, cx).copilot_enabled(None, None);
 9602        let copilot_enabled_for_language = self
 9603            .buffer
 9604            .read(cx)
 9605            .settings_at(0, cx)
 9606            .show_copilot_suggestions;
 9607
 9608        let telemetry = project.read(cx).client().telemetry().clone();
 9609        telemetry.report_editor_event(
 9610            file_extension,
 9611            vim_mode,
 9612            operation,
 9613            copilot_enabled,
 9614            copilot_enabled_for_language,
 9615        )
 9616    }
 9617
 9618    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
 9619    /// with each line being an array of {text, highlight} objects.
 9620    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
 9621        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
 9622            return;
 9623        };
 9624
 9625        #[derive(Serialize)]
 9626        struct Chunk<'a> {
 9627            text: String,
 9628            highlight: Option<&'a str>,
 9629        }
 9630
 9631        let snapshot = buffer.read(cx).snapshot();
 9632        let range = self
 9633            .selected_text_range(cx)
 9634            .and_then(|selected_range| {
 9635                if selected_range.is_empty() {
 9636                    None
 9637                } else {
 9638                    Some(selected_range)
 9639                }
 9640            })
 9641            .unwrap_or_else(|| 0..snapshot.len());
 9642
 9643        let chunks = snapshot.chunks(range, true);
 9644        let mut lines = Vec::new();
 9645        let mut line: VecDeque<Chunk> = VecDeque::new();
 9646
 9647        let Some(style) = self.style.as_ref() else {
 9648            return;
 9649        };
 9650
 9651        for chunk in chunks {
 9652            let highlight = chunk
 9653                .syntax_highlight_id
 9654                .and_then(|id| id.name(&style.syntax));
 9655            let mut chunk_lines = chunk.text.split('\n').peekable();
 9656            while let Some(text) = chunk_lines.next() {
 9657                let mut merged_with_last_token = false;
 9658                if let Some(last_token) = line.back_mut() {
 9659                    if last_token.highlight == highlight {
 9660                        last_token.text.push_str(text);
 9661                        merged_with_last_token = true;
 9662                    }
 9663                }
 9664
 9665                if !merged_with_last_token {
 9666                    line.push_back(Chunk {
 9667                        text: text.into(),
 9668                        highlight,
 9669                    });
 9670                }
 9671
 9672                if chunk_lines.peek().is_some() {
 9673                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
 9674                        line.pop_front();
 9675                    }
 9676                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
 9677                        line.pop_back();
 9678                    }
 9679
 9680                    lines.push(mem::take(&mut line));
 9681                }
 9682            }
 9683        }
 9684
 9685        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
 9686            return;
 9687        };
 9688        cx.write_to_clipboard(ClipboardItem::new(lines));
 9689    }
 9690
 9691    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
 9692        &self.inlay_hint_cache
 9693    }
 9694
 9695    pub fn replay_insert_event(
 9696        &mut self,
 9697        text: &str,
 9698        relative_utf16_range: Option<Range<isize>>,
 9699        cx: &mut ViewContext<Self>,
 9700    ) {
 9701        if !self.input_enabled {
 9702            cx.emit(EditorEvent::InputIgnored { text: text.into() });
 9703            return;
 9704        }
 9705        if let Some(relative_utf16_range) = relative_utf16_range {
 9706            let selections = self.selections.all::<OffsetUtf16>(cx);
 9707            self.change_selections(None, cx, |s| {
 9708                let new_ranges = selections.into_iter().map(|range| {
 9709                    let start = OffsetUtf16(
 9710                        range
 9711                            .head()
 9712                            .0
 9713                            .saturating_add_signed(relative_utf16_range.start),
 9714                    );
 9715                    let end = OffsetUtf16(
 9716                        range
 9717                            .head()
 9718                            .0
 9719                            .saturating_add_signed(relative_utf16_range.end),
 9720                    );
 9721                    start..end
 9722                });
 9723                s.select_ranges(new_ranges);
 9724            });
 9725        }
 9726
 9727        self.handle_input(text, cx);
 9728    }
 9729
 9730    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
 9731        let Some(project) = self.project.as_ref() else {
 9732            return false;
 9733        };
 9734        let project = project.read(cx);
 9735
 9736        let mut supports = false;
 9737        self.buffer().read(cx).for_each_buffer(|buffer| {
 9738            if !supports {
 9739                supports = project
 9740                    .language_servers_for_buffer(buffer.read(cx), cx)
 9741                    .any(
 9742                        |(_, server)| match server.capabilities().inlay_hint_provider {
 9743                            Some(lsp::OneOf::Left(enabled)) => enabled,
 9744                            Some(lsp::OneOf::Right(_)) => true,
 9745                            None => false,
 9746                        },
 9747                    )
 9748            }
 9749        });
 9750        supports
 9751    }
 9752
 9753    pub fn focus(&self, cx: &mut WindowContext) {
 9754        cx.focus(&self.focus_handle)
 9755    }
 9756
 9757    pub fn is_focused(&self, cx: &WindowContext) -> bool {
 9758        self.focus_handle.is_focused(cx)
 9759    }
 9760
 9761    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
 9762        cx.emit(EditorEvent::Focused);
 9763
 9764        if let Some(rename) = self.pending_rename.as_ref() {
 9765            let rename_editor_focus_handle = rename.editor.read(cx).focus_handle.clone();
 9766            cx.focus(&rename_editor_focus_handle);
 9767        } else {
 9768            self.blink_manager.update(cx, BlinkManager::enable);
 9769            self.show_cursor_names(cx);
 9770            self.buffer.update(cx, |buffer, cx| {
 9771                buffer.finalize_last_transaction(cx);
 9772                if self.leader_peer_id.is_none() {
 9773                    buffer.set_active_selections(
 9774                        &self.selections.disjoint_anchors(),
 9775                        self.selections.line_mode,
 9776                        self.cursor_shape,
 9777                        cx,
 9778                    );
 9779                }
 9780            });
 9781        }
 9782    }
 9783
 9784    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
 9785        self.blink_manager.update(cx, BlinkManager::disable);
 9786        self.buffer
 9787            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
 9788        self.hide_context_menu(cx);
 9789        hide_hover(self, cx);
 9790        cx.emit(EditorEvent::Blurred);
 9791        cx.notify();
 9792    }
 9793
 9794    pub fn register_action<A: Action>(
 9795        &mut self,
 9796        listener: impl Fn(&A, &mut WindowContext) + 'static,
 9797    ) -> &mut Self {
 9798        let listener = Arc::new(listener);
 9799
 9800        self.editor_actions.push(Box::new(move |cx| {
 9801            let _view = cx.view().clone();
 9802            let cx = cx.window_context();
 9803            let listener = listener.clone();
 9804            cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
 9805                let action = action.downcast_ref().unwrap();
 9806                if phase == DispatchPhase::Bubble {
 9807                    listener(action, cx)
 9808                }
 9809            })
 9810        }));
 9811        self
 9812    }
 9813}
 9814
 9815pub trait CollaborationHub {
 9816    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
 9817    fn user_participant_indices<'a>(
 9818        &self,
 9819        cx: &'a AppContext,
 9820    ) -> &'a HashMap<u64, ParticipantIndex>;
 9821    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
 9822}
 9823
 9824impl CollaborationHub for Model<Project> {
 9825    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
 9826        self.read(cx).collaborators()
 9827    }
 9828
 9829    fn user_participant_indices<'a>(
 9830        &self,
 9831        cx: &'a AppContext,
 9832    ) -> &'a HashMap<u64, ParticipantIndex> {
 9833        self.read(cx).user_store().read(cx).participant_indices()
 9834    }
 9835
 9836    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
 9837        let this = self.read(cx);
 9838        let user_ids = this.collaborators().values().map(|c| c.user_id);
 9839        this.user_store().read_with(cx, |user_store, cx| {
 9840            user_store.participant_names(user_ids, cx)
 9841        })
 9842    }
 9843}
 9844
 9845pub trait CompletionProvider {
 9846    fn completions(
 9847        &self,
 9848        buffer: &Model<Buffer>,
 9849        buffer_position: text::Anchor,
 9850        cx: &mut ViewContext<Editor>,
 9851    ) -> Task<Result<Vec<Completion>>>;
 9852
 9853    fn resolve_completions(
 9854        &self,
 9855        completion_indices: Vec<usize>,
 9856        completions: Arc<RwLock<Box<[Completion]>>>,
 9857        cx: &mut ViewContext<Editor>,
 9858    ) -> Task<Result<bool>>;
 9859
 9860    fn apply_additional_edits_for_completion(
 9861        &self,
 9862        buffer: Model<Buffer>,
 9863        completion: Completion,
 9864        push_to_history: bool,
 9865        cx: &mut ViewContext<Editor>,
 9866    ) -> Task<Result<Option<language::Transaction>>>;
 9867}
 9868
 9869impl CompletionProvider for Model<Project> {
 9870    fn completions(
 9871        &self,
 9872        buffer: &Model<Buffer>,
 9873        buffer_position: text::Anchor,
 9874        cx: &mut ViewContext<Editor>,
 9875    ) -> Task<Result<Vec<Completion>>> {
 9876        self.update(cx, |project, cx| {
 9877            project.completions(&buffer, buffer_position, cx)
 9878        })
 9879    }
 9880
 9881    fn resolve_completions(
 9882        &self,
 9883        completion_indices: Vec<usize>,
 9884        completions: Arc<RwLock<Box<[Completion]>>>,
 9885        cx: &mut ViewContext<Editor>,
 9886    ) -> Task<Result<bool>> {
 9887        self.update(cx, |project, cx| {
 9888            project.resolve_completions(completion_indices, completions, cx)
 9889        })
 9890    }
 9891
 9892    fn apply_additional_edits_for_completion(
 9893        &self,
 9894        buffer: Model<Buffer>,
 9895        completion: Completion,
 9896        push_to_history: bool,
 9897        cx: &mut ViewContext<Editor>,
 9898    ) -> Task<Result<Option<language::Transaction>>> {
 9899        self.update(cx, |project, cx| {
 9900            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
 9901        })
 9902    }
 9903}
 9904
 9905fn inlay_hint_settings(
 9906    location: Anchor,
 9907    snapshot: &MultiBufferSnapshot,
 9908    cx: &mut ViewContext<'_, Editor>,
 9909) -> InlayHintSettings {
 9910    let file = snapshot.file_at(location);
 9911    let language = snapshot.language_at(location);
 9912    let settings = all_language_settings(file, cx);
 9913    settings
 9914        .language(language.map(|l| l.name()).as_deref())
 9915        .inlay_hints
 9916}
 9917
 9918fn consume_contiguous_rows(
 9919    contiguous_row_selections: &mut Vec<Selection<Point>>,
 9920    selection: &Selection<Point>,
 9921    display_map: &DisplaySnapshot,
 9922    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
 9923) -> (u32, u32) {
 9924    contiguous_row_selections.push(selection.clone());
 9925    let start_row = selection.start.row;
 9926    let mut end_row = ending_row(selection, display_map);
 9927
 9928    while let Some(next_selection) = selections.peek() {
 9929        if next_selection.start.row <= end_row {
 9930            end_row = ending_row(next_selection, display_map);
 9931            contiguous_row_selections.push(selections.next().unwrap().clone());
 9932        } else {
 9933            break;
 9934        }
 9935    }
 9936    (start_row, end_row)
 9937}
 9938
 9939fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> u32 {
 9940    if next_selection.end.column > 0 || next_selection.is_empty() {
 9941        display_map.next_line_boundary(next_selection.end).0.row + 1
 9942    } else {
 9943        next_selection.end.row
 9944    }
 9945}
 9946
 9947impl EditorSnapshot {
 9948    pub fn remote_selections_in_range<'a>(
 9949        &'a self,
 9950        range: &'a Range<Anchor>,
 9951        collaboration_hub: &dyn CollaborationHub,
 9952        cx: &'a AppContext,
 9953    ) -> impl 'a + Iterator<Item = RemoteSelection> {
 9954        let participant_names = collaboration_hub.user_names(cx);
 9955        let participant_indices = collaboration_hub.user_participant_indices(cx);
 9956        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
 9957        let collaborators_by_replica_id = collaborators_by_peer_id
 9958            .iter()
 9959            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
 9960            .collect::<HashMap<_, _>>();
 9961        self.buffer_snapshot
 9962            .remote_selections_in_range(range)
 9963            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
 9964                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
 9965                let participant_index = participant_indices.get(&collaborator.user_id).copied();
 9966                let user_name = participant_names.get(&collaborator.user_id).cloned();
 9967                Some(RemoteSelection {
 9968                    replica_id,
 9969                    selection,
 9970                    cursor_shape,
 9971                    line_mode,
 9972                    participant_index,
 9973                    peer_id: collaborator.peer_id,
 9974                    user_name,
 9975                })
 9976            })
 9977    }
 9978
 9979    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
 9980        self.display_snapshot.buffer_snapshot.language_at(position)
 9981    }
 9982
 9983    pub fn is_focused(&self) -> bool {
 9984        self.is_focused
 9985    }
 9986
 9987    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
 9988        self.placeholder_text.as_ref()
 9989    }
 9990
 9991    pub fn scroll_position(&self) -> gpui::Point<f32> {
 9992        self.scroll_anchor.scroll_position(&self.display_snapshot)
 9993    }
 9994
 9995    pub fn gutter_dimensions(
 9996        &self,
 9997        font_id: FontId,
 9998        font_size: Pixels,
 9999        em_width: Pixels,
10000        max_line_number_width: Pixels,
10001        cx: &AppContext,
10002    ) -> GutterDimensions {
10003        if !self.show_gutter {
10004            return GutterDimensions::default();
10005        }
10006        let descent = cx.text_system().descent(font_id, font_size);
10007
10008        let show_git_gutter = matches!(
10009            ProjectSettings::get_global(cx).git.git_gutter,
10010            Some(GitGutterSetting::TrackedFiles)
10011        );
10012        let gutter_settings = EditorSettings::get_global(cx).gutter;
10013
10014        let line_gutter_width = if gutter_settings.line_numbers {
10015            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
10016            let min_width_for_number_on_gutter = em_width * 4.0;
10017            max_line_number_width.max(min_width_for_number_on_gutter)
10018        } else {
10019            0.0.into()
10020        };
10021
10022        let left_padding = if gutter_settings.code_actions {
10023            em_width * 3.0
10024        } else if show_git_gutter && gutter_settings.line_numbers {
10025            em_width * 2.0
10026        } else if show_git_gutter || gutter_settings.line_numbers {
10027            em_width
10028        } else {
10029            px(0.)
10030        };
10031
10032        let right_padding = if gutter_settings.folds && gutter_settings.line_numbers {
10033            em_width * 4.0
10034        } else if gutter_settings.folds {
10035            em_width * 3.0
10036        } else if gutter_settings.line_numbers {
10037            em_width
10038        } else {
10039            px(0.)
10040        };
10041
10042        GutterDimensions {
10043            left_padding,
10044            right_padding,
10045            width: line_gutter_width + left_padding + right_padding,
10046            margin: -descent,
10047        }
10048    }
10049}
10050
10051impl Deref for EditorSnapshot {
10052    type Target = DisplaySnapshot;
10053
10054    fn deref(&self) -> &Self::Target {
10055        &self.display_snapshot
10056    }
10057}
10058
10059#[derive(Clone, Debug, PartialEq, Eq)]
10060pub enum EditorEvent {
10061    InputIgnored {
10062        text: Arc<str>,
10063    },
10064    InputHandled {
10065        utf16_range_to_replace: Option<Range<isize>>,
10066        text: Arc<str>,
10067    },
10068    ExcerptsAdded {
10069        buffer: Model<Buffer>,
10070        predecessor: ExcerptId,
10071        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
10072    },
10073    ExcerptsRemoved {
10074        ids: Vec<ExcerptId>,
10075    },
10076    BufferEdited,
10077    Edited,
10078    Reparsed,
10079    Focused,
10080    Blurred,
10081    DirtyChanged,
10082    Saved,
10083    TitleChanged,
10084    DiffBaseChanged,
10085    SelectionsChanged {
10086        local: bool,
10087    },
10088    ScrollPositionChanged {
10089        local: bool,
10090        autoscroll: bool,
10091    },
10092    Closed,
10093}
10094
10095impl EventEmitter<EditorEvent> for Editor {}
10096
10097impl FocusableView for Editor {
10098    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
10099        self.focus_handle.clone()
10100    }
10101}
10102
10103impl Render for Editor {
10104    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
10105        let settings = ThemeSettings::get_global(cx);
10106        let text_style = match self.mode {
10107            EditorMode::SingleLine | EditorMode::AutoHeight { .. } => TextStyle {
10108                color: cx.theme().colors().editor_foreground,
10109                font_family: settings.ui_font.family.clone(),
10110                font_features: settings.ui_font.features,
10111                font_size: rems(0.875).into(),
10112                font_weight: FontWeight::NORMAL,
10113                font_style: FontStyle::Normal,
10114                line_height: relative(settings.buffer_line_height.value()),
10115                background_color: None,
10116                underline: None,
10117                strikethrough: None,
10118                white_space: WhiteSpace::Normal,
10119            },
10120
10121            EditorMode::Full => TextStyle {
10122                color: cx.theme().colors().editor_foreground,
10123                font_family: settings.buffer_font.family.clone(),
10124                font_features: settings.buffer_font.features,
10125                font_size: settings.buffer_font_size(cx).into(),
10126                font_weight: FontWeight::NORMAL,
10127                font_style: FontStyle::Normal,
10128                line_height: relative(settings.buffer_line_height.value()),
10129                background_color: None,
10130                underline: None,
10131                strikethrough: None,
10132                white_space: WhiteSpace::Normal,
10133            },
10134        };
10135
10136        let background = match self.mode {
10137            EditorMode::SingleLine => cx.theme().system().transparent,
10138            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
10139            EditorMode::Full => cx.theme().colors().editor_background,
10140        };
10141
10142        EditorElement::new(
10143            cx.view(),
10144            EditorStyle {
10145                background,
10146                local_player: cx.theme().players().local(),
10147                text: text_style,
10148                scrollbar_width: px(12.),
10149                syntax: cx.theme().syntax().clone(),
10150                status: cx.theme().status().clone(),
10151                inlay_hints_style: HighlightStyle {
10152                    color: Some(cx.theme().status().hint),
10153                    ..HighlightStyle::default()
10154                },
10155                suggestions_style: HighlightStyle {
10156                    color: Some(cx.theme().status().predictive),
10157                    ..HighlightStyle::default()
10158                },
10159            },
10160        )
10161    }
10162}
10163
10164impl ViewInputHandler for Editor {
10165    fn text_for_range(
10166        &mut self,
10167        range_utf16: Range<usize>,
10168        cx: &mut ViewContext<Self>,
10169    ) -> Option<String> {
10170        Some(
10171            self.buffer
10172                .read(cx)
10173                .read(cx)
10174                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
10175                .collect(),
10176        )
10177    }
10178
10179    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
10180        // Prevent the IME menu from appearing when holding down an alphabetic key
10181        // while input is disabled.
10182        if !self.input_enabled {
10183            return None;
10184        }
10185
10186        let range = self.selections.newest::<OffsetUtf16>(cx).range();
10187        Some(range.start.0..range.end.0)
10188    }
10189
10190    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
10191        let snapshot = self.buffer.read(cx).read(cx);
10192        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
10193        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
10194    }
10195
10196    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
10197        self.clear_highlights::<InputComposition>(cx);
10198        self.ime_transaction.take();
10199    }
10200
10201    fn replace_text_in_range(
10202        &mut self,
10203        range_utf16: Option<Range<usize>>,
10204        text: &str,
10205        cx: &mut ViewContext<Self>,
10206    ) {
10207        if !self.input_enabled {
10208            cx.emit(EditorEvent::InputIgnored { text: text.into() });
10209            return;
10210        }
10211
10212        self.transact(cx, |this, cx| {
10213            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
10214                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
10215                Some(this.selection_replacement_ranges(range_utf16, cx))
10216            } else {
10217                this.marked_text_ranges(cx)
10218            };
10219
10220            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
10221                let newest_selection_id = this.selections.newest_anchor().id;
10222                this.selections
10223                    .all::<OffsetUtf16>(cx)
10224                    .iter()
10225                    .zip(ranges_to_replace.iter())
10226                    .find_map(|(selection, range)| {
10227                        if selection.id == newest_selection_id {
10228                            Some(
10229                                (range.start.0 as isize - selection.head().0 as isize)
10230                                    ..(range.end.0 as isize - selection.head().0 as isize),
10231                            )
10232                        } else {
10233                            None
10234                        }
10235                    })
10236            });
10237
10238            cx.emit(EditorEvent::InputHandled {
10239                utf16_range_to_replace: range_to_replace,
10240                text: text.into(),
10241            });
10242
10243            if let Some(new_selected_ranges) = new_selected_ranges {
10244                this.change_selections(None, cx, |selections| {
10245                    selections.select_ranges(new_selected_ranges)
10246                });
10247                this.backspace(&Default::default(), cx);
10248            }
10249
10250            this.handle_input(text, cx);
10251        });
10252
10253        if let Some(transaction) = self.ime_transaction {
10254            self.buffer.update(cx, |buffer, cx| {
10255                buffer.group_until_transaction(transaction, cx);
10256            });
10257        }
10258
10259        self.unmark_text(cx);
10260    }
10261
10262    fn replace_and_mark_text_in_range(
10263        &mut self,
10264        range_utf16: Option<Range<usize>>,
10265        text: &str,
10266        new_selected_range_utf16: Option<Range<usize>>,
10267        cx: &mut ViewContext<Self>,
10268    ) {
10269        if !self.input_enabled {
10270            cx.emit(EditorEvent::InputIgnored { text: text.into() });
10271            return;
10272        }
10273
10274        let transaction = self.transact(cx, |this, cx| {
10275            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
10276                let snapshot = this.buffer.read(cx).read(cx);
10277                if let Some(relative_range_utf16) = range_utf16.as_ref() {
10278                    for marked_range in &mut marked_ranges {
10279                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
10280                        marked_range.start.0 += relative_range_utf16.start;
10281                        marked_range.start =
10282                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
10283                        marked_range.end =
10284                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
10285                    }
10286                }
10287                Some(marked_ranges)
10288            } else if let Some(range_utf16) = range_utf16 {
10289                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
10290                Some(this.selection_replacement_ranges(range_utf16, cx))
10291            } else {
10292                None
10293            };
10294
10295            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
10296                let newest_selection_id = this.selections.newest_anchor().id;
10297                this.selections
10298                    .all::<OffsetUtf16>(cx)
10299                    .iter()
10300                    .zip(ranges_to_replace.iter())
10301                    .find_map(|(selection, range)| {
10302                        if selection.id == newest_selection_id {
10303                            Some(
10304                                (range.start.0 as isize - selection.head().0 as isize)
10305                                    ..(range.end.0 as isize - selection.head().0 as isize),
10306                            )
10307                        } else {
10308                            None
10309                        }
10310                    })
10311            });
10312
10313            cx.emit(EditorEvent::InputHandled {
10314                utf16_range_to_replace: range_to_replace,
10315                text: text.into(),
10316            });
10317
10318            if let Some(ranges) = ranges_to_replace {
10319                this.change_selections(None, cx, |s| s.select_ranges(ranges));
10320            }
10321
10322            let marked_ranges = {
10323                let snapshot = this.buffer.read(cx).read(cx);
10324                this.selections
10325                    .disjoint_anchors()
10326                    .iter()
10327                    .map(|selection| {
10328                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
10329                    })
10330                    .collect::<Vec<_>>()
10331            };
10332
10333            if text.is_empty() {
10334                this.unmark_text(cx);
10335            } else {
10336                this.highlight_text::<InputComposition>(
10337                    marked_ranges.clone(),
10338                    HighlightStyle {
10339                        underline: Some(UnderlineStyle {
10340                            thickness: px(1.),
10341                            color: None,
10342                            wavy: false,
10343                        }),
10344                        ..Default::default()
10345                    },
10346                    cx,
10347                );
10348            }
10349
10350            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
10351            let use_autoclose = this.use_autoclose;
10352            this.set_use_autoclose(false);
10353            this.handle_input(text, cx);
10354            this.set_use_autoclose(use_autoclose);
10355
10356            if let Some(new_selected_range) = new_selected_range_utf16 {
10357                let snapshot = this.buffer.read(cx).read(cx);
10358                let new_selected_ranges = marked_ranges
10359                    .into_iter()
10360                    .map(|marked_range| {
10361                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
10362                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
10363                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
10364                        snapshot.clip_offset_utf16(new_start, Bias::Left)
10365                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
10366                    })
10367                    .collect::<Vec<_>>();
10368
10369                drop(snapshot);
10370                this.change_selections(None, cx, |selections| {
10371                    selections.select_ranges(new_selected_ranges)
10372                });
10373            }
10374        });
10375
10376        self.ime_transaction = self.ime_transaction.or(transaction);
10377        if let Some(transaction) = self.ime_transaction {
10378            self.buffer.update(cx, |buffer, cx| {
10379                buffer.group_until_transaction(transaction, cx);
10380            });
10381        }
10382
10383        if self.text_highlights::<InputComposition>(cx).is_none() {
10384            self.ime_transaction.take();
10385        }
10386    }
10387
10388    fn bounds_for_range(
10389        &mut self,
10390        range_utf16: Range<usize>,
10391        element_bounds: gpui::Bounds<Pixels>,
10392        cx: &mut ViewContext<Self>,
10393    ) -> Option<gpui::Bounds<Pixels>> {
10394        let text_layout_details = self.text_layout_details(cx);
10395        let style = &text_layout_details.editor_style;
10396        let font_id = cx.text_system().resolve_font(&style.text.font());
10397        let font_size = style.text.font_size.to_pixels(cx.rem_size());
10398        let line_height = style.text.line_height_in_pixels(cx.rem_size());
10399        let em_width = cx
10400            .text_system()
10401            .typographic_bounds(font_id, font_size, 'm')
10402            .unwrap()
10403            .size
10404            .width;
10405
10406        let snapshot = self.snapshot(cx);
10407        let scroll_position = snapshot.scroll_position();
10408        let scroll_left = scroll_position.x * em_width;
10409
10410        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
10411        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
10412            + self.gutter_width;
10413        let y = line_height * (start.row() as f32 - scroll_position.y);
10414
10415        Some(Bounds {
10416            origin: element_bounds.origin + point(x, y),
10417            size: size(em_width, line_height),
10418        })
10419    }
10420}
10421
10422trait SelectionExt {
10423    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize>;
10424    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point>;
10425    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
10426    fn spanned_rows(&self, include_end_if_at_line_start: bool, map: &DisplaySnapshot)
10427        -> Range<u32>;
10428}
10429
10430impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
10431    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
10432        let start = self.start.to_point(buffer);
10433        let end = self.end.to_point(buffer);
10434        if self.reversed {
10435            end..start
10436        } else {
10437            start..end
10438        }
10439    }
10440
10441    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
10442        let start = self.start.to_offset(buffer);
10443        let end = self.end.to_offset(buffer);
10444        if self.reversed {
10445            end..start
10446        } else {
10447            start..end
10448        }
10449    }
10450
10451    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
10452        let start = self
10453            .start
10454            .to_point(&map.buffer_snapshot)
10455            .to_display_point(map);
10456        let end = self
10457            .end
10458            .to_point(&map.buffer_snapshot)
10459            .to_display_point(map);
10460        if self.reversed {
10461            end..start
10462        } else {
10463            start..end
10464        }
10465    }
10466
10467    fn spanned_rows(
10468        &self,
10469        include_end_if_at_line_start: bool,
10470        map: &DisplaySnapshot,
10471    ) -> Range<u32> {
10472        let start = self.start.to_point(&map.buffer_snapshot);
10473        let mut end = self.end.to_point(&map.buffer_snapshot);
10474        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
10475            end.row -= 1;
10476        }
10477
10478        let buffer_start = map.prev_line_boundary(start).0;
10479        let buffer_end = map.next_line_boundary(end).0;
10480        buffer_start.row..buffer_end.row + 1
10481    }
10482}
10483
10484impl<T: InvalidationRegion> InvalidationStack<T> {
10485    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
10486    where
10487        S: Clone + ToOffset,
10488    {
10489        while let Some(region) = self.last() {
10490            let all_selections_inside_invalidation_ranges =
10491                if selections.len() == region.ranges().len() {
10492                    selections
10493                        .iter()
10494                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
10495                        .all(|(selection, invalidation_range)| {
10496                            let head = selection.head().to_offset(buffer);
10497                            invalidation_range.start <= head && invalidation_range.end >= head
10498                        })
10499                } else {
10500                    false
10501                };
10502
10503            if all_selections_inside_invalidation_ranges {
10504                break;
10505            } else {
10506                self.pop();
10507            }
10508        }
10509    }
10510}
10511
10512impl<T> Default for InvalidationStack<T> {
10513    fn default() -> Self {
10514        Self(Default::default())
10515    }
10516}
10517
10518impl<T> Deref for InvalidationStack<T> {
10519    type Target = Vec<T>;
10520
10521    fn deref(&self) -> &Self::Target {
10522        &self.0
10523    }
10524}
10525
10526impl<T> DerefMut for InvalidationStack<T> {
10527    fn deref_mut(&mut self) -> &mut Self::Target {
10528        &mut self.0
10529    }
10530}
10531
10532impl InvalidationRegion for SnippetState {
10533    fn ranges(&self) -> &[Range<Anchor>] {
10534        &self.ranges[self.active_index]
10535    }
10536}
10537
10538pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
10539    let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
10540
10541    Arc::new(move |cx: &mut BlockContext| {
10542        let group_id: SharedString = cx.block_id.to_string().into();
10543
10544        let mut text_style = cx.text_style().clone();
10545        text_style.color = diagnostic_style(diagnostic.severity, true, cx.theme().status());
10546
10547        h_flex()
10548            .id(cx.block_id)
10549            .group(group_id.clone())
10550            .relative()
10551            .size_full()
10552            .pl(cx.gutter_dimensions.width)
10553            .w(cx.max_width + cx.gutter_dimensions.width)
10554            .child(
10555                div()
10556                    .flex()
10557                    .w(cx.anchor_x - cx.gutter_dimensions.width)
10558                    .flex_shrink(),
10559            )
10560            .child(div().flex().flex_shrink_0().child(
10561                StyledText::new(text_without_backticks.clone()).with_highlights(
10562                    &text_style,
10563                    code_ranges.iter().map(|range| {
10564                        (
10565                            range.clone(),
10566                            HighlightStyle {
10567                                font_weight: Some(FontWeight::BOLD),
10568                                ..Default::default()
10569                            },
10570                        )
10571                    }),
10572                ),
10573            ))
10574            .child(
10575                IconButton::new(("copy-block", cx.block_id), IconName::Copy)
10576                    .icon_color(Color::Muted)
10577                    .size(ButtonSize::Compact)
10578                    .style(ButtonStyle::Transparent)
10579                    .visible_on_hover(group_id)
10580                    .on_click({
10581                        let message = diagnostic.message.clone();
10582                        move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
10583                    })
10584                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
10585            )
10586            .into_any_element()
10587    })
10588}
10589
10590pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
10591    let mut text_without_backticks = String::new();
10592    let mut code_ranges = Vec::new();
10593
10594    if let Some(source) = &diagnostic.source {
10595        text_without_backticks.push_str(&source);
10596        code_ranges.push(0..source.len());
10597        text_without_backticks.push_str(": ");
10598    }
10599
10600    let mut prev_offset = 0;
10601    let mut in_code_block = false;
10602    for (ix, _) in diagnostic
10603        .message
10604        .match_indices('`')
10605        .chain([(diagnostic.message.len(), "")])
10606    {
10607        let prev_len = text_without_backticks.len();
10608        text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
10609        prev_offset = ix + 1;
10610        if in_code_block {
10611            code_ranges.push(prev_len..text_without_backticks.len());
10612            in_code_block = false;
10613        } else {
10614            in_code_block = true;
10615        }
10616    }
10617
10618    (text_without_backticks.into(), code_ranges)
10619}
10620
10621fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, colors: &StatusColors) -> Hsla {
10622    match (severity, valid) {
10623        (DiagnosticSeverity::ERROR, true) => colors.error,
10624        (DiagnosticSeverity::ERROR, false) => colors.error,
10625        (DiagnosticSeverity::WARNING, true) => colors.warning,
10626        (DiagnosticSeverity::WARNING, false) => colors.warning,
10627        (DiagnosticSeverity::INFORMATION, true) => colors.info,
10628        (DiagnosticSeverity::INFORMATION, false) => colors.info,
10629        (DiagnosticSeverity::HINT, true) => colors.info,
10630        (DiagnosticSeverity::HINT, false) => colors.info,
10631        _ => colors.ignored,
10632    }
10633}
10634
10635pub fn styled_runs_for_code_label<'a>(
10636    label: &'a CodeLabel,
10637    syntax_theme: &'a theme::SyntaxTheme,
10638) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
10639    let fade_out = HighlightStyle {
10640        fade_out: Some(0.35),
10641        ..Default::default()
10642    };
10643
10644    let mut prev_end = label.filter_range.end;
10645    label
10646        .runs
10647        .iter()
10648        .enumerate()
10649        .flat_map(move |(ix, (range, highlight_id))| {
10650            let style = if let Some(style) = highlight_id.style(syntax_theme) {
10651                style
10652            } else {
10653                return Default::default();
10654            };
10655            let mut muted_style = style;
10656            muted_style.highlight(fade_out);
10657
10658            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
10659            if range.start >= label.filter_range.end {
10660                if range.start > prev_end {
10661                    runs.push((prev_end..range.start, fade_out));
10662                }
10663                runs.push((range.clone(), muted_style));
10664            } else if range.end <= label.filter_range.end {
10665                runs.push((range.clone(), style));
10666            } else {
10667                runs.push((range.start..label.filter_range.end, style));
10668                runs.push((label.filter_range.end..range.end, muted_style));
10669            }
10670            prev_end = cmp::max(prev_end, range.end);
10671
10672            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
10673                runs.push((prev_end..label.text.len(), fade_out));
10674            }
10675
10676            runs
10677        })
10678}
10679
10680pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
10681    let mut index = 0;
10682    let mut codepoints = text.char_indices().peekable();
10683
10684    std::iter::from_fn(move || {
10685        let start_index = index;
10686        while let Some((new_index, codepoint)) = codepoints.next() {
10687            index = new_index + codepoint.len_utf8();
10688            let current_upper = codepoint.is_uppercase();
10689            let next_upper = codepoints
10690                .peek()
10691                .map(|(_, c)| c.is_uppercase())
10692                .unwrap_or(false);
10693
10694            if !current_upper && next_upper {
10695                return Some(&text[start_index..index]);
10696            }
10697        }
10698
10699        index = text.len();
10700        if start_index < text.len() {
10701            return Some(&text[start_index..]);
10702        }
10703        None
10704    })
10705    .flat_map(|word| word.split_inclusive('_'))
10706    .flat_map(|word| word.split_inclusive('-'))
10707}
10708
10709trait RangeToAnchorExt {
10710    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
10711}
10712
10713impl<T: ToOffset> RangeToAnchorExt for Range<T> {
10714    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
10715        snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
10716    }
10717}