editor.rs

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