editor.rs

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