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