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