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