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;
   18mod debounced_delay;
   19pub mod display_map;
   20mod editor_settings;
   21mod element;
   22mod git;
   23mod highlight_matching_bracket;
   24mod hover_links;
   25mod hover_popover;
   26mod hunk_diff;
   27mod indent_guides;
   28mod inlay_hint_cache;
   29mod inline_completion_provider;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod mouse_context_menu;
   33pub mod movement;
   34mod persistence;
   35mod rust_analyzer_ext;
   36pub mod scroll;
   37mod selections_collection;
   38pub mod tasks;
   39
   40#[cfg(test)]
   41mod editor_tests;
   42#[cfg(any(test, feature = "test-support"))]
   43pub mod test;
   44use ::git::diff::{DiffHunk, DiffHunkStatus};
   45use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
   46pub(crate) use actions::*;
   47use aho_corasick::AhoCorasick;
   48use anyhow::{anyhow, Context as _, Result};
   49use blink_manager::BlinkManager;
   50use client::{Collaborator, ParticipantIndex};
   51use clock::ReplicaId;
   52use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   53use convert_case::{Case, Casing};
   54use debounced_delay::DebouncedDelay;
   55use display_map::*;
   56pub use display_map::{DisplayPoint, FoldPlaceholder};
   57pub use editor_settings::{CurrentLineHighlight, EditorSettings};
   58use element::LineWithInvisibles;
   59pub use element::{
   60    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   61};
   62use futures::FutureExt;
   63use fuzzy::{StringMatch, StringMatchCandidate};
   64use git::blame::GitBlame;
   65use git::diff_hunk_to_display;
   66use gpui::{
   67    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   68    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardItem,
   69    Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView,
   70    FontId, FontStyle, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext,
   71    ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString,
   72    Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle, UnderlineStyle,
   73    UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
   74    WeakView, WhiteSpace, WindowContext,
   75};
   76use highlight_matching_bracket::refresh_matching_bracket_highlights;
   77use hover_popover::{hide_hover, HoverState};
   78use hunk_diff::ExpandedHunks;
   79pub(crate) use hunk_diff::HunkToExpand;
   80use indent_guides::ActiveIndentGuidesState;
   81use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   82pub use inline_completion_provider::*;
   83pub use items::MAX_TAB_TITLE_LEN;
   84use itertools::Itertools;
   85use language::{
   86    char_kind,
   87    language_settings::{self, all_language_settings, InlayHintSettings},
   88    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   89    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   90    Point, Selection, SelectionGoal, TransactionId,
   91};
   92use language::{BufferRow, Runnable, RunnableRange};
   93use linked_editing_ranges::refresh_linked_ranges;
   94use task::{ResolvedTask, TaskTemplate, TaskVariables};
   95
   96use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
   97pub use lsp::CompletionContext;
   98use lsp::{CompletionTriggerKind, DiagnosticSeverity, LanguageServerId};
   99use mouse_context_menu::MouseContextMenu;
  100use movement::TextLayoutDetails;
  101pub use multi_buffer::{
  102    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  103    ToPoint,
  104};
  105use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
  106use ordered_float::OrderedFloat;
  107use parking_lot::{Mutex, RwLock};
  108use project::project_settings::{GitGutterSetting, ProjectSettings};
  109use project::{
  110    CodeAction, Completion, FormatTrigger, Item, Location, Project, ProjectPath,
  111    ProjectTransaction, TaskSourceKind, WorktreeId,
  112};
  113use rand::prelude::*;
  114use rpc::{proto::*, ErrorExt};
  115use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  116use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  117use serde::{Deserialize, Serialize};
  118use settings::{update_settings_file, Settings, SettingsStore};
  119use smallvec::SmallVec;
  120use snippet::Snippet;
  121use std::{
  122    any::TypeId,
  123    borrow::Cow,
  124    cell::RefCell,
  125    cmp::{self, Ordering, Reverse},
  126    mem,
  127    num::NonZeroU32,
  128    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  129    path::Path,
  130    rc::Rc,
  131    sync::Arc,
  132    time::{Duration, Instant},
  133};
  134pub use sum_tree::Bias;
  135use sum_tree::TreeMap;
  136use text::{BufferId, OffsetUtf16, Rope};
  137use theme::{
  138    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  139    ThemeColors, ThemeSettings,
  140};
  141use ui::{
  142    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  143    ListItem, Popover, Tooltip,
  144};
  145use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  146use workspace::item::{ItemHandle, PreviewTabsSettings};
  147use workspace::notifications::{DetachAndPromptErr, NotificationId};
  148use workspace::{
  149    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  150};
  151use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  152
  153use crate::hover_links::find_url;
  154
  155pub const FILE_HEADER_HEIGHT: u8 = 1;
  156pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u8 = 1;
  157pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u8 = 1;
  158pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  159const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  160const MAX_LINE_LEN: usize = 1024;
  161const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  162const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  163pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  164#[doc(hidden)]
  165pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  166#[doc(hidden)]
  167pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  168
  169pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  170
  171pub fn render_parsed_markdown(
  172    element_id: impl Into<ElementId>,
  173    parsed: &language::ParsedMarkdown,
  174    editor_style: &EditorStyle,
  175    workspace: Option<WeakView<Workspace>>,
  176    cx: &mut WindowContext,
  177) -> InteractiveText {
  178    let code_span_background_color = cx
  179        .theme()
  180        .colors()
  181        .editor_document_highlight_read_background;
  182
  183    let highlights = gpui::combine_highlights(
  184        parsed.highlights.iter().filter_map(|(range, highlight)| {
  185            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  186            Some((range.clone(), highlight))
  187        }),
  188        parsed
  189            .regions
  190            .iter()
  191            .zip(&parsed.region_ranges)
  192            .filter_map(|(region, range)| {
  193                if region.code {
  194                    Some((
  195                        range.clone(),
  196                        HighlightStyle {
  197                            background_color: Some(code_span_background_color),
  198                            ..Default::default()
  199                        },
  200                    ))
  201                } else {
  202                    None
  203                }
  204            }),
  205    );
  206
  207    let mut links = Vec::new();
  208    let mut link_ranges = Vec::new();
  209    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  210        if let Some(link) = region.link.clone() {
  211            links.push(link);
  212            link_ranges.push(range.clone());
  213        }
  214    }
  215
  216    InteractiveText::new(
  217        element_id,
  218        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  219    )
  220    .on_click(link_ranges, move |clicked_range_ix, cx| {
  221        match &links[clicked_range_ix] {
  222            markdown::Link::Web { url } => cx.open_url(url),
  223            markdown::Link::Path { path } => {
  224                if let Some(workspace) = &workspace {
  225                    _ = workspace.update(cx, |workspace, cx| {
  226                        workspace.open_abs_path(path.clone(), false, cx).detach();
  227                    });
  228                }
  229            }
  230        }
  231    })
  232}
  233
  234#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  235pub(crate) enum InlayId {
  236    Suggestion(usize),
  237    Hint(usize),
  238}
  239
  240impl InlayId {
  241    fn id(&self) -> usize {
  242        match self {
  243            Self::Suggestion(id) => *id,
  244            Self::Hint(id) => *id,
  245        }
  246    }
  247}
  248
  249enum DiffRowHighlight {}
  250enum DocumentHighlightRead {}
  251enum DocumentHighlightWrite {}
  252enum InputComposition {}
  253
  254#[derive(Copy, Clone, PartialEq, Eq)]
  255pub enum Direction {
  256    Prev,
  257    Next,
  258}
  259
  260pub fn init_settings(cx: &mut AppContext) {
  261    EditorSettings::register(cx);
  262}
  263
  264pub fn init(cx: &mut AppContext) {
  265    init_settings(cx);
  266
  267    workspace::register_project_item::<Editor>(cx);
  268    workspace::register_followable_item::<Editor>(cx);
  269    workspace::register_deserializable_item::<Editor>(cx);
  270    cx.observe_new_views(
  271        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  272            workspace.register_action(Editor::new_file);
  273            workspace.register_action(Editor::new_file_in_direction);
  274        },
  275    )
  276    .detach();
  277
  278    cx.on_action(move |_: &workspace::NewFile, 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    cx.on_action(move |_: &workspace::NewWindow, cx| {
  288        let app_state = workspace::AppState::global(cx);
  289        if let Some(app_state) = app_state.upgrade() {
  290            workspace::open_new(app_state, cx, |workspace, cx| {
  291                Editor::new_file(workspace, &Default::default(), cx)
  292            })
  293            .detach();
  294        }
  295    });
  296}
  297
  298pub struct SearchWithinRange;
  299
  300trait InvalidationRegion {
  301    fn ranges(&self) -> &[Range<Anchor>];
  302}
  303
  304#[derive(Clone, Debug, PartialEq)]
  305pub enum SelectPhase {
  306    Begin {
  307        position: DisplayPoint,
  308        add: bool,
  309        click_count: usize,
  310    },
  311    BeginColumnar {
  312        position: DisplayPoint,
  313        reset: bool,
  314        goal_column: u32,
  315    },
  316    Extend {
  317        position: DisplayPoint,
  318        click_count: usize,
  319    },
  320    Update {
  321        position: DisplayPoint,
  322        goal_column: u32,
  323        scroll_delta: gpui::Point<f32>,
  324    },
  325    End,
  326}
  327
  328#[derive(Clone, Debug)]
  329pub enum SelectMode {
  330    Character,
  331    Word(Range<Anchor>),
  332    Line(Range<Anchor>),
  333    All,
  334}
  335
  336#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  337pub enum EditorMode {
  338    SingleLine { auto_width: bool },
  339    AutoHeight { max_lines: usize },
  340    Full,
  341}
  342
  343#[derive(Clone, Debug)]
  344pub enum SoftWrap {
  345    None,
  346    PreferLine,
  347    EditorWidth,
  348    Column(u32),
  349}
  350
  351#[derive(Clone)]
  352pub struct EditorStyle {
  353    pub background: Hsla,
  354    pub local_player: PlayerColor,
  355    pub text: TextStyle,
  356    pub scrollbar_width: Pixels,
  357    pub syntax: Arc<SyntaxTheme>,
  358    pub status: StatusColors,
  359    pub inlay_hints_style: HighlightStyle,
  360    pub suggestions_style: HighlightStyle,
  361}
  362
  363impl Default for EditorStyle {
  364    fn default() -> Self {
  365        Self {
  366            background: Hsla::default(),
  367            local_player: PlayerColor::default(),
  368            text: TextStyle::default(),
  369            scrollbar_width: Pixels::default(),
  370            syntax: Default::default(),
  371            // HACK: Status colors don't have a real default.
  372            // We should look into removing the status colors from the editor
  373            // style and retrieve them directly from the theme.
  374            status: StatusColors::dark(),
  375            inlay_hints_style: HighlightStyle::default(),
  376            suggestions_style: HighlightStyle::default(),
  377        }
  378    }
  379}
  380
  381type CompletionId = usize;
  382
  383#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  384struct EditorActionId(usize);
  385
  386impl EditorActionId {
  387    pub fn post_inc(&mut self) -> Self {
  388        let answer = self.0;
  389
  390        *self = Self(answer + 1);
  391
  392        Self(answer)
  393    }
  394}
  395
  396// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  397// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  398
  399type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  400type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  401
  402struct ScrollbarMarkerState {
  403    scrollbar_size: Size<Pixels>,
  404    dirty: bool,
  405    markers: Arc<[PaintQuad]>,
  406    pending_refresh: Option<Task<Result<()>>>,
  407}
  408
  409impl ScrollbarMarkerState {
  410    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  411        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  412    }
  413}
  414
  415impl Default for ScrollbarMarkerState {
  416    fn default() -> Self {
  417        Self {
  418            scrollbar_size: Size::default(),
  419            dirty: false,
  420            markers: Arc::from([]),
  421            pending_refresh: None,
  422        }
  423    }
  424}
  425
  426#[derive(Clone, Debug)]
  427struct RunnableTasks {
  428    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  429    offset: MultiBufferOffset,
  430    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  431    column: u32,
  432    // Values of all named captures, including those starting with '_'
  433    extra_variables: HashMap<String, String>,
  434    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  435    context_range: Range<BufferOffset>,
  436}
  437
  438#[derive(Clone)]
  439struct ResolvedTasks {
  440    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  441    position: Anchor,
  442}
  443#[derive(Copy, Clone, Debug)]
  444struct MultiBufferOffset(usize);
  445#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  446struct BufferOffset(usize);
  447/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  448///
  449/// See the [module level documentation](self) for more information.
  450pub struct Editor {
  451    focus_handle: FocusHandle,
  452    last_focused_descendant: Option<WeakFocusHandle>,
  453    /// The text buffer being edited
  454    buffer: Model<MultiBuffer>,
  455    /// Map of how text in the buffer should be displayed.
  456    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  457    pub display_map: Model<DisplayMap>,
  458    pub selections: SelectionsCollection,
  459    pub scroll_manager: ScrollManager,
  460    /// When inline assist editors are linked, they all render cursors because
  461    /// typing enters text into each of them, even the ones that aren't focused.
  462    pub(crate) show_cursor_when_unfocused: bool,
  463    columnar_selection_tail: Option<Anchor>,
  464    add_selections_state: Option<AddSelectionsState>,
  465    select_next_state: Option<SelectNextState>,
  466    select_prev_state: Option<SelectNextState>,
  467    selection_history: SelectionHistory,
  468    autoclose_regions: Vec<AutocloseRegion>,
  469    snippet_stack: InvalidationStack<SnippetState>,
  470    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  471    ime_transaction: Option<TransactionId>,
  472    active_diagnostics: Option<ActiveDiagnosticGroup>,
  473    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  474    project: Option<Model<Project>>,
  475    completion_provider: Option<Box<dyn CompletionProvider>>,
  476    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  477    blink_manager: Model<BlinkManager>,
  478    show_cursor_names: bool,
  479    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  480    pub show_local_selections: bool,
  481    mode: EditorMode,
  482    show_breadcrumbs: bool,
  483    show_gutter: bool,
  484    show_line_numbers: Option<bool>,
  485    show_git_diff_gutter: Option<bool>,
  486    show_code_actions: Option<bool>,
  487    show_runnables: Option<bool>,
  488    show_wrap_guides: Option<bool>,
  489    show_indent_guides: Option<bool>,
  490    placeholder_text: Option<Arc<str>>,
  491    highlight_order: usize,
  492    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  493    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  494    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  495    scrollbar_marker_state: ScrollbarMarkerState,
  496    active_indent_guides_state: ActiveIndentGuidesState,
  497    nav_history: Option<ItemNavHistory>,
  498    context_menu: RwLock<Option<ContextMenu>>,
  499    mouse_context_menu: Option<MouseContextMenu>,
  500    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  501    find_all_references_task_sources: Vec<Anchor>,
  502    next_completion_id: CompletionId,
  503    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  504    available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
  505    code_actions_task: Option<Task<()>>,
  506    document_highlights_task: Option<Task<()>>,
  507    linked_editing_range_task: Option<Task<Option<()>>>,
  508    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  509    pending_rename: Option<RenameState>,
  510    searchable: bool,
  511    cursor_shape: CursorShape,
  512    current_line_highlight: Option<CurrentLineHighlight>,
  513    collapse_matches: bool,
  514    autoindent_mode: Option<AutoindentMode>,
  515    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  516    keymap_context_layers: BTreeMap<TypeId, KeyContext>,
  517    input_enabled: bool,
  518    use_modal_editing: bool,
  519    read_only: bool,
  520    leader_peer_id: Option<PeerId>,
  521    remote_id: Option<ViewId>,
  522    hover_state: HoverState,
  523    gutter_hovered: bool,
  524    hovered_link_state: Option<HoveredLinkState>,
  525    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  526    active_inline_completion: Option<Inlay>,
  527    show_inline_completions: bool,
  528    inlay_hint_cache: InlayHintCache,
  529    expanded_hunks: ExpandedHunks,
  530    next_inlay_id: usize,
  531    _subscriptions: Vec<Subscription>,
  532    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  533    gutter_dimensions: GutterDimensions,
  534    pub vim_replace_map: HashMap<Range<usize>, String>,
  535    style: Option<EditorStyle>,
  536    next_editor_action_id: EditorActionId,
  537    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  538    use_autoclose: bool,
  539    use_auto_surround: bool,
  540    auto_replace_emoji_shortcode: bool,
  541    show_git_blame_gutter: bool,
  542    show_git_blame_inline: bool,
  543    show_git_blame_inline_delay_task: Option<Task<()>>,
  544    git_blame_inline_enabled: bool,
  545    show_selection_menu: Option<bool>,
  546    blame: Option<Model<GitBlame>>,
  547    blame_subscription: Option<Subscription>,
  548    custom_context_menu: Option<
  549        Box<
  550            dyn 'static
  551                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  552        >,
  553    >,
  554    last_bounds: Option<Bounds<Pixels>>,
  555    expect_bounds_change: Option<Bounds<Pixels>>,
  556    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  557    tasks_update_task: Option<Task<()>>,
  558    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  559    file_header_size: u8,
  560    breadcrumb_header: Option<String>,
  561}
  562
  563#[derive(Clone)]
  564pub struct EditorSnapshot {
  565    pub mode: EditorMode,
  566    show_gutter: bool,
  567    show_line_numbers: Option<bool>,
  568    show_git_diff_gutter: Option<bool>,
  569    show_code_actions: Option<bool>,
  570    show_runnables: Option<bool>,
  571    render_git_blame_gutter: bool,
  572    pub display_snapshot: DisplaySnapshot,
  573    pub placeholder_text: Option<Arc<str>>,
  574    is_focused: bool,
  575    scroll_anchor: ScrollAnchor,
  576    ongoing_scroll: OngoingScroll,
  577    current_line_highlight: CurrentLineHighlight,
  578    gutter_hovered: bool,
  579}
  580
  581const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
  582
  583#[derive(Debug, Clone, Copy)]
  584pub struct GutterDimensions {
  585    pub left_padding: Pixels,
  586    pub right_padding: Pixels,
  587    pub width: Pixels,
  588    pub margin: Pixels,
  589    pub git_blame_entries_width: Option<Pixels>,
  590}
  591
  592impl GutterDimensions {
  593    /// The full width of the space taken up by the gutter.
  594    pub fn full_width(&self) -> Pixels {
  595        self.margin + self.width
  596    }
  597
  598    /// The width of the space reserved for the fold indicators,
  599    /// use alongside 'justify_end' and `gutter_width` to
  600    /// right align content with the line numbers
  601    pub fn fold_area_width(&self) -> Pixels {
  602        self.margin + self.right_padding
  603    }
  604}
  605
  606impl Default for GutterDimensions {
  607    fn default() -> Self {
  608        Self {
  609            left_padding: Pixels::ZERO,
  610            right_padding: Pixels::ZERO,
  611            width: Pixels::ZERO,
  612            margin: Pixels::ZERO,
  613            git_blame_entries_width: None,
  614        }
  615    }
  616}
  617
  618#[derive(Debug)]
  619pub struct RemoteSelection {
  620    pub replica_id: ReplicaId,
  621    pub selection: Selection<Anchor>,
  622    pub cursor_shape: CursorShape,
  623    pub peer_id: PeerId,
  624    pub line_mode: bool,
  625    pub participant_index: Option<ParticipantIndex>,
  626    pub user_name: Option<SharedString>,
  627}
  628
  629#[derive(Clone, Debug)]
  630struct SelectionHistoryEntry {
  631    selections: Arc<[Selection<Anchor>]>,
  632    select_next_state: Option<SelectNextState>,
  633    select_prev_state: Option<SelectNextState>,
  634    add_selections_state: Option<AddSelectionsState>,
  635}
  636
  637enum SelectionHistoryMode {
  638    Normal,
  639    Undoing,
  640    Redoing,
  641}
  642
  643#[derive(Clone, PartialEq, Eq, Hash)]
  644struct HoveredCursor {
  645    replica_id: u16,
  646    selection_id: usize,
  647}
  648
  649impl Default for SelectionHistoryMode {
  650    fn default() -> Self {
  651        Self::Normal
  652    }
  653}
  654
  655#[derive(Default)]
  656struct SelectionHistory {
  657    #[allow(clippy::type_complexity)]
  658    selections_by_transaction:
  659        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  660    mode: SelectionHistoryMode,
  661    undo_stack: VecDeque<SelectionHistoryEntry>,
  662    redo_stack: VecDeque<SelectionHistoryEntry>,
  663}
  664
  665impl SelectionHistory {
  666    fn insert_transaction(
  667        &mut self,
  668        transaction_id: TransactionId,
  669        selections: Arc<[Selection<Anchor>]>,
  670    ) {
  671        self.selections_by_transaction
  672            .insert(transaction_id, (selections, None));
  673    }
  674
  675    #[allow(clippy::type_complexity)]
  676    fn transaction(
  677        &self,
  678        transaction_id: TransactionId,
  679    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  680        self.selections_by_transaction.get(&transaction_id)
  681    }
  682
  683    #[allow(clippy::type_complexity)]
  684    fn transaction_mut(
  685        &mut self,
  686        transaction_id: TransactionId,
  687    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  688        self.selections_by_transaction.get_mut(&transaction_id)
  689    }
  690
  691    fn push(&mut self, entry: SelectionHistoryEntry) {
  692        if !entry.selections.is_empty() {
  693            match self.mode {
  694                SelectionHistoryMode::Normal => {
  695                    self.push_undo(entry);
  696                    self.redo_stack.clear();
  697                }
  698                SelectionHistoryMode::Undoing => self.push_redo(entry),
  699                SelectionHistoryMode::Redoing => self.push_undo(entry),
  700            }
  701        }
  702    }
  703
  704    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  705        if self
  706            .undo_stack
  707            .back()
  708            .map_or(true, |e| e.selections != entry.selections)
  709        {
  710            self.undo_stack.push_back(entry);
  711            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  712                self.undo_stack.pop_front();
  713            }
  714        }
  715    }
  716
  717    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  718        if self
  719            .redo_stack
  720            .back()
  721            .map_or(true, |e| e.selections != entry.selections)
  722        {
  723            self.redo_stack.push_back(entry);
  724            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  725                self.redo_stack.pop_front();
  726            }
  727        }
  728    }
  729}
  730
  731struct RowHighlight {
  732    index: usize,
  733    range: RangeInclusive<Anchor>,
  734    color: Option<Hsla>,
  735    should_autoscroll: bool,
  736}
  737
  738#[derive(Clone, Debug)]
  739struct AddSelectionsState {
  740    above: bool,
  741    stack: Vec<usize>,
  742}
  743
  744#[derive(Clone)]
  745struct SelectNextState {
  746    query: AhoCorasick,
  747    wordwise: bool,
  748    done: bool,
  749}
  750
  751impl std::fmt::Debug for SelectNextState {
  752    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  753        f.debug_struct(std::any::type_name::<Self>())
  754            .field("wordwise", &self.wordwise)
  755            .field("done", &self.done)
  756            .finish()
  757    }
  758}
  759
  760#[derive(Debug)]
  761struct AutocloseRegion {
  762    selection_id: usize,
  763    range: Range<Anchor>,
  764    pair: BracketPair,
  765}
  766
  767#[derive(Debug)]
  768struct SnippetState {
  769    ranges: Vec<Vec<Range<Anchor>>>,
  770    active_index: usize,
  771}
  772
  773#[doc(hidden)]
  774pub struct RenameState {
  775    pub range: Range<Anchor>,
  776    pub old_name: Arc<str>,
  777    pub editor: View<Editor>,
  778    block_id: BlockId,
  779}
  780
  781struct InvalidationStack<T>(Vec<T>);
  782
  783struct RegisteredInlineCompletionProvider {
  784    provider: Arc<dyn InlineCompletionProviderHandle>,
  785    _subscription: Subscription,
  786}
  787
  788enum ContextMenu {
  789    Completions(CompletionsMenu),
  790    CodeActions(CodeActionsMenu),
  791}
  792
  793impl ContextMenu {
  794    fn select_first(
  795        &mut self,
  796        project: Option<&Model<Project>>,
  797        cx: &mut ViewContext<Editor>,
  798    ) -> bool {
  799        if self.visible() {
  800            match self {
  801                ContextMenu::Completions(menu) => menu.select_first(project, cx),
  802                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  803            }
  804            true
  805        } else {
  806            false
  807        }
  808    }
  809
  810    fn select_prev(
  811        &mut self,
  812        project: Option<&Model<Project>>,
  813        cx: &mut ViewContext<Editor>,
  814    ) -> bool {
  815        if self.visible() {
  816            match self {
  817                ContextMenu::Completions(menu) => menu.select_prev(project, cx),
  818                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  819            }
  820            true
  821        } else {
  822            false
  823        }
  824    }
  825
  826    fn select_next(
  827        &mut self,
  828        project: Option<&Model<Project>>,
  829        cx: &mut ViewContext<Editor>,
  830    ) -> bool {
  831        if self.visible() {
  832            match self {
  833                ContextMenu::Completions(menu) => menu.select_next(project, cx),
  834                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  835            }
  836            true
  837        } else {
  838            false
  839        }
  840    }
  841
  842    fn select_last(
  843        &mut self,
  844        project: Option<&Model<Project>>,
  845        cx: &mut ViewContext<Editor>,
  846    ) -> bool {
  847        if self.visible() {
  848            match self {
  849                ContextMenu::Completions(menu) => menu.select_last(project, cx),
  850                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  851            }
  852            true
  853        } else {
  854            false
  855        }
  856    }
  857
  858    fn visible(&self) -> bool {
  859        match self {
  860            ContextMenu::Completions(menu) => menu.visible(),
  861            ContextMenu::CodeActions(menu) => menu.visible(),
  862        }
  863    }
  864
  865    fn render(
  866        &self,
  867        cursor_position: DisplayPoint,
  868        style: &EditorStyle,
  869        max_height: Pixels,
  870        workspace: Option<WeakView<Workspace>>,
  871        cx: &mut ViewContext<Editor>,
  872    ) -> (ContextMenuOrigin, AnyElement) {
  873        match self {
  874            ContextMenu::Completions(menu) => (
  875                ContextMenuOrigin::EditorPoint(cursor_position),
  876                menu.render(style, max_height, workspace, cx),
  877            ),
  878            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  879        }
  880    }
  881}
  882
  883enum ContextMenuOrigin {
  884    EditorPoint(DisplayPoint),
  885    GutterIndicator(DisplayRow),
  886}
  887
  888#[derive(Clone)]
  889struct CompletionsMenu {
  890    id: CompletionId,
  891    initial_position: Anchor,
  892    buffer: Model<Buffer>,
  893    completions: Arc<RwLock<Box<[Completion]>>>,
  894    match_candidates: Arc<[StringMatchCandidate]>,
  895    matches: Arc<[StringMatch]>,
  896    selected_item: usize,
  897    scroll_handle: UniformListScrollHandle,
  898    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  899}
  900
  901impl CompletionsMenu {
  902    fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  903        self.selected_item = 0;
  904        self.scroll_handle.scroll_to_item(self.selected_item);
  905        self.attempt_resolve_selected_completion_documentation(project, cx);
  906        cx.notify();
  907    }
  908
  909    fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  910        if self.selected_item > 0 {
  911            self.selected_item -= 1;
  912        } else {
  913            self.selected_item = self.matches.len() - 1;
  914        }
  915        self.scroll_handle.scroll_to_item(self.selected_item);
  916        self.attempt_resolve_selected_completion_documentation(project, cx);
  917        cx.notify();
  918    }
  919
  920    fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  921        if self.selected_item + 1 < self.matches.len() {
  922            self.selected_item += 1;
  923        } else {
  924            self.selected_item = 0;
  925        }
  926        self.scroll_handle.scroll_to_item(self.selected_item);
  927        self.attempt_resolve_selected_completion_documentation(project, cx);
  928        cx.notify();
  929    }
  930
  931    fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  932        self.selected_item = self.matches.len() - 1;
  933        self.scroll_handle.scroll_to_item(self.selected_item);
  934        self.attempt_resolve_selected_completion_documentation(project, cx);
  935        cx.notify();
  936    }
  937
  938    fn pre_resolve_completion_documentation(
  939        buffer: Model<Buffer>,
  940        completions: Arc<RwLock<Box<[Completion]>>>,
  941        matches: Arc<[StringMatch]>,
  942        editor: &Editor,
  943        cx: &mut ViewContext<Editor>,
  944    ) -> Task<()> {
  945        let settings = EditorSettings::get_global(cx);
  946        if !settings.show_completion_documentation {
  947            return Task::ready(());
  948        }
  949
  950        let Some(provider) = editor.completion_provider.as_ref() else {
  951            return Task::ready(());
  952        };
  953
  954        let resolve_task = provider.resolve_completions(
  955            buffer,
  956            matches.iter().map(|m| m.candidate_id).collect(),
  957            completions.clone(),
  958            cx,
  959        );
  960
  961        return cx.spawn(move |this, mut cx| async move {
  962            if let Some(true) = resolve_task.await.log_err() {
  963                this.update(&mut cx, |_, cx| cx.notify()).ok();
  964            }
  965        });
  966    }
  967
  968    fn attempt_resolve_selected_completion_documentation(
  969        &mut self,
  970        project: Option<&Model<Project>>,
  971        cx: &mut ViewContext<Editor>,
  972    ) {
  973        let settings = EditorSettings::get_global(cx);
  974        if !settings.show_completion_documentation {
  975            return;
  976        }
  977
  978        let completion_index = self.matches[self.selected_item].candidate_id;
  979        let Some(project) = project else {
  980            return;
  981        };
  982
  983        let resolve_task = project.update(cx, |project, cx| {
  984            project.resolve_completions(
  985                self.buffer.clone(),
  986                vec![completion_index],
  987                self.completions.clone(),
  988                cx,
  989            )
  990        });
  991
  992        let delay_ms =
  993            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
  994        let delay = Duration::from_millis(delay_ms);
  995
  996        self.selected_completion_documentation_resolve_debounce
  997            .lock()
  998            .fire_new(delay, cx, |_, cx| {
  999                cx.spawn(move |this, mut cx| async move {
 1000                    if let Some(true) = resolve_task.await.log_err() {
 1001                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1002                    }
 1003                })
 1004            });
 1005    }
 1006
 1007    fn visible(&self) -> bool {
 1008        !self.matches.is_empty()
 1009    }
 1010
 1011    fn render(
 1012        &self,
 1013        style: &EditorStyle,
 1014        max_height: Pixels,
 1015        workspace: Option<WeakView<Workspace>>,
 1016        cx: &mut ViewContext<Editor>,
 1017    ) -> AnyElement {
 1018        let settings = EditorSettings::get_global(cx);
 1019        let show_completion_documentation = settings.show_completion_documentation;
 1020
 1021        let widest_completion_ix = self
 1022            .matches
 1023            .iter()
 1024            .enumerate()
 1025            .max_by_key(|(_, mat)| {
 1026                let completions = self.completions.read();
 1027                let completion = &completions[mat.candidate_id];
 1028                let documentation = &completion.documentation;
 1029
 1030                let mut len = completion.label.text.chars().count();
 1031                if let Some(Documentation::SingleLine(text)) = documentation {
 1032                    if show_completion_documentation {
 1033                        len += text.chars().count();
 1034                    }
 1035                }
 1036
 1037                len
 1038            })
 1039            .map(|(ix, _)| ix);
 1040
 1041        let completions = self.completions.clone();
 1042        let matches = self.matches.clone();
 1043        let selected_item = self.selected_item;
 1044        let style = style.clone();
 1045
 1046        let multiline_docs = if show_completion_documentation {
 1047            let mat = &self.matches[selected_item];
 1048            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1049                Some(Documentation::MultiLinePlainText(text)) => {
 1050                    Some(div().child(SharedString::from(text.clone())))
 1051                }
 1052                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1053                    Some(div().child(render_parsed_markdown(
 1054                        "completions_markdown",
 1055                        parsed,
 1056                        &style,
 1057                        workspace,
 1058                        cx,
 1059                    )))
 1060                }
 1061                _ => None,
 1062            };
 1063            multiline_docs.map(|div| {
 1064                div.id("multiline_docs")
 1065                    .max_h(max_height)
 1066                    .flex_1()
 1067                    .px_1p5()
 1068                    .py_1()
 1069                    .min_w(px(260.))
 1070                    .max_w(px(640.))
 1071                    .w(px(500.))
 1072                    .overflow_y_scroll()
 1073                    .occlude()
 1074            })
 1075        } else {
 1076            None
 1077        };
 1078
 1079        let list = uniform_list(
 1080            cx.view().clone(),
 1081            "completions",
 1082            matches.len(),
 1083            move |_editor, range, cx| {
 1084                let start_ix = range.start;
 1085                let completions_guard = completions.read();
 1086
 1087                matches[range]
 1088                    .iter()
 1089                    .enumerate()
 1090                    .map(|(ix, mat)| {
 1091                        let item_ix = start_ix + ix;
 1092                        let candidate_id = mat.candidate_id;
 1093                        let completion = &completions_guard[candidate_id];
 1094
 1095                        let documentation = if show_completion_documentation {
 1096                            &completion.documentation
 1097                        } else {
 1098                            &None
 1099                        };
 1100
 1101                        let highlights = gpui::combine_highlights(
 1102                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1103                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1104                                |(range, mut highlight)| {
 1105                                    // Ignore font weight for syntax highlighting, as we'll use it
 1106                                    // for fuzzy matches.
 1107                                    highlight.font_weight = None;
 1108
 1109                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1110                                        highlight.strikethrough = Some(StrikethroughStyle {
 1111                                            thickness: 1.0.into(),
 1112                                            ..Default::default()
 1113                                        });
 1114                                        highlight.color = Some(cx.theme().colors().text_muted);
 1115                                    }
 1116
 1117                                    (range, highlight)
 1118                                },
 1119                            ),
 1120                        );
 1121                        let completion_label = StyledText::new(completion.label.text.clone())
 1122                            .with_highlights(&style.text, highlights);
 1123                        let documentation_label =
 1124                            if let Some(Documentation::SingleLine(text)) = documentation {
 1125                                if text.trim().is_empty() {
 1126                                    None
 1127                                } else {
 1128                                    Some(
 1129                                        h_flex().ml_4().child(
 1130                                            Label::new(text.clone())
 1131                                                .size(LabelSize::Small)
 1132                                                .color(Color::Muted),
 1133                                        ),
 1134                                    )
 1135                                }
 1136                            } else {
 1137                                None
 1138                            };
 1139
 1140                        div().min_w(px(220.)).max_w(px(540.)).child(
 1141                            ListItem::new(mat.candidate_id)
 1142                                .inset(true)
 1143                                .selected(item_ix == selected_item)
 1144                                .on_click(cx.listener(move |editor, _event, cx| {
 1145                                    cx.stop_propagation();
 1146                                    if let Some(task) = editor.confirm_completion(
 1147                                        &ConfirmCompletion {
 1148                                            item_ix: Some(item_ix),
 1149                                        },
 1150                                        cx,
 1151                                    ) {
 1152                                        task.detach_and_log_err(cx)
 1153                                    }
 1154                                }))
 1155                                .child(h_flex().overflow_hidden().child(completion_label))
 1156                                .end_slot::<Div>(documentation_label),
 1157                        )
 1158                    })
 1159                    .collect()
 1160            },
 1161        )
 1162        .occlude()
 1163        .max_h(max_height)
 1164        .track_scroll(self.scroll_handle.clone())
 1165        .with_width_from_item(widest_completion_ix)
 1166        .with_sizing_behavior(ListSizingBehavior::Infer);
 1167
 1168        Popover::new()
 1169            .child(list)
 1170            .when_some(multiline_docs, |popover, multiline_docs| {
 1171                popover.aside(multiline_docs)
 1172            })
 1173            .into_any_element()
 1174    }
 1175
 1176    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1177        let mut matches = if let Some(query) = query {
 1178            fuzzy::match_strings(
 1179                &self.match_candidates,
 1180                query,
 1181                query.chars().any(|c| c.is_uppercase()),
 1182                100,
 1183                &Default::default(),
 1184                executor,
 1185            )
 1186            .await
 1187        } else {
 1188            self.match_candidates
 1189                .iter()
 1190                .enumerate()
 1191                .map(|(candidate_id, candidate)| StringMatch {
 1192                    candidate_id,
 1193                    score: Default::default(),
 1194                    positions: Default::default(),
 1195                    string: candidate.string.clone(),
 1196                })
 1197                .collect()
 1198        };
 1199
 1200        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1201        if let Some(query) = query {
 1202            if let Some(query_start) = query.chars().next() {
 1203                matches.retain(|string_match| {
 1204                    split_words(&string_match.string).any(|word| {
 1205                        // Check that the first codepoint of the word as lowercase matches the first
 1206                        // codepoint of the query as lowercase
 1207                        word.chars()
 1208                            .flat_map(|codepoint| codepoint.to_lowercase())
 1209                            .zip(query_start.to_lowercase())
 1210                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1211                    })
 1212                });
 1213            }
 1214        }
 1215
 1216        let completions = self.completions.read();
 1217        matches.sort_unstable_by_key(|mat| {
 1218            // We do want to strike a balance here between what the language server tells us
 1219            // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1220            // `Creat` and there is a local variable called `CreateComponent`).
 1221            // So what we do is: we bucket all matches into two buckets
 1222            // - Strong matches
 1223            // - Weak matches
 1224            // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1225            // and the Weak matches are the rest.
 1226            //
 1227            // For the strong matches, we sort by the language-servers score first and for the weak
 1228            // matches, we prefer our fuzzy finder first.
 1229            //
 1230            // The thinking behind that: it's useless to take the sort_text the language-server gives
 1231            // us into account when it's obviously a bad match.
 1232
 1233            #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1234            enum MatchScore<'a> {
 1235                Strong {
 1236                    sort_text: Option<&'a str>,
 1237                    score: Reverse<OrderedFloat<f64>>,
 1238                    sort_key: (usize, &'a str),
 1239                },
 1240                Weak {
 1241                    score: Reverse<OrderedFloat<f64>>,
 1242                    sort_text: Option<&'a str>,
 1243                    sort_key: (usize, &'a str),
 1244                },
 1245            }
 1246
 1247            let completion = &completions[mat.candidate_id];
 1248            let sort_key = completion.sort_key();
 1249            let sort_text = completion.lsp_completion.sort_text.as_deref();
 1250            let score = Reverse(OrderedFloat(mat.score));
 1251
 1252            if mat.score >= 0.2 {
 1253                MatchScore::Strong {
 1254                    sort_text,
 1255                    score,
 1256                    sort_key,
 1257                }
 1258            } else {
 1259                MatchScore::Weak {
 1260                    score,
 1261                    sort_text,
 1262                    sort_key,
 1263                }
 1264            }
 1265        });
 1266
 1267        for mat in &mut matches {
 1268            let completion = &completions[mat.candidate_id];
 1269            mat.string.clone_from(&completion.label.text);
 1270            for position in &mut mat.positions {
 1271                *position += completion.label.filter_range.start;
 1272            }
 1273        }
 1274        drop(completions);
 1275
 1276        self.matches = matches.into();
 1277        self.selected_item = 0;
 1278    }
 1279}
 1280
 1281#[derive(Clone)]
 1282struct CodeActionContents {
 1283    tasks: Option<Arc<ResolvedTasks>>,
 1284    actions: Option<Arc<[CodeAction]>>,
 1285}
 1286
 1287impl CodeActionContents {
 1288    fn len(&self) -> usize {
 1289        match (&self.tasks, &self.actions) {
 1290            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1291            (Some(tasks), None) => tasks.templates.len(),
 1292            (None, Some(actions)) => actions.len(),
 1293            (None, None) => 0,
 1294        }
 1295    }
 1296
 1297    fn is_empty(&self) -> bool {
 1298        match (&self.tasks, &self.actions) {
 1299            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1300            (Some(tasks), None) => tasks.templates.is_empty(),
 1301            (None, Some(actions)) => actions.is_empty(),
 1302            (None, None) => true,
 1303        }
 1304    }
 1305
 1306    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1307        self.tasks
 1308            .iter()
 1309            .flat_map(|tasks| {
 1310                tasks
 1311                    .templates
 1312                    .iter()
 1313                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1314            })
 1315            .chain(self.actions.iter().flat_map(|actions| {
 1316                actions
 1317                    .iter()
 1318                    .map(|action| CodeActionsItem::CodeAction(action.clone()))
 1319            }))
 1320    }
 1321    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1322        match (&self.tasks, &self.actions) {
 1323            (Some(tasks), Some(actions)) => {
 1324                if index < tasks.templates.len() {
 1325                    tasks
 1326                        .templates
 1327                        .get(index)
 1328                        .cloned()
 1329                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1330                } else {
 1331                    actions
 1332                        .get(index - tasks.templates.len())
 1333                        .cloned()
 1334                        .map(CodeActionsItem::CodeAction)
 1335                }
 1336            }
 1337            (Some(tasks), None) => tasks
 1338                .templates
 1339                .get(index)
 1340                .cloned()
 1341                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1342            (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
 1343            (None, None) => None,
 1344        }
 1345    }
 1346}
 1347
 1348#[allow(clippy::large_enum_variant)]
 1349#[derive(Clone)]
 1350enum CodeActionsItem {
 1351    Task(TaskSourceKind, ResolvedTask),
 1352    CodeAction(CodeAction),
 1353}
 1354
 1355impl CodeActionsItem {
 1356    fn as_task(&self) -> Option<&ResolvedTask> {
 1357        let Self::Task(_, task) = self else {
 1358            return None;
 1359        };
 1360        Some(task)
 1361    }
 1362    fn as_code_action(&self) -> Option<&CodeAction> {
 1363        let Self::CodeAction(action) = self else {
 1364            return None;
 1365        };
 1366        Some(action)
 1367    }
 1368    fn label(&self) -> String {
 1369        match self {
 1370            Self::CodeAction(action) => action.lsp_action.title.clone(),
 1371            Self::Task(_, task) => task.resolved_label.clone(),
 1372        }
 1373    }
 1374}
 1375
 1376struct CodeActionsMenu {
 1377    actions: CodeActionContents,
 1378    buffer: Model<Buffer>,
 1379    selected_item: usize,
 1380    scroll_handle: UniformListScrollHandle,
 1381    deployed_from_indicator: Option<DisplayRow>,
 1382}
 1383
 1384impl CodeActionsMenu {
 1385    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1386        self.selected_item = 0;
 1387        self.scroll_handle.scroll_to_item(self.selected_item);
 1388        cx.notify()
 1389    }
 1390
 1391    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1392        if self.selected_item > 0 {
 1393            self.selected_item -= 1;
 1394        } else {
 1395            self.selected_item = self.actions.len() - 1;
 1396        }
 1397        self.scroll_handle.scroll_to_item(self.selected_item);
 1398        cx.notify();
 1399    }
 1400
 1401    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1402        if self.selected_item + 1 < self.actions.len() {
 1403            self.selected_item += 1;
 1404        } else {
 1405            self.selected_item = 0;
 1406        }
 1407        self.scroll_handle.scroll_to_item(self.selected_item);
 1408        cx.notify();
 1409    }
 1410
 1411    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1412        self.selected_item = self.actions.len() - 1;
 1413        self.scroll_handle.scroll_to_item(self.selected_item);
 1414        cx.notify()
 1415    }
 1416
 1417    fn visible(&self) -> bool {
 1418        !self.actions.is_empty()
 1419    }
 1420
 1421    fn render(
 1422        &self,
 1423        cursor_position: DisplayPoint,
 1424        _style: &EditorStyle,
 1425        max_height: Pixels,
 1426        cx: &mut ViewContext<Editor>,
 1427    ) -> (ContextMenuOrigin, AnyElement) {
 1428        let actions = self.actions.clone();
 1429        let selected_item = self.selected_item;
 1430        let element = uniform_list(
 1431            cx.view().clone(),
 1432            "code_actions_menu",
 1433            self.actions.len(),
 1434            move |_this, range, cx| {
 1435                actions
 1436                    .iter()
 1437                    .skip(range.start)
 1438                    .take(range.end - range.start)
 1439                    .enumerate()
 1440                    .map(|(ix, action)| {
 1441                        let item_ix = range.start + ix;
 1442                        let selected = selected_item == item_ix;
 1443                        let colors = cx.theme().colors();
 1444                        div()
 1445                            .px_2()
 1446                            .text_color(colors.text)
 1447                            .when(selected, |style| {
 1448                                style
 1449                                    .bg(colors.element_active)
 1450                                    .text_color(colors.text_accent)
 1451                            })
 1452                            .hover(|style| {
 1453                                style
 1454                                    .bg(colors.element_hover)
 1455                                    .text_color(colors.text_accent)
 1456                            })
 1457                            .whitespace_nowrap()
 1458                            .when_some(action.as_code_action(), |this, action| {
 1459                                this.on_mouse_down(
 1460                                    MouseButton::Left,
 1461                                    cx.listener(move |editor, _, cx| {
 1462                                        cx.stop_propagation();
 1463                                        if let Some(task) = editor.confirm_code_action(
 1464                                            &ConfirmCodeAction {
 1465                                                item_ix: Some(item_ix),
 1466                                            },
 1467                                            cx,
 1468                                        ) {
 1469                                            task.detach_and_log_err(cx)
 1470                                        }
 1471                                    }),
 1472                                )
 1473                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1474                                .child(SharedString::from(action.lsp_action.title.clone()))
 1475                            })
 1476                            .when_some(action.as_task(), |this, task| {
 1477                                this.on_mouse_down(
 1478                                    MouseButton::Left,
 1479                                    cx.listener(move |editor, _, cx| {
 1480                                        cx.stop_propagation();
 1481                                        if let Some(task) = editor.confirm_code_action(
 1482                                            &ConfirmCodeAction {
 1483                                                item_ix: Some(item_ix),
 1484                                            },
 1485                                            cx,
 1486                                        ) {
 1487                                            task.detach_and_log_err(cx)
 1488                                        }
 1489                                    }),
 1490                                )
 1491                                .child(SharedString::from(task.resolved_label.clone()))
 1492                            })
 1493                    })
 1494                    .collect()
 1495            },
 1496        )
 1497        .elevation_1(cx)
 1498        .px_2()
 1499        .py_1()
 1500        .max_h(max_height)
 1501        .occlude()
 1502        .track_scroll(self.scroll_handle.clone())
 1503        .with_width_from_item(
 1504            self.actions
 1505                .iter()
 1506                .enumerate()
 1507                .max_by_key(|(_, action)| match action {
 1508                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1509                    CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
 1510                })
 1511                .map(|(ix, _)| ix),
 1512        )
 1513        .with_sizing_behavior(ListSizingBehavior::Infer)
 1514        .into_any_element();
 1515
 1516        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1517            ContextMenuOrigin::GutterIndicator(row)
 1518        } else {
 1519            ContextMenuOrigin::EditorPoint(cursor_position)
 1520        };
 1521
 1522        (cursor_position, element)
 1523    }
 1524}
 1525
 1526#[derive(Debug)]
 1527struct ActiveDiagnosticGroup {
 1528    primary_range: Range<Anchor>,
 1529    primary_message: String,
 1530    group_id: usize,
 1531    blocks: HashMap<BlockId, Diagnostic>,
 1532    is_valid: bool,
 1533}
 1534
 1535#[derive(Serialize, Deserialize, Clone, Debug)]
 1536pub struct ClipboardSelection {
 1537    pub len: usize,
 1538    pub is_entire_line: bool,
 1539    pub first_line_indent: u32,
 1540}
 1541
 1542#[derive(Debug)]
 1543pub(crate) struct NavigationData {
 1544    cursor_anchor: Anchor,
 1545    cursor_position: Point,
 1546    scroll_anchor: ScrollAnchor,
 1547    scroll_top_row: u32,
 1548}
 1549
 1550enum GotoDefinitionKind {
 1551    Symbol,
 1552    Type,
 1553    Implementation,
 1554}
 1555
 1556#[derive(Debug, Clone)]
 1557enum InlayHintRefreshReason {
 1558    Toggle(bool),
 1559    SettingsChange(InlayHintSettings),
 1560    NewLinesShown,
 1561    BufferEdited(HashSet<Arc<Language>>),
 1562    RefreshRequested,
 1563    ExcerptsRemoved(Vec<ExcerptId>),
 1564}
 1565
 1566impl InlayHintRefreshReason {
 1567    fn description(&self) -> &'static str {
 1568        match self {
 1569            Self::Toggle(_) => "toggle",
 1570            Self::SettingsChange(_) => "settings change",
 1571            Self::NewLinesShown => "new lines shown",
 1572            Self::BufferEdited(_) => "buffer edited",
 1573            Self::RefreshRequested => "refresh requested",
 1574            Self::ExcerptsRemoved(_) => "excerpts removed",
 1575        }
 1576    }
 1577}
 1578
 1579impl Editor {
 1580    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1581        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1582        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1583        Self::new(
 1584            EditorMode::SingleLine { auto_width: false },
 1585            buffer,
 1586            None,
 1587            false,
 1588            cx,
 1589        )
 1590    }
 1591
 1592    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1593        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1594        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1595        Self::new(EditorMode::Full, buffer, None, false, cx)
 1596    }
 1597
 1598    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1599        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1600        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1601        Self::new(
 1602            EditorMode::SingleLine { auto_width: true },
 1603            buffer,
 1604            None,
 1605            false,
 1606            cx,
 1607        )
 1608    }
 1609
 1610    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1611        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1612        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1613        Self::new(
 1614            EditorMode::AutoHeight { max_lines },
 1615            buffer,
 1616            None,
 1617            false,
 1618            cx,
 1619        )
 1620    }
 1621
 1622    pub fn for_buffer(
 1623        buffer: Model<Buffer>,
 1624        project: Option<Model<Project>>,
 1625        cx: &mut ViewContext<Self>,
 1626    ) -> Self {
 1627        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1628        Self::new(EditorMode::Full, buffer, project, false, cx)
 1629    }
 1630
 1631    pub fn for_multibuffer(
 1632        buffer: Model<MultiBuffer>,
 1633        project: Option<Model<Project>>,
 1634        show_excerpt_controls: bool,
 1635        cx: &mut ViewContext<Self>,
 1636    ) -> Self {
 1637        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1638    }
 1639
 1640    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1641        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1642        let mut clone = Self::new(
 1643            self.mode,
 1644            self.buffer.clone(),
 1645            self.project.clone(),
 1646            show_excerpt_controls,
 1647            cx,
 1648        );
 1649        self.display_map.update(cx, |display_map, cx| {
 1650            let snapshot = display_map.snapshot(cx);
 1651            clone.display_map.update(cx, |display_map, cx| {
 1652                display_map.set_state(&snapshot, cx);
 1653            });
 1654        });
 1655        clone.selections.clone_state(&self.selections);
 1656        clone.scroll_manager.clone_state(&self.scroll_manager);
 1657        clone.searchable = self.searchable;
 1658        clone
 1659    }
 1660
 1661    pub fn new(
 1662        mode: EditorMode,
 1663        buffer: Model<MultiBuffer>,
 1664        project: Option<Model<Project>>,
 1665        show_excerpt_controls: bool,
 1666        cx: &mut ViewContext<Self>,
 1667    ) -> Self {
 1668        let style = cx.text_style();
 1669        let font_size = style.font_size.to_pixels(cx.rem_size());
 1670        let editor = cx.view().downgrade();
 1671        let fold_placeholder = FoldPlaceholder {
 1672            constrain_width: true,
 1673            render: Arc::new(move |fold_id, fold_range, cx| {
 1674                let editor = editor.clone();
 1675                div()
 1676                    .id(fold_id)
 1677                    .bg(cx.theme().colors().ghost_element_background)
 1678                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1679                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1680                    .rounded_sm()
 1681                    .size_full()
 1682                    .cursor_pointer()
 1683                    .child("")
 1684                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1685                    .on_click(move |_, cx| {
 1686                        editor
 1687                            .update(cx, |editor, cx| {
 1688                                editor.unfold_ranges(
 1689                                    [fold_range.start..fold_range.end],
 1690                                    true,
 1691                                    false,
 1692                                    cx,
 1693                                );
 1694                                cx.stop_propagation();
 1695                            })
 1696                            .ok();
 1697                    })
 1698                    .into_any()
 1699            }),
 1700            merge_adjacent: true,
 1701        };
 1702        let file_header_size = if show_excerpt_controls { 3 } else { 2 };
 1703        let display_map = cx.new_model(|cx| {
 1704            DisplayMap::new(
 1705                buffer.clone(),
 1706                style.font(),
 1707                font_size,
 1708                None,
 1709                show_excerpt_controls,
 1710                file_header_size,
 1711                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1712                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1713                fold_placeholder,
 1714                cx,
 1715            )
 1716        });
 1717
 1718        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1719
 1720        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1721
 1722        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1723            .then(|| language_settings::SoftWrap::PreferLine);
 1724
 1725        let mut project_subscriptions = Vec::new();
 1726        if mode == EditorMode::Full {
 1727            if let Some(project) = project.as_ref() {
 1728                if buffer.read(cx).is_singleton() {
 1729                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1730                        cx.emit(EditorEvent::TitleChanged);
 1731                    }));
 1732                }
 1733                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1734                    if let project::Event::RefreshInlayHints = event {
 1735                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1736                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1737                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1738                            let focus_handle = editor.focus_handle(cx);
 1739                            if focus_handle.is_focused(cx) {
 1740                                let snapshot = buffer.read(cx).snapshot();
 1741                                for (range, snippet) in snippet_edits {
 1742                                    let editor_range =
 1743                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1744                                    editor
 1745                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1746                                        .ok();
 1747                                }
 1748                            }
 1749                        }
 1750                    }
 1751                }));
 1752                let task_inventory = project.read(cx).task_inventory().clone();
 1753                project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1754                    editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1755                }));
 1756            }
 1757        }
 1758
 1759        let inlay_hint_settings = inlay_hint_settings(
 1760            selections.newest_anchor().head(),
 1761            &buffer.read(cx).snapshot(cx),
 1762            cx,
 1763        );
 1764        let focus_handle = cx.focus_handle();
 1765        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1766        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1767            .detach();
 1768        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1769
 1770        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1771            Some(false)
 1772        } else {
 1773            None
 1774        };
 1775
 1776        let mut this = Self {
 1777            focus_handle,
 1778            show_cursor_when_unfocused: false,
 1779            last_focused_descendant: None,
 1780            buffer: buffer.clone(),
 1781            display_map: display_map.clone(),
 1782            selections,
 1783            scroll_manager: ScrollManager::new(cx),
 1784            columnar_selection_tail: None,
 1785            add_selections_state: None,
 1786            select_next_state: None,
 1787            select_prev_state: None,
 1788            selection_history: Default::default(),
 1789            autoclose_regions: Default::default(),
 1790            snippet_stack: Default::default(),
 1791            select_larger_syntax_node_stack: Vec::new(),
 1792            ime_transaction: Default::default(),
 1793            active_diagnostics: None,
 1794            soft_wrap_mode_override,
 1795            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1796            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1797            project,
 1798            blink_manager: blink_manager.clone(),
 1799            show_local_selections: true,
 1800            mode,
 1801            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1802            show_gutter: mode == EditorMode::Full,
 1803            show_line_numbers: None,
 1804            show_git_diff_gutter: None,
 1805            show_code_actions: None,
 1806            show_runnables: None,
 1807            show_wrap_guides: None,
 1808            show_indent_guides,
 1809            placeholder_text: None,
 1810            highlight_order: 0,
 1811            highlighted_rows: HashMap::default(),
 1812            background_highlights: Default::default(),
 1813            gutter_highlights: TreeMap::default(),
 1814            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1815            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1816            nav_history: None,
 1817            context_menu: RwLock::new(None),
 1818            mouse_context_menu: None,
 1819            completion_tasks: Default::default(),
 1820            find_all_references_task_sources: Vec::new(),
 1821            next_completion_id: 0,
 1822            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1823            next_inlay_id: 0,
 1824            available_code_actions: Default::default(),
 1825            code_actions_task: Default::default(),
 1826            document_highlights_task: Default::default(),
 1827            linked_editing_range_task: Default::default(),
 1828            pending_rename: Default::default(),
 1829            searchable: true,
 1830            cursor_shape: Default::default(),
 1831            current_line_highlight: None,
 1832            autoindent_mode: Some(AutoindentMode::EachLine),
 1833            collapse_matches: false,
 1834            workspace: None,
 1835            keymap_context_layers: Default::default(),
 1836            input_enabled: true,
 1837            use_modal_editing: mode == EditorMode::Full,
 1838            read_only: false,
 1839            use_autoclose: true,
 1840            use_auto_surround: true,
 1841            auto_replace_emoji_shortcode: false,
 1842            leader_peer_id: None,
 1843            remote_id: None,
 1844            hover_state: Default::default(),
 1845            hovered_link_state: Default::default(),
 1846            inline_completion_provider: None,
 1847            active_inline_completion: None,
 1848            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1849            expanded_hunks: ExpandedHunks::default(),
 1850            gutter_hovered: false,
 1851            pixel_position_of_newest_cursor: None,
 1852            last_bounds: None,
 1853            expect_bounds_change: None,
 1854            gutter_dimensions: GutterDimensions::default(),
 1855            style: None,
 1856            show_cursor_names: false,
 1857            hovered_cursors: Default::default(),
 1858            next_editor_action_id: EditorActionId::default(),
 1859            editor_actions: Rc::default(),
 1860            vim_replace_map: Default::default(),
 1861            show_inline_completions: mode == EditorMode::Full,
 1862            custom_context_menu: None,
 1863            show_git_blame_gutter: false,
 1864            show_git_blame_inline: false,
 1865            show_selection_menu: None,
 1866            show_git_blame_inline_delay_task: None,
 1867            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1868            blame: None,
 1869            blame_subscription: None,
 1870            file_header_size,
 1871            tasks: Default::default(),
 1872            _subscriptions: vec![
 1873                cx.observe(&buffer, Self::on_buffer_changed),
 1874                cx.subscribe(&buffer, Self::on_buffer_event),
 1875                cx.observe(&display_map, Self::on_display_map_changed),
 1876                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1877                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1878                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1879                cx.observe_window_activation(|editor, cx| {
 1880                    let active = cx.is_window_active();
 1881                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1882                        if active {
 1883                            blink_manager.enable(cx);
 1884                        } else {
 1885                            blink_manager.show_cursor(cx);
 1886                            blink_manager.disable(cx);
 1887                        }
 1888                    });
 1889                }),
 1890            ],
 1891            tasks_update_task: None,
 1892            linked_edit_ranges: Default::default(),
 1893            previous_search_ranges: None,
 1894            breadcrumb_header: None,
 1895        };
 1896        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1897        this._subscriptions.extend(project_subscriptions);
 1898
 1899        this.end_selection(cx);
 1900        this.scroll_manager.show_scrollbar(cx);
 1901
 1902        if mode == EditorMode::Full {
 1903            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1904            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1905
 1906            if this.git_blame_inline_enabled {
 1907                this.git_blame_inline_enabled = true;
 1908                this.start_git_blame_inline(false, cx);
 1909            }
 1910        }
 1911
 1912        this.report_editor_event("open", None, cx);
 1913        this
 1914    }
 1915
 1916    pub fn mouse_menu_is_focused(&self, cx: &mut WindowContext) -> bool {
 1917        self.mouse_context_menu
 1918            .as_ref()
 1919            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1920    }
 1921
 1922    fn key_context(&self, cx: &AppContext) -> KeyContext {
 1923        let mut key_context = KeyContext::new_with_defaults();
 1924        key_context.add("Editor");
 1925        let mode = match self.mode {
 1926            EditorMode::SingleLine { .. } => "single_line",
 1927            EditorMode::AutoHeight { .. } => "auto_height",
 1928            EditorMode::Full => "full",
 1929        };
 1930        key_context.set("mode", mode);
 1931        if self.pending_rename.is_some() {
 1932            key_context.add("renaming");
 1933        }
 1934        if self.context_menu_visible() {
 1935            match self.context_menu.read().as_ref() {
 1936                Some(ContextMenu::Completions(_)) => {
 1937                    key_context.add("menu");
 1938                    key_context.add("showing_completions")
 1939                }
 1940                Some(ContextMenu::CodeActions(_)) => {
 1941                    key_context.add("menu");
 1942                    key_context.add("showing_code_actions")
 1943                }
 1944                None => {}
 1945            }
 1946        }
 1947
 1948        for layer in self.keymap_context_layers.values() {
 1949            key_context.extend(layer);
 1950        }
 1951
 1952        if let Some(extension) = self
 1953            .buffer
 1954            .read(cx)
 1955            .as_singleton()
 1956            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1957        {
 1958            key_context.set("extension", extension.to_string());
 1959        }
 1960
 1961        if self.has_active_inline_completion(cx) {
 1962            key_context.add("copilot_suggestion");
 1963            key_context.add("inline_completion");
 1964        }
 1965
 1966        key_context
 1967    }
 1968
 1969    pub fn new_file(
 1970        workspace: &mut Workspace,
 1971        _: &workspace::NewFile,
 1972        cx: &mut ViewContext<Workspace>,
 1973    ) {
 1974        let project = workspace.project().clone();
 1975        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1976
 1977        cx.spawn(|workspace, mut cx| async move {
 1978            let buffer = create.await?;
 1979            workspace.update(&mut cx, |workspace, cx| {
 1980                workspace.add_item_to_active_pane(
 1981                    Box::new(
 1982                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1983                    ),
 1984                    None,
 1985                    cx,
 1986                )
 1987            })
 1988        })
 1989        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1990            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1991                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1992                e.error_tag("required").unwrap_or("the latest version")
 1993            )),
 1994            _ => None,
 1995        });
 1996    }
 1997
 1998    pub fn new_file_in_direction(
 1999        workspace: &mut Workspace,
 2000        action: &workspace::NewFileInDirection,
 2001        cx: &mut ViewContext<Workspace>,
 2002    ) {
 2003        let project = workspace.project().clone();
 2004        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2005        let direction = action.0;
 2006
 2007        cx.spawn(|workspace, mut cx| async move {
 2008            let buffer = create.await?;
 2009            workspace.update(&mut cx, move |workspace, cx| {
 2010                workspace.split_item(
 2011                    direction,
 2012                    Box::new(
 2013                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2014                    ),
 2015                    cx,
 2016                )
 2017            })?;
 2018            anyhow::Ok(())
 2019        })
 2020        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2021            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2022                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2023                e.error_tag("required").unwrap_or("the latest version")
 2024            )),
 2025            _ => None,
 2026        });
 2027    }
 2028
 2029    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
 2030        self.buffer.read(cx).replica_id()
 2031    }
 2032
 2033    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2034        self.leader_peer_id
 2035    }
 2036
 2037    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2038        &self.buffer
 2039    }
 2040
 2041    pub fn workspace(&self) -> Option<View<Workspace>> {
 2042        self.workspace.as_ref()?.0.upgrade()
 2043    }
 2044
 2045    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2046        self.buffer().read(cx).title(cx)
 2047    }
 2048
 2049    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2050        EditorSnapshot {
 2051            mode: self.mode,
 2052            show_gutter: self.show_gutter,
 2053            show_line_numbers: self.show_line_numbers,
 2054            show_git_diff_gutter: self.show_git_diff_gutter,
 2055            show_code_actions: self.show_code_actions,
 2056            show_runnables: self.show_runnables,
 2057            render_git_blame_gutter: self.render_git_blame_gutter(cx),
 2058            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2059            scroll_anchor: self.scroll_manager.anchor(),
 2060            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2061            placeholder_text: self.placeholder_text.clone(),
 2062            is_focused: self.focus_handle.is_focused(cx),
 2063            current_line_highlight: self
 2064                .current_line_highlight
 2065                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2066            gutter_hovered: self.gutter_hovered,
 2067        }
 2068    }
 2069
 2070    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2071        self.buffer.read(cx).language_at(point, cx)
 2072    }
 2073
 2074    pub fn file_at<T: ToOffset>(
 2075        &self,
 2076        point: T,
 2077        cx: &AppContext,
 2078    ) -> Option<Arc<dyn language::File>> {
 2079        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2080    }
 2081
 2082    pub fn active_excerpt(
 2083        &self,
 2084        cx: &AppContext,
 2085    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2086        self.buffer
 2087            .read(cx)
 2088            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2089    }
 2090
 2091    pub fn mode(&self) -> EditorMode {
 2092        self.mode
 2093    }
 2094
 2095    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2096        self.collaboration_hub.as_deref()
 2097    }
 2098
 2099    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2100        self.collaboration_hub = Some(hub);
 2101    }
 2102
 2103    pub fn set_custom_context_menu(
 2104        &mut self,
 2105        f: impl 'static
 2106            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2107    ) {
 2108        self.custom_context_menu = Some(Box::new(f))
 2109    }
 2110
 2111    pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
 2112        self.completion_provider = Some(provider);
 2113    }
 2114
 2115    pub fn set_inline_completion_provider<T>(
 2116        &mut self,
 2117        provider: Option<Model<T>>,
 2118        cx: &mut ViewContext<Self>,
 2119    ) where
 2120        T: InlineCompletionProvider,
 2121    {
 2122        self.inline_completion_provider =
 2123            provider.map(|provider| RegisteredInlineCompletionProvider {
 2124                _subscription: cx.observe(&provider, |this, _, cx| {
 2125                    if this.focus_handle.is_focused(cx) {
 2126                        this.update_visible_inline_completion(cx);
 2127                    }
 2128                }),
 2129                provider: Arc::new(provider),
 2130            });
 2131        self.refresh_inline_completion(false, cx);
 2132    }
 2133
 2134    pub fn placeholder_text(&self, _cx: &mut WindowContext) -> Option<&str> {
 2135        self.placeholder_text.as_deref()
 2136    }
 2137
 2138    pub fn set_placeholder_text(
 2139        &mut self,
 2140        placeholder_text: impl Into<Arc<str>>,
 2141        cx: &mut ViewContext<Self>,
 2142    ) {
 2143        let placeholder_text = Some(placeholder_text.into());
 2144        if self.placeholder_text != placeholder_text {
 2145            self.placeholder_text = placeholder_text;
 2146            cx.notify();
 2147        }
 2148    }
 2149
 2150    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2151        self.cursor_shape = cursor_shape;
 2152        cx.notify();
 2153    }
 2154
 2155    pub fn set_current_line_highlight(
 2156        &mut self,
 2157        current_line_highlight: Option<CurrentLineHighlight>,
 2158    ) {
 2159        self.current_line_highlight = current_line_highlight;
 2160    }
 2161
 2162    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2163        self.collapse_matches = collapse_matches;
 2164    }
 2165
 2166    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2167        if self.collapse_matches {
 2168            return range.start..range.start;
 2169        }
 2170        range.clone()
 2171    }
 2172
 2173    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2174        if self.display_map.read(cx).clip_at_line_ends != clip {
 2175            self.display_map
 2176                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2177        }
 2178    }
 2179
 2180    pub fn set_keymap_context_layer<Tag: 'static>(
 2181        &mut self,
 2182        context: KeyContext,
 2183        cx: &mut ViewContext<Self>,
 2184    ) {
 2185        self.keymap_context_layers
 2186            .insert(TypeId::of::<Tag>(), context);
 2187        cx.notify();
 2188    }
 2189
 2190    pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
 2191        self.keymap_context_layers.remove(&TypeId::of::<Tag>());
 2192        cx.notify();
 2193    }
 2194
 2195    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2196        self.input_enabled = input_enabled;
 2197    }
 2198
 2199    pub fn set_autoindent(&mut self, autoindent: bool) {
 2200        if autoindent {
 2201            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2202        } else {
 2203            self.autoindent_mode = None;
 2204        }
 2205    }
 2206
 2207    pub fn read_only(&self, cx: &AppContext) -> bool {
 2208        self.read_only || self.buffer.read(cx).read_only()
 2209    }
 2210
 2211    pub fn set_read_only(&mut self, read_only: bool) {
 2212        self.read_only = read_only;
 2213    }
 2214
 2215    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2216        self.use_autoclose = autoclose;
 2217    }
 2218
 2219    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2220        self.use_auto_surround = auto_surround;
 2221    }
 2222
 2223    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2224        self.auto_replace_emoji_shortcode = auto_replace;
 2225    }
 2226
 2227    pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
 2228        self.show_inline_completions = show_inline_completions;
 2229    }
 2230
 2231    pub fn set_use_modal_editing(&mut self, to: bool) {
 2232        self.use_modal_editing = to;
 2233    }
 2234
 2235    pub fn use_modal_editing(&self) -> bool {
 2236        self.use_modal_editing
 2237    }
 2238
 2239    fn selections_did_change(
 2240        &mut self,
 2241        local: bool,
 2242        old_cursor_position: &Anchor,
 2243        show_completions: bool,
 2244        cx: &mut ViewContext<Self>,
 2245    ) {
 2246        // Copy selections to primary selection buffer
 2247        #[cfg(target_os = "linux")]
 2248        if local {
 2249            let selections = self.selections.all::<usize>(cx);
 2250            let buffer_handle = self.buffer.read(cx).read(cx);
 2251
 2252            let mut text = String::new();
 2253            for (index, selection) in selections.iter().enumerate() {
 2254                let text_for_selection = buffer_handle
 2255                    .text_for_range(selection.start..selection.end)
 2256                    .collect::<String>();
 2257
 2258                text.push_str(&text_for_selection);
 2259                if index != selections.len() - 1 {
 2260                    text.push('\n');
 2261                }
 2262            }
 2263
 2264            if !text.is_empty() {
 2265                cx.write_to_primary(ClipboardItem::new(text));
 2266            }
 2267        }
 2268
 2269        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2270            self.buffer.update(cx, |buffer, cx| {
 2271                buffer.set_active_selections(
 2272                    &self.selections.disjoint_anchors(),
 2273                    self.selections.line_mode,
 2274                    self.cursor_shape,
 2275                    cx,
 2276                )
 2277            });
 2278        }
 2279        let display_map = self
 2280            .display_map
 2281            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2282        let buffer = &display_map.buffer_snapshot;
 2283        self.add_selections_state = None;
 2284        self.select_next_state = None;
 2285        self.select_prev_state = None;
 2286        self.select_larger_syntax_node_stack.clear();
 2287        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2288        self.snippet_stack
 2289            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2290        self.take_rename(false, cx);
 2291
 2292        let new_cursor_position = self.selections.newest_anchor().head();
 2293
 2294        self.push_to_nav_history(
 2295            *old_cursor_position,
 2296            Some(new_cursor_position.to_point(buffer)),
 2297            cx,
 2298        );
 2299
 2300        if local {
 2301            let new_cursor_position = self.selections.newest_anchor().head();
 2302            let mut context_menu = self.context_menu.write();
 2303            let completion_menu = match context_menu.as_ref() {
 2304                Some(ContextMenu::Completions(menu)) => Some(menu),
 2305
 2306                _ => {
 2307                    *context_menu = None;
 2308                    None
 2309                }
 2310            };
 2311
 2312            if let Some(completion_menu) = completion_menu {
 2313                let cursor_position = new_cursor_position.to_offset(buffer);
 2314                let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
 2315                if kind == Some(CharKind::Word)
 2316                    && word_range.to_inclusive().contains(&cursor_position)
 2317                {
 2318                    let mut completion_menu = completion_menu.clone();
 2319                    drop(context_menu);
 2320
 2321                    let query = Self::completion_query(buffer, cursor_position);
 2322                    cx.spawn(move |this, mut cx| async move {
 2323                        completion_menu
 2324                            .filter(query.as_deref(), cx.background_executor().clone())
 2325                            .await;
 2326
 2327                        this.update(&mut cx, |this, cx| {
 2328                            let mut context_menu = this.context_menu.write();
 2329                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2330                                return;
 2331                            };
 2332
 2333                            if menu.id > completion_menu.id {
 2334                                return;
 2335                            }
 2336
 2337                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2338                            drop(context_menu);
 2339                            cx.notify();
 2340                        })
 2341                    })
 2342                    .detach();
 2343
 2344                    if show_completions {
 2345                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2346                    }
 2347                } else {
 2348                    drop(context_menu);
 2349                    self.hide_context_menu(cx);
 2350                }
 2351            } else {
 2352                drop(context_menu);
 2353            }
 2354
 2355            hide_hover(self, cx);
 2356
 2357            if old_cursor_position.to_display_point(&display_map).row()
 2358                != new_cursor_position.to_display_point(&display_map).row()
 2359            {
 2360                self.available_code_actions.take();
 2361            }
 2362            self.refresh_code_actions(cx);
 2363            self.refresh_document_highlights(cx);
 2364            refresh_matching_bracket_highlights(self, cx);
 2365            self.discard_inline_completion(false, cx);
 2366            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2367            if self.git_blame_inline_enabled {
 2368                self.start_inline_blame_timer(cx);
 2369            }
 2370        }
 2371
 2372        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2373        cx.emit(EditorEvent::SelectionsChanged { local });
 2374
 2375        if self.selections.disjoint_anchors().len() == 1 {
 2376            cx.emit(SearchEvent::ActiveMatchChanged)
 2377        }
 2378        cx.notify();
 2379    }
 2380
 2381    pub fn change_selections<R>(
 2382        &mut self,
 2383        autoscroll: Option<Autoscroll>,
 2384        cx: &mut ViewContext<Self>,
 2385        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2386    ) -> R {
 2387        self.change_selections_inner(autoscroll, true, cx, change)
 2388    }
 2389
 2390    pub fn change_selections_inner<R>(
 2391        &mut self,
 2392        autoscroll: Option<Autoscroll>,
 2393        request_completions: bool,
 2394        cx: &mut ViewContext<Self>,
 2395        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2396    ) -> R {
 2397        let old_cursor_position = self.selections.newest_anchor().head();
 2398        self.push_to_selection_history();
 2399
 2400        let (changed, result) = self.selections.change_with(cx, change);
 2401
 2402        if changed {
 2403            if let Some(autoscroll) = autoscroll {
 2404                self.request_autoscroll(autoscroll, cx);
 2405            }
 2406            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2407        }
 2408
 2409        result
 2410    }
 2411
 2412    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2413    where
 2414        I: IntoIterator<Item = (Range<S>, T)>,
 2415        S: ToOffset,
 2416        T: Into<Arc<str>>,
 2417    {
 2418        if self.read_only(cx) {
 2419            return;
 2420        }
 2421
 2422        self.buffer
 2423            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2424    }
 2425
 2426    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2427    where
 2428        I: IntoIterator<Item = (Range<S>, T)>,
 2429        S: ToOffset,
 2430        T: Into<Arc<str>>,
 2431    {
 2432        if self.read_only(cx) {
 2433            return;
 2434        }
 2435
 2436        self.buffer.update(cx, |buffer, cx| {
 2437            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2438        });
 2439    }
 2440
 2441    pub fn edit_with_block_indent<I, S, T>(
 2442        &mut self,
 2443        edits: I,
 2444        original_indent_columns: Vec<u32>,
 2445        cx: &mut ViewContext<Self>,
 2446    ) where
 2447        I: IntoIterator<Item = (Range<S>, T)>,
 2448        S: ToOffset,
 2449        T: Into<Arc<str>>,
 2450    {
 2451        if self.read_only(cx) {
 2452            return;
 2453        }
 2454
 2455        self.buffer.update(cx, |buffer, cx| {
 2456            buffer.edit(
 2457                edits,
 2458                Some(AutoindentMode::Block {
 2459                    original_indent_columns,
 2460                }),
 2461                cx,
 2462            )
 2463        });
 2464    }
 2465
 2466    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2467        self.hide_context_menu(cx);
 2468
 2469        match phase {
 2470            SelectPhase::Begin {
 2471                position,
 2472                add,
 2473                click_count,
 2474            } => self.begin_selection(position, add, click_count, cx),
 2475            SelectPhase::BeginColumnar {
 2476                position,
 2477                goal_column,
 2478                reset,
 2479            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2480            SelectPhase::Extend {
 2481                position,
 2482                click_count,
 2483            } => self.extend_selection(position, click_count, cx),
 2484            SelectPhase::Update {
 2485                position,
 2486                goal_column,
 2487                scroll_delta,
 2488            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2489            SelectPhase::End => self.end_selection(cx),
 2490        }
 2491    }
 2492
 2493    fn extend_selection(
 2494        &mut self,
 2495        position: DisplayPoint,
 2496        click_count: usize,
 2497        cx: &mut ViewContext<Self>,
 2498    ) {
 2499        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2500        let tail = self.selections.newest::<usize>(cx).tail();
 2501        self.begin_selection(position, false, click_count, cx);
 2502
 2503        let position = position.to_offset(&display_map, Bias::Left);
 2504        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2505
 2506        let mut pending_selection = self
 2507            .selections
 2508            .pending_anchor()
 2509            .expect("extend_selection not called with pending selection");
 2510        if position >= tail {
 2511            pending_selection.start = tail_anchor;
 2512        } else {
 2513            pending_selection.end = tail_anchor;
 2514            pending_selection.reversed = true;
 2515        }
 2516
 2517        let mut pending_mode = self.selections.pending_mode().unwrap();
 2518        match &mut pending_mode {
 2519            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2520            _ => {}
 2521        }
 2522
 2523        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2524            s.set_pending(pending_selection, pending_mode)
 2525        });
 2526    }
 2527
 2528    fn begin_selection(
 2529        &mut self,
 2530        position: DisplayPoint,
 2531        add: bool,
 2532        click_count: usize,
 2533        cx: &mut ViewContext<Self>,
 2534    ) {
 2535        if !self.focus_handle.is_focused(cx) {
 2536            self.last_focused_descendant = None;
 2537            cx.focus(&self.focus_handle);
 2538        }
 2539
 2540        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2541        let buffer = &display_map.buffer_snapshot;
 2542        let newest_selection = self.selections.newest_anchor().clone();
 2543        let position = display_map.clip_point(position, Bias::Left);
 2544
 2545        let start;
 2546        let end;
 2547        let mode;
 2548        let auto_scroll;
 2549        match click_count {
 2550            1 => {
 2551                start = buffer.anchor_before(position.to_point(&display_map));
 2552                end = start;
 2553                mode = SelectMode::Character;
 2554                auto_scroll = true;
 2555            }
 2556            2 => {
 2557                let range = movement::surrounding_word(&display_map, position);
 2558                start = buffer.anchor_before(range.start.to_point(&display_map));
 2559                end = buffer.anchor_before(range.end.to_point(&display_map));
 2560                mode = SelectMode::Word(start..end);
 2561                auto_scroll = true;
 2562            }
 2563            3 => {
 2564                let position = display_map
 2565                    .clip_point(position, Bias::Left)
 2566                    .to_point(&display_map);
 2567                let line_start = display_map.prev_line_boundary(position).0;
 2568                let next_line_start = buffer.clip_point(
 2569                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2570                    Bias::Left,
 2571                );
 2572                start = buffer.anchor_before(line_start);
 2573                end = buffer.anchor_before(next_line_start);
 2574                mode = SelectMode::Line(start..end);
 2575                auto_scroll = true;
 2576            }
 2577            _ => {
 2578                start = buffer.anchor_before(0);
 2579                end = buffer.anchor_before(buffer.len());
 2580                mode = SelectMode::All;
 2581                auto_scroll = false;
 2582            }
 2583        }
 2584
 2585        let point_to_delete: Option<usize> = {
 2586            let selected_points: Vec<Selection<Point>> =
 2587                self.selections.disjoint_in_range(start..end, cx);
 2588
 2589            if !add || click_count > 1 {
 2590                None
 2591            } else if selected_points.len() > 0 {
 2592                Some(selected_points[0].id)
 2593            } else {
 2594                let clicked_point_already_selected =
 2595                    self.selections.disjoint.iter().find(|selection| {
 2596                        selection.start.to_point(buffer) == start.to_point(buffer)
 2597                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2598                    });
 2599
 2600                if let Some(selection) = clicked_point_already_selected {
 2601                    Some(selection.id)
 2602                } else {
 2603                    None
 2604                }
 2605            }
 2606        };
 2607
 2608        let selections_count = self.selections.count();
 2609
 2610        self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
 2611            if let Some(point_to_delete) = point_to_delete {
 2612                s.delete(point_to_delete);
 2613
 2614                if selections_count == 1 {
 2615                    s.set_pending_anchor_range(start..end, mode);
 2616                }
 2617            } else {
 2618                if !add {
 2619                    s.clear_disjoint();
 2620                } else if click_count > 1 {
 2621                    s.delete(newest_selection.id)
 2622                }
 2623
 2624                s.set_pending_anchor_range(start..end, mode);
 2625            }
 2626        });
 2627    }
 2628
 2629    fn begin_columnar_selection(
 2630        &mut self,
 2631        position: DisplayPoint,
 2632        goal_column: u32,
 2633        reset: bool,
 2634        cx: &mut ViewContext<Self>,
 2635    ) {
 2636        if !self.focus_handle.is_focused(cx) {
 2637            self.last_focused_descendant = None;
 2638            cx.focus(&self.focus_handle);
 2639        }
 2640
 2641        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2642
 2643        if reset {
 2644            let pointer_position = display_map
 2645                .buffer_snapshot
 2646                .anchor_before(position.to_point(&display_map));
 2647
 2648            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2649                s.clear_disjoint();
 2650                s.set_pending_anchor_range(
 2651                    pointer_position..pointer_position,
 2652                    SelectMode::Character,
 2653                );
 2654            });
 2655        }
 2656
 2657        let tail = self.selections.newest::<Point>(cx).tail();
 2658        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2659
 2660        if !reset {
 2661            self.select_columns(
 2662                tail.to_display_point(&display_map),
 2663                position,
 2664                goal_column,
 2665                &display_map,
 2666                cx,
 2667            );
 2668        }
 2669    }
 2670
 2671    fn update_selection(
 2672        &mut self,
 2673        position: DisplayPoint,
 2674        goal_column: u32,
 2675        scroll_delta: gpui::Point<f32>,
 2676        cx: &mut ViewContext<Self>,
 2677    ) {
 2678        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2679
 2680        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2681            let tail = tail.to_display_point(&display_map);
 2682            self.select_columns(tail, position, goal_column, &display_map, cx);
 2683        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2684            let buffer = self.buffer.read(cx).snapshot(cx);
 2685            let head;
 2686            let tail;
 2687            let mode = self.selections.pending_mode().unwrap();
 2688            match &mode {
 2689                SelectMode::Character => {
 2690                    head = position.to_point(&display_map);
 2691                    tail = pending.tail().to_point(&buffer);
 2692                }
 2693                SelectMode::Word(original_range) => {
 2694                    let original_display_range = original_range.start.to_display_point(&display_map)
 2695                        ..original_range.end.to_display_point(&display_map);
 2696                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2697                        ..original_display_range.end.to_point(&display_map);
 2698                    if movement::is_inside_word(&display_map, position)
 2699                        || original_display_range.contains(&position)
 2700                    {
 2701                        let word_range = movement::surrounding_word(&display_map, position);
 2702                        if word_range.start < original_display_range.start {
 2703                            head = word_range.start.to_point(&display_map);
 2704                        } else {
 2705                            head = word_range.end.to_point(&display_map);
 2706                        }
 2707                    } else {
 2708                        head = position.to_point(&display_map);
 2709                    }
 2710
 2711                    if head <= original_buffer_range.start {
 2712                        tail = original_buffer_range.end;
 2713                    } else {
 2714                        tail = original_buffer_range.start;
 2715                    }
 2716                }
 2717                SelectMode::Line(original_range) => {
 2718                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2719
 2720                    let position = display_map
 2721                        .clip_point(position, Bias::Left)
 2722                        .to_point(&display_map);
 2723                    let line_start = display_map.prev_line_boundary(position).0;
 2724                    let next_line_start = buffer.clip_point(
 2725                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2726                        Bias::Left,
 2727                    );
 2728
 2729                    if line_start < original_range.start {
 2730                        head = line_start
 2731                    } else {
 2732                        head = next_line_start
 2733                    }
 2734
 2735                    if head <= original_range.start {
 2736                        tail = original_range.end;
 2737                    } else {
 2738                        tail = original_range.start;
 2739                    }
 2740                }
 2741                SelectMode::All => {
 2742                    return;
 2743                }
 2744            };
 2745
 2746            if head < tail {
 2747                pending.start = buffer.anchor_before(head);
 2748                pending.end = buffer.anchor_before(tail);
 2749                pending.reversed = true;
 2750            } else {
 2751                pending.start = buffer.anchor_before(tail);
 2752                pending.end = buffer.anchor_before(head);
 2753                pending.reversed = false;
 2754            }
 2755
 2756            self.change_selections(None, cx, |s| {
 2757                s.set_pending(pending, mode);
 2758            });
 2759        } else {
 2760            log::error!("update_selection dispatched with no pending selection");
 2761            return;
 2762        }
 2763
 2764        self.apply_scroll_delta(scroll_delta, cx);
 2765        cx.notify();
 2766    }
 2767
 2768    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2769        self.columnar_selection_tail.take();
 2770        if self.selections.pending_anchor().is_some() {
 2771            let selections = self.selections.all::<usize>(cx);
 2772            self.change_selections(None, cx, |s| {
 2773                s.select(selections);
 2774                s.clear_pending();
 2775            });
 2776        }
 2777    }
 2778
 2779    fn select_columns(
 2780        &mut self,
 2781        tail: DisplayPoint,
 2782        head: DisplayPoint,
 2783        goal_column: u32,
 2784        display_map: &DisplaySnapshot,
 2785        cx: &mut ViewContext<Self>,
 2786    ) {
 2787        let start_row = cmp::min(tail.row(), head.row());
 2788        let end_row = cmp::max(tail.row(), head.row());
 2789        let start_column = cmp::min(tail.column(), goal_column);
 2790        let end_column = cmp::max(tail.column(), goal_column);
 2791        let reversed = start_column < tail.column();
 2792
 2793        let selection_ranges = (start_row.0..=end_row.0)
 2794            .map(DisplayRow)
 2795            .filter_map(|row| {
 2796                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2797                    let start = display_map
 2798                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2799                        .to_point(display_map);
 2800                    let end = display_map
 2801                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2802                        .to_point(display_map);
 2803                    if reversed {
 2804                        Some(end..start)
 2805                    } else {
 2806                        Some(start..end)
 2807                    }
 2808                } else {
 2809                    None
 2810                }
 2811            })
 2812            .collect::<Vec<_>>();
 2813
 2814        self.change_selections(None, cx, |s| {
 2815            s.select_ranges(selection_ranges);
 2816        });
 2817        cx.notify();
 2818    }
 2819
 2820    pub fn has_pending_nonempty_selection(&self) -> bool {
 2821        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2822            Some(Selection { start, end, .. }) => start != end,
 2823            None => false,
 2824        };
 2825
 2826        pending_nonempty_selection
 2827            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2828    }
 2829
 2830    pub fn has_pending_selection(&self) -> bool {
 2831        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2832    }
 2833
 2834    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2835        self.clear_expanded_diff_hunks(cx);
 2836        if self.dismiss_menus_and_popups(true, cx) {
 2837            return;
 2838        }
 2839
 2840        if self.mode == EditorMode::Full {
 2841            if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
 2842                return;
 2843            }
 2844        }
 2845
 2846        cx.propagate();
 2847    }
 2848
 2849    pub fn dismiss_menus_and_popups(
 2850        &mut self,
 2851        should_report_inline_completion_event: bool,
 2852        cx: &mut ViewContext<Self>,
 2853    ) -> bool {
 2854        if self.take_rename(false, cx).is_some() {
 2855            return true;
 2856        }
 2857
 2858        if hide_hover(self, cx) {
 2859            return true;
 2860        }
 2861
 2862        if self.hide_context_menu(cx).is_some() {
 2863            return true;
 2864        }
 2865
 2866        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2867            return true;
 2868        }
 2869
 2870        if self.snippet_stack.pop().is_some() {
 2871            return true;
 2872        }
 2873
 2874        if self.mode == EditorMode::Full {
 2875            if self.active_diagnostics.is_some() {
 2876                self.dismiss_diagnostics(cx);
 2877                return true;
 2878            }
 2879        }
 2880
 2881        false
 2882    }
 2883
 2884    fn linked_editing_ranges_for(
 2885        &self,
 2886        selection: Range<text::Anchor>,
 2887        cx: &AppContext,
 2888    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2889        if self.linked_edit_ranges.is_empty() {
 2890            return None;
 2891        }
 2892        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2893            selection.end.buffer_id.and_then(|end_buffer_id| {
 2894                if selection.start.buffer_id != Some(end_buffer_id) {
 2895                    return None;
 2896                }
 2897                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2898                let snapshot = buffer.read(cx).snapshot();
 2899                self.linked_edit_ranges
 2900                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2901                    .map(|ranges| (ranges, snapshot, buffer))
 2902            })?;
 2903        use text::ToOffset as TO;
 2904        // find offset from the start of current range to current cursor position
 2905        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2906
 2907        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2908        let start_difference = start_offset - start_byte_offset;
 2909        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2910        let end_difference = end_offset - start_byte_offset;
 2911        // Current range has associated linked ranges.
 2912        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2913        for range in linked_ranges.iter() {
 2914            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2915            let end_offset = start_offset + end_difference;
 2916            let start_offset = start_offset + start_difference;
 2917            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2918                continue;
 2919            }
 2920            let start = buffer_snapshot.anchor_after(start_offset);
 2921            let end = buffer_snapshot.anchor_after(end_offset);
 2922            linked_edits
 2923                .entry(buffer.clone())
 2924                .or_default()
 2925                .push(start..end);
 2926        }
 2927        Some(linked_edits)
 2928    }
 2929
 2930    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2931        let text: Arc<str> = text.into();
 2932
 2933        if self.read_only(cx) {
 2934            return;
 2935        }
 2936
 2937        let selections = self.selections.all_adjusted(cx);
 2938        let mut brace_inserted = false;
 2939        let mut edits = Vec::new();
 2940        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2941        let mut new_selections = Vec::with_capacity(selections.len());
 2942        let mut new_autoclose_regions = Vec::new();
 2943        let snapshot = self.buffer.read(cx).read(cx);
 2944
 2945        for (selection, autoclose_region) in
 2946            self.selections_with_autoclose_regions(selections, &snapshot)
 2947        {
 2948            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2949                // Determine if the inserted text matches the opening or closing
 2950                // bracket of any of this language's bracket pairs.
 2951                let mut bracket_pair = None;
 2952                let mut is_bracket_pair_start = false;
 2953                let mut is_bracket_pair_end = false;
 2954                if !text.is_empty() {
 2955                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2956                    //  and they are removing the character that triggered IME popup.
 2957                    for (pair, enabled) in scope.brackets() {
 2958                        if !pair.close && !pair.surround {
 2959                            continue;
 2960                        }
 2961
 2962                        if enabled && pair.start.ends_with(text.as_ref()) {
 2963                            bracket_pair = Some(pair.clone());
 2964                            is_bracket_pair_start = true;
 2965                            break;
 2966                        }
 2967                        if pair.end.as_str() == text.as_ref() {
 2968                            bracket_pair = Some(pair.clone());
 2969                            is_bracket_pair_end = true;
 2970                            break;
 2971                        }
 2972                    }
 2973                }
 2974
 2975                if let Some(bracket_pair) = bracket_pair {
 2976                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2977                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2978                    let auto_surround =
 2979                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2980                    if selection.is_empty() {
 2981                        if is_bracket_pair_start {
 2982                            let prefix_len = bracket_pair.start.len() - text.len();
 2983
 2984                            // If the inserted text is a suffix of an opening bracket and the
 2985                            // selection is preceded by the rest of the opening bracket, then
 2986                            // insert the closing bracket.
 2987                            let following_text_allows_autoclose = snapshot
 2988                                .chars_at(selection.start)
 2989                                .next()
 2990                                .map_or(true, |c| scope.should_autoclose_before(c));
 2991                            let preceding_text_matches_prefix = prefix_len == 0
 2992                                || (selection.start.column >= (prefix_len as u32)
 2993                                    && snapshot.contains_str_at(
 2994                                        Point::new(
 2995                                            selection.start.row,
 2996                                            selection.start.column - (prefix_len as u32),
 2997                                        ),
 2998                                        &bracket_pair.start[..prefix_len],
 2999                                    ));
 3000                            if autoclose
 3001                                && bracket_pair.close
 3002                                && following_text_allows_autoclose
 3003                                && preceding_text_matches_prefix
 3004                            {
 3005                                let anchor = snapshot.anchor_before(selection.end);
 3006                                new_selections.push((selection.map(|_| anchor), text.len()));
 3007                                new_autoclose_regions.push((
 3008                                    anchor,
 3009                                    text.len(),
 3010                                    selection.id,
 3011                                    bracket_pair.clone(),
 3012                                ));
 3013                                edits.push((
 3014                                    selection.range(),
 3015                                    format!("{}{}", text, bracket_pair.end).into(),
 3016                                ));
 3017                                brace_inserted = true;
 3018                                continue;
 3019                            }
 3020                        }
 3021
 3022                        if let Some(region) = autoclose_region {
 3023                            // If the selection is followed by an auto-inserted closing bracket,
 3024                            // then don't insert that closing bracket again; just move the selection
 3025                            // past the closing bracket.
 3026                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3027                                && text.as_ref() == region.pair.end.as_str();
 3028                            if should_skip {
 3029                                let anchor = snapshot.anchor_after(selection.end);
 3030                                new_selections
 3031                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3032                                continue;
 3033                            }
 3034                        }
 3035
 3036                        let always_treat_brackets_as_autoclosed = snapshot
 3037                            .settings_at(selection.start, cx)
 3038                            .always_treat_brackets_as_autoclosed;
 3039                        if always_treat_brackets_as_autoclosed
 3040                            && is_bracket_pair_end
 3041                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3042                        {
 3043                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3044                            // and the inserted text is a closing bracket and the selection is followed
 3045                            // by the closing bracket then move the selection past the closing bracket.
 3046                            let anchor = snapshot.anchor_after(selection.end);
 3047                            new_selections.push((selection.map(|_| anchor), text.len()));
 3048                            continue;
 3049                        }
 3050                    }
 3051                    // If an opening bracket is 1 character long and is typed while
 3052                    // text is selected, then surround that text with the bracket pair.
 3053                    else if auto_surround
 3054                        && bracket_pair.surround
 3055                        && is_bracket_pair_start
 3056                        && bracket_pair.start.chars().count() == 1
 3057                    {
 3058                        edits.push((selection.start..selection.start, text.clone()));
 3059                        edits.push((
 3060                            selection.end..selection.end,
 3061                            bracket_pair.end.as_str().into(),
 3062                        ));
 3063                        brace_inserted = true;
 3064                        new_selections.push((
 3065                            Selection {
 3066                                id: selection.id,
 3067                                start: snapshot.anchor_after(selection.start),
 3068                                end: snapshot.anchor_before(selection.end),
 3069                                reversed: selection.reversed,
 3070                                goal: selection.goal,
 3071                            },
 3072                            0,
 3073                        ));
 3074                        continue;
 3075                    }
 3076                }
 3077            }
 3078
 3079            if self.auto_replace_emoji_shortcode
 3080                && selection.is_empty()
 3081                && text.as_ref().ends_with(':')
 3082            {
 3083                if let Some(possible_emoji_short_code) =
 3084                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3085                {
 3086                    if !possible_emoji_short_code.is_empty() {
 3087                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3088                            let emoji_shortcode_start = Point::new(
 3089                                selection.start.row,
 3090                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3091                            );
 3092
 3093                            // Remove shortcode from buffer
 3094                            edits.push((
 3095                                emoji_shortcode_start..selection.start,
 3096                                "".to_string().into(),
 3097                            ));
 3098                            new_selections.push((
 3099                                Selection {
 3100                                    id: selection.id,
 3101                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3102                                    end: snapshot.anchor_before(selection.start),
 3103                                    reversed: selection.reversed,
 3104                                    goal: selection.goal,
 3105                                },
 3106                                0,
 3107                            ));
 3108
 3109                            // Insert emoji
 3110                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3111                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3112                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3113
 3114                            continue;
 3115                        }
 3116                    }
 3117                }
 3118            }
 3119
 3120            // If not handling any auto-close operation, then just replace the selected
 3121            // text with the given input and move the selection to the end of the
 3122            // newly inserted text.
 3123            let anchor = snapshot.anchor_after(selection.end);
 3124            if !self.linked_edit_ranges.is_empty() {
 3125                let start_anchor = snapshot.anchor_before(selection.start);
 3126                if let Some(ranges) =
 3127                    self.linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3128                {
 3129                    for (buffer, edits) in ranges {
 3130                        linked_edits
 3131                            .entry(buffer.clone())
 3132                            .or_default()
 3133                            .extend(edits.into_iter().map(|range| (range, text.clone())));
 3134                    }
 3135                }
 3136            }
 3137
 3138            new_selections.push((selection.map(|_| anchor), 0));
 3139            edits.push((selection.start..selection.end, text.clone()));
 3140        }
 3141
 3142        drop(snapshot);
 3143
 3144        self.transact(cx, |this, cx| {
 3145            this.buffer.update(cx, |buffer, cx| {
 3146                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3147            });
 3148            for (buffer, edits) in linked_edits {
 3149                buffer.update(cx, |buffer, cx| {
 3150                    let snapshot = buffer.snapshot();
 3151                    let edits = edits
 3152                        .into_iter()
 3153                        .map(|(range, text)| {
 3154                            use text::ToPoint as TP;
 3155                            let end_point = TP::to_point(&range.end, &snapshot);
 3156                            let start_point = TP::to_point(&range.start, &snapshot);
 3157                            (start_point..end_point, text)
 3158                        })
 3159                        .sorted_by_key(|(range, _)| range.start)
 3160                        .collect::<Vec<_>>();
 3161                    buffer.edit(edits, None, cx);
 3162                })
 3163            }
 3164            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3165            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3166            let snapshot = this.buffer.read(cx).read(cx);
 3167            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3168                .zip(new_selection_deltas)
 3169                .map(|(selection, delta)| Selection {
 3170                    id: selection.id,
 3171                    start: selection.start + delta,
 3172                    end: selection.end + delta,
 3173                    reversed: selection.reversed,
 3174                    goal: SelectionGoal::None,
 3175                })
 3176                .collect::<Vec<_>>();
 3177
 3178            let mut i = 0;
 3179            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3180                let position = position.to_offset(&snapshot) + delta;
 3181                let start = snapshot.anchor_before(position);
 3182                let end = snapshot.anchor_after(position);
 3183                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3184                    match existing_state.range.start.cmp(&start, &snapshot) {
 3185                        Ordering::Less => i += 1,
 3186                        Ordering::Greater => break,
 3187                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3188                            Ordering::Less => i += 1,
 3189                            Ordering::Equal => break,
 3190                            Ordering::Greater => break,
 3191                        },
 3192                    }
 3193                }
 3194                this.autoclose_regions.insert(
 3195                    i,
 3196                    AutocloseRegion {
 3197                        selection_id,
 3198                        range: start..end,
 3199                        pair,
 3200                    },
 3201                );
 3202            }
 3203
 3204            drop(snapshot);
 3205            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3206            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3207                s.select(new_selections)
 3208            });
 3209
 3210            if !brace_inserted && EditorSettings::get_global(cx).use_on_type_format {
 3211                if let Some(on_type_format_task) =
 3212                    this.trigger_on_type_formatting(text.to_string(), cx)
 3213                {
 3214                    on_type_format_task.detach_and_log_err(cx);
 3215                }
 3216            }
 3217
 3218            let trigger_in_words = !had_active_inline_completion;
 3219            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3220            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3221            this.refresh_inline_completion(true, cx);
 3222        });
 3223    }
 3224
 3225    fn find_possible_emoji_shortcode_at_position(
 3226        snapshot: &MultiBufferSnapshot,
 3227        position: Point,
 3228    ) -> Option<String> {
 3229        let mut chars = Vec::new();
 3230        let mut found_colon = false;
 3231        for char in snapshot.reversed_chars_at(position).take(100) {
 3232            // Found a possible emoji shortcode in the middle of the buffer
 3233            if found_colon {
 3234                if char.is_whitespace() {
 3235                    chars.reverse();
 3236                    return Some(chars.iter().collect());
 3237                }
 3238                // If the previous character is not a whitespace, we are in the middle of a word
 3239                // and we only want to complete the shortcode if the word is made up of other emojis
 3240                let mut containing_word = String::new();
 3241                for ch in snapshot
 3242                    .reversed_chars_at(position)
 3243                    .skip(chars.len() + 1)
 3244                    .take(100)
 3245                {
 3246                    if ch.is_whitespace() {
 3247                        break;
 3248                    }
 3249                    containing_word.push(ch);
 3250                }
 3251                let containing_word = containing_word.chars().rev().collect::<String>();
 3252                if util::word_consists_of_emojis(containing_word.as_str()) {
 3253                    chars.reverse();
 3254                    return Some(chars.iter().collect());
 3255                }
 3256            }
 3257
 3258            if char.is_whitespace() || !char.is_ascii() {
 3259                return None;
 3260            }
 3261            if char == ':' {
 3262                found_colon = true;
 3263            } else {
 3264                chars.push(char);
 3265            }
 3266        }
 3267        // Found a possible emoji shortcode at the beginning of the buffer
 3268        chars.reverse();
 3269        Some(chars.iter().collect())
 3270    }
 3271
 3272    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3273        self.transact(cx, |this, cx| {
 3274            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3275                let selections = this.selections.all::<usize>(cx);
 3276                let multi_buffer = this.buffer.read(cx);
 3277                let buffer = multi_buffer.snapshot(cx);
 3278                selections
 3279                    .iter()
 3280                    .map(|selection| {
 3281                        let start_point = selection.start.to_point(&buffer);
 3282                        let mut indent =
 3283                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3284                        indent.len = cmp::min(indent.len, start_point.column);
 3285                        let start = selection.start;
 3286                        let end = selection.end;
 3287                        let selection_is_empty = start == end;
 3288                        let language_scope = buffer.language_scope_at(start);
 3289                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3290                            &language_scope
 3291                        {
 3292                            let leading_whitespace_len = buffer
 3293                                .reversed_chars_at(start)
 3294                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3295                                .map(|c| c.len_utf8())
 3296                                .sum::<usize>();
 3297
 3298                            let trailing_whitespace_len = buffer
 3299                                .chars_at(end)
 3300                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3301                                .map(|c| c.len_utf8())
 3302                                .sum::<usize>();
 3303
 3304                            let insert_extra_newline =
 3305                                language.brackets().any(|(pair, enabled)| {
 3306                                    let pair_start = pair.start.trim_end();
 3307                                    let pair_end = pair.end.trim_start();
 3308
 3309                                    enabled
 3310                                        && pair.newline
 3311                                        && buffer.contains_str_at(
 3312                                            end + trailing_whitespace_len,
 3313                                            pair_end,
 3314                                        )
 3315                                        && buffer.contains_str_at(
 3316                                            (start - leading_whitespace_len)
 3317                                                .saturating_sub(pair_start.len()),
 3318                                            pair_start,
 3319                                        )
 3320                                });
 3321
 3322                            // Comment extension on newline is allowed only for cursor selections
 3323                            let comment_delimiter = maybe!({
 3324                                if !selection_is_empty {
 3325                                    return None;
 3326                                }
 3327
 3328                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3329                                    return None;
 3330                                }
 3331
 3332                                let delimiters = language.line_comment_prefixes();
 3333                                let max_len_of_delimiter =
 3334                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3335                                let (snapshot, range) =
 3336                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3337
 3338                                let mut index_of_first_non_whitespace = 0;
 3339                                let comment_candidate = snapshot
 3340                                    .chars_for_range(range)
 3341                                    .skip_while(|c| {
 3342                                        let should_skip = c.is_whitespace();
 3343                                        if should_skip {
 3344                                            index_of_first_non_whitespace += 1;
 3345                                        }
 3346                                        should_skip
 3347                                    })
 3348                                    .take(max_len_of_delimiter)
 3349                                    .collect::<String>();
 3350                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3351                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3352                                })?;
 3353                                let cursor_is_placed_after_comment_marker =
 3354                                    index_of_first_non_whitespace + comment_prefix.len()
 3355                                        <= start_point.column as usize;
 3356                                if cursor_is_placed_after_comment_marker {
 3357                                    Some(comment_prefix.clone())
 3358                                } else {
 3359                                    None
 3360                                }
 3361                            });
 3362                            (comment_delimiter, insert_extra_newline)
 3363                        } else {
 3364                            (None, false)
 3365                        };
 3366
 3367                        let capacity_for_delimiter = comment_delimiter
 3368                            .as_deref()
 3369                            .map(str::len)
 3370                            .unwrap_or_default();
 3371                        let mut new_text =
 3372                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3373                        new_text.push_str("\n");
 3374                        new_text.extend(indent.chars());
 3375                        if let Some(delimiter) = &comment_delimiter {
 3376                            new_text.push_str(&delimiter);
 3377                        }
 3378                        if insert_extra_newline {
 3379                            new_text = new_text.repeat(2);
 3380                        }
 3381
 3382                        let anchor = buffer.anchor_after(end);
 3383                        let new_selection = selection.map(|_| anchor);
 3384                        (
 3385                            (start..end, new_text),
 3386                            (insert_extra_newline, new_selection),
 3387                        )
 3388                    })
 3389                    .unzip()
 3390            };
 3391
 3392            this.edit_with_autoindent(edits, cx);
 3393            let buffer = this.buffer.read(cx).snapshot(cx);
 3394            let new_selections = selection_fixup_info
 3395                .into_iter()
 3396                .map(|(extra_newline_inserted, new_selection)| {
 3397                    let mut cursor = new_selection.end.to_point(&buffer);
 3398                    if extra_newline_inserted {
 3399                        cursor.row -= 1;
 3400                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3401                    }
 3402                    new_selection.map(|_| cursor)
 3403                })
 3404                .collect();
 3405
 3406            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3407            this.refresh_inline_completion(true, cx);
 3408        });
 3409    }
 3410
 3411    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3412        let buffer = self.buffer.read(cx);
 3413        let snapshot = buffer.snapshot(cx);
 3414
 3415        let mut edits = Vec::new();
 3416        let mut rows = Vec::new();
 3417
 3418        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3419            let cursor = selection.head();
 3420            let row = cursor.row;
 3421
 3422            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3423
 3424            let newline = "\n".to_string();
 3425            edits.push((start_of_line..start_of_line, newline));
 3426
 3427            rows.push(row + rows_inserted as u32);
 3428        }
 3429
 3430        self.transact(cx, |editor, cx| {
 3431            editor.edit(edits, cx);
 3432
 3433            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3434                let mut index = 0;
 3435                s.move_cursors_with(|map, _, _| {
 3436                    let row = rows[index];
 3437                    index += 1;
 3438
 3439                    let point = Point::new(row, 0);
 3440                    let boundary = map.next_line_boundary(point).1;
 3441                    let clipped = map.clip_point(boundary, Bias::Left);
 3442
 3443                    (clipped, SelectionGoal::None)
 3444                });
 3445            });
 3446
 3447            let mut indent_edits = Vec::new();
 3448            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3449            for row in rows {
 3450                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3451                for (row, indent) in indents {
 3452                    if indent.len == 0 {
 3453                        continue;
 3454                    }
 3455
 3456                    let text = match indent.kind {
 3457                        IndentKind::Space => " ".repeat(indent.len as usize),
 3458                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3459                    };
 3460                    let point = Point::new(row.0, 0);
 3461                    indent_edits.push((point..point, text));
 3462                }
 3463            }
 3464            editor.edit(indent_edits, cx);
 3465        });
 3466    }
 3467
 3468    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3469        let buffer = self.buffer.read(cx);
 3470        let snapshot = buffer.snapshot(cx);
 3471
 3472        let mut edits = Vec::new();
 3473        let mut rows = Vec::new();
 3474        let mut rows_inserted = 0;
 3475
 3476        for selection in self.selections.all_adjusted(cx) {
 3477            let cursor = selection.head();
 3478            let row = cursor.row;
 3479
 3480            let point = Point::new(row + 1, 0);
 3481            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3482
 3483            let newline = "\n".to_string();
 3484            edits.push((start_of_line..start_of_line, newline));
 3485
 3486            rows_inserted += 1;
 3487            rows.push(row + rows_inserted);
 3488        }
 3489
 3490        self.transact(cx, |editor, cx| {
 3491            editor.edit(edits, cx);
 3492
 3493            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3494                let mut index = 0;
 3495                s.move_cursors_with(|map, _, _| {
 3496                    let row = rows[index];
 3497                    index += 1;
 3498
 3499                    let point = Point::new(row, 0);
 3500                    let boundary = map.next_line_boundary(point).1;
 3501                    let clipped = map.clip_point(boundary, Bias::Left);
 3502
 3503                    (clipped, SelectionGoal::None)
 3504                });
 3505            });
 3506
 3507            let mut indent_edits = Vec::new();
 3508            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3509            for row in rows {
 3510                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3511                for (row, indent) in indents {
 3512                    if indent.len == 0 {
 3513                        continue;
 3514                    }
 3515
 3516                    let text = match indent.kind {
 3517                        IndentKind::Space => " ".repeat(indent.len as usize),
 3518                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3519                    };
 3520                    let point = Point::new(row.0, 0);
 3521                    indent_edits.push((point..point, text));
 3522                }
 3523            }
 3524            editor.edit(indent_edits, cx);
 3525        });
 3526    }
 3527
 3528    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3529        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3530            original_indent_columns: Vec::new(),
 3531        });
 3532        self.insert_with_autoindent_mode(text, autoindent, cx);
 3533    }
 3534
 3535    fn insert_with_autoindent_mode(
 3536        &mut self,
 3537        text: &str,
 3538        autoindent_mode: Option<AutoindentMode>,
 3539        cx: &mut ViewContext<Self>,
 3540    ) {
 3541        if self.read_only(cx) {
 3542            return;
 3543        }
 3544
 3545        let text: Arc<str> = text.into();
 3546        self.transact(cx, |this, cx| {
 3547            let old_selections = this.selections.all_adjusted(cx);
 3548            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3549                let anchors = {
 3550                    let snapshot = buffer.read(cx);
 3551                    old_selections
 3552                        .iter()
 3553                        .map(|s| {
 3554                            let anchor = snapshot.anchor_after(s.head());
 3555                            s.map(|_| anchor)
 3556                        })
 3557                        .collect::<Vec<_>>()
 3558                };
 3559                buffer.edit(
 3560                    old_selections
 3561                        .iter()
 3562                        .map(|s| (s.start..s.end, text.clone())),
 3563                    autoindent_mode,
 3564                    cx,
 3565                );
 3566                anchors
 3567            });
 3568
 3569            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3570                s.select_anchors(selection_anchors);
 3571            })
 3572        });
 3573    }
 3574
 3575    fn trigger_completion_on_input(
 3576        &mut self,
 3577        text: &str,
 3578        trigger_in_words: bool,
 3579        cx: &mut ViewContext<Self>,
 3580    ) {
 3581        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3582            self.show_completions(
 3583                &ShowCompletions {
 3584                    trigger: text.chars().last(),
 3585                },
 3586                cx,
 3587            );
 3588        } else {
 3589            self.hide_context_menu(cx);
 3590        }
 3591    }
 3592
 3593    fn is_completion_trigger(
 3594        &self,
 3595        text: &str,
 3596        trigger_in_words: bool,
 3597        cx: &mut ViewContext<Self>,
 3598    ) -> bool {
 3599        let position = self.selections.newest_anchor().head();
 3600        let multibuffer = self.buffer.read(cx);
 3601        let Some(buffer) = position
 3602            .buffer_id
 3603            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3604        else {
 3605            return false;
 3606        };
 3607
 3608        if let Some(completion_provider) = &self.completion_provider {
 3609            completion_provider.is_completion_trigger(
 3610                &buffer,
 3611                position.text_anchor,
 3612                text,
 3613                trigger_in_words,
 3614                cx,
 3615            )
 3616        } else {
 3617            false
 3618        }
 3619    }
 3620
 3621    /// If any empty selections is touching the start of its innermost containing autoclose
 3622    /// region, expand it to select the brackets.
 3623    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3624        let selections = self.selections.all::<usize>(cx);
 3625        let buffer = self.buffer.read(cx).read(cx);
 3626        let new_selections = self
 3627            .selections_with_autoclose_regions(selections, &buffer)
 3628            .map(|(mut selection, region)| {
 3629                if !selection.is_empty() {
 3630                    return selection;
 3631                }
 3632
 3633                if let Some(region) = region {
 3634                    let mut range = region.range.to_offset(&buffer);
 3635                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3636                        range.start -= region.pair.start.len();
 3637                        if buffer.contains_str_at(range.start, &region.pair.start)
 3638                            && buffer.contains_str_at(range.end, &region.pair.end)
 3639                        {
 3640                            range.end += region.pair.end.len();
 3641                            selection.start = range.start;
 3642                            selection.end = range.end;
 3643
 3644                            return selection;
 3645                        }
 3646                    }
 3647                }
 3648
 3649                let always_treat_brackets_as_autoclosed = buffer
 3650                    .settings_at(selection.start, cx)
 3651                    .always_treat_brackets_as_autoclosed;
 3652
 3653                if !always_treat_brackets_as_autoclosed {
 3654                    return selection;
 3655                }
 3656
 3657                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3658                    for (pair, enabled) in scope.brackets() {
 3659                        if !enabled || !pair.close {
 3660                            continue;
 3661                        }
 3662
 3663                        if buffer.contains_str_at(selection.start, &pair.end) {
 3664                            let pair_start_len = pair.start.len();
 3665                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3666                            {
 3667                                selection.start -= pair_start_len;
 3668                                selection.end += pair.end.len();
 3669
 3670                                return selection;
 3671                            }
 3672                        }
 3673                    }
 3674                }
 3675
 3676                selection
 3677            })
 3678            .collect();
 3679
 3680        drop(buffer);
 3681        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3682    }
 3683
 3684    /// Iterate the given selections, and for each one, find the smallest surrounding
 3685    /// autoclose region. This uses the ordering of the selections and the autoclose
 3686    /// regions to avoid repeated comparisons.
 3687    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3688        &'a self,
 3689        selections: impl IntoIterator<Item = Selection<D>>,
 3690        buffer: &'a MultiBufferSnapshot,
 3691    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3692        let mut i = 0;
 3693        let mut regions = self.autoclose_regions.as_slice();
 3694        selections.into_iter().map(move |selection| {
 3695            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3696
 3697            let mut enclosing = None;
 3698            while let Some(pair_state) = regions.get(i) {
 3699                if pair_state.range.end.to_offset(buffer) < range.start {
 3700                    regions = &regions[i + 1..];
 3701                    i = 0;
 3702                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3703                    break;
 3704                } else {
 3705                    if pair_state.selection_id == selection.id {
 3706                        enclosing = Some(pair_state);
 3707                    }
 3708                    i += 1;
 3709                }
 3710            }
 3711
 3712            (selection.clone(), enclosing)
 3713        })
 3714    }
 3715
 3716    /// Remove any autoclose regions that no longer contain their selection.
 3717    fn invalidate_autoclose_regions(
 3718        &mut self,
 3719        mut selections: &[Selection<Anchor>],
 3720        buffer: &MultiBufferSnapshot,
 3721    ) {
 3722        self.autoclose_regions.retain(|state| {
 3723            let mut i = 0;
 3724            while let Some(selection) = selections.get(i) {
 3725                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3726                    selections = &selections[1..];
 3727                    continue;
 3728                }
 3729                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3730                    break;
 3731                }
 3732                if selection.id == state.selection_id {
 3733                    return true;
 3734                } else {
 3735                    i += 1;
 3736                }
 3737            }
 3738            false
 3739        });
 3740    }
 3741
 3742    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3743        let offset = position.to_offset(buffer);
 3744        let (word_range, kind) = buffer.surrounding_word(offset);
 3745        if offset > word_range.start && kind == Some(CharKind::Word) {
 3746            Some(
 3747                buffer
 3748                    .text_for_range(word_range.start..offset)
 3749                    .collect::<String>(),
 3750            )
 3751        } else {
 3752            None
 3753        }
 3754    }
 3755
 3756    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3757        self.refresh_inlay_hints(
 3758            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3759            cx,
 3760        );
 3761    }
 3762
 3763    pub fn inlay_hints_enabled(&self) -> bool {
 3764        self.inlay_hint_cache.enabled
 3765    }
 3766
 3767    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3768        if self.project.is_none() || self.mode != EditorMode::Full {
 3769            return;
 3770        }
 3771
 3772        let reason_description = reason.description();
 3773        let ignore_debounce = matches!(
 3774            reason,
 3775            InlayHintRefreshReason::SettingsChange(_)
 3776                | InlayHintRefreshReason::Toggle(_)
 3777                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3778        );
 3779        let (invalidate_cache, required_languages) = match reason {
 3780            InlayHintRefreshReason::Toggle(enabled) => {
 3781                self.inlay_hint_cache.enabled = enabled;
 3782                if enabled {
 3783                    (InvalidationStrategy::RefreshRequested, None)
 3784                } else {
 3785                    self.inlay_hint_cache.clear();
 3786                    self.splice_inlays(
 3787                        self.visible_inlay_hints(cx)
 3788                            .iter()
 3789                            .map(|inlay| inlay.id)
 3790                            .collect(),
 3791                        Vec::new(),
 3792                        cx,
 3793                    );
 3794                    return;
 3795                }
 3796            }
 3797            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3798                match self.inlay_hint_cache.update_settings(
 3799                    &self.buffer,
 3800                    new_settings,
 3801                    self.visible_inlay_hints(cx),
 3802                    cx,
 3803                ) {
 3804                    ControlFlow::Break(Some(InlaySplice {
 3805                        to_remove,
 3806                        to_insert,
 3807                    })) => {
 3808                        self.splice_inlays(to_remove, to_insert, cx);
 3809                        return;
 3810                    }
 3811                    ControlFlow::Break(None) => return,
 3812                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3813                }
 3814            }
 3815            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3816                if let Some(InlaySplice {
 3817                    to_remove,
 3818                    to_insert,
 3819                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3820                {
 3821                    self.splice_inlays(to_remove, to_insert, cx);
 3822                }
 3823                return;
 3824            }
 3825            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3826            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3827                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3828            }
 3829            InlayHintRefreshReason::RefreshRequested => {
 3830                (InvalidationStrategy::RefreshRequested, None)
 3831            }
 3832        };
 3833
 3834        if let Some(InlaySplice {
 3835            to_remove,
 3836            to_insert,
 3837        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3838            reason_description,
 3839            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3840            invalidate_cache,
 3841            ignore_debounce,
 3842            cx,
 3843        ) {
 3844            self.splice_inlays(to_remove, to_insert, cx);
 3845        }
 3846    }
 3847
 3848    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3849        self.display_map
 3850            .read(cx)
 3851            .current_inlays()
 3852            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3853            .cloned()
 3854            .collect()
 3855    }
 3856
 3857    pub fn excerpts_for_inlay_hints_query(
 3858        &self,
 3859        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3860        cx: &mut ViewContext<Editor>,
 3861    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3862        let Some(project) = self.project.as_ref() else {
 3863            return HashMap::default();
 3864        };
 3865        let project = project.read(cx);
 3866        let multi_buffer = self.buffer().read(cx);
 3867        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3868        let multi_buffer_visible_start = self
 3869            .scroll_manager
 3870            .anchor()
 3871            .anchor
 3872            .to_point(&multi_buffer_snapshot);
 3873        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3874            multi_buffer_visible_start
 3875                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3876            Bias::Left,
 3877        );
 3878        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3879        multi_buffer
 3880            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3881            .into_iter()
 3882            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3883            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3884                let buffer = buffer_handle.read(cx);
 3885                let buffer_file = project::File::from_dyn(buffer.file())?;
 3886                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3887                let worktree_entry = buffer_worktree
 3888                    .read(cx)
 3889                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3890                if worktree_entry.is_ignored {
 3891                    return None;
 3892                }
 3893
 3894                let language = buffer.language()?;
 3895                if let Some(restrict_to_languages) = restrict_to_languages {
 3896                    if !restrict_to_languages.contains(language) {
 3897                        return None;
 3898                    }
 3899                }
 3900                Some((
 3901                    excerpt_id,
 3902                    (
 3903                        buffer_handle,
 3904                        buffer.version().clone(),
 3905                        excerpt_visible_range,
 3906                    ),
 3907                ))
 3908            })
 3909            .collect()
 3910    }
 3911
 3912    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3913        TextLayoutDetails {
 3914            text_system: cx.text_system().clone(),
 3915            editor_style: self.style.clone().unwrap(),
 3916            rem_size: cx.rem_size(),
 3917            scroll_anchor: self.scroll_manager.anchor(),
 3918            visible_rows: self.visible_line_count(),
 3919            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3920        }
 3921    }
 3922
 3923    fn splice_inlays(
 3924        &self,
 3925        to_remove: Vec<InlayId>,
 3926        to_insert: Vec<Inlay>,
 3927        cx: &mut ViewContext<Self>,
 3928    ) {
 3929        self.display_map.update(cx, |display_map, cx| {
 3930            display_map.splice_inlays(to_remove, to_insert, cx);
 3931        });
 3932        cx.notify();
 3933    }
 3934
 3935    fn trigger_on_type_formatting(
 3936        &self,
 3937        input: String,
 3938        cx: &mut ViewContext<Self>,
 3939    ) -> Option<Task<Result<()>>> {
 3940        if input.len() != 1 {
 3941            return None;
 3942        }
 3943
 3944        let project = self.project.as_ref()?;
 3945        let position = self.selections.newest_anchor().head();
 3946        let (buffer, buffer_position) = self
 3947            .buffer
 3948            .read(cx)
 3949            .text_anchor_for_position(position, cx)?;
 3950
 3951        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3952        // hence we do LSP request & edit on host side only — add formats to host's history.
 3953        let push_to_lsp_host_history = true;
 3954        // If this is not the host, append its history with new edits.
 3955        let push_to_client_history = project.read(cx).is_remote();
 3956
 3957        let on_type_formatting = project.update(cx, |project, cx| {
 3958            project.on_type_format(
 3959                buffer.clone(),
 3960                buffer_position,
 3961                input,
 3962                push_to_lsp_host_history,
 3963                cx,
 3964            )
 3965        });
 3966        Some(cx.spawn(|editor, mut cx| async move {
 3967            if let Some(transaction) = on_type_formatting.await? {
 3968                if push_to_client_history {
 3969                    buffer
 3970                        .update(&mut cx, |buffer, _| {
 3971                            buffer.push_transaction(transaction, Instant::now());
 3972                        })
 3973                        .ok();
 3974                }
 3975                editor.update(&mut cx, |editor, cx| {
 3976                    editor.refresh_document_highlights(cx);
 3977                })?;
 3978            }
 3979            Ok(())
 3980        }))
 3981    }
 3982
 3983    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3984        if self.pending_rename.is_some() {
 3985            return;
 3986        }
 3987
 3988        let Some(provider) = self.completion_provider.as_ref() else {
 3989            return;
 3990        };
 3991
 3992        let position = self.selections.newest_anchor().head();
 3993        let (buffer, buffer_position) =
 3994            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3995                output
 3996            } else {
 3997                return;
 3998            };
 3999
 4000        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4001        let is_followup_invoke = {
 4002            let context_menu_state = self.context_menu.read();
 4003            matches!(
 4004                context_menu_state.deref(),
 4005                Some(ContextMenu::Completions(_))
 4006            )
 4007        };
 4008        let trigger_kind = match (options.trigger, is_followup_invoke) {
 4009            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4010            (Some(_), _) => CompletionTriggerKind::TRIGGER_CHARACTER,
 4011            _ => CompletionTriggerKind::INVOKED,
 4012        };
 4013        let completion_context = CompletionContext {
 4014            trigger_character: options.trigger.and_then(|c| {
 4015                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4016                    Some(String::from(c))
 4017                } else {
 4018                    None
 4019                }
 4020            }),
 4021            trigger_kind,
 4022        };
 4023        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4024
 4025        let id = post_inc(&mut self.next_completion_id);
 4026        let task = cx.spawn(|this, mut cx| {
 4027            async move {
 4028                this.update(&mut cx, |this, _| {
 4029                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4030                })?;
 4031                let completions = completions.await.log_err();
 4032                let menu = if let Some(completions) = completions {
 4033                    let mut menu = CompletionsMenu {
 4034                        id,
 4035                        initial_position: position,
 4036                        match_candidates: completions
 4037                            .iter()
 4038                            .enumerate()
 4039                            .map(|(id, completion)| {
 4040                                StringMatchCandidate::new(
 4041                                    id,
 4042                                    completion.label.text[completion.label.filter_range.clone()]
 4043                                        .into(),
 4044                                )
 4045                            })
 4046                            .collect(),
 4047                        buffer: buffer.clone(),
 4048                        completions: Arc::new(RwLock::new(completions.into())),
 4049                        matches: Vec::new().into(),
 4050                        selected_item: 0,
 4051                        scroll_handle: UniformListScrollHandle::new(),
 4052                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4053                            DebouncedDelay::new(),
 4054                        )),
 4055                    };
 4056                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4057                        .await;
 4058
 4059                    if menu.matches.is_empty() {
 4060                        None
 4061                    } else {
 4062                        this.update(&mut cx, |editor, cx| {
 4063                            let completions = menu.completions.clone();
 4064                            let matches = menu.matches.clone();
 4065
 4066                            let delay_ms = EditorSettings::get_global(cx)
 4067                                .completion_documentation_secondary_query_debounce;
 4068                            let delay = Duration::from_millis(delay_ms);
 4069                            editor
 4070                                .completion_documentation_pre_resolve_debounce
 4071                                .fire_new(delay, cx, |editor, cx| {
 4072                                    CompletionsMenu::pre_resolve_completion_documentation(
 4073                                        buffer,
 4074                                        completions,
 4075                                        matches,
 4076                                        editor,
 4077                                        cx,
 4078                                    )
 4079                                });
 4080                        })
 4081                        .ok();
 4082                        Some(menu)
 4083                    }
 4084                } else {
 4085                    None
 4086                };
 4087
 4088                this.update(&mut cx, |this, cx| {
 4089                    let mut context_menu = this.context_menu.write();
 4090                    match context_menu.as_ref() {
 4091                        None => {}
 4092
 4093                        Some(ContextMenu::Completions(prev_menu)) => {
 4094                            if prev_menu.id > id {
 4095                                return;
 4096                            }
 4097                        }
 4098
 4099                        _ => return,
 4100                    }
 4101
 4102                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4103                        let menu = menu.unwrap();
 4104                        *context_menu = Some(ContextMenu::Completions(menu));
 4105                        drop(context_menu);
 4106                        this.discard_inline_completion(false, cx);
 4107                        cx.notify();
 4108                    } else if this.completion_tasks.len() <= 1 {
 4109                        // If there are no more completion tasks and the last menu was
 4110                        // empty, we should hide it. If it was already hidden, we should
 4111                        // also show the copilot completion when available.
 4112                        drop(context_menu);
 4113                        if this.hide_context_menu(cx).is_none() {
 4114                            this.update_visible_inline_completion(cx);
 4115                        }
 4116                    }
 4117                })?;
 4118
 4119                Ok::<_, anyhow::Error>(())
 4120            }
 4121            .log_err()
 4122        });
 4123
 4124        self.completion_tasks.push((id, task));
 4125    }
 4126
 4127    pub fn confirm_completion(
 4128        &mut self,
 4129        action: &ConfirmCompletion,
 4130        cx: &mut ViewContext<Self>,
 4131    ) -> Option<Task<Result<()>>> {
 4132        use language::ToOffset as _;
 4133
 4134        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4135            menu
 4136        } else {
 4137            return None;
 4138        };
 4139
 4140        let mat = completions_menu
 4141            .matches
 4142            .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
 4143        let buffer_handle = completions_menu.buffer;
 4144        let completions = completions_menu.completions.read();
 4145        let completion = completions.get(mat.candidate_id)?;
 4146        cx.stop_propagation();
 4147
 4148        let snippet;
 4149        let text;
 4150
 4151        if completion.is_snippet() {
 4152            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4153            text = snippet.as_ref().unwrap().text.clone();
 4154        } else {
 4155            snippet = None;
 4156            text = completion.new_text.clone();
 4157        };
 4158        let selections = self.selections.all::<usize>(cx);
 4159        let buffer = buffer_handle.read(cx);
 4160        let old_range = completion.old_range.to_offset(buffer);
 4161        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4162
 4163        let newest_selection = self.selections.newest_anchor();
 4164        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4165            return None;
 4166        }
 4167
 4168        let lookbehind = newest_selection
 4169            .start
 4170            .text_anchor
 4171            .to_offset(buffer)
 4172            .saturating_sub(old_range.start);
 4173        let lookahead = old_range
 4174            .end
 4175            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4176        let mut common_prefix_len = old_text
 4177            .bytes()
 4178            .zip(text.bytes())
 4179            .take_while(|(a, b)| a == b)
 4180            .count();
 4181
 4182        let snapshot = self.buffer.read(cx).snapshot(cx);
 4183        let mut range_to_replace: Option<Range<isize>> = None;
 4184        let mut ranges = Vec::new();
 4185        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4186        for selection in &selections {
 4187            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4188                let start = selection.start.saturating_sub(lookbehind);
 4189                let end = selection.end + lookahead;
 4190                if selection.id == newest_selection.id {
 4191                    range_to_replace = Some(
 4192                        ((start + common_prefix_len) as isize - selection.start as isize)
 4193                            ..(end as isize - selection.start as isize),
 4194                    );
 4195                }
 4196                ranges.push(start + common_prefix_len..end);
 4197            } else {
 4198                common_prefix_len = 0;
 4199                ranges.clear();
 4200                ranges.extend(selections.iter().map(|s| {
 4201                    if s.id == newest_selection.id {
 4202                        range_to_replace = Some(
 4203                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4204                                - selection.start as isize
 4205                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4206                                    - selection.start as isize,
 4207                        );
 4208                        old_range.clone()
 4209                    } else {
 4210                        s.start..s.end
 4211                    }
 4212                }));
 4213                break;
 4214            }
 4215            if !self.linked_edit_ranges.is_empty() {
 4216                let start_anchor = snapshot.anchor_before(selection.head());
 4217                let end_anchor = snapshot.anchor_after(selection.tail());
 4218                if let Some(ranges) = self
 4219                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4220                {
 4221                    for (buffer, edits) in ranges {
 4222                        linked_edits.entry(buffer.clone()).or_default().extend(
 4223                            edits
 4224                                .into_iter()
 4225                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4226                        );
 4227                    }
 4228                }
 4229            }
 4230        }
 4231        let text = &text[common_prefix_len..];
 4232
 4233        cx.emit(EditorEvent::InputHandled {
 4234            utf16_range_to_replace: range_to_replace,
 4235            text: text.into(),
 4236        });
 4237
 4238        self.transact(cx, |this, cx| {
 4239            if let Some(mut snippet) = snippet {
 4240                snippet.text = text.to_string();
 4241                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4242                    tabstop.start -= common_prefix_len as isize;
 4243                    tabstop.end -= common_prefix_len as isize;
 4244                }
 4245
 4246                this.insert_snippet(&ranges, snippet, cx).log_err();
 4247            } else {
 4248                this.buffer.update(cx, |buffer, cx| {
 4249                    buffer.edit(
 4250                        ranges.iter().map(|range| (range.clone(), text)),
 4251                        this.autoindent_mode.clone(),
 4252                        cx,
 4253                    );
 4254                });
 4255            }
 4256            for (buffer, edits) in linked_edits {
 4257                buffer.update(cx, |buffer, cx| {
 4258                    let snapshot = buffer.snapshot();
 4259                    let edits = edits
 4260                        .into_iter()
 4261                        .map(|(range, text)| {
 4262                            use text::ToPoint as TP;
 4263                            let end_point = TP::to_point(&range.end, &snapshot);
 4264                            let start_point = TP::to_point(&range.start, &snapshot);
 4265                            (start_point..end_point, text)
 4266                        })
 4267                        .sorted_by_key(|(range, _)| range.start)
 4268                        .collect::<Vec<_>>();
 4269                    buffer.edit(edits, None, cx);
 4270                })
 4271            }
 4272
 4273            this.refresh_inline_completion(true, cx);
 4274        });
 4275
 4276        if let Some(confirm) = completion.confirm.as_ref() {
 4277            (confirm)(cx);
 4278        }
 4279
 4280        if completion.show_new_completions_on_confirm {
 4281            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4282        }
 4283
 4284        let provider = self.completion_provider.as_ref()?;
 4285        let apply_edits = provider.apply_additional_edits_for_completion(
 4286            buffer_handle,
 4287            completion.clone(),
 4288            true,
 4289            cx,
 4290        );
 4291        Some(cx.foreground_executor().spawn(async move {
 4292            apply_edits.await?;
 4293            Ok(())
 4294        }))
 4295    }
 4296
 4297    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4298        let mut context_menu = self.context_menu.write();
 4299        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4300            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4301                // Toggle if we're selecting the same one
 4302                *context_menu = None;
 4303                cx.notify();
 4304                return;
 4305            } else {
 4306                // Otherwise, clear it and start a new one
 4307                *context_menu = None;
 4308                cx.notify();
 4309            }
 4310        }
 4311        drop(context_menu);
 4312        let snapshot = self.snapshot(cx);
 4313        let deployed_from_indicator = action.deployed_from_indicator;
 4314        let mut task = self.code_actions_task.take();
 4315        let action = action.clone();
 4316        cx.spawn(|editor, mut cx| async move {
 4317            while let Some(prev_task) = task {
 4318                prev_task.await;
 4319                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4320            }
 4321
 4322            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4323                if editor.focus_handle.is_focused(cx) {
 4324                    let multibuffer_point = action
 4325                        .deployed_from_indicator
 4326                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4327                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4328                    let (buffer, buffer_row) = snapshot
 4329                        .buffer_snapshot
 4330                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4331                        .and_then(|(buffer_snapshot, range)| {
 4332                            editor
 4333                                .buffer
 4334                                .read(cx)
 4335                                .buffer(buffer_snapshot.remote_id())
 4336                                .map(|buffer| (buffer, range.start.row))
 4337                        })?;
 4338                    let (_, code_actions) = editor
 4339                        .available_code_actions
 4340                        .clone()
 4341                        .and_then(|(location, code_actions)| {
 4342                            let snapshot = location.buffer.read(cx).snapshot();
 4343                            let point_range = location.range.to_point(&snapshot);
 4344                            let point_range = point_range.start.row..=point_range.end.row;
 4345                            if point_range.contains(&buffer_row) {
 4346                                Some((location, code_actions))
 4347                            } else {
 4348                                None
 4349                            }
 4350                        })
 4351                        .unzip();
 4352                    let buffer_id = buffer.read(cx).remote_id();
 4353                    let tasks = editor
 4354                        .tasks
 4355                        .get(&(buffer_id, buffer_row))
 4356                        .map(|t| Arc::new(t.to_owned()));
 4357                    if tasks.is_none() && code_actions.is_none() {
 4358                        return None;
 4359                    }
 4360
 4361                    editor.completion_tasks.clear();
 4362                    editor.discard_inline_completion(false, cx);
 4363                    let task_context =
 4364                        tasks
 4365                            .as_ref()
 4366                            .zip(editor.project.clone())
 4367                            .map(|(tasks, project)| {
 4368                                let position = Point::new(buffer_row, tasks.column);
 4369                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4370                                let location = Location {
 4371                                    buffer: buffer.clone(),
 4372                                    range: range_start..range_start,
 4373                                };
 4374                                // Fill in the environmental variables from the tree-sitter captures
 4375                                let mut captured_task_variables = TaskVariables::default();
 4376                                for (capture_name, value) in tasks.extra_variables.clone() {
 4377                                    captured_task_variables.insert(
 4378                                        task::VariableName::Custom(capture_name.into()),
 4379                                        value.clone(),
 4380                                    );
 4381                                }
 4382                                project.update(cx, |project, cx| {
 4383                                    project.task_context_for_location(
 4384                                        captured_task_variables,
 4385                                        location,
 4386                                        cx,
 4387                                    )
 4388                                })
 4389                            });
 4390
 4391                    Some(cx.spawn(|editor, mut cx| async move {
 4392                        let task_context = match task_context {
 4393                            Some(task_context) => task_context.await,
 4394                            None => None,
 4395                        };
 4396                        let resolved_tasks =
 4397                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4398                                Arc::new(ResolvedTasks {
 4399                                    templates: tasks
 4400                                        .templates
 4401                                        .iter()
 4402                                        .filter_map(|(kind, template)| {
 4403                                            template
 4404                                                .resolve_task(&kind.to_id_base(), &task_context)
 4405                                                .map(|task| (kind.clone(), task))
 4406                                        })
 4407                                        .collect(),
 4408                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4409                                        multibuffer_point.row,
 4410                                        tasks.column,
 4411                                    )),
 4412                                })
 4413                            });
 4414                        let spawn_straight_away = resolved_tasks
 4415                            .as_ref()
 4416                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4417                            && code_actions
 4418                                .as_ref()
 4419                                .map_or(true, |actions| actions.is_empty());
 4420                        if let Some(task) = editor
 4421                            .update(&mut cx, |editor, cx| {
 4422                                *editor.context_menu.write() =
 4423                                    Some(ContextMenu::CodeActions(CodeActionsMenu {
 4424                                        buffer,
 4425                                        actions: CodeActionContents {
 4426                                            tasks: resolved_tasks,
 4427                                            actions: code_actions,
 4428                                        },
 4429                                        selected_item: Default::default(),
 4430                                        scroll_handle: UniformListScrollHandle::default(),
 4431                                        deployed_from_indicator,
 4432                                    }));
 4433                                if spawn_straight_away {
 4434                                    if let Some(task) = editor.confirm_code_action(
 4435                                        &ConfirmCodeAction { item_ix: Some(0) },
 4436                                        cx,
 4437                                    ) {
 4438                                        cx.notify();
 4439                                        return task;
 4440                                    }
 4441                                }
 4442                                cx.notify();
 4443                                Task::ready(Ok(()))
 4444                            })
 4445                            .ok()
 4446                        {
 4447                            task.await
 4448                        } else {
 4449                            Ok(())
 4450                        }
 4451                    }))
 4452                } else {
 4453                    Some(Task::ready(Ok(())))
 4454                }
 4455            })?;
 4456            if let Some(task) = spawned_test_task {
 4457                task.await?;
 4458            }
 4459
 4460            Ok::<_, anyhow::Error>(())
 4461        })
 4462        .detach_and_log_err(cx);
 4463    }
 4464
 4465    pub fn confirm_code_action(
 4466        &mut self,
 4467        action: &ConfirmCodeAction,
 4468        cx: &mut ViewContext<Self>,
 4469    ) -> Option<Task<Result<()>>> {
 4470        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4471            menu
 4472        } else {
 4473            return None;
 4474        };
 4475        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4476        let action = actions_menu.actions.get(action_ix)?;
 4477        let title = action.label();
 4478        let buffer = actions_menu.buffer;
 4479        let workspace = self.workspace()?;
 4480
 4481        match action {
 4482            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4483                workspace.update(cx, |workspace, cx| {
 4484                    workspace::tasks::schedule_resolved_task(
 4485                        workspace,
 4486                        task_source_kind,
 4487                        resolved_task,
 4488                        false,
 4489                        cx,
 4490                    );
 4491
 4492                    Some(Task::ready(Ok(())))
 4493                })
 4494            }
 4495            CodeActionsItem::CodeAction(action) => {
 4496                let apply_code_actions = workspace
 4497                    .read(cx)
 4498                    .project()
 4499                    .clone()
 4500                    .update(cx, |project, cx| {
 4501                        project.apply_code_action(buffer, action, true, cx)
 4502                    });
 4503                let workspace = workspace.downgrade();
 4504                Some(cx.spawn(|editor, cx| async move {
 4505                    let project_transaction = apply_code_actions.await?;
 4506                    Self::open_project_transaction(
 4507                        &editor,
 4508                        workspace,
 4509                        project_transaction,
 4510                        title,
 4511                        cx,
 4512                    )
 4513                    .await
 4514                }))
 4515            }
 4516        }
 4517    }
 4518
 4519    pub async fn open_project_transaction(
 4520        this: &WeakView<Editor>,
 4521        workspace: WeakView<Workspace>,
 4522        transaction: ProjectTransaction,
 4523        title: String,
 4524        mut cx: AsyncWindowContext,
 4525    ) -> Result<()> {
 4526        let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
 4527
 4528        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4529        cx.update(|cx| {
 4530            entries.sort_unstable_by_key(|(buffer, _)| {
 4531                buffer.read(cx).file().map(|f| f.path().clone())
 4532            });
 4533        })?;
 4534
 4535        // If the project transaction's edits are all contained within this editor, then
 4536        // avoid opening a new editor to display them.
 4537
 4538        if let Some((buffer, transaction)) = entries.first() {
 4539            if entries.len() == 1 {
 4540                let excerpt = this.update(&mut cx, |editor, cx| {
 4541                    editor
 4542                        .buffer()
 4543                        .read(cx)
 4544                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4545                })?;
 4546                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4547                    if excerpted_buffer == *buffer {
 4548                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4549                            let excerpt_range = excerpt_range.to_offset(buffer);
 4550                            buffer
 4551                                .edited_ranges_for_transaction::<usize>(transaction)
 4552                                .all(|range| {
 4553                                    excerpt_range.start <= range.start
 4554                                        && excerpt_range.end >= range.end
 4555                                })
 4556                        })?;
 4557
 4558                        if all_edits_within_excerpt {
 4559                            return Ok(());
 4560                        }
 4561                    }
 4562                }
 4563            }
 4564        } else {
 4565            return Ok(());
 4566        }
 4567
 4568        let mut ranges_to_highlight = Vec::new();
 4569        let excerpt_buffer = cx.new_model(|cx| {
 4570            let mut multibuffer =
 4571                MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
 4572            for (buffer_handle, transaction) in &entries {
 4573                let buffer = buffer_handle.read(cx);
 4574                ranges_to_highlight.extend(
 4575                    multibuffer.push_excerpts_with_context_lines(
 4576                        buffer_handle.clone(),
 4577                        buffer
 4578                            .edited_ranges_for_transaction::<usize>(transaction)
 4579                            .collect(),
 4580                        DEFAULT_MULTIBUFFER_CONTEXT,
 4581                        cx,
 4582                    ),
 4583                );
 4584            }
 4585            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4586            multibuffer
 4587        })?;
 4588
 4589        workspace.update(&mut cx, |workspace, cx| {
 4590            let project = workspace.project().clone();
 4591            let editor =
 4592                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4593            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, cx);
 4594            editor.update(cx, |editor, cx| {
 4595                editor.highlight_background::<Self>(
 4596                    &ranges_to_highlight,
 4597                    |theme| theme.editor_highlighted_line_background,
 4598                    cx,
 4599                );
 4600            });
 4601        })?;
 4602
 4603        Ok(())
 4604    }
 4605
 4606    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4607        let project = self.project.clone()?;
 4608        let buffer = self.buffer.read(cx);
 4609        let newest_selection = self.selections.newest_anchor().clone();
 4610        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4611        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4612        if start_buffer != end_buffer {
 4613            return None;
 4614        }
 4615
 4616        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4617            cx.background_executor()
 4618                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4619                .await;
 4620
 4621            let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
 4622                project.code_actions(&start_buffer, start..end, cx)
 4623            }) {
 4624                code_actions.await
 4625            } else {
 4626                Vec::new()
 4627            };
 4628
 4629            this.update(&mut cx, |this, cx| {
 4630                this.available_code_actions = if actions.is_empty() {
 4631                    None
 4632                } else {
 4633                    Some((
 4634                        Location {
 4635                            buffer: start_buffer,
 4636                            range: start..end,
 4637                        },
 4638                        actions.into(),
 4639                    ))
 4640                };
 4641                cx.notify();
 4642            })
 4643            .log_err();
 4644        }));
 4645        None
 4646    }
 4647
 4648    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4649        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4650            self.show_git_blame_inline = false;
 4651
 4652            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4653                cx.background_executor().timer(delay).await;
 4654
 4655                this.update(&mut cx, |this, cx| {
 4656                    this.show_git_blame_inline = true;
 4657                    cx.notify();
 4658                })
 4659                .log_err();
 4660            }));
 4661        }
 4662    }
 4663
 4664    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4665        if self.pending_rename.is_some() {
 4666            return None;
 4667        }
 4668
 4669        let project = self.project.clone()?;
 4670        let buffer = self.buffer.read(cx);
 4671        let newest_selection = self.selections.newest_anchor().clone();
 4672        let cursor_position = newest_selection.head();
 4673        let (cursor_buffer, cursor_buffer_position) =
 4674            buffer.text_anchor_for_position(cursor_position, cx)?;
 4675        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4676        if cursor_buffer != tail_buffer {
 4677            return None;
 4678        }
 4679
 4680        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4681            cx.background_executor()
 4682                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 4683                .await;
 4684
 4685            let highlights = if let Some(highlights) = project
 4686                .update(&mut cx, |project, cx| {
 4687                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4688                })
 4689                .log_err()
 4690            {
 4691                highlights.await.log_err()
 4692            } else {
 4693                None
 4694            };
 4695
 4696            if let Some(highlights) = highlights {
 4697                this.update(&mut cx, |this, cx| {
 4698                    if this.pending_rename.is_some() {
 4699                        return;
 4700                    }
 4701
 4702                    let buffer_id = cursor_position.buffer_id;
 4703                    let buffer = this.buffer.read(cx);
 4704                    if !buffer
 4705                        .text_anchor_for_position(cursor_position, cx)
 4706                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4707                    {
 4708                        return;
 4709                    }
 4710
 4711                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4712                    let mut write_ranges = Vec::new();
 4713                    let mut read_ranges = Vec::new();
 4714                    for highlight in highlights {
 4715                        for (excerpt_id, excerpt_range) in
 4716                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4717                        {
 4718                            let start = highlight
 4719                                .range
 4720                                .start
 4721                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4722                            let end = highlight
 4723                                .range
 4724                                .end
 4725                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4726                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4727                                continue;
 4728                            }
 4729
 4730                            let range = Anchor {
 4731                                buffer_id,
 4732                                excerpt_id: excerpt_id,
 4733                                text_anchor: start,
 4734                            }..Anchor {
 4735                                buffer_id,
 4736                                excerpt_id,
 4737                                text_anchor: end,
 4738                            };
 4739                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4740                                write_ranges.push(range);
 4741                            } else {
 4742                                read_ranges.push(range);
 4743                            }
 4744                        }
 4745                    }
 4746
 4747                    this.highlight_background::<DocumentHighlightRead>(
 4748                        &read_ranges,
 4749                        |theme| theme.editor_document_highlight_read_background,
 4750                        cx,
 4751                    );
 4752                    this.highlight_background::<DocumentHighlightWrite>(
 4753                        &write_ranges,
 4754                        |theme| theme.editor_document_highlight_write_background,
 4755                        cx,
 4756                    );
 4757                    cx.notify();
 4758                })
 4759                .log_err();
 4760            }
 4761        }));
 4762        None
 4763    }
 4764
 4765    fn refresh_inline_completion(
 4766        &mut self,
 4767        debounce: bool,
 4768        cx: &mut ViewContext<Self>,
 4769    ) -> Option<()> {
 4770        let provider = self.inline_completion_provider()?;
 4771        let cursor = self.selections.newest_anchor().head();
 4772        let (buffer, cursor_buffer_position) =
 4773            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4774        if !self.show_inline_completions
 4775            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4776        {
 4777            self.discard_inline_completion(false, cx);
 4778            return None;
 4779        }
 4780
 4781        self.update_visible_inline_completion(cx);
 4782        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4783        Some(())
 4784    }
 4785
 4786    fn cycle_inline_completion(
 4787        &mut self,
 4788        direction: Direction,
 4789        cx: &mut ViewContext<Self>,
 4790    ) -> Option<()> {
 4791        let provider = self.inline_completion_provider()?;
 4792        let cursor = self.selections.newest_anchor().head();
 4793        let (buffer, cursor_buffer_position) =
 4794            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4795        if !self.show_inline_completions
 4796            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4797        {
 4798            return None;
 4799        }
 4800
 4801        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4802        self.update_visible_inline_completion(cx);
 4803
 4804        Some(())
 4805    }
 4806
 4807    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4808        if !self.has_active_inline_completion(cx) {
 4809            self.refresh_inline_completion(false, cx);
 4810            return;
 4811        }
 4812
 4813        self.update_visible_inline_completion(cx);
 4814    }
 4815
 4816    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4817        self.show_cursor_names(cx);
 4818    }
 4819
 4820    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4821        self.show_cursor_names = true;
 4822        cx.notify();
 4823        cx.spawn(|this, mut cx| async move {
 4824            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4825            this.update(&mut cx, |this, cx| {
 4826                this.show_cursor_names = false;
 4827                cx.notify()
 4828            })
 4829            .ok()
 4830        })
 4831        .detach();
 4832    }
 4833
 4834    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4835        if self.has_active_inline_completion(cx) {
 4836            self.cycle_inline_completion(Direction::Next, cx);
 4837        } else {
 4838            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4839            if is_copilot_disabled {
 4840                cx.propagate();
 4841            }
 4842        }
 4843    }
 4844
 4845    pub fn previous_inline_completion(
 4846        &mut self,
 4847        _: &PreviousInlineCompletion,
 4848        cx: &mut ViewContext<Self>,
 4849    ) {
 4850        if self.has_active_inline_completion(cx) {
 4851            self.cycle_inline_completion(Direction::Prev, cx);
 4852        } else {
 4853            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4854            if is_copilot_disabled {
 4855                cx.propagate();
 4856            }
 4857        }
 4858    }
 4859
 4860    pub fn accept_inline_completion(
 4861        &mut self,
 4862        _: &AcceptInlineCompletion,
 4863        cx: &mut ViewContext<Self>,
 4864    ) {
 4865        let Some(completion) = self.take_active_inline_completion(cx) else {
 4866            return;
 4867        };
 4868        if let Some(provider) = self.inline_completion_provider() {
 4869            provider.accept(cx);
 4870        }
 4871
 4872        cx.emit(EditorEvent::InputHandled {
 4873            utf16_range_to_replace: None,
 4874            text: completion.text.to_string().into(),
 4875        });
 4876        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 4877        self.refresh_inline_completion(true, cx);
 4878        cx.notify();
 4879    }
 4880
 4881    pub fn accept_partial_inline_completion(
 4882        &mut self,
 4883        _: &AcceptPartialInlineCompletion,
 4884        cx: &mut ViewContext<Self>,
 4885    ) {
 4886        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 4887            if let Some(completion) = self.take_active_inline_completion(cx) {
 4888                let mut partial_completion = completion
 4889                    .text
 4890                    .chars()
 4891                    .by_ref()
 4892                    .take_while(|c| c.is_alphabetic())
 4893                    .collect::<String>();
 4894                if partial_completion.is_empty() {
 4895                    partial_completion = completion
 4896                        .text
 4897                        .chars()
 4898                        .by_ref()
 4899                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4900                        .collect::<String>();
 4901                }
 4902
 4903                cx.emit(EditorEvent::InputHandled {
 4904                    utf16_range_to_replace: None,
 4905                    text: partial_completion.clone().into(),
 4906                });
 4907                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4908                self.refresh_inline_completion(true, cx);
 4909                cx.notify();
 4910            }
 4911        }
 4912    }
 4913
 4914    fn discard_inline_completion(
 4915        &mut self,
 4916        should_report_inline_completion_event: bool,
 4917        cx: &mut ViewContext<Self>,
 4918    ) -> bool {
 4919        if let Some(provider) = self.inline_completion_provider() {
 4920            provider.discard(should_report_inline_completion_event, cx);
 4921        }
 4922
 4923        self.take_active_inline_completion(cx).is_some()
 4924    }
 4925
 4926    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 4927        if let Some(completion) = self.active_inline_completion.as_ref() {
 4928            let buffer = self.buffer.read(cx).read(cx);
 4929            completion.position.is_valid(&buffer)
 4930        } else {
 4931            false
 4932        }
 4933    }
 4934
 4935    fn take_active_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
 4936        let completion = self.active_inline_completion.take()?;
 4937        self.display_map.update(cx, |map, cx| {
 4938            map.splice_inlays(vec![completion.id], Default::default(), cx);
 4939        });
 4940        let buffer = self.buffer.read(cx).read(cx);
 4941
 4942        if completion.position.is_valid(&buffer) {
 4943            Some(completion)
 4944        } else {
 4945            None
 4946        }
 4947    }
 4948
 4949    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 4950        let selection = self.selections.newest_anchor();
 4951        let cursor = selection.head();
 4952
 4953        if self.context_menu.read().is_none()
 4954            && self.completion_tasks.is_empty()
 4955            && selection.start == selection.end
 4956        {
 4957            if let Some(provider) = self.inline_completion_provider() {
 4958                if let Some((buffer, cursor_buffer_position)) =
 4959                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4960                {
 4961                    if let Some(text) =
 4962                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 4963                    {
 4964                        let text = Rope::from(text);
 4965                        let mut to_remove = Vec::new();
 4966                        if let Some(completion) = self.active_inline_completion.take() {
 4967                            to_remove.push(completion.id);
 4968                        }
 4969
 4970                        let completion_inlay =
 4971                            Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
 4972                        self.active_inline_completion = Some(completion_inlay.clone());
 4973                        self.display_map.update(cx, move |map, cx| {
 4974                            map.splice_inlays(to_remove, vec![completion_inlay], cx)
 4975                        });
 4976                        cx.notify();
 4977                        return;
 4978                    }
 4979                }
 4980            }
 4981        }
 4982
 4983        self.discard_inline_completion(false, cx);
 4984    }
 4985
 4986    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4987        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4988    }
 4989
 4990    fn render_code_actions_indicator(
 4991        &self,
 4992        _style: &EditorStyle,
 4993        row: DisplayRow,
 4994        is_active: bool,
 4995        cx: &mut ViewContext<Self>,
 4996    ) -> Option<IconButton> {
 4997        if self.available_code_actions.is_some() {
 4998            Some(
 4999                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5000                    .shape(ui::IconButtonShape::Square)
 5001                    .icon_size(IconSize::XSmall)
 5002                    .icon_color(Color::Muted)
 5003                    .selected(is_active)
 5004                    .on_click(cx.listener(move |editor, _e, cx| {
 5005                        editor.focus(cx);
 5006                        editor.toggle_code_actions(
 5007                            &ToggleCodeActions {
 5008                                deployed_from_indicator: Some(row),
 5009                            },
 5010                            cx,
 5011                        );
 5012                    })),
 5013            )
 5014        } else {
 5015            None
 5016        }
 5017    }
 5018
 5019    fn clear_tasks(&mut self) {
 5020        self.tasks.clear()
 5021    }
 5022
 5023    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5024        if let Some(_) = self.tasks.insert(key, value) {
 5025            // This case should hopefully be rare, but just in case...
 5026            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5027        }
 5028    }
 5029
 5030    fn render_run_indicator(
 5031        &self,
 5032        _style: &EditorStyle,
 5033        is_active: bool,
 5034        row: DisplayRow,
 5035        cx: &mut ViewContext<Self>,
 5036    ) -> IconButton {
 5037        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5038            .shape(ui::IconButtonShape::Square)
 5039            .icon_size(IconSize::XSmall)
 5040            .icon_color(Color::Muted)
 5041            .selected(is_active)
 5042            .on_click(cx.listener(move |editor, _e, cx| {
 5043                editor.focus(cx);
 5044                editor.toggle_code_actions(
 5045                    &ToggleCodeActions {
 5046                        deployed_from_indicator: Some(row),
 5047                    },
 5048                    cx,
 5049                );
 5050            }))
 5051    }
 5052
 5053    pub fn context_menu_visible(&self) -> bool {
 5054        self.context_menu
 5055            .read()
 5056            .as_ref()
 5057            .map_or(false, |menu| menu.visible())
 5058    }
 5059
 5060    fn render_context_menu(
 5061        &self,
 5062        cursor_position: DisplayPoint,
 5063        style: &EditorStyle,
 5064        max_height: Pixels,
 5065        cx: &mut ViewContext<Editor>,
 5066    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5067        self.context_menu.read().as_ref().map(|menu| {
 5068            menu.render(
 5069                cursor_position,
 5070                style,
 5071                max_height,
 5072                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5073                cx,
 5074            )
 5075        })
 5076    }
 5077
 5078    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5079        cx.notify();
 5080        self.completion_tasks.clear();
 5081        let context_menu = self.context_menu.write().take();
 5082        if context_menu.is_some() {
 5083            self.update_visible_inline_completion(cx);
 5084        }
 5085        context_menu
 5086    }
 5087
 5088    pub fn insert_snippet(
 5089        &mut self,
 5090        insertion_ranges: &[Range<usize>],
 5091        snippet: Snippet,
 5092        cx: &mut ViewContext<Self>,
 5093    ) -> Result<()> {
 5094        struct Tabstop<T> {
 5095            is_end_tabstop: bool,
 5096            ranges: Vec<Range<T>>,
 5097        }
 5098
 5099        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5100            let snippet_text: Arc<str> = snippet.text.clone().into();
 5101            buffer.edit(
 5102                insertion_ranges
 5103                    .iter()
 5104                    .cloned()
 5105                    .map(|range| (range, snippet_text.clone())),
 5106                Some(AutoindentMode::EachLine),
 5107                cx,
 5108            );
 5109
 5110            let snapshot = &*buffer.read(cx);
 5111            let snippet = &snippet;
 5112            snippet
 5113                .tabstops
 5114                .iter()
 5115                .map(|tabstop| {
 5116                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5117                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5118                    });
 5119                    let mut tabstop_ranges = tabstop
 5120                        .iter()
 5121                        .flat_map(|tabstop_range| {
 5122                            let mut delta = 0_isize;
 5123                            insertion_ranges.iter().map(move |insertion_range| {
 5124                                let insertion_start = insertion_range.start as isize + delta;
 5125                                delta +=
 5126                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5127
 5128                                let start = ((insertion_start + tabstop_range.start) as usize)
 5129                                    .min(snapshot.len());
 5130                                let end = ((insertion_start + tabstop_range.end) as usize)
 5131                                    .min(snapshot.len());
 5132                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5133                            })
 5134                        })
 5135                        .collect::<Vec<_>>();
 5136                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5137
 5138                    Tabstop {
 5139                        is_end_tabstop,
 5140                        ranges: tabstop_ranges,
 5141                    }
 5142                })
 5143                .collect::<Vec<_>>()
 5144        });
 5145
 5146        if let Some(tabstop) = tabstops.first() {
 5147            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5148                s.select_ranges(tabstop.ranges.iter().cloned());
 5149            });
 5150
 5151            // If we're already at the last tabstop and it's at the end of the snippet,
 5152            // we're done, we don't need to keep the state around.
 5153            if !tabstop.is_end_tabstop {
 5154                let ranges = tabstops
 5155                    .into_iter()
 5156                    .map(|tabstop| tabstop.ranges)
 5157                    .collect::<Vec<_>>();
 5158                self.snippet_stack.push(SnippetState {
 5159                    active_index: 0,
 5160                    ranges,
 5161                });
 5162            }
 5163
 5164            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5165            if self.autoclose_regions.is_empty() {
 5166                let snapshot = self.buffer.read(cx).snapshot(cx);
 5167                for selection in &mut self.selections.all::<Point>(cx) {
 5168                    let selection_head = selection.head();
 5169                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5170                        continue;
 5171                    };
 5172
 5173                    let mut bracket_pair = None;
 5174                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5175                    let prev_chars = snapshot
 5176                        .reversed_chars_at(selection_head)
 5177                        .collect::<String>();
 5178                    for (pair, enabled) in scope.brackets() {
 5179                        if enabled
 5180                            && pair.close
 5181                            && prev_chars.starts_with(pair.start.as_str())
 5182                            && next_chars.starts_with(pair.end.as_str())
 5183                        {
 5184                            bracket_pair = Some(pair.clone());
 5185                            break;
 5186                        }
 5187                    }
 5188                    if let Some(pair) = bracket_pair {
 5189                        let start = snapshot.anchor_after(selection_head);
 5190                        let end = snapshot.anchor_after(selection_head);
 5191                        self.autoclose_regions.push(AutocloseRegion {
 5192                            selection_id: selection.id,
 5193                            range: start..end,
 5194                            pair,
 5195                        });
 5196                    }
 5197                }
 5198            }
 5199        }
 5200        Ok(())
 5201    }
 5202
 5203    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5204        self.move_to_snippet_tabstop(Bias::Right, cx)
 5205    }
 5206
 5207    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5208        self.move_to_snippet_tabstop(Bias::Left, cx)
 5209    }
 5210
 5211    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5212        if let Some(mut snippet) = self.snippet_stack.pop() {
 5213            match bias {
 5214                Bias::Left => {
 5215                    if snippet.active_index > 0 {
 5216                        snippet.active_index -= 1;
 5217                    } else {
 5218                        self.snippet_stack.push(snippet);
 5219                        return false;
 5220                    }
 5221                }
 5222                Bias::Right => {
 5223                    if snippet.active_index + 1 < snippet.ranges.len() {
 5224                        snippet.active_index += 1;
 5225                    } else {
 5226                        self.snippet_stack.push(snippet);
 5227                        return false;
 5228                    }
 5229                }
 5230            }
 5231            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5232                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5233                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5234                });
 5235                // If snippet state is not at the last tabstop, push it back on the stack
 5236                if snippet.active_index + 1 < snippet.ranges.len() {
 5237                    self.snippet_stack.push(snippet);
 5238                }
 5239                return true;
 5240            }
 5241        }
 5242
 5243        false
 5244    }
 5245
 5246    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5247        self.transact(cx, |this, cx| {
 5248            this.select_all(&SelectAll, cx);
 5249            this.insert("", cx);
 5250        });
 5251    }
 5252
 5253    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5254        self.transact(cx, |this, cx| {
 5255            this.select_autoclose_pair(cx);
 5256            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5257            if !this.linked_edit_ranges.is_empty() {
 5258                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5259                let snapshot = this.buffer.read(cx).snapshot(cx);
 5260
 5261                for selection in selections.iter() {
 5262                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5263                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5264                    if selection_start.buffer_id != selection_end.buffer_id {
 5265                        continue;
 5266                    }
 5267                    if let Some(ranges) =
 5268                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5269                    {
 5270                        for (buffer, entries) in ranges {
 5271                            linked_ranges.entry(buffer).or_default().extend(entries);
 5272                        }
 5273                    }
 5274                }
 5275            }
 5276
 5277            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5278            if !this.selections.line_mode {
 5279                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5280                for selection in &mut selections {
 5281                    if selection.is_empty() {
 5282                        let old_head = selection.head();
 5283                        let mut new_head =
 5284                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5285                                .to_point(&display_map);
 5286                        if let Some((buffer, line_buffer_range)) = display_map
 5287                            .buffer_snapshot
 5288                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5289                        {
 5290                            let indent_size =
 5291                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5292                            let indent_len = match indent_size.kind {
 5293                                IndentKind::Space => {
 5294                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5295                                }
 5296                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5297                            };
 5298                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5299                                let indent_len = indent_len.get();
 5300                                new_head = cmp::min(
 5301                                    new_head,
 5302                                    MultiBufferPoint::new(
 5303                                        old_head.row,
 5304                                        ((old_head.column - 1) / indent_len) * indent_len,
 5305                                    ),
 5306                                );
 5307                            }
 5308                        }
 5309
 5310                        selection.set_head(new_head, SelectionGoal::None);
 5311                    }
 5312                }
 5313            }
 5314
 5315            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5316            this.insert("", cx);
 5317            let empty_str: Arc<str> = Arc::from("");
 5318            for (buffer, edits) in linked_ranges {
 5319                let snapshot = buffer.read(cx).snapshot();
 5320                use text::ToPoint as TP;
 5321
 5322                let edits = edits
 5323                    .into_iter()
 5324                    .map(|range| {
 5325                        let end_point = TP::to_point(&range.end, &snapshot);
 5326                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5327
 5328                        if end_point == start_point {
 5329                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5330                                .saturating_sub(1);
 5331                            start_point = TP::to_point(&offset, &snapshot);
 5332                        };
 5333
 5334                        (start_point..end_point, empty_str.clone())
 5335                    })
 5336                    .sorted_by_key(|(range, _)| range.start)
 5337                    .collect::<Vec<_>>();
 5338                buffer.update(cx, |this, cx| {
 5339                    this.edit(edits, None, cx);
 5340                })
 5341            }
 5342            this.refresh_inline_completion(true, cx);
 5343            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5344        });
 5345    }
 5346
 5347    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5348        self.transact(cx, |this, cx| {
 5349            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5350                let line_mode = s.line_mode;
 5351                s.move_with(|map, selection| {
 5352                    if selection.is_empty() && !line_mode {
 5353                        let cursor = movement::right(map, selection.head());
 5354                        selection.end = cursor;
 5355                        selection.reversed = true;
 5356                        selection.goal = SelectionGoal::None;
 5357                    }
 5358                })
 5359            });
 5360            this.insert("", cx);
 5361            this.refresh_inline_completion(true, cx);
 5362        });
 5363    }
 5364
 5365    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5366        if self.move_to_prev_snippet_tabstop(cx) {
 5367            return;
 5368        }
 5369
 5370        self.outdent(&Outdent, cx);
 5371    }
 5372
 5373    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5374        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5375            return;
 5376        }
 5377
 5378        let mut selections = self.selections.all_adjusted(cx);
 5379        let buffer = self.buffer.read(cx);
 5380        let snapshot = buffer.snapshot(cx);
 5381        let rows_iter = selections.iter().map(|s| s.head().row);
 5382        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5383
 5384        let mut edits = Vec::new();
 5385        let mut prev_edited_row = 0;
 5386        let mut row_delta = 0;
 5387        for selection in &mut selections {
 5388            if selection.start.row != prev_edited_row {
 5389                row_delta = 0;
 5390            }
 5391            prev_edited_row = selection.end.row;
 5392
 5393            // If the selection is non-empty, then increase the indentation of the selected lines.
 5394            if !selection.is_empty() {
 5395                row_delta =
 5396                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5397                continue;
 5398            }
 5399
 5400            // If the selection is empty and the cursor is in the leading whitespace before the
 5401            // suggested indentation, then auto-indent the line.
 5402            let cursor = selection.head();
 5403            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5404            if let Some(suggested_indent) =
 5405                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5406            {
 5407                if cursor.column < suggested_indent.len
 5408                    && cursor.column <= current_indent.len
 5409                    && current_indent.len <= suggested_indent.len
 5410                {
 5411                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5412                    selection.end = selection.start;
 5413                    if row_delta == 0 {
 5414                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5415                            cursor.row,
 5416                            current_indent,
 5417                            suggested_indent,
 5418                        ));
 5419                        row_delta = suggested_indent.len - current_indent.len;
 5420                    }
 5421                    continue;
 5422                }
 5423            }
 5424
 5425            // Otherwise, insert a hard or soft tab.
 5426            let settings = buffer.settings_at(cursor, cx);
 5427            let tab_size = if settings.hard_tabs {
 5428                IndentSize::tab()
 5429            } else {
 5430                let tab_size = settings.tab_size.get();
 5431                let char_column = snapshot
 5432                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5433                    .flat_map(str::chars)
 5434                    .count()
 5435                    + row_delta as usize;
 5436                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5437                IndentSize::spaces(chars_to_next_tab_stop)
 5438            };
 5439            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5440            selection.end = selection.start;
 5441            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5442            row_delta += tab_size.len;
 5443        }
 5444
 5445        self.transact(cx, |this, cx| {
 5446            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5447            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5448            this.refresh_inline_completion(true, cx);
 5449        });
 5450    }
 5451
 5452    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5453        if self.read_only(cx) {
 5454            return;
 5455        }
 5456        let mut selections = self.selections.all::<Point>(cx);
 5457        let mut prev_edited_row = 0;
 5458        let mut row_delta = 0;
 5459        let mut edits = Vec::new();
 5460        let buffer = self.buffer.read(cx);
 5461        let snapshot = buffer.snapshot(cx);
 5462        for selection in &mut selections {
 5463            if selection.start.row != prev_edited_row {
 5464                row_delta = 0;
 5465            }
 5466            prev_edited_row = selection.end.row;
 5467
 5468            row_delta =
 5469                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5470        }
 5471
 5472        self.transact(cx, |this, cx| {
 5473            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5474            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5475        });
 5476    }
 5477
 5478    fn indent_selection(
 5479        buffer: &MultiBuffer,
 5480        snapshot: &MultiBufferSnapshot,
 5481        selection: &mut Selection<Point>,
 5482        edits: &mut Vec<(Range<Point>, String)>,
 5483        delta_for_start_row: u32,
 5484        cx: &AppContext,
 5485    ) -> u32 {
 5486        let settings = buffer.settings_at(selection.start, cx);
 5487        let tab_size = settings.tab_size.get();
 5488        let indent_kind = if settings.hard_tabs {
 5489            IndentKind::Tab
 5490        } else {
 5491            IndentKind::Space
 5492        };
 5493        let mut start_row = selection.start.row;
 5494        let mut end_row = selection.end.row + 1;
 5495
 5496        // If a selection ends at the beginning of a line, don't indent
 5497        // that last line.
 5498        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5499            end_row -= 1;
 5500        }
 5501
 5502        // Avoid re-indenting a row that has already been indented by a
 5503        // previous selection, but still update this selection's column
 5504        // to reflect that indentation.
 5505        if delta_for_start_row > 0 {
 5506            start_row += 1;
 5507            selection.start.column += delta_for_start_row;
 5508            if selection.end.row == selection.start.row {
 5509                selection.end.column += delta_for_start_row;
 5510            }
 5511        }
 5512
 5513        let mut delta_for_end_row = 0;
 5514        let has_multiple_rows = start_row + 1 != end_row;
 5515        for row in start_row..end_row {
 5516            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5517            let indent_delta = match (current_indent.kind, indent_kind) {
 5518                (IndentKind::Space, IndentKind::Space) => {
 5519                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5520                    IndentSize::spaces(columns_to_next_tab_stop)
 5521                }
 5522                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5523                (_, IndentKind::Tab) => IndentSize::tab(),
 5524            };
 5525
 5526            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5527                0
 5528            } else {
 5529                selection.start.column
 5530            };
 5531            let row_start = Point::new(row, start);
 5532            edits.push((
 5533                row_start..row_start,
 5534                indent_delta.chars().collect::<String>(),
 5535            ));
 5536
 5537            // Update this selection's endpoints to reflect the indentation.
 5538            if row == selection.start.row {
 5539                selection.start.column += indent_delta.len;
 5540            }
 5541            if row == selection.end.row {
 5542                selection.end.column += indent_delta.len;
 5543                delta_for_end_row = indent_delta.len;
 5544            }
 5545        }
 5546
 5547        if selection.start.row == selection.end.row {
 5548            delta_for_start_row + delta_for_end_row
 5549        } else {
 5550            delta_for_end_row
 5551        }
 5552    }
 5553
 5554    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5555        if self.read_only(cx) {
 5556            return;
 5557        }
 5558        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5559        let selections = self.selections.all::<Point>(cx);
 5560        let mut deletion_ranges = Vec::new();
 5561        let mut last_outdent = None;
 5562        {
 5563            let buffer = self.buffer.read(cx);
 5564            let snapshot = buffer.snapshot(cx);
 5565            for selection in &selections {
 5566                let settings = buffer.settings_at(selection.start, cx);
 5567                let tab_size = settings.tab_size.get();
 5568                let mut rows = selection.spanned_rows(false, &display_map);
 5569
 5570                // Avoid re-outdenting a row that has already been outdented by a
 5571                // previous selection.
 5572                if let Some(last_row) = last_outdent {
 5573                    if last_row == rows.start {
 5574                        rows.start = rows.start.next_row();
 5575                    }
 5576                }
 5577                let has_multiple_rows = rows.len() > 1;
 5578                for row in rows.iter_rows() {
 5579                    let indent_size = snapshot.indent_size_for_line(row);
 5580                    if indent_size.len > 0 {
 5581                        let deletion_len = match indent_size.kind {
 5582                            IndentKind::Space => {
 5583                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5584                                if columns_to_prev_tab_stop == 0 {
 5585                                    tab_size
 5586                                } else {
 5587                                    columns_to_prev_tab_stop
 5588                                }
 5589                            }
 5590                            IndentKind::Tab => 1,
 5591                        };
 5592                        let start = if has_multiple_rows
 5593                            || deletion_len > selection.start.column
 5594                            || indent_size.len < selection.start.column
 5595                        {
 5596                            0
 5597                        } else {
 5598                            selection.start.column - deletion_len
 5599                        };
 5600                        deletion_ranges.push(
 5601                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5602                        );
 5603                        last_outdent = Some(row);
 5604                    }
 5605                }
 5606            }
 5607        }
 5608
 5609        self.transact(cx, |this, cx| {
 5610            this.buffer.update(cx, |buffer, cx| {
 5611                let empty_str: Arc<str> = "".into();
 5612                buffer.edit(
 5613                    deletion_ranges
 5614                        .into_iter()
 5615                        .map(|range| (range, empty_str.clone())),
 5616                    None,
 5617                    cx,
 5618                );
 5619            });
 5620            let selections = this.selections.all::<usize>(cx);
 5621            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5622        });
 5623    }
 5624
 5625    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5626        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5627        let selections = self.selections.all::<Point>(cx);
 5628
 5629        let mut new_cursors = Vec::new();
 5630        let mut edit_ranges = Vec::new();
 5631        let mut selections = selections.iter().peekable();
 5632        while let Some(selection) = selections.next() {
 5633            let mut rows = selection.spanned_rows(false, &display_map);
 5634            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5635
 5636            // Accumulate contiguous regions of rows that we want to delete.
 5637            while let Some(next_selection) = selections.peek() {
 5638                let next_rows = next_selection.spanned_rows(false, &display_map);
 5639                if next_rows.start <= rows.end {
 5640                    rows.end = next_rows.end;
 5641                    selections.next().unwrap();
 5642                } else {
 5643                    break;
 5644                }
 5645            }
 5646
 5647            let buffer = &display_map.buffer_snapshot;
 5648            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5649            let edit_end;
 5650            let cursor_buffer_row;
 5651            if buffer.max_point().row >= rows.end.0 {
 5652                // If there's a line after the range, delete the \n from the end of the row range
 5653                // and position the cursor on the next line.
 5654                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5655                cursor_buffer_row = rows.end;
 5656            } else {
 5657                // If there isn't a line after the range, delete the \n from the line before the
 5658                // start of the row range and position the cursor there.
 5659                edit_start = edit_start.saturating_sub(1);
 5660                edit_end = buffer.len();
 5661                cursor_buffer_row = rows.start.previous_row();
 5662            }
 5663
 5664            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5665            *cursor.column_mut() =
 5666                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5667
 5668            new_cursors.push((
 5669                selection.id,
 5670                buffer.anchor_after(cursor.to_point(&display_map)),
 5671            ));
 5672            edit_ranges.push(edit_start..edit_end);
 5673        }
 5674
 5675        self.transact(cx, |this, cx| {
 5676            let buffer = this.buffer.update(cx, |buffer, cx| {
 5677                let empty_str: Arc<str> = "".into();
 5678                buffer.edit(
 5679                    edit_ranges
 5680                        .into_iter()
 5681                        .map(|range| (range, empty_str.clone())),
 5682                    None,
 5683                    cx,
 5684                );
 5685                buffer.snapshot(cx)
 5686            });
 5687            let new_selections = new_cursors
 5688                .into_iter()
 5689                .map(|(id, cursor)| {
 5690                    let cursor = cursor.to_point(&buffer);
 5691                    Selection {
 5692                        id,
 5693                        start: cursor,
 5694                        end: cursor,
 5695                        reversed: false,
 5696                        goal: SelectionGoal::None,
 5697                    }
 5698                })
 5699                .collect();
 5700
 5701            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5702                s.select(new_selections);
 5703            });
 5704        });
 5705    }
 5706
 5707    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5708        if self.read_only(cx) {
 5709            return;
 5710        }
 5711        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5712        for selection in self.selections.all::<Point>(cx) {
 5713            let start = MultiBufferRow(selection.start.row);
 5714            let end = if selection.start.row == selection.end.row {
 5715                MultiBufferRow(selection.start.row + 1)
 5716            } else {
 5717                MultiBufferRow(selection.end.row)
 5718            };
 5719
 5720            if let Some(last_row_range) = row_ranges.last_mut() {
 5721                if start <= last_row_range.end {
 5722                    last_row_range.end = end;
 5723                    continue;
 5724                }
 5725            }
 5726            row_ranges.push(start..end);
 5727        }
 5728
 5729        let snapshot = self.buffer.read(cx).snapshot(cx);
 5730        let mut cursor_positions = Vec::new();
 5731        for row_range in &row_ranges {
 5732            let anchor = snapshot.anchor_before(Point::new(
 5733                row_range.end.previous_row().0,
 5734                snapshot.line_len(row_range.end.previous_row()),
 5735            ));
 5736            cursor_positions.push(anchor..anchor);
 5737        }
 5738
 5739        self.transact(cx, |this, cx| {
 5740            for row_range in row_ranges.into_iter().rev() {
 5741                for row in row_range.iter_rows().rev() {
 5742                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5743                    let next_line_row = row.next_row();
 5744                    let indent = snapshot.indent_size_for_line(next_line_row);
 5745                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5746
 5747                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5748                        " "
 5749                    } else {
 5750                        ""
 5751                    };
 5752
 5753                    this.buffer.update(cx, |buffer, cx| {
 5754                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5755                    });
 5756                }
 5757            }
 5758
 5759            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5760                s.select_anchor_ranges(cursor_positions)
 5761            });
 5762        });
 5763    }
 5764
 5765    pub fn sort_lines_case_sensitive(
 5766        &mut self,
 5767        _: &SortLinesCaseSensitive,
 5768        cx: &mut ViewContext<Self>,
 5769    ) {
 5770        self.manipulate_lines(cx, |lines| lines.sort())
 5771    }
 5772
 5773    pub fn sort_lines_case_insensitive(
 5774        &mut self,
 5775        _: &SortLinesCaseInsensitive,
 5776        cx: &mut ViewContext<Self>,
 5777    ) {
 5778        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5779    }
 5780
 5781    pub fn unique_lines_case_insensitive(
 5782        &mut self,
 5783        _: &UniqueLinesCaseInsensitive,
 5784        cx: &mut ViewContext<Self>,
 5785    ) {
 5786        self.manipulate_lines(cx, |lines| {
 5787            let mut seen = HashSet::default();
 5788            lines.retain(|line| seen.insert(line.to_lowercase()));
 5789        })
 5790    }
 5791
 5792    pub fn unique_lines_case_sensitive(
 5793        &mut self,
 5794        _: &UniqueLinesCaseSensitive,
 5795        cx: &mut ViewContext<Self>,
 5796    ) {
 5797        self.manipulate_lines(cx, |lines| {
 5798            let mut seen = HashSet::default();
 5799            lines.retain(|line| seen.insert(*line));
 5800        })
 5801    }
 5802
 5803    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5804        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 5805        if !revert_changes.is_empty() {
 5806            self.transact(cx, |editor, cx| {
 5807                editor.buffer().update(cx, |multi_buffer, cx| {
 5808                    for (buffer_id, changes) in revert_changes {
 5809                        if let Some(buffer) = multi_buffer.buffer(buffer_id) {
 5810                            buffer.update(cx, |buffer, cx| {
 5811                                buffer.edit(
 5812                                    changes.into_iter().map(|(range, text)| {
 5813                                        (range, text.to_string().map(Arc::<str>::from))
 5814                                    }),
 5815                                    None,
 5816                                    cx,
 5817                                );
 5818                            });
 5819                        }
 5820                    }
 5821                });
 5822                editor.change_selections(None, cx, |selections| selections.refresh());
 5823            });
 5824        }
 5825    }
 5826
 5827    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5828        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5829            let project_path = buffer.read(cx).project_path(cx)?;
 5830            let project = self.project.as_ref()?.read(cx);
 5831            let entry = project.entry_for_path(&project_path, cx)?;
 5832            let abs_path = project.absolute_path(&project_path, cx)?;
 5833            let parent = if entry.is_symlink {
 5834                abs_path.canonicalize().ok()?
 5835            } else {
 5836                abs_path
 5837            }
 5838            .parent()?
 5839            .to_path_buf();
 5840            Some(parent)
 5841        }) {
 5842            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5843        }
 5844    }
 5845
 5846    fn gather_revert_changes(
 5847        &mut self,
 5848        selections: &[Selection<Anchor>],
 5849        cx: &mut ViewContext<'_, Editor>,
 5850    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 5851        let mut revert_changes = HashMap::default();
 5852        self.buffer.update(cx, |multi_buffer, cx| {
 5853            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 5854            for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 5855                Self::prepare_revert_change(&mut revert_changes, &multi_buffer, &hunk, cx);
 5856            }
 5857        });
 5858        revert_changes
 5859    }
 5860
 5861    fn prepare_revert_change(
 5862        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 5863        multi_buffer: &MultiBuffer,
 5864        hunk: &DiffHunk<MultiBufferRow>,
 5865        cx: &mut AppContext,
 5866    ) -> Option<()> {
 5867        let buffer = multi_buffer.buffer(hunk.buffer_id)?;
 5868        let buffer = buffer.read(cx);
 5869        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 5870        let buffer_snapshot = buffer.snapshot();
 5871        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5872        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5873            probe
 5874                .0
 5875                .start
 5876                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5877                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5878        }) {
 5879            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 5880            Some(())
 5881        } else {
 5882            None
 5883        }
 5884    }
 5885
 5886    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5887        self.manipulate_lines(cx, |lines| lines.reverse())
 5888    }
 5889
 5890    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5891        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5892    }
 5893
 5894    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5895    where
 5896        Fn: FnMut(&mut Vec<&str>),
 5897    {
 5898        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5899        let buffer = self.buffer.read(cx).snapshot(cx);
 5900
 5901        let mut edits = Vec::new();
 5902
 5903        let selections = self.selections.all::<Point>(cx);
 5904        let mut selections = selections.iter().peekable();
 5905        let mut contiguous_row_selections = Vec::new();
 5906        let mut new_selections = Vec::new();
 5907        let mut added_lines = 0;
 5908        let mut removed_lines = 0;
 5909
 5910        while let Some(selection) = selections.next() {
 5911            let (start_row, end_row) = consume_contiguous_rows(
 5912                &mut contiguous_row_selections,
 5913                selection,
 5914                &display_map,
 5915                &mut selections,
 5916            );
 5917
 5918            let start_point = Point::new(start_row.0, 0);
 5919            let end_point = Point::new(
 5920                end_row.previous_row().0,
 5921                buffer.line_len(end_row.previous_row()),
 5922            );
 5923            let text = buffer
 5924                .text_for_range(start_point..end_point)
 5925                .collect::<String>();
 5926
 5927            let mut lines = text.split('\n').collect_vec();
 5928
 5929            let lines_before = lines.len();
 5930            callback(&mut lines);
 5931            let lines_after = lines.len();
 5932
 5933            edits.push((start_point..end_point, lines.join("\n")));
 5934
 5935            // Selections must change based on added and removed line count
 5936            let start_row =
 5937                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 5938            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 5939            new_selections.push(Selection {
 5940                id: selection.id,
 5941                start: start_row,
 5942                end: end_row,
 5943                goal: SelectionGoal::None,
 5944                reversed: selection.reversed,
 5945            });
 5946
 5947            if lines_after > lines_before {
 5948                added_lines += lines_after - lines_before;
 5949            } else if lines_before > lines_after {
 5950                removed_lines += lines_before - lines_after;
 5951            }
 5952        }
 5953
 5954        self.transact(cx, |this, cx| {
 5955            let buffer = this.buffer.update(cx, |buffer, cx| {
 5956                buffer.edit(edits, None, cx);
 5957                buffer.snapshot(cx)
 5958            });
 5959
 5960            // Recalculate offsets on newly edited buffer
 5961            let new_selections = new_selections
 5962                .iter()
 5963                .map(|s| {
 5964                    let start_point = Point::new(s.start.0, 0);
 5965                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 5966                    Selection {
 5967                        id: s.id,
 5968                        start: buffer.point_to_offset(start_point),
 5969                        end: buffer.point_to_offset(end_point),
 5970                        goal: s.goal,
 5971                        reversed: s.reversed,
 5972                    }
 5973                })
 5974                .collect();
 5975
 5976            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5977                s.select(new_selections);
 5978            });
 5979
 5980            this.request_autoscroll(Autoscroll::fit(), cx);
 5981        });
 5982    }
 5983
 5984    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 5985        self.manipulate_text(cx, |text| text.to_uppercase())
 5986    }
 5987
 5988    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 5989        self.manipulate_text(cx, |text| text.to_lowercase())
 5990    }
 5991
 5992    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 5993        self.manipulate_text(cx, |text| {
 5994            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 5995            // https://github.com/rutrum/convert-case/issues/16
 5996            text.split('\n')
 5997                .map(|line| line.to_case(Case::Title))
 5998                .join("\n")
 5999        })
 6000    }
 6001
 6002    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6003        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6004    }
 6005
 6006    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6007        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6008    }
 6009
 6010    pub fn convert_to_upper_camel_case(
 6011        &mut self,
 6012        _: &ConvertToUpperCamelCase,
 6013        cx: &mut ViewContext<Self>,
 6014    ) {
 6015        self.manipulate_text(cx, |text| {
 6016            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6017            // https://github.com/rutrum/convert-case/issues/16
 6018            text.split('\n')
 6019                .map(|line| line.to_case(Case::UpperCamel))
 6020                .join("\n")
 6021        })
 6022    }
 6023
 6024    pub fn convert_to_lower_camel_case(
 6025        &mut self,
 6026        _: &ConvertToLowerCamelCase,
 6027        cx: &mut ViewContext<Self>,
 6028    ) {
 6029        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6030    }
 6031
 6032    pub fn convert_to_opposite_case(
 6033        &mut self,
 6034        _: &ConvertToOppositeCase,
 6035        cx: &mut ViewContext<Self>,
 6036    ) {
 6037        self.manipulate_text(cx, |text| {
 6038            text.chars()
 6039                .fold(String::with_capacity(text.len()), |mut t, c| {
 6040                    if c.is_uppercase() {
 6041                        t.extend(c.to_lowercase());
 6042                    } else {
 6043                        t.extend(c.to_uppercase());
 6044                    }
 6045                    t
 6046                })
 6047        })
 6048    }
 6049
 6050    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6051    where
 6052        Fn: FnMut(&str) -> String,
 6053    {
 6054        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6055        let buffer = self.buffer.read(cx).snapshot(cx);
 6056
 6057        let mut new_selections = Vec::new();
 6058        let mut edits = Vec::new();
 6059        let mut selection_adjustment = 0i32;
 6060
 6061        for selection in self.selections.all::<usize>(cx) {
 6062            let selection_is_empty = selection.is_empty();
 6063
 6064            let (start, end) = if selection_is_empty {
 6065                let word_range = movement::surrounding_word(
 6066                    &display_map,
 6067                    selection.start.to_display_point(&display_map),
 6068                );
 6069                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6070                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6071                (start, end)
 6072            } else {
 6073                (selection.start, selection.end)
 6074            };
 6075
 6076            let text = buffer.text_for_range(start..end).collect::<String>();
 6077            let old_length = text.len() as i32;
 6078            let text = callback(&text);
 6079
 6080            new_selections.push(Selection {
 6081                start: (start as i32 - selection_adjustment) as usize,
 6082                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6083                goal: SelectionGoal::None,
 6084                ..selection
 6085            });
 6086
 6087            selection_adjustment += old_length - text.len() as i32;
 6088
 6089            edits.push((start..end, text));
 6090        }
 6091
 6092        self.transact(cx, |this, cx| {
 6093            this.buffer.update(cx, |buffer, cx| {
 6094                buffer.edit(edits, None, cx);
 6095            });
 6096
 6097            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6098                s.select(new_selections);
 6099            });
 6100
 6101            this.request_autoscroll(Autoscroll::fit(), cx);
 6102        });
 6103    }
 6104
 6105    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6106        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6107        let buffer = &display_map.buffer_snapshot;
 6108        let selections = self.selections.all::<Point>(cx);
 6109
 6110        let mut edits = Vec::new();
 6111        let mut selections_iter = selections.iter().peekable();
 6112        while let Some(selection) = selections_iter.next() {
 6113            // Avoid duplicating the same lines twice.
 6114            let mut rows = selection.spanned_rows(false, &display_map);
 6115
 6116            while let Some(next_selection) = selections_iter.peek() {
 6117                let next_rows = next_selection.spanned_rows(false, &display_map);
 6118                if next_rows.start < rows.end {
 6119                    rows.end = next_rows.end;
 6120                    selections_iter.next().unwrap();
 6121                } else {
 6122                    break;
 6123                }
 6124            }
 6125
 6126            // Copy the text from the selected row region and splice it either at the start
 6127            // or end of the region.
 6128            let start = Point::new(rows.start.0, 0);
 6129            let end = Point::new(
 6130                rows.end.previous_row().0,
 6131                buffer.line_len(rows.end.previous_row()),
 6132            );
 6133            let text = buffer
 6134                .text_for_range(start..end)
 6135                .chain(Some("\n"))
 6136                .collect::<String>();
 6137            let insert_location = if upwards {
 6138                Point::new(rows.end.0, 0)
 6139            } else {
 6140                start
 6141            };
 6142            edits.push((insert_location..insert_location, text));
 6143        }
 6144
 6145        self.transact(cx, |this, cx| {
 6146            this.buffer.update(cx, |buffer, cx| {
 6147                buffer.edit(edits, None, cx);
 6148            });
 6149
 6150            this.request_autoscroll(Autoscroll::fit(), cx);
 6151        });
 6152    }
 6153
 6154    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6155        self.duplicate_line(true, cx);
 6156    }
 6157
 6158    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6159        self.duplicate_line(false, cx);
 6160    }
 6161
 6162    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6163        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6164        let buffer = self.buffer.read(cx).snapshot(cx);
 6165
 6166        let mut edits = Vec::new();
 6167        let mut unfold_ranges = Vec::new();
 6168        let mut refold_ranges = Vec::new();
 6169
 6170        let selections = self.selections.all::<Point>(cx);
 6171        let mut selections = selections.iter().peekable();
 6172        let mut contiguous_row_selections = Vec::new();
 6173        let mut new_selections = Vec::new();
 6174
 6175        while let Some(selection) = selections.next() {
 6176            // Find all the selections that span a contiguous row range
 6177            let (start_row, end_row) = consume_contiguous_rows(
 6178                &mut contiguous_row_selections,
 6179                selection,
 6180                &display_map,
 6181                &mut selections,
 6182            );
 6183
 6184            // Move the text spanned by the row range to be before the line preceding the row range
 6185            if start_row.0 > 0 {
 6186                let range_to_move = Point::new(
 6187                    start_row.previous_row().0,
 6188                    buffer.line_len(start_row.previous_row()),
 6189                )
 6190                    ..Point::new(
 6191                        end_row.previous_row().0,
 6192                        buffer.line_len(end_row.previous_row()),
 6193                    );
 6194                let insertion_point = display_map
 6195                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6196                    .0;
 6197
 6198                // Don't move lines across excerpts
 6199                if buffer
 6200                    .excerpt_boundaries_in_range((
 6201                        Bound::Excluded(insertion_point),
 6202                        Bound::Included(range_to_move.end),
 6203                    ))
 6204                    .next()
 6205                    .is_none()
 6206                {
 6207                    let text = buffer
 6208                        .text_for_range(range_to_move.clone())
 6209                        .flat_map(|s| s.chars())
 6210                        .skip(1)
 6211                        .chain(['\n'])
 6212                        .collect::<String>();
 6213
 6214                    edits.push((
 6215                        buffer.anchor_after(range_to_move.start)
 6216                            ..buffer.anchor_before(range_to_move.end),
 6217                        String::new(),
 6218                    ));
 6219                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6220                    edits.push((insertion_anchor..insertion_anchor, text));
 6221
 6222                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6223
 6224                    // Move selections up
 6225                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6226                        |mut selection| {
 6227                            selection.start.row -= row_delta;
 6228                            selection.end.row -= row_delta;
 6229                            selection
 6230                        },
 6231                    ));
 6232
 6233                    // Move folds up
 6234                    unfold_ranges.push(range_to_move.clone());
 6235                    for fold in display_map.folds_in_range(
 6236                        buffer.anchor_before(range_to_move.start)
 6237                            ..buffer.anchor_after(range_to_move.end),
 6238                    ) {
 6239                        let mut start = fold.range.start.to_point(&buffer);
 6240                        let mut end = fold.range.end.to_point(&buffer);
 6241                        start.row -= row_delta;
 6242                        end.row -= row_delta;
 6243                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6244                    }
 6245                }
 6246            }
 6247
 6248            // If we didn't move line(s), preserve the existing selections
 6249            new_selections.append(&mut contiguous_row_selections);
 6250        }
 6251
 6252        self.transact(cx, |this, cx| {
 6253            this.unfold_ranges(unfold_ranges, true, true, cx);
 6254            this.buffer.update(cx, |buffer, cx| {
 6255                for (range, text) in edits {
 6256                    buffer.edit([(range, text)], None, cx);
 6257                }
 6258            });
 6259            this.fold_ranges(refold_ranges, true, cx);
 6260            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6261                s.select(new_selections);
 6262            })
 6263        });
 6264    }
 6265
 6266    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6267        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6268        let buffer = self.buffer.read(cx).snapshot(cx);
 6269
 6270        let mut edits = Vec::new();
 6271        let mut unfold_ranges = Vec::new();
 6272        let mut refold_ranges = Vec::new();
 6273
 6274        let selections = self.selections.all::<Point>(cx);
 6275        let mut selections = selections.iter().peekable();
 6276        let mut contiguous_row_selections = Vec::new();
 6277        let mut new_selections = Vec::new();
 6278
 6279        while let Some(selection) = selections.next() {
 6280            // Find all the selections that span a contiguous row range
 6281            let (start_row, end_row) = consume_contiguous_rows(
 6282                &mut contiguous_row_selections,
 6283                selection,
 6284                &display_map,
 6285                &mut selections,
 6286            );
 6287
 6288            // Move the text spanned by the row range to be after the last line of the row range
 6289            if end_row.0 <= buffer.max_point().row {
 6290                let range_to_move =
 6291                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6292                let insertion_point = display_map
 6293                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6294                    .0;
 6295
 6296                // Don't move lines across excerpt boundaries
 6297                if buffer
 6298                    .excerpt_boundaries_in_range((
 6299                        Bound::Excluded(range_to_move.start),
 6300                        Bound::Included(insertion_point),
 6301                    ))
 6302                    .next()
 6303                    .is_none()
 6304                {
 6305                    let mut text = String::from("\n");
 6306                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6307                    text.pop(); // Drop trailing newline
 6308                    edits.push((
 6309                        buffer.anchor_after(range_to_move.start)
 6310                            ..buffer.anchor_before(range_to_move.end),
 6311                        String::new(),
 6312                    ));
 6313                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6314                    edits.push((insertion_anchor..insertion_anchor, text));
 6315
 6316                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6317
 6318                    // Move selections down
 6319                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6320                        |mut selection| {
 6321                            selection.start.row += row_delta;
 6322                            selection.end.row += row_delta;
 6323                            selection
 6324                        },
 6325                    ));
 6326
 6327                    // Move folds down
 6328                    unfold_ranges.push(range_to_move.clone());
 6329                    for fold in display_map.folds_in_range(
 6330                        buffer.anchor_before(range_to_move.start)
 6331                            ..buffer.anchor_after(range_to_move.end),
 6332                    ) {
 6333                        let mut start = fold.range.start.to_point(&buffer);
 6334                        let mut end = fold.range.end.to_point(&buffer);
 6335                        start.row += row_delta;
 6336                        end.row += row_delta;
 6337                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6338                    }
 6339                }
 6340            }
 6341
 6342            // If we didn't move line(s), preserve the existing selections
 6343            new_selections.append(&mut contiguous_row_selections);
 6344        }
 6345
 6346        self.transact(cx, |this, cx| {
 6347            this.unfold_ranges(unfold_ranges, true, true, cx);
 6348            this.buffer.update(cx, |buffer, cx| {
 6349                for (range, text) in edits {
 6350                    buffer.edit([(range, text)], None, cx);
 6351                }
 6352            });
 6353            this.fold_ranges(refold_ranges, true, cx);
 6354            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6355        });
 6356    }
 6357
 6358    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6359        let text_layout_details = &self.text_layout_details(cx);
 6360        self.transact(cx, |this, cx| {
 6361            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6362                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6363                let line_mode = s.line_mode;
 6364                s.move_with(|display_map, selection| {
 6365                    if !selection.is_empty() || line_mode {
 6366                        return;
 6367                    }
 6368
 6369                    let mut head = selection.head();
 6370                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6371                    if head.column() == display_map.line_len(head.row()) {
 6372                        transpose_offset = display_map
 6373                            .buffer_snapshot
 6374                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6375                    }
 6376
 6377                    if transpose_offset == 0 {
 6378                        return;
 6379                    }
 6380
 6381                    *head.column_mut() += 1;
 6382                    head = display_map.clip_point(head, Bias::Right);
 6383                    let goal = SelectionGoal::HorizontalPosition(
 6384                        display_map
 6385                            .x_for_display_point(head, &text_layout_details)
 6386                            .into(),
 6387                    );
 6388                    selection.collapse_to(head, goal);
 6389
 6390                    let transpose_start = display_map
 6391                        .buffer_snapshot
 6392                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6393                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6394                        let transpose_end = display_map
 6395                            .buffer_snapshot
 6396                            .clip_offset(transpose_offset + 1, Bias::Right);
 6397                        if let Some(ch) =
 6398                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6399                        {
 6400                            edits.push((transpose_start..transpose_offset, String::new()));
 6401                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6402                        }
 6403                    }
 6404                });
 6405                edits
 6406            });
 6407            this.buffer
 6408                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6409            let selections = this.selections.all::<usize>(cx);
 6410            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6411                s.select(selections);
 6412            });
 6413        });
 6414    }
 6415
 6416    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6417        let mut text = String::new();
 6418        let buffer = self.buffer.read(cx).snapshot(cx);
 6419        let mut selections = self.selections.all::<Point>(cx);
 6420        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6421        {
 6422            let max_point = buffer.max_point();
 6423            let mut is_first = true;
 6424            for selection in &mut selections {
 6425                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6426                if is_entire_line {
 6427                    selection.start = Point::new(selection.start.row, 0);
 6428                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6429                    selection.goal = SelectionGoal::None;
 6430                }
 6431                if is_first {
 6432                    is_first = false;
 6433                } else {
 6434                    text += "\n";
 6435                }
 6436                let mut len = 0;
 6437                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6438                    text.push_str(chunk);
 6439                    len += chunk.len();
 6440                }
 6441                clipboard_selections.push(ClipboardSelection {
 6442                    len,
 6443                    is_entire_line,
 6444                    first_line_indent: buffer
 6445                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6446                        .len,
 6447                });
 6448            }
 6449        }
 6450
 6451        self.transact(cx, |this, cx| {
 6452            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6453                s.select(selections);
 6454            });
 6455            this.insert("", cx);
 6456            cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6457        });
 6458    }
 6459
 6460    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6461        let selections = self.selections.all::<Point>(cx);
 6462        let buffer = self.buffer.read(cx).read(cx);
 6463        let mut text = String::new();
 6464
 6465        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6466        {
 6467            let max_point = buffer.max_point();
 6468            let mut is_first = true;
 6469            for selection in selections.iter() {
 6470                let mut start = selection.start;
 6471                let mut end = selection.end;
 6472                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6473                if is_entire_line {
 6474                    start = Point::new(start.row, 0);
 6475                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6476                }
 6477                if is_first {
 6478                    is_first = false;
 6479                } else {
 6480                    text += "\n";
 6481                }
 6482                let mut len = 0;
 6483                for chunk in buffer.text_for_range(start..end) {
 6484                    text.push_str(chunk);
 6485                    len += chunk.len();
 6486                }
 6487                clipboard_selections.push(ClipboardSelection {
 6488                    len,
 6489                    is_entire_line,
 6490                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6491                });
 6492            }
 6493        }
 6494
 6495        cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6496    }
 6497
 6498    pub fn do_paste(
 6499        &mut self,
 6500        text: &String,
 6501        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6502        handle_entire_lines: bool,
 6503        cx: &mut ViewContext<Self>,
 6504    ) {
 6505        if self.read_only(cx) {
 6506            return;
 6507        }
 6508
 6509        let clipboard_text = Cow::Borrowed(text);
 6510
 6511        self.transact(cx, |this, cx| {
 6512            if let Some(mut clipboard_selections) = clipboard_selections {
 6513                let old_selections = this.selections.all::<usize>(cx);
 6514                let all_selections_were_entire_line =
 6515                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6516                let first_selection_indent_column =
 6517                    clipboard_selections.first().map(|s| s.first_line_indent);
 6518                if clipboard_selections.len() != old_selections.len() {
 6519                    clipboard_selections.drain(..);
 6520                }
 6521
 6522                this.buffer.update(cx, |buffer, cx| {
 6523                    let snapshot = buffer.read(cx);
 6524                    let mut start_offset = 0;
 6525                    let mut edits = Vec::new();
 6526                    let mut original_indent_columns = Vec::new();
 6527                    for (ix, selection) in old_selections.iter().enumerate() {
 6528                        let to_insert;
 6529                        let entire_line;
 6530                        let original_indent_column;
 6531                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6532                            let end_offset = start_offset + clipboard_selection.len;
 6533                            to_insert = &clipboard_text[start_offset..end_offset];
 6534                            entire_line = clipboard_selection.is_entire_line;
 6535                            start_offset = end_offset + 1;
 6536                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6537                        } else {
 6538                            to_insert = clipboard_text.as_str();
 6539                            entire_line = all_selections_were_entire_line;
 6540                            original_indent_column = first_selection_indent_column
 6541                        }
 6542
 6543                        // If the corresponding selection was empty when this slice of the
 6544                        // clipboard text was written, then the entire line containing the
 6545                        // selection was copied. If this selection is also currently empty,
 6546                        // then paste the line before the current line of the buffer.
 6547                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6548                            let column = selection.start.to_point(&snapshot).column as usize;
 6549                            let line_start = selection.start - column;
 6550                            line_start..line_start
 6551                        } else {
 6552                            selection.range()
 6553                        };
 6554
 6555                        edits.push((range, to_insert));
 6556                        original_indent_columns.extend(original_indent_column);
 6557                    }
 6558                    drop(snapshot);
 6559
 6560                    buffer.edit(
 6561                        edits,
 6562                        Some(AutoindentMode::Block {
 6563                            original_indent_columns,
 6564                        }),
 6565                        cx,
 6566                    );
 6567                });
 6568
 6569                let selections = this.selections.all::<usize>(cx);
 6570                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6571            } else {
 6572                this.insert(&clipboard_text, cx);
 6573            }
 6574        });
 6575    }
 6576
 6577    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6578        if let Some(item) = cx.read_from_clipboard() {
 6579            self.do_paste(
 6580                item.text(),
 6581                item.metadata::<Vec<ClipboardSelection>>(),
 6582                true,
 6583                cx,
 6584            )
 6585        };
 6586    }
 6587
 6588    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6589        if self.read_only(cx) {
 6590            return;
 6591        }
 6592
 6593        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6594            if let Some((selections, _)) =
 6595                self.selection_history.transaction(transaction_id).cloned()
 6596            {
 6597                self.change_selections(None, cx, |s| {
 6598                    s.select_anchors(selections.to_vec());
 6599                });
 6600            }
 6601            self.request_autoscroll(Autoscroll::fit(), cx);
 6602            self.unmark_text(cx);
 6603            self.refresh_inline_completion(true, cx);
 6604            cx.emit(EditorEvent::Edited { transaction_id });
 6605            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 6606        }
 6607    }
 6608
 6609    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 6610        if self.read_only(cx) {
 6611            return;
 6612        }
 6613
 6614        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 6615            if let Some((_, Some(selections))) =
 6616                self.selection_history.transaction(transaction_id).cloned()
 6617            {
 6618                self.change_selections(None, cx, |s| {
 6619                    s.select_anchors(selections.to_vec());
 6620                });
 6621            }
 6622            self.request_autoscroll(Autoscroll::fit(), cx);
 6623            self.unmark_text(cx);
 6624            self.refresh_inline_completion(true, cx);
 6625            cx.emit(EditorEvent::Edited { transaction_id });
 6626        }
 6627    }
 6628
 6629    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 6630        self.buffer
 6631            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 6632    }
 6633
 6634    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 6635        self.buffer
 6636            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 6637    }
 6638
 6639    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 6640        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6641            let line_mode = s.line_mode;
 6642            s.move_with(|map, selection| {
 6643                let cursor = if selection.is_empty() && !line_mode {
 6644                    movement::left(map, selection.start)
 6645                } else {
 6646                    selection.start
 6647                };
 6648                selection.collapse_to(cursor, SelectionGoal::None);
 6649            });
 6650        })
 6651    }
 6652
 6653    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 6654        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6655            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 6656        })
 6657    }
 6658
 6659    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 6660        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6661            let line_mode = s.line_mode;
 6662            s.move_with(|map, selection| {
 6663                let cursor = if selection.is_empty() && !line_mode {
 6664                    movement::right(map, selection.end)
 6665                } else {
 6666                    selection.end
 6667                };
 6668                selection.collapse_to(cursor, SelectionGoal::None)
 6669            });
 6670        })
 6671    }
 6672
 6673    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 6674        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6675            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 6676        })
 6677    }
 6678
 6679    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 6680        if self.take_rename(true, cx).is_some() {
 6681            return;
 6682        }
 6683
 6684        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6685            cx.propagate();
 6686            return;
 6687        }
 6688
 6689        let text_layout_details = &self.text_layout_details(cx);
 6690        let selection_count = self.selections.count();
 6691        let first_selection = self.selections.first_anchor();
 6692
 6693        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6694            let line_mode = s.line_mode;
 6695            s.move_with(|map, selection| {
 6696                if !selection.is_empty() && !line_mode {
 6697                    selection.goal = SelectionGoal::None;
 6698                }
 6699                let (cursor, goal) = movement::up(
 6700                    map,
 6701                    selection.start,
 6702                    selection.goal,
 6703                    false,
 6704                    &text_layout_details,
 6705                );
 6706                selection.collapse_to(cursor, goal);
 6707            });
 6708        });
 6709
 6710        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6711        {
 6712            cx.propagate();
 6713        }
 6714    }
 6715
 6716    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 6717        if self.take_rename(true, cx).is_some() {
 6718            return;
 6719        }
 6720
 6721        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6722            cx.propagate();
 6723            return;
 6724        }
 6725
 6726        let text_layout_details = &self.text_layout_details(cx);
 6727
 6728        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6729            let line_mode = s.line_mode;
 6730            s.move_with(|map, selection| {
 6731                if !selection.is_empty() && !line_mode {
 6732                    selection.goal = SelectionGoal::None;
 6733                }
 6734                let (cursor, goal) = movement::up_by_rows(
 6735                    map,
 6736                    selection.start,
 6737                    action.lines,
 6738                    selection.goal,
 6739                    false,
 6740                    &text_layout_details,
 6741                );
 6742                selection.collapse_to(cursor, goal);
 6743            });
 6744        })
 6745    }
 6746
 6747    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 6748        if self.take_rename(true, cx).is_some() {
 6749            return;
 6750        }
 6751
 6752        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6753            cx.propagate();
 6754            return;
 6755        }
 6756
 6757        let text_layout_details = &self.text_layout_details(cx);
 6758
 6759        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6760            let line_mode = s.line_mode;
 6761            s.move_with(|map, selection| {
 6762                if !selection.is_empty() && !line_mode {
 6763                    selection.goal = SelectionGoal::None;
 6764                }
 6765                let (cursor, goal) = movement::down_by_rows(
 6766                    map,
 6767                    selection.start,
 6768                    action.lines,
 6769                    selection.goal,
 6770                    false,
 6771                    &text_layout_details,
 6772                );
 6773                selection.collapse_to(cursor, goal);
 6774            });
 6775        })
 6776    }
 6777
 6778    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 6779        let text_layout_details = &self.text_layout_details(cx);
 6780        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6781            s.move_heads_with(|map, head, goal| {
 6782                movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6783            })
 6784        })
 6785    }
 6786
 6787    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 6788        let text_layout_details = &self.text_layout_details(cx);
 6789        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6790            s.move_heads_with(|map, head, goal| {
 6791                movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6792            })
 6793        })
 6794    }
 6795
 6796    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 6797        let Some(row_count) = self.visible_row_count() else {
 6798            return;
 6799        };
 6800
 6801        let text_layout_details = &self.text_layout_details(cx);
 6802
 6803        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6804            s.move_heads_with(|map, head, goal| {
 6805                movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
 6806            })
 6807        })
 6808    }
 6809
 6810    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 6811        if self.take_rename(true, cx).is_some() {
 6812            return;
 6813        }
 6814
 6815        if self
 6816            .context_menu
 6817            .write()
 6818            .as_mut()
 6819            .map(|menu| menu.select_first(self.project.as_ref(), cx))
 6820            .unwrap_or(false)
 6821        {
 6822            return;
 6823        }
 6824
 6825        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6826            cx.propagate();
 6827            return;
 6828        }
 6829
 6830        let Some(row_count) = self.visible_row_count() else {
 6831            return;
 6832        };
 6833
 6834        let autoscroll = if action.center_cursor {
 6835            Autoscroll::center()
 6836        } else {
 6837            Autoscroll::fit()
 6838        };
 6839
 6840        let text_layout_details = &self.text_layout_details(cx);
 6841
 6842        self.change_selections(Some(autoscroll), cx, |s| {
 6843            let line_mode = s.line_mode;
 6844            s.move_with(|map, selection| {
 6845                if !selection.is_empty() && !line_mode {
 6846                    selection.goal = SelectionGoal::None;
 6847                }
 6848                let (cursor, goal) = movement::up_by_rows(
 6849                    map,
 6850                    selection.end,
 6851                    row_count,
 6852                    selection.goal,
 6853                    false,
 6854                    &text_layout_details,
 6855                );
 6856                selection.collapse_to(cursor, goal);
 6857            });
 6858        });
 6859    }
 6860
 6861    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 6862        let text_layout_details = &self.text_layout_details(cx);
 6863        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6864            s.move_heads_with(|map, head, goal| {
 6865                movement::up(map, head, goal, false, &text_layout_details)
 6866            })
 6867        })
 6868    }
 6869
 6870    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 6871        self.take_rename(true, cx);
 6872
 6873        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6874            cx.propagate();
 6875            return;
 6876        }
 6877
 6878        let text_layout_details = &self.text_layout_details(cx);
 6879        let selection_count = self.selections.count();
 6880        let first_selection = self.selections.first_anchor();
 6881
 6882        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6883            let line_mode = s.line_mode;
 6884            s.move_with(|map, selection| {
 6885                if !selection.is_empty() && !line_mode {
 6886                    selection.goal = SelectionGoal::None;
 6887                }
 6888                let (cursor, goal) = movement::down(
 6889                    map,
 6890                    selection.end,
 6891                    selection.goal,
 6892                    false,
 6893                    &text_layout_details,
 6894                );
 6895                selection.collapse_to(cursor, goal);
 6896            });
 6897        });
 6898
 6899        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6900        {
 6901            cx.propagate();
 6902        }
 6903    }
 6904
 6905    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 6906        let Some(row_count) = self.visible_row_count() else {
 6907            return;
 6908        };
 6909
 6910        let text_layout_details = &self.text_layout_details(cx);
 6911
 6912        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6913            s.move_heads_with(|map, head, goal| {
 6914                movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
 6915            })
 6916        })
 6917    }
 6918
 6919    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 6920        if self.take_rename(true, cx).is_some() {
 6921            return;
 6922        }
 6923
 6924        if self
 6925            .context_menu
 6926            .write()
 6927            .as_mut()
 6928            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 6929            .unwrap_or(false)
 6930        {
 6931            return;
 6932        }
 6933
 6934        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6935            cx.propagate();
 6936            return;
 6937        }
 6938
 6939        let Some(row_count) = self.visible_row_count() else {
 6940            return;
 6941        };
 6942
 6943        let autoscroll = if action.center_cursor {
 6944            Autoscroll::center()
 6945        } else {
 6946            Autoscroll::fit()
 6947        };
 6948
 6949        let text_layout_details = &self.text_layout_details(cx);
 6950        self.change_selections(Some(autoscroll), cx, |s| {
 6951            let line_mode = s.line_mode;
 6952            s.move_with(|map, selection| {
 6953                if !selection.is_empty() && !line_mode {
 6954                    selection.goal = SelectionGoal::None;
 6955                }
 6956                let (cursor, goal) = movement::down_by_rows(
 6957                    map,
 6958                    selection.end,
 6959                    row_count,
 6960                    selection.goal,
 6961                    false,
 6962                    &text_layout_details,
 6963                );
 6964                selection.collapse_to(cursor, goal);
 6965            });
 6966        });
 6967    }
 6968
 6969    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 6970        let text_layout_details = &self.text_layout_details(cx);
 6971        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6972            s.move_heads_with(|map, head, goal| {
 6973                movement::down(map, head, goal, false, &text_layout_details)
 6974            })
 6975        });
 6976    }
 6977
 6978    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 6979        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6980            context_menu.select_first(self.project.as_ref(), cx);
 6981        }
 6982    }
 6983
 6984    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 6985        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6986            context_menu.select_prev(self.project.as_ref(), cx);
 6987        }
 6988    }
 6989
 6990    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 6991        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6992            context_menu.select_next(self.project.as_ref(), cx);
 6993        }
 6994    }
 6995
 6996    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 6997        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6998            context_menu.select_last(self.project.as_ref(), cx);
 6999        }
 7000    }
 7001
 7002    pub fn move_to_previous_word_start(
 7003        &mut self,
 7004        _: &MoveToPreviousWordStart,
 7005        cx: &mut ViewContext<Self>,
 7006    ) {
 7007        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7008            s.move_cursors_with(|map, head, _| {
 7009                (
 7010                    movement::previous_word_start(map, head),
 7011                    SelectionGoal::None,
 7012                )
 7013            });
 7014        })
 7015    }
 7016
 7017    pub fn move_to_previous_subword_start(
 7018        &mut self,
 7019        _: &MoveToPreviousSubwordStart,
 7020        cx: &mut ViewContext<Self>,
 7021    ) {
 7022        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7023            s.move_cursors_with(|map, head, _| {
 7024                (
 7025                    movement::previous_subword_start(map, head),
 7026                    SelectionGoal::None,
 7027                )
 7028            });
 7029        })
 7030    }
 7031
 7032    pub fn select_to_previous_word_start(
 7033        &mut self,
 7034        _: &SelectToPreviousWordStart,
 7035        cx: &mut ViewContext<Self>,
 7036    ) {
 7037        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7038            s.move_heads_with(|map, head, _| {
 7039                (
 7040                    movement::previous_word_start(map, head),
 7041                    SelectionGoal::None,
 7042                )
 7043            });
 7044        })
 7045    }
 7046
 7047    pub fn select_to_previous_subword_start(
 7048        &mut self,
 7049        _: &SelectToPreviousSubwordStart,
 7050        cx: &mut ViewContext<Self>,
 7051    ) {
 7052        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7053            s.move_heads_with(|map, head, _| {
 7054                (
 7055                    movement::previous_subword_start(map, head),
 7056                    SelectionGoal::None,
 7057                )
 7058            });
 7059        })
 7060    }
 7061
 7062    pub fn delete_to_previous_word_start(
 7063        &mut self,
 7064        _: &DeleteToPreviousWordStart,
 7065        cx: &mut ViewContext<Self>,
 7066    ) {
 7067        self.transact(cx, |this, cx| {
 7068            this.select_autoclose_pair(cx);
 7069            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7070                let line_mode = s.line_mode;
 7071                s.move_with(|map, selection| {
 7072                    if selection.is_empty() && !line_mode {
 7073                        let cursor = movement::previous_word_start(map, selection.head());
 7074                        selection.set_head(cursor, SelectionGoal::None);
 7075                    }
 7076                });
 7077            });
 7078            this.insert("", cx);
 7079        });
 7080    }
 7081
 7082    pub fn delete_to_previous_subword_start(
 7083        &mut self,
 7084        _: &DeleteToPreviousSubwordStart,
 7085        cx: &mut ViewContext<Self>,
 7086    ) {
 7087        self.transact(cx, |this, cx| {
 7088            this.select_autoclose_pair(cx);
 7089            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7090                let line_mode = s.line_mode;
 7091                s.move_with(|map, selection| {
 7092                    if selection.is_empty() && !line_mode {
 7093                        let cursor = movement::previous_subword_start(map, selection.head());
 7094                        selection.set_head(cursor, SelectionGoal::None);
 7095                    }
 7096                });
 7097            });
 7098            this.insert("", cx);
 7099        });
 7100    }
 7101
 7102    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7103        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7104            s.move_cursors_with(|map, head, _| {
 7105                (movement::next_word_end(map, head), SelectionGoal::None)
 7106            });
 7107        })
 7108    }
 7109
 7110    pub fn move_to_next_subword_end(
 7111        &mut self,
 7112        _: &MoveToNextSubwordEnd,
 7113        cx: &mut ViewContext<Self>,
 7114    ) {
 7115        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7116            s.move_cursors_with(|map, head, _| {
 7117                (movement::next_subword_end(map, head), SelectionGoal::None)
 7118            });
 7119        })
 7120    }
 7121
 7122    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7123        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7124            s.move_heads_with(|map, head, _| {
 7125                (movement::next_word_end(map, head), SelectionGoal::None)
 7126            });
 7127        })
 7128    }
 7129
 7130    pub fn select_to_next_subword_end(
 7131        &mut self,
 7132        _: &SelectToNextSubwordEnd,
 7133        cx: &mut ViewContext<Self>,
 7134    ) {
 7135        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7136            s.move_heads_with(|map, head, _| {
 7137                (movement::next_subword_end(map, head), SelectionGoal::None)
 7138            });
 7139        })
 7140    }
 7141
 7142    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
 7143        self.transact(cx, |this, cx| {
 7144            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7145                let line_mode = s.line_mode;
 7146                s.move_with(|map, selection| {
 7147                    if selection.is_empty() && !line_mode {
 7148                        let cursor = movement::next_word_end(map, selection.head());
 7149                        selection.set_head(cursor, SelectionGoal::None);
 7150                    }
 7151                });
 7152            });
 7153            this.insert("", cx);
 7154        });
 7155    }
 7156
 7157    pub fn delete_to_next_subword_end(
 7158        &mut self,
 7159        _: &DeleteToNextSubwordEnd,
 7160        cx: &mut ViewContext<Self>,
 7161    ) {
 7162        self.transact(cx, |this, cx| {
 7163            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7164                s.move_with(|map, selection| {
 7165                    if selection.is_empty() {
 7166                        let cursor = movement::next_subword_end(map, selection.head());
 7167                        selection.set_head(cursor, SelectionGoal::None);
 7168                    }
 7169                });
 7170            });
 7171            this.insert("", cx);
 7172        });
 7173    }
 7174
 7175    pub fn move_to_beginning_of_line(
 7176        &mut self,
 7177        action: &MoveToBeginningOfLine,
 7178        cx: &mut ViewContext<Self>,
 7179    ) {
 7180        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7181            s.move_cursors_with(|map, head, _| {
 7182                (
 7183                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7184                    SelectionGoal::None,
 7185                )
 7186            });
 7187        })
 7188    }
 7189
 7190    pub fn select_to_beginning_of_line(
 7191        &mut self,
 7192        action: &SelectToBeginningOfLine,
 7193        cx: &mut ViewContext<Self>,
 7194    ) {
 7195        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7196            s.move_heads_with(|map, head, _| {
 7197                (
 7198                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7199                    SelectionGoal::None,
 7200                )
 7201            });
 7202        });
 7203    }
 7204
 7205    pub fn delete_to_beginning_of_line(
 7206        &mut self,
 7207        _: &DeleteToBeginningOfLine,
 7208        cx: &mut ViewContext<Self>,
 7209    ) {
 7210        self.transact(cx, |this, cx| {
 7211            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7212                s.move_with(|_, selection| {
 7213                    selection.reversed = true;
 7214                });
 7215            });
 7216
 7217            this.select_to_beginning_of_line(
 7218                &SelectToBeginningOfLine {
 7219                    stop_at_soft_wraps: false,
 7220                },
 7221                cx,
 7222            );
 7223            this.backspace(&Backspace, cx);
 7224        });
 7225    }
 7226
 7227    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7228        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7229            s.move_cursors_with(|map, head, _| {
 7230                (
 7231                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7232                    SelectionGoal::None,
 7233                )
 7234            });
 7235        })
 7236    }
 7237
 7238    pub fn select_to_end_of_line(
 7239        &mut self,
 7240        action: &SelectToEndOfLine,
 7241        cx: &mut ViewContext<Self>,
 7242    ) {
 7243        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7244            s.move_heads_with(|map, head, _| {
 7245                (
 7246                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7247                    SelectionGoal::None,
 7248                )
 7249            });
 7250        })
 7251    }
 7252
 7253    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7254        self.transact(cx, |this, cx| {
 7255            this.select_to_end_of_line(
 7256                &SelectToEndOfLine {
 7257                    stop_at_soft_wraps: false,
 7258                },
 7259                cx,
 7260            );
 7261            this.delete(&Delete, cx);
 7262        });
 7263    }
 7264
 7265    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7266        self.transact(cx, |this, cx| {
 7267            this.select_to_end_of_line(
 7268                &SelectToEndOfLine {
 7269                    stop_at_soft_wraps: false,
 7270                },
 7271                cx,
 7272            );
 7273            this.cut(&Cut, cx);
 7274        });
 7275    }
 7276
 7277    pub fn move_to_start_of_paragraph(
 7278        &mut self,
 7279        _: &MoveToStartOfParagraph,
 7280        cx: &mut ViewContext<Self>,
 7281    ) {
 7282        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7283            cx.propagate();
 7284            return;
 7285        }
 7286
 7287        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7288            s.move_with(|map, selection| {
 7289                selection.collapse_to(
 7290                    movement::start_of_paragraph(map, selection.head(), 1),
 7291                    SelectionGoal::None,
 7292                )
 7293            });
 7294        })
 7295    }
 7296
 7297    pub fn move_to_end_of_paragraph(
 7298        &mut self,
 7299        _: &MoveToEndOfParagraph,
 7300        cx: &mut ViewContext<Self>,
 7301    ) {
 7302        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7303            cx.propagate();
 7304            return;
 7305        }
 7306
 7307        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7308            s.move_with(|map, selection| {
 7309                selection.collapse_to(
 7310                    movement::end_of_paragraph(map, selection.head(), 1),
 7311                    SelectionGoal::None,
 7312                )
 7313            });
 7314        })
 7315    }
 7316
 7317    pub fn select_to_start_of_paragraph(
 7318        &mut self,
 7319        _: &SelectToStartOfParagraph,
 7320        cx: &mut ViewContext<Self>,
 7321    ) {
 7322        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7323            cx.propagate();
 7324            return;
 7325        }
 7326
 7327        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7328            s.move_heads_with(|map, head, _| {
 7329                (
 7330                    movement::start_of_paragraph(map, head, 1),
 7331                    SelectionGoal::None,
 7332                )
 7333            });
 7334        })
 7335    }
 7336
 7337    pub fn select_to_end_of_paragraph(
 7338        &mut self,
 7339        _: &SelectToEndOfParagraph,
 7340        cx: &mut ViewContext<Self>,
 7341    ) {
 7342        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7343            cx.propagate();
 7344            return;
 7345        }
 7346
 7347        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7348            s.move_heads_with(|map, head, _| {
 7349                (
 7350                    movement::end_of_paragraph(map, head, 1),
 7351                    SelectionGoal::None,
 7352                )
 7353            });
 7354        })
 7355    }
 7356
 7357    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7358        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7359            cx.propagate();
 7360            return;
 7361        }
 7362
 7363        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7364            s.select_ranges(vec![0..0]);
 7365        });
 7366    }
 7367
 7368    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7369        let mut selection = self.selections.last::<Point>(cx);
 7370        selection.set_head(Point::zero(), SelectionGoal::None);
 7371
 7372        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7373            s.select(vec![selection]);
 7374        });
 7375    }
 7376
 7377    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7378        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7379            cx.propagate();
 7380            return;
 7381        }
 7382
 7383        let cursor = self.buffer.read(cx).read(cx).len();
 7384        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7385            s.select_ranges(vec![cursor..cursor])
 7386        });
 7387    }
 7388
 7389    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7390        self.nav_history = nav_history;
 7391    }
 7392
 7393    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7394        self.nav_history.as_ref()
 7395    }
 7396
 7397    fn push_to_nav_history(
 7398        &mut self,
 7399        cursor_anchor: Anchor,
 7400        new_position: Option<Point>,
 7401        cx: &mut ViewContext<Self>,
 7402    ) {
 7403        if let Some(nav_history) = self.nav_history.as_mut() {
 7404            let buffer = self.buffer.read(cx).read(cx);
 7405            let cursor_position = cursor_anchor.to_point(&buffer);
 7406            let scroll_state = self.scroll_manager.anchor();
 7407            let scroll_top_row = scroll_state.top_row(&buffer);
 7408            drop(buffer);
 7409
 7410            if let Some(new_position) = new_position {
 7411                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7412                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7413                    return;
 7414                }
 7415            }
 7416
 7417            nav_history.push(
 7418                Some(NavigationData {
 7419                    cursor_anchor,
 7420                    cursor_position,
 7421                    scroll_anchor: scroll_state,
 7422                    scroll_top_row,
 7423                }),
 7424                cx,
 7425            );
 7426        }
 7427    }
 7428
 7429    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7430        let buffer = self.buffer.read(cx).snapshot(cx);
 7431        let mut selection = self.selections.first::<usize>(cx);
 7432        selection.set_head(buffer.len(), SelectionGoal::None);
 7433        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7434            s.select(vec![selection]);
 7435        });
 7436    }
 7437
 7438    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7439        let end = self.buffer.read(cx).read(cx).len();
 7440        self.change_selections(None, cx, |s| {
 7441            s.select_ranges(vec![0..end]);
 7442        });
 7443    }
 7444
 7445    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7446        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7447        let mut selections = self.selections.all::<Point>(cx);
 7448        let max_point = display_map.buffer_snapshot.max_point();
 7449        for selection in &mut selections {
 7450            let rows = selection.spanned_rows(true, &display_map);
 7451            selection.start = Point::new(rows.start.0, 0);
 7452            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7453            selection.reversed = false;
 7454        }
 7455        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7456            s.select(selections);
 7457        });
 7458    }
 7459
 7460    pub fn split_selection_into_lines(
 7461        &mut self,
 7462        _: &SplitSelectionIntoLines,
 7463        cx: &mut ViewContext<Self>,
 7464    ) {
 7465        let mut to_unfold = Vec::new();
 7466        let mut new_selection_ranges = Vec::new();
 7467        {
 7468            let selections = self.selections.all::<Point>(cx);
 7469            let buffer = self.buffer.read(cx).read(cx);
 7470            for selection in selections {
 7471                for row in selection.start.row..selection.end.row {
 7472                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7473                    new_selection_ranges.push(cursor..cursor);
 7474                }
 7475                new_selection_ranges.push(selection.end..selection.end);
 7476                to_unfold.push(selection.start..selection.end);
 7477            }
 7478        }
 7479        self.unfold_ranges(to_unfold, true, true, cx);
 7480        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7481            s.select_ranges(new_selection_ranges);
 7482        });
 7483    }
 7484
 7485    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7486        self.add_selection(true, cx);
 7487    }
 7488
 7489    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7490        self.add_selection(false, cx);
 7491    }
 7492
 7493    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7494        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7495        let mut selections = self.selections.all::<Point>(cx);
 7496        let text_layout_details = self.text_layout_details(cx);
 7497        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7498            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7499            let range = oldest_selection.display_range(&display_map).sorted();
 7500
 7501            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7502            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7503            let positions = start_x.min(end_x)..start_x.max(end_x);
 7504
 7505            selections.clear();
 7506            let mut stack = Vec::new();
 7507            for row in range.start.row().0..=range.end.row().0 {
 7508                if let Some(selection) = self.selections.build_columnar_selection(
 7509                    &display_map,
 7510                    DisplayRow(row),
 7511                    &positions,
 7512                    oldest_selection.reversed,
 7513                    &text_layout_details,
 7514                ) {
 7515                    stack.push(selection.id);
 7516                    selections.push(selection);
 7517                }
 7518            }
 7519
 7520            if above {
 7521                stack.reverse();
 7522            }
 7523
 7524            AddSelectionsState { above, stack }
 7525        });
 7526
 7527        let last_added_selection = *state.stack.last().unwrap();
 7528        let mut new_selections = Vec::new();
 7529        if above == state.above {
 7530            let end_row = if above {
 7531                DisplayRow(0)
 7532            } else {
 7533                display_map.max_point().row()
 7534            };
 7535
 7536            'outer: for selection in selections {
 7537                if selection.id == last_added_selection {
 7538                    let range = selection.display_range(&display_map).sorted();
 7539                    debug_assert_eq!(range.start.row(), range.end.row());
 7540                    let mut row = range.start.row();
 7541                    let positions =
 7542                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7543                            px(start)..px(end)
 7544                        } else {
 7545                            let start_x =
 7546                                display_map.x_for_display_point(range.start, &text_layout_details);
 7547                            let end_x =
 7548                                display_map.x_for_display_point(range.end, &text_layout_details);
 7549                            start_x.min(end_x)..start_x.max(end_x)
 7550                        };
 7551
 7552                    while row != end_row {
 7553                        if above {
 7554                            row.0 -= 1;
 7555                        } else {
 7556                            row.0 += 1;
 7557                        }
 7558
 7559                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7560                            &display_map,
 7561                            row,
 7562                            &positions,
 7563                            selection.reversed,
 7564                            &text_layout_details,
 7565                        ) {
 7566                            state.stack.push(new_selection.id);
 7567                            if above {
 7568                                new_selections.push(new_selection);
 7569                                new_selections.push(selection);
 7570                            } else {
 7571                                new_selections.push(selection);
 7572                                new_selections.push(new_selection);
 7573                            }
 7574
 7575                            continue 'outer;
 7576                        }
 7577                    }
 7578                }
 7579
 7580                new_selections.push(selection);
 7581            }
 7582        } else {
 7583            new_selections = selections;
 7584            new_selections.retain(|s| s.id != last_added_selection);
 7585            state.stack.pop();
 7586        }
 7587
 7588        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7589            s.select(new_selections);
 7590        });
 7591        if state.stack.len() > 1 {
 7592            self.add_selections_state = Some(state);
 7593        }
 7594    }
 7595
 7596    pub fn select_next_match_internal(
 7597        &mut self,
 7598        display_map: &DisplaySnapshot,
 7599        replace_newest: bool,
 7600        autoscroll: Option<Autoscroll>,
 7601        cx: &mut ViewContext<Self>,
 7602    ) -> Result<()> {
 7603        fn select_next_match_ranges(
 7604            this: &mut Editor,
 7605            range: Range<usize>,
 7606            replace_newest: bool,
 7607            auto_scroll: Option<Autoscroll>,
 7608            cx: &mut ViewContext<Editor>,
 7609        ) {
 7610            this.unfold_ranges([range.clone()], false, true, cx);
 7611            this.change_selections(auto_scroll, cx, |s| {
 7612                if replace_newest {
 7613                    s.delete(s.newest_anchor().id);
 7614                }
 7615                s.insert_range(range.clone());
 7616            });
 7617        }
 7618
 7619        let buffer = &display_map.buffer_snapshot;
 7620        let mut selections = self.selections.all::<usize>(cx);
 7621        if let Some(mut select_next_state) = self.select_next_state.take() {
 7622            let query = &select_next_state.query;
 7623            if !select_next_state.done {
 7624                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7625                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7626                let mut next_selected_range = None;
 7627
 7628                let bytes_after_last_selection =
 7629                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7630                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7631                let query_matches = query
 7632                    .stream_find_iter(bytes_after_last_selection)
 7633                    .map(|result| (last_selection.end, result))
 7634                    .chain(
 7635                        query
 7636                            .stream_find_iter(bytes_before_first_selection)
 7637                            .map(|result| (0, result)),
 7638                    );
 7639
 7640                for (start_offset, query_match) in query_matches {
 7641                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7642                    let offset_range =
 7643                        start_offset + query_match.start()..start_offset + query_match.end();
 7644                    let display_range = offset_range.start.to_display_point(&display_map)
 7645                        ..offset_range.end.to_display_point(&display_map);
 7646
 7647                    if !select_next_state.wordwise
 7648                        || (!movement::is_inside_word(&display_map, display_range.start)
 7649                            && !movement::is_inside_word(&display_map, display_range.end))
 7650                    {
 7651                        // TODO: This is n^2, because we might check all the selections
 7652                        if !selections
 7653                            .iter()
 7654                            .any(|selection| selection.range().overlaps(&offset_range))
 7655                        {
 7656                            next_selected_range = Some(offset_range);
 7657                            break;
 7658                        }
 7659                    }
 7660                }
 7661
 7662                if let Some(next_selected_range) = next_selected_range {
 7663                    select_next_match_ranges(
 7664                        self,
 7665                        next_selected_range,
 7666                        replace_newest,
 7667                        autoscroll,
 7668                        cx,
 7669                    );
 7670                } else {
 7671                    select_next_state.done = true;
 7672                }
 7673            }
 7674
 7675            self.select_next_state = Some(select_next_state);
 7676        } else {
 7677            let mut only_carets = true;
 7678            let mut same_text_selected = true;
 7679            let mut selected_text = None;
 7680
 7681            let mut selections_iter = selections.iter().peekable();
 7682            while let Some(selection) = selections_iter.next() {
 7683                if selection.start != selection.end {
 7684                    only_carets = false;
 7685                }
 7686
 7687                if same_text_selected {
 7688                    if selected_text.is_none() {
 7689                        selected_text =
 7690                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7691                    }
 7692
 7693                    if let Some(next_selection) = selections_iter.peek() {
 7694                        if next_selection.range().len() == selection.range().len() {
 7695                            let next_selected_text = buffer
 7696                                .text_for_range(next_selection.range())
 7697                                .collect::<String>();
 7698                            if Some(next_selected_text) != selected_text {
 7699                                same_text_selected = false;
 7700                                selected_text = None;
 7701                            }
 7702                        } else {
 7703                            same_text_selected = false;
 7704                            selected_text = None;
 7705                        }
 7706                    }
 7707                }
 7708            }
 7709
 7710            if only_carets {
 7711                for selection in &mut selections {
 7712                    let word_range = movement::surrounding_word(
 7713                        &display_map,
 7714                        selection.start.to_display_point(&display_map),
 7715                    );
 7716                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7717                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7718                    selection.goal = SelectionGoal::None;
 7719                    selection.reversed = false;
 7720                    select_next_match_ranges(
 7721                        self,
 7722                        selection.start..selection.end,
 7723                        replace_newest,
 7724                        autoscroll,
 7725                        cx,
 7726                    );
 7727                }
 7728
 7729                if selections.len() == 1 {
 7730                    let selection = selections
 7731                        .last()
 7732                        .expect("ensured that there's only one selection");
 7733                    let query = buffer
 7734                        .text_for_range(selection.start..selection.end)
 7735                        .collect::<String>();
 7736                    let is_empty = query.is_empty();
 7737                    let select_state = SelectNextState {
 7738                        query: AhoCorasick::new(&[query])?,
 7739                        wordwise: true,
 7740                        done: is_empty,
 7741                    };
 7742                    self.select_next_state = Some(select_state);
 7743                } else {
 7744                    self.select_next_state = None;
 7745                }
 7746            } else if let Some(selected_text) = selected_text {
 7747                self.select_next_state = Some(SelectNextState {
 7748                    query: AhoCorasick::new(&[selected_text])?,
 7749                    wordwise: false,
 7750                    done: false,
 7751                });
 7752                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 7753            }
 7754        }
 7755        Ok(())
 7756    }
 7757
 7758    pub fn select_all_matches(
 7759        &mut self,
 7760        _action: &SelectAllMatches,
 7761        cx: &mut ViewContext<Self>,
 7762    ) -> Result<()> {
 7763        self.push_to_selection_history();
 7764        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7765
 7766        self.select_next_match_internal(&display_map, false, None, cx)?;
 7767        let Some(select_next_state) = self.select_next_state.as_mut() else {
 7768            return Ok(());
 7769        };
 7770        if select_next_state.done {
 7771            return Ok(());
 7772        }
 7773
 7774        let mut new_selections = self.selections.all::<usize>(cx);
 7775
 7776        let buffer = &display_map.buffer_snapshot;
 7777        let query_matches = select_next_state
 7778            .query
 7779            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 7780
 7781        for query_match in query_matches {
 7782            let query_match = query_match.unwrap(); // can only fail due to I/O
 7783            let offset_range = query_match.start()..query_match.end();
 7784            let display_range = offset_range.start.to_display_point(&display_map)
 7785                ..offset_range.end.to_display_point(&display_map);
 7786
 7787            if !select_next_state.wordwise
 7788                || (!movement::is_inside_word(&display_map, display_range.start)
 7789                    && !movement::is_inside_word(&display_map, display_range.end))
 7790            {
 7791                self.selections.change_with(cx, |selections| {
 7792                    new_selections.push(Selection {
 7793                        id: selections.new_selection_id(),
 7794                        start: offset_range.start,
 7795                        end: offset_range.end,
 7796                        reversed: false,
 7797                        goal: SelectionGoal::None,
 7798                    });
 7799                });
 7800            }
 7801        }
 7802
 7803        new_selections.sort_by_key(|selection| selection.start);
 7804        let mut ix = 0;
 7805        while ix + 1 < new_selections.len() {
 7806            let current_selection = &new_selections[ix];
 7807            let next_selection = &new_selections[ix + 1];
 7808            if current_selection.range().overlaps(&next_selection.range()) {
 7809                if current_selection.id < next_selection.id {
 7810                    new_selections.remove(ix + 1);
 7811                } else {
 7812                    new_selections.remove(ix);
 7813                }
 7814            } else {
 7815                ix += 1;
 7816            }
 7817        }
 7818
 7819        select_next_state.done = true;
 7820        self.unfold_ranges(
 7821            new_selections.iter().map(|selection| selection.range()),
 7822            false,
 7823            false,
 7824            cx,
 7825        );
 7826        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 7827            selections.select(new_selections)
 7828        });
 7829
 7830        Ok(())
 7831    }
 7832
 7833    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 7834        self.push_to_selection_history();
 7835        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7836        self.select_next_match_internal(
 7837            &display_map,
 7838            action.replace_newest,
 7839            Some(Autoscroll::newest()),
 7840            cx,
 7841        )?;
 7842        Ok(())
 7843    }
 7844
 7845    pub fn select_previous(
 7846        &mut self,
 7847        action: &SelectPrevious,
 7848        cx: &mut ViewContext<Self>,
 7849    ) -> Result<()> {
 7850        self.push_to_selection_history();
 7851        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7852        let buffer = &display_map.buffer_snapshot;
 7853        let mut selections = self.selections.all::<usize>(cx);
 7854        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 7855            let query = &select_prev_state.query;
 7856            if !select_prev_state.done {
 7857                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7858                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7859                let mut next_selected_range = None;
 7860                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 7861                let bytes_before_last_selection =
 7862                    buffer.reversed_bytes_in_range(0..last_selection.start);
 7863                let bytes_after_first_selection =
 7864                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 7865                let query_matches = query
 7866                    .stream_find_iter(bytes_before_last_selection)
 7867                    .map(|result| (last_selection.start, result))
 7868                    .chain(
 7869                        query
 7870                            .stream_find_iter(bytes_after_first_selection)
 7871                            .map(|result| (buffer.len(), result)),
 7872                    );
 7873                for (end_offset, query_match) in query_matches {
 7874                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7875                    let offset_range =
 7876                        end_offset - query_match.end()..end_offset - query_match.start();
 7877                    let display_range = offset_range.start.to_display_point(&display_map)
 7878                        ..offset_range.end.to_display_point(&display_map);
 7879
 7880                    if !select_prev_state.wordwise
 7881                        || (!movement::is_inside_word(&display_map, display_range.start)
 7882                            && !movement::is_inside_word(&display_map, display_range.end))
 7883                    {
 7884                        next_selected_range = Some(offset_range);
 7885                        break;
 7886                    }
 7887                }
 7888
 7889                if let Some(next_selected_range) = next_selected_range {
 7890                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 7891                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7892                        if action.replace_newest {
 7893                            s.delete(s.newest_anchor().id);
 7894                        }
 7895                        s.insert_range(next_selected_range);
 7896                    });
 7897                } else {
 7898                    select_prev_state.done = true;
 7899                }
 7900            }
 7901
 7902            self.select_prev_state = Some(select_prev_state);
 7903        } else {
 7904            let mut only_carets = true;
 7905            let mut same_text_selected = true;
 7906            let mut selected_text = None;
 7907
 7908            let mut selections_iter = selections.iter().peekable();
 7909            while let Some(selection) = selections_iter.next() {
 7910                if selection.start != selection.end {
 7911                    only_carets = false;
 7912                }
 7913
 7914                if same_text_selected {
 7915                    if selected_text.is_none() {
 7916                        selected_text =
 7917                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7918                    }
 7919
 7920                    if let Some(next_selection) = selections_iter.peek() {
 7921                        if next_selection.range().len() == selection.range().len() {
 7922                            let next_selected_text = buffer
 7923                                .text_for_range(next_selection.range())
 7924                                .collect::<String>();
 7925                            if Some(next_selected_text) != selected_text {
 7926                                same_text_selected = false;
 7927                                selected_text = None;
 7928                            }
 7929                        } else {
 7930                            same_text_selected = false;
 7931                            selected_text = None;
 7932                        }
 7933                    }
 7934                }
 7935            }
 7936
 7937            if only_carets {
 7938                for selection in &mut selections {
 7939                    let word_range = movement::surrounding_word(
 7940                        &display_map,
 7941                        selection.start.to_display_point(&display_map),
 7942                    );
 7943                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7944                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7945                    selection.goal = SelectionGoal::None;
 7946                    selection.reversed = false;
 7947                }
 7948                if selections.len() == 1 {
 7949                    let selection = selections
 7950                        .last()
 7951                        .expect("ensured that there's only one selection");
 7952                    let query = buffer
 7953                        .text_for_range(selection.start..selection.end)
 7954                        .collect::<String>();
 7955                    let is_empty = query.is_empty();
 7956                    let select_state = SelectNextState {
 7957                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 7958                        wordwise: true,
 7959                        done: is_empty,
 7960                    };
 7961                    self.select_prev_state = Some(select_state);
 7962                } else {
 7963                    self.select_prev_state = None;
 7964                }
 7965
 7966                self.unfold_ranges(
 7967                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 7968                    false,
 7969                    true,
 7970                    cx,
 7971                );
 7972                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7973                    s.select(selections);
 7974                });
 7975            } else if let Some(selected_text) = selected_text {
 7976                self.select_prev_state = Some(SelectNextState {
 7977                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 7978                    wordwise: false,
 7979                    done: false,
 7980                });
 7981                self.select_previous(action, cx)?;
 7982            }
 7983        }
 7984        Ok(())
 7985    }
 7986
 7987    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 7988        let text_layout_details = &self.text_layout_details(cx);
 7989        self.transact(cx, |this, cx| {
 7990            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7991            let mut edits = Vec::new();
 7992            let mut selection_edit_ranges = Vec::new();
 7993            let mut last_toggled_row = None;
 7994            let snapshot = this.buffer.read(cx).read(cx);
 7995            let empty_str: Arc<str> = "".into();
 7996            let mut suffixes_inserted = Vec::new();
 7997
 7998            fn comment_prefix_range(
 7999                snapshot: &MultiBufferSnapshot,
 8000                row: MultiBufferRow,
 8001                comment_prefix: &str,
 8002                comment_prefix_whitespace: &str,
 8003            ) -> Range<Point> {
 8004                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8005
 8006                let mut line_bytes = snapshot
 8007                    .bytes_in_range(start..snapshot.max_point())
 8008                    .flatten()
 8009                    .copied();
 8010
 8011                // If this line currently begins with the line comment prefix, then record
 8012                // the range containing the prefix.
 8013                if line_bytes
 8014                    .by_ref()
 8015                    .take(comment_prefix.len())
 8016                    .eq(comment_prefix.bytes())
 8017                {
 8018                    // Include any whitespace that matches the comment prefix.
 8019                    let matching_whitespace_len = line_bytes
 8020                        .zip(comment_prefix_whitespace.bytes())
 8021                        .take_while(|(a, b)| a == b)
 8022                        .count() as u32;
 8023                    let end = Point::new(
 8024                        start.row,
 8025                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8026                    );
 8027                    start..end
 8028                } else {
 8029                    start..start
 8030                }
 8031            }
 8032
 8033            fn comment_suffix_range(
 8034                snapshot: &MultiBufferSnapshot,
 8035                row: MultiBufferRow,
 8036                comment_suffix: &str,
 8037                comment_suffix_has_leading_space: bool,
 8038            ) -> Range<Point> {
 8039                let end = Point::new(row.0, snapshot.line_len(row));
 8040                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8041
 8042                let mut line_end_bytes = snapshot
 8043                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8044                    .flatten()
 8045                    .copied();
 8046
 8047                let leading_space_len = if suffix_start_column > 0
 8048                    && line_end_bytes.next() == Some(b' ')
 8049                    && comment_suffix_has_leading_space
 8050                {
 8051                    1
 8052                } else {
 8053                    0
 8054                };
 8055
 8056                // If this line currently begins with the line comment prefix, then record
 8057                // the range containing the prefix.
 8058                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8059                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8060                    start..end
 8061                } else {
 8062                    end..end
 8063                }
 8064            }
 8065
 8066            // TODO: Handle selections that cross excerpts
 8067            for selection in &mut selections {
 8068                let start_column = snapshot
 8069                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8070                    .len;
 8071                let language = if let Some(language) =
 8072                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8073                {
 8074                    language
 8075                } else {
 8076                    continue;
 8077                };
 8078
 8079                selection_edit_ranges.clear();
 8080
 8081                // If multiple selections contain a given row, avoid processing that
 8082                // row more than once.
 8083                let mut start_row = MultiBufferRow(selection.start.row);
 8084                if last_toggled_row == Some(start_row) {
 8085                    start_row = start_row.next_row();
 8086                }
 8087                let end_row =
 8088                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8089                        MultiBufferRow(selection.end.row - 1)
 8090                    } else {
 8091                        MultiBufferRow(selection.end.row)
 8092                    };
 8093                last_toggled_row = Some(end_row);
 8094
 8095                if start_row > end_row {
 8096                    continue;
 8097                }
 8098
 8099                // If the language has line comments, toggle those.
 8100                let full_comment_prefixes = language.line_comment_prefixes();
 8101                if !full_comment_prefixes.is_empty() {
 8102                    let first_prefix = full_comment_prefixes
 8103                        .first()
 8104                        .expect("prefixes is non-empty");
 8105                    let prefix_trimmed_lengths = full_comment_prefixes
 8106                        .iter()
 8107                        .map(|p| p.trim_end_matches(' ').len())
 8108                        .collect::<SmallVec<[usize; 4]>>();
 8109
 8110                    let mut all_selection_lines_are_comments = true;
 8111
 8112                    for row in start_row.0..=end_row.0 {
 8113                        let row = MultiBufferRow(row);
 8114                        if start_row < end_row && snapshot.is_line_blank(row) {
 8115                            continue;
 8116                        }
 8117
 8118                        let prefix_range = full_comment_prefixes
 8119                            .iter()
 8120                            .zip(prefix_trimmed_lengths.iter().copied())
 8121                            .map(|(prefix, trimmed_prefix_len)| {
 8122                                comment_prefix_range(
 8123                                    snapshot.deref(),
 8124                                    row,
 8125                                    &prefix[..trimmed_prefix_len],
 8126                                    &prefix[trimmed_prefix_len..],
 8127                                )
 8128                            })
 8129                            .max_by_key(|range| range.end.column - range.start.column)
 8130                            .expect("prefixes is non-empty");
 8131
 8132                        if prefix_range.is_empty() {
 8133                            all_selection_lines_are_comments = false;
 8134                        }
 8135
 8136                        selection_edit_ranges.push(prefix_range);
 8137                    }
 8138
 8139                    if all_selection_lines_are_comments {
 8140                        edits.extend(
 8141                            selection_edit_ranges
 8142                                .iter()
 8143                                .cloned()
 8144                                .map(|range| (range, empty_str.clone())),
 8145                        );
 8146                    } else {
 8147                        let min_column = selection_edit_ranges
 8148                            .iter()
 8149                            .map(|range| range.start.column)
 8150                            .min()
 8151                            .unwrap_or(0);
 8152                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8153                            let position = Point::new(range.start.row, min_column);
 8154                            (position..position, first_prefix.clone())
 8155                        }));
 8156                    }
 8157                } else if let Some((full_comment_prefix, comment_suffix)) =
 8158                    language.block_comment_delimiters()
 8159                {
 8160                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8161                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8162                    let prefix_range = comment_prefix_range(
 8163                        snapshot.deref(),
 8164                        start_row,
 8165                        comment_prefix,
 8166                        comment_prefix_whitespace,
 8167                    );
 8168                    let suffix_range = comment_suffix_range(
 8169                        snapshot.deref(),
 8170                        end_row,
 8171                        comment_suffix.trim_start_matches(' '),
 8172                        comment_suffix.starts_with(' '),
 8173                    );
 8174
 8175                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8176                        edits.push((
 8177                            prefix_range.start..prefix_range.start,
 8178                            full_comment_prefix.clone(),
 8179                        ));
 8180                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8181                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8182                    } else {
 8183                        edits.push((prefix_range, empty_str.clone()));
 8184                        edits.push((suffix_range, empty_str.clone()));
 8185                    }
 8186                } else {
 8187                    continue;
 8188                }
 8189            }
 8190
 8191            drop(snapshot);
 8192            this.buffer.update(cx, |buffer, cx| {
 8193                buffer.edit(edits, None, cx);
 8194            });
 8195
 8196            // Adjust selections so that they end before any comment suffixes that
 8197            // were inserted.
 8198            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8199            let mut selections = this.selections.all::<Point>(cx);
 8200            let snapshot = this.buffer.read(cx).read(cx);
 8201            for selection in &mut selections {
 8202                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8203                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8204                        Ordering::Less => {
 8205                            suffixes_inserted.next();
 8206                            continue;
 8207                        }
 8208                        Ordering::Greater => break,
 8209                        Ordering::Equal => {
 8210                            if selection.end.column == snapshot.line_len(row) {
 8211                                if selection.is_empty() {
 8212                                    selection.start.column -= suffix_len as u32;
 8213                                }
 8214                                selection.end.column -= suffix_len as u32;
 8215                            }
 8216                            break;
 8217                        }
 8218                    }
 8219                }
 8220            }
 8221
 8222            drop(snapshot);
 8223            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8224
 8225            let selections = this.selections.all::<Point>(cx);
 8226            let selections_on_single_row = selections.windows(2).all(|selections| {
 8227                selections[0].start.row == selections[1].start.row
 8228                    && selections[0].end.row == selections[1].end.row
 8229                    && selections[0].start.row == selections[0].end.row
 8230            });
 8231            let selections_selecting = selections
 8232                .iter()
 8233                .any(|selection| selection.start != selection.end);
 8234            let advance_downwards = action.advance_downwards
 8235                && selections_on_single_row
 8236                && !selections_selecting
 8237                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8238
 8239            if advance_downwards {
 8240                let snapshot = this.buffer.read(cx).snapshot(cx);
 8241
 8242                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8243                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8244                        let mut point = display_point.to_point(display_snapshot);
 8245                        point.row += 1;
 8246                        point = snapshot.clip_point(point, Bias::Left);
 8247                        let display_point = point.to_display_point(display_snapshot);
 8248                        let goal = SelectionGoal::HorizontalPosition(
 8249                            display_snapshot
 8250                                .x_for_display_point(display_point, &text_layout_details)
 8251                                .into(),
 8252                        );
 8253                        (display_point, goal)
 8254                    })
 8255                });
 8256            }
 8257        });
 8258    }
 8259
 8260    pub fn select_enclosing_symbol(
 8261        &mut self,
 8262        _: &SelectEnclosingSymbol,
 8263        cx: &mut ViewContext<Self>,
 8264    ) {
 8265        let buffer = self.buffer.read(cx).snapshot(cx);
 8266        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8267
 8268        fn update_selection(
 8269            selection: &Selection<usize>,
 8270            buffer_snap: &MultiBufferSnapshot,
 8271        ) -> Option<Selection<usize>> {
 8272            let cursor = selection.head();
 8273            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8274            for symbol in symbols.iter().rev() {
 8275                let start = symbol.range.start.to_offset(&buffer_snap);
 8276                let end = symbol.range.end.to_offset(&buffer_snap);
 8277                let new_range = start..end;
 8278                if start < selection.start || end > selection.end {
 8279                    return Some(Selection {
 8280                        id: selection.id,
 8281                        start: new_range.start,
 8282                        end: new_range.end,
 8283                        goal: SelectionGoal::None,
 8284                        reversed: selection.reversed,
 8285                    });
 8286                }
 8287            }
 8288            None
 8289        }
 8290
 8291        let mut selected_larger_symbol = false;
 8292        let new_selections = old_selections
 8293            .iter()
 8294            .map(|selection| match update_selection(selection, &buffer) {
 8295                Some(new_selection) => {
 8296                    if new_selection.range() != selection.range() {
 8297                        selected_larger_symbol = true;
 8298                    }
 8299                    new_selection
 8300                }
 8301                None => selection.clone(),
 8302            })
 8303            .collect::<Vec<_>>();
 8304
 8305        if selected_larger_symbol {
 8306            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8307                s.select(new_selections);
 8308            });
 8309        }
 8310    }
 8311
 8312    pub fn select_larger_syntax_node(
 8313        &mut self,
 8314        _: &SelectLargerSyntaxNode,
 8315        cx: &mut ViewContext<Self>,
 8316    ) {
 8317        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8318        let buffer = self.buffer.read(cx).snapshot(cx);
 8319        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8320
 8321        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8322        let mut selected_larger_node = false;
 8323        let new_selections = old_selections
 8324            .iter()
 8325            .map(|selection| {
 8326                let old_range = selection.start..selection.end;
 8327                let mut new_range = old_range.clone();
 8328                while let Some(containing_range) =
 8329                    buffer.range_for_syntax_ancestor(new_range.clone())
 8330                {
 8331                    new_range = containing_range;
 8332                    if !display_map.intersects_fold(new_range.start)
 8333                        && !display_map.intersects_fold(new_range.end)
 8334                    {
 8335                        break;
 8336                    }
 8337                }
 8338
 8339                selected_larger_node |= new_range != old_range;
 8340                Selection {
 8341                    id: selection.id,
 8342                    start: new_range.start,
 8343                    end: new_range.end,
 8344                    goal: SelectionGoal::None,
 8345                    reversed: selection.reversed,
 8346                }
 8347            })
 8348            .collect::<Vec<_>>();
 8349
 8350        if selected_larger_node {
 8351            stack.push(old_selections);
 8352            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8353                s.select(new_selections);
 8354            });
 8355        }
 8356        self.select_larger_syntax_node_stack = stack;
 8357    }
 8358
 8359    pub fn select_smaller_syntax_node(
 8360        &mut self,
 8361        _: &SelectSmallerSyntaxNode,
 8362        cx: &mut ViewContext<Self>,
 8363    ) {
 8364        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8365        if let Some(selections) = stack.pop() {
 8366            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8367                s.select(selections.to_vec());
 8368            });
 8369        }
 8370        self.select_larger_syntax_node_stack = stack;
 8371    }
 8372
 8373    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8374        if !EditorSettings::get_global(cx).gutter.runnables {
 8375            self.clear_tasks();
 8376            return Task::ready(());
 8377        }
 8378        let project = self.project.clone();
 8379        cx.spawn(|this, mut cx| async move {
 8380            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8381                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8382            }) else {
 8383                return;
 8384            };
 8385
 8386            let Some(project) = project else {
 8387                return;
 8388            };
 8389
 8390            let hide_runnables = project
 8391                .update(&mut cx, |project, cx| {
 8392                    // Do not display any test indicators in non-dev server remote projects.
 8393                    project.is_remote() && project.ssh_connection_string(cx).is_none()
 8394                })
 8395                .unwrap_or(true);
 8396            if hide_runnables {
 8397                return;
 8398            }
 8399            let new_rows =
 8400                cx.background_executor()
 8401                    .spawn({
 8402                        let snapshot = display_snapshot.clone();
 8403                        async move {
 8404                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8405                        }
 8406                    })
 8407                    .await;
 8408            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8409
 8410            this.update(&mut cx, |this, _| {
 8411                this.clear_tasks();
 8412                for (key, value) in rows {
 8413                    this.insert_tasks(key, value);
 8414                }
 8415            })
 8416            .ok();
 8417        })
 8418    }
 8419    fn fetch_runnable_ranges(
 8420        snapshot: &DisplaySnapshot,
 8421        range: Range<Anchor>,
 8422    ) -> Vec<language::RunnableRange> {
 8423        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8424    }
 8425
 8426    fn runnable_rows(
 8427        project: Model<Project>,
 8428        snapshot: DisplaySnapshot,
 8429        runnable_ranges: Vec<RunnableRange>,
 8430        mut cx: AsyncWindowContext,
 8431    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8432        runnable_ranges
 8433            .into_iter()
 8434            .filter_map(|mut runnable| {
 8435                let tasks = cx
 8436                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8437                    .ok()?;
 8438                if tasks.is_empty() {
 8439                    return None;
 8440                }
 8441
 8442                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8443
 8444                let row = snapshot
 8445                    .buffer_snapshot
 8446                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8447                    .1
 8448                    .start
 8449                    .row;
 8450
 8451                let context_range =
 8452                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8453                Some((
 8454                    (runnable.buffer_id, row),
 8455                    RunnableTasks {
 8456                        templates: tasks,
 8457                        offset: MultiBufferOffset(runnable.run_range.start),
 8458                        context_range,
 8459                        column: point.column,
 8460                        extra_variables: runnable.extra_captures,
 8461                    },
 8462                ))
 8463            })
 8464            .collect()
 8465    }
 8466
 8467    fn templates_with_tags(
 8468        project: &Model<Project>,
 8469        runnable: &mut Runnable,
 8470        cx: &WindowContext<'_>,
 8471    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8472        let (inventory, worktree_id) = project.read_with(cx, |project, cx| {
 8473            let worktree_id = project
 8474                .buffer_for_id(runnable.buffer)
 8475                .and_then(|buffer| buffer.read(cx).file())
 8476                .map(|file| WorktreeId::from_usize(file.worktree_id()));
 8477
 8478            (project.task_inventory().clone(), worktree_id)
 8479        });
 8480
 8481        let inventory = inventory.read(cx);
 8482        let tags = mem::take(&mut runnable.tags);
 8483        let mut tags: Vec<_> = tags
 8484            .into_iter()
 8485            .flat_map(|tag| {
 8486                let tag = tag.0.clone();
 8487                inventory
 8488                    .list_tasks(Some(runnable.language.clone()), worktree_id)
 8489                    .into_iter()
 8490                    .filter(move |(_, template)| {
 8491                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8492                    })
 8493            })
 8494            .sorted_by_key(|(kind, _)| kind.to_owned())
 8495            .collect();
 8496        if let Some((leading_tag_source, _)) = tags.first() {
 8497            // Strongest source wins; if we have worktree tag binding, prefer that to
 8498            // global and language bindings;
 8499            // if we have a global binding, prefer that to language binding.
 8500            let first_mismatch = tags
 8501                .iter()
 8502                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8503            if let Some(index) = first_mismatch {
 8504                tags.truncate(index);
 8505            }
 8506        }
 8507
 8508        tags
 8509    }
 8510
 8511    pub fn move_to_enclosing_bracket(
 8512        &mut self,
 8513        _: &MoveToEnclosingBracket,
 8514        cx: &mut ViewContext<Self>,
 8515    ) {
 8516        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8517            s.move_offsets_with(|snapshot, selection| {
 8518                let Some(enclosing_bracket_ranges) =
 8519                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8520                else {
 8521                    return;
 8522                };
 8523
 8524                let mut best_length = usize::MAX;
 8525                let mut best_inside = false;
 8526                let mut best_in_bracket_range = false;
 8527                let mut best_destination = None;
 8528                for (open, close) in enclosing_bracket_ranges {
 8529                    let close = close.to_inclusive();
 8530                    let length = close.end() - open.start;
 8531                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8532                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8533                        || close.contains(&selection.head());
 8534
 8535                    // If best is next to a bracket and current isn't, skip
 8536                    if !in_bracket_range && best_in_bracket_range {
 8537                        continue;
 8538                    }
 8539
 8540                    // Prefer smaller lengths unless best is inside and current isn't
 8541                    if length > best_length && (best_inside || !inside) {
 8542                        continue;
 8543                    }
 8544
 8545                    best_length = length;
 8546                    best_inside = inside;
 8547                    best_in_bracket_range = in_bracket_range;
 8548                    best_destination = Some(
 8549                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8550                            if inside {
 8551                                open.end
 8552                            } else {
 8553                                open.start
 8554                            }
 8555                        } else {
 8556                            if inside {
 8557                                *close.start()
 8558                            } else {
 8559                                *close.end()
 8560                            }
 8561                        },
 8562                    );
 8563                }
 8564
 8565                if let Some(destination) = best_destination {
 8566                    selection.collapse_to(destination, SelectionGoal::None);
 8567                }
 8568            })
 8569        });
 8570    }
 8571
 8572    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 8573        self.end_selection(cx);
 8574        self.selection_history.mode = SelectionHistoryMode::Undoing;
 8575        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 8576            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8577            self.select_next_state = entry.select_next_state;
 8578            self.select_prev_state = entry.select_prev_state;
 8579            self.add_selections_state = entry.add_selections_state;
 8580            self.request_autoscroll(Autoscroll::newest(), cx);
 8581        }
 8582        self.selection_history.mode = SelectionHistoryMode::Normal;
 8583    }
 8584
 8585    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 8586        self.end_selection(cx);
 8587        self.selection_history.mode = SelectionHistoryMode::Redoing;
 8588        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 8589            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8590            self.select_next_state = entry.select_next_state;
 8591            self.select_prev_state = entry.select_prev_state;
 8592            self.add_selections_state = entry.add_selections_state;
 8593            self.request_autoscroll(Autoscroll::newest(), cx);
 8594        }
 8595        self.selection_history.mode = SelectionHistoryMode::Normal;
 8596    }
 8597
 8598    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 8599        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 8600    }
 8601
 8602    pub fn expand_excerpts_down(
 8603        &mut self,
 8604        action: &ExpandExcerptsDown,
 8605        cx: &mut ViewContext<Self>,
 8606    ) {
 8607        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 8608    }
 8609
 8610    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 8611        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 8612    }
 8613
 8614    pub fn expand_excerpts_for_direction(
 8615        &mut self,
 8616        lines: u32,
 8617        direction: ExpandExcerptDirection,
 8618        cx: &mut ViewContext<Self>,
 8619    ) {
 8620        let selections = self.selections.disjoint_anchors();
 8621
 8622        let lines = if lines == 0 {
 8623            EditorSettings::get_global(cx).expand_excerpt_lines
 8624        } else {
 8625            lines
 8626        };
 8627
 8628        self.buffer.update(cx, |buffer, cx| {
 8629            buffer.expand_excerpts(
 8630                selections
 8631                    .into_iter()
 8632                    .map(|selection| selection.head().excerpt_id)
 8633                    .dedup(),
 8634                lines,
 8635                direction,
 8636                cx,
 8637            )
 8638        })
 8639    }
 8640
 8641    pub fn expand_excerpt(
 8642        &mut self,
 8643        excerpt: ExcerptId,
 8644        direction: ExpandExcerptDirection,
 8645        cx: &mut ViewContext<Self>,
 8646    ) {
 8647        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 8648        self.buffer.update(cx, |buffer, cx| {
 8649            buffer.expand_excerpts([excerpt], lines, direction, cx)
 8650        })
 8651    }
 8652
 8653    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8654        self.go_to_diagnostic_impl(Direction::Next, cx)
 8655    }
 8656
 8657    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8658        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8659    }
 8660
 8661    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8662        let buffer = self.buffer.read(cx).snapshot(cx);
 8663        let selection = self.selections.newest::<usize>(cx);
 8664
 8665        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8666        if direction == Direction::Next {
 8667            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8668                let (group_id, jump_to) = popover.activation_info();
 8669                if self.activate_diagnostics(group_id, cx) {
 8670                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8671                        let mut new_selection = s.newest_anchor().clone();
 8672                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 8673                        s.select_anchors(vec![new_selection.clone()]);
 8674                    });
 8675                }
 8676                return;
 8677            }
 8678        }
 8679
 8680        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 8681            active_diagnostics
 8682                .primary_range
 8683                .to_offset(&buffer)
 8684                .to_inclusive()
 8685        });
 8686        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 8687            if active_primary_range.contains(&selection.head()) {
 8688                *active_primary_range.start()
 8689            } else {
 8690                selection.head()
 8691            }
 8692        } else {
 8693            selection.head()
 8694        };
 8695        let snapshot = self.snapshot(cx);
 8696        loop {
 8697            let diagnostics = if direction == Direction::Prev {
 8698                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 8699            } else {
 8700                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 8701            }
 8702            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 8703            let group = diagnostics
 8704                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 8705                // be sorted in a stable way
 8706                // skip until we are at current active diagnostic, if it exists
 8707                .skip_while(|entry| {
 8708                    (match direction {
 8709                        Direction::Prev => entry.range.start >= search_start,
 8710                        Direction::Next => entry.range.start <= search_start,
 8711                    }) && self
 8712                        .active_diagnostics
 8713                        .as_ref()
 8714                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 8715                })
 8716                .find_map(|entry| {
 8717                    if entry.diagnostic.is_primary
 8718                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 8719                        && !entry.range.is_empty()
 8720                        // if we match with the active diagnostic, skip it
 8721                        && Some(entry.diagnostic.group_id)
 8722                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 8723                    {
 8724                        Some((entry.range, entry.diagnostic.group_id))
 8725                    } else {
 8726                        None
 8727                    }
 8728                });
 8729
 8730            if let Some((primary_range, group_id)) = group {
 8731                if self.activate_diagnostics(group_id, cx) {
 8732                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8733                        s.select(vec![Selection {
 8734                            id: selection.id,
 8735                            start: primary_range.start,
 8736                            end: primary_range.start,
 8737                            reversed: false,
 8738                            goal: SelectionGoal::None,
 8739                        }]);
 8740                    });
 8741                }
 8742                break;
 8743            } else {
 8744                // Cycle around to the start of the buffer, potentially moving back to the start of
 8745                // the currently active diagnostic.
 8746                active_primary_range.take();
 8747                if direction == Direction::Prev {
 8748                    if search_start == buffer.len() {
 8749                        break;
 8750                    } else {
 8751                        search_start = buffer.len();
 8752                    }
 8753                } else if search_start == 0 {
 8754                    break;
 8755                } else {
 8756                    search_start = 0;
 8757                }
 8758            }
 8759        }
 8760    }
 8761
 8762    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 8763        let snapshot = self
 8764            .display_map
 8765            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8766        let selection = self.selections.newest::<Point>(cx);
 8767
 8768        if !self.seek_in_direction(
 8769            &snapshot,
 8770            selection.head(),
 8771            false,
 8772            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8773                MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
 8774            ),
 8775            cx,
 8776        ) {
 8777            let wrapped_point = Point::zero();
 8778            self.seek_in_direction(
 8779                &snapshot,
 8780                wrapped_point,
 8781                true,
 8782                snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8783                    MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 8784                ),
 8785                cx,
 8786            );
 8787        }
 8788    }
 8789
 8790    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 8791        let snapshot = self
 8792            .display_map
 8793            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8794        let selection = self.selections.newest::<Point>(cx);
 8795
 8796        if !self.seek_in_direction(
 8797            &snapshot,
 8798            selection.head(),
 8799            false,
 8800            snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8801                MultiBufferRow(0)..MultiBufferRow(selection.head().row),
 8802            ),
 8803            cx,
 8804        ) {
 8805            let wrapped_point = snapshot.buffer_snapshot.max_point();
 8806            self.seek_in_direction(
 8807                &snapshot,
 8808                wrapped_point,
 8809                true,
 8810                snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8811                    MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
 8812                ),
 8813                cx,
 8814            );
 8815        }
 8816    }
 8817
 8818    fn seek_in_direction(
 8819        &mut self,
 8820        snapshot: &DisplaySnapshot,
 8821        initial_point: Point,
 8822        is_wrapped: bool,
 8823        hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
 8824        cx: &mut ViewContext<Editor>,
 8825    ) -> bool {
 8826        let display_point = initial_point.to_display_point(snapshot);
 8827        let mut hunks = hunks
 8828            .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
 8829            .filter(|hunk| {
 8830                if is_wrapped {
 8831                    true
 8832                } else {
 8833                    !hunk.contains_display_row(display_point.row())
 8834                }
 8835            })
 8836            .dedup();
 8837
 8838        if let Some(hunk) = hunks.next() {
 8839            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8840                let row = hunk.start_display_row();
 8841                let point = DisplayPoint::new(row, 0);
 8842                s.select_display_ranges([point..point]);
 8843            });
 8844
 8845            true
 8846        } else {
 8847            false
 8848        }
 8849    }
 8850
 8851    pub fn go_to_definition(
 8852        &mut self,
 8853        _: &GoToDefinition,
 8854        cx: &mut ViewContext<Self>,
 8855    ) -> Task<Result<bool>> {
 8856        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
 8857    }
 8858
 8859    pub fn go_to_implementation(
 8860        &mut self,
 8861        _: &GoToImplementation,
 8862        cx: &mut ViewContext<Self>,
 8863    ) -> Task<Result<bool>> {
 8864        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 8865    }
 8866
 8867    pub fn go_to_implementation_split(
 8868        &mut self,
 8869        _: &GoToImplementationSplit,
 8870        cx: &mut ViewContext<Self>,
 8871    ) -> Task<Result<bool>> {
 8872        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 8873    }
 8874
 8875    pub fn go_to_type_definition(
 8876        &mut self,
 8877        _: &GoToTypeDefinition,
 8878        cx: &mut ViewContext<Self>,
 8879    ) -> Task<Result<bool>> {
 8880        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 8881    }
 8882
 8883    pub fn go_to_definition_split(
 8884        &mut self,
 8885        _: &GoToDefinitionSplit,
 8886        cx: &mut ViewContext<Self>,
 8887    ) -> Task<Result<bool>> {
 8888        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 8889    }
 8890
 8891    pub fn go_to_type_definition_split(
 8892        &mut self,
 8893        _: &GoToTypeDefinitionSplit,
 8894        cx: &mut ViewContext<Self>,
 8895    ) -> Task<Result<bool>> {
 8896        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 8897    }
 8898
 8899    fn go_to_definition_of_kind(
 8900        &mut self,
 8901        kind: GotoDefinitionKind,
 8902        split: bool,
 8903        cx: &mut ViewContext<Self>,
 8904    ) -> Task<Result<bool>> {
 8905        let Some(workspace) = self.workspace() else {
 8906            return Task::ready(Ok(false));
 8907        };
 8908        let buffer = self.buffer.read(cx);
 8909        let head = self.selections.newest::<usize>(cx).head();
 8910        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 8911            text_anchor
 8912        } else {
 8913            return Task::ready(Ok(false));
 8914        };
 8915
 8916        let project = workspace.read(cx).project().clone();
 8917        let definitions = project.update(cx, |project, cx| match kind {
 8918            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 8919            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 8920            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 8921        });
 8922
 8923        cx.spawn(|editor, mut cx| async move {
 8924            let definitions = definitions.await?;
 8925            let navigated = editor
 8926                .update(&mut cx, |editor, cx| {
 8927                    editor.navigate_to_hover_links(
 8928                        Some(kind),
 8929                        definitions
 8930                            .into_iter()
 8931                            .filter(|location| {
 8932                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 8933                            })
 8934                            .map(HoverLink::Text)
 8935                            .collect::<Vec<_>>(),
 8936                        split,
 8937                        cx,
 8938                    )
 8939                })?
 8940                .await?;
 8941            anyhow::Ok(navigated)
 8942        })
 8943    }
 8944
 8945    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 8946        let position = self.selections.newest_anchor().head();
 8947        let Some((buffer, buffer_position)) =
 8948            self.buffer.read(cx).text_anchor_for_position(position, cx)
 8949        else {
 8950            return;
 8951        };
 8952
 8953        cx.spawn(|editor, mut cx| async move {
 8954            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 8955                editor.update(&mut cx, |_, cx| {
 8956                    cx.open_url(&url);
 8957                })
 8958            } else {
 8959                Ok(())
 8960            }
 8961        })
 8962        .detach();
 8963    }
 8964
 8965    pub(crate) fn navigate_to_hover_links(
 8966        &mut self,
 8967        kind: Option<GotoDefinitionKind>,
 8968        mut definitions: Vec<HoverLink>,
 8969        split: bool,
 8970        cx: &mut ViewContext<Editor>,
 8971    ) -> Task<Result<bool>> {
 8972        // If there is one definition, just open it directly
 8973        if definitions.len() == 1 {
 8974            let definition = definitions.pop().unwrap();
 8975            let target_task = match definition {
 8976                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 8977                HoverLink::InlayHint(lsp_location, server_id) => {
 8978                    self.compute_target_location(lsp_location, server_id, cx)
 8979                }
 8980                HoverLink::Url(url) => {
 8981                    cx.open_url(&url);
 8982                    Task::ready(Ok(None))
 8983                }
 8984            };
 8985            cx.spawn(|editor, mut cx| async move {
 8986                let target = target_task.await.context("target resolution task")?;
 8987                if let Some(target) = target {
 8988                    editor.update(&mut cx, |editor, cx| {
 8989                        let Some(workspace) = editor.workspace() else {
 8990                            return false;
 8991                        };
 8992                        let pane = workspace.read(cx).active_pane().clone();
 8993
 8994                        let range = target.range.to_offset(target.buffer.read(cx));
 8995                        let range = editor.range_for_match(&range);
 8996
 8997                        /// If select range has more than one line, we
 8998                        /// just point the cursor to range.start.
 8999                        fn check_multiline_range(
 9000                            buffer: &Buffer,
 9001                            range: Range<usize>,
 9002                        ) -> Range<usize> {
 9003                            if buffer.offset_to_point(range.start).row
 9004                                == buffer.offset_to_point(range.end).row
 9005                            {
 9006                                range
 9007                            } else {
 9008                                range.start..range.start
 9009                            }
 9010                        }
 9011
 9012                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9013                            let buffer = target.buffer.read(cx);
 9014                            let range = check_multiline_range(buffer, range);
 9015                            editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 9016                                s.select_ranges([range]);
 9017                            });
 9018                        } else {
 9019                            cx.window_context().defer(move |cx| {
 9020                                let target_editor: View<Self> =
 9021                                    workspace.update(cx, |workspace, cx| {
 9022                                        let pane = if split {
 9023                                            workspace.adjacent_pane(cx)
 9024                                        } else {
 9025                                            workspace.active_pane().clone()
 9026                                        };
 9027
 9028                                        workspace.open_project_item(pane, target.buffer.clone(), cx)
 9029                                    });
 9030                                target_editor.update(cx, |target_editor, cx| {
 9031                                    // When selecting a definition in a different buffer, disable the nav history
 9032                                    // to avoid creating a history entry at the previous cursor location.
 9033                                    pane.update(cx, |pane, _| pane.disable_history());
 9034                                    let buffer = target.buffer.read(cx);
 9035                                    let range = check_multiline_range(buffer, range);
 9036                                    target_editor.change_selections(
 9037                                        Some(Autoscroll::focused()),
 9038                                        cx,
 9039                                        |s| {
 9040                                            s.select_ranges([range]);
 9041                                        },
 9042                                    );
 9043                                    pane.update(cx, |pane, _| pane.enable_history());
 9044                                });
 9045                            });
 9046                        }
 9047                        true
 9048                    })
 9049                } else {
 9050                    Ok(false)
 9051                }
 9052            })
 9053        } else if !definitions.is_empty() {
 9054            let replica_id = self.replica_id(cx);
 9055            cx.spawn(|editor, mut cx| async move {
 9056                let (title, location_tasks, workspace) = editor
 9057                    .update(&mut cx, |editor, cx| {
 9058                        let tab_kind = match kind {
 9059                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9060                            _ => "Definitions",
 9061                        };
 9062                        let title = definitions
 9063                            .iter()
 9064                            .find_map(|definition| match definition {
 9065                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9066                                    let buffer = origin.buffer.read(cx);
 9067                                    format!(
 9068                                        "{} for {}",
 9069                                        tab_kind,
 9070                                        buffer
 9071                                            .text_for_range(origin.range.clone())
 9072                                            .collect::<String>()
 9073                                    )
 9074                                }),
 9075                                HoverLink::InlayHint(_, _) => None,
 9076                                HoverLink::Url(_) => None,
 9077                            })
 9078                            .unwrap_or(tab_kind.to_string());
 9079                        let location_tasks = definitions
 9080                            .into_iter()
 9081                            .map(|definition| match definition {
 9082                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9083                                HoverLink::InlayHint(lsp_location, server_id) => {
 9084                                    editor.compute_target_location(lsp_location, server_id, cx)
 9085                                }
 9086                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9087                            })
 9088                            .collect::<Vec<_>>();
 9089                        (title, location_tasks, editor.workspace().clone())
 9090                    })
 9091                    .context("location tasks preparation")?;
 9092
 9093                let locations = futures::future::join_all(location_tasks)
 9094                    .await
 9095                    .into_iter()
 9096                    .filter_map(|location| location.transpose())
 9097                    .collect::<Result<_>>()
 9098                    .context("location tasks")?;
 9099
 9100                let Some(workspace) = workspace else {
 9101                    return Ok(false);
 9102                };
 9103                let opened = workspace
 9104                    .update(&mut cx, |workspace, cx| {
 9105                        Self::open_locations_in_multibuffer(
 9106                            workspace, locations, replica_id, title, split, cx,
 9107                        )
 9108                    })
 9109                    .ok();
 9110
 9111                anyhow::Ok(opened.is_some())
 9112            })
 9113        } else {
 9114            Task::ready(Ok(false))
 9115        }
 9116    }
 9117
 9118    fn compute_target_location(
 9119        &self,
 9120        lsp_location: lsp::Location,
 9121        server_id: LanguageServerId,
 9122        cx: &mut ViewContext<Editor>,
 9123    ) -> Task<anyhow::Result<Option<Location>>> {
 9124        let Some(project) = self.project.clone() else {
 9125            return Task::Ready(Some(Ok(None)));
 9126        };
 9127
 9128        cx.spawn(move |editor, mut cx| async move {
 9129            let location_task = editor.update(&mut cx, |editor, cx| {
 9130                project.update(cx, |project, cx| {
 9131                    let language_server_name =
 9132                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 9133                            project
 9134                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 9135                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 9136                        });
 9137                    language_server_name.map(|language_server_name| {
 9138                        project.open_local_buffer_via_lsp(
 9139                            lsp_location.uri.clone(),
 9140                            server_id,
 9141                            language_server_name,
 9142                            cx,
 9143                        )
 9144                    })
 9145                })
 9146            })?;
 9147            let location = match location_task {
 9148                Some(task) => Some({
 9149                    let target_buffer_handle = task.await.context("open local buffer")?;
 9150                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9151                        let target_start = target_buffer
 9152                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9153                        let target_end = target_buffer
 9154                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9155                        target_buffer.anchor_after(target_start)
 9156                            ..target_buffer.anchor_before(target_end)
 9157                    })?;
 9158                    Location {
 9159                        buffer: target_buffer_handle,
 9160                        range,
 9161                    }
 9162                }),
 9163                None => None,
 9164            };
 9165            Ok(location)
 9166        })
 9167    }
 9168
 9169    pub fn find_all_references(
 9170        &mut self,
 9171        _: &FindAllReferences,
 9172        cx: &mut ViewContext<Self>,
 9173    ) -> Option<Task<Result<()>>> {
 9174        let multi_buffer = self.buffer.read(cx);
 9175        let selection = self.selections.newest::<usize>(cx);
 9176        let head = selection.head();
 9177
 9178        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9179        let head_anchor = multi_buffer_snapshot.anchor_at(
 9180            head,
 9181            if head < selection.tail() {
 9182                Bias::Right
 9183            } else {
 9184                Bias::Left
 9185            },
 9186        );
 9187
 9188        match self
 9189            .find_all_references_task_sources
 9190            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9191        {
 9192            Ok(_) => {
 9193                log::info!(
 9194                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9195                );
 9196                return None;
 9197            }
 9198            Err(i) => {
 9199                self.find_all_references_task_sources.insert(i, head_anchor);
 9200            }
 9201        }
 9202
 9203        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9204        let replica_id = self.replica_id(cx);
 9205        let workspace = self.workspace()?;
 9206        let project = workspace.read(cx).project().clone();
 9207        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9208        Some(cx.spawn(|editor, mut cx| async move {
 9209            let _cleanup = defer({
 9210                let mut cx = cx.clone();
 9211                move || {
 9212                    let _ = editor.update(&mut cx, |editor, _| {
 9213                        if let Ok(i) =
 9214                            editor
 9215                                .find_all_references_task_sources
 9216                                .binary_search_by(|anchor| {
 9217                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9218                                })
 9219                        {
 9220                            editor.find_all_references_task_sources.remove(i);
 9221                        }
 9222                    });
 9223                }
 9224            });
 9225
 9226            let locations = references.await?;
 9227            if locations.is_empty() {
 9228                return anyhow::Ok(());
 9229            }
 9230
 9231            workspace.update(&mut cx, |workspace, cx| {
 9232                let title = locations
 9233                    .first()
 9234                    .as_ref()
 9235                    .map(|location| {
 9236                        let buffer = location.buffer.read(cx);
 9237                        format!(
 9238                            "References to `{}`",
 9239                            buffer
 9240                                .text_for_range(location.range.clone())
 9241                                .collect::<String>()
 9242                        )
 9243                    })
 9244                    .unwrap();
 9245                Self::open_locations_in_multibuffer(
 9246                    workspace, locations, replica_id, title, false, cx,
 9247                );
 9248            })
 9249        }))
 9250    }
 9251
 9252    /// Opens a multibuffer with the given project locations in it
 9253    pub fn open_locations_in_multibuffer(
 9254        workspace: &mut Workspace,
 9255        mut locations: Vec<Location>,
 9256        replica_id: ReplicaId,
 9257        title: String,
 9258        split: bool,
 9259        cx: &mut ViewContext<Workspace>,
 9260    ) {
 9261        // If there are multiple definitions, open them in a multibuffer
 9262        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9263        let mut locations = locations.into_iter().peekable();
 9264        let mut ranges_to_highlight = Vec::new();
 9265        let capability = workspace.project().read(cx).capability();
 9266
 9267        let excerpt_buffer = cx.new_model(|cx| {
 9268            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 9269            while let Some(location) = locations.next() {
 9270                let buffer = location.buffer.read(cx);
 9271                let mut ranges_for_buffer = Vec::new();
 9272                let range = location.range.to_offset(buffer);
 9273                ranges_for_buffer.push(range.clone());
 9274
 9275                while let Some(next_location) = locations.peek() {
 9276                    if next_location.buffer == location.buffer {
 9277                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9278                        locations.next();
 9279                    } else {
 9280                        break;
 9281                    }
 9282                }
 9283
 9284                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9285                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9286                    location.buffer.clone(),
 9287                    ranges_for_buffer,
 9288                    DEFAULT_MULTIBUFFER_CONTEXT,
 9289                    cx,
 9290                ))
 9291            }
 9292
 9293            multibuffer.with_title(title)
 9294        });
 9295
 9296        let editor = cx.new_view(|cx| {
 9297            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9298        });
 9299        editor.update(cx, |editor, cx| {
 9300            if let Some(first_range) = ranges_to_highlight.first() {
 9301                editor.change_selections(None, cx, |selections| {
 9302                    selections.clear_disjoint();
 9303                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9304                });
 9305            }
 9306            editor.highlight_background::<Self>(
 9307                &ranges_to_highlight,
 9308                |theme| theme.editor_highlighted_line_background,
 9309                cx,
 9310            );
 9311        });
 9312
 9313        let item = Box::new(editor);
 9314        let item_id = item.item_id();
 9315
 9316        if split {
 9317            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9318        } else {
 9319            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9320                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9321                    pane.close_current_preview_item(cx)
 9322                } else {
 9323                    None
 9324                }
 9325            });
 9326            workspace.add_item_to_active_pane(item.clone(), destination_index, cx);
 9327        }
 9328        workspace.active_pane().update(cx, |pane, cx| {
 9329            pane.set_preview_item_id(Some(item_id), cx);
 9330        });
 9331    }
 9332
 9333    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9334        use language::ToOffset as _;
 9335
 9336        let project = self.project.clone()?;
 9337        let selection = self.selections.newest_anchor().clone();
 9338        let (cursor_buffer, cursor_buffer_position) = self
 9339            .buffer
 9340            .read(cx)
 9341            .text_anchor_for_position(selection.head(), cx)?;
 9342        let (tail_buffer, cursor_buffer_position_end) = self
 9343            .buffer
 9344            .read(cx)
 9345            .text_anchor_for_position(selection.tail(), cx)?;
 9346        if tail_buffer != cursor_buffer {
 9347            return None;
 9348        }
 9349
 9350        let snapshot = cursor_buffer.read(cx).snapshot();
 9351        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9352        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9353        let prepare_rename = project.update(cx, |project, cx| {
 9354            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 9355        });
 9356        drop(snapshot);
 9357
 9358        Some(cx.spawn(|this, mut cx| async move {
 9359            let rename_range = if let Some(range) = prepare_rename.await? {
 9360                Some(range)
 9361            } else {
 9362                this.update(&mut cx, |this, cx| {
 9363                    let buffer = this.buffer.read(cx).snapshot(cx);
 9364                    let mut buffer_highlights = this
 9365                        .document_highlights_for_position(selection.head(), &buffer)
 9366                        .filter(|highlight| {
 9367                            highlight.start.excerpt_id == selection.head().excerpt_id
 9368                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9369                        });
 9370                    buffer_highlights
 9371                        .next()
 9372                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9373                })?
 9374            };
 9375            if let Some(rename_range) = rename_range {
 9376                this.update(&mut cx, |this, cx| {
 9377                    let snapshot = cursor_buffer.read(cx).snapshot();
 9378                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9379                    let cursor_offset_in_rename_range =
 9380                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9381                    let cursor_offset_in_rename_range_end =
 9382                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9383
 9384                    this.take_rename(false, cx);
 9385                    let buffer = this.buffer.read(cx).read(cx);
 9386                    let cursor_offset = selection.head().to_offset(&buffer);
 9387                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9388                    let rename_end = rename_start + rename_buffer_range.len();
 9389                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9390                    let mut old_highlight_id = None;
 9391                    let old_name: Arc<str> = buffer
 9392                        .chunks(rename_start..rename_end, true)
 9393                        .map(|chunk| {
 9394                            if old_highlight_id.is_none() {
 9395                                old_highlight_id = chunk.syntax_highlight_id;
 9396                            }
 9397                            chunk.text
 9398                        })
 9399                        .collect::<String>()
 9400                        .into();
 9401
 9402                    drop(buffer);
 9403
 9404                    // Position the selection in the rename editor so that it matches the current selection.
 9405                    this.show_local_selections = false;
 9406                    let rename_editor = cx.new_view(|cx| {
 9407                        let mut editor = Editor::single_line(cx);
 9408                        editor.buffer.update(cx, |buffer, cx| {
 9409                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9410                        });
 9411                        let rename_selection_range = match cursor_offset_in_rename_range
 9412                            .cmp(&cursor_offset_in_rename_range_end)
 9413                        {
 9414                            Ordering::Equal => {
 9415                                editor.select_all(&SelectAll, cx);
 9416                                return editor;
 9417                            }
 9418                            Ordering::Less => {
 9419                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9420                            }
 9421                            Ordering::Greater => {
 9422                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9423                            }
 9424                        };
 9425                        if rename_selection_range.end > old_name.len() {
 9426                            editor.select_all(&SelectAll, cx);
 9427                        } else {
 9428                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9429                                s.select_ranges([rename_selection_range]);
 9430                            });
 9431                        }
 9432                        editor
 9433                    });
 9434
 9435                    let write_highlights =
 9436                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9437                    let read_highlights =
 9438                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9439                    let ranges = write_highlights
 9440                        .iter()
 9441                        .flat_map(|(_, ranges)| ranges.iter())
 9442                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9443                        .cloned()
 9444                        .collect();
 9445
 9446                    this.highlight_text::<Rename>(
 9447                        ranges,
 9448                        HighlightStyle {
 9449                            fade_out: Some(0.6),
 9450                            ..Default::default()
 9451                        },
 9452                        cx,
 9453                    );
 9454                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9455                    cx.focus(&rename_focus_handle);
 9456                    let block_id = this.insert_blocks(
 9457                        [BlockProperties {
 9458                            style: BlockStyle::Flex,
 9459                            position: range.start,
 9460                            height: 1,
 9461                            render: Box::new({
 9462                                let rename_editor = rename_editor.clone();
 9463                                move |cx: &mut BlockContext| {
 9464                                    let mut text_style = cx.editor_style.text.clone();
 9465                                    if let Some(highlight_style) = old_highlight_id
 9466                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 9467                                    {
 9468                                        text_style = text_style.highlight(highlight_style);
 9469                                    }
 9470                                    div()
 9471                                        .pl(cx.anchor_x)
 9472                                        .child(EditorElement::new(
 9473                                            &rename_editor,
 9474                                            EditorStyle {
 9475                                                background: cx.theme().system().transparent,
 9476                                                local_player: cx.editor_style.local_player,
 9477                                                text: text_style,
 9478                                                scrollbar_width: cx.editor_style.scrollbar_width,
 9479                                                syntax: cx.editor_style.syntax.clone(),
 9480                                                status: cx.editor_style.status.clone(),
 9481                                                inlay_hints_style: HighlightStyle {
 9482                                                    color: Some(cx.theme().status().hint),
 9483                                                    font_weight: Some(FontWeight::BOLD),
 9484                                                    ..HighlightStyle::default()
 9485                                                },
 9486                                                suggestions_style: HighlightStyle {
 9487                                                    color: Some(cx.theme().status().predictive),
 9488                                                    ..HighlightStyle::default()
 9489                                                },
 9490                                            },
 9491                                        ))
 9492                                        .into_any_element()
 9493                                }
 9494                            }),
 9495                            disposition: BlockDisposition::Below,
 9496                        }],
 9497                        Some(Autoscroll::fit()),
 9498                        cx,
 9499                    )[0];
 9500                    this.pending_rename = Some(RenameState {
 9501                        range,
 9502                        old_name,
 9503                        editor: rename_editor,
 9504                        block_id,
 9505                    });
 9506                })?;
 9507            }
 9508
 9509            Ok(())
 9510        }))
 9511    }
 9512
 9513    pub fn confirm_rename(
 9514        &mut self,
 9515        _: &ConfirmRename,
 9516        cx: &mut ViewContext<Self>,
 9517    ) -> Option<Task<Result<()>>> {
 9518        let rename = self.take_rename(false, cx)?;
 9519        let workspace = self.workspace()?;
 9520        let (start_buffer, start) = self
 9521            .buffer
 9522            .read(cx)
 9523            .text_anchor_for_position(rename.range.start, cx)?;
 9524        let (end_buffer, end) = self
 9525            .buffer
 9526            .read(cx)
 9527            .text_anchor_for_position(rename.range.end, cx)?;
 9528        if start_buffer != end_buffer {
 9529            return None;
 9530        }
 9531
 9532        let buffer = start_buffer;
 9533        let range = start..end;
 9534        let old_name = rename.old_name;
 9535        let new_name = rename.editor.read(cx).text(cx);
 9536
 9537        let rename = workspace
 9538            .read(cx)
 9539            .project()
 9540            .clone()
 9541            .update(cx, |project, cx| {
 9542                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 9543            });
 9544        let workspace = workspace.downgrade();
 9545
 9546        Some(cx.spawn(|editor, mut cx| async move {
 9547            let project_transaction = rename.await?;
 9548            Self::open_project_transaction(
 9549                &editor,
 9550                workspace,
 9551                project_transaction,
 9552                format!("Rename: {}{}", old_name, new_name),
 9553                cx.clone(),
 9554            )
 9555            .await?;
 9556
 9557            editor.update(&mut cx, |editor, cx| {
 9558                editor.refresh_document_highlights(cx);
 9559            })?;
 9560            Ok(())
 9561        }))
 9562    }
 9563
 9564    fn take_rename(
 9565        &mut self,
 9566        moving_cursor: bool,
 9567        cx: &mut ViewContext<Self>,
 9568    ) -> Option<RenameState> {
 9569        let rename = self.pending_rename.take()?;
 9570        if rename.editor.focus_handle(cx).is_focused(cx) {
 9571            cx.focus(&self.focus_handle);
 9572        }
 9573
 9574        self.remove_blocks(
 9575            [rename.block_id].into_iter().collect(),
 9576            Some(Autoscroll::fit()),
 9577            cx,
 9578        );
 9579        self.clear_highlights::<Rename>(cx);
 9580        self.show_local_selections = true;
 9581
 9582        if moving_cursor {
 9583            let rename_editor = rename.editor.read(cx);
 9584            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 9585
 9586            // Update the selection to match the position of the selection inside
 9587            // the rename editor.
 9588            let snapshot = self.buffer.read(cx).read(cx);
 9589            let rename_range = rename.range.to_offset(&snapshot);
 9590            let cursor_in_editor = snapshot
 9591                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 9592                .min(rename_range.end);
 9593            drop(snapshot);
 9594
 9595            self.change_selections(None, cx, |s| {
 9596                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 9597            });
 9598        } else {
 9599            self.refresh_document_highlights(cx);
 9600        }
 9601
 9602        Some(rename)
 9603    }
 9604
 9605    pub fn pending_rename(&self) -> Option<&RenameState> {
 9606        self.pending_rename.as_ref()
 9607    }
 9608
 9609    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9610        let project = match &self.project {
 9611            Some(project) => project.clone(),
 9612            None => return None,
 9613        };
 9614
 9615        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 9616    }
 9617
 9618    fn perform_format(
 9619        &mut self,
 9620        project: Model<Project>,
 9621        trigger: FormatTrigger,
 9622        cx: &mut ViewContext<Self>,
 9623    ) -> Task<Result<()>> {
 9624        let buffer = self.buffer().clone();
 9625        let mut buffers = buffer.read(cx).all_buffers();
 9626        if trigger == FormatTrigger::Save {
 9627            buffers.retain(|buffer| buffer.read(cx).is_dirty());
 9628        }
 9629
 9630        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 9631        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 9632
 9633        cx.spawn(|_, mut cx| async move {
 9634            let transaction = futures::select_biased! {
 9635                () = timeout => {
 9636                    log::warn!("timed out waiting for formatting");
 9637                    None
 9638                }
 9639                transaction = format.log_err().fuse() => transaction,
 9640            };
 9641
 9642            buffer
 9643                .update(&mut cx, |buffer, cx| {
 9644                    if let Some(transaction) = transaction {
 9645                        if !buffer.is_singleton() {
 9646                            buffer.push_transaction(&transaction.0, cx);
 9647                        }
 9648                    }
 9649
 9650                    cx.notify();
 9651                })
 9652                .ok();
 9653
 9654            Ok(())
 9655        })
 9656    }
 9657
 9658    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
 9659        if let Some(project) = self.project.clone() {
 9660            self.buffer.update(cx, |multi_buffer, cx| {
 9661                project.update(cx, |project, cx| {
 9662                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
 9663                });
 9664            })
 9665        }
 9666    }
 9667
 9668    fn cancel_language_server_work(
 9669        &mut self,
 9670        _: &CancelLanguageServerWork,
 9671        cx: &mut ViewContext<Self>,
 9672    ) {
 9673        if let Some(project) = self.project.clone() {
 9674            self.buffer.update(cx, |multi_buffer, cx| {
 9675                project.update(cx, |project, cx| {
 9676                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
 9677                });
 9678            })
 9679        }
 9680    }
 9681
 9682    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 9683        cx.show_character_palette();
 9684    }
 9685
 9686    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
 9687        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
 9688            let buffer = self.buffer.read(cx).snapshot(cx);
 9689            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
 9690            let is_valid = buffer
 9691                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
 9692                .any(|entry| {
 9693                    entry.diagnostic.is_primary
 9694                        && !entry.range.is_empty()
 9695                        && entry.range.start == primary_range_start
 9696                        && entry.diagnostic.message == active_diagnostics.primary_message
 9697                });
 9698
 9699            if is_valid != active_diagnostics.is_valid {
 9700                active_diagnostics.is_valid = is_valid;
 9701                let mut new_styles = HashMap::default();
 9702                for (block_id, diagnostic) in &active_diagnostics.blocks {
 9703                    new_styles.insert(
 9704                        *block_id,
 9705                        (
 9706                            None,
 9707                            diagnostic_block_renderer(diagnostic.clone(), is_valid),
 9708                        ),
 9709                    );
 9710                }
 9711                self.display_map.update(cx, |display_map, cx| {
 9712                    display_map.replace_blocks(new_styles, cx)
 9713                });
 9714            }
 9715        }
 9716    }
 9717
 9718    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
 9719        self.dismiss_diagnostics(cx);
 9720        let snapshot = self.snapshot(cx);
 9721        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
 9722            let buffer = self.buffer.read(cx).snapshot(cx);
 9723
 9724            let mut primary_range = None;
 9725            let mut primary_message = None;
 9726            let mut group_end = Point::zero();
 9727            let diagnostic_group = buffer
 9728                .diagnostic_group::<MultiBufferPoint>(group_id)
 9729                .filter_map(|entry| {
 9730                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
 9731                        && (entry.range.start.row == entry.range.end.row
 9732                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
 9733                    {
 9734                        return None;
 9735                    }
 9736                    if entry.range.end > group_end {
 9737                        group_end = entry.range.end;
 9738                    }
 9739                    if entry.diagnostic.is_primary {
 9740                        primary_range = Some(entry.range.clone());
 9741                        primary_message = Some(entry.diagnostic.message.clone());
 9742                    }
 9743                    Some(entry)
 9744                })
 9745                .collect::<Vec<_>>();
 9746            let primary_range = primary_range?;
 9747            let primary_message = primary_message?;
 9748            let primary_range =
 9749                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
 9750
 9751            let blocks = display_map
 9752                .insert_blocks(
 9753                    diagnostic_group.iter().map(|entry| {
 9754                        let diagnostic = entry.diagnostic.clone();
 9755                        let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
 9756                        BlockProperties {
 9757                            style: BlockStyle::Fixed,
 9758                            position: buffer.anchor_after(entry.range.start),
 9759                            height: message_height,
 9760                            render: diagnostic_block_renderer(diagnostic, true),
 9761                            disposition: BlockDisposition::Below,
 9762                        }
 9763                    }),
 9764                    cx,
 9765                )
 9766                .into_iter()
 9767                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
 9768                .collect();
 9769
 9770            Some(ActiveDiagnosticGroup {
 9771                primary_range,
 9772                primary_message,
 9773                group_id,
 9774                blocks,
 9775                is_valid: true,
 9776            })
 9777        });
 9778        self.active_diagnostics.is_some()
 9779    }
 9780
 9781    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
 9782        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
 9783            self.display_map.update(cx, |display_map, cx| {
 9784                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
 9785            });
 9786            cx.notify();
 9787        }
 9788    }
 9789
 9790    pub fn set_selections_from_remote(
 9791        &mut self,
 9792        selections: Vec<Selection<Anchor>>,
 9793        pending_selection: Option<Selection<Anchor>>,
 9794        cx: &mut ViewContext<Self>,
 9795    ) {
 9796        let old_cursor_position = self.selections.newest_anchor().head();
 9797        self.selections.change_with(cx, |s| {
 9798            s.select_anchors(selections);
 9799            if let Some(pending_selection) = pending_selection {
 9800                s.set_pending(pending_selection, SelectMode::Character);
 9801            } else {
 9802                s.clear_pending();
 9803            }
 9804        });
 9805        self.selections_did_change(false, &old_cursor_position, true, cx);
 9806    }
 9807
 9808    fn push_to_selection_history(&mut self) {
 9809        self.selection_history.push(SelectionHistoryEntry {
 9810            selections: self.selections.disjoint_anchors(),
 9811            select_next_state: self.select_next_state.clone(),
 9812            select_prev_state: self.select_prev_state.clone(),
 9813            add_selections_state: self.add_selections_state.clone(),
 9814        });
 9815    }
 9816
 9817    pub fn transact(
 9818        &mut self,
 9819        cx: &mut ViewContext<Self>,
 9820        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
 9821    ) -> Option<TransactionId> {
 9822        self.start_transaction_at(Instant::now(), cx);
 9823        update(self, cx);
 9824        self.end_transaction_at(Instant::now(), cx)
 9825    }
 9826
 9827    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
 9828        self.end_selection(cx);
 9829        if let Some(tx_id) = self
 9830            .buffer
 9831            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
 9832        {
 9833            self.selection_history
 9834                .insert_transaction(tx_id, self.selections.disjoint_anchors());
 9835            cx.emit(EditorEvent::TransactionBegun {
 9836                transaction_id: tx_id,
 9837            })
 9838        }
 9839    }
 9840
 9841    fn end_transaction_at(
 9842        &mut self,
 9843        now: Instant,
 9844        cx: &mut ViewContext<Self>,
 9845    ) -> Option<TransactionId> {
 9846        if let Some(transaction_id) = self
 9847            .buffer
 9848            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 9849        {
 9850            if let Some((_, end_selections)) =
 9851                self.selection_history.transaction_mut(transaction_id)
 9852            {
 9853                *end_selections = Some(self.selections.disjoint_anchors());
 9854            } else {
 9855                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
 9856            }
 9857
 9858            cx.emit(EditorEvent::Edited { transaction_id });
 9859            Some(transaction_id)
 9860        } else {
 9861            None
 9862        }
 9863    }
 9864
 9865    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
 9866        let mut fold_ranges = Vec::new();
 9867
 9868        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9869
 9870        let selections = self.selections.all_adjusted(cx);
 9871        for selection in selections {
 9872            let range = selection.range().sorted();
 9873            let buffer_start_row = range.start.row;
 9874
 9875            for row in (0..=range.end.row).rev() {
 9876                if let Some((foldable_range, fold_text)) =
 9877                    display_map.foldable_range(MultiBufferRow(row))
 9878                {
 9879                    if foldable_range.end.row >= buffer_start_row {
 9880                        fold_ranges.push((foldable_range, fold_text));
 9881                        if row <= range.start.row {
 9882                            break;
 9883                        }
 9884                    }
 9885                }
 9886            }
 9887        }
 9888
 9889        self.fold_ranges(fold_ranges, true, cx);
 9890    }
 9891
 9892    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
 9893        let buffer_row = fold_at.buffer_row;
 9894        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9895
 9896        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
 9897            let autoscroll = self
 9898                .selections
 9899                .all::<Point>(cx)
 9900                .iter()
 9901                .any(|selection| fold_range.overlaps(&selection.range()));
 9902
 9903            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
 9904        }
 9905    }
 9906
 9907    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
 9908        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9909        let buffer = &display_map.buffer_snapshot;
 9910        let selections = self.selections.all::<Point>(cx);
 9911        let ranges = selections
 9912            .iter()
 9913            .map(|s| {
 9914                let range = s.display_range(&display_map).sorted();
 9915                let mut start = range.start.to_point(&display_map);
 9916                let mut end = range.end.to_point(&display_map);
 9917                start.column = 0;
 9918                end.column = buffer.line_len(MultiBufferRow(end.row));
 9919                start..end
 9920            })
 9921            .collect::<Vec<_>>();
 9922
 9923        self.unfold_ranges(ranges, true, true, cx);
 9924    }
 9925
 9926    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
 9927        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9928
 9929        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
 9930            ..Point::new(
 9931                unfold_at.buffer_row.0,
 9932                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
 9933            );
 9934
 9935        let autoscroll = self
 9936            .selections
 9937            .all::<Point>(cx)
 9938            .iter()
 9939            .any(|selection| selection.range().overlaps(&intersection_range));
 9940
 9941        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
 9942    }
 9943
 9944    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
 9945        let selections = self.selections.all::<Point>(cx);
 9946        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9947        let line_mode = self.selections.line_mode;
 9948        let ranges = selections.into_iter().map(|s| {
 9949            if line_mode {
 9950                let start = Point::new(s.start.row, 0);
 9951                let end = Point::new(
 9952                    s.end.row,
 9953                    display_map
 9954                        .buffer_snapshot
 9955                        .line_len(MultiBufferRow(s.end.row)),
 9956                );
 9957                (start..end, display_map.fold_placeholder.clone())
 9958            } else {
 9959                (s.start..s.end, display_map.fold_placeholder.clone())
 9960            }
 9961        });
 9962        self.fold_ranges(ranges, true, cx);
 9963    }
 9964
 9965    pub fn fold_ranges<T: ToOffset + Clone>(
 9966        &mut self,
 9967        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
 9968        auto_scroll: bool,
 9969        cx: &mut ViewContext<Self>,
 9970    ) {
 9971        let mut fold_ranges = Vec::new();
 9972        let mut buffers_affected = HashMap::default();
 9973        let multi_buffer = self.buffer().read(cx);
 9974        for (fold_range, fold_text) in ranges {
 9975            if let Some((_, buffer, _)) =
 9976                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
 9977            {
 9978                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
 9979            };
 9980            fold_ranges.push((fold_range, fold_text));
 9981        }
 9982
 9983        let mut ranges = fold_ranges.into_iter().peekable();
 9984        if ranges.peek().is_some() {
 9985            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
 9986
 9987            if auto_scroll {
 9988                self.request_autoscroll(Autoscroll::fit(), cx);
 9989            }
 9990
 9991            for buffer in buffers_affected.into_values() {
 9992                self.sync_expanded_diff_hunks(buffer, cx);
 9993            }
 9994
 9995            cx.notify();
 9996
 9997            if let Some(active_diagnostics) = self.active_diagnostics.take() {
 9998                // Clear diagnostics block when folding a range that contains it.
 9999                let snapshot = self.snapshot(cx);
10000                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10001                    drop(snapshot);
10002                    self.active_diagnostics = Some(active_diagnostics);
10003                    self.dismiss_diagnostics(cx);
10004                } else {
10005                    self.active_diagnostics = Some(active_diagnostics);
10006                }
10007            }
10008
10009            self.scrollbar_marker_state.dirty = true;
10010        }
10011    }
10012
10013    pub fn unfold_ranges<T: ToOffset + Clone>(
10014        &mut self,
10015        ranges: impl IntoIterator<Item = Range<T>>,
10016        inclusive: bool,
10017        auto_scroll: bool,
10018        cx: &mut ViewContext<Self>,
10019    ) {
10020        let mut unfold_ranges = Vec::new();
10021        let mut buffers_affected = HashMap::default();
10022        let multi_buffer = self.buffer().read(cx);
10023        for range in ranges {
10024            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10025                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10026            };
10027            unfold_ranges.push(range);
10028        }
10029
10030        let mut ranges = unfold_ranges.into_iter().peekable();
10031        if ranges.peek().is_some() {
10032            self.display_map
10033                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10034            if auto_scroll {
10035                self.request_autoscroll(Autoscroll::fit(), cx);
10036            }
10037
10038            for buffer in buffers_affected.into_values() {
10039                self.sync_expanded_diff_hunks(buffer, cx);
10040            }
10041
10042            cx.notify();
10043            self.scrollbar_marker_state.dirty = true;
10044            self.active_indent_guides_state.dirty = true;
10045        }
10046    }
10047
10048    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10049        if hovered != self.gutter_hovered {
10050            self.gutter_hovered = hovered;
10051            cx.notify();
10052        }
10053    }
10054
10055    pub fn insert_blocks(
10056        &mut self,
10057        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10058        autoscroll: Option<Autoscroll>,
10059        cx: &mut ViewContext<Self>,
10060    ) -> Vec<BlockId> {
10061        let blocks = self
10062            .display_map
10063            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10064        if let Some(autoscroll) = autoscroll {
10065            self.request_autoscroll(autoscroll, cx);
10066        }
10067        blocks
10068    }
10069
10070    pub fn replace_blocks(
10071        &mut self,
10072        blocks: HashMap<BlockId, (Option<u8>, RenderBlock)>,
10073        autoscroll: Option<Autoscroll>,
10074        cx: &mut ViewContext<Self>,
10075    ) {
10076        self.display_map
10077            .update(cx, |display_map, cx| display_map.replace_blocks(blocks, cx));
10078        if let Some(autoscroll) = autoscroll {
10079            self.request_autoscroll(autoscroll, cx);
10080        }
10081    }
10082
10083    pub fn remove_blocks(
10084        &mut self,
10085        block_ids: HashSet<BlockId>,
10086        autoscroll: Option<Autoscroll>,
10087        cx: &mut ViewContext<Self>,
10088    ) {
10089        self.display_map.update(cx, |display_map, cx| {
10090            display_map.remove_blocks(block_ids, cx)
10091        });
10092        if let Some(autoscroll) = autoscroll {
10093            self.request_autoscroll(autoscroll, cx);
10094        }
10095    }
10096
10097    pub fn row_for_block(
10098        &self,
10099        block_id: BlockId,
10100        cx: &mut ViewContext<Self>,
10101    ) -> Option<DisplayRow> {
10102        self.display_map
10103            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10104    }
10105
10106    pub fn insert_creases(
10107        &mut self,
10108        creases: impl IntoIterator<Item = Crease>,
10109        cx: &mut ViewContext<Self>,
10110    ) -> Vec<CreaseId> {
10111        self.display_map
10112            .update(cx, |map, cx| map.insert_creases(creases, cx))
10113    }
10114
10115    pub fn remove_creases(
10116        &mut self,
10117        ids: impl IntoIterator<Item = CreaseId>,
10118        cx: &mut ViewContext<Self>,
10119    ) {
10120        self.display_map
10121            .update(cx, |map, cx| map.remove_creases(ids, cx));
10122    }
10123
10124    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10125        self.display_map
10126            .update(cx, |map, cx| map.snapshot(cx))
10127            .longest_row()
10128    }
10129
10130    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10131        self.display_map
10132            .update(cx, |map, cx| map.snapshot(cx))
10133            .max_point()
10134    }
10135
10136    pub fn text(&self, cx: &AppContext) -> String {
10137        self.buffer.read(cx).read(cx).text()
10138    }
10139
10140    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10141        let text = self.text(cx);
10142        let text = text.trim();
10143
10144        if text.is_empty() {
10145            return None;
10146        }
10147
10148        Some(text.to_string())
10149    }
10150
10151    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10152        self.transact(cx, |this, cx| {
10153            this.buffer
10154                .read(cx)
10155                .as_singleton()
10156                .expect("you can only call set_text on editors for singleton buffers")
10157                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10158        });
10159    }
10160
10161    pub fn display_text(&self, cx: &mut AppContext) -> String {
10162        self.display_map
10163            .update(cx, |map, cx| map.snapshot(cx))
10164            .text()
10165    }
10166
10167    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10168        let mut wrap_guides = smallvec::smallvec![];
10169
10170        if self.show_wrap_guides == Some(false) {
10171            return wrap_guides;
10172        }
10173
10174        let settings = self.buffer.read(cx).settings_at(0, cx);
10175        if settings.show_wrap_guides {
10176            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10177                wrap_guides.push((soft_wrap as usize, true));
10178            }
10179            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10180        }
10181
10182        wrap_guides
10183    }
10184
10185    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10186        let settings = self.buffer.read(cx).settings_at(0, cx);
10187        let mode = self
10188            .soft_wrap_mode_override
10189            .unwrap_or_else(|| settings.soft_wrap);
10190        match mode {
10191            language_settings::SoftWrap::None => SoftWrap::None,
10192            language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10193            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10194            language_settings::SoftWrap::PreferredLineLength => {
10195                SoftWrap::Column(settings.preferred_line_length)
10196            }
10197        }
10198    }
10199
10200    pub fn set_soft_wrap_mode(
10201        &mut self,
10202        mode: language_settings::SoftWrap,
10203        cx: &mut ViewContext<Self>,
10204    ) {
10205        self.soft_wrap_mode_override = Some(mode);
10206        cx.notify();
10207    }
10208
10209    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10210        let rem_size = cx.rem_size();
10211        self.display_map.update(cx, |map, cx| {
10212            map.set_font(
10213                style.text.font(),
10214                style.text.font_size.to_pixels(rem_size),
10215                cx,
10216            )
10217        });
10218        self.style = Some(style);
10219    }
10220
10221    pub fn style(&self) -> Option<&EditorStyle> {
10222        self.style.as_ref()
10223    }
10224
10225    // Called by the element. This method is not designed to be called outside of the editor
10226    // element's layout code because it does not notify when rewrapping is computed synchronously.
10227    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10228        self.display_map
10229            .update(cx, |map, cx| map.set_wrap_width(width, cx))
10230    }
10231
10232    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10233        if self.soft_wrap_mode_override.is_some() {
10234            self.soft_wrap_mode_override.take();
10235        } else {
10236            let soft_wrap = match self.soft_wrap_mode(cx) {
10237                SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10238                SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10239                    language_settings::SoftWrap::PreferLine
10240                }
10241            };
10242            self.soft_wrap_mode_override = Some(soft_wrap);
10243        }
10244        cx.notify();
10245    }
10246
10247    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10248        let Some(workspace) = self.workspace() else {
10249            return;
10250        };
10251        let fs = workspace.read(cx).app_state().fs.clone();
10252        let current_show = TabBarSettings::get_global(cx).show;
10253        update_settings_file::<TabBarSettings>(fs, cx, move |setting| {
10254            setting.show = Some(!current_show);
10255        });
10256    }
10257
10258    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10259        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10260            self.buffer
10261                .read(cx)
10262                .settings_at(0, cx)
10263                .indent_guides
10264                .enabled
10265        });
10266        self.show_indent_guides = Some(!currently_enabled);
10267        cx.notify();
10268    }
10269
10270    fn should_show_indent_guides(&self) -> Option<bool> {
10271        self.show_indent_guides
10272    }
10273
10274    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10275        let mut editor_settings = EditorSettings::get_global(cx).clone();
10276        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10277        EditorSettings::override_global(editor_settings, cx);
10278    }
10279
10280    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10281        self.show_gutter = show_gutter;
10282        cx.notify();
10283    }
10284
10285    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10286        self.show_line_numbers = Some(show_line_numbers);
10287        cx.notify();
10288    }
10289
10290    pub fn set_show_git_diff_gutter(
10291        &mut self,
10292        show_git_diff_gutter: bool,
10293        cx: &mut ViewContext<Self>,
10294    ) {
10295        self.show_git_diff_gutter = Some(show_git_diff_gutter);
10296        cx.notify();
10297    }
10298
10299    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10300        self.show_code_actions = Some(show_code_actions);
10301        cx.notify();
10302    }
10303
10304    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10305        self.show_runnables = Some(show_runnables);
10306        cx.notify();
10307    }
10308
10309    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10310        self.show_wrap_guides = Some(show_wrap_guides);
10311        cx.notify();
10312    }
10313
10314    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10315        self.show_indent_guides = Some(show_indent_guides);
10316        cx.notify();
10317    }
10318
10319    pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
10320        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10321            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10322                cx.reveal_path(&file.abs_path(cx));
10323            }
10324        }
10325    }
10326
10327    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10328        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10329            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10330                if let Some(path) = file.abs_path(cx).to_str() {
10331                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10332                }
10333            }
10334        }
10335    }
10336
10337    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10338        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10339            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10340                if let Some(path) = file.path().to_str() {
10341                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10342                }
10343            }
10344        }
10345    }
10346
10347    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10348        self.show_git_blame_gutter = !self.show_git_blame_gutter;
10349
10350        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10351            self.start_git_blame(true, cx);
10352        }
10353
10354        cx.notify();
10355    }
10356
10357    pub fn toggle_git_blame_inline(
10358        &mut self,
10359        _: &ToggleGitBlameInline,
10360        cx: &mut ViewContext<Self>,
10361    ) {
10362        self.toggle_git_blame_inline_internal(true, cx);
10363        cx.notify();
10364    }
10365
10366    pub fn git_blame_inline_enabled(&self) -> bool {
10367        self.git_blame_inline_enabled
10368    }
10369
10370    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10371        self.show_selection_menu = self
10372            .show_selection_menu
10373            .map(|show_selections_menu| !show_selections_menu)
10374            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10375
10376        cx.notify();
10377    }
10378
10379    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10380        self.show_selection_menu
10381            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10382    }
10383
10384    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10385        if let Some(project) = self.project.as_ref() {
10386            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10387                return;
10388            };
10389
10390            if buffer.read(cx).file().is_none() {
10391                return;
10392            }
10393
10394            let focused = self.focus_handle(cx).contains_focused(cx);
10395
10396            let project = project.clone();
10397            let blame =
10398                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10399            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10400            self.blame = Some(blame);
10401        }
10402    }
10403
10404    fn toggle_git_blame_inline_internal(
10405        &mut self,
10406        user_triggered: bool,
10407        cx: &mut ViewContext<Self>,
10408    ) {
10409        if self.git_blame_inline_enabled {
10410            self.git_blame_inline_enabled = false;
10411            self.show_git_blame_inline = false;
10412            self.show_git_blame_inline_delay_task.take();
10413        } else {
10414            self.git_blame_inline_enabled = true;
10415            self.start_git_blame_inline(user_triggered, cx);
10416        }
10417
10418        cx.notify();
10419    }
10420
10421    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10422        self.start_git_blame(user_triggered, cx);
10423
10424        if ProjectSettings::get_global(cx)
10425            .git
10426            .inline_blame_delay()
10427            .is_some()
10428        {
10429            self.start_inline_blame_timer(cx);
10430        } else {
10431            self.show_git_blame_inline = true
10432        }
10433    }
10434
10435    pub fn blame(&self) -> Option<&Model<GitBlame>> {
10436        self.blame.as_ref()
10437    }
10438
10439    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10440        self.show_git_blame_gutter && self.has_blame_entries(cx)
10441    }
10442
10443    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10444        self.show_git_blame_inline
10445            && self.focus_handle.is_focused(cx)
10446            && !self.newest_selection_head_on_empty_line(cx)
10447            && self.has_blame_entries(cx)
10448    }
10449
10450    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10451        self.blame()
10452            .map_or(false, |blame| blame.read(cx).has_generated_entries())
10453    }
10454
10455    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10456        let cursor_anchor = self.selections.newest_anchor().head();
10457
10458        let snapshot = self.buffer.read(cx).snapshot(cx);
10459        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10460
10461        snapshot.line_len(buffer_row) == 0
10462    }
10463
10464    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10465        let (path, selection, repo) = maybe!({
10466            let project_handle = self.project.as_ref()?.clone();
10467            let project = project_handle.read(cx);
10468
10469            let selection = self.selections.newest::<Point>(cx);
10470            let selection_range = selection.range();
10471
10472            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10473                (buffer, selection_range.start.row..selection_range.end.row)
10474            } else {
10475                let buffer_ranges = self
10476                    .buffer()
10477                    .read(cx)
10478                    .range_to_buffer_ranges(selection_range, cx);
10479
10480                let (buffer, range, _) = if selection.reversed {
10481                    buffer_ranges.first()
10482                } else {
10483                    buffer_ranges.last()
10484                }?;
10485
10486                let snapshot = buffer.read(cx).snapshot();
10487                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10488                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
10489                (buffer.clone(), selection)
10490            };
10491
10492            let path = buffer
10493                .read(cx)
10494                .file()?
10495                .as_local()?
10496                .path()
10497                .to_str()?
10498                .to_string();
10499            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10500            Some((path, selection, repo))
10501        })
10502        .ok_or_else(|| anyhow!("unable to open git repository"))?;
10503
10504        const REMOTE_NAME: &str = "origin";
10505        let origin_url = repo
10506            .remote_url(REMOTE_NAME)
10507            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10508        let sha = repo
10509            .head_sha()
10510            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10511
10512        let (provider, remote) =
10513            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10514                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10515
10516        Ok(provider.build_permalink(
10517            remote,
10518            BuildPermalinkParams {
10519                sha: &sha,
10520                path: &path,
10521                selection: Some(selection),
10522            },
10523        ))
10524    }
10525
10526    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10527        let permalink = self.get_permalink_to_line(cx);
10528
10529        match permalink {
10530            Ok(permalink) => {
10531                cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
10532            }
10533            Err(err) => {
10534                let message = format!("Failed to copy permalink: {err}");
10535
10536                Err::<(), anyhow::Error>(err).log_err();
10537
10538                if let Some(workspace) = self.workspace() {
10539                    workspace.update(cx, |workspace, cx| {
10540                        struct CopyPermalinkToLine;
10541
10542                        workspace.show_toast(
10543                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10544                            cx,
10545                        )
10546                    })
10547                }
10548            }
10549        }
10550    }
10551
10552    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10553        let permalink = self.get_permalink_to_line(cx);
10554
10555        match permalink {
10556            Ok(permalink) => {
10557                cx.open_url(permalink.as_ref());
10558            }
10559            Err(err) => {
10560                let message = format!("Failed to open permalink: {err}");
10561
10562                Err::<(), anyhow::Error>(err).log_err();
10563
10564                if let Some(workspace) = self.workspace() {
10565                    workspace.update(cx, |workspace, cx| {
10566                        struct OpenPermalinkToLine;
10567
10568                        workspace.show_toast(
10569                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10570                            cx,
10571                        )
10572                    })
10573                }
10574            }
10575        }
10576    }
10577
10578    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10579    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10580    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10581    pub fn highlight_rows<T: 'static>(
10582        &mut self,
10583        rows: RangeInclusive<Anchor>,
10584        color: Option<Hsla>,
10585        should_autoscroll: bool,
10586        cx: &mut ViewContext<Self>,
10587    ) {
10588        let snapshot = self.buffer().read(cx).snapshot(cx);
10589        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10590        let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10591            highlight
10592                .range
10593                .start()
10594                .cmp(&rows.start(), &snapshot)
10595                .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10596        });
10597        match (color, existing_highlight_index) {
10598            (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10599                ix,
10600                RowHighlight {
10601                    index: post_inc(&mut self.highlight_order),
10602                    range: rows,
10603                    should_autoscroll,
10604                    color,
10605                },
10606            ),
10607            (None, Ok(i)) => {
10608                row_highlights.remove(i);
10609            }
10610        }
10611    }
10612
10613    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10614    pub fn clear_row_highlights<T: 'static>(&mut self) {
10615        self.highlighted_rows.remove(&TypeId::of::<T>());
10616    }
10617
10618    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10619    pub fn highlighted_rows<T: 'static>(
10620        &self,
10621    ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10622        Some(
10623            self.highlighted_rows
10624                .get(&TypeId::of::<T>())?
10625                .iter()
10626                .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10627        )
10628    }
10629
10630    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10631    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10632    /// Allows to ignore certain kinds of highlights.
10633    pub fn highlighted_display_rows(
10634        &mut self,
10635        cx: &mut WindowContext,
10636    ) -> BTreeMap<DisplayRow, Hsla> {
10637        let snapshot = self.snapshot(cx);
10638        let mut used_highlight_orders = HashMap::default();
10639        self.highlighted_rows
10640            .iter()
10641            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10642            .fold(
10643                BTreeMap::<DisplayRow, Hsla>::new(),
10644                |mut unique_rows, highlight| {
10645                    let start_row = highlight.range.start().to_display_point(&snapshot).row();
10646                    let end_row = highlight.range.end().to_display_point(&snapshot).row();
10647                    for row in start_row.0..=end_row.0 {
10648                        let used_index =
10649                            used_highlight_orders.entry(row).or_insert(highlight.index);
10650                        if highlight.index >= *used_index {
10651                            *used_index = highlight.index;
10652                            match highlight.color {
10653                                Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10654                                None => unique_rows.remove(&DisplayRow(row)),
10655                            };
10656                        }
10657                    }
10658                    unique_rows
10659                },
10660            )
10661    }
10662
10663    pub fn highlighted_display_row_for_autoscroll(
10664        &self,
10665        snapshot: &DisplaySnapshot,
10666    ) -> Option<DisplayRow> {
10667        self.highlighted_rows
10668            .values()
10669            .flat_map(|highlighted_rows| highlighted_rows.iter())
10670            .filter_map(|highlight| {
10671                if highlight.color.is_none() || !highlight.should_autoscroll {
10672                    return None;
10673                }
10674                Some(highlight.range.start().to_display_point(&snapshot).row())
10675            })
10676            .min()
10677    }
10678
10679    pub fn set_search_within_ranges(
10680        &mut self,
10681        ranges: &[Range<Anchor>],
10682        cx: &mut ViewContext<Self>,
10683    ) {
10684        self.highlight_background::<SearchWithinRange>(
10685            ranges,
10686            |colors| colors.editor_document_highlight_read_background,
10687            cx,
10688        )
10689    }
10690
10691    pub fn set_breadcrumb_header(&mut self, new_header: String) {
10692        self.breadcrumb_header = Some(new_header);
10693    }
10694
10695    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10696        self.clear_background_highlights::<SearchWithinRange>(cx);
10697    }
10698
10699    pub fn highlight_background<T: 'static>(
10700        &mut self,
10701        ranges: &[Range<Anchor>],
10702        color_fetcher: fn(&ThemeColors) -> Hsla,
10703        cx: &mut ViewContext<Self>,
10704    ) {
10705        let snapshot = self.snapshot(cx);
10706        // this is to try and catch a panic sooner
10707        for range in ranges {
10708            snapshot
10709                .buffer_snapshot
10710                .summary_for_anchor::<usize>(&range.start);
10711            snapshot
10712                .buffer_snapshot
10713                .summary_for_anchor::<usize>(&range.end);
10714        }
10715
10716        self.background_highlights
10717            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10718        self.scrollbar_marker_state.dirty = true;
10719        cx.notify();
10720    }
10721
10722    pub fn clear_background_highlights<T: 'static>(
10723        &mut self,
10724        cx: &mut ViewContext<Self>,
10725    ) -> Option<BackgroundHighlight> {
10726        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10727        if !text_highlights.1.is_empty() {
10728            self.scrollbar_marker_state.dirty = true;
10729            cx.notify();
10730        }
10731        Some(text_highlights)
10732    }
10733
10734    pub fn highlight_gutter<T: 'static>(
10735        &mut self,
10736        ranges: &[Range<Anchor>],
10737        color_fetcher: fn(&AppContext) -> Hsla,
10738        cx: &mut ViewContext<Self>,
10739    ) {
10740        self.gutter_highlights
10741            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10742        cx.notify();
10743    }
10744
10745    pub fn clear_gutter_highlights<T: 'static>(
10746        &mut self,
10747        cx: &mut ViewContext<Self>,
10748    ) -> Option<GutterHighlight> {
10749        cx.notify();
10750        self.gutter_highlights.remove(&TypeId::of::<T>())
10751    }
10752
10753    #[cfg(feature = "test-support")]
10754    pub fn all_text_background_highlights(
10755        &mut self,
10756        cx: &mut ViewContext<Self>,
10757    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10758        let snapshot = self.snapshot(cx);
10759        let buffer = &snapshot.buffer_snapshot;
10760        let start = buffer.anchor_before(0);
10761        let end = buffer.anchor_after(buffer.len());
10762        let theme = cx.theme().colors();
10763        self.background_highlights_in_range(start..end, &snapshot, theme)
10764    }
10765
10766    #[cfg(feature = "test-support")]
10767    pub fn search_background_highlights(
10768        &mut self,
10769        cx: &mut ViewContext<Self>,
10770    ) -> Vec<Range<Point>> {
10771        let snapshot = self.buffer().read(cx).snapshot(cx);
10772
10773        let highlights = self
10774            .background_highlights
10775            .get(&TypeId::of::<items::BufferSearchHighlights>());
10776
10777        if let Some((_color, ranges)) = highlights {
10778            ranges
10779                .iter()
10780                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
10781                .collect_vec()
10782        } else {
10783            vec![]
10784        }
10785    }
10786
10787    fn document_highlights_for_position<'a>(
10788        &'a self,
10789        position: Anchor,
10790        buffer: &'a MultiBufferSnapshot,
10791    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
10792        let read_highlights = self
10793            .background_highlights
10794            .get(&TypeId::of::<DocumentHighlightRead>())
10795            .map(|h| &h.1);
10796        let write_highlights = self
10797            .background_highlights
10798            .get(&TypeId::of::<DocumentHighlightWrite>())
10799            .map(|h| &h.1);
10800        let left_position = position.bias_left(buffer);
10801        let right_position = position.bias_right(buffer);
10802        read_highlights
10803            .into_iter()
10804            .chain(write_highlights)
10805            .flat_map(move |ranges| {
10806                let start_ix = match ranges.binary_search_by(|probe| {
10807                    let cmp = probe.end.cmp(&left_position, buffer);
10808                    if cmp.is_ge() {
10809                        Ordering::Greater
10810                    } else {
10811                        Ordering::Less
10812                    }
10813                }) {
10814                    Ok(i) | Err(i) => i,
10815                };
10816
10817                ranges[start_ix..]
10818                    .iter()
10819                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
10820            })
10821    }
10822
10823    pub fn has_background_highlights<T: 'static>(&self) -> bool {
10824        self.background_highlights
10825            .get(&TypeId::of::<T>())
10826            .map_or(false, |(_, highlights)| !highlights.is_empty())
10827    }
10828
10829    pub fn background_highlights_in_range(
10830        &self,
10831        search_range: Range<Anchor>,
10832        display_snapshot: &DisplaySnapshot,
10833        theme: &ThemeColors,
10834    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10835        let mut results = Vec::new();
10836        for (color_fetcher, ranges) in self.background_highlights.values() {
10837            let color = color_fetcher(theme);
10838            let start_ix = match ranges.binary_search_by(|probe| {
10839                let cmp = probe
10840                    .end
10841                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10842                if cmp.is_gt() {
10843                    Ordering::Greater
10844                } else {
10845                    Ordering::Less
10846                }
10847            }) {
10848                Ok(i) | Err(i) => i,
10849            };
10850            for range in &ranges[start_ix..] {
10851                if range
10852                    .start
10853                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10854                    .is_ge()
10855                {
10856                    break;
10857                }
10858
10859                let start = range.start.to_display_point(&display_snapshot);
10860                let end = range.end.to_display_point(&display_snapshot);
10861                results.push((start..end, color))
10862            }
10863        }
10864        results
10865    }
10866
10867    pub fn background_highlight_row_ranges<T: 'static>(
10868        &self,
10869        search_range: Range<Anchor>,
10870        display_snapshot: &DisplaySnapshot,
10871        count: usize,
10872    ) -> Vec<RangeInclusive<DisplayPoint>> {
10873        let mut results = Vec::new();
10874        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
10875            return vec![];
10876        };
10877
10878        let start_ix = match ranges.binary_search_by(|probe| {
10879            let cmp = probe
10880                .end
10881                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10882            if cmp.is_gt() {
10883                Ordering::Greater
10884            } else {
10885                Ordering::Less
10886            }
10887        }) {
10888            Ok(i) | Err(i) => i,
10889        };
10890        let mut push_region = |start: Option<Point>, end: Option<Point>| {
10891            if let (Some(start_display), Some(end_display)) = (start, end) {
10892                results.push(
10893                    start_display.to_display_point(display_snapshot)
10894                        ..=end_display.to_display_point(display_snapshot),
10895                );
10896            }
10897        };
10898        let mut start_row: Option<Point> = None;
10899        let mut end_row: Option<Point> = None;
10900        if ranges.len() > count {
10901            return Vec::new();
10902        }
10903        for range in &ranges[start_ix..] {
10904            if range
10905                .start
10906                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10907                .is_ge()
10908            {
10909                break;
10910            }
10911            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
10912            if let Some(current_row) = &end_row {
10913                if end.row == current_row.row {
10914                    continue;
10915                }
10916            }
10917            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
10918            if start_row.is_none() {
10919                assert_eq!(end_row, None);
10920                start_row = Some(start);
10921                end_row = Some(end);
10922                continue;
10923            }
10924            if let Some(current_end) = end_row.as_mut() {
10925                if start.row > current_end.row + 1 {
10926                    push_region(start_row, end_row);
10927                    start_row = Some(start);
10928                    end_row = Some(end);
10929                } else {
10930                    // Merge two hunks.
10931                    *current_end = end;
10932                }
10933            } else {
10934                unreachable!();
10935            }
10936        }
10937        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
10938        push_region(start_row, end_row);
10939        results
10940    }
10941
10942    pub fn gutter_highlights_in_range(
10943        &self,
10944        search_range: Range<Anchor>,
10945        display_snapshot: &DisplaySnapshot,
10946        cx: &AppContext,
10947    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10948        let mut results = Vec::new();
10949        for (color_fetcher, ranges) in self.gutter_highlights.values() {
10950            let color = color_fetcher(cx);
10951            let start_ix = match ranges.binary_search_by(|probe| {
10952                let cmp = probe
10953                    .end
10954                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10955                if cmp.is_gt() {
10956                    Ordering::Greater
10957                } else {
10958                    Ordering::Less
10959                }
10960            }) {
10961                Ok(i) | Err(i) => i,
10962            };
10963            for range in &ranges[start_ix..] {
10964                if range
10965                    .start
10966                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10967                    .is_ge()
10968                {
10969                    break;
10970                }
10971
10972                let start = range.start.to_display_point(&display_snapshot);
10973                let end = range.end.to_display_point(&display_snapshot);
10974                results.push((start..end, color))
10975            }
10976        }
10977        results
10978    }
10979
10980    /// Get the text ranges corresponding to the redaction query
10981    pub fn redacted_ranges(
10982        &self,
10983        search_range: Range<Anchor>,
10984        display_snapshot: &DisplaySnapshot,
10985        cx: &WindowContext,
10986    ) -> Vec<Range<DisplayPoint>> {
10987        display_snapshot
10988            .buffer_snapshot
10989            .redacted_ranges(search_range, |file| {
10990                if let Some(file) = file {
10991                    file.is_private()
10992                        && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
10993                } else {
10994                    false
10995                }
10996            })
10997            .map(|range| {
10998                range.start.to_display_point(display_snapshot)
10999                    ..range.end.to_display_point(display_snapshot)
11000            })
11001            .collect()
11002    }
11003
11004    pub fn highlight_text<T: 'static>(
11005        &mut self,
11006        ranges: Vec<Range<Anchor>>,
11007        style: HighlightStyle,
11008        cx: &mut ViewContext<Self>,
11009    ) {
11010        self.display_map.update(cx, |map, _| {
11011            map.highlight_text(TypeId::of::<T>(), ranges, style)
11012        });
11013        cx.notify();
11014    }
11015
11016    pub(crate) fn highlight_inlays<T: 'static>(
11017        &mut self,
11018        highlights: Vec<InlayHighlight>,
11019        style: HighlightStyle,
11020        cx: &mut ViewContext<Self>,
11021    ) {
11022        self.display_map.update(cx, |map, _| {
11023            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11024        });
11025        cx.notify();
11026    }
11027
11028    pub fn text_highlights<'a, T: 'static>(
11029        &'a self,
11030        cx: &'a AppContext,
11031    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11032        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11033    }
11034
11035    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11036        let cleared = self
11037            .display_map
11038            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11039        if cleared {
11040            cx.notify();
11041        }
11042    }
11043
11044    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11045        (self.read_only(cx) || self.blink_manager.read(cx).visible())
11046            && self.focus_handle.is_focused(cx)
11047    }
11048
11049    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11050        self.show_cursor_when_unfocused = is_enabled;
11051        cx.notify();
11052    }
11053
11054    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11055        cx.notify();
11056    }
11057
11058    fn on_buffer_event(
11059        &mut self,
11060        multibuffer: Model<MultiBuffer>,
11061        event: &multi_buffer::Event,
11062        cx: &mut ViewContext<Self>,
11063    ) {
11064        match event {
11065            multi_buffer::Event::Edited {
11066                singleton_buffer_edited,
11067            } => {
11068                self.scrollbar_marker_state.dirty = true;
11069                self.active_indent_guides_state.dirty = true;
11070                self.refresh_active_diagnostics(cx);
11071                self.refresh_code_actions(cx);
11072                if self.has_active_inline_completion(cx) {
11073                    self.update_visible_inline_completion(cx);
11074                }
11075                cx.emit(EditorEvent::BufferEdited);
11076                cx.emit(SearchEvent::MatchesInvalidated);
11077                if *singleton_buffer_edited {
11078                    if let Some(project) = &self.project {
11079                        let project = project.read(cx);
11080                        let languages_affected = multibuffer
11081                            .read(cx)
11082                            .all_buffers()
11083                            .into_iter()
11084                            .filter_map(|buffer| {
11085                                let buffer = buffer.read(cx);
11086                                let language = buffer.language()?;
11087                                if project.is_local()
11088                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
11089                                {
11090                                    None
11091                                } else {
11092                                    Some(language)
11093                                }
11094                            })
11095                            .cloned()
11096                            .collect::<HashSet<_>>();
11097                        if !languages_affected.is_empty() {
11098                            self.refresh_inlay_hints(
11099                                InlayHintRefreshReason::BufferEdited(languages_affected),
11100                                cx,
11101                            );
11102                        }
11103                    }
11104                }
11105
11106                let Some(project) = &self.project else { return };
11107                let telemetry = project.read(cx).client().telemetry().clone();
11108                refresh_linked_ranges(self, cx);
11109                telemetry.log_edit_event("editor");
11110            }
11111            multi_buffer::Event::ExcerptsAdded {
11112                buffer,
11113                predecessor,
11114                excerpts,
11115            } => {
11116                self.tasks_update_task = Some(self.refresh_runnables(cx));
11117                cx.emit(EditorEvent::ExcerptsAdded {
11118                    buffer: buffer.clone(),
11119                    predecessor: *predecessor,
11120                    excerpts: excerpts.clone(),
11121                });
11122                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11123            }
11124            multi_buffer::Event::ExcerptsRemoved { ids } => {
11125                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11126                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11127            }
11128            multi_buffer::Event::ExcerptsEdited { ids } => {
11129                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11130            }
11131            multi_buffer::Event::ExcerptsExpanded { ids } => {
11132                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11133            }
11134            multi_buffer::Event::Reparsed(buffer_id) => {
11135                self.tasks_update_task = Some(self.refresh_runnables(cx));
11136
11137                cx.emit(EditorEvent::Reparsed(*buffer_id));
11138            }
11139            multi_buffer::Event::LanguageChanged(buffer_id) => {
11140                linked_editing_ranges::refresh_linked_ranges(self, cx);
11141                cx.emit(EditorEvent::Reparsed(*buffer_id));
11142                cx.notify();
11143            }
11144            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11145            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11146            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11147                cx.emit(EditorEvent::TitleChanged)
11148            }
11149            multi_buffer::Event::DiffBaseChanged => {
11150                self.scrollbar_marker_state.dirty = true;
11151                cx.emit(EditorEvent::DiffBaseChanged);
11152                cx.notify();
11153            }
11154            multi_buffer::Event::DiffUpdated { buffer } => {
11155                self.sync_expanded_diff_hunks(buffer.clone(), cx);
11156                cx.notify();
11157            }
11158            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11159            multi_buffer::Event::DiagnosticsUpdated => {
11160                self.refresh_active_diagnostics(cx);
11161                self.scrollbar_marker_state.dirty = true;
11162                cx.notify();
11163            }
11164            _ => {}
11165        };
11166    }
11167
11168    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11169        cx.notify();
11170    }
11171
11172    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11173        self.tasks_update_task = Some(self.refresh_runnables(cx));
11174        self.refresh_inline_completion(true, cx);
11175        self.refresh_inlay_hints(
11176            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11177                self.selections.newest_anchor().head(),
11178                &self.buffer.read(cx).snapshot(cx),
11179                cx,
11180            )),
11181            cx,
11182        );
11183        let editor_settings = EditorSettings::get_global(cx);
11184        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11185        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11186
11187        if self.mode == EditorMode::Full {
11188            let inline_blame_enabled = ProjectSettings::get_global(cx).git.inline_blame_enabled();
11189            if self.git_blame_inline_enabled != inline_blame_enabled {
11190                self.toggle_git_blame_inline_internal(false, cx);
11191            }
11192        }
11193
11194        cx.notify();
11195    }
11196
11197    pub fn set_searchable(&mut self, searchable: bool) {
11198        self.searchable = searchable;
11199    }
11200
11201    pub fn searchable(&self) -> bool {
11202        self.searchable
11203    }
11204
11205    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11206        self.open_excerpts_common(true, cx)
11207    }
11208
11209    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11210        self.open_excerpts_common(false, cx)
11211    }
11212
11213    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11214        let buffer = self.buffer.read(cx);
11215        if buffer.is_singleton() {
11216            cx.propagate();
11217            return;
11218        }
11219
11220        let Some(workspace) = self.workspace() else {
11221            cx.propagate();
11222            return;
11223        };
11224
11225        let mut new_selections_by_buffer = HashMap::default();
11226        for selection in self.selections.all::<usize>(cx) {
11227            for (buffer, mut range, _) in
11228                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11229            {
11230                if selection.reversed {
11231                    mem::swap(&mut range.start, &mut range.end);
11232                }
11233                new_selections_by_buffer
11234                    .entry(buffer)
11235                    .or_insert(Vec::new())
11236                    .push(range)
11237            }
11238        }
11239
11240        // We defer the pane interaction because we ourselves are a workspace item
11241        // and activating a new item causes the pane to call a method on us reentrantly,
11242        // which panics if we're on the stack.
11243        cx.window_context().defer(move |cx| {
11244            workspace.update(cx, |workspace, cx| {
11245                let pane = if split {
11246                    workspace.adjacent_pane(cx)
11247                } else {
11248                    workspace.active_pane().clone()
11249                };
11250
11251                for (buffer, ranges) in new_selections_by_buffer {
11252                    let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
11253                    editor.update(cx, |editor, cx| {
11254                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11255                            s.select_ranges(ranges);
11256                        });
11257                    });
11258                }
11259            })
11260        });
11261    }
11262
11263    fn jump(
11264        &mut self,
11265        path: ProjectPath,
11266        position: Point,
11267        anchor: language::Anchor,
11268        offset_from_top: u32,
11269        cx: &mut ViewContext<Self>,
11270    ) {
11271        let workspace = self.workspace();
11272        cx.spawn(|_, mut cx| async move {
11273            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11274            let editor = workspace.update(&mut cx, |workspace, cx| {
11275                // Reset the preview item id before opening the new item
11276                workspace.active_pane().update(cx, |pane, cx| {
11277                    pane.set_preview_item_id(None, cx);
11278                });
11279                workspace.open_path_preview(path, None, true, true, cx)
11280            })?;
11281            let editor = editor
11282                .await?
11283                .downcast::<Editor>()
11284                .ok_or_else(|| anyhow!("opened item was not an editor"))?
11285                .downgrade();
11286            editor.update(&mut cx, |editor, cx| {
11287                let buffer = editor
11288                    .buffer()
11289                    .read(cx)
11290                    .as_singleton()
11291                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11292                let buffer = buffer.read(cx);
11293                let cursor = if buffer.can_resolve(&anchor) {
11294                    language::ToPoint::to_point(&anchor, buffer)
11295                } else {
11296                    buffer.clip_point(position, Bias::Left)
11297                };
11298
11299                let nav_history = editor.nav_history.take();
11300                editor.change_selections(
11301                    Some(Autoscroll::top_relative(offset_from_top as usize)),
11302                    cx,
11303                    |s| {
11304                        s.select_ranges([cursor..cursor]);
11305                    },
11306                );
11307                editor.nav_history = nav_history;
11308
11309                anyhow::Ok(())
11310            })??;
11311
11312            anyhow::Ok(())
11313        })
11314        .detach_and_log_err(cx);
11315    }
11316
11317    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11318        let snapshot = self.buffer.read(cx).read(cx);
11319        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11320        Some(
11321            ranges
11322                .iter()
11323                .map(move |range| {
11324                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11325                })
11326                .collect(),
11327        )
11328    }
11329
11330    fn selection_replacement_ranges(
11331        &self,
11332        range: Range<OffsetUtf16>,
11333        cx: &AppContext,
11334    ) -> Vec<Range<OffsetUtf16>> {
11335        let selections = self.selections.all::<OffsetUtf16>(cx);
11336        let newest_selection = selections
11337            .iter()
11338            .max_by_key(|selection| selection.id)
11339            .unwrap();
11340        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11341        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11342        let snapshot = self.buffer.read(cx).read(cx);
11343        selections
11344            .into_iter()
11345            .map(|mut selection| {
11346                selection.start.0 =
11347                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
11348                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11349                snapshot.clip_offset_utf16(selection.start, Bias::Left)
11350                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11351            })
11352            .collect()
11353    }
11354
11355    fn report_editor_event(
11356        &self,
11357        operation: &'static str,
11358        file_extension: Option<String>,
11359        cx: &AppContext,
11360    ) {
11361        if cfg!(any(test, feature = "test-support")) {
11362            return;
11363        }
11364
11365        let Some(project) = &self.project else { return };
11366
11367        // If None, we are in a file without an extension
11368        let file = self
11369            .buffer
11370            .read(cx)
11371            .as_singleton()
11372            .and_then(|b| b.read(cx).file());
11373        let file_extension = file_extension.or(file
11374            .as_ref()
11375            .and_then(|file| Path::new(file.file_name(cx)).extension())
11376            .and_then(|e| e.to_str())
11377            .map(|a| a.to_string()));
11378
11379        let vim_mode = cx
11380            .global::<SettingsStore>()
11381            .raw_user_settings()
11382            .get("vim_mode")
11383            == Some(&serde_json::Value::Bool(true));
11384
11385        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11386            == language::language_settings::InlineCompletionProvider::Copilot;
11387        let copilot_enabled_for_language = self
11388            .buffer
11389            .read(cx)
11390            .settings_at(0, cx)
11391            .show_inline_completions;
11392
11393        let telemetry = project.read(cx).client().telemetry().clone();
11394        telemetry.report_editor_event(
11395            file_extension,
11396            vim_mode,
11397            operation,
11398            copilot_enabled,
11399            copilot_enabled_for_language,
11400        )
11401    }
11402
11403    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11404    /// with each line being an array of {text, highlight} objects.
11405    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11406        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11407            return;
11408        };
11409
11410        #[derive(Serialize)]
11411        struct Chunk<'a> {
11412            text: String,
11413            highlight: Option<&'a str>,
11414        }
11415
11416        let snapshot = buffer.read(cx).snapshot();
11417        let range = self
11418            .selected_text_range(cx)
11419            .and_then(|selected_range| {
11420                if selected_range.is_empty() {
11421                    None
11422                } else {
11423                    Some(selected_range)
11424                }
11425            })
11426            .unwrap_or_else(|| 0..snapshot.len());
11427
11428        let chunks = snapshot.chunks(range, true);
11429        let mut lines = Vec::new();
11430        let mut line: VecDeque<Chunk> = VecDeque::new();
11431
11432        let Some(style) = self.style.as_ref() else {
11433            return;
11434        };
11435
11436        for chunk in chunks {
11437            let highlight = chunk
11438                .syntax_highlight_id
11439                .and_then(|id| id.name(&style.syntax));
11440            let mut chunk_lines = chunk.text.split('\n').peekable();
11441            while let Some(text) = chunk_lines.next() {
11442                let mut merged_with_last_token = false;
11443                if let Some(last_token) = line.back_mut() {
11444                    if last_token.highlight == highlight {
11445                        last_token.text.push_str(text);
11446                        merged_with_last_token = true;
11447                    }
11448                }
11449
11450                if !merged_with_last_token {
11451                    line.push_back(Chunk {
11452                        text: text.into(),
11453                        highlight,
11454                    });
11455                }
11456
11457                if chunk_lines.peek().is_some() {
11458                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
11459                        line.pop_front();
11460                    }
11461                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
11462                        line.pop_back();
11463                    }
11464
11465                    lines.push(mem::take(&mut line));
11466                }
11467            }
11468        }
11469
11470        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11471            return;
11472        };
11473        cx.write_to_clipboard(ClipboardItem::new(lines));
11474    }
11475
11476    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11477        &self.inlay_hint_cache
11478    }
11479
11480    pub fn replay_insert_event(
11481        &mut self,
11482        text: &str,
11483        relative_utf16_range: Option<Range<isize>>,
11484        cx: &mut ViewContext<Self>,
11485    ) {
11486        if !self.input_enabled {
11487            cx.emit(EditorEvent::InputIgnored { text: text.into() });
11488            return;
11489        }
11490        if let Some(relative_utf16_range) = relative_utf16_range {
11491            let selections = self.selections.all::<OffsetUtf16>(cx);
11492            self.change_selections(None, cx, |s| {
11493                let new_ranges = selections.into_iter().map(|range| {
11494                    let start = OffsetUtf16(
11495                        range
11496                            .head()
11497                            .0
11498                            .saturating_add_signed(relative_utf16_range.start),
11499                    );
11500                    let end = OffsetUtf16(
11501                        range
11502                            .head()
11503                            .0
11504                            .saturating_add_signed(relative_utf16_range.end),
11505                    );
11506                    start..end
11507                });
11508                s.select_ranges(new_ranges);
11509            });
11510        }
11511
11512        self.handle_input(text, cx);
11513    }
11514
11515    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11516        let Some(project) = self.project.as_ref() else {
11517            return false;
11518        };
11519        let project = project.read(cx);
11520
11521        let mut supports = false;
11522        self.buffer().read(cx).for_each_buffer(|buffer| {
11523            if !supports {
11524                supports = project
11525                    .language_servers_for_buffer(buffer.read(cx), cx)
11526                    .any(
11527                        |(_, server)| match server.capabilities().inlay_hint_provider {
11528                            Some(lsp::OneOf::Left(enabled)) => enabled,
11529                            Some(lsp::OneOf::Right(_)) => true,
11530                            None => false,
11531                        },
11532                    )
11533            }
11534        });
11535        supports
11536    }
11537
11538    pub fn focus(&self, cx: &mut WindowContext) {
11539        cx.focus(&self.focus_handle)
11540    }
11541
11542    pub fn is_focused(&self, cx: &WindowContext) -> bool {
11543        self.focus_handle.is_focused(cx)
11544    }
11545
11546    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11547        cx.emit(EditorEvent::Focused);
11548
11549        if let Some(descendant) = self
11550            .last_focused_descendant
11551            .take()
11552            .and_then(|descendant| descendant.upgrade())
11553        {
11554            cx.focus(&descendant);
11555        } else {
11556            if let Some(blame) = self.blame.as_ref() {
11557                blame.update(cx, GitBlame::focus)
11558            }
11559
11560            self.blink_manager.update(cx, BlinkManager::enable);
11561            self.show_cursor_names(cx);
11562            self.buffer.update(cx, |buffer, cx| {
11563                buffer.finalize_last_transaction(cx);
11564                if self.leader_peer_id.is_none() {
11565                    buffer.set_active_selections(
11566                        &self.selections.disjoint_anchors(),
11567                        self.selections.line_mode,
11568                        self.cursor_shape,
11569                        cx,
11570                    );
11571                }
11572            });
11573        }
11574    }
11575
11576    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11577        if event.blurred != self.focus_handle {
11578            self.last_focused_descendant = Some(event.blurred);
11579        }
11580    }
11581
11582    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11583        self.blink_manager.update(cx, BlinkManager::disable);
11584        self.buffer
11585            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11586
11587        if let Some(blame) = self.blame.as_ref() {
11588            blame.update(cx, GitBlame::blur)
11589        }
11590        self.hide_context_menu(cx);
11591        hide_hover(self, cx);
11592        cx.emit(EditorEvent::Blurred);
11593        cx.notify();
11594    }
11595
11596    pub fn register_action<A: Action>(
11597        &mut self,
11598        listener: impl Fn(&A, &mut WindowContext) + 'static,
11599    ) -> Subscription {
11600        let id = self.next_editor_action_id.post_inc();
11601        let listener = Arc::new(listener);
11602        self.editor_actions.borrow_mut().insert(
11603            id,
11604            Box::new(move |cx| {
11605                let _view = cx.view().clone();
11606                let cx = cx.window_context();
11607                let listener = listener.clone();
11608                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11609                    let action = action.downcast_ref().unwrap();
11610                    if phase == DispatchPhase::Bubble {
11611                        listener(action, cx)
11612                    }
11613                })
11614            }),
11615        );
11616
11617        let editor_actions = self.editor_actions.clone();
11618        Subscription::new(move || {
11619            editor_actions.borrow_mut().remove(&id);
11620        })
11621    }
11622
11623    pub fn file_header_size(&self) -> u8 {
11624        self.file_header_size
11625    }
11626}
11627
11628fn hunks_for_selections(
11629    multi_buffer_snapshot: &MultiBufferSnapshot,
11630    selections: &[Selection<Anchor>],
11631) -> Vec<DiffHunk<MultiBufferRow>> {
11632    let mut hunks = Vec::with_capacity(selections.len());
11633    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11634        HashMap::default();
11635    let buffer_rows_for_selections = selections.iter().map(|selection| {
11636        let head = selection.head();
11637        let tail = selection.tail();
11638        let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11639        let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11640        if start > end {
11641            end..start
11642        } else {
11643            start..end
11644        }
11645    });
11646
11647    for selected_multi_buffer_rows in buffer_rows_for_selections {
11648        let query_rows =
11649            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11650        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11651            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11652            // when the caret is just above or just below the deleted hunk.
11653            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11654            let related_to_selection = if allow_adjacent {
11655                hunk.associated_range.overlaps(&query_rows)
11656                    || hunk.associated_range.start == query_rows.end
11657                    || hunk.associated_range.end == query_rows.start
11658            } else {
11659                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11660                // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11661                hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11662                    || selected_multi_buffer_rows.end == hunk.associated_range.start
11663            };
11664            if related_to_selection {
11665                if !processed_buffer_rows
11666                    .entry(hunk.buffer_id)
11667                    .or_default()
11668                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
11669                {
11670                    continue;
11671                }
11672                hunks.push(hunk);
11673            }
11674        }
11675    }
11676
11677    hunks
11678}
11679
11680pub trait CollaborationHub {
11681    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
11682    fn user_participant_indices<'a>(
11683        &self,
11684        cx: &'a AppContext,
11685    ) -> &'a HashMap<u64, ParticipantIndex>;
11686    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
11687}
11688
11689impl CollaborationHub for Model<Project> {
11690    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
11691        self.read(cx).collaborators()
11692    }
11693
11694    fn user_participant_indices<'a>(
11695        &self,
11696        cx: &'a AppContext,
11697    ) -> &'a HashMap<u64, ParticipantIndex> {
11698        self.read(cx).user_store().read(cx).participant_indices()
11699    }
11700
11701    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
11702        let this = self.read(cx);
11703        let user_ids = this.collaborators().values().map(|c| c.user_id);
11704        this.user_store().read_with(cx, |user_store, cx| {
11705            user_store.participant_names(user_ids, cx)
11706        })
11707    }
11708}
11709
11710pub trait CompletionProvider {
11711    fn completions(
11712        &self,
11713        buffer: &Model<Buffer>,
11714        buffer_position: text::Anchor,
11715        trigger: CompletionContext,
11716        cx: &mut ViewContext<Editor>,
11717    ) -> Task<Result<Vec<Completion>>>;
11718
11719    fn resolve_completions(
11720        &self,
11721        buffer: Model<Buffer>,
11722        completion_indices: Vec<usize>,
11723        completions: Arc<RwLock<Box<[Completion]>>>,
11724        cx: &mut ViewContext<Editor>,
11725    ) -> Task<Result<bool>>;
11726
11727    fn apply_additional_edits_for_completion(
11728        &self,
11729        buffer: Model<Buffer>,
11730        completion: Completion,
11731        push_to_history: bool,
11732        cx: &mut ViewContext<Editor>,
11733    ) -> Task<Result<Option<language::Transaction>>>;
11734
11735    fn is_completion_trigger(
11736        &self,
11737        buffer: &Model<Buffer>,
11738        position: language::Anchor,
11739        text: &str,
11740        trigger_in_words: bool,
11741        cx: &mut ViewContext<Editor>,
11742    ) -> bool;
11743}
11744
11745impl CompletionProvider for Model<Project> {
11746    fn completions(
11747        &self,
11748        buffer: &Model<Buffer>,
11749        buffer_position: text::Anchor,
11750        options: CompletionContext,
11751        cx: &mut ViewContext<Editor>,
11752    ) -> Task<Result<Vec<Completion>>> {
11753        self.update(cx, |project, cx| {
11754            project.completions(&buffer, buffer_position, options, cx)
11755        })
11756    }
11757
11758    fn resolve_completions(
11759        &self,
11760        buffer: Model<Buffer>,
11761        completion_indices: Vec<usize>,
11762        completions: Arc<RwLock<Box<[Completion]>>>,
11763        cx: &mut ViewContext<Editor>,
11764    ) -> Task<Result<bool>> {
11765        self.update(cx, |project, cx| {
11766            project.resolve_completions(buffer, completion_indices, completions, cx)
11767        })
11768    }
11769
11770    fn apply_additional_edits_for_completion(
11771        &self,
11772        buffer: Model<Buffer>,
11773        completion: Completion,
11774        push_to_history: bool,
11775        cx: &mut ViewContext<Editor>,
11776    ) -> Task<Result<Option<language::Transaction>>> {
11777        self.update(cx, |project, cx| {
11778            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
11779        })
11780    }
11781
11782    fn is_completion_trigger(
11783        &self,
11784        buffer: &Model<Buffer>,
11785        position: language::Anchor,
11786        text: &str,
11787        trigger_in_words: bool,
11788        cx: &mut ViewContext<Editor>,
11789    ) -> bool {
11790        if !EditorSettings::get_global(cx).show_completions_on_input {
11791            return false;
11792        }
11793
11794        let mut chars = text.chars();
11795        let char = if let Some(char) = chars.next() {
11796            char
11797        } else {
11798            return false;
11799        };
11800        if chars.next().is_some() {
11801            return false;
11802        }
11803
11804        let buffer = buffer.read(cx);
11805        let scope = buffer.snapshot().language_scope_at(position);
11806        if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
11807            return true;
11808        }
11809
11810        buffer
11811            .completion_triggers()
11812            .iter()
11813            .any(|string| string == text)
11814    }
11815}
11816
11817fn inlay_hint_settings(
11818    location: Anchor,
11819    snapshot: &MultiBufferSnapshot,
11820    cx: &mut ViewContext<'_, Editor>,
11821) -> InlayHintSettings {
11822    let file = snapshot.file_at(location);
11823    let language = snapshot.language_at(location);
11824    let settings = all_language_settings(file, cx);
11825    settings
11826        .language(language.map(|l| l.name()).as_deref())
11827        .inlay_hints
11828}
11829
11830fn consume_contiguous_rows(
11831    contiguous_row_selections: &mut Vec<Selection<Point>>,
11832    selection: &Selection<Point>,
11833    display_map: &DisplaySnapshot,
11834    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
11835) -> (MultiBufferRow, MultiBufferRow) {
11836    contiguous_row_selections.push(selection.clone());
11837    let start_row = MultiBufferRow(selection.start.row);
11838    let mut end_row = ending_row(selection, display_map);
11839
11840    while let Some(next_selection) = selections.peek() {
11841        if next_selection.start.row <= end_row.0 {
11842            end_row = ending_row(next_selection, display_map);
11843            contiguous_row_selections.push(selections.next().unwrap().clone());
11844        } else {
11845            break;
11846        }
11847    }
11848    (start_row, end_row)
11849}
11850
11851fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
11852    if next_selection.end.column > 0 || next_selection.is_empty() {
11853        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
11854    } else {
11855        MultiBufferRow(next_selection.end.row)
11856    }
11857}
11858
11859impl EditorSnapshot {
11860    pub fn remote_selections_in_range<'a>(
11861        &'a self,
11862        range: &'a Range<Anchor>,
11863        collaboration_hub: &dyn CollaborationHub,
11864        cx: &'a AppContext,
11865    ) -> impl 'a + Iterator<Item = RemoteSelection> {
11866        let participant_names = collaboration_hub.user_names(cx);
11867        let participant_indices = collaboration_hub.user_participant_indices(cx);
11868        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
11869        let collaborators_by_replica_id = collaborators_by_peer_id
11870            .iter()
11871            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
11872            .collect::<HashMap<_, _>>();
11873        self.buffer_snapshot
11874            .selections_in_range(range, false)
11875            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
11876                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
11877                let participant_index = participant_indices.get(&collaborator.user_id).copied();
11878                let user_name = participant_names.get(&collaborator.user_id).cloned();
11879                Some(RemoteSelection {
11880                    replica_id,
11881                    selection,
11882                    cursor_shape,
11883                    line_mode,
11884                    participant_index,
11885                    peer_id: collaborator.peer_id,
11886                    user_name,
11887                })
11888            })
11889    }
11890
11891    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
11892        self.display_snapshot.buffer_snapshot.language_at(position)
11893    }
11894
11895    pub fn is_focused(&self) -> bool {
11896        self.is_focused
11897    }
11898
11899    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
11900        self.placeholder_text.as_ref()
11901    }
11902
11903    pub fn scroll_position(&self) -> gpui::Point<f32> {
11904        self.scroll_anchor.scroll_position(&self.display_snapshot)
11905    }
11906
11907    pub fn gutter_dimensions(
11908        &self,
11909        font_id: FontId,
11910        font_size: Pixels,
11911        em_width: Pixels,
11912        max_line_number_width: Pixels,
11913        cx: &AppContext,
11914    ) -> GutterDimensions {
11915        if !self.show_gutter {
11916            return GutterDimensions::default();
11917        }
11918        let descent = cx.text_system().descent(font_id, font_size);
11919
11920        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
11921            matches!(
11922                ProjectSettings::get_global(cx).git.git_gutter,
11923                Some(GitGutterSetting::TrackedFiles)
11924            )
11925        });
11926        let gutter_settings = EditorSettings::get_global(cx).gutter;
11927        let show_line_numbers = self
11928            .show_line_numbers
11929            .unwrap_or(gutter_settings.line_numbers);
11930        let line_gutter_width = if show_line_numbers {
11931            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
11932            let min_width_for_number_on_gutter = em_width * 4.0;
11933            max_line_number_width.max(min_width_for_number_on_gutter)
11934        } else {
11935            0.0.into()
11936        };
11937
11938        let show_code_actions = self
11939            .show_code_actions
11940            .unwrap_or(gutter_settings.code_actions);
11941
11942        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
11943
11944        let git_blame_entries_width = self
11945            .render_git_blame_gutter
11946            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
11947
11948        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
11949        left_padding += if show_code_actions || show_runnables {
11950            em_width * 3.0
11951        } else if show_git_gutter && show_line_numbers {
11952            em_width * 2.0
11953        } else if show_git_gutter || show_line_numbers {
11954            em_width
11955        } else {
11956            px(0.)
11957        };
11958
11959        let right_padding = if gutter_settings.folds && show_line_numbers {
11960            em_width * 4.0
11961        } else if gutter_settings.folds {
11962            em_width * 3.0
11963        } else if show_line_numbers {
11964            em_width
11965        } else {
11966            px(0.)
11967        };
11968
11969        GutterDimensions {
11970            left_padding,
11971            right_padding,
11972            width: line_gutter_width + left_padding + right_padding,
11973            margin: -descent,
11974            git_blame_entries_width,
11975        }
11976    }
11977
11978    pub fn render_fold_toggle(
11979        &self,
11980        buffer_row: MultiBufferRow,
11981        row_contains_cursor: bool,
11982        editor: View<Editor>,
11983        cx: &mut WindowContext,
11984    ) -> Option<AnyElement> {
11985        let folded = self.is_line_folded(buffer_row);
11986
11987        if let Some(crease) = self
11988            .crease_snapshot
11989            .query_row(buffer_row, &self.buffer_snapshot)
11990        {
11991            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
11992                if folded {
11993                    editor.update(cx, |editor, cx| {
11994                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
11995                    });
11996                } else {
11997                    editor.update(cx, |editor, cx| {
11998                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
11999                    });
12000                }
12001            });
12002
12003            Some((crease.render_toggle)(
12004                buffer_row,
12005                folded,
12006                toggle_callback,
12007                cx,
12008            ))
12009        } else if folded
12010            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12011        {
12012            Some(
12013                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12014                    .selected(folded)
12015                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12016                        if folded {
12017                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
12018                        } else {
12019                            this.fold_at(&FoldAt { buffer_row }, cx);
12020                        }
12021                    }))
12022                    .into_any_element(),
12023            )
12024        } else {
12025            None
12026        }
12027    }
12028
12029    pub fn render_crease_trailer(
12030        &self,
12031        buffer_row: MultiBufferRow,
12032        cx: &mut WindowContext,
12033    ) -> Option<AnyElement> {
12034        let folded = self.is_line_folded(buffer_row);
12035        let crease = self
12036            .crease_snapshot
12037            .query_row(buffer_row, &self.buffer_snapshot)?;
12038        Some((crease.render_trailer)(buffer_row, folded, cx))
12039    }
12040}
12041
12042impl Deref for EditorSnapshot {
12043    type Target = DisplaySnapshot;
12044
12045    fn deref(&self) -> &Self::Target {
12046        &self.display_snapshot
12047    }
12048}
12049
12050#[derive(Clone, Debug, PartialEq, Eq)]
12051pub enum EditorEvent {
12052    InputIgnored {
12053        text: Arc<str>,
12054    },
12055    InputHandled {
12056        utf16_range_to_replace: Option<Range<isize>>,
12057        text: Arc<str>,
12058    },
12059    ExcerptsAdded {
12060        buffer: Model<Buffer>,
12061        predecessor: ExcerptId,
12062        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12063    },
12064    ExcerptsRemoved {
12065        ids: Vec<ExcerptId>,
12066    },
12067    ExcerptsEdited {
12068        ids: Vec<ExcerptId>,
12069    },
12070    ExcerptsExpanded {
12071        ids: Vec<ExcerptId>,
12072    },
12073    BufferEdited,
12074    Edited {
12075        transaction_id: clock::Lamport,
12076    },
12077    Reparsed(BufferId),
12078    Focused,
12079    Blurred,
12080    DirtyChanged,
12081    Saved,
12082    TitleChanged,
12083    DiffBaseChanged,
12084    SelectionsChanged {
12085        local: bool,
12086    },
12087    ScrollPositionChanged {
12088        local: bool,
12089        autoscroll: bool,
12090    },
12091    Closed,
12092    TransactionUndone {
12093        transaction_id: clock::Lamport,
12094    },
12095    TransactionBegun {
12096        transaction_id: clock::Lamport,
12097    },
12098}
12099
12100impl EventEmitter<EditorEvent> for Editor {}
12101
12102impl FocusableView for Editor {
12103    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12104        self.focus_handle.clone()
12105    }
12106}
12107
12108impl Render for Editor {
12109    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12110        let settings = ThemeSettings::get_global(cx);
12111
12112        let text_style = match self.mode {
12113            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12114                color: cx.theme().colors().editor_foreground,
12115                font_family: settings.ui_font.family.clone(),
12116                font_features: settings.ui_font.features.clone(),
12117                font_size: rems(0.875).into(),
12118                font_weight: settings.ui_font.weight,
12119                font_style: FontStyle::Normal,
12120                line_height: relative(settings.buffer_line_height.value()),
12121                background_color: None,
12122                underline: None,
12123                strikethrough: None,
12124                white_space: WhiteSpace::Normal,
12125            },
12126            EditorMode::Full => TextStyle {
12127                color: cx.theme().colors().editor_foreground,
12128                font_family: settings.buffer_font.family.clone(),
12129                font_features: settings.buffer_font.features.clone(),
12130                font_size: settings.buffer_font_size(cx).into(),
12131                font_weight: settings.buffer_font.weight,
12132                font_style: FontStyle::Normal,
12133                line_height: relative(settings.buffer_line_height.value()),
12134                background_color: None,
12135                underline: None,
12136                strikethrough: None,
12137                white_space: WhiteSpace::Normal,
12138            },
12139        };
12140
12141        let background = match self.mode {
12142            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12143            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12144            EditorMode::Full => cx.theme().colors().editor_background,
12145        };
12146
12147        EditorElement::new(
12148            cx.view(),
12149            EditorStyle {
12150                background,
12151                local_player: cx.theme().players().local(),
12152                text: text_style,
12153                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12154                syntax: cx.theme().syntax().clone(),
12155                status: cx.theme().status().clone(),
12156                inlay_hints_style: HighlightStyle {
12157                    color: Some(cx.theme().status().hint),
12158                    ..HighlightStyle::default()
12159                },
12160                suggestions_style: HighlightStyle {
12161                    color: Some(cx.theme().status().predictive),
12162                    ..HighlightStyle::default()
12163                },
12164            },
12165        )
12166    }
12167}
12168
12169impl ViewInputHandler for Editor {
12170    fn text_for_range(
12171        &mut self,
12172        range_utf16: Range<usize>,
12173        cx: &mut ViewContext<Self>,
12174    ) -> Option<String> {
12175        Some(
12176            self.buffer
12177                .read(cx)
12178                .read(cx)
12179                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12180                .collect(),
12181        )
12182    }
12183
12184    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12185        // Prevent the IME menu from appearing when holding down an alphabetic key
12186        // while input is disabled.
12187        if !self.input_enabled {
12188            return None;
12189        }
12190
12191        let range = self.selections.newest::<OffsetUtf16>(cx).range();
12192        Some(range.start.0..range.end.0)
12193    }
12194
12195    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12196        let snapshot = self.buffer.read(cx).read(cx);
12197        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12198        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12199    }
12200
12201    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12202        self.clear_highlights::<InputComposition>(cx);
12203        self.ime_transaction.take();
12204    }
12205
12206    fn replace_text_in_range(
12207        &mut self,
12208        range_utf16: Option<Range<usize>>,
12209        text: &str,
12210        cx: &mut ViewContext<Self>,
12211    ) {
12212        if !self.input_enabled {
12213            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12214            return;
12215        }
12216
12217        self.transact(cx, |this, cx| {
12218            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12219                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12220                Some(this.selection_replacement_ranges(range_utf16, cx))
12221            } else {
12222                this.marked_text_ranges(cx)
12223            };
12224
12225            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12226                let newest_selection_id = this.selections.newest_anchor().id;
12227                this.selections
12228                    .all::<OffsetUtf16>(cx)
12229                    .iter()
12230                    .zip(ranges_to_replace.iter())
12231                    .find_map(|(selection, range)| {
12232                        if selection.id == newest_selection_id {
12233                            Some(
12234                                (range.start.0 as isize - selection.head().0 as isize)
12235                                    ..(range.end.0 as isize - selection.head().0 as isize),
12236                            )
12237                        } else {
12238                            None
12239                        }
12240                    })
12241            });
12242
12243            cx.emit(EditorEvent::InputHandled {
12244                utf16_range_to_replace: range_to_replace,
12245                text: text.into(),
12246            });
12247
12248            if let Some(new_selected_ranges) = new_selected_ranges {
12249                this.change_selections(None, cx, |selections| {
12250                    selections.select_ranges(new_selected_ranges)
12251                });
12252                this.backspace(&Default::default(), cx);
12253            }
12254
12255            this.handle_input(text, cx);
12256        });
12257
12258        if let Some(transaction) = self.ime_transaction {
12259            self.buffer.update(cx, |buffer, cx| {
12260                buffer.group_until_transaction(transaction, cx);
12261            });
12262        }
12263
12264        self.unmark_text(cx);
12265    }
12266
12267    fn replace_and_mark_text_in_range(
12268        &mut self,
12269        range_utf16: Option<Range<usize>>,
12270        text: &str,
12271        new_selected_range_utf16: Option<Range<usize>>,
12272        cx: &mut ViewContext<Self>,
12273    ) {
12274        if !self.input_enabled {
12275            return;
12276        }
12277
12278        let transaction = self.transact(cx, |this, cx| {
12279            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12280                let snapshot = this.buffer.read(cx).read(cx);
12281                if let Some(relative_range_utf16) = range_utf16.as_ref() {
12282                    for marked_range in &mut marked_ranges {
12283                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12284                        marked_range.start.0 += relative_range_utf16.start;
12285                        marked_range.start =
12286                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12287                        marked_range.end =
12288                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12289                    }
12290                }
12291                Some(marked_ranges)
12292            } else if let Some(range_utf16) = range_utf16 {
12293                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12294                Some(this.selection_replacement_ranges(range_utf16, cx))
12295            } else {
12296                None
12297            };
12298
12299            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12300                let newest_selection_id = this.selections.newest_anchor().id;
12301                this.selections
12302                    .all::<OffsetUtf16>(cx)
12303                    .iter()
12304                    .zip(ranges_to_replace.iter())
12305                    .find_map(|(selection, range)| {
12306                        if selection.id == newest_selection_id {
12307                            Some(
12308                                (range.start.0 as isize - selection.head().0 as isize)
12309                                    ..(range.end.0 as isize - selection.head().0 as isize),
12310                            )
12311                        } else {
12312                            None
12313                        }
12314                    })
12315            });
12316
12317            cx.emit(EditorEvent::InputHandled {
12318                utf16_range_to_replace: range_to_replace,
12319                text: text.into(),
12320            });
12321
12322            if let Some(ranges) = ranges_to_replace {
12323                this.change_selections(None, cx, |s| s.select_ranges(ranges));
12324            }
12325
12326            let marked_ranges = {
12327                let snapshot = this.buffer.read(cx).read(cx);
12328                this.selections
12329                    .disjoint_anchors()
12330                    .iter()
12331                    .map(|selection| {
12332                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12333                    })
12334                    .collect::<Vec<_>>()
12335            };
12336
12337            if text.is_empty() {
12338                this.unmark_text(cx);
12339            } else {
12340                this.highlight_text::<InputComposition>(
12341                    marked_ranges.clone(),
12342                    HighlightStyle {
12343                        underline: Some(UnderlineStyle {
12344                            thickness: px(1.),
12345                            color: None,
12346                            wavy: false,
12347                        }),
12348                        ..Default::default()
12349                    },
12350                    cx,
12351                );
12352            }
12353
12354            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12355            let use_autoclose = this.use_autoclose;
12356            let use_auto_surround = this.use_auto_surround;
12357            this.set_use_autoclose(false);
12358            this.set_use_auto_surround(false);
12359            this.handle_input(text, cx);
12360            this.set_use_autoclose(use_autoclose);
12361            this.set_use_auto_surround(use_auto_surround);
12362
12363            if let Some(new_selected_range) = new_selected_range_utf16 {
12364                let snapshot = this.buffer.read(cx).read(cx);
12365                let new_selected_ranges = marked_ranges
12366                    .into_iter()
12367                    .map(|marked_range| {
12368                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12369                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12370                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12371                        snapshot.clip_offset_utf16(new_start, Bias::Left)
12372                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12373                    })
12374                    .collect::<Vec<_>>();
12375
12376                drop(snapshot);
12377                this.change_selections(None, cx, |selections| {
12378                    selections.select_ranges(new_selected_ranges)
12379                });
12380            }
12381        });
12382
12383        self.ime_transaction = self.ime_transaction.or(transaction);
12384        if let Some(transaction) = self.ime_transaction {
12385            self.buffer.update(cx, |buffer, cx| {
12386                buffer.group_until_transaction(transaction, cx);
12387            });
12388        }
12389
12390        if self.text_highlights::<InputComposition>(cx).is_none() {
12391            self.ime_transaction.take();
12392        }
12393    }
12394
12395    fn bounds_for_range(
12396        &mut self,
12397        range_utf16: Range<usize>,
12398        element_bounds: gpui::Bounds<Pixels>,
12399        cx: &mut ViewContext<Self>,
12400    ) -> Option<gpui::Bounds<Pixels>> {
12401        let text_layout_details = self.text_layout_details(cx);
12402        let style = &text_layout_details.editor_style;
12403        let font_id = cx.text_system().resolve_font(&style.text.font());
12404        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12405        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12406
12407        let em_width = cx
12408            .text_system()
12409            .typographic_bounds(font_id, font_size, 'm')
12410            .unwrap()
12411            .size
12412            .width;
12413
12414        let snapshot = self.snapshot(cx);
12415        let scroll_position = snapshot.scroll_position();
12416        let scroll_left = scroll_position.x * em_width;
12417
12418        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12419        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12420            + self.gutter_dimensions.width;
12421        let y = line_height * (start.row().as_f32() - scroll_position.y);
12422
12423        Some(Bounds {
12424            origin: element_bounds.origin + point(x, y),
12425            size: size(em_width, line_height),
12426        })
12427    }
12428}
12429
12430trait SelectionExt {
12431    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12432    fn spanned_rows(
12433        &self,
12434        include_end_if_at_line_start: bool,
12435        map: &DisplaySnapshot,
12436    ) -> Range<MultiBufferRow>;
12437}
12438
12439impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12440    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12441        let start = self
12442            .start
12443            .to_point(&map.buffer_snapshot)
12444            .to_display_point(map);
12445        let end = self
12446            .end
12447            .to_point(&map.buffer_snapshot)
12448            .to_display_point(map);
12449        if self.reversed {
12450            end..start
12451        } else {
12452            start..end
12453        }
12454    }
12455
12456    fn spanned_rows(
12457        &self,
12458        include_end_if_at_line_start: bool,
12459        map: &DisplaySnapshot,
12460    ) -> Range<MultiBufferRow> {
12461        let start = self.start.to_point(&map.buffer_snapshot);
12462        let mut end = self.end.to_point(&map.buffer_snapshot);
12463        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12464            end.row -= 1;
12465        }
12466
12467        let buffer_start = map.prev_line_boundary(start).0;
12468        let buffer_end = map.next_line_boundary(end).0;
12469        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12470    }
12471}
12472
12473impl<T: InvalidationRegion> InvalidationStack<T> {
12474    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12475    where
12476        S: Clone + ToOffset,
12477    {
12478        while let Some(region) = self.last() {
12479            let all_selections_inside_invalidation_ranges =
12480                if selections.len() == region.ranges().len() {
12481                    selections
12482                        .iter()
12483                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12484                        .all(|(selection, invalidation_range)| {
12485                            let head = selection.head().to_offset(buffer);
12486                            invalidation_range.start <= head && invalidation_range.end >= head
12487                        })
12488                } else {
12489                    false
12490                };
12491
12492            if all_selections_inside_invalidation_ranges {
12493                break;
12494            } else {
12495                self.pop();
12496            }
12497        }
12498    }
12499}
12500
12501impl<T> Default for InvalidationStack<T> {
12502    fn default() -> Self {
12503        Self(Default::default())
12504    }
12505}
12506
12507impl<T> Deref for InvalidationStack<T> {
12508    type Target = Vec<T>;
12509
12510    fn deref(&self) -> &Self::Target {
12511        &self.0
12512    }
12513}
12514
12515impl<T> DerefMut for InvalidationStack<T> {
12516    fn deref_mut(&mut self) -> &mut Self::Target {
12517        &mut self.0
12518    }
12519}
12520
12521impl InvalidationRegion for SnippetState {
12522    fn ranges(&self) -> &[Range<Anchor>] {
12523        &self.ranges[self.active_index]
12524    }
12525}
12526
12527pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
12528    let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
12529
12530    Box::new(move |cx: &mut BlockContext| {
12531        let group_id: SharedString = cx.block_id.to_string().into();
12532
12533        let mut text_style = cx.text_style().clone();
12534        text_style.color = diagnostic_style(diagnostic.severity, true, cx.theme().status());
12535        let theme_settings = ThemeSettings::get_global(cx);
12536        text_style.font_family = theme_settings.buffer_font.family.clone();
12537        text_style.font_style = theme_settings.buffer_font.style;
12538        text_style.font_features = theme_settings.buffer_font.features.clone();
12539        text_style.font_weight = theme_settings.buffer_font.weight;
12540
12541        let multi_line_diagnostic = diagnostic.message.contains('\n');
12542
12543        let buttons = |diagnostic: &Diagnostic, block_id: usize| {
12544            if multi_line_diagnostic {
12545                v_flex()
12546            } else {
12547                h_flex()
12548            }
12549            .children(diagnostic.is_primary.then(|| {
12550                IconButton::new(("close-block", block_id), IconName::XCircle)
12551                    .icon_color(Color::Muted)
12552                    .size(ButtonSize::Compact)
12553                    .style(ButtonStyle::Transparent)
12554                    .visible_on_hover(group_id.clone())
12555                    .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
12556                    .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
12557            }))
12558            .child(
12559                IconButton::new(("copy-block", block_id), IconName::Copy)
12560                    .icon_color(Color::Muted)
12561                    .size(ButtonSize::Compact)
12562                    .style(ButtonStyle::Transparent)
12563                    .visible_on_hover(group_id.clone())
12564                    .on_click({
12565                        let message = diagnostic.message.clone();
12566                        move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
12567                    })
12568                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
12569            )
12570        };
12571
12572        let icon_size = buttons(&diagnostic, cx.block_id)
12573            .into_any_element()
12574            .layout_as_root(AvailableSpace::min_size(), cx);
12575
12576        h_flex()
12577            .id(cx.block_id)
12578            .group(group_id.clone())
12579            .relative()
12580            .size_full()
12581            .pl(cx.gutter_dimensions.width)
12582            .w(cx.max_width + cx.gutter_dimensions.width)
12583            .child(
12584                div()
12585                    .flex()
12586                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
12587                    .flex_shrink(),
12588            )
12589            .child(buttons(&diagnostic, cx.block_id))
12590            .child(div().flex().flex_shrink_0().child(
12591                StyledText::new(text_without_backticks.clone()).with_highlights(
12592                    &text_style,
12593                    code_ranges.iter().map(|range| {
12594                        (
12595                            range.clone(),
12596                            HighlightStyle {
12597                                font_weight: Some(FontWeight::BOLD),
12598                                ..Default::default()
12599                            },
12600                        )
12601                    }),
12602                ),
12603            ))
12604            .into_any_element()
12605    })
12606}
12607
12608pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
12609    let mut text_without_backticks = String::new();
12610    let mut code_ranges = Vec::new();
12611
12612    if let Some(source) = &diagnostic.source {
12613        text_without_backticks.push_str(&source);
12614        code_ranges.push(0..source.len());
12615        text_without_backticks.push_str(": ");
12616    }
12617
12618    let mut prev_offset = 0;
12619    let mut in_code_block = false;
12620    for (ix, _) in diagnostic
12621        .message
12622        .match_indices('`')
12623        .chain([(diagnostic.message.len(), "")])
12624    {
12625        let prev_len = text_without_backticks.len();
12626        text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
12627        prev_offset = ix + 1;
12628        if in_code_block {
12629            code_ranges.push(prev_len..text_without_backticks.len());
12630            in_code_block = false;
12631        } else {
12632            in_code_block = true;
12633        }
12634    }
12635
12636    (text_without_backticks.into(), code_ranges)
12637}
12638
12639fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, colors: &StatusColors) -> Hsla {
12640    match (severity, valid) {
12641        (DiagnosticSeverity::ERROR, true) => colors.error,
12642        (DiagnosticSeverity::ERROR, false) => colors.error,
12643        (DiagnosticSeverity::WARNING, true) => colors.warning,
12644        (DiagnosticSeverity::WARNING, false) => colors.warning,
12645        (DiagnosticSeverity::INFORMATION, true) => colors.info,
12646        (DiagnosticSeverity::INFORMATION, false) => colors.info,
12647        (DiagnosticSeverity::HINT, true) => colors.info,
12648        (DiagnosticSeverity::HINT, false) => colors.info,
12649        _ => colors.ignored,
12650    }
12651}
12652
12653pub fn styled_runs_for_code_label<'a>(
12654    label: &'a CodeLabel,
12655    syntax_theme: &'a theme::SyntaxTheme,
12656) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
12657    let fade_out = HighlightStyle {
12658        fade_out: Some(0.35),
12659        ..Default::default()
12660    };
12661
12662    let mut prev_end = label.filter_range.end;
12663    label
12664        .runs
12665        .iter()
12666        .enumerate()
12667        .flat_map(move |(ix, (range, highlight_id))| {
12668            let style = if let Some(style) = highlight_id.style(syntax_theme) {
12669                style
12670            } else {
12671                return Default::default();
12672            };
12673            let mut muted_style = style;
12674            muted_style.highlight(fade_out);
12675
12676            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
12677            if range.start >= label.filter_range.end {
12678                if range.start > prev_end {
12679                    runs.push((prev_end..range.start, fade_out));
12680                }
12681                runs.push((range.clone(), muted_style));
12682            } else if range.end <= label.filter_range.end {
12683                runs.push((range.clone(), style));
12684            } else {
12685                runs.push((range.start..label.filter_range.end, style));
12686                runs.push((label.filter_range.end..range.end, muted_style));
12687            }
12688            prev_end = cmp::max(prev_end, range.end);
12689
12690            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
12691                runs.push((prev_end..label.text.len(), fade_out));
12692            }
12693
12694            runs
12695        })
12696}
12697
12698pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
12699    let mut prev_index = 0;
12700    let mut prev_codepoint: Option<char> = None;
12701    text.char_indices()
12702        .chain([(text.len(), '\0')])
12703        .filter_map(move |(index, codepoint)| {
12704            let prev_codepoint = prev_codepoint.replace(codepoint)?;
12705            let is_boundary = index == text.len()
12706                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
12707                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
12708            if is_boundary {
12709                let chunk = &text[prev_index..index];
12710                prev_index = index;
12711                Some(chunk)
12712            } else {
12713                None
12714            }
12715        })
12716}
12717
12718trait RangeToAnchorExt {
12719    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
12720}
12721
12722impl<T: ToOffset> RangeToAnchorExt for Range<T> {
12723    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
12724        let start_offset = self.start.to_offset(snapshot);
12725        let end_offset = self.end.to_offset(snapshot);
12726        if start_offset == end_offset {
12727            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
12728        } else {
12729            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
12730        }
12731    }
12732}
12733
12734pub trait RowExt {
12735    fn as_f32(&self) -> f32;
12736
12737    fn next_row(&self) -> Self;
12738
12739    fn previous_row(&self) -> Self;
12740
12741    fn minus(&self, other: Self) -> u32;
12742}
12743
12744impl RowExt for DisplayRow {
12745    fn as_f32(&self) -> f32 {
12746        self.0 as f32
12747    }
12748
12749    fn next_row(&self) -> Self {
12750        Self(self.0 + 1)
12751    }
12752
12753    fn previous_row(&self) -> Self {
12754        Self(self.0.saturating_sub(1))
12755    }
12756
12757    fn minus(&self, other: Self) -> u32 {
12758        self.0 - other.0
12759    }
12760}
12761
12762impl RowExt for MultiBufferRow {
12763    fn as_f32(&self) -> f32 {
12764        self.0 as f32
12765    }
12766
12767    fn next_row(&self) -> Self {
12768        Self(self.0 + 1)
12769    }
12770
12771    fn previous_row(&self) -> Self {
12772        Self(self.0.saturating_sub(1))
12773    }
12774
12775    fn minus(&self, other: Self) -> u32 {
12776        self.0 - other.0
12777    }
12778}
12779
12780trait RowRangeExt {
12781    type Row;
12782
12783    fn len(&self) -> usize;
12784
12785    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
12786}
12787
12788impl RowRangeExt for Range<MultiBufferRow> {
12789    type Row = MultiBufferRow;
12790
12791    fn len(&self) -> usize {
12792        (self.end.0 - self.start.0) as usize
12793    }
12794
12795    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
12796        (self.start.0..self.end.0).map(MultiBufferRow)
12797    }
12798}
12799
12800impl RowRangeExt for Range<DisplayRow> {
12801    type Row = DisplayRow;
12802
12803    fn len(&self) -> usize {
12804        (self.end.0 - self.start.0) as usize
12805    }
12806
12807    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
12808        (self.start.0..self.end.0).map(DisplayRow)
12809    }
12810}
12811
12812fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
12813    if hunk.diff_base_byte_range.is_empty() {
12814        DiffHunkStatus::Added
12815    } else if hunk.associated_range.is_empty() {
12816        DiffHunkStatus::Removed
12817    } else {
12818        DiffHunkStatus::Modified
12819    }
12820}