editor.rs

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