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