editor.rs

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