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: &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
 3127                let is_word_char = text.chars().next().map_or(true, |char| {
 3128                    let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
 3129                    let kind = char_kind(&scope, char);
 3130
 3131                    kind == CharKind::Word
 3132                });
 3133
 3134                if is_word_char {
 3135                    if let Some(ranges) = self
 3136                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3137                    {
 3138                        for (buffer, edits) in ranges {
 3139                            linked_edits
 3140                                .entry(buffer.clone())
 3141                                .or_default()
 3142                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3143                        }
 3144                    }
 3145                }
 3146            }
 3147
 3148            new_selections.push((selection.map(|_| anchor), 0));
 3149            edits.push((selection.start..selection.end, text.clone()));
 3150        }
 3151
 3152        drop(snapshot);
 3153
 3154        self.transact(cx, |this, cx| {
 3155            this.buffer.update(cx, |buffer, cx| {
 3156                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3157            });
 3158            for (buffer, edits) in linked_edits {
 3159                buffer.update(cx, |buffer, cx| {
 3160                    let snapshot = buffer.snapshot();
 3161                    let edits = edits
 3162                        .into_iter()
 3163                        .map(|(range, text)| {
 3164                            use text::ToPoint as TP;
 3165                            let end_point = TP::to_point(&range.end, &snapshot);
 3166                            let start_point = TP::to_point(&range.start, &snapshot);
 3167                            (start_point..end_point, text)
 3168                        })
 3169                        .sorted_by_key(|(range, _)| range.start)
 3170                        .collect::<Vec<_>>();
 3171                    buffer.edit(edits, None, cx);
 3172                })
 3173            }
 3174            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3175            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3176            let snapshot = this.buffer.read(cx).read(cx);
 3177            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3178                .zip(new_selection_deltas)
 3179                .map(|(selection, delta)| Selection {
 3180                    id: selection.id,
 3181                    start: selection.start + delta,
 3182                    end: selection.end + delta,
 3183                    reversed: selection.reversed,
 3184                    goal: SelectionGoal::None,
 3185                })
 3186                .collect::<Vec<_>>();
 3187
 3188            let mut i = 0;
 3189            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3190                let position = position.to_offset(&snapshot) + delta;
 3191                let start = snapshot.anchor_before(position);
 3192                let end = snapshot.anchor_after(position);
 3193                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3194                    match existing_state.range.start.cmp(&start, &snapshot) {
 3195                        Ordering::Less => i += 1,
 3196                        Ordering::Greater => break,
 3197                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3198                            Ordering::Less => i += 1,
 3199                            Ordering::Equal => break,
 3200                            Ordering::Greater => break,
 3201                        },
 3202                    }
 3203                }
 3204                this.autoclose_regions.insert(
 3205                    i,
 3206                    AutocloseRegion {
 3207                        selection_id,
 3208                        range: start..end,
 3209                        pair,
 3210                    },
 3211                );
 3212            }
 3213
 3214            drop(snapshot);
 3215            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3216            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3217                s.select(new_selections)
 3218            });
 3219
 3220            if !brace_inserted && EditorSettings::get_global(cx).use_on_type_format {
 3221                if let Some(on_type_format_task) =
 3222                    this.trigger_on_type_formatting(text.to_string(), cx)
 3223                {
 3224                    on_type_format_task.detach_and_log_err(cx);
 3225                }
 3226            }
 3227
 3228            let trigger_in_words = !had_active_inline_completion;
 3229            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3230            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3231            this.refresh_inline_completion(true, cx);
 3232        });
 3233    }
 3234
 3235    fn find_possible_emoji_shortcode_at_position(
 3236        snapshot: &MultiBufferSnapshot,
 3237        position: Point,
 3238    ) -> Option<String> {
 3239        let mut chars = Vec::new();
 3240        let mut found_colon = false;
 3241        for char in snapshot.reversed_chars_at(position).take(100) {
 3242            // Found a possible emoji shortcode in the middle of the buffer
 3243            if found_colon {
 3244                if char.is_whitespace() {
 3245                    chars.reverse();
 3246                    return Some(chars.iter().collect());
 3247                }
 3248                // If the previous character is not a whitespace, we are in the middle of a word
 3249                // and we only want to complete the shortcode if the word is made up of other emojis
 3250                let mut containing_word = String::new();
 3251                for ch in snapshot
 3252                    .reversed_chars_at(position)
 3253                    .skip(chars.len() + 1)
 3254                    .take(100)
 3255                {
 3256                    if ch.is_whitespace() {
 3257                        break;
 3258                    }
 3259                    containing_word.push(ch);
 3260                }
 3261                let containing_word = containing_word.chars().rev().collect::<String>();
 3262                if util::word_consists_of_emojis(containing_word.as_str()) {
 3263                    chars.reverse();
 3264                    return Some(chars.iter().collect());
 3265                }
 3266            }
 3267
 3268            if char.is_whitespace() || !char.is_ascii() {
 3269                return None;
 3270            }
 3271            if char == ':' {
 3272                found_colon = true;
 3273            } else {
 3274                chars.push(char);
 3275            }
 3276        }
 3277        // Found a possible emoji shortcode at the beginning of the buffer
 3278        chars.reverse();
 3279        Some(chars.iter().collect())
 3280    }
 3281
 3282    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3283        self.transact(cx, |this, cx| {
 3284            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3285                let selections = this.selections.all::<usize>(cx);
 3286                let multi_buffer = this.buffer.read(cx);
 3287                let buffer = multi_buffer.snapshot(cx);
 3288                selections
 3289                    .iter()
 3290                    .map(|selection| {
 3291                        let start_point = selection.start.to_point(&buffer);
 3292                        let mut indent =
 3293                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3294                        indent.len = cmp::min(indent.len, start_point.column);
 3295                        let start = selection.start;
 3296                        let end = selection.end;
 3297                        let selection_is_empty = start == end;
 3298                        let language_scope = buffer.language_scope_at(start);
 3299                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3300                            &language_scope
 3301                        {
 3302                            let leading_whitespace_len = buffer
 3303                                .reversed_chars_at(start)
 3304                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3305                                .map(|c| c.len_utf8())
 3306                                .sum::<usize>();
 3307
 3308                            let trailing_whitespace_len = buffer
 3309                                .chars_at(end)
 3310                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3311                                .map(|c| c.len_utf8())
 3312                                .sum::<usize>();
 3313
 3314                            let insert_extra_newline =
 3315                                language.brackets().any(|(pair, enabled)| {
 3316                                    let pair_start = pair.start.trim_end();
 3317                                    let pair_end = pair.end.trim_start();
 3318
 3319                                    enabled
 3320                                        && pair.newline
 3321                                        && buffer.contains_str_at(
 3322                                            end + trailing_whitespace_len,
 3323                                            pair_end,
 3324                                        )
 3325                                        && buffer.contains_str_at(
 3326                                            (start - leading_whitespace_len)
 3327                                                .saturating_sub(pair_start.len()),
 3328                                            pair_start,
 3329                                        )
 3330                                });
 3331
 3332                            // Comment extension on newline is allowed only for cursor selections
 3333                            let comment_delimiter = maybe!({
 3334                                if !selection_is_empty {
 3335                                    return None;
 3336                                }
 3337
 3338                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3339                                    return None;
 3340                                }
 3341
 3342                                let delimiters = language.line_comment_prefixes();
 3343                                let max_len_of_delimiter =
 3344                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3345                                let (snapshot, range) =
 3346                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3347
 3348                                let mut index_of_first_non_whitespace = 0;
 3349                                let comment_candidate = snapshot
 3350                                    .chars_for_range(range)
 3351                                    .skip_while(|c| {
 3352                                        let should_skip = c.is_whitespace();
 3353                                        if should_skip {
 3354                                            index_of_first_non_whitespace += 1;
 3355                                        }
 3356                                        should_skip
 3357                                    })
 3358                                    .take(max_len_of_delimiter)
 3359                                    .collect::<String>();
 3360                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3361                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3362                                })?;
 3363                                let cursor_is_placed_after_comment_marker =
 3364                                    index_of_first_non_whitespace + comment_prefix.len()
 3365                                        <= start_point.column as usize;
 3366                                if cursor_is_placed_after_comment_marker {
 3367                                    Some(comment_prefix.clone())
 3368                                } else {
 3369                                    None
 3370                                }
 3371                            });
 3372                            (comment_delimiter, insert_extra_newline)
 3373                        } else {
 3374                            (None, false)
 3375                        };
 3376
 3377                        let capacity_for_delimiter = comment_delimiter
 3378                            .as_deref()
 3379                            .map(str::len)
 3380                            .unwrap_or_default();
 3381                        let mut new_text =
 3382                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3383                        new_text.push_str("\n");
 3384                        new_text.extend(indent.chars());
 3385                        if let Some(delimiter) = &comment_delimiter {
 3386                            new_text.push_str(&delimiter);
 3387                        }
 3388                        if insert_extra_newline {
 3389                            new_text = new_text.repeat(2);
 3390                        }
 3391
 3392                        let anchor = buffer.anchor_after(end);
 3393                        let new_selection = selection.map(|_| anchor);
 3394                        (
 3395                            (start..end, new_text),
 3396                            (insert_extra_newline, new_selection),
 3397                        )
 3398                    })
 3399                    .unzip()
 3400            };
 3401
 3402            this.edit_with_autoindent(edits, cx);
 3403            let buffer = this.buffer.read(cx).snapshot(cx);
 3404            let new_selections = selection_fixup_info
 3405                .into_iter()
 3406                .map(|(extra_newline_inserted, new_selection)| {
 3407                    let mut cursor = new_selection.end.to_point(&buffer);
 3408                    if extra_newline_inserted {
 3409                        cursor.row -= 1;
 3410                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3411                    }
 3412                    new_selection.map(|_| cursor)
 3413                })
 3414                .collect();
 3415
 3416            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3417            this.refresh_inline_completion(true, cx);
 3418        });
 3419    }
 3420
 3421    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3422        let buffer = self.buffer.read(cx);
 3423        let snapshot = buffer.snapshot(cx);
 3424
 3425        let mut edits = Vec::new();
 3426        let mut rows = Vec::new();
 3427
 3428        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3429            let cursor = selection.head();
 3430            let row = cursor.row;
 3431
 3432            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3433
 3434            let newline = "\n".to_string();
 3435            edits.push((start_of_line..start_of_line, newline));
 3436
 3437            rows.push(row + rows_inserted as u32);
 3438        }
 3439
 3440        self.transact(cx, |editor, cx| {
 3441            editor.edit(edits, cx);
 3442
 3443            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3444                let mut index = 0;
 3445                s.move_cursors_with(|map, _, _| {
 3446                    let row = rows[index];
 3447                    index += 1;
 3448
 3449                    let point = Point::new(row, 0);
 3450                    let boundary = map.next_line_boundary(point).1;
 3451                    let clipped = map.clip_point(boundary, Bias::Left);
 3452
 3453                    (clipped, SelectionGoal::None)
 3454                });
 3455            });
 3456
 3457            let mut indent_edits = Vec::new();
 3458            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3459            for row in rows {
 3460                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3461                for (row, indent) in indents {
 3462                    if indent.len == 0 {
 3463                        continue;
 3464                    }
 3465
 3466                    let text = match indent.kind {
 3467                        IndentKind::Space => " ".repeat(indent.len as usize),
 3468                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3469                    };
 3470                    let point = Point::new(row.0, 0);
 3471                    indent_edits.push((point..point, text));
 3472                }
 3473            }
 3474            editor.edit(indent_edits, cx);
 3475        });
 3476    }
 3477
 3478    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3479        let buffer = self.buffer.read(cx);
 3480        let snapshot = buffer.snapshot(cx);
 3481
 3482        let mut edits = Vec::new();
 3483        let mut rows = Vec::new();
 3484        let mut rows_inserted = 0;
 3485
 3486        for selection in self.selections.all_adjusted(cx) {
 3487            let cursor = selection.head();
 3488            let row = cursor.row;
 3489
 3490            let point = Point::new(row + 1, 0);
 3491            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3492
 3493            let newline = "\n".to_string();
 3494            edits.push((start_of_line..start_of_line, newline));
 3495
 3496            rows_inserted += 1;
 3497            rows.push(row + rows_inserted);
 3498        }
 3499
 3500        self.transact(cx, |editor, cx| {
 3501            editor.edit(edits, cx);
 3502
 3503            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3504                let mut index = 0;
 3505                s.move_cursors_with(|map, _, _| {
 3506                    let row = rows[index];
 3507                    index += 1;
 3508
 3509                    let point = Point::new(row, 0);
 3510                    let boundary = map.next_line_boundary(point).1;
 3511                    let clipped = map.clip_point(boundary, Bias::Left);
 3512
 3513                    (clipped, SelectionGoal::None)
 3514                });
 3515            });
 3516
 3517            let mut indent_edits = Vec::new();
 3518            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3519            for row in rows {
 3520                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3521                for (row, indent) in indents {
 3522                    if indent.len == 0 {
 3523                        continue;
 3524                    }
 3525
 3526                    let text = match indent.kind {
 3527                        IndentKind::Space => " ".repeat(indent.len as usize),
 3528                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3529                    };
 3530                    let point = Point::new(row.0, 0);
 3531                    indent_edits.push((point..point, text));
 3532                }
 3533            }
 3534            editor.edit(indent_edits, cx);
 3535        });
 3536    }
 3537
 3538    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3539        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3540            original_indent_columns: Vec::new(),
 3541        });
 3542        self.insert_with_autoindent_mode(text, autoindent, cx);
 3543    }
 3544
 3545    fn insert_with_autoindent_mode(
 3546        &mut self,
 3547        text: &str,
 3548        autoindent_mode: Option<AutoindentMode>,
 3549        cx: &mut ViewContext<Self>,
 3550    ) {
 3551        if self.read_only(cx) {
 3552            return;
 3553        }
 3554
 3555        let text: Arc<str> = text.into();
 3556        self.transact(cx, |this, cx| {
 3557            let old_selections = this.selections.all_adjusted(cx);
 3558            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3559                let anchors = {
 3560                    let snapshot = buffer.read(cx);
 3561                    old_selections
 3562                        .iter()
 3563                        .map(|s| {
 3564                            let anchor = snapshot.anchor_after(s.head());
 3565                            s.map(|_| anchor)
 3566                        })
 3567                        .collect::<Vec<_>>()
 3568                };
 3569                buffer.edit(
 3570                    old_selections
 3571                        .iter()
 3572                        .map(|s| (s.start..s.end, text.clone())),
 3573                    autoindent_mode,
 3574                    cx,
 3575                );
 3576                anchors
 3577            });
 3578
 3579            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3580                s.select_anchors(selection_anchors);
 3581            })
 3582        });
 3583    }
 3584
 3585    fn trigger_completion_on_input(
 3586        &mut self,
 3587        text: &str,
 3588        trigger_in_words: bool,
 3589        cx: &mut ViewContext<Self>,
 3590    ) {
 3591        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3592            self.show_completions(
 3593                &ShowCompletions {
 3594                    trigger: text.chars().last(),
 3595                },
 3596                cx,
 3597            );
 3598        } else {
 3599            self.hide_context_menu(cx);
 3600        }
 3601    }
 3602
 3603    fn is_completion_trigger(
 3604        &self,
 3605        text: &str,
 3606        trigger_in_words: bool,
 3607        cx: &mut ViewContext<Self>,
 3608    ) -> bool {
 3609        let position = self.selections.newest_anchor().head();
 3610        let multibuffer = self.buffer.read(cx);
 3611        let Some(buffer) = position
 3612            .buffer_id
 3613            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3614        else {
 3615            return false;
 3616        };
 3617
 3618        if let Some(completion_provider) = &self.completion_provider {
 3619            completion_provider.is_completion_trigger(
 3620                &buffer,
 3621                position.text_anchor,
 3622                text,
 3623                trigger_in_words,
 3624                cx,
 3625            )
 3626        } else {
 3627            false
 3628        }
 3629    }
 3630
 3631    /// If any empty selections is touching the start of its innermost containing autoclose
 3632    /// region, expand it to select the brackets.
 3633    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3634        let selections = self.selections.all::<usize>(cx);
 3635        let buffer = self.buffer.read(cx).read(cx);
 3636        let new_selections = self
 3637            .selections_with_autoclose_regions(selections, &buffer)
 3638            .map(|(mut selection, region)| {
 3639                if !selection.is_empty() {
 3640                    return selection;
 3641                }
 3642
 3643                if let Some(region) = region {
 3644                    let mut range = region.range.to_offset(&buffer);
 3645                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3646                        range.start -= region.pair.start.len();
 3647                        if buffer.contains_str_at(range.start, &region.pair.start)
 3648                            && buffer.contains_str_at(range.end, &region.pair.end)
 3649                        {
 3650                            range.end += region.pair.end.len();
 3651                            selection.start = range.start;
 3652                            selection.end = range.end;
 3653
 3654                            return selection;
 3655                        }
 3656                    }
 3657                }
 3658
 3659                let always_treat_brackets_as_autoclosed = buffer
 3660                    .settings_at(selection.start, cx)
 3661                    .always_treat_brackets_as_autoclosed;
 3662
 3663                if !always_treat_brackets_as_autoclosed {
 3664                    return selection;
 3665                }
 3666
 3667                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3668                    for (pair, enabled) in scope.brackets() {
 3669                        if !enabled || !pair.close {
 3670                            continue;
 3671                        }
 3672
 3673                        if buffer.contains_str_at(selection.start, &pair.end) {
 3674                            let pair_start_len = pair.start.len();
 3675                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3676                            {
 3677                                selection.start -= pair_start_len;
 3678                                selection.end += pair.end.len();
 3679
 3680                                return selection;
 3681                            }
 3682                        }
 3683                    }
 3684                }
 3685
 3686                selection
 3687            })
 3688            .collect();
 3689
 3690        drop(buffer);
 3691        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3692    }
 3693
 3694    /// Iterate the given selections, and for each one, find the smallest surrounding
 3695    /// autoclose region. This uses the ordering of the selections and the autoclose
 3696    /// regions to avoid repeated comparisons.
 3697    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3698        &'a self,
 3699        selections: impl IntoIterator<Item = Selection<D>>,
 3700        buffer: &'a MultiBufferSnapshot,
 3701    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3702        let mut i = 0;
 3703        let mut regions = self.autoclose_regions.as_slice();
 3704        selections.into_iter().map(move |selection| {
 3705            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3706
 3707            let mut enclosing = None;
 3708            while let Some(pair_state) = regions.get(i) {
 3709                if pair_state.range.end.to_offset(buffer) < range.start {
 3710                    regions = &regions[i + 1..];
 3711                    i = 0;
 3712                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3713                    break;
 3714                } else {
 3715                    if pair_state.selection_id == selection.id {
 3716                        enclosing = Some(pair_state);
 3717                    }
 3718                    i += 1;
 3719                }
 3720            }
 3721
 3722            (selection.clone(), enclosing)
 3723        })
 3724    }
 3725
 3726    /// Remove any autoclose regions that no longer contain their selection.
 3727    fn invalidate_autoclose_regions(
 3728        &mut self,
 3729        mut selections: &[Selection<Anchor>],
 3730        buffer: &MultiBufferSnapshot,
 3731    ) {
 3732        self.autoclose_regions.retain(|state| {
 3733            let mut i = 0;
 3734            while let Some(selection) = selections.get(i) {
 3735                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3736                    selections = &selections[1..];
 3737                    continue;
 3738                }
 3739                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3740                    break;
 3741                }
 3742                if selection.id == state.selection_id {
 3743                    return true;
 3744                } else {
 3745                    i += 1;
 3746                }
 3747            }
 3748            false
 3749        });
 3750    }
 3751
 3752    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3753        let offset = position.to_offset(buffer);
 3754        let (word_range, kind) = buffer.surrounding_word(offset);
 3755        if offset > word_range.start && kind == Some(CharKind::Word) {
 3756            Some(
 3757                buffer
 3758                    .text_for_range(word_range.start..offset)
 3759                    .collect::<String>(),
 3760            )
 3761        } else {
 3762            None
 3763        }
 3764    }
 3765
 3766    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3767        self.refresh_inlay_hints(
 3768            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3769            cx,
 3770        );
 3771    }
 3772
 3773    pub fn inlay_hints_enabled(&self) -> bool {
 3774        self.inlay_hint_cache.enabled
 3775    }
 3776
 3777    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3778        if self.project.is_none() || self.mode != EditorMode::Full {
 3779            return;
 3780        }
 3781
 3782        let reason_description = reason.description();
 3783        let ignore_debounce = matches!(
 3784            reason,
 3785            InlayHintRefreshReason::SettingsChange(_)
 3786                | InlayHintRefreshReason::Toggle(_)
 3787                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3788        );
 3789        let (invalidate_cache, required_languages) = match reason {
 3790            InlayHintRefreshReason::Toggle(enabled) => {
 3791                self.inlay_hint_cache.enabled = enabled;
 3792                if enabled {
 3793                    (InvalidationStrategy::RefreshRequested, None)
 3794                } else {
 3795                    self.inlay_hint_cache.clear();
 3796                    self.splice_inlays(
 3797                        self.visible_inlay_hints(cx)
 3798                            .iter()
 3799                            .map(|inlay| inlay.id)
 3800                            .collect(),
 3801                        Vec::new(),
 3802                        cx,
 3803                    );
 3804                    return;
 3805                }
 3806            }
 3807            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3808                match self.inlay_hint_cache.update_settings(
 3809                    &self.buffer,
 3810                    new_settings,
 3811                    self.visible_inlay_hints(cx),
 3812                    cx,
 3813                ) {
 3814                    ControlFlow::Break(Some(InlaySplice {
 3815                        to_remove,
 3816                        to_insert,
 3817                    })) => {
 3818                        self.splice_inlays(to_remove, to_insert, cx);
 3819                        return;
 3820                    }
 3821                    ControlFlow::Break(None) => return,
 3822                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3823                }
 3824            }
 3825            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3826                if let Some(InlaySplice {
 3827                    to_remove,
 3828                    to_insert,
 3829                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3830                {
 3831                    self.splice_inlays(to_remove, to_insert, cx);
 3832                }
 3833                return;
 3834            }
 3835            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3836            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3837                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3838            }
 3839            InlayHintRefreshReason::RefreshRequested => {
 3840                (InvalidationStrategy::RefreshRequested, None)
 3841            }
 3842        };
 3843
 3844        if let Some(InlaySplice {
 3845            to_remove,
 3846            to_insert,
 3847        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3848            reason_description,
 3849            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3850            invalidate_cache,
 3851            ignore_debounce,
 3852            cx,
 3853        ) {
 3854            self.splice_inlays(to_remove, to_insert, cx);
 3855        }
 3856    }
 3857
 3858    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3859        self.display_map
 3860            .read(cx)
 3861            .current_inlays()
 3862            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3863            .cloned()
 3864            .collect()
 3865    }
 3866
 3867    pub fn excerpts_for_inlay_hints_query(
 3868        &self,
 3869        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3870        cx: &mut ViewContext<Editor>,
 3871    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3872        let Some(project) = self.project.as_ref() else {
 3873            return HashMap::default();
 3874        };
 3875        let project = project.read(cx);
 3876        let multi_buffer = self.buffer().read(cx);
 3877        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3878        let multi_buffer_visible_start = self
 3879            .scroll_manager
 3880            .anchor()
 3881            .anchor
 3882            .to_point(&multi_buffer_snapshot);
 3883        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3884            multi_buffer_visible_start
 3885                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3886            Bias::Left,
 3887        );
 3888        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3889        multi_buffer
 3890            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3891            .into_iter()
 3892            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3893            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3894                let buffer = buffer_handle.read(cx);
 3895                let buffer_file = project::File::from_dyn(buffer.file())?;
 3896                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3897                let worktree_entry = buffer_worktree
 3898                    .read(cx)
 3899                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3900                if worktree_entry.is_ignored {
 3901                    return None;
 3902                }
 3903
 3904                let language = buffer.language()?;
 3905                if let Some(restrict_to_languages) = restrict_to_languages {
 3906                    if !restrict_to_languages.contains(language) {
 3907                        return None;
 3908                    }
 3909                }
 3910                Some((
 3911                    excerpt_id,
 3912                    (
 3913                        buffer_handle,
 3914                        buffer.version().clone(),
 3915                        excerpt_visible_range,
 3916                    ),
 3917                ))
 3918            })
 3919            .collect()
 3920    }
 3921
 3922    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3923        TextLayoutDetails {
 3924            text_system: cx.text_system().clone(),
 3925            editor_style: self.style.clone().unwrap(),
 3926            rem_size: cx.rem_size(),
 3927            scroll_anchor: self.scroll_manager.anchor(),
 3928            visible_rows: self.visible_line_count(),
 3929            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3930        }
 3931    }
 3932
 3933    fn splice_inlays(
 3934        &self,
 3935        to_remove: Vec<InlayId>,
 3936        to_insert: Vec<Inlay>,
 3937        cx: &mut ViewContext<Self>,
 3938    ) {
 3939        self.display_map.update(cx, |display_map, cx| {
 3940            display_map.splice_inlays(to_remove, to_insert, cx);
 3941        });
 3942        cx.notify();
 3943    }
 3944
 3945    fn trigger_on_type_formatting(
 3946        &self,
 3947        input: String,
 3948        cx: &mut ViewContext<Self>,
 3949    ) -> Option<Task<Result<()>>> {
 3950        if input.len() != 1 {
 3951            return None;
 3952        }
 3953
 3954        let project = self.project.as_ref()?;
 3955        let position = self.selections.newest_anchor().head();
 3956        let (buffer, buffer_position) = self
 3957            .buffer
 3958            .read(cx)
 3959            .text_anchor_for_position(position, cx)?;
 3960
 3961        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3962        // hence we do LSP request & edit on host side only — add formats to host's history.
 3963        let push_to_lsp_host_history = true;
 3964        // If this is not the host, append its history with new edits.
 3965        let push_to_client_history = project.read(cx).is_remote();
 3966
 3967        let on_type_formatting = project.update(cx, |project, cx| {
 3968            project.on_type_format(
 3969                buffer.clone(),
 3970                buffer_position,
 3971                input,
 3972                push_to_lsp_host_history,
 3973                cx,
 3974            )
 3975        });
 3976        Some(cx.spawn(|editor, mut cx| async move {
 3977            if let Some(transaction) = on_type_formatting.await? {
 3978                if push_to_client_history {
 3979                    buffer
 3980                        .update(&mut cx, |buffer, _| {
 3981                            buffer.push_transaction(transaction, Instant::now());
 3982                        })
 3983                        .ok();
 3984                }
 3985                editor.update(&mut cx, |editor, cx| {
 3986                    editor.refresh_document_highlights(cx);
 3987                })?;
 3988            }
 3989            Ok(())
 3990        }))
 3991    }
 3992
 3993    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3994        if self.pending_rename.is_some() {
 3995            return;
 3996        }
 3997
 3998        let Some(provider) = self.completion_provider.as_ref() else {
 3999            return;
 4000        };
 4001
 4002        let position = self.selections.newest_anchor().head();
 4003        let (buffer, buffer_position) =
 4004            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4005                output
 4006            } else {
 4007                return;
 4008            };
 4009
 4010        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4011        let is_followup_invoke = {
 4012            let context_menu_state = self.context_menu.read();
 4013            matches!(
 4014                context_menu_state.deref(),
 4015                Some(ContextMenu::Completions(_))
 4016            )
 4017        };
 4018        let trigger_kind = match (options.trigger, is_followup_invoke) {
 4019            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4020            (Some(_), _) => CompletionTriggerKind::TRIGGER_CHARACTER,
 4021            _ => CompletionTriggerKind::INVOKED,
 4022        };
 4023        let completion_context = CompletionContext {
 4024            trigger_character: options.trigger.and_then(|c| {
 4025                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4026                    Some(String::from(c))
 4027                } else {
 4028                    None
 4029                }
 4030            }),
 4031            trigger_kind,
 4032        };
 4033        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4034
 4035        let id = post_inc(&mut self.next_completion_id);
 4036        let task = cx.spawn(|this, mut cx| {
 4037            async move {
 4038                this.update(&mut cx, |this, _| {
 4039                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4040                })?;
 4041                let completions = completions.await.log_err();
 4042                let menu = if let Some(completions) = completions {
 4043                    let mut menu = CompletionsMenu {
 4044                        id,
 4045                        initial_position: position,
 4046                        match_candidates: completions
 4047                            .iter()
 4048                            .enumerate()
 4049                            .map(|(id, completion)| {
 4050                                StringMatchCandidate::new(
 4051                                    id,
 4052                                    completion.label.text[completion.label.filter_range.clone()]
 4053                                        .into(),
 4054                                )
 4055                            })
 4056                            .collect(),
 4057                        buffer: buffer.clone(),
 4058                        completions: Arc::new(RwLock::new(completions.into())),
 4059                        matches: Vec::new().into(),
 4060                        selected_item: 0,
 4061                        scroll_handle: UniformListScrollHandle::new(),
 4062                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4063                            DebouncedDelay::new(),
 4064                        )),
 4065                    };
 4066                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4067                        .await;
 4068
 4069                    if menu.matches.is_empty() {
 4070                        None
 4071                    } else {
 4072                        this.update(&mut cx, |editor, cx| {
 4073                            let completions = menu.completions.clone();
 4074                            let matches = menu.matches.clone();
 4075
 4076                            let delay_ms = EditorSettings::get_global(cx)
 4077                                .completion_documentation_secondary_query_debounce;
 4078                            let delay = Duration::from_millis(delay_ms);
 4079                            editor
 4080                                .completion_documentation_pre_resolve_debounce
 4081                                .fire_new(delay, cx, |editor, cx| {
 4082                                    CompletionsMenu::pre_resolve_completion_documentation(
 4083                                        buffer,
 4084                                        completions,
 4085                                        matches,
 4086                                        editor,
 4087                                        cx,
 4088                                    )
 4089                                });
 4090                        })
 4091                        .ok();
 4092                        Some(menu)
 4093                    }
 4094                } else {
 4095                    None
 4096                };
 4097
 4098                this.update(&mut cx, |this, cx| {
 4099                    let mut context_menu = this.context_menu.write();
 4100                    match context_menu.as_ref() {
 4101                        None => {}
 4102
 4103                        Some(ContextMenu::Completions(prev_menu)) => {
 4104                            if prev_menu.id > id {
 4105                                return;
 4106                            }
 4107                        }
 4108
 4109                        _ => return,
 4110                    }
 4111
 4112                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4113                        let menu = menu.unwrap();
 4114                        *context_menu = Some(ContextMenu::Completions(menu));
 4115                        drop(context_menu);
 4116                        this.discard_inline_completion(false, cx);
 4117                        cx.notify();
 4118                    } else if this.completion_tasks.len() <= 1 {
 4119                        // If there are no more completion tasks and the last menu was
 4120                        // empty, we should hide it. If it was already hidden, we should
 4121                        // also show the copilot completion when available.
 4122                        drop(context_menu);
 4123                        if this.hide_context_menu(cx).is_none() {
 4124                            this.update_visible_inline_completion(cx);
 4125                        }
 4126                    }
 4127                })?;
 4128
 4129                Ok::<_, anyhow::Error>(())
 4130            }
 4131            .log_err()
 4132        });
 4133
 4134        self.completion_tasks.push((id, task));
 4135    }
 4136
 4137    pub fn confirm_completion(
 4138        &mut self,
 4139        action: &ConfirmCompletion,
 4140        cx: &mut ViewContext<Self>,
 4141    ) -> Option<Task<Result<()>>> {
 4142        use language::ToOffset as _;
 4143
 4144        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4145            menu
 4146        } else {
 4147            return None;
 4148        };
 4149
 4150        let mat = completions_menu
 4151            .matches
 4152            .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
 4153        let buffer_handle = completions_menu.buffer;
 4154        let completions = completions_menu.completions.read();
 4155        let completion = completions.get(mat.candidate_id)?;
 4156        cx.stop_propagation();
 4157
 4158        let snippet;
 4159        let text;
 4160
 4161        if completion.is_snippet() {
 4162            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4163            text = snippet.as_ref().unwrap().text.clone();
 4164        } else {
 4165            snippet = None;
 4166            text = completion.new_text.clone();
 4167        };
 4168        let selections = self.selections.all::<usize>(cx);
 4169        let buffer = buffer_handle.read(cx);
 4170        let old_range = completion.old_range.to_offset(buffer);
 4171        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4172
 4173        let newest_selection = self.selections.newest_anchor();
 4174        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4175            return None;
 4176        }
 4177
 4178        let lookbehind = newest_selection
 4179            .start
 4180            .text_anchor
 4181            .to_offset(buffer)
 4182            .saturating_sub(old_range.start);
 4183        let lookahead = old_range
 4184            .end
 4185            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4186        let mut common_prefix_len = old_text
 4187            .bytes()
 4188            .zip(text.bytes())
 4189            .take_while(|(a, b)| a == b)
 4190            .count();
 4191
 4192        let snapshot = self.buffer.read(cx).snapshot(cx);
 4193        let mut range_to_replace: Option<Range<isize>> = None;
 4194        let mut ranges = Vec::new();
 4195        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4196        for selection in &selections {
 4197            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4198                let start = selection.start.saturating_sub(lookbehind);
 4199                let end = selection.end + lookahead;
 4200                if selection.id == newest_selection.id {
 4201                    range_to_replace = Some(
 4202                        ((start + common_prefix_len) as isize - selection.start as isize)
 4203                            ..(end as isize - selection.start as isize),
 4204                    );
 4205                }
 4206                ranges.push(start + common_prefix_len..end);
 4207            } else {
 4208                common_prefix_len = 0;
 4209                ranges.clear();
 4210                ranges.extend(selections.iter().map(|s| {
 4211                    if s.id == newest_selection.id {
 4212                        range_to_replace = Some(
 4213                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4214                                - selection.start as isize
 4215                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4216                                    - selection.start as isize,
 4217                        );
 4218                        old_range.clone()
 4219                    } else {
 4220                        s.start..s.end
 4221                    }
 4222                }));
 4223                break;
 4224            }
 4225            if !self.linked_edit_ranges.is_empty() {
 4226                let start_anchor = snapshot.anchor_before(selection.head());
 4227                let end_anchor = snapshot.anchor_after(selection.tail());
 4228                if let Some(ranges) = self
 4229                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4230                {
 4231                    for (buffer, edits) in ranges {
 4232                        linked_edits.entry(buffer.clone()).or_default().extend(
 4233                            edits
 4234                                .into_iter()
 4235                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4236                        );
 4237                    }
 4238                }
 4239            }
 4240        }
 4241        let text = &text[common_prefix_len..];
 4242
 4243        cx.emit(EditorEvent::InputHandled {
 4244            utf16_range_to_replace: range_to_replace,
 4245            text: text.into(),
 4246        });
 4247
 4248        self.transact(cx, |this, cx| {
 4249            if let Some(mut snippet) = snippet {
 4250                snippet.text = text.to_string();
 4251                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4252                    tabstop.start -= common_prefix_len as isize;
 4253                    tabstop.end -= common_prefix_len as isize;
 4254                }
 4255
 4256                this.insert_snippet(&ranges, snippet, cx).log_err();
 4257            } else {
 4258                this.buffer.update(cx, |buffer, cx| {
 4259                    buffer.edit(
 4260                        ranges.iter().map(|range| (range.clone(), text)),
 4261                        this.autoindent_mode.clone(),
 4262                        cx,
 4263                    );
 4264                });
 4265            }
 4266            for (buffer, edits) in linked_edits {
 4267                buffer.update(cx, |buffer, cx| {
 4268                    let snapshot = buffer.snapshot();
 4269                    let edits = edits
 4270                        .into_iter()
 4271                        .map(|(range, text)| {
 4272                            use text::ToPoint as TP;
 4273                            let end_point = TP::to_point(&range.end, &snapshot);
 4274                            let start_point = TP::to_point(&range.start, &snapshot);
 4275                            (start_point..end_point, text)
 4276                        })
 4277                        .sorted_by_key(|(range, _)| range.start)
 4278                        .collect::<Vec<_>>();
 4279                    buffer.edit(edits, None, cx);
 4280                })
 4281            }
 4282
 4283            this.refresh_inline_completion(true, cx);
 4284        });
 4285
 4286        if let Some(confirm) = completion.confirm.as_ref() {
 4287            (confirm)(cx);
 4288        }
 4289
 4290        if completion.show_new_completions_on_confirm {
 4291            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4292        }
 4293
 4294        let provider = self.completion_provider.as_ref()?;
 4295        let apply_edits = provider.apply_additional_edits_for_completion(
 4296            buffer_handle,
 4297            completion.clone(),
 4298            true,
 4299            cx,
 4300        );
 4301        Some(cx.foreground_executor().spawn(async move {
 4302            apply_edits.await?;
 4303            Ok(())
 4304        }))
 4305    }
 4306
 4307    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4308        let mut context_menu = self.context_menu.write();
 4309        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4310            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4311                // Toggle if we're selecting the same one
 4312                *context_menu = None;
 4313                cx.notify();
 4314                return;
 4315            } else {
 4316                // Otherwise, clear it and start a new one
 4317                *context_menu = None;
 4318                cx.notify();
 4319            }
 4320        }
 4321        drop(context_menu);
 4322        let snapshot = self.snapshot(cx);
 4323        let deployed_from_indicator = action.deployed_from_indicator;
 4324        let mut task = self.code_actions_task.take();
 4325        let action = action.clone();
 4326        cx.spawn(|editor, mut cx| async move {
 4327            while let Some(prev_task) = task {
 4328                prev_task.await;
 4329                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4330            }
 4331
 4332            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4333                if editor.focus_handle.is_focused(cx) {
 4334                    let multibuffer_point = action
 4335                        .deployed_from_indicator
 4336                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4337                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4338                    let (buffer, buffer_row) = snapshot
 4339                        .buffer_snapshot
 4340                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4341                        .and_then(|(buffer_snapshot, range)| {
 4342                            editor
 4343                                .buffer
 4344                                .read(cx)
 4345                                .buffer(buffer_snapshot.remote_id())
 4346                                .map(|buffer| (buffer, range.start.row))
 4347                        })?;
 4348                    let (_, code_actions) = editor
 4349                        .available_code_actions
 4350                        .clone()
 4351                        .and_then(|(location, code_actions)| {
 4352                            let snapshot = location.buffer.read(cx).snapshot();
 4353                            let point_range = location.range.to_point(&snapshot);
 4354                            let point_range = point_range.start.row..=point_range.end.row;
 4355                            if point_range.contains(&buffer_row) {
 4356                                Some((location, code_actions))
 4357                            } else {
 4358                                None
 4359                            }
 4360                        })
 4361                        .unzip();
 4362                    let buffer_id = buffer.read(cx).remote_id();
 4363                    let tasks = editor
 4364                        .tasks
 4365                        .get(&(buffer_id, buffer_row))
 4366                        .map(|t| Arc::new(t.to_owned()));
 4367                    if tasks.is_none() && code_actions.is_none() {
 4368                        return None;
 4369                    }
 4370
 4371                    editor.completion_tasks.clear();
 4372                    editor.discard_inline_completion(false, cx);
 4373                    let task_context =
 4374                        tasks
 4375                            .as_ref()
 4376                            .zip(editor.project.clone())
 4377                            .map(|(tasks, project)| {
 4378                                let position = Point::new(buffer_row, tasks.column);
 4379                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4380                                let location = Location {
 4381                                    buffer: buffer.clone(),
 4382                                    range: range_start..range_start,
 4383                                };
 4384                                // Fill in the environmental variables from the tree-sitter captures
 4385                                let mut captured_task_variables = TaskVariables::default();
 4386                                for (capture_name, value) in tasks.extra_variables.clone() {
 4387                                    captured_task_variables.insert(
 4388                                        task::VariableName::Custom(capture_name.into()),
 4389                                        value.clone(),
 4390                                    );
 4391                                }
 4392                                project.update(cx, |project, cx| {
 4393                                    project.task_context_for_location(
 4394                                        captured_task_variables,
 4395                                        location,
 4396                                        cx,
 4397                                    )
 4398                                })
 4399                            });
 4400
 4401                    Some(cx.spawn(|editor, mut cx| async move {
 4402                        let task_context = match task_context {
 4403                            Some(task_context) => task_context.await,
 4404                            None => None,
 4405                        };
 4406                        let resolved_tasks =
 4407                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4408                                Arc::new(ResolvedTasks {
 4409                                    templates: tasks
 4410                                        .templates
 4411                                        .iter()
 4412                                        .filter_map(|(kind, template)| {
 4413                                            template
 4414                                                .resolve_task(&kind.to_id_base(), &task_context)
 4415                                                .map(|task| (kind.clone(), task))
 4416                                        })
 4417                                        .collect(),
 4418                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4419                                        multibuffer_point.row,
 4420                                        tasks.column,
 4421                                    )),
 4422                                })
 4423                            });
 4424                        let spawn_straight_away = resolved_tasks
 4425                            .as_ref()
 4426                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4427                            && code_actions
 4428                                .as_ref()
 4429                                .map_or(true, |actions| actions.is_empty());
 4430                        if let Some(task) = editor
 4431                            .update(&mut cx, |editor, cx| {
 4432                                *editor.context_menu.write() =
 4433                                    Some(ContextMenu::CodeActions(CodeActionsMenu {
 4434                                        buffer,
 4435                                        actions: CodeActionContents {
 4436                                            tasks: resolved_tasks,
 4437                                            actions: code_actions,
 4438                                        },
 4439                                        selected_item: Default::default(),
 4440                                        scroll_handle: UniformListScrollHandle::default(),
 4441                                        deployed_from_indicator,
 4442                                    }));
 4443                                if spawn_straight_away {
 4444                                    if let Some(task) = editor.confirm_code_action(
 4445                                        &ConfirmCodeAction { item_ix: Some(0) },
 4446                                        cx,
 4447                                    ) {
 4448                                        cx.notify();
 4449                                        return task;
 4450                                    }
 4451                                }
 4452                                cx.notify();
 4453                                Task::ready(Ok(()))
 4454                            })
 4455                            .ok()
 4456                        {
 4457                            task.await
 4458                        } else {
 4459                            Ok(())
 4460                        }
 4461                    }))
 4462                } else {
 4463                    Some(Task::ready(Ok(())))
 4464                }
 4465            })?;
 4466            if let Some(task) = spawned_test_task {
 4467                task.await?;
 4468            }
 4469
 4470            Ok::<_, anyhow::Error>(())
 4471        })
 4472        .detach_and_log_err(cx);
 4473    }
 4474
 4475    pub fn confirm_code_action(
 4476        &mut self,
 4477        action: &ConfirmCodeAction,
 4478        cx: &mut ViewContext<Self>,
 4479    ) -> Option<Task<Result<()>>> {
 4480        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4481            menu
 4482        } else {
 4483            return None;
 4484        };
 4485        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4486        let action = actions_menu.actions.get(action_ix)?;
 4487        let title = action.label();
 4488        let buffer = actions_menu.buffer;
 4489        let workspace = self.workspace()?;
 4490
 4491        match action {
 4492            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4493                workspace.update(cx, |workspace, cx| {
 4494                    workspace::tasks::schedule_resolved_task(
 4495                        workspace,
 4496                        task_source_kind,
 4497                        resolved_task,
 4498                        false,
 4499                        cx,
 4500                    );
 4501
 4502                    Some(Task::ready(Ok(())))
 4503                })
 4504            }
 4505            CodeActionsItem::CodeAction(action) => {
 4506                let apply_code_actions = workspace
 4507                    .read(cx)
 4508                    .project()
 4509                    .clone()
 4510                    .update(cx, |project, cx| {
 4511                        project.apply_code_action(buffer, action, true, cx)
 4512                    });
 4513                let workspace = workspace.downgrade();
 4514                Some(cx.spawn(|editor, cx| async move {
 4515                    let project_transaction = apply_code_actions.await?;
 4516                    Self::open_project_transaction(
 4517                        &editor,
 4518                        workspace,
 4519                        project_transaction,
 4520                        title,
 4521                        cx,
 4522                    )
 4523                    .await
 4524                }))
 4525            }
 4526        }
 4527    }
 4528
 4529    pub async fn open_project_transaction(
 4530        this: &WeakView<Editor>,
 4531        workspace: WeakView<Workspace>,
 4532        transaction: ProjectTransaction,
 4533        title: String,
 4534        mut cx: AsyncWindowContext,
 4535    ) -> Result<()> {
 4536        let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
 4537
 4538        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4539        cx.update(|cx| {
 4540            entries.sort_unstable_by_key(|(buffer, _)| {
 4541                buffer.read(cx).file().map(|f| f.path().clone())
 4542            });
 4543        })?;
 4544
 4545        // If the project transaction's edits are all contained within this editor, then
 4546        // avoid opening a new editor to display them.
 4547
 4548        if let Some((buffer, transaction)) = entries.first() {
 4549            if entries.len() == 1 {
 4550                let excerpt = this.update(&mut cx, |editor, cx| {
 4551                    editor
 4552                        .buffer()
 4553                        .read(cx)
 4554                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4555                })?;
 4556                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4557                    if excerpted_buffer == *buffer {
 4558                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4559                            let excerpt_range = excerpt_range.to_offset(buffer);
 4560                            buffer
 4561                                .edited_ranges_for_transaction::<usize>(transaction)
 4562                                .all(|range| {
 4563                                    excerpt_range.start <= range.start
 4564                                        && excerpt_range.end >= range.end
 4565                                })
 4566                        })?;
 4567
 4568                        if all_edits_within_excerpt {
 4569                            return Ok(());
 4570                        }
 4571                    }
 4572                }
 4573            }
 4574        } else {
 4575            return Ok(());
 4576        }
 4577
 4578        let mut ranges_to_highlight = Vec::new();
 4579        let excerpt_buffer = cx.new_model(|cx| {
 4580            let mut multibuffer =
 4581                MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
 4582            for (buffer_handle, transaction) in &entries {
 4583                let buffer = buffer_handle.read(cx);
 4584                ranges_to_highlight.extend(
 4585                    multibuffer.push_excerpts_with_context_lines(
 4586                        buffer_handle.clone(),
 4587                        buffer
 4588                            .edited_ranges_for_transaction::<usize>(transaction)
 4589                            .collect(),
 4590                        DEFAULT_MULTIBUFFER_CONTEXT,
 4591                        cx,
 4592                    ),
 4593                );
 4594            }
 4595            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4596            multibuffer
 4597        })?;
 4598
 4599        workspace.update(&mut cx, |workspace, cx| {
 4600            let project = workspace.project().clone();
 4601            let editor =
 4602                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4603            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, cx);
 4604            editor.update(cx, |editor, cx| {
 4605                editor.highlight_background::<Self>(
 4606                    &ranges_to_highlight,
 4607                    |theme| theme.editor_highlighted_line_background,
 4608                    cx,
 4609                );
 4610            });
 4611        })?;
 4612
 4613        Ok(())
 4614    }
 4615
 4616    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4617        let project = self.project.clone()?;
 4618        let buffer = self.buffer.read(cx);
 4619        let newest_selection = self.selections.newest_anchor().clone();
 4620        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4621        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4622        if start_buffer != end_buffer {
 4623            return None;
 4624        }
 4625
 4626        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4627            cx.background_executor()
 4628                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4629                .await;
 4630
 4631            let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
 4632                project.code_actions(&start_buffer, start..end, cx)
 4633            }) {
 4634                code_actions.await
 4635            } else {
 4636                Vec::new()
 4637            };
 4638
 4639            this.update(&mut cx, |this, cx| {
 4640                this.available_code_actions = if actions.is_empty() {
 4641                    None
 4642                } else {
 4643                    Some((
 4644                        Location {
 4645                            buffer: start_buffer,
 4646                            range: start..end,
 4647                        },
 4648                        actions.into(),
 4649                    ))
 4650                };
 4651                cx.notify();
 4652            })
 4653            .log_err();
 4654        }));
 4655        None
 4656    }
 4657
 4658    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4659        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4660            self.show_git_blame_inline = false;
 4661
 4662            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4663                cx.background_executor().timer(delay).await;
 4664
 4665                this.update(&mut cx, |this, cx| {
 4666                    this.show_git_blame_inline = true;
 4667                    cx.notify();
 4668                })
 4669                .log_err();
 4670            }));
 4671        }
 4672    }
 4673
 4674    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4675        if self.pending_rename.is_some() {
 4676            return None;
 4677        }
 4678
 4679        let project = self.project.clone()?;
 4680        let buffer = self.buffer.read(cx);
 4681        let newest_selection = self.selections.newest_anchor().clone();
 4682        let cursor_position = newest_selection.head();
 4683        let (cursor_buffer, cursor_buffer_position) =
 4684            buffer.text_anchor_for_position(cursor_position, cx)?;
 4685        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4686        if cursor_buffer != tail_buffer {
 4687            return None;
 4688        }
 4689
 4690        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4691            cx.background_executor()
 4692                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 4693                .await;
 4694
 4695            let highlights = if let Some(highlights) = project
 4696                .update(&mut cx, |project, cx| {
 4697                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4698                })
 4699                .log_err()
 4700            {
 4701                highlights.await.log_err()
 4702            } else {
 4703                None
 4704            };
 4705
 4706            if let Some(highlights) = highlights {
 4707                this.update(&mut cx, |this, cx| {
 4708                    if this.pending_rename.is_some() {
 4709                        return;
 4710                    }
 4711
 4712                    let buffer_id = cursor_position.buffer_id;
 4713                    let buffer = this.buffer.read(cx);
 4714                    if !buffer
 4715                        .text_anchor_for_position(cursor_position, cx)
 4716                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4717                    {
 4718                        return;
 4719                    }
 4720
 4721                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4722                    let mut write_ranges = Vec::new();
 4723                    let mut read_ranges = Vec::new();
 4724                    for highlight in highlights {
 4725                        for (excerpt_id, excerpt_range) in
 4726                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4727                        {
 4728                            let start = highlight
 4729                                .range
 4730                                .start
 4731                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4732                            let end = highlight
 4733                                .range
 4734                                .end
 4735                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4736                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4737                                continue;
 4738                            }
 4739
 4740                            let range = Anchor {
 4741                                buffer_id,
 4742                                excerpt_id: excerpt_id,
 4743                                text_anchor: start,
 4744                            }..Anchor {
 4745                                buffer_id,
 4746                                excerpt_id,
 4747                                text_anchor: end,
 4748                            };
 4749                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4750                                write_ranges.push(range);
 4751                            } else {
 4752                                read_ranges.push(range);
 4753                            }
 4754                        }
 4755                    }
 4756
 4757                    this.highlight_background::<DocumentHighlightRead>(
 4758                        &read_ranges,
 4759                        |theme| theme.editor_document_highlight_read_background,
 4760                        cx,
 4761                    );
 4762                    this.highlight_background::<DocumentHighlightWrite>(
 4763                        &write_ranges,
 4764                        |theme| theme.editor_document_highlight_write_background,
 4765                        cx,
 4766                    );
 4767                    cx.notify();
 4768                })
 4769                .log_err();
 4770            }
 4771        }));
 4772        None
 4773    }
 4774
 4775    fn refresh_inline_completion(
 4776        &mut self,
 4777        debounce: bool,
 4778        cx: &mut ViewContext<Self>,
 4779    ) -> Option<()> {
 4780        let provider = self.inline_completion_provider()?;
 4781        let cursor = self.selections.newest_anchor().head();
 4782        let (buffer, cursor_buffer_position) =
 4783            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4784        if !self.show_inline_completions
 4785            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4786        {
 4787            self.discard_inline_completion(false, cx);
 4788            return None;
 4789        }
 4790
 4791        self.update_visible_inline_completion(cx);
 4792        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4793        Some(())
 4794    }
 4795
 4796    fn cycle_inline_completion(
 4797        &mut self,
 4798        direction: Direction,
 4799        cx: &mut ViewContext<Self>,
 4800    ) -> Option<()> {
 4801        let provider = self.inline_completion_provider()?;
 4802        let cursor = self.selections.newest_anchor().head();
 4803        let (buffer, cursor_buffer_position) =
 4804            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4805        if !self.show_inline_completions
 4806            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4807        {
 4808            return None;
 4809        }
 4810
 4811        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4812        self.update_visible_inline_completion(cx);
 4813
 4814        Some(())
 4815    }
 4816
 4817    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4818        if !self.has_active_inline_completion(cx) {
 4819            self.refresh_inline_completion(false, cx);
 4820            return;
 4821        }
 4822
 4823        self.update_visible_inline_completion(cx);
 4824    }
 4825
 4826    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4827        self.show_cursor_names(cx);
 4828    }
 4829
 4830    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4831        self.show_cursor_names = true;
 4832        cx.notify();
 4833        cx.spawn(|this, mut cx| async move {
 4834            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4835            this.update(&mut cx, |this, cx| {
 4836                this.show_cursor_names = false;
 4837                cx.notify()
 4838            })
 4839            .ok()
 4840        })
 4841        .detach();
 4842    }
 4843
 4844    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4845        if self.has_active_inline_completion(cx) {
 4846            self.cycle_inline_completion(Direction::Next, cx);
 4847        } else {
 4848            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4849            if is_copilot_disabled {
 4850                cx.propagate();
 4851            }
 4852        }
 4853    }
 4854
 4855    pub fn previous_inline_completion(
 4856        &mut self,
 4857        _: &PreviousInlineCompletion,
 4858        cx: &mut ViewContext<Self>,
 4859    ) {
 4860        if self.has_active_inline_completion(cx) {
 4861            self.cycle_inline_completion(Direction::Prev, cx);
 4862        } else {
 4863            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4864            if is_copilot_disabled {
 4865                cx.propagate();
 4866            }
 4867        }
 4868    }
 4869
 4870    pub fn accept_inline_completion(
 4871        &mut self,
 4872        _: &AcceptInlineCompletion,
 4873        cx: &mut ViewContext<Self>,
 4874    ) {
 4875        let Some(completion) = self.take_active_inline_completion(cx) else {
 4876            return;
 4877        };
 4878        if let Some(provider) = self.inline_completion_provider() {
 4879            provider.accept(cx);
 4880        }
 4881
 4882        cx.emit(EditorEvent::InputHandled {
 4883            utf16_range_to_replace: None,
 4884            text: completion.text.to_string().into(),
 4885        });
 4886        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 4887        self.refresh_inline_completion(true, cx);
 4888        cx.notify();
 4889    }
 4890
 4891    pub fn accept_partial_inline_completion(
 4892        &mut self,
 4893        _: &AcceptPartialInlineCompletion,
 4894        cx: &mut ViewContext<Self>,
 4895    ) {
 4896        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 4897            if let Some(completion) = self.take_active_inline_completion(cx) {
 4898                let mut partial_completion = completion
 4899                    .text
 4900                    .chars()
 4901                    .by_ref()
 4902                    .take_while(|c| c.is_alphabetic())
 4903                    .collect::<String>();
 4904                if partial_completion.is_empty() {
 4905                    partial_completion = completion
 4906                        .text
 4907                        .chars()
 4908                        .by_ref()
 4909                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4910                        .collect::<String>();
 4911                }
 4912
 4913                cx.emit(EditorEvent::InputHandled {
 4914                    utf16_range_to_replace: None,
 4915                    text: partial_completion.clone().into(),
 4916                });
 4917                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4918                self.refresh_inline_completion(true, cx);
 4919                cx.notify();
 4920            }
 4921        }
 4922    }
 4923
 4924    fn discard_inline_completion(
 4925        &mut self,
 4926        should_report_inline_completion_event: bool,
 4927        cx: &mut ViewContext<Self>,
 4928    ) -> bool {
 4929        if let Some(provider) = self.inline_completion_provider() {
 4930            provider.discard(should_report_inline_completion_event, cx);
 4931        }
 4932
 4933        self.take_active_inline_completion(cx).is_some()
 4934    }
 4935
 4936    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 4937        if let Some(completion) = self.active_inline_completion.as_ref() {
 4938            let buffer = self.buffer.read(cx).read(cx);
 4939            completion.position.is_valid(&buffer)
 4940        } else {
 4941            false
 4942        }
 4943    }
 4944
 4945    fn take_active_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
 4946        let completion = self.active_inline_completion.take()?;
 4947        self.display_map.update(cx, |map, cx| {
 4948            map.splice_inlays(vec![completion.id], Default::default(), cx);
 4949        });
 4950        let buffer = self.buffer.read(cx).read(cx);
 4951
 4952        if completion.position.is_valid(&buffer) {
 4953            Some(completion)
 4954        } else {
 4955            None
 4956        }
 4957    }
 4958
 4959    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 4960        let selection = self.selections.newest_anchor();
 4961        let cursor = selection.head();
 4962
 4963        if self.context_menu.read().is_none()
 4964            && self.completion_tasks.is_empty()
 4965            && selection.start == selection.end
 4966        {
 4967            if let Some(provider) = self.inline_completion_provider() {
 4968                if let Some((buffer, cursor_buffer_position)) =
 4969                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4970                {
 4971                    if let Some(text) =
 4972                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 4973                    {
 4974                        let text = Rope::from(text);
 4975                        let mut to_remove = Vec::new();
 4976                        if let Some(completion) = self.active_inline_completion.take() {
 4977                            to_remove.push(completion.id);
 4978                        }
 4979
 4980                        let completion_inlay =
 4981                            Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
 4982                        self.active_inline_completion = Some(completion_inlay.clone());
 4983                        self.display_map.update(cx, move |map, cx| {
 4984                            map.splice_inlays(to_remove, vec![completion_inlay], cx)
 4985                        });
 4986                        cx.notify();
 4987                        return;
 4988                    }
 4989                }
 4990            }
 4991        }
 4992
 4993        self.discard_inline_completion(false, cx);
 4994    }
 4995
 4996    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4997        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4998    }
 4999
 5000    fn render_code_actions_indicator(
 5001        &self,
 5002        _style: &EditorStyle,
 5003        row: DisplayRow,
 5004        is_active: bool,
 5005        cx: &mut ViewContext<Self>,
 5006    ) -> Option<IconButton> {
 5007        if self.available_code_actions.is_some() {
 5008            Some(
 5009                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5010                    .shape(ui::IconButtonShape::Square)
 5011                    .icon_size(IconSize::XSmall)
 5012                    .icon_color(Color::Muted)
 5013                    .selected(is_active)
 5014                    .on_click(cx.listener(move |editor, _e, cx| {
 5015                        editor.focus(cx);
 5016                        editor.toggle_code_actions(
 5017                            &ToggleCodeActions {
 5018                                deployed_from_indicator: Some(row),
 5019                            },
 5020                            cx,
 5021                        );
 5022                    })),
 5023            )
 5024        } else {
 5025            None
 5026        }
 5027    }
 5028
 5029    fn clear_tasks(&mut self) {
 5030        self.tasks.clear()
 5031    }
 5032
 5033    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5034        if let Some(_) = self.tasks.insert(key, value) {
 5035            // This case should hopefully be rare, but just in case...
 5036            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5037        }
 5038    }
 5039
 5040    fn render_run_indicator(
 5041        &self,
 5042        _style: &EditorStyle,
 5043        is_active: bool,
 5044        row: DisplayRow,
 5045        cx: &mut ViewContext<Self>,
 5046    ) -> IconButton {
 5047        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5048            .shape(ui::IconButtonShape::Square)
 5049            .icon_size(IconSize::XSmall)
 5050            .icon_color(Color::Muted)
 5051            .selected(is_active)
 5052            .on_click(cx.listener(move |editor, _e, cx| {
 5053                editor.focus(cx);
 5054                editor.toggle_code_actions(
 5055                    &ToggleCodeActions {
 5056                        deployed_from_indicator: Some(row),
 5057                    },
 5058                    cx,
 5059                );
 5060            }))
 5061    }
 5062
 5063    pub fn context_menu_visible(&self) -> bool {
 5064        self.context_menu
 5065            .read()
 5066            .as_ref()
 5067            .map_or(false, |menu| menu.visible())
 5068    }
 5069
 5070    fn render_context_menu(
 5071        &self,
 5072        cursor_position: DisplayPoint,
 5073        style: &EditorStyle,
 5074        max_height: Pixels,
 5075        cx: &mut ViewContext<Editor>,
 5076    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5077        self.context_menu.read().as_ref().map(|menu| {
 5078            menu.render(
 5079                cursor_position,
 5080                style,
 5081                max_height,
 5082                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5083                cx,
 5084            )
 5085        })
 5086    }
 5087
 5088    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5089        cx.notify();
 5090        self.completion_tasks.clear();
 5091        let context_menu = self.context_menu.write().take();
 5092        if context_menu.is_some() {
 5093            self.update_visible_inline_completion(cx);
 5094        }
 5095        context_menu
 5096    }
 5097
 5098    pub fn insert_snippet(
 5099        &mut self,
 5100        insertion_ranges: &[Range<usize>],
 5101        snippet: Snippet,
 5102        cx: &mut ViewContext<Self>,
 5103    ) -> Result<()> {
 5104        struct Tabstop<T> {
 5105            is_end_tabstop: bool,
 5106            ranges: Vec<Range<T>>,
 5107        }
 5108
 5109        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5110            let snippet_text: Arc<str> = snippet.text.clone().into();
 5111            buffer.edit(
 5112                insertion_ranges
 5113                    .iter()
 5114                    .cloned()
 5115                    .map(|range| (range, snippet_text.clone())),
 5116                Some(AutoindentMode::EachLine),
 5117                cx,
 5118            );
 5119
 5120            let snapshot = &*buffer.read(cx);
 5121            let snippet = &snippet;
 5122            snippet
 5123                .tabstops
 5124                .iter()
 5125                .map(|tabstop| {
 5126                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5127                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5128                    });
 5129                    let mut tabstop_ranges = tabstop
 5130                        .iter()
 5131                        .flat_map(|tabstop_range| {
 5132                            let mut delta = 0_isize;
 5133                            insertion_ranges.iter().map(move |insertion_range| {
 5134                                let insertion_start = insertion_range.start as isize + delta;
 5135                                delta +=
 5136                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5137
 5138                                let start = ((insertion_start + tabstop_range.start) as usize)
 5139                                    .min(snapshot.len());
 5140                                let end = ((insertion_start + tabstop_range.end) as usize)
 5141                                    .min(snapshot.len());
 5142                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5143                            })
 5144                        })
 5145                        .collect::<Vec<_>>();
 5146                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5147
 5148                    Tabstop {
 5149                        is_end_tabstop,
 5150                        ranges: tabstop_ranges,
 5151                    }
 5152                })
 5153                .collect::<Vec<_>>()
 5154        });
 5155
 5156        if let Some(tabstop) = tabstops.first() {
 5157            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5158                s.select_ranges(tabstop.ranges.iter().cloned());
 5159            });
 5160
 5161            // If we're already at the last tabstop and it's at the end of the snippet,
 5162            // we're done, we don't need to keep the state around.
 5163            if !tabstop.is_end_tabstop {
 5164                let ranges = tabstops
 5165                    .into_iter()
 5166                    .map(|tabstop| tabstop.ranges)
 5167                    .collect::<Vec<_>>();
 5168                self.snippet_stack.push(SnippetState {
 5169                    active_index: 0,
 5170                    ranges,
 5171                });
 5172            }
 5173
 5174            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5175            if self.autoclose_regions.is_empty() {
 5176                let snapshot = self.buffer.read(cx).snapshot(cx);
 5177                for selection in &mut self.selections.all::<Point>(cx) {
 5178                    let selection_head = selection.head();
 5179                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5180                        continue;
 5181                    };
 5182
 5183                    let mut bracket_pair = None;
 5184                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5185                    let prev_chars = snapshot
 5186                        .reversed_chars_at(selection_head)
 5187                        .collect::<String>();
 5188                    for (pair, enabled) in scope.brackets() {
 5189                        if enabled
 5190                            && pair.close
 5191                            && prev_chars.starts_with(pair.start.as_str())
 5192                            && next_chars.starts_with(pair.end.as_str())
 5193                        {
 5194                            bracket_pair = Some(pair.clone());
 5195                            break;
 5196                        }
 5197                    }
 5198                    if let Some(pair) = bracket_pair {
 5199                        let start = snapshot.anchor_after(selection_head);
 5200                        let end = snapshot.anchor_after(selection_head);
 5201                        self.autoclose_regions.push(AutocloseRegion {
 5202                            selection_id: selection.id,
 5203                            range: start..end,
 5204                            pair,
 5205                        });
 5206                    }
 5207                }
 5208            }
 5209        }
 5210        Ok(())
 5211    }
 5212
 5213    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5214        self.move_to_snippet_tabstop(Bias::Right, cx)
 5215    }
 5216
 5217    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5218        self.move_to_snippet_tabstop(Bias::Left, cx)
 5219    }
 5220
 5221    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5222        if let Some(mut snippet) = self.snippet_stack.pop() {
 5223            match bias {
 5224                Bias::Left => {
 5225                    if snippet.active_index > 0 {
 5226                        snippet.active_index -= 1;
 5227                    } else {
 5228                        self.snippet_stack.push(snippet);
 5229                        return false;
 5230                    }
 5231                }
 5232                Bias::Right => {
 5233                    if snippet.active_index + 1 < snippet.ranges.len() {
 5234                        snippet.active_index += 1;
 5235                    } else {
 5236                        self.snippet_stack.push(snippet);
 5237                        return false;
 5238                    }
 5239                }
 5240            }
 5241            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5242                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5243                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5244                });
 5245                // If snippet state is not at the last tabstop, push it back on the stack
 5246                if snippet.active_index + 1 < snippet.ranges.len() {
 5247                    self.snippet_stack.push(snippet);
 5248                }
 5249                return true;
 5250            }
 5251        }
 5252
 5253        false
 5254    }
 5255
 5256    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5257        self.transact(cx, |this, cx| {
 5258            this.select_all(&SelectAll, cx);
 5259            this.insert("", cx);
 5260        });
 5261    }
 5262
 5263    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5264        self.transact(cx, |this, cx| {
 5265            this.select_autoclose_pair(cx);
 5266            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5267            if !this.linked_edit_ranges.is_empty() {
 5268                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5269                let snapshot = this.buffer.read(cx).snapshot(cx);
 5270
 5271                for selection in selections.iter() {
 5272                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5273                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5274                    if selection_start.buffer_id != selection_end.buffer_id {
 5275                        continue;
 5276                    }
 5277                    if let Some(ranges) =
 5278                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5279                    {
 5280                        for (buffer, entries) in ranges {
 5281                            linked_ranges.entry(buffer).or_default().extend(entries);
 5282                        }
 5283                    }
 5284                }
 5285            }
 5286
 5287            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5288            if !this.selections.line_mode {
 5289                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5290                for selection in &mut selections {
 5291                    if selection.is_empty() {
 5292                        let old_head = selection.head();
 5293                        let mut new_head =
 5294                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5295                                .to_point(&display_map);
 5296                        if let Some((buffer, line_buffer_range)) = display_map
 5297                            .buffer_snapshot
 5298                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5299                        {
 5300                            let indent_size =
 5301                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5302                            let indent_len = match indent_size.kind {
 5303                                IndentKind::Space => {
 5304                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5305                                }
 5306                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5307                            };
 5308                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5309                                let indent_len = indent_len.get();
 5310                                new_head = cmp::min(
 5311                                    new_head,
 5312                                    MultiBufferPoint::new(
 5313                                        old_head.row,
 5314                                        ((old_head.column - 1) / indent_len) * indent_len,
 5315                                    ),
 5316                                );
 5317                            }
 5318                        }
 5319
 5320                        selection.set_head(new_head, SelectionGoal::None);
 5321                    }
 5322                }
 5323            }
 5324
 5325            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5326            this.insert("", cx);
 5327            let empty_str: Arc<str> = Arc::from("");
 5328            for (buffer, edits) in linked_ranges {
 5329                let snapshot = buffer.read(cx).snapshot();
 5330                use text::ToPoint as TP;
 5331
 5332                let edits = edits
 5333                    .into_iter()
 5334                    .map(|range| {
 5335                        let end_point = TP::to_point(&range.end, &snapshot);
 5336                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5337
 5338                        if end_point == start_point {
 5339                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5340                                .saturating_sub(1);
 5341                            start_point = TP::to_point(&offset, &snapshot);
 5342                        };
 5343
 5344                        (start_point..end_point, empty_str.clone())
 5345                    })
 5346                    .sorted_by_key(|(range, _)| range.start)
 5347                    .collect::<Vec<_>>();
 5348                buffer.update(cx, |this, cx| {
 5349                    this.edit(edits, None, cx);
 5350                })
 5351            }
 5352            this.refresh_inline_completion(true, cx);
 5353            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5354        });
 5355    }
 5356
 5357    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5358        self.transact(cx, |this, cx| {
 5359            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5360                let line_mode = s.line_mode;
 5361                s.move_with(|map, selection| {
 5362                    if selection.is_empty() && !line_mode {
 5363                        let cursor = movement::right(map, selection.head());
 5364                        selection.end = cursor;
 5365                        selection.reversed = true;
 5366                        selection.goal = SelectionGoal::None;
 5367                    }
 5368                })
 5369            });
 5370            this.insert("", cx);
 5371            this.refresh_inline_completion(true, cx);
 5372        });
 5373    }
 5374
 5375    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5376        if self.move_to_prev_snippet_tabstop(cx) {
 5377            return;
 5378        }
 5379
 5380        self.outdent(&Outdent, cx);
 5381    }
 5382
 5383    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5384        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5385            return;
 5386        }
 5387
 5388        let mut selections = self.selections.all_adjusted(cx);
 5389        let buffer = self.buffer.read(cx);
 5390        let snapshot = buffer.snapshot(cx);
 5391        let rows_iter = selections.iter().map(|s| s.head().row);
 5392        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5393
 5394        let mut edits = Vec::new();
 5395        let mut prev_edited_row = 0;
 5396        let mut row_delta = 0;
 5397        for selection in &mut selections {
 5398            if selection.start.row != prev_edited_row {
 5399                row_delta = 0;
 5400            }
 5401            prev_edited_row = selection.end.row;
 5402
 5403            // If the selection is non-empty, then increase the indentation of the selected lines.
 5404            if !selection.is_empty() {
 5405                row_delta =
 5406                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5407                continue;
 5408            }
 5409
 5410            // If the selection is empty and the cursor is in the leading whitespace before the
 5411            // suggested indentation, then auto-indent the line.
 5412            let cursor = selection.head();
 5413            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5414            if let Some(suggested_indent) =
 5415                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5416            {
 5417                if cursor.column < suggested_indent.len
 5418                    && cursor.column <= current_indent.len
 5419                    && current_indent.len <= suggested_indent.len
 5420                {
 5421                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5422                    selection.end = selection.start;
 5423                    if row_delta == 0 {
 5424                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5425                            cursor.row,
 5426                            current_indent,
 5427                            suggested_indent,
 5428                        ));
 5429                        row_delta = suggested_indent.len - current_indent.len;
 5430                    }
 5431                    continue;
 5432                }
 5433            }
 5434
 5435            // Otherwise, insert a hard or soft tab.
 5436            let settings = buffer.settings_at(cursor, cx);
 5437            let tab_size = if settings.hard_tabs {
 5438                IndentSize::tab()
 5439            } else {
 5440                let tab_size = settings.tab_size.get();
 5441                let char_column = snapshot
 5442                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5443                    .flat_map(str::chars)
 5444                    .count()
 5445                    + row_delta as usize;
 5446                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5447                IndentSize::spaces(chars_to_next_tab_stop)
 5448            };
 5449            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5450            selection.end = selection.start;
 5451            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5452            row_delta += tab_size.len;
 5453        }
 5454
 5455        self.transact(cx, |this, cx| {
 5456            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5457            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5458            this.refresh_inline_completion(true, cx);
 5459        });
 5460    }
 5461
 5462    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5463        if self.read_only(cx) {
 5464            return;
 5465        }
 5466        let mut selections = self.selections.all::<Point>(cx);
 5467        let mut prev_edited_row = 0;
 5468        let mut row_delta = 0;
 5469        let mut edits = Vec::new();
 5470        let buffer = self.buffer.read(cx);
 5471        let snapshot = buffer.snapshot(cx);
 5472        for selection in &mut selections {
 5473            if selection.start.row != prev_edited_row {
 5474                row_delta = 0;
 5475            }
 5476            prev_edited_row = selection.end.row;
 5477
 5478            row_delta =
 5479                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5480        }
 5481
 5482        self.transact(cx, |this, cx| {
 5483            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5484            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5485        });
 5486    }
 5487
 5488    fn indent_selection(
 5489        buffer: &MultiBuffer,
 5490        snapshot: &MultiBufferSnapshot,
 5491        selection: &mut Selection<Point>,
 5492        edits: &mut Vec<(Range<Point>, String)>,
 5493        delta_for_start_row: u32,
 5494        cx: &AppContext,
 5495    ) -> u32 {
 5496        let settings = buffer.settings_at(selection.start, cx);
 5497        let tab_size = settings.tab_size.get();
 5498        let indent_kind = if settings.hard_tabs {
 5499            IndentKind::Tab
 5500        } else {
 5501            IndentKind::Space
 5502        };
 5503        let mut start_row = selection.start.row;
 5504        let mut end_row = selection.end.row + 1;
 5505
 5506        // If a selection ends at the beginning of a line, don't indent
 5507        // that last line.
 5508        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5509            end_row -= 1;
 5510        }
 5511
 5512        // Avoid re-indenting a row that has already been indented by a
 5513        // previous selection, but still update this selection's column
 5514        // to reflect that indentation.
 5515        if delta_for_start_row > 0 {
 5516            start_row += 1;
 5517            selection.start.column += delta_for_start_row;
 5518            if selection.end.row == selection.start.row {
 5519                selection.end.column += delta_for_start_row;
 5520            }
 5521        }
 5522
 5523        let mut delta_for_end_row = 0;
 5524        let has_multiple_rows = start_row + 1 != end_row;
 5525        for row in start_row..end_row {
 5526            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5527            let indent_delta = match (current_indent.kind, indent_kind) {
 5528                (IndentKind::Space, IndentKind::Space) => {
 5529                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5530                    IndentSize::spaces(columns_to_next_tab_stop)
 5531                }
 5532                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5533                (_, IndentKind::Tab) => IndentSize::tab(),
 5534            };
 5535
 5536            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5537                0
 5538            } else {
 5539                selection.start.column
 5540            };
 5541            let row_start = Point::new(row, start);
 5542            edits.push((
 5543                row_start..row_start,
 5544                indent_delta.chars().collect::<String>(),
 5545            ));
 5546
 5547            // Update this selection's endpoints to reflect the indentation.
 5548            if row == selection.start.row {
 5549                selection.start.column += indent_delta.len;
 5550            }
 5551            if row == selection.end.row {
 5552                selection.end.column += indent_delta.len;
 5553                delta_for_end_row = indent_delta.len;
 5554            }
 5555        }
 5556
 5557        if selection.start.row == selection.end.row {
 5558            delta_for_start_row + delta_for_end_row
 5559        } else {
 5560            delta_for_end_row
 5561        }
 5562    }
 5563
 5564    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5565        if self.read_only(cx) {
 5566            return;
 5567        }
 5568        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5569        let selections = self.selections.all::<Point>(cx);
 5570        let mut deletion_ranges = Vec::new();
 5571        let mut last_outdent = None;
 5572        {
 5573            let buffer = self.buffer.read(cx);
 5574            let snapshot = buffer.snapshot(cx);
 5575            for selection in &selections {
 5576                let settings = buffer.settings_at(selection.start, cx);
 5577                let tab_size = settings.tab_size.get();
 5578                let mut rows = selection.spanned_rows(false, &display_map);
 5579
 5580                // Avoid re-outdenting a row that has already been outdented by a
 5581                // previous selection.
 5582                if let Some(last_row) = last_outdent {
 5583                    if last_row == rows.start {
 5584                        rows.start = rows.start.next_row();
 5585                    }
 5586                }
 5587                let has_multiple_rows = rows.len() > 1;
 5588                for row in rows.iter_rows() {
 5589                    let indent_size = snapshot.indent_size_for_line(row);
 5590                    if indent_size.len > 0 {
 5591                        let deletion_len = match indent_size.kind {
 5592                            IndentKind::Space => {
 5593                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5594                                if columns_to_prev_tab_stop == 0 {
 5595                                    tab_size
 5596                                } else {
 5597                                    columns_to_prev_tab_stop
 5598                                }
 5599                            }
 5600                            IndentKind::Tab => 1,
 5601                        };
 5602                        let start = if has_multiple_rows
 5603                            || deletion_len > selection.start.column
 5604                            || indent_size.len < selection.start.column
 5605                        {
 5606                            0
 5607                        } else {
 5608                            selection.start.column - deletion_len
 5609                        };
 5610                        deletion_ranges.push(
 5611                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5612                        );
 5613                        last_outdent = Some(row);
 5614                    }
 5615                }
 5616            }
 5617        }
 5618
 5619        self.transact(cx, |this, cx| {
 5620            this.buffer.update(cx, |buffer, cx| {
 5621                let empty_str: Arc<str> = "".into();
 5622                buffer.edit(
 5623                    deletion_ranges
 5624                        .into_iter()
 5625                        .map(|range| (range, empty_str.clone())),
 5626                    None,
 5627                    cx,
 5628                );
 5629            });
 5630            let selections = this.selections.all::<usize>(cx);
 5631            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5632        });
 5633    }
 5634
 5635    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5636        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5637        let selections = self.selections.all::<Point>(cx);
 5638
 5639        let mut new_cursors = Vec::new();
 5640        let mut edit_ranges = Vec::new();
 5641        let mut selections = selections.iter().peekable();
 5642        while let Some(selection) = selections.next() {
 5643            let mut rows = selection.spanned_rows(false, &display_map);
 5644            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5645
 5646            // Accumulate contiguous regions of rows that we want to delete.
 5647            while let Some(next_selection) = selections.peek() {
 5648                let next_rows = next_selection.spanned_rows(false, &display_map);
 5649                if next_rows.start <= rows.end {
 5650                    rows.end = next_rows.end;
 5651                    selections.next().unwrap();
 5652                } else {
 5653                    break;
 5654                }
 5655            }
 5656
 5657            let buffer = &display_map.buffer_snapshot;
 5658            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5659            let edit_end;
 5660            let cursor_buffer_row;
 5661            if buffer.max_point().row >= rows.end.0 {
 5662                // If there's a line after the range, delete the \n from the end of the row range
 5663                // and position the cursor on the next line.
 5664                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5665                cursor_buffer_row = rows.end;
 5666            } else {
 5667                // If there isn't a line after the range, delete the \n from the line before the
 5668                // start of the row range and position the cursor there.
 5669                edit_start = edit_start.saturating_sub(1);
 5670                edit_end = buffer.len();
 5671                cursor_buffer_row = rows.start.previous_row();
 5672            }
 5673
 5674            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5675            *cursor.column_mut() =
 5676                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5677
 5678            new_cursors.push((
 5679                selection.id,
 5680                buffer.anchor_after(cursor.to_point(&display_map)),
 5681            ));
 5682            edit_ranges.push(edit_start..edit_end);
 5683        }
 5684
 5685        self.transact(cx, |this, cx| {
 5686            let buffer = this.buffer.update(cx, |buffer, cx| {
 5687                let empty_str: Arc<str> = "".into();
 5688                buffer.edit(
 5689                    edit_ranges
 5690                        .into_iter()
 5691                        .map(|range| (range, empty_str.clone())),
 5692                    None,
 5693                    cx,
 5694                );
 5695                buffer.snapshot(cx)
 5696            });
 5697            let new_selections = new_cursors
 5698                .into_iter()
 5699                .map(|(id, cursor)| {
 5700                    let cursor = cursor.to_point(&buffer);
 5701                    Selection {
 5702                        id,
 5703                        start: cursor,
 5704                        end: cursor,
 5705                        reversed: false,
 5706                        goal: SelectionGoal::None,
 5707                    }
 5708                })
 5709                .collect();
 5710
 5711            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5712                s.select(new_selections);
 5713            });
 5714        });
 5715    }
 5716
 5717    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5718        if self.read_only(cx) {
 5719            return;
 5720        }
 5721        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5722        for selection in self.selections.all::<Point>(cx) {
 5723            let start = MultiBufferRow(selection.start.row);
 5724            let end = if selection.start.row == selection.end.row {
 5725                MultiBufferRow(selection.start.row + 1)
 5726            } else {
 5727                MultiBufferRow(selection.end.row)
 5728            };
 5729
 5730            if let Some(last_row_range) = row_ranges.last_mut() {
 5731                if start <= last_row_range.end {
 5732                    last_row_range.end = end;
 5733                    continue;
 5734                }
 5735            }
 5736            row_ranges.push(start..end);
 5737        }
 5738
 5739        let snapshot = self.buffer.read(cx).snapshot(cx);
 5740        let mut cursor_positions = Vec::new();
 5741        for row_range in &row_ranges {
 5742            let anchor = snapshot.anchor_before(Point::new(
 5743                row_range.end.previous_row().0,
 5744                snapshot.line_len(row_range.end.previous_row()),
 5745            ));
 5746            cursor_positions.push(anchor..anchor);
 5747        }
 5748
 5749        self.transact(cx, |this, cx| {
 5750            for row_range in row_ranges.into_iter().rev() {
 5751                for row in row_range.iter_rows().rev() {
 5752                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5753                    let next_line_row = row.next_row();
 5754                    let indent = snapshot.indent_size_for_line(next_line_row);
 5755                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5756
 5757                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5758                        " "
 5759                    } else {
 5760                        ""
 5761                    };
 5762
 5763                    this.buffer.update(cx, |buffer, cx| {
 5764                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5765                    });
 5766                }
 5767            }
 5768
 5769            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5770                s.select_anchor_ranges(cursor_positions)
 5771            });
 5772        });
 5773    }
 5774
 5775    pub fn sort_lines_case_sensitive(
 5776        &mut self,
 5777        _: &SortLinesCaseSensitive,
 5778        cx: &mut ViewContext<Self>,
 5779    ) {
 5780        self.manipulate_lines(cx, |lines| lines.sort())
 5781    }
 5782
 5783    pub fn sort_lines_case_insensitive(
 5784        &mut self,
 5785        _: &SortLinesCaseInsensitive,
 5786        cx: &mut ViewContext<Self>,
 5787    ) {
 5788        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5789    }
 5790
 5791    pub fn unique_lines_case_insensitive(
 5792        &mut self,
 5793        _: &UniqueLinesCaseInsensitive,
 5794        cx: &mut ViewContext<Self>,
 5795    ) {
 5796        self.manipulate_lines(cx, |lines| {
 5797            let mut seen = HashSet::default();
 5798            lines.retain(|line| seen.insert(line.to_lowercase()));
 5799        })
 5800    }
 5801
 5802    pub fn unique_lines_case_sensitive(
 5803        &mut self,
 5804        _: &UniqueLinesCaseSensitive,
 5805        cx: &mut ViewContext<Self>,
 5806    ) {
 5807        self.manipulate_lines(cx, |lines| {
 5808            let mut seen = HashSet::default();
 5809            lines.retain(|line| seen.insert(*line));
 5810        })
 5811    }
 5812
 5813    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5814        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 5815        if !revert_changes.is_empty() {
 5816            self.transact(cx, |editor, cx| {
 5817                editor.buffer().update(cx, |multi_buffer, cx| {
 5818                    for (buffer_id, changes) in revert_changes {
 5819                        if let Some(buffer) = multi_buffer.buffer(buffer_id) {
 5820                            buffer.update(cx, |buffer, cx| {
 5821                                buffer.edit(
 5822                                    changes.into_iter().map(|(range, text)| {
 5823                                        (range, text.to_string().map(Arc::<str>::from))
 5824                                    }),
 5825                                    None,
 5826                                    cx,
 5827                                );
 5828                            });
 5829                        }
 5830                    }
 5831                });
 5832                editor.change_selections(None, cx, |selections| selections.refresh());
 5833            });
 5834        }
 5835    }
 5836
 5837    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5838        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5839            let project_path = buffer.read(cx).project_path(cx)?;
 5840            let project = self.project.as_ref()?.read(cx);
 5841            let entry = project.entry_for_path(&project_path, cx)?;
 5842            let abs_path = project.absolute_path(&project_path, cx)?;
 5843            let parent = if entry.is_symlink {
 5844                abs_path.canonicalize().ok()?
 5845            } else {
 5846                abs_path
 5847            }
 5848            .parent()?
 5849            .to_path_buf();
 5850            Some(parent)
 5851        }) {
 5852            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5853        }
 5854    }
 5855
 5856    fn gather_revert_changes(
 5857        &mut self,
 5858        selections: &[Selection<Anchor>],
 5859        cx: &mut ViewContext<'_, Editor>,
 5860    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 5861        let mut revert_changes = HashMap::default();
 5862        self.buffer.update(cx, |multi_buffer, cx| {
 5863            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 5864            for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 5865                Self::prepare_revert_change(&mut revert_changes, &multi_buffer, &hunk, cx);
 5866            }
 5867        });
 5868        revert_changes
 5869    }
 5870
 5871    fn prepare_revert_change(
 5872        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 5873        multi_buffer: &MultiBuffer,
 5874        hunk: &DiffHunk<MultiBufferRow>,
 5875        cx: &mut AppContext,
 5876    ) -> Option<()> {
 5877        let buffer = multi_buffer.buffer(hunk.buffer_id)?;
 5878        let buffer = buffer.read(cx);
 5879        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 5880        let buffer_snapshot = buffer.snapshot();
 5881        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5882        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5883            probe
 5884                .0
 5885                .start
 5886                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5887                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5888        }) {
 5889            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 5890            Some(())
 5891        } else {
 5892            None
 5893        }
 5894    }
 5895
 5896    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5897        self.manipulate_lines(cx, |lines| lines.reverse())
 5898    }
 5899
 5900    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5901        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5902    }
 5903
 5904    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5905    where
 5906        Fn: FnMut(&mut Vec<&str>),
 5907    {
 5908        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5909        let buffer = self.buffer.read(cx).snapshot(cx);
 5910
 5911        let mut edits = Vec::new();
 5912
 5913        let selections = self.selections.all::<Point>(cx);
 5914        let mut selections = selections.iter().peekable();
 5915        let mut contiguous_row_selections = Vec::new();
 5916        let mut new_selections = Vec::new();
 5917        let mut added_lines = 0;
 5918        let mut removed_lines = 0;
 5919
 5920        while let Some(selection) = selections.next() {
 5921            let (start_row, end_row) = consume_contiguous_rows(
 5922                &mut contiguous_row_selections,
 5923                selection,
 5924                &display_map,
 5925                &mut selections,
 5926            );
 5927
 5928            let start_point = Point::new(start_row.0, 0);
 5929            let end_point = Point::new(
 5930                end_row.previous_row().0,
 5931                buffer.line_len(end_row.previous_row()),
 5932            );
 5933            let text = buffer
 5934                .text_for_range(start_point..end_point)
 5935                .collect::<String>();
 5936
 5937            let mut lines = text.split('\n').collect_vec();
 5938
 5939            let lines_before = lines.len();
 5940            callback(&mut lines);
 5941            let lines_after = lines.len();
 5942
 5943            edits.push((start_point..end_point, lines.join("\n")));
 5944
 5945            // Selections must change based on added and removed line count
 5946            let start_row =
 5947                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 5948            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 5949            new_selections.push(Selection {
 5950                id: selection.id,
 5951                start: start_row,
 5952                end: end_row,
 5953                goal: SelectionGoal::None,
 5954                reversed: selection.reversed,
 5955            });
 5956
 5957            if lines_after > lines_before {
 5958                added_lines += lines_after - lines_before;
 5959            } else if lines_before > lines_after {
 5960                removed_lines += lines_before - lines_after;
 5961            }
 5962        }
 5963
 5964        self.transact(cx, |this, cx| {
 5965            let buffer = this.buffer.update(cx, |buffer, cx| {
 5966                buffer.edit(edits, None, cx);
 5967                buffer.snapshot(cx)
 5968            });
 5969
 5970            // Recalculate offsets on newly edited buffer
 5971            let new_selections = new_selections
 5972                .iter()
 5973                .map(|s| {
 5974                    let start_point = Point::new(s.start.0, 0);
 5975                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 5976                    Selection {
 5977                        id: s.id,
 5978                        start: buffer.point_to_offset(start_point),
 5979                        end: buffer.point_to_offset(end_point),
 5980                        goal: s.goal,
 5981                        reversed: s.reversed,
 5982                    }
 5983                })
 5984                .collect();
 5985
 5986            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5987                s.select(new_selections);
 5988            });
 5989
 5990            this.request_autoscroll(Autoscroll::fit(), cx);
 5991        });
 5992    }
 5993
 5994    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 5995        self.manipulate_text(cx, |text| text.to_uppercase())
 5996    }
 5997
 5998    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 5999        self.manipulate_text(cx, |text| text.to_lowercase())
 6000    }
 6001
 6002    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6003        self.manipulate_text(cx, |text| {
 6004            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6005            // https://github.com/rutrum/convert-case/issues/16
 6006            text.split('\n')
 6007                .map(|line| line.to_case(Case::Title))
 6008                .join("\n")
 6009        })
 6010    }
 6011
 6012    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6013        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6014    }
 6015
 6016    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6017        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6018    }
 6019
 6020    pub fn convert_to_upper_camel_case(
 6021        &mut self,
 6022        _: &ConvertToUpperCamelCase,
 6023        cx: &mut ViewContext<Self>,
 6024    ) {
 6025        self.manipulate_text(cx, |text| {
 6026            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6027            // https://github.com/rutrum/convert-case/issues/16
 6028            text.split('\n')
 6029                .map(|line| line.to_case(Case::UpperCamel))
 6030                .join("\n")
 6031        })
 6032    }
 6033
 6034    pub fn convert_to_lower_camel_case(
 6035        &mut self,
 6036        _: &ConvertToLowerCamelCase,
 6037        cx: &mut ViewContext<Self>,
 6038    ) {
 6039        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6040    }
 6041
 6042    pub fn convert_to_opposite_case(
 6043        &mut self,
 6044        _: &ConvertToOppositeCase,
 6045        cx: &mut ViewContext<Self>,
 6046    ) {
 6047        self.manipulate_text(cx, |text| {
 6048            text.chars()
 6049                .fold(String::with_capacity(text.len()), |mut t, c| {
 6050                    if c.is_uppercase() {
 6051                        t.extend(c.to_lowercase());
 6052                    } else {
 6053                        t.extend(c.to_uppercase());
 6054                    }
 6055                    t
 6056                })
 6057        })
 6058    }
 6059
 6060    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6061    where
 6062        Fn: FnMut(&str) -> String,
 6063    {
 6064        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6065        let buffer = self.buffer.read(cx).snapshot(cx);
 6066
 6067        let mut new_selections = Vec::new();
 6068        let mut edits = Vec::new();
 6069        let mut selection_adjustment = 0i32;
 6070
 6071        for selection in self.selections.all::<usize>(cx) {
 6072            let selection_is_empty = selection.is_empty();
 6073
 6074            let (start, end) = if selection_is_empty {
 6075                let word_range = movement::surrounding_word(
 6076                    &display_map,
 6077                    selection.start.to_display_point(&display_map),
 6078                );
 6079                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6080                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6081                (start, end)
 6082            } else {
 6083                (selection.start, selection.end)
 6084            };
 6085
 6086            let text = buffer.text_for_range(start..end).collect::<String>();
 6087            let old_length = text.len() as i32;
 6088            let text = callback(&text);
 6089
 6090            new_selections.push(Selection {
 6091                start: (start as i32 - selection_adjustment) as usize,
 6092                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6093                goal: SelectionGoal::None,
 6094                ..selection
 6095            });
 6096
 6097            selection_adjustment += old_length - text.len() as i32;
 6098
 6099            edits.push((start..end, text));
 6100        }
 6101
 6102        self.transact(cx, |this, cx| {
 6103            this.buffer.update(cx, |buffer, cx| {
 6104                buffer.edit(edits, None, cx);
 6105            });
 6106
 6107            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6108                s.select(new_selections);
 6109            });
 6110
 6111            this.request_autoscroll(Autoscroll::fit(), cx);
 6112        });
 6113    }
 6114
 6115    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6116        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6117        let buffer = &display_map.buffer_snapshot;
 6118        let selections = self.selections.all::<Point>(cx);
 6119
 6120        let mut edits = Vec::new();
 6121        let mut selections_iter = selections.iter().peekable();
 6122        while let Some(selection) = selections_iter.next() {
 6123            // Avoid duplicating the same lines twice.
 6124            let mut rows = selection.spanned_rows(false, &display_map);
 6125
 6126            while let Some(next_selection) = selections_iter.peek() {
 6127                let next_rows = next_selection.spanned_rows(false, &display_map);
 6128                if next_rows.start < rows.end {
 6129                    rows.end = next_rows.end;
 6130                    selections_iter.next().unwrap();
 6131                } else {
 6132                    break;
 6133                }
 6134            }
 6135
 6136            // Copy the text from the selected row region and splice it either at the start
 6137            // or end of the region.
 6138            let start = Point::new(rows.start.0, 0);
 6139            let end = Point::new(
 6140                rows.end.previous_row().0,
 6141                buffer.line_len(rows.end.previous_row()),
 6142            );
 6143            let text = buffer
 6144                .text_for_range(start..end)
 6145                .chain(Some("\n"))
 6146                .collect::<String>();
 6147            let insert_location = if upwards {
 6148                Point::new(rows.end.0, 0)
 6149            } else {
 6150                start
 6151            };
 6152            edits.push((insert_location..insert_location, text));
 6153        }
 6154
 6155        self.transact(cx, |this, cx| {
 6156            this.buffer.update(cx, |buffer, cx| {
 6157                buffer.edit(edits, None, cx);
 6158            });
 6159
 6160            this.request_autoscroll(Autoscroll::fit(), cx);
 6161        });
 6162    }
 6163
 6164    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6165        self.duplicate_line(true, cx);
 6166    }
 6167
 6168    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6169        self.duplicate_line(false, cx);
 6170    }
 6171
 6172    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6173        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6174        let buffer = self.buffer.read(cx).snapshot(cx);
 6175
 6176        let mut edits = Vec::new();
 6177        let mut unfold_ranges = Vec::new();
 6178        let mut refold_ranges = Vec::new();
 6179
 6180        let selections = self.selections.all::<Point>(cx);
 6181        let mut selections = selections.iter().peekable();
 6182        let mut contiguous_row_selections = Vec::new();
 6183        let mut new_selections = Vec::new();
 6184
 6185        while let Some(selection) = selections.next() {
 6186            // Find all the selections that span a contiguous row range
 6187            let (start_row, end_row) = consume_contiguous_rows(
 6188                &mut contiguous_row_selections,
 6189                selection,
 6190                &display_map,
 6191                &mut selections,
 6192            );
 6193
 6194            // Move the text spanned by the row range to be before the line preceding the row range
 6195            if start_row.0 > 0 {
 6196                let range_to_move = Point::new(
 6197                    start_row.previous_row().0,
 6198                    buffer.line_len(start_row.previous_row()),
 6199                )
 6200                    ..Point::new(
 6201                        end_row.previous_row().0,
 6202                        buffer.line_len(end_row.previous_row()),
 6203                    );
 6204                let insertion_point = display_map
 6205                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6206                    .0;
 6207
 6208                // Don't move lines across excerpts
 6209                if buffer
 6210                    .excerpt_boundaries_in_range((
 6211                        Bound::Excluded(insertion_point),
 6212                        Bound::Included(range_to_move.end),
 6213                    ))
 6214                    .next()
 6215                    .is_none()
 6216                {
 6217                    let text = buffer
 6218                        .text_for_range(range_to_move.clone())
 6219                        .flat_map(|s| s.chars())
 6220                        .skip(1)
 6221                        .chain(['\n'])
 6222                        .collect::<String>();
 6223
 6224                    edits.push((
 6225                        buffer.anchor_after(range_to_move.start)
 6226                            ..buffer.anchor_before(range_to_move.end),
 6227                        String::new(),
 6228                    ));
 6229                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6230                    edits.push((insertion_anchor..insertion_anchor, text));
 6231
 6232                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6233
 6234                    // Move selections up
 6235                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6236                        |mut selection| {
 6237                            selection.start.row -= row_delta;
 6238                            selection.end.row -= row_delta;
 6239                            selection
 6240                        },
 6241                    ));
 6242
 6243                    // Move folds up
 6244                    unfold_ranges.push(range_to_move.clone());
 6245                    for fold in display_map.folds_in_range(
 6246                        buffer.anchor_before(range_to_move.start)
 6247                            ..buffer.anchor_after(range_to_move.end),
 6248                    ) {
 6249                        let mut start = fold.range.start.to_point(&buffer);
 6250                        let mut end = fold.range.end.to_point(&buffer);
 6251                        start.row -= row_delta;
 6252                        end.row -= row_delta;
 6253                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6254                    }
 6255                }
 6256            }
 6257
 6258            // If we didn't move line(s), preserve the existing selections
 6259            new_selections.append(&mut contiguous_row_selections);
 6260        }
 6261
 6262        self.transact(cx, |this, cx| {
 6263            this.unfold_ranges(unfold_ranges, true, true, cx);
 6264            this.buffer.update(cx, |buffer, cx| {
 6265                for (range, text) in edits {
 6266                    buffer.edit([(range, text)], None, cx);
 6267                }
 6268            });
 6269            this.fold_ranges(refold_ranges, true, cx);
 6270            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6271                s.select(new_selections);
 6272            })
 6273        });
 6274    }
 6275
 6276    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6277        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6278        let buffer = self.buffer.read(cx).snapshot(cx);
 6279
 6280        let mut edits = Vec::new();
 6281        let mut unfold_ranges = Vec::new();
 6282        let mut refold_ranges = Vec::new();
 6283
 6284        let selections = self.selections.all::<Point>(cx);
 6285        let mut selections = selections.iter().peekable();
 6286        let mut contiguous_row_selections = Vec::new();
 6287        let mut new_selections = Vec::new();
 6288
 6289        while let Some(selection) = selections.next() {
 6290            // Find all the selections that span a contiguous row range
 6291            let (start_row, end_row) = consume_contiguous_rows(
 6292                &mut contiguous_row_selections,
 6293                selection,
 6294                &display_map,
 6295                &mut selections,
 6296            );
 6297
 6298            // Move the text spanned by the row range to be after the last line of the row range
 6299            if end_row.0 <= buffer.max_point().row {
 6300                let range_to_move =
 6301                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6302                let insertion_point = display_map
 6303                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6304                    .0;
 6305
 6306                // Don't move lines across excerpt boundaries
 6307                if buffer
 6308                    .excerpt_boundaries_in_range((
 6309                        Bound::Excluded(range_to_move.start),
 6310                        Bound::Included(insertion_point),
 6311                    ))
 6312                    .next()
 6313                    .is_none()
 6314                {
 6315                    let mut text = String::from("\n");
 6316                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6317                    text.pop(); // Drop trailing newline
 6318                    edits.push((
 6319                        buffer.anchor_after(range_to_move.start)
 6320                            ..buffer.anchor_before(range_to_move.end),
 6321                        String::new(),
 6322                    ));
 6323                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6324                    edits.push((insertion_anchor..insertion_anchor, text));
 6325
 6326                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6327
 6328                    // Move selections down
 6329                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6330                        |mut selection| {
 6331                            selection.start.row += row_delta;
 6332                            selection.end.row += row_delta;
 6333                            selection
 6334                        },
 6335                    ));
 6336
 6337                    // Move folds down
 6338                    unfold_ranges.push(range_to_move.clone());
 6339                    for fold in display_map.folds_in_range(
 6340                        buffer.anchor_before(range_to_move.start)
 6341                            ..buffer.anchor_after(range_to_move.end),
 6342                    ) {
 6343                        let mut start = fold.range.start.to_point(&buffer);
 6344                        let mut end = fold.range.end.to_point(&buffer);
 6345                        start.row += row_delta;
 6346                        end.row += row_delta;
 6347                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6348                    }
 6349                }
 6350            }
 6351
 6352            // If we didn't move line(s), preserve the existing selections
 6353            new_selections.append(&mut contiguous_row_selections);
 6354        }
 6355
 6356        self.transact(cx, |this, cx| {
 6357            this.unfold_ranges(unfold_ranges, true, true, cx);
 6358            this.buffer.update(cx, |buffer, cx| {
 6359                for (range, text) in edits {
 6360                    buffer.edit([(range, text)], None, cx);
 6361                }
 6362            });
 6363            this.fold_ranges(refold_ranges, true, cx);
 6364            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6365        });
 6366    }
 6367
 6368    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6369        let text_layout_details = &self.text_layout_details(cx);
 6370        self.transact(cx, |this, cx| {
 6371            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6372                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6373                let line_mode = s.line_mode;
 6374                s.move_with(|display_map, selection| {
 6375                    if !selection.is_empty() || line_mode {
 6376                        return;
 6377                    }
 6378
 6379                    let mut head = selection.head();
 6380                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6381                    if head.column() == display_map.line_len(head.row()) {
 6382                        transpose_offset = display_map
 6383                            .buffer_snapshot
 6384                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6385                    }
 6386
 6387                    if transpose_offset == 0 {
 6388                        return;
 6389                    }
 6390
 6391                    *head.column_mut() += 1;
 6392                    head = display_map.clip_point(head, Bias::Right);
 6393                    let goal = SelectionGoal::HorizontalPosition(
 6394                        display_map
 6395                            .x_for_display_point(head, &text_layout_details)
 6396                            .into(),
 6397                    );
 6398                    selection.collapse_to(head, goal);
 6399
 6400                    let transpose_start = display_map
 6401                        .buffer_snapshot
 6402                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6403                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6404                        let transpose_end = display_map
 6405                            .buffer_snapshot
 6406                            .clip_offset(transpose_offset + 1, Bias::Right);
 6407                        if let Some(ch) =
 6408                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6409                        {
 6410                            edits.push((transpose_start..transpose_offset, String::new()));
 6411                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6412                        }
 6413                    }
 6414                });
 6415                edits
 6416            });
 6417            this.buffer
 6418                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6419            let selections = this.selections.all::<usize>(cx);
 6420            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6421                s.select(selections);
 6422            });
 6423        });
 6424    }
 6425
 6426    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6427        let mut text = String::new();
 6428        let buffer = self.buffer.read(cx).snapshot(cx);
 6429        let mut selections = self.selections.all::<Point>(cx);
 6430        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6431        {
 6432            let max_point = buffer.max_point();
 6433            let mut is_first = true;
 6434            for selection in &mut selections {
 6435                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6436                if is_entire_line {
 6437                    selection.start = Point::new(selection.start.row, 0);
 6438                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6439                    selection.goal = SelectionGoal::None;
 6440                }
 6441                if is_first {
 6442                    is_first = false;
 6443                } else {
 6444                    text += "\n";
 6445                }
 6446                let mut len = 0;
 6447                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6448                    text.push_str(chunk);
 6449                    len += chunk.len();
 6450                }
 6451                clipboard_selections.push(ClipboardSelection {
 6452                    len,
 6453                    is_entire_line,
 6454                    first_line_indent: buffer
 6455                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6456                        .len,
 6457                });
 6458            }
 6459        }
 6460
 6461        self.transact(cx, |this, cx| {
 6462            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6463                s.select(selections);
 6464            });
 6465            this.insert("", cx);
 6466            cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6467        });
 6468    }
 6469
 6470    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6471        let selections = self.selections.all::<Point>(cx);
 6472        let buffer = self.buffer.read(cx).read(cx);
 6473        let mut text = String::new();
 6474
 6475        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6476        {
 6477            let max_point = buffer.max_point();
 6478            let mut is_first = true;
 6479            for selection in selections.iter() {
 6480                let mut start = selection.start;
 6481                let mut end = selection.end;
 6482                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6483                if is_entire_line {
 6484                    start = Point::new(start.row, 0);
 6485                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6486                }
 6487                if is_first {
 6488                    is_first = false;
 6489                } else {
 6490                    text += "\n";
 6491                }
 6492                let mut len = 0;
 6493                for chunk in buffer.text_for_range(start..end) {
 6494                    text.push_str(chunk);
 6495                    len += chunk.len();
 6496                }
 6497                clipboard_selections.push(ClipboardSelection {
 6498                    len,
 6499                    is_entire_line,
 6500                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6501                });
 6502            }
 6503        }
 6504
 6505        cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6506    }
 6507
 6508    pub fn do_paste(
 6509        &mut self,
 6510        text: &String,
 6511        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6512        handle_entire_lines: bool,
 6513        cx: &mut ViewContext<Self>,
 6514    ) {
 6515        if self.read_only(cx) {
 6516            return;
 6517        }
 6518
 6519        let clipboard_text = Cow::Borrowed(text);
 6520
 6521        self.transact(cx, |this, cx| {
 6522            if let Some(mut clipboard_selections) = clipboard_selections {
 6523                let old_selections = this.selections.all::<usize>(cx);
 6524                let all_selections_were_entire_line =
 6525                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6526                let first_selection_indent_column =
 6527                    clipboard_selections.first().map(|s| s.first_line_indent);
 6528                if clipboard_selections.len() != old_selections.len() {
 6529                    clipboard_selections.drain(..);
 6530                }
 6531
 6532                this.buffer.update(cx, |buffer, cx| {
 6533                    let snapshot = buffer.read(cx);
 6534                    let mut start_offset = 0;
 6535                    let mut edits = Vec::new();
 6536                    let mut original_indent_columns = Vec::new();
 6537                    for (ix, selection) in old_selections.iter().enumerate() {
 6538                        let to_insert;
 6539                        let entire_line;
 6540                        let original_indent_column;
 6541                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6542                            let end_offset = start_offset + clipboard_selection.len;
 6543                            to_insert = &clipboard_text[start_offset..end_offset];
 6544                            entire_line = clipboard_selection.is_entire_line;
 6545                            start_offset = end_offset + 1;
 6546                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6547                        } else {
 6548                            to_insert = clipboard_text.as_str();
 6549                            entire_line = all_selections_were_entire_line;
 6550                            original_indent_column = first_selection_indent_column
 6551                        }
 6552
 6553                        // If the corresponding selection was empty when this slice of the
 6554                        // clipboard text was written, then the entire line containing the
 6555                        // selection was copied. If this selection is also currently empty,
 6556                        // then paste the line before the current line of the buffer.
 6557                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6558                            let column = selection.start.to_point(&snapshot).column as usize;
 6559                            let line_start = selection.start - column;
 6560                            line_start..line_start
 6561                        } else {
 6562                            selection.range()
 6563                        };
 6564
 6565                        edits.push((range, to_insert));
 6566                        original_indent_columns.extend(original_indent_column);
 6567                    }
 6568                    drop(snapshot);
 6569
 6570                    buffer.edit(
 6571                        edits,
 6572                        Some(AutoindentMode::Block {
 6573                            original_indent_columns,
 6574                        }),
 6575                        cx,
 6576                    );
 6577                });
 6578
 6579                let selections = this.selections.all::<usize>(cx);
 6580                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6581            } else {
 6582                this.insert(&clipboard_text, cx);
 6583            }
 6584        });
 6585    }
 6586
 6587    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6588        if let Some(item) = cx.read_from_clipboard() {
 6589            self.do_paste(
 6590                item.text(),
 6591                item.metadata::<Vec<ClipboardSelection>>(),
 6592                true,
 6593                cx,
 6594            )
 6595        };
 6596    }
 6597
 6598    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6599        if self.read_only(cx) {
 6600            return;
 6601        }
 6602
 6603        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6604            if let Some((selections, _)) =
 6605                self.selection_history.transaction(transaction_id).cloned()
 6606            {
 6607                self.change_selections(None, cx, |s| {
 6608                    s.select_anchors(selections.to_vec());
 6609                });
 6610            }
 6611            self.request_autoscroll(Autoscroll::fit(), cx);
 6612            self.unmark_text(cx);
 6613            self.refresh_inline_completion(true, cx);
 6614            cx.emit(EditorEvent::Edited { transaction_id });
 6615            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 6616        }
 6617    }
 6618
 6619    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 6620        if self.read_only(cx) {
 6621            return;
 6622        }
 6623
 6624        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 6625            if let Some((_, Some(selections))) =
 6626                self.selection_history.transaction(transaction_id).cloned()
 6627            {
 6628                self.change_selections(None, cx, |s| {
 6629                    s.select_anchors(selections.to_vec());
 6630                });
 6631            }
 6632            self.request_autoscroll(Autoscroll::fit(), cx);
 6633            self.unmark_text(cx);
 6634            self.refresh_inline_completion(true, cx);
 6635            cx.emit(EditorEvent::Edited { transaction_id });
 6636        }
 6637    }
 6638
 6639    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 6640        self.buffer
 6641            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 6642    }
 6643
 6644    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 6645        self.buffer
 6646            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 6647    }
 6648
 6649    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 6650        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6651            let line_mode = s.line_mode;
 6652            s.move_with(|map, selection| {
 6653                let cursor = if selection.is_empty() && !line_mode {
 6654                    movement::left(map, selection.start)
 6655                } else {
 6656                    selection.start
 6657                };
 6658                selection.collapse_to(cursor, SelectionGoal::None);
 6659            });
 6660        })
 6661    }
 6662
 6663    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 6664        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6665            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 6666        })
 6667    }
 6668
 6669    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 6670        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6671            let line_mode = s.line_mode;
 6672            s.move_with(|map, selection| {
 6673                let cursor = if selection.is_empty() && !line_mode {
 6674                    movement::right(map, selection.end)
 6675                } else {
 6676                    selection.end
 6677                };
 6678                selection.collapse_to(cursor, SelectionGoal::None)
 6679            });
 6680        })
 6681    }
 6682
 6683    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 6684        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6685            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 6686        })
 6687    }
 6688
 6689    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 6690        if self.take_rename(true, cx).is_some() {
 6691            return;
 6692        }
 6693
 6694        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6695            cx.propagate();
 6696            return;
 6697        }
 6698
 6699        let text_layout_details = &self.text_layout_details(cx);
 6700        let selection_count = self.selections.count();
 6701        let first_selection = self.selections.first_anchor();
 6702
 6703        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6704            let line_mode = s.line_mode;
 6705            s.move_with(|map, selection| {
 6706                if !selection.is_empty() && !line_mode {
 6707                    selection.goal = SelectionGoal::None;
 6708                }
 6709                let (cursor, goal) = movement::up(
 6710                    map,
 6711                    selection.start,
 6712                    selection.goal,
 6713                    false,
 6714                    &text_layout_details,
 6715                );
 6716                selection.collapse_to(cursor, goal);
 6717            });
 6718        });
 6719
 6720        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6721        {
 6722            cx.propagate();
 6723        }
 6724    }
 6725
 6726    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 6727        if self.take_rename(true, cx).is_some() {
 6728            return;
 6729        }
 6730
 6731        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6732            cx.propagate();
 6733            return;
 6734        }
 6735
 6736        let text_layout_details = &self.text_layout_details(cx);
 6737
 6738        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6739            let line_mode = s.line_mode;
 6740            s.move_with(|map, selection| {
 6741                if !selection.is_empty() && !line_mode {
 6742                    selection.goal = SelectionGoal::None;
 6743                }
 6744                let (cursor, goal) = movement::up_by_rows(
 6745                    map,
 6746                    selection.start,
 6747                    action.lines,
 6748                    selection.goal,
 6749                    false,
 6750                    &text_layout_details,
 6751                );
 6752                selection.collapse_to(cursor, goal);
 6753            });
 6754        })
 6755    }
 6756
 6757    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 6758        if self.take_rename(true, cx).is_some() {
 6759            return;
 6760        }
 6761
 6762        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6763            cx.propagate();
 6764            return;
 6765        }
 6766
 6767        let text_layout_details = &self.text_layout_details(cx);
 6768
 6769        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6770            let line_mode = s.line_mode;
 6771            s.move_with(|map, selection| {
 6772                if !selection.is_empty() && !line_mode {
 6773                    selection.goal = SelectionGoal::None;
 6774                }
 6775                let (cursor, goal) = movement::down_by_rows(
 6776                    map,
 6777                    selection.start,
 6778                    action.lines,
 6779                    selection.goal,
 6780                    false,
 6781                    &text_layout_details,
 6782                );
 6783                selection.collapse_to(cursor, goal);
 6784            });
 6785        })
 6786    }
 6787
 6788    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 6789        let text_layout_details = &self.text_layout_details(cx);
 6790        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6791            s.move_heads_with(|map, head, goal| {
 6792                movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6793            })
 6794        })
 6795    }
 6796
 6797    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 6798        let text_layout_details = &self.text_layout_details(cx);
 6799        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6800            s.move_heads_with(|map, head, goal| {
 6801                movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6802            })
 6803        })
 6804    }
 6805
 6806    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 6807        let Some(row_count) = self.visible_row_count() else {
 6808            return;
 6809        };
 6810
 6811        let text_layout_details = &self.text_layout_details(cx);
 6812
 6813        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6814            s.move_heads_with(|map, head, goal| {
 6815                movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
 6816            })
 6817        })
 6818    }
 6819
 6820    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 6821        if self.take_rename(true, cx).is_some() {
 6822            return;
 6823        }
 6824
 6825        if self
 6826            .context_menu
 6827            .write()
 6828            .as_mut()
 6829            .map(|menu| menu.select_first(self.project.as_ref(), cx))
 6830            .unwrap_or(false)
 6831        {
 6832            return;
 6833        }
 6834
 6835        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6836            cx.propagate();
 6837            return;
 6838        }
 6839
 6840        let Some(row_count) = self.visible_row_count() else {
 6841            return;
 6842        };
 6843
 6844        let autoscroll = if action.center_cursor {
 6845            Autoscroll::center()
 6846        } else {
 6847            Autoscroll::fit()
 6848        };
 6849
 6850        let text_layout_details = &self.text_layout_details(cx);
 6851
 6852        self.change_selections(Some(autoscroll), cx, |s| {
 6853            let line_mode = s.line_mode;
 6854            s.move_with(|map, selection| {
 6855                if !selection.is_empty() && !line_mode {
 6856                    selection.goal = SelectionGoal::None;
 6857                }
 6858                let (cursor, goal) = movement::up_by_rows(
 6859                    map,
 6860                    selection.end,
 6861                    row_count,
 6862                    selection.goal,
 6863                    false,
 6864                    &text_layout_details,
 6865                );
 6866                selection.collapse_to(cursor, goal);
 6867            });
 6868        });
 6869    }
 6870
 6871    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 6872        let text_layout_details = &self.text_layout_details(cx);
 6873        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6874            s.move_heads_with(|map, head, goal| {
 6875                movement::up(map, head, goal, false, &text_layout_details)
 6876            })
 6877        })
 6878    }
 6879
 6880    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 6881        self.take_rename(true, cx);
 6882
 6883        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6884            cx.propagate();
 6885            return;
 6886        }
 6887
 6888        let text_layout_details = &self.text_layout_details(cx);
 6889        let selection_count = self.selections.count();
 6890        let first_selection = self.selections.first_anchor();
 6891
 6892        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6893            let line_mode = s.line_mode;
 6894            s.move_with(|map, selection| {
 6895                if !selection.is_empty() && !line_mode {
 6896                    selection.goal = SelectionGoal::None;
 6897                }
 6898                let (cursor, goal) = movement::down(
 6899                    map,
 6900                    selection.end,
 6901                    selection.goal,
 6902                    false,
 6903                    &text_layout_details,
 6904                );
 6905                selection.collapse_to(cursor, goal);
 6906            });
 6907        });
 6908
 6909        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6910        {
 6911            cx.propagate();
 6912        }
 6913    }
 6914
 6915    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 6916        let Some(row_count) = self.visible_row_count() else {
 6917            return;
 6918        };
 6919
 6920        let text_layout_details = &self.text_layout_details(cx);
 6921
 6922        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6923            s.move_heads_with(|map, head, goal| {
 6924                movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
 6925            })
 6926        })
 6927    }
 6928
 6929    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 6930        if self.take_rename(true, cx).is_some() {
 6931            return;
 6932        }
 6933
 6934        if self
 6935            .context_menu
 6936            .write()
 6937            .as_mut()
 6938            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 6939            .unwrap_or(false)
 6940        {
 6941            return;
 6942        }
 6943
 6944        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6945            cx.propagate();
 6946            return;
 6947        }
 6948
 6949        let Some(row_count) = self.visible_row_count() else {
 6950            return;
 6951        };
 6952
 6953        let autoscroll = if action.center_cursor {
 6954            Autoscroll::center()
 6955        } else {
 6956            Autoscroll::fit()
 6957        };
 6958
 6959        let text_layout_details = &self.text_layout_details(cx);
 6960        self.change_selections(Some(autoscroll), cx, |s| {
 6961            let line_mode = s.line_mode;
 6962            s.move_with(|map, selection| {
 6963                if !selection.is_empty() && !line_mode {
 6964                    selection.goal = SelectionGoal::None;
 6965                }
 6966                let (cursor, goal) = movement::down_by_rows(
 6967                    map,
 6968                    selection.end,
 6969                    row_count,
 6970                    selection.goal,
 6971                    false,
 6972                    &text_layout_details,
 6973                );
 6974                selection.collapse_to(cursor, goal);
 6975            });
 6976        });
 6977    }
 6978
 6979    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 6980        let text_layout_details = &self.text_layout_details(cx);
 6981        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6982            s.move_heads_with(|map, head, goal| {
 6983                movement::down(map, head, goal, false, &text_layout_details)
 6984            })
 6985        });
 6986    }
 6987
 6988    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 6989        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6990            context_menu.select_first(self.project.as_ref(), cx);
 6991        }
 6992    }
 6993
 6994    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 6995        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6996            context_menu.select_prev(self.project.as_ref(), cx);
 6997        }
 6998    }
 6999
 7000    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7001        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7002            context_menu.select_next(self.project.as_ref(), cx);
 7003        }
 7004    }
 7005
 7006    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7007        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7008            context_menu.select_last(self.project.as_ref(), cx);
 7009        }
 7010    }
 7011
 7012    pub fn move_to_previous_word_start(
 7013        &mut self,
 7014        _: &MoveToPreviousWordStart,
 7015        cx: &mut ViewContext<Self>,
 7016    ) {
 7017        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7018            s.move_cursors_with(|map, head, _| {
 7019                (
 7020                    movement::previous_word_start(map, head),
 7021                    SelectionGoal::None,
 7022                )
 7023            });
 7024        })
 7025    }
 7026
 7027    pub fn move_to_previous_subword_start(
 7028        &mut self,
 7029        _: &MoveToPreviousSubwordStart,
 7030        cx: &mut ViewContext<Self>,
 7031    ) {
 7032        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7033            s.move_cursors_with(|map, head, _| {
 7034                (
 7035                    movement::previous_subword_start(map, head),
 7036                    SelectionGoal::None,
 7037                )
 7038            });
 7039        })
 7040    }
 7041
 7042    pub fn select_to_previous_word_start(
 7043        &mut self,
 7044        _: &SelectToPreviousWordStart,
 7045        cx: &mut ViewContext<Self>,
 7046    ) {
 7047        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7048            s.move_heads_with(|map, head, _| {
 7049                (
 7050                    movement::previous_word_start(map, head),
 7051                    SelectionGoal::None,
 7052                )
 7053            });
 7054        })
 7055    }
 7056
 7057    pub fn select_to_previous_subword_start(
 7058        &mut self,
 7059        _: &SelectToPreviousSubwordStart,
 7060        cx: &mut ViewContext<Self>,
 7061    ) {
 7062        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7063            s.move_heads_with(|map, head, _| {
 7064                (
 7065                    movement::previous_subword_start(map, head),
 7066                    SelectionGoal::None,
 7067                )
 7068            });
 7069        })
 7070    }
 7071
 7072    pub fn delete_to_previous_word_start(
 7073        &mut self,
 7074        _: &DeleteToPreviousWordStart,
 7075        cx: &mut ViewContext<Self>,
 7076    ) {
 7077        self.transact(cx, |this, cx| {
 7078            this.select_autoclose_pair(cx);
 7079            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7080                let line_mode = s.line_mode;
 7081                s.move_with(|map, selection| {
 7082                    if selection.is_empty() && !line_mode {
 7083                        let cursor = movement::previous_word_start(map, selection.head());
 7084                        selection.set_head(cursor, SelectionGoal::None);
 7085                    }
 7086                });
 7087            });
 7088            this.insert("", cx);
 7089        });
 7090    }
 7091
 7092    pub fn delete_to_previous_subword_start(
 7093        &mut self,
 7094        _: &DeleteToPreviousSubwordStart,
 7095        cx: &mut ViewContext<Self>,
 7096    ) {
 7097        self.transact(cx, |this, cx| {
 7098            this.select_autoclose_pair(cx);
 7099            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7100                let line_mode = s.line_mode;
 7101                s.move_with(|map, selection| {
 7102                    if selection.is_empty() && !line_mode {
 7103                        let cursor = movement::previous_subword_start(map, selection.head());
 7104                        selection.set_head(cursor, SelectionGoal::None);
 7105                    }
 7106                });
 7107            });
 7108            this.insert("", cx);
 7109        });
 7110    }
 7111
 7112    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7113        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7114            s.move_cursors_with(|map, head, _| {
 7115                (movement::next_word_end(map, head), SelectionGoal::None)
 7116            });
 7117        })
 7118    }
 7119
 7120    pub fn move_to_next_subword_end(
 7121        &mut self,
 7122        _: &MoveToNextSubwordEnd,
 7123        cx: &mut ViewContext<Self>,
 7124    ) {
 7125        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7126            s.move_cursors_with(|map, head, _| {
 7127                (movement::next_subword_end(map, head), SelectionGoal::None)
 7128            });
 7129        })
 7130    }
 7131
 7132    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7133        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7134            s.move_heads_with(|map, head, _| {
 7135                (movement::next_word_end(map, head), SelectionGoal::None)
 7136            });
 7137        })
 7138    }
 7139
 7140    pub fn select_to_next_subword_end(
 7141        &mut self,
 7142        _: &SelectToNextSubwordEnd,
 7143        cx: &mut ViewContext<Self>,
 7144    ) {
 7145        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7146            s.move_heads_with(|map, head, _| {
 7147                (movement::next_subword_end(map, head), SelectionGoal::None)
 7148            });
 7149        })
 7150    }
 7151
 7152    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
 7153        self.transact(cx, |this, cx| {
 7154            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7155                let line_mode = s.line_mode;
 7156                s.move_with(|map, selection| {
 7157                    if selection.is_empty() && !line_mode {
 7158                        let cursor = movement::next_word_end(map, selection.head());
 7159                        selection.set_head(cursor, SelectionGoal::None);
 7160                    }
 7161                });
 7162            });
 7163            this.insert("", cx);
 7164        });
 7165    }
 7166
 7167    pub fn delete_to_next_subword_end(
 7168        &mut self,
 7169        _: &DeleteToNextSubwordEnd,
 7170        cx: &mut ViewContext<Self>,
 7171    ) {
 7172        self.transact(cx, |this, cx| {
 7173            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7174                s.move_with(|map, selection| {
 7175                    if selection.is_empty() {
 7176                        let cursor = movement::next_subword_end(map, selection.head());
 7177                        selection.set_head(cursor, SelectionGoal::None);
 7178                    }
 7179                });
 7180            });
 7181            this.insert("", cx);
 7182        });
 7183    }
 7184
 7185    pub fn move_to_beginning_of_line(
 7186        &mut self,
 7187        action: &MoveToBeginningOfLine,
 7188        cx: &mut ViewContext<Self>,
 7189    ) {
 7190        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7191            s.move_cursors_with(|map, head, _| {
 7192                (
 7193                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7194                    SelectionGoal::None,
 7195                )
 7196            });
 7197        })
 7198    }
 7199
 7200    pub fn select_to_beginning_of_line(
 7201        &mut self,
 7202        action: &SelectToBeginningOfLine,
 7203        cx: &mut ViewContext<Self>,
 7204    ) {
 7205        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7206            s.move_heads_with(|map, head, _| {
 7207                (
 7208                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7209                    SelectionGoal::None,
 7210                )
 7211            });
 7212        });
 7213    }
 7214
 7215    pub fn delete_to_beginning_of_line(
 7216        &mut self,
 7217        _: &DeleteToBeginningOfLine,
 7218        cx: &mut ViewContext<Self>,
 7219    ) {
 7220        self.transact(cx, |this, cx| {
 7221            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7222                s.move_with(|_, selection| {
 7223                    selection.reversed = true;
 7224                });
 7225            });
 7226
 7227            this.select_to_beginning_of_line(
 7228                &SelectToBeginningOfLine {
 7229                    stop_at_soft_wraps: false,
 7230                },
 7231                cx,
 7232            );
 7233            this.backspace(&Backspace, cx);
 7234        });
 7235    }
 7236
 7237    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7238        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7239            s.move_cursors_with(|map, head, _| {
 7240                (
 7241                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7242                    SelectionGoal::None,
 7243                )
 7244            });
 7245        })
 7246    }
 7247
 7248    pub fn select_to_end_of_line(
 7249        &mut self,
 7250        action: &SelectToEndOfLine,
 7251        cx: &mut ViewContext<Self>,
 7252    ) {
 7253        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7254            s.move_heads_with(|map, head, _| {
 7255                (
 7256                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7257                    SelectionGoal::None,
 7258                )
 7259            });
 7260        })
 7261    }
 7262
 7263    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7264        self.transact(cx, |this, cx| {
 7265            this.select_to_end_of_line(
 7266                &SelectToEndOfLine {
 7267                    stop_at_soft_wraps: false,
 7268                },
 7269                cx,
 7270            );
 7271            this.delete(&Delete, cx);
 7272        });
 7273    }
 7274
 7275    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7276        self.transact(cx, |this, cx| {
 7277            this.select_to_end_of_line(
 7278                &SelectToEndOfLine {
 7279                    stop_at_soft_wraps: false,
 7280                },
 7281                cx,
 7282            );
 7283            this.cut(&Cut, cx);
 7284        });
 7285    }
 7286
 7287    pub fn move_to_start_of_paragraph(
 7288        &mut self,
 7289        _: &MoveToStartOfParagraph,
 7290        cx: &mut ViewContext<Self>,
 7291    ) {
 7292        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7293            cx.propagate();
 7294            return;
 7295        }
 7296
 7297        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7298            s.move_with(|map, selection| {
 7299                selection.collapse_to(
 7300                    movement::start_of_paragraph(map, selection.head(), 1),
 7301                    SelectionGoal::None,
 7302                )
 7303            });
 7304        })
 7305    }
 7306
 7307    pub fn move_to_end_of_paragraph(
 7308        &mut self,
 7309        _: &MoveToEndOfParagraph,
 7310        cx: &mut ViewContext<Self>,
 7311    ) {
 7312        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7313            cx.propagate();
 7314            return;
 7315        }
 7316
 7317        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7318            s.move_with(|map, selection| {
 7319                selection.collapse_to(
 7320                    movement::end_of_paragraph(map, selection.head(), 1),
 7321                    SelectionGoal::None,
 7322                )
 7323            });
 7324        })
 7325    }
 7326
 7327    pub fn select_to_start_of_paragraph(
 7328        &mut self,
 7329        _: &SelectToStartOfParagraph,
 7330        cx: &mut ViewContext<Self>,
 7331    ) {
 7332        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7333            cx.propagate();
 7334            return;
 7335        }
 7336
 7337        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7338            s.move_heads_with(|map, head, _| {
 7339                (
 7340                    movement::start_of_paragraph(map, head, 1),
 7341                    SelectionGoal::None,
 7342                )
 7343            });
 7344        })
 7345    }
 7346
 7347    pub fn select_to_end_of_paragraph(
 7348        &mut self,
 7349        _: &SelectToEndOfParagraph,
 7350        cx: &mut ViewContext<Self>,
 7351    ) {
 7352        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7353            cx.propagate();
 7354            return;
 7355        }
 7356
 7357        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7358            s.move_heads_with(|map, head, _| {
 7359                (
 7360                    movement::end_of_paragraph(map, head, 1),
 7361                    SelectionGoal::None,
 7362                )
 7363            });
 7364        })
 7365    }
 7366
 7367    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7368        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7369            cx.propagate();
 7370            return;
 7371        }
 7372
 7373        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7374            s.select_ranges(vec![0..0]);
 7375        });
 7376    }
 7377
 7378    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7379        let mut selection = self.selections.last::<Point>(cx);
 7380        selection.set_head(Point::zero(), SelectionGoal::None);
 7381
 7382        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7383            s.select(vec![selection]);
 7384        });
 7385    }
 7386
 7387    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7388        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7389            cx.propagate();
 7390            return;
 7391        }
 7392
 7393        let cursor = self.buffer.read(cx).read(cx).len();
 7394        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7395            s.select_ranges(vec![cursor..cursor])
 7396        });
 7397    }
 7398
 7399    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7400        self.nav_history = nav_history;
 7401    }
 7402
 7403    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7404        self.nav_history.as_ref()
 7405    }
 7406
 7407    fn push_to_nav_history(
 7408        &mut self,
 7409        cursor_anchor: Anchor,
 7410        new_position: Option<Point>,
 7411        cx: &mut ViewContext<Self>,
 7412    ) {
 7413        if let Some(nav_history) = self.nav_history.as_mut() {
 7414            let buffer = self.buffer.read(cx).read(cx);
 7415            let cursor_position = cursor_anchor.to_point(&buffer);
 7416            let scroll_state = self.scroll_manager.anchor();
 7417            let scroll_top_row = scroll_state.top_row(&buffer);
 7418            drop(buffer);
 7419
 7420            if let Some(new_position) = new_position {
 7421                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7422                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7423                    return;
 7424                }
 7425            }
 7426
 7427            nav_history.push(
 7428                Some(NavigationData {
 7429                    cursor_anchor,
 7430                    cursor_position,
 7431                    scroll_anchor: scroll_state,
 7432                    scroll_top_row,
 7433                }),
 7434                cx,
 7435            );
 7436        }
 7437    }
 7438
 7439    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7440        let buffer = self.buffer.read(cx).snapshot(cx);
 7441        let mut selection = self.selections.first::<usize>(cx);
 7442        selection.set_head(buffer.len(), SelectionGoal::None);
 7443        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7444            s.select(vec![selection]);
 7445        });
 7446    }
 7447
 7448    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7449        let end = self.buffer.read(cx).read(cx).len();
 7450        self.change_selections(None, cx, |s| {
 7451            s.select_ranges(vec![0..end]);
 7452        });
 7453    }
 7454
 7455    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7456        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7457        let mut selections = self.selections.all::<Point>(cx);
 7458        let max_point = display_map.buffer_snapshot.max_point();
 7459        for selection in &mut selections {
 7460            let rows = selection.spanned_rows(true, &display_map);
 7461            selection.start = Point::new(rows.start.0, 0);
 7462            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7463            selection.reversed = false;
 7464        }
 7465        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7466            s.select(selections);
 7467        });
 7468    }
 7469
 7470    pub fn split_selection_into_lines(
 7471        &mut self,
 7472        _: &SplitSelectionIntoLines,
 7473        cx: &mut ViewContext<Self>,
 7474    ) {
 7475        let mut to_unfold = Vec::new();
 7476        let mut new_selection_ranges = Vec::new();
 7477        {
 7478            let selections = self.selections.all::<Point>(cx);
 7479            let buffer = self.buffer.read(cx).read(cx);
 7480            for selection in selections {
 7481                for row in selection.start.row..selection.end.row {
 7482                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7483                    new_selection_ranges.push(cursor..cursor);
 7484                }
 7485                new_selection_ranges.push(selection.end..selection.end);
 7486                to_unfold.push(selection.start..selection.end);
 7487            }
 7488        }
 7489        self.unfold_ranges(to_unfold, true, true, cx);
 7490        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7491            s.select_ranges(new_selection_ranges);
 7492        });
 7493    }
 7494
 7495    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7496        self.add_selection(true, cx);
 7497    }
 7498
 7499    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7500        self.add_selection(false, cx);
 7501    }
 7502
 7503    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7504        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7505        let mut selections = self.selections.all::<Point>(cx);
 7506        let text_layout_details = self.text_layout_details(cx);
 7507        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7508            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7509            let range = oldest_selection.display_range(&display_map).sorted();
 7510
 7511            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7512            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7513            let positions = start_x.min(end_x)..start_x.max(end_x);
 7514
 7515            selections.clear();
 7516            let mut stack = Vec::new();
 7517            for row in range.start.row().0..=range.end.row().0 {
 7518                if let Some(selection) = self.selections.build_columnar_selection(
 7519                    &display_map,
 7520                    DisplayRow(row),
 7521                    &positions,
 7522                    oldest_selection.reversed,
 7523                    &text_layout_details,
 7524                ) {
 7525                    stack.push(selection.id);
 7526                    selections.push(selection);
 7527                }
 7528            }
 7529
 7530            if above {
 7531                stack.reverse();
 7532            }
 7533
 7534            AddSelectionsState { above, stack }
 7535        });
 7536
 7537        let last_added_selection = *state.stack.last().unwrap();
 7538        let mut new_selections = Vec::new();
 7539        if above == state.above {
 7540            let end_row = if above {
 7541                DisplayRow(0)
 7542            } else {
 7543                display_map.max_point().row()
 7544            };
 7545
 7546            'outer: for selection in selections {
 7547                if selection.id == last_added_selection {
 7548                    let range = selection.display_range(&display_map).sorted();
 7549                    debug_assert_eq!(range.start.row(), range.end.row());
 7550                    let mut row = range.start.row();
 7551                    let positions =
 7552                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7553                            px(start)..px(end)
 7554                        } else {
 7555                            let start_x =
 7556                                display_map.x_for_display_point(range.start, &text_layout_details);
 7557                            let end_x =
 7558                                display_map.x_for_display_point(range.end, &text_layout_details);
 7559                            start_x.min(end_x)..start_x.max(end_x)
 7560                        };
 7561
 7562                    while row != end_row {
 7563                        if above {
 7564                            row.0 -= 1;
 7565                        } else {
 7566                            row.0 += 1;
 7567                        }
 7568
 7569                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7570                            &display_map,
 7571                            row,
 7572                            &positions,
 7573                            selection.reversed,
 7574                            &text_layout_details,
 7575                        ) {
 7576                            state.stack.push(new_selection.id);
 7577                            if above {
 7578                                new_selections.push(new_selection);
 7579                                new_selections.push(selection);
 7580                            } else {
 7581                                new_selections.push(selection);
 7582                                new_selections.push(new_selection);
 7583                            }
 7584
 7585                            continue 'outer;
 7586                        }
 7587                    }
 7588                }
 7589
 7590                new_selections.push(selection);
 7591            }
 7592        } else {
 7593            new_selections = selections;
 7594            new_selections.retain(|s| s.id != last_added_selection);
 7595            state.stack.pop();
 7596        }
 7597
 7598        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7599            s.select(new_selections);
 7600        });
 7601        if state.stack.len() > 1 {
 7602            self.add_selections_state = Some(state);
 7603        }
 7604    }
 7605
 7606    pub fn select_next_match_internal(
 7607        &mut self,
 7608        display_map: &DisplaySnapshot,
 7609        replace_newest: bool,
 7610        autoscroll: Option<Autoscroll>,
 7611        cx: &mut ViewContext<Self>,
 7612    ) -> Result<()> {
 7613        fn select_next_match_ranges(
 7614            this: &mut Editor,
 7615            range: Range<usize>,
 7616            replace_newest: bool,
 7617            auto_scroll: Option<Autoscroll>,
 7618            cx: &mut ViewContext<Editor>,
 7619        ) {
 7620            this.unfold_ranges([range.clone()], false, true, cx);
 7621            this.change_selections(auto_scroll, cx, |s| {
 7622                if replace_newest {
 7623                    s.delete(s.newest_anchor().id);
 7624                }
 7625                s.insert_range(range.clone());
 7626            });
 7627        }
 7628
 7629        let buffer = &display_map.buffer_snapshot;
 7630        let mut selections = self.selections.all::<usize>(cx);
 7631        if let Some(mut select_next_state) = self.select_next_state.take() {
 7632            let query = &select_next_state.query;
 7633            if !select_next_state.done {
 7634                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7635                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7636                let mut next_selected_range = None;
 7637
 7638                let bytes_after_last_selection =
 7639                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7640                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7641                let query_matches = query
 7642                    .stream_find_iter(bytes_after_last_selection)
 7643                    .map(|result| (last_selection.end, result))
 7644                    .chain(
 7645                        query
 7646                            .stream_find_iter(bytes_before_first_selection)
 7647                            .map(|result| (0, result)),
 7648                    );
 7649
 7650                for (start_offset, query_match) in query_matches {
 7651                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7652                    let offset_range =
 7653                        start_offset + query_match.start()..start_offset + query_match.end();
 7654                    let display_range = offset_range.start.to_display_point(&display_map)
 7655                        ..offset_range.end.to_display_point(&display_map);
 7656
 7657                    if !select_next_state.wordwise
 7658                        || (!movement::is_inside_word(&display_map, display_range.start)
 7659                            && !movement::is_inside_word(&display_map, display_range.end))
 7660                    {
 7661                        // TODO: This is n^2, because we might check all the selections
 7662                        if !selections
 7663                            .iter()
 7664                            .any(|selection| selection.range().overlaps(&offset_range))
 7665                        {
 7666                            next_selected_range = Some(offset_range);
 7667                            break;
 7668                        }
 7669                    }
 7670                }
 7671
 7672                if let Some(next_selected_range) = next_selected_range {
 7673                    select_next_match_ranges(
 7674                        self,
 7675                        next_selected_range,
 7676                        replace_newest,
 7677                        autoscroll,
 7678                        cx,
 7679                    );
 7680                } else {
 7681                    select_next_state.done = true;
 7682                }
 7683            }
 7684
 7685            self.select_next_state = Some(select_next_state);
 7686        } else {
 7687            let mut only_carets = true;
 7688            let mut same_text_selected = true;
 7689            let mut selected_text = None;
 7690
 7691            let mut selections_iter = selections.iter().peekable();
 7692            while let Some(selection) = selections_iter.next() {
 7693                if selection.start != selection.end {
 7694                    only_carets = false;
 7695                }
 7696
 7697                if same_text_selected {
 7698                    if selected_text.is_none() {
 7699                        selected_text =
 7700                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7701                    }
 7702
 7703                    if let Some(next_selection) = selections_iter.peek() {
 7704                        if next_selection.range().len() == selection.range().len() {
 7705                            let next_selected_text = buffer
 7706                                .text_for_range(next_selection.range())
 7707                                .collect::<String>();
 7708                            if Some(next_selected_text) != selected_text {
 7709                                same_text_selected = false;
 7710                                selected_text = None;
 7711                            }
 7712                        } else {
 7713                            same_text_selected = false;
 7714                            selected_text = None;
 7715                        }
 7716                    }
 7717                }
 7718            }
 7719
 7720            if only_carets {
 7721                for selection in &mut selections {
 7722                    let word_range = movement::surrounding_word(
 7723                        &display_map,
 7724                        selection.start.to_display_point(&display_map),
 7725                    );
 7726                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7727                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7728                    selection.goal = SelectionGoal::None;
 7729                    selection.reversed = false;
 7730                    select_next_match_ranges(
 7731                        self,
 7732                        selection.start..selection.end,
 7733                        replace_newest,
 7734                        autoscroll,
 7735                        cx,
 7736                    );
 7737                }
 7738
 7739                if selections.len() == 1 {
 7740                    let selection = selections
 7741                        .last()
 7742                        .expect("ensured that there's only one selection");
 7743                    let query = buffer
 7744                        .text_for_range(selection.start..selection.end)
 7745                        .collect::<String>();
 7746                    let is_empty = query.is_empty();
 7747                    let select_state = SelectNextState {
 7748                        query: AhoCorasick::new(&[query])?,
 7749                        wordwise: true,
 7750                        done: is_empty,
 7751                    };
 7752                    self.select_next_state = Some(select_state);
 7753                } else {
 7754                    self.select_next_state = None;
 7755                }
 7756            } else if let Some(selected_text) = selected_text {
 7757                self.select_next_state = Some(SelectNextState {
 7758                    query: AhoCorasick::new(&[selected_text])?,
 7759                    wordwise: false,
 7760                    done: false,
 7761                });
 7762                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 7763            }
 7764        }
 7765        Ok(())
 7766    }
 7767
 7768    pub fn select_all_matches(
 7769        &mut self,
 7770        _action: &SelectAllMatches,
 7771        cx: &mut ViewContext<Self>,
 7772    ) -> Result<()> {
 7773        self.push_to_selection_history();
 7774        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7775
 7776        self.select_next_match_internal(&display_map, false, None, cx)?;
 7777        let Some(select_next_state) = self.select_next_state.as_mut() else {
 7778            return Ok(());
 7779        };
 7780        if select_next_state.done {
 7781            return Ok(());
 7782        }
 7783
 7784        let mut new_selections = self.selections.all::<usize>(cx);
 7785
 7786        let buffer = &display_map.buffer_snapshot;
 7787        let query_matches = select_next_state
 7788            .query
 7789            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 7790
 7791        for query_match in query_matches {
 7792            let query_match = query_match.unwrap(); // can only fail due to I/O
 7793            let offset_range = query_match.start()..query_match.end();
 7794            let display_range = offset_range.start.to_display_point(&display_map)
 7795                ..offset_range.end.to_display_point(&display_map);
 7796
 7797            if !select_next_state.wordwise
 7798                || (!movement::is_inside_word(&display_map, display_range.start)
 7799                    && !movement::is_inside_word(&display_map, display_range.end))
 7800            {
 7801                self.selections.change_with(cx, |selections| {
 7802                    new_selections.push(Selection {
 7803                        id: selections.new_selection_id(),
 7804                        start: offset_range.start,
 7805                        end: offset_range.end,
 7806                        reversed: false,
 7807                        goal: SelectionGoal::None,
 7808                    });
 7809                });
 7810            }
 7811        }
 7812
 7813        new_selections.sort_by_key(|selection| selection.start);
 7814        let mut ix = 0;
 7815        while ix + 1 < new_selections.len() {
 7816            let current_selection = &new_selections[ix];
 7817            let next_selection = &new_selections[ix + 1];
 7818            if current_selection.range().overlaps(&next_selection.range()) {
 7819                if current_selection.id < next_selection.id {
 7820                    new_selections.remove(ix + 1);
 7821                } else {
 7822                    new_selections.remove(ix);
 7823                }
 7824            } else {
 7825                ix += 1;
 7826            }
 7827        }
 7828
 7829        select_next_state.done = true;
 7830        self.unfold_ranges(
 7831            new_selections.iter().map(|selection| selection.range()),
 7832            false,
 7833            false,
 7834            cx,
 7835        );
 7836        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 7837            selections.select(new_selections)
 7838        });
 7839
 7840        Ok(())
 7841    }
 7842
 7843    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 7844        self.push_to_selection_history();
 7845        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7846        self.select_next_match_internal(
 7847            &display_map,
 7848            action.replace_newest,
 7849            Some(Autoscroll::newest()),
 7850            cx,
 7851        )?;
 7852        Ok(())
 7853    }
 7854
 7855    pub fn select_previous(
 7856        &mut self,
 7857        action: &SelectPrevious,
 7858        cx: &mut ViewContext<Self>,
 7859    ) -> Result<()> {
 7860        self.push_to_selection_history();
 7861        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7862        let buffer = &display_map.buffer_snapshot;
 7863        let mut selections = self.selections.all::<usize>(cx);
 7864        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 7865            let query = &select_prev_state.query;
 7866            if !select_prev_state.done {
 7867                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7868                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7869                let mut next_selected_range = None;
 7870                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 7871                let bytes_before_last_selection =
 7872                    buffer.reversed_bytes_in_range(0..last_selection.start);
 7873                let bytes_after_first_selection =
 7874                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 7875                let query_matches = query
 7876                    .stream_find_iter(bytes_before_last_selection)
 7877                    .map(|result| (last_selection.start, result))
 7878                    .chain(
 7879                        query
 7880                            .stream_find_iter(bytes_after_first_selection)
 7881                            .map(|result| (buffer.len(), result)),
 7882                    );
 7883                for (end_offset, query_match) in query_matches {
 7884                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7885                    let offset_range =
 7886                        end_offset - query_match.end()..end_offset - query_match.start();
 7887                    let display_range = offset_range.start.to_display_point(&display_map)
 7888                        ..offset_range.end.to_display_point(&display_map);
 7889
 7890                    if !select_prev_state.wordwise
 7891                        || (!movement::is_inside_word(&display_map, display_range.start)
 7892                            && !movement::is_inside_word(&display_map, display_range.end))
 7893                    {
 7894                        next_selected_range = Some(offset_range);
 7895                        break;
 7896                    }
 7897                }
 7898
 7899                if let Some(next_selected_range) = next_selected_range {
 7900                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 7901                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7902                        if action.replace_newest {
 7903                            s.delete(s.newest_anchor().id);
 7904                        }
 7905                        s.insert_range(next_selected_range);
 7906                    });
 7907                } else {
 7908                    select_prev_state.done = true;
 7909                }
 7910            }
 7911
 7912            self.select_prev_state = Some(select_prev_state);
 7913        } else {
 7914            let mut only_carets = true;
 7915            let mut same_text_selected = true;
 7916            let mut selected_text = None;
 7917
 7918            let mut selections_iter = selections.iter().peekable();
 7919            while let Some(selection) = selections_iter.next() {
 7920                if selection.start != selection.end {
 7921                    only_carets = false;
 7922                }
 7923
 7924                if same_text_selected {
 7925                    if selected_text.is_none() {
 7926                        selected_text =
 7927                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7928                    }
 7929
 7930                    if let Some(next_selection) = selections_iter.peek() {
 7931                        if next_selection.range().len() == selection.range().len() {
 7932                            let next_selected_text = buffer
 7933                                .text_for_range(next_selection.range())
 7934                                .collect::<String>();
 7935                            if Some(next_selected_text) != selected_text {
 7936                                same_text_selected = false;
 7937                                selected_text = None;
 7938                            }
 7939                        } else {
 7940                            same_text_selected = false;
 7941                            selected_text = None;
 7942                        }
 7943                    }
 7944                }
 7945            }
 7946
 7947            if only_carets {
 7948                for selection in &mut selections {
 7949                    let word_range = movement::surrounding_word(
 7950                        &display_map,
 7951                        selection.start.to_display_point(&display_map),
 7952                    );
 7953                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7954                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7955                    selection.goal = SelectionGoal::None;
 7956                    selection.reversed = false;
 7957                }
 7958                if selections.len() == 1 {
 7959                    let selection = selections
 7960                        .last()
 7961                        .expect("ensured that there's only one selection");
 7962                    let query = buffer
 7963                        .text_for_range(selection.start..selection.end)
 7964                        .collect::<String>();
 7965                    let is_empty = query.is_empty();
 7966                    let select_state = SelectNextState {
 7967                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 7968                        wordwise: true,
 7969                        done: is_empty,
 7970                    };
 7971                    self.select_prev_state = Some(select_state);
 7972                } else {
 7973                    self.select_prev_state = None;
 7974                }
 7975
 7976                self.unfold_ranges(
 7977                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 7978                    false,
 7979                    true,
 7980                    cx,
 7981                );
 7982                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7983                    s.select(selections);
 7984                });
 7985            } else if let Some(selected_text) = selected_text {
 7986                self.select_prev_state = Some(SelectNextState {
 7987                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 7988                    wordwise: false,
 7989                    done: false,
 7990                });
 7991                self.select_previous(action, cx)?;
 7992            }
 7993        }
 7994        Ok(())
 7995    }
 7996
 7997    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 7998        let text_layout_details = &self.text_layout_details(cx);
 7999        self.transact(cx, |this, cx| {
 8000            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8001            let mut edits = Vec::new();
 8002            let mut selection_edit_ranges = Vec::new();
 8003            let mut last_toggled_row = None;
 8004            let snapshot = this.buffer.read(cx).read(cx);
 8005            let empty_str: Arc<str> = "".into();
 8006            let mut suffixes_inserted = Vec::new();
 8007
 8008            fn comment_prefix_range(
 8009                snapshot: &MultiBufferSnapshot,
 8010                row: MultiBufferRow,
 8011                comment_prefix: &str,
 8012                comment_prefix_whitespace: &str,
 8013            ) -> Range<Point> {
 8014                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8015
 8016                let mut line_bytes = snapshot
 8017                    .bytes_in_range(start..snapshot.max_point())
 8018                    .flatten()
 8019                    .copied();
 8020
 8021                // If this line currently begins with the line comment prefix, then record
 8022                // the range containing the prefix.
 8023                if line_bytes
 8024                    .by_ref()
 8025                    .take(comment_prefix.len())
 8026                    .eq(comment_prefix.bytes())
 8027                {
 8028                    // Include any whitespace that matches the comment prefix.
 8029                    let matching_whitespace_len = line_bytes
 8030                        .zip(comment_prefix_whitespace.bytes())
 8031                        .take_while(|(a, b)| a == b)
 8032                        .count() as u32;
 8033                    let end = Point::new(
 8034                        start.row,
 8035                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8036                    );
 8037                    start..end
 8038                } else {
 8039                    start..start
 8040                }
 8041            }
 8042
 8043            fn comment_suffix_range(
 8044                snapshot: &MultiBufferSnapshot,
 8045                row: MultiBufferRow,
 8046                comment_suffix: &str,
 8047                comment_suffix_has_leading_space: bool,
 8048            ) -> Range<Point> {
 8049                let end = Point::new(row.0, snapshot.line_len(row));
 8050                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8051
 8052                let mut line_end_bytes = snapshot
 8053                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8054                    .flatten()
 8055                    .copied();
 8056
 8057                let leading_space_len = if suffix_start_column > 0
 8058                    && line_end_bytes.next() == Some(b' ')
 8059                    && comment_suffix_has_leading_space
 8060                {
 8061                    1
 8062                } else {
 8063                    0
 8064                };
 8065
 8066                // If this line currently begins with the line comment prefix, then record
 8067                // the range containing the prefix.
 8068                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8069                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8070                    start..end
 8071                } else {
 8072                    end..end
 8073                }
 8074            }
 8075
 8076            // TODO: Handle selections that cross excerpts
 8077            for selection in &mut selections {
 8078                let start_column = snapshot
 8079                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8080                    .len;
 8081                let language = if let Some(language) =
 8082                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8083                {
 8084                    language
 8085                } else {
 8086                    continue;
 8087                };
 8088
 8089                selection_edit_ranges.clear();
 8090
 8091                // If multiple selections contain a given row, avoid processing that
 8092                // row more than once.
 8093                let mut start_row = MultiBufferRow(selection.start.row);
 8094                if last_toggled_row == Some(start_row) {
 8095                    start_row = start_row.next_row();
 8096                }
 8097                let end_row =
 8098                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8099                        MultiBufferRow(selection.end.row - 1)
 8100                    } else {
 8101                        MultiBufferRow(selection.end.row)
 8102                    };
 8103                last_toggled_row = Some(end_row);
 8104
 8105                if start_row > end_row {
 8106                    continue;
 8107                }
 8108
 8109                // If the language has line comments, toggle those.
 8110                let full_comment_prefixes = language.line_comment_prefixes();
 8111                if !full_comment_prefixes.is_empty() {
 8112                    let first_prefix = full_comment_prefixes
 8113                        .first()
 8114                        .expect("prefixes is non-empty");
 8115                    let prefix_trimmed_lengths = full_comment_prefixes
 8116                        .iter()
 8117                        .map(|p| p.trim_end_matches(' ').len())
 8118                        .collect::<SmallVec<[usize; 4]>>();
 8119
 8120                    let mut all_selection_lines_are_comments = true;
 8121
 8122                    for row in start_row.0..=end_row.0 {
 8123                        let row = MultiBufferRow(row);
 8124                        if start_row < end_row && snapshot.is_line_blank(row) {
 8125                            continue;
 8126                        }
 8127
 8128                        let prefix_range = full_comment_prefixes
 8129                            .iter()
 8130                            .zip(prefix_trimmed_lengths.iter().copied())
 8131                            .map(|(prefix, trimmed_prefix_len)| {
 8132                                comment_prefix_range(
 8133                                    snapshot.deref(),
 8134                                    row,
 8135                                    &prefix[..trimmed_prefix_len],
 8136                                    &prefix[trimmed_prefix_len..],
 8137                                )
 8138                            })
 8139                            .max_by_key(|range| range.end.column - range.start.column)
 8140                            .expect("prefixes is non-empty");
 8141
 8142                        if prefix_range.is_empty() {
 8143                            all_selection_lines_are_comments = false;
 8144                        }
 8145
 8146                        selection_edit_ranges.push(prefix_range);
 8147                    }
 8148
 8149                    if all_selection_lines_are_comments {
 8150                        edits.extend(
 8151                            selection_edit_ranges
 8152                                .iter()
 8153                                .cloned()
 8154                                .map(|range| (range, empty_str.clone())),
 8155                        );
 8156                    } else {
 8157                        let min_column = selection_edit_ranges
 8158                            .iter()
 8159                            .map(|range| range.start.column)
 8160                            .min()
 8161                            .unwrap_or(0);
 8162                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8163                            let position = Point::new(range.start.row, min_column);
 8164                            (position..position, first_prefix.clone())
 8165                        }));
 8166                    }
 8167                } else if let Some((full_comment_prefix, comment_suffix)) =
 8168                    language.block_comment_delimiters()
 8169                {
 8170                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8171                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8172                    let prefix_range = comment_prefix_range(
 8173                        snapshot.deref(),
 8174                        start_row,
 8175                        comment_prefix,
 8176                        comment_prefix_whitespace,
 8177                    );
 8178                    let suffix_range = comment_suffix_range(
 8179                        snapshot.deref(),
 8180                        end_row,
 8181                        comment_suffix.trim_start_matches(' '),
 8182                        comment_suffix.starts_with(' '),
 8183                    );
 8184
 8185                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8186                        edits.push((
 8187                            prefix_range.start..prefix_range.start,
 8188                            full_comment_prefix.clone(),
 8189                        ));
 8190                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8191                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8192                    } else {
 8193                        edits.push((prefix_range, empty_str.clone()));
 8194                        edits.push((suffix_range, empty_str.clone()));
 8195                    }
 8196                } else {
 8197                    continue;
 8198                }
 8199            }
 8200
 8201            drop(snapshot);
 8202            this.buffer.update(cx, |buffer, cx| {
 8203                buffer.edit(edits, None, cx);
 8204            });
 8205
 8206            // Adjust selections so that they end before any comment suffixes that
 8207            // were inserted.
 8208            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8209            let mut selections = this.selections.all::<Point>(cx);
 8210            let snapshot = this.buffer.read(cx).read(cx);
 8211            for selection in &mut selections {
 8212                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8213                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8214                        Ordering::Less => {
 8215                            suffixes_inserted.next();
 8216                            continue;
 8217                        }
 8218                        Ordering::Greater => break,
 8219                        Ordering::Equal => {
 8220                            if selection.end.column == snapshot.line_len(row) {
 8221                                if selection.is_empty() {
 8222                                    selection.start.column -= suffix_len as u32;
 8223                                }
 8224                                selection.end.column -= suffix_len as u32;
 8225                            }
 8226                            break;
 8227                        }
 8228                    }
 8229                }
 8230            }
 8231
 8232            drop(snapshot);
 8233            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8234
 8235            let selections = this.selections.all::<Point>(cx);
 8236            let selections_on_single_row = selections.windows(2).all(|selections| {
 8237                selections[0].start.row == selections[1].start.row
 8238                    && selections[0].end.row == selections[1].end.row
 8239                    && selections[0].start.row == selections[0].end.row
 8240            });
 8241            let selections_selecting = selections
 8242                .iter()
 8243                .any(|selection| selection.start != selection.end);
 8244            let advance_downwards = action.advance_downwards
 8245                && selections_on_single_row
 8246                && !selections_selecting
 8247                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8248
 8249            if advance_downwards {
 8250                let snapshot = this.buffer.read(cx).snapshot(cx);
 8251
 8252                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8253                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8254                        let mut point = display_point.to_point(display_snapshot);
 8255                        point.row += 1;
 8256                        point = snapshot.clip_point(point, Bias::Left);
 8257                        let display_point = point.to_display_point(display_snapshot);
 8258                        let goal = SelectionGoal::HorizontalPosition(
 8259                            display_snapshot
 8260                                .x_for_display_point(display_point, &text_layout_details)
 8261                                .into(),
 8262                        );
 8263                        (display_point, goal)
 8264                    })
 8265                });
 8266            }
 8267        });
 8268    }
 8269
 8270    pub fn select_enclosing_symbol(
 8271        &mut self,
 8272        _: &SelectEnclosingSymbol,
 8273        cx: &mut ViewContext<Self>,
 8274    ) {
 8275        let buffer = self.buffer.read(cx).snapshot(cx);
 8276        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8277
 8278        fn update_selection(
 8279            selection: &Selection<usize>,
 8280            buffer_snap: &MultiBufferSnapshot,
 8281        ) -> Option<Selection<usize>> {
 8282            let cursor = selection.head();
 8283            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8284            for symbol in symbols.iter().rev() {
 8285                let start = symbol.range.start.to_offset(&buffer_snap);
 8286                let end = symbol.range.end.to_offset(&buffer_snap);
 8287                let new_range = start..end;
 8288                if start < selection.start || end > selection.end {
 8289                    return Some(Selection {
 8290                        id: selection.id,
 8291                        start: new_range.start,
 8292                        end: new_range.end,
 8293                        goal: SelectionGoal::None,
 8294                        reversed: selection.reversed,
 8295                    });
 8296                }
 8297            }
 8298            None
 8299        }
 8300
 8301        let mut selected_larger_symbol = false;
 8302        let new_selections = old_selections
 8303            .iter()
 8304            .map(|selection| match update_selection(selection, &buffer) {
 8305                Some(new_selection) => {
 8306                    if new_selection.range() != selection.range() {
 8307                        selected_larger_symbol = true;
 8308                    }
 8309                    new_selection
 8310                }
 8311                None => selection.clone(),
 8312            })
 8313            .collect::<Vec<_>>();
 8314
 8315        if selected_larger_symbol {
 8316            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8317                s.select(new_selections);
 8318            });
 8319        }
 8320    }
 8321
 8322    pub fn select_larger_syntax_node(
 8323        &mut self,
 8324        _: &SelectLargerSyntaxNode,
 8325        cx: &mut ViewContext<Self>,
 8326    ) {
 8327        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8328        let buffer = self.buffer.read(cx).snapshot(cx);
 8329        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8330
 8331        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8332        let mut selected_larger_node = false;
 8333        let new_selections = old_selections
 8334            .iter()
 8335            .map(|selection| {
 8336                let old_range = selection.start..selection.end;
 8337                let mut new_range = old_range.clone();
 8338                while let Some(containing_range) =
 8339                    buffer.range_for_syntax_ancestor(new_range.clone())
 8340                {
 8341                    new_range = containing_range;
 8342                    if !display_map.intersects_fold(new_range.start)
 8343                        && !display_map.intersects_fold(new_range.end)
 8344                    {
 8345                        break;
 8346                    }
 8347                }
 8348
 8349                selected_larger_node |= new_range != old_range;
 8350                Selection {
 8351                    id: selection.id,
 8352                    start: new_range.start,
 8353                    end: new_range.end,
 8354                    goal: SelectionGoal::None,
 8355                    reversed: selection.reversed,
 8356                }
 8357            })
 8358            .collect::<Vec<_>>();
 8359
 8360        if selected_larger_node {
 8361            stack.push(old_selections);
 8362            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8363                s.select(new_selections);
 8364            });
 8365        }
 8366        self.select_larger_syntax_node_stack = stack;
 8367    }
 8368
 8369    pub fn select_smaller_syntax_node(
 8370        &mut self,
 8371        _: &SelectSmallerSyntaxNode,
 8372        cx: &mut ViewContext<Self>,
 8373    ) {
 8374        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8375        if let Some(selections) = stack.pop() {
 8376            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8377                s.select(selections.to_vec());
 8378            });
 8379        }
 8380        self.select_larger_syntax_node_stack = stack;
 8381    }
 8382
 8383    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8384        if !EditorSettings::get_global(cx).gutter.runnables {
 8385            self.clear_tasks();
 8386            return Task::ready(());
 8387        }
 8388        let project = self.project.clone();
 8389        cx.spawn(|this, mut cx| async move {
 8390            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8391                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8392            }) else {
 8393                return;
 8394            };
 8395
 8396            let Some(project) = project else {
 8397                return;
 8398            };
 8399
 8400            let hide_runnables = project
 8401                .update(&mut cx, |project, cx| {
 8402                    // Do not display any test indicators in non-dev server remote projects.
 8403                    project.is_remote() && project.ssh_connection_string(cx).is_none()
 8404                })
 8405                .unwrap_or(true);
 8406            if hide_runnables {
 8407                return;
 8408            }
 8409            let new_rows =
 8410                cx.background_executor()
 8411                    .spawn({
 8412                        let snapshot = display_snapshot.clone();
 8413                        async move {
 8414                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8415                        }
 8416                    })
 8417                    .await;
 8418            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8419
 8420            this.update(&mut cx, |this, _| {
 8421                this.clear_tasks();
 8422                for (key, value) in rows {
 8423                    this.insert_tasks(key, value);
 8424                }
 8425            })
 8426            .ok();
 8427        })
 8428    }
 8429    fn fetch_runnable_ranges(
 8430        snapshot: &DisplaySnapshot,
 8431        range: Range<Anchor>,
 8432    ) -> Vec<language::RunnableRange> {
 8433        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8434    }
 8435
 8436    fn runnable_rows(
 8437        project: Model<Project>,
 8438        snapshot: DisplaySnapshot,
 8439        runnable_ranges: Vec<RunnableRange>,
 8440        mut cx: AsyncWindowContext,
 8441    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8442        runnable_ranges
 8443            .into_iter()
 8444            .filter_map(|mut runnable| {
 8445                let tasks = cx
 8446                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8447                    .ok()?;
 8448                if tasks.is_empty() {
 8449                    return None;
 8450                }
 8451
 8452                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8453
 8454                let row = snapshot
 8455                    .buffer_snapshot
 8456                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8457                    .1
 8458                    .start
 8459                    .row;
 8460
 8461                let context_range =
 8462                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8463                Some((
 8464                    (runnable.buffer_id, row),
 8465                    RunnableTasks {
 8466                        templates: tasks,
 8467                        offset: MultiBufferOffset(runnable.run_range.start),
 8468                        context_range,
 8469                        column: point.column,
 8470                        extra_variables: runnable.extra_captures,
 8471                    },
 8472                ))
 8473            })
 8474            .collect()
 8475    }
 8476
 8477    fn templates_with_tags(
 8478        project: &Model<Project>,
 8479        runnable: &mut Runnable,
 8480        cx: &WindowContext<'_>,
 8481    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8482        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8483            let (worktree_id, file) = project
 8484                .buffer_for_id(runnable.buffer)
 8485                .and_then(|buffer| buffer.read(cx).file())
 8486                .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
 8487                .unzip();
 8488
 8489            (project.task_inventory().clone(), worktree_id, file)
 8490        });
 8491
 8492        let inventory = inventory.read(cx);
 8493        let tags = mem::take(&mut runnable.tags);
 8494        let mut tags: Vec<_> = tags
 8495            .into_iter()
 8496            .flat_map(|tag| {
 8497                let tag = tag.0.clone();
 8498                inventory
 8499                    .list_tasks(
 8500                        file.clone(),
 8501                        Some(runnable.language.clone()),
 8502                        worktree_id,
 8503                        cx,
 8504                    )
 8505                    .into_iter()
 8506                    .filter(move |(_, template)| {
 8507                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8508                    })
 8509            })
 8510            .sorted_by_key(|(kind, _)| kind.to_owned())
 8511            .collect();
 8512        if let Some((leading_tag_source, _)) = tags.first() {
 8513            // Strongest source wins; if we have worktree tag binding, prefer that to
 8514            // global and language bindings;
 8515            // if we have a global binding, prefer that to language binding.
 8516            let first_mismatch = tags
 8517                .iter()
 8518                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8519            if let Some(index) = first_mismatch {
 8520                tags.truncate(index);
 8521            }
 8522        }
 8523
 8524        tags
 8525    }
 8526
 8527    pub fn move_to_enclosing_bracket(
 8528        &mut self,
 8529        _: &MoveToEnclosingBracket,
 8530        cx: &mut ViewContext<Self>,
 8531    ) {
 8532        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8533            s.move_offsets_with(|snapshot, selection| {
 8534                let Some(enclosing_bracket_ranges) =
 8535                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8536                else {
 8537                    return;
 8538                };
 8539
 8540                let mut best_length = usize::MAX;
 8541                let mut best_inside = false;
 8542                let mut best_in_bracket_range = false;
 8543                let mut best_destination = None;
 8544                for (open, close) in enclosing_bracket_ranges {
 8545                    let close = close.to_inclusive();
 8546                    let length = close.end() - open.start;
 8547                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8548                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8549                        || close.contains(&selection.head());
 8550
 8551                    // If best is next to a bracket and current isn't, skip
 8552                    if !in_bracket_range && best_in_bracket_range {
 8553                        continue;
 8554                    }
 8555
 8556                    // Prefer smaller lengths unless best is inside and current isn't
 8557                    if length > best_length && (best_inside || !inside) {
 8558                        continue;
 8559                    }
 8560
 8561                    best_length = length;
 8562                    best_inside = inside;
 8563                    best_in_bracket_range = in_bracket_range;
 8564                    best_destination = Some(
 8565                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8566                            if inside {
 8567                                open.end
 8568                            } else {
 8569                                open.start
 8570                            }
 8571                        } else {
 8572                            if inside {
 8573                                *close.start()
 8574                            } else {
 8575                                *close.end()
 8576                            }
 8577                        },
 8578                    );
 8579                }
 8580
 8581                if let Some(destination) = best_destination {
 8582                    selection.collapse_to(destination, SelectionGoal::None);
 8583                }
 8584            })
 8585        });
 8586    }
 8587
 8588    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 8589        self.end_selection(cx);
 8590        self.selection_history.mode = SelectionHistoryMode::Undoing;
 8591        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 8592            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8593            self.select_next_state = entry.select_next_state;
 8594            self.select_prev_state = entry.select_prev_state;
 8595            self.add_selections_state = entry.add_selections_state;
 8596            self.request_autoscroll(Autoscroll::newest(), cx);
 8597        }
 8598        self.selection_history.mode = SelectionHistoryMode::Normal;
 8599    }
 8600
 8601    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 8602        self.end_selection(cx);
 8603        self.selection_history.mode = SelectionHistoryMode::Redoing;
 8604        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 8605            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8606            self.select_next_state = entry.select_next_state;
 8607            self.select_prev_state = entry.select_prev_state;
 8608            self.add_selections_state = entry.add_selections_state;
 8609            self.request_autoscroll(Autoscroll::newest(), cx);
 8610        }
 8611        self.selection_history.mode = SelectionHistoryMode::Normal;
 8612    }
 8613
 8614    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 8615        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 8616    }
 8617
 8618    pub fn expand_excerpts_down(
 8619        &mut self,
 8620        action: &ExpandExcerptsDown,
 8621        cx: &mut ViewContext<Self>,
 8622    ) {
 8623        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 8624    }
 8625
 8626    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 8627        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 8628    }
 8629
 8630    pub fn expand_excerpts_for_direction(
 8631        &mut self,
 8632        lines: u32,
 8633        direction: ExpandExcerptDirection,
 8634        cx: &mut ViewContext<Self>,
 8635    ) {
 8636        let selections = self.selections.disjoint_anchors();
 8637
 8638        let lines = if lines == 0 {
 8639            EditorSettings::get_global(cx).expand_excerpt_lines
 8640        } else {
 8641            lines
 8642        };
 8643
 8644        self.buffer.update(cx, |buffer, cx| {
 8645            buffer.expand_excerpts(
 8646                selections
 8647                    .into_iter()
 8648                    .map(|selection| selection.head().excerpt_id)
 8649                    .dedup(),
 8650                lines,
 8651                direction,
 8652                cx,
 8653            )
 8654        })
 8655    }
 8656
 8657    pub fn expand_excerpt(
 8658        &mut self,
 8659        excerpt: ExcerptId,
 8660        direction: ExpandExcerptDirection,
 8661        cx: &mut ViewContext<Self>,
 8662    ) {
 8663        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 8664        self.buffer.update(cx, |buffer, cx| {
 8665            buffer.expand_excerpts([excerpt], lines, direction, cx)
 8666        })
 8667    }
 8668
 8669    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8670        self.go_to_diagnostic_impl(Direction::Next, cx)
 8671    }
 8672
 8673    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8674        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8675    }
 8676
 8677    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8678        let buffer = self.buffer.read(cx).snapshot(cx);
 8679        let selection = self.selections.newest::<usize>(cx);
 8680
 8681        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8682        if direction == Direction::Next {
 8683            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8684                let (group_id, jump_to) = popover.activation_info();
 8685                if self.activate_diagnostics(group_id, cx) {
 8686                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8687                        let mut new_selection = s.newest_anchor().clone();
 8688                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 8689                        s.select_anchors(vec![new_selection.clone()]);
 8690                    });
 8691                }
 8692                return;
 8693            }
 8694        }
 8695
 8696        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 8697            active_diagnostics
 8698                .primary_range
 8699                .to_offset(&buffer)
 8700                .to_inclusive()
 8701        });
 8702        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 8703            if active_primary_range.contains(&selection.head()) {
 8704                *active_primary_range.start()
 8705            } else {
 8706                selection.head()
 8707            }
 8708        } else {
 8709            selection.head()
 8710        };
 8711        let snapshot = self.snapshot(cx);
 8712        loop {
 8713            let diagnostics = if direction == Direction::Prev {
 8714                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 8715            } else {
 8716                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 8717            }
 8718            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 8719            let group = diagnostics
 8720                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 8721                // be sorted in a stable way
 8722                // skip until we are at current active diagnostic, if it exists
 8723                .skip_while(|entry| {
 8724                    (match direction {
 8725                        Direction::Prev => entry.range.start >= search_start,
 8726                        Direction::Next => entry.range.start <= search_start,
 8727                    }) && self
 8728                        .active_diagnostics
 8729                        .as_ref()
 8730                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 8731                })
 8732                .find_map(|entry| {
 8733                    if entry.diagnostic.is_primary
 8734                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 8735                        && !entry.range.is_empty()
 8736                        // if we match with the active diagnostic, skip it
 8737                        && Some(entry.diagnostic.group_id)
 8738                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 8739                    {
 8740                        Some((entry.range, entry.diagnostic.group_id))
 8741                    } else {
 8742                        None
 8743                    }
 8744                });
 8745
 8746            if let Some((primary_range, group_id)) = group {
 8747                if self.activate_diagnostics(group_id, cx) {
 8748                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8749                        s.select(vec![Selection {
 8750                            id: selection.id,
 8751                            start: primary_range.start,
 8752                            end: primary_range.start,
 8753                            reversed: false,
 8754                            goal: SelectionGoal::None,
 8755                        }]);
 8756                    });
 8757                }
 8758                break;
 8759            } else {
 8760                // Cycle around to the start of the buffer, potentially moving back to the start of
 8761                // the currently active diagnostic.
 8762                active_primary_range.take();
 8763                if direction == Direction::Prev {
 8764                    if search_start == buffer.len() {
 8765                        break;
 8766                    } else {
 8767                        search_start = buffer.len();
 8768                    }
 8769                } else if search_start == 0 {
 8770                    break;
 8771                } else {
 8772                    search_start = 0;
 8773                }
 8774            }
 8775        }
 8776    }
 8777
 8778    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 8779        let snapshot = self
 8780            .display_map
 8781            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8782        let selection = self.selections.newest::<Point>(cx);
 8783
 8784        if !self.seek_in_direction(
 8785            &snapshot,
 8786            selection.head(),
 8787            false,
 8788            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8789                MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
 8790            ),
 8791            cx,
 8792        ) {
 8793            let wrapped_point = Point::zero();
 8794            self.seek_in_direction(
 8795                &snapshot,
 8796                wrapped_point,
 8797                true,
 8798                snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8799                    MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 8800                ),
 8801                cx,
 8802            );
 8803        }
 8804    }
 8805
 8806    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 8807        let snapshot = self
 8808            .display_map
 8809            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8810        let selection = self.selections.newest::<Point>(cx);
 8811
 8812        if !self.seek_in_direction(
 8813            &snapshot,
 8814            selection.head(),
 8815            false,
 8816            snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8817                MultiBufferRow(0)..MultiBufferRow(selection.head().row),
 8818            ),
 8819            cx,
 8820        ) {
 8821            let wrapped_point = snapshot.buffer_snapshot.max_point();
 8822            self.seek_in_direction(
 8823                &snapshot,
 8824                wrapped_point,
 8825                true,
 8826                snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8827                    MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
 8828                ),
 8829                cx,
 8830            );
 8831        }
 8832    }
 8833
 8834    fn seek_in_direction(
 8835        &mut self,
 8836        snapshot: &DisplaySnapshot,
 8837        initial_point: Point,
 8838        is_wrapped: bool,
 8839        hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
 8840        cx: &mut ViewContext<Editor>,
 8841    ) -> bool {
 8842        let display_point = initial_point.to_display_point(snapshot);
 8843        let mut hunks = hunks
 8844            .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
 8845            .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
 8846            .dedup();
 8847
 8848        if let Some(hunk) = hunks.next() {
 8849            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8850                let row = hunk.start_display_row();
 8851                let point = DisplayPoint::new(row, 0);
 8852                s.select_display_ranges([point..point]);
 8853            });
 8854
 8855            true
 8856        } else {
 8857            false
 8858        }
 8859    }
 8860
 8861    pub fn go_to_definition(
 8862        &mut self,
 8863        _: &GoToDefinition,
 8864        cx: &mut ViewContext<Self>,
 8865    ) -> Task<Result<bool>> {
 8866        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
 8867    }
 8868
 8869    pub fn go_to_implementation(
 8870        &mut self,
 8871        _: &GoToImplementation,
 8872        cx: &mut ViewContext<Self>,
 8873    ) -> Task<Result<bool>> {
 8874        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 8875    }
 8876
 8877    pub fn go_to_implementation_split(
 8878        &mut self,
 8879        _: &GoToImplementationSplit,
 8880        cx: &mut ViewContext<Self>,
 8881    ) -> Task<Result<bool>> {
 8882        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 8883    }
 8884
 8885    pub fn go_to_type_definition(
 8886        &mut self,
 8887        _: &GoToTypeDefinition,
 8888        cx: &mut ViewContext<Self>,
 8889    ) -> Task<Result<bool>> {
 8890        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 8891    }
 8892
 8893    pub fn go_to_definition_split(
 8894        &mut self,
 8895        _: &GoToDefinitionSplit,
 8896        cx: &mut ViewContext<Self>,
 8897    ) -> Task<Result<bool>> {
 8898        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 8899    }
 8900
 8901    pub fn go_to_type_definition_split(
 8902        &mut self,
 8903        _: &GoToTypeDefinitionSplit,
 8904        cx: &mut ViewContext<Self>,
 8905    ) -> Task<Result<bool>> {
 8906        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 8907    }
 8908
 8909    fn go_to_definition_of_kind(
 8910        &mut self,
 8911        kind: GotoDefinitionKind,
 8912        split: bool,
 8913        cx: &mut ViewContext<Self>,
 8914    ) -> Task<Result<bool>> {
 8915        let Some(workspace) = self.workspace() else {
 8916            return Task::ready(Ok(false));
 8917        };
 8918        let buffer = self.buffer.read(cx);
 8919        let head = self.selections.newest::<usize>(cx).head();
 8920        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 8921            text_anchor
 8922        } else {
 8923            return Task::ready(Ok(false));
 8924        };
 8925
 8926        let project = workspace.read(cx).project().clone();
 8927        let definitions = project.update(cx, |project, cx| match kind {
 8928            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 8929            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 8930            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 8931        });
 8932
 8933        cx.spawn(|editor, mut cx| async move {
 8934            let definitions = definitions.await?;
 8935            let navigated = editor
 8936                .update(&mut cx, |editor, cx| {
 8937                    editor.navigate_to_hover_links(
 8938                        Some(kind),
 8939                        definitions
 8940                            .into_iter()
 8941                            .filter(|location| {
 8942                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 8943                            })
 8944                            .map(HoverLink::Text)
 8945                            .collect::<Vec<_>>(),
 8946                        split,
 8947                        cx,
 8948                    )
 8949                })?
 8950                .await?;
 8951            anyhow::Ok(navigated)
 8952        })
 8953    }
 8954
 8955    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 8956        let position = self.selections.newest_anchor().head();
 8957        let Some((buffer, buffer_position)) =
 8958            self.buffer.read(cx).text_anchor_for_position(position, cx)
 8959        else {
 8960            return;
 8961        };
 8962
 8963        cx.spawn(|editor, mut cx| async move {
 8964            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 8965                editor.update(&mut cx, |_, cx| {
 8966                    cx.open_url(&url);
 8967                })
 8968            } else {
 8969                Ok(())
 8970            }
 8971        })
 8972        .detach();
 8973    }
 8974
 8975    pub(crate) fn navigate_to_hover_links(
 8976        &mut self,
 8977        kind: Option<GotoDefinitionKind>,
 8978        mut definitions: Vec<HoverLink>,
 8979        split: bool,
 8980        cx: &mut ViewContext<Editor>,
 8981    ) -> Task<Result<bool>> {
 8982        // If there is one definition, just open it directly
 8983        if definitions.len() == 1 {
 8984            let definition = definitions.pop().unwrap();
 8985            let target_task = match definition {
 8986                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 8987                HoverLink::InlayHint(lsp_location, server_id) => {
 8988                    self.compute_target_location(lsp_location, server_id, cx)
 8989                }
 8990                HoverLink::Url(url) => {
 8991                    cx.open_url(&url);
 8992                    Task::ready(Ok(None))
 8993                }
 8994            };
 8995            cx.spawn(|editor, mut cx| async move {
 8996                let target = target_task.await.context("target resolution task")?;
 8997                if let Some(target) = target {
 8998                    editor.update(&mut cx, |editor, cx| {
 8999                        let Some(workspace) = editor.workspace() else {
 9000                            return false;
 9001                        };
 9002                        let pane = workspace.read(cx).active_pane().clone();
 9003
 9004                        let range = target.range.to_offset(target.buffer.read(cx));
 9005                        let range = editor.range_for_match(&range);
 9006
 9007                        /// If select range has more than one line, we
 9008                        /// just point the cursor to range.start.
 9009                        fn check_multiline_range(
 9010                            buffer: &Buffer,
 9011                            range: Range<usize>,
 9012                        ) -> Range<usize> {
 9013                            if buffer.offset_to_point(range.start).row
 9014                                == buffer.offset_to_point(range.end).row
 9015                            {
 9016                                range
 9017                            } else {
 9018                                range.start..range.start
 9019                            }
 9020                        }
 9021
 9022                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9023                            let buffer = target.buffer.read(cx);
 9024                            let range = check_multiline_range(buffer, range);
 9025                            editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 9026                                s.select_ranges([range]);
 9027                            });
 9028                        } else {
 9029                            cx.window_context().defer(move |cx| {
 9030                                let target_editor: View<Self> =
 9031                                    workspace.update(cx, |workspace, cx| {
 9032                                        let pane = if split {
 9033                                            workspace.adjacent_pane(cx)
 9034                                        } else {
 9035                                            workspace.active_pane().clone()
 9036                                        };
 9037
 9038                                        workspace.open_project_item(pane, target.buffer.clone(), cx)
 9039                                    });
 9040                                target_editor.update(cx, |target_editor, cx| {
 9041                                    // When selecting a definition in a different buffer, disable the nav history
 9042                                    // to avoid creating a history entry at the previous cursor location.
 9043                                    pane.update(cx, |pane, _| pane.disable_history());
 9044                                    let buffer = target.buffer.read(cx);
 9045                                    let range = check_multiline_range(buffer, range);
 9046                                    target_editor.change_selections(
 9047                                        Some(Autoscroll::focused()),
 9048                                        cx,
 9049                                        |s| {
 9050                                            s.select_ranges([range]);
 9051                                        },
 9052                                    );
 9053                                    pane.update(cx, |pane, _| pane.enable_history());
 9054                                });
 9055                            });
 9056                        }
 9057                        true
 9058                    })
 9059                } else {
 9060                    Ok(false)
 9061                }
 9062            })
 9063        } else if !definitions.is_empty() {
 9064            let replica_id = self.replica_id(cx);
 9065            cx.spawn(|editor, mut cx| async move {
 9066                let (title, location_tasks, workspace) = editor
 9067                    .update(&mut cx, |editor, cx| {
 9068                        let tab_kind = match kind {
 9069                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9070                            _ => "Definitions",
 9071                        };
 9072                        let title = definitions
 9073                            .iter()
 9074                            .find_map(|definition| match definition {
 9075                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9076                                    let buffer = origin.buffer.read(cx);
 9077                                    format!(
 9078                                        "{} for {}",
 9079                                        tab_kind,
 9080                                        buffer
 9081                                            .text_for_range(origin.range.clone())
 9082                                            .collect::<String>()
 9083                                    )
 9084                                }),
 9085                                HoverLink::InlayHint(_, _) => None,
 9086                                HoverLink::Url(_) => None,
 9087                            })
 9088                            .unwrap_or(tab_kind.to_string());
 9089                        let location_tasks = definitions
 9090                            .into_iter()
 9091                            .map(|definition| match definition {
 9092                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9093                                HoverLink::InlayHint(lsp_location, server_id) => {
 9094                                    editor.compute_target_location(lsp_location, server_id, cx)
 9095                                }
 9096                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9097                            })
 9098                            .collect::<Vec<_>>();
 9099                        (title, location_tasks, editor.workspace().clone())
 9100                    })
 9101                    .context("location tasks preparation")?;
 9102
 9103                let locations = futures::future::join_all(location_tasks)
 9104                    .await
 9105                    .into_iter()
 9106                    .filter_map(|location| location.transpose())
 9107                    .collect::<Result<_>>()
 9108                    .context("location tasks")?;
 9109
 9110                let Some(workspace) = workspace else {
 9111                    return Ok(false);
 9112                };
 9113                let opened = workspace
 9114                    .update(&mut cx, |workspace, cx| {
 9115                        Self::open_locations_in_multibuffer(
 9116                            workspace, locations, replica_id, title, split, cx,
 9117                        )
 9118                    })
 9119                    .ok();
 9120
 9121                anyhow::Ok(opened.is_some())
 9122            })
 9123        } else {
 9124            Task::ready(Ok(false))
 9125        }
 9126    }
 9127
 9128    fn compute_target_location(
 9129        &self,
 9130        lsp_location: lsp::Location,
 9131        server_id: LanguageServerId,
 9132        cx: &mut ViewContext<Editor>,
 9133    ) -> Task<anyhow::Result<Option<Location>>> {
 9134        let Some(project) = self.project.clone() else {
 9135            return Task::Ready(Some(Ok(None)));
 9136        };
 9137
 9138        cx.spawn(move |editor, mut cx| async move {
 9139            let location_task = editor.update(&mut cx, |editor, cx| {
 9140                project.update(cx, |project, cx| {
 9141                    let language_server_name =
 9142                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 9143                            project
 9144                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 9145                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 9146                        });
 9147                    language_server_name.map(|language_server_name| {
 9148                        project.open_local_buffer_via_lsp(
 9149                            lsp_location.uri.clone(),
 9150                            server_id,
 9151                            language_server_name,
 9152                            cx,
 9153                        )
 9154                    })
 9155                })
 9156            })?;
 9157            let location = match location_task {
 9158                Some(task) => Some({
 9159                    let target_buffer_handle = task.await.context("open local buffer")?;
 9160                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9161                        let target_start = target_buffer
 9162                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9163                        let target_end = target_buffer
 9164                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9165                        target_buffer.anchor_after(target_start)
 9166                            ..target_buffer.anchor_before(target_end)
 9167                    })?;
 9168                    Location {
 9169                        buffer: target_buffer_handle,
 9170                        range,
 9171                    }
 9172                }),
 9173                None => None,
 9174            };
 9175            Ok(location)
 9176        })
 9177    }
 9178
 9179    pub fn find_all_references(
 9180        &mut self,
 9181        _: &FindAllReferences,
 9182        cx: &mut ViewContext<Self>,
 9183    ) -> Option<Task<Result<()>>> {
 9184        let multi_buffer = self.buffer.read(cx);
 9185        let selection = self.selections.newest::<usize>(cx);
 9186        let head = selection.head();
 9187
 9188        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9189        let head_anchor = multi_buffer_snapshot.anchor_at(
 9190            head,
 9191            if head < selection.tail() {
 9192                Bias::Right
 9193            } else {
 9194                Bias::Left
 9195            },
 9196        );
 9197
 9198        match self
 9199            .find_all_references_task_sources
 9200            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9201        {
 9202            Ok(_) => {
 9203                log::info!(
 9204                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9205                );
 9206                return None;
 9207            }
 9208            Err(i) => {
 9209                self.find_all_references_task_sources.insert(i, head_anchor);
 9210            }
 9211        }
 9212
 9213        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9214        let replica_id = self.replica_id(cx);
 9215        let workspace = self.workspace()?;
 9216        let project = workspace.read(cx).project().clone();
 9217        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9218        Some(cx.spawn(|editor, mut cx| async move {
 9219            let _cleanup = defer({
 9220                let mut cx = cx.clone();
 9221                move || {
 9222                    let _ = editor.update(&mut cx, |editor, _| {
 9223                        if let Ok(i) =
 9224                            editor
 9225                                .find_all_references_task_sources
 9226                                .binary_search_by(|anchor| {
 9227                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9228                                })
 9229                        {
 9230                            editor.find_all_references_task_sources.remove(i);
 9231                        }
 9232                    });
 9233                }
 9234            });
 9235
 9236            let locations = references.await?;
 9237            if locations.is_empty() {
 9238                return anyhow::Ok(());
 9239            }
 9240
 9241            workspace.update(&mut cx, |workspace, cx| {
 9242                let title = locations
 9243                    .first()
 9244                    .as_ref()
 9245                    .map(|location| {
 9246                        let buffer = location.buffer.read(cx);
 9247                        format!(
 9248                            "References to `{}`",
 9249                            buffer
 9250                                .text_for_range(location.range.clone())
 9251                                .collect::<String>()
 9252                        )
 9253                    })
 9254                    .unwrap();
 9255                Self::open_locations_in_multibuffer(
 9256                    workspace, locations, replica_id, title, false, cx,
 9257                );
 9258            })
 9259        }))
 9260    }
 9261
 9262    /// Opens a multibuffer with the given project locations in it
 9263    pub fn open_locations_in_multibuffer(
 9264        workspace: &mut Workspace,
 9265        mut locations: Vec<Location>,
 9266        replica_id: ReplicaId,
 9267        title: String,
 9268        split: bool,
 9269        cx: &mut ViewContext<Workspace>,
 9270    ) {
 9271        // If there are multiple definitions, open them in a multibuffer
 9272        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9273        let mut locations = locations.into_iter().peekable();
 9274        let mut ranges_to_highlight = Vec::new();
 9275        let capability = workspace.project().read(cx).capability();
 9276
 9277        let excerpt_buffer = cx.new_model(|cx| {
 9278            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 9279            while let Some(location) = locations.next() {
 9280                let buffer = location.buffer.read(cx);
 9281                let mut ranges_for_buffer = Vec::new();
 9282                let range = location.range.to_offset(buffer);
 9283                ranges_for_buffer.push(range.clone());
 9284
 9285                while let Some(next_location) = locations.peek() {
 9286                    if next_location.buffer == location.buffer {
 9287                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9288                        locations.next();
 9289                    } else {
 9290                        break;
 9291                    }
 9292                }
 9293
 9294                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9295                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9296                    location.buffer.clone(),
 9297                    ranges_for_buffer,
 9298                    DEFAULT_MULTIBUFFER_CONTEXT,
 9299                    cx,
 9300                ))
 9301            }
 9302
 9303            multibuffer.with_title(title)
 9304        });
 9305
 9306        let editor = cx.new_view(|cx| {
 9307            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9308        });
 9309        editor.update(cx, |editor, cx| {
 9310            if let Some(first_range) = ranges_to_highlight.first() {
 9311                editor.change_selections(None, cx, |selections| {
 9312                    selections.clear_disjoint();
 9313                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9314                });
 9315            }
 9316            editor.highlight_background::<Self>(
 9317                &ranges_to_highlight,
 9318                |theme| theme.editor_highlighted_line_background,
 9319                cx,
 9320            );
 9321        });
 9322
 9323        let item = Box::new(editor);
 9324        let item_id = item.item_id();
 9325
 9326        if split {
 9327            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9328        } else {
 9329            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9330                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9331                    pane.close_current_preview_item(cx)
 9332                } else {
 9333                    None
 9334                }
 9335            });
 9336            workspace.add_item_to_active_pane(item.clone(), destination_index, cx);
 9337        }
 9338        workspace.active_pane().update(cx, |pane, cx| {
 9339            pane.set_preview_item_id(Some(item_id), cx);
 9340        });
 9341    }
 9342
 9343    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9344        use language::ToOffset as _;
 9345
 9346        let project = self.project.clone()?;
 9347        let selection = self.selections.newest_anchor().clone();
 9348        let (cursor_buffer, cursor_buffer_position) = self
 9349            .buffer
 9350            .read(cx)
 9351            .text_anchor_for_position(selection.head(), cx)?;
 9352        let (tail_buffer, cursor_buffer_position_end) = self
 9353            .buffer
 9354            .read(cx)
 9355            .text_anchor_for_position(selection.tail(), cx)?;
 9356        if tail_buffer != cursor_buffer {
 9357            return None;
 9358        }
 9359
 9360        let snapshot = cursor_buffer.read(cx).snapshot();
 9361        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9362        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9363        let prepare_rename = project.update(cx, |project, cx| {
 9364            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 9365        });
 9366        drop(snapshot);
 9367
 9368        Some(cx.spawn(|this, mut cx| async move {
 9369            let rename_range = if let Some(range) = prepare_rename.await? {
 9370                Some(range)
 9371            } else {
 9372                this.update(&mut cx, |this, cx| {
 9373                    let buffer = this.buffer.read(cx).snapshot(cx);
 9374                    let mut buffer_highlights = this
 9375                        .document_highlights_for_position(selection.head(), &buffer)
 9376                        .filter(|highlight| {
 9377                            highlight.start.excerpt_id == selection.head().excerpt_id
 9378                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9379                        });
 9380                    buffer_highlights
 9381                        .next()
 9382                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9383                })?
 9384            };
 9385            if let Some(rename_range) = rename_range {
 9386                this.update(&mut cx, |this, cx| {
 9387                    let snapshot = cursor_buffer.read(cx).snapshot();
 9388                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9389                    let cursor_offset_in_rename_range =
 9390                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9391                    let cursor_offset_in_rename_range_end =
 9392                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9393
 9394                    this.take_rename(false, cx);
 9395                    let buffer = this.buffer.read(cx).read(cx);
 9396                    let cursor_offset = selection.head().to_offset(&buffer);
 9397                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9398                    let rename_end = rename_start + rename_buffer_range.len();
 9399                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9400                    let mut old_highlight_id = None;
 9401                    let old_name: Arc<str> = buffer
 9402                        .chunks(rename_start..rename_end, true)
 9403                        .map(|chunk| {
 9404                            if old_highlight_id.is_none() {
 9405                                old_highlight_id = chunk.syntax_highlight_id;
 9406                            }
 9407                            chunk.text
 9408                        })
 9409                        .collect::<String>()
 9410                        .into();
 9411
 9412                    drop(buffer);
 9413
 9414                    // Position the selection in the rename editor so that it matches the current selection.
 9415                    this.show_local_selections = false;
 9416                    let rename_editor = cx.new_view(|cx| {
 9417                        let mut editor = Editor::single_line(cx);
 9418                        editor.buffer.update(cx, |buffer, cx| {
 9419                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9420                        });
 9421                        let rename_selection_range = match cursor_offset_in_rename_range
 9422                            .cmp(&cursor_offset_in_rename_range_end)
 9423                        {
 9424                            Ordering::Equal => {
 9425                                editor.select_all(&SelectAll, cx);
 9426                                return editor;
 9427                            }
 9428                            Ordering::Less => {
 9429                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9430                            }
 9431                            Ordering::Greater => {
 9432                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9433                            }
 9434                        };
 9435                        if rename_selection_range.end > old_name.len() {
 9436                            editor.select_all(&SelectAll, cx);
 9437                        } else {
 9438                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9439                                s.select_ranges([rename_selection_range]);
 9440                            });
 9441                        }
 9442                        editor
 9443                    });
 9444
 9445                    let write_highlights =
 9446                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9447                    let read_highlights =
 9448                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9449                    let ranges = write_highlights
 9450                        .iter()
 9451                        .flat_map(|(_, ranges)| ranges.iter())
 9452                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9453                        .cloned()
 9454                        .collect();
 9455
 9456                    this.highlight_text::<Rename>(
 9457                        ranges,
 9458                        HighlightStyle {
 9459                            fade_out: Some(0.6),
 9460                            ..Default::default()
 9461                        },
 9462                        cx,
 9463                    );
 9464                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9465                    cx.focus(&rename_focus_handle);
 9466                    let block_id = this.insert_blocks(
 9467                        [BlockProperties {
 9468                            style: BlockStyle::Flex,
 9469                            position: range.start,
 9470                            height: 1,
 9471                            render: Box::new({
 9472                                let rename_editor = rename_editor.clone();
 9473                                move |cx: &mut BlockContext| {
 9474                                    let mut text_style = cx.editor_style.text.clone();
 9475                                    if let Some(highlight_style) = old_highlight_id
 9476                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 9477                                    {
 9478                                        text_style = text_style.highlight(highlight_style);
 9479                                    }
 9480                                    div()
 9481                                        .pl(cx.anchor_x)
 9482                                        .child(EditorElement::new(
 9483                                            &rename_editor,
 9484                                            EditorStyle {
 9485                                                background: cx.theme().system().transparent,
 9486                                                local_player: cx.editor_style.local_player,
 9487                                                text: text_style,
 9488                                                scrollbar_width: cx.editor_style.scrollbar_width,
 9489                                                syntax: cx.editor_style.syntax.clone(),
 9490                                                status: cx.editor_style.status.clone(),
 9491                                                inlay_hints_style: HighlightStyle {
 9492                                                    color: Some(cx.theme().status().hint),
 9493                                                    font_weight: Some(FontWeight::BOLD),
 9494                                                    ..HighlightStyle::default()
 9495                                                },
 9496                                                suggestions_style: HighlightStyle {
 9497                                                    color: Some(cx.theme().status().predictive),
 9498                                                    ..HighlightStyle::default()
 9499                                                },
 9500                                            },
 9501                                        ))
 9502                                        .into_any_element()
 9503                                }
 9504                            }),
 9505                            disposition: BlockDisposition::Below,
 9506                        }],
 9507                        Some(Autoscroll::fit()),
 9508                        cx,
 9509                    )[0];
 9510                    this.pending_rename = Some(RenameState {
 9511                        range,
 9512                        old_name,
 9513                        editor: rename_editor,
 9514                        block_id,
 9515                    });
 9516                })?;
 9517            }
 9518
 9519            Ok(())
 9520        }))
 9521    }
 9522
 9523    pub fn confirm_rename(
 9524        &mut self,
 9525        _: &ConfirmRename,
 9526        cx: &mut ViewContext<Self>,
 9527    ) -> Option<Task<Result<()>>> {
 9528        let rename = self.take_rename(false, cx)?;
 9529        let workspace = self.workspace()?;
 9530        let (start_buffer, start) = self
 9531            .buffer
 9532            .read(cx)
 9533            .text_anchor_for_position(rename.range.start, cx)?;
 9534        let (end_buffer, end) = self
 9535            .buffer
 9536            .read(cx)
 9537            .text_anchor_for_position(rename.range.end, cx)?;
 9538        if start_buffer != end_buffer {
 9539            return None;
 9540        }
 9541
 9542        let buffer = start_buffer;
 9543        let range = start..end;
 9544        let old_name = rename.old_name;
 9545        let new_name = rename.editor.read(cx).text(cx);
 9546
 9547        let rename = workspace
 9548            .read(cx)
 9549            .project()
 9550            .clone()
 9551            .update(cx, |project, cx| {
 9552                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 9553            });
 9554        let workspace = workspace.downgrade();
 9555
 9556        Some(cx.spawn(|editor, mut cx| async move {
 9557            let project_transaction = rename.await?;
 9558            Self::open_project_transaction(
 9559                &editor,
 9560                workspace,
 9561                project_transaction,
 9562                format!("Rename: {}{}", old_name, new_name),
 9563                cx.clone(),
 9564            )
 9565            .await?;
 9566
 9567            editor.update(&mut cx, |editor, cx| {
 9568                editor.refresh_document_highlights(cx);
 9569            })?;
 9570            Ok(())
 9571        }))
 9572    }
 9573
 9574    fn take_rename(
 9575        &mut self,
 9576        moving_cursor: bool,
 9577        cx: &mut ViewContext<Self>,
 9578    ) -> Option<RenameState> {
 9579        let rename = self.pending_rename.take()?;
 9580        if rename.editor.focus_handle(cx).is_focused(cx) {
 9581            cx.focus(&self.focus_handle);
 9582        }
 9583
 9584        self.remove_blocks(
 9585            [rename.block_id].into_iter().collect(),
 9586            Some(Autoscroll::fit()),
 9587            cx,
 9588        );
 9589        self.clear_highlights::<Rename>(cx);
 9590        self.show_local_selections = true;
 9591
 9592        if moving_cursor {
 9593            let rename_editor = rename.editor.read(cx);
 9594            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 9595
 9596            // Update the selection to match the position of the selection inside
 9597            // the rename editor.
 9598            let snapshot = self.buffer.read(cx).read(cx);
 9599            let rename_range = rename.range.to_offset(&snapshot);
 9600            let cursor_in_editor = snapshot
 9601                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 9602                .min(rename_range.end);
 9603            drop(snapshot);
 9604
 9605            self.change_selections(None, cx, |s| {
 9606                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 9607            });
 9608        } else {
 9609            self.refresh_document_highlights(cx);
 9610        }
 9611
 9612        Some(rename)
 9613    }
 9614
 9615    pub fn pending_rename(&self) -> Option<&RenameState> {
 9616        self.pending_rename.as_ref()
 9617    }
 9618
 9619    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9620        let project = match &self.project {
 9621            Some(project) => project.clone(),
 9622            None => return None,
 9623        };
 9624
 9625        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 9626    }
 9627
 9628    fn perform_format(
 9629        &mut self,
 9630        project: Model<Project>,
 9631        trigger: FormatTrigger,
 9632        cx: &mut ViewContext<Self>,
 9633    ) -> Task<Result<()>> {
 9634        let buffer = self.buffer().clone();
 9635        let mut buffers = buffer.read(cx).all_buffers();
 9636        if trigger == FormatTrigger::Save {
 9637            buffers.retain(|buffer| buffer.read(cx).is_dirty());
 9638        }
 9639
 9640        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 9641        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 9642
 9643        cx.spawn(|_, mut cx| async move {
 9644            let transaction = futures::select_biased! {
 9645                () = timeout => {
 9646                    log::warn!("timed out waiting for formatting");
 9647                    None
 9648                }
 9649                transaction = format.log_err().fuse() => transaction,
 9650            };
 9651
 9652            buffer
 9653                .update(&mut cx, |buffer, cx| {
 9654                    if let Some(transaction) = transaction {
 9655                        if !buffer.is_singleton() {
 9656                            buffer.push_transaction(&transaction.0, cx);
 9657                        }
 9658                    }
 9659
 9660                    cx.notify();
 9661                })
 9662                .ok();
 9663
 9664            Ok(())
 9665        })
 9666    }
 9667
 9668    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
 9669        if let Some(project) = self.project.clone() {
 9670            self.buffer.update(cx, |multi_buffer, cx| {
 9671                project.update(cx, |project, cx| {
 9672                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
 9673                });
 9674            })
 9675        }
 9676    }
 9677
 9678    fn cancel_language_server_work(
 9679        &mut self,
 9680        _: &CancelLanguageServerWork,
 9681        cx: &mut ViewContext<Self>,
 9682    ) {
 9683        if let Some(project) = self.project.clone() {
 9684            self.buffer.update(cx, |multi_buffer, cx| {
 9685                project.update(cx, |project, cx| {
 9686                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
 9687                });
 9688            })
 9689        }
 9690    }
 9691
 9692    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 9693        cx.show_character_palette();
 9694    }
 9695
 9696    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
 9697        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
 9698            let buffer = self.buffer.read(cx).snapshot(cx);
 9699            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
 9700            let is_valid = buffer
 9701                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
 9702                .any(|entry| {
 9703                    entry.diagnostic.is_primary
 9704                        && !entry.range.is_empty()
 9705                        && entry.range.start == primary_range_start
 9706                        && entry.diagnostic.message == active_diagnostics.primary_message
 9707                });
 9708
 9709            if is_valid != active_diagnostics.is_valid {
 9710                active_diagnostics.is_valid = is_valid;
 9711                let mut new_styles = HashMap::default();
 9712                for (block_id, diagnostic) in &active_diagnostics.blocks {
 9713                    new_styles.insert(
 9714                        *block_id,
 9715                        (
 9716                            None,
 9717                            diagnostic_block_renderer(diagnostic.clone(), is_valid),
 9718                        ),
 9719                    );
 9720                }
 9721                self.display_map.update(cx, |display_map, cx| {
 9722                    display_map.replace_blocks(new_styles, cx)
 9723                });
 9724            }
 9725        }
 9726    }
 9727
 9728    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
 9729        self.dismiss_diagnostics(cx);
 9730        let snapshot = self.snapshot(cx);
 9731        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
 9732            let buffer = self.buffer.read(cx).snapshot(cx);
 9733
 9734            let mut primary_range = None;
 9735            let mut primary_message = None;
 9736            let mut group_end = Point::zero();
 9737            let diagnostic_group = buffer
 9738                .diagnostic_group::<MultiBufferPoint>(group_id)
 9739                .filter_map(|entry| {
 9740                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
 9741                        && (entry.range.start.row == entry.range.end.row
 9742                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
 9743                    {
 9744                        return None;
 9745                    }
 9746                    if entry.range.end > group_end {
 9747                        group_end = entry.range.end;
 9748                    }
 9749                    if entry.diagnostic.is_primary {
 9750                        primary_range = Some(entry.range.clone());
 9751                        primary_message = Some(entry.diagnostic.message.clone());
 9752                    }
 9753                    Some(entry)
 9754                })
 9755                .collect::<Vec<_>>();
 9756            let primary_range = primary_range?;
 9757            let primary_message = primary_message?;
 9758            let primary_range =
 9759                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
 9760
 9761            let blocks = display_map
 9762                .insert_blocks(
 9763                    diagnostic_group.iter().map(|entry| {
 9764                        let diagnostic = entry.diagnostic.clone();
 9765                        let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
 9766                        BlockProperties {
 9767                            style: BlockStyle::Fixed,
 9768                            position: buffer.anchor_after(entry.range.start),
 9769                            height: message_height,
 9770                            render: diagnostic_block_renderer(diagnostic, true),
 9771                            disposition: BlockDisposition::Below,
 9772                        }
 9773                    }),
 9774                    cx,
 9775                )
 9776                .into_iter()
 9777                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
 9778                .collect();
 9779
 9780            Some(ActiveDiagnosticGroup {
 9781                primary_range,
 9782                primary_message,
 9783                group_id,
 9784                blocks,
 9785                is_valid: true,
 9786            })
 9787        });
 9788        self.active_diagnostics.is_some()
 9789    }
 9790
 9791    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
 9792        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
 9793            self.display_map.update(cx, |display_map, cx| {
 9794                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
 9795            });
 9796            cx.notify();
 9797        }
 9798    }
 9799
 9800    pub fn set_selections_from_remote(
 9801        &mut self,
 9802        selections: Vec<Selection<Anchor>>,
 9803        pending_selection: Option<Selection<Anchor>>,
 9804        cx: &mut ViewContext<Self>,
 9805    ) {
 9806        let old_cursor_position = self.selections.newest_anchor().head();
 9807        self.selections.change_with(cx, |s| {
 9808            s.select_anchors(selections);
 9809            if let Some(pending_selection) = pending_selection {
 9810                s.set_pending(pending_selection, SelectMode::Character);
 9811            } else {
 9812                s.clear_pending();
 9813            }
 9814        });
 9815        self.selections_did_change(false, &old_cursor_position, true, cx);
 9816    }
 9817
 9818    fn push_to_selection_history(&mut self) {
 9819        self.selection_history.push(SelectionHistoryEntry {
 9820            selections: self.selections.disjoint_anchors(),
 9821            select_next_state: self.select_next_state.clone(),
 9822            select_prev_state: self.select_prev_state.clone(),
 9823            add_selections_state: self.add_selections_state.clone(),
 9824        });
 9825    }
 9826
 9827    pub fn transact(
 9828        &mut self,
 9829        cx: &mut ViewContext<Self>,
 9830        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
 9831    ) -> Option<TransactionId> {
 9832        self.start_transaction_at(Instant::now(), cx);
 9833        update(self, cx);
 9834        self.end_transaction_at(Instant::now(), cx)
 9835    }
 9836
 9837    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
 9838        self.end_selection(cx);
 9839        if let Some(tx_id) = self
 9840            .buffer
 9841            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
 9842        {
 9843            self.selection_history
 9844                .insert_transaction(tx_id, self.selections.disjoint_anchors());
 9845            cx.emit(EditorEvent::TransactionBegun {
 9846                transaction_id: tx_id,
 9847            })
 9848        }
 9849    }
 9850
 9851    fn end_transaction_at(
 9852        &mut self,
 9853        now: Instant,
 9854        cx: &mut ViewContext<Self>,
 9855    ) -> Option<TransactionId> {
 9856        if let Some(transaction_id) = self
 9857            .buffer
 9858            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 9859        {
 9860            if let Some((_, end_selections)) =
 9861                self.selection_history.transaction_mut(transaction_id)
 9862            {
 9863                *end_selections = Some(self.selections.disjoint_anchors());
 9864            } else {
 9865                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
 9866            }
 9867
 9868            cx.emit(EditorEvent::Edited { transaction_id });
 9869            Some(transaction_id)
 9870        } else {
 9871            None
 9872        }
 9873    }
 9874
 9875    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
 9876        let mut fold_ranges = Vec::new();
 9877
 9878        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9879
 9880        let selections = self.selections.all_adjusted(cx);
 9881        for selection in selections {
 9882            let range = selection.range().sorted();
 9883            let buffer_start_row = range.start.row;
 9884
 9885            for row in (0..=range.end.row).rev() {
 9886                if let Some((foldable_range, fold_text)) =
 9887                    display_map.foldable_range(MultiBufferRow(row))
 9888                {
 9889                    if foldable_range.end.row >= buffer_start_row {
 9890                        fold_ranges.push((foldable_range, fold_text));
 9891                        if row <= range.start.row {
 9892                            break;
 9893                        }
 9894                    }
 9895                }
 9896            }
 9897        }
 9898
 9899        self.fold_ranges(fold_ranges, true, cx);
 9900    }
 9901
 9902    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
 9903        let buffer_row = fold_at.buffer_row;
 9904        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9905
 9906        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
 9907            let autoscroll = self
 9908                .selections
 9909                .all::<Point>(cx)
 9910                .iter()
 9911                .any(|selection| fold_range.overlaps(&selection.range()));
 9912
 9913            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
 9914        }
 9915    }
 9916
 9917    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
 9918        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9919        let buffer = &display_map.buffer_snapshot;
 9920        let selections = self.selections.all::<Point>(cx);
 9921        let ranges = selections
 9922            .iter()
 9923            .map(|s| {
 9924                let range = s.display_range(&display_map).sorted();
 9925                let mut start = range.start.to_point(&display_map);
 9926                let mut end = range.end.to_point(&display_map);
 9927                start.column = 0;
 9928                end.column = buffer.line_len(MultiBufferRow(end.row));
 9929                start..end
 9930            })
 9931            .collect::<Vec<_>>();
 9932
 9933        self.unfold_ranges(ranges, true, true, cx);
 9934    }
 9935
 9936    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
 9937        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9938
 9939        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
 9940            ..Point::new(
 9941                unfold_at.buffer_row.0,
 9942                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
 9943            );
 9944
 9945        let autoscroll = self
 9946            .selections
 9947            .all::<Point>(cx)
 9948            .iter()
 9949            .any(|selection| selection.range().overlaps(&intersection_range));
 9950
 9951        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
 9952    }
 9953
 9954    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
 9955        let selections = self.selections.all::<Point>(cx);
 9956        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9957        let line_mode = self.selections.line_mode;
 9958        let ranges = selections.into_iter().map(|s| {
 9959            if line_mode {
 9960                let start = Point::new(s.start.row, 0);
 9961                let end = Point::new(
 9962                    s.end.row,
 9963                    display_map
 9964                        .buffer_snapshot
 9965                        .line_len(MultiBufferRow(s.end.row)),
 9966                );
 9967                (start..end, display_map.fold_placeholder.clone())
 9968            } else {
 9969                (s.start..s.end, display_map.fold_placeholder.clone())
 9970            }
 9971        });
 9972        self.fold_ranges(ranges, true, cx);
 9973    }
 9974
 9975    pub fn fold_ranges<T: ToOffset + Clone>(
 9976        &mut self,
 9977        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
 9978        auto_scroll: bool,
 9979        cx: &mut ViewContext<Self>,
 9980    ) {
 9981        let mut fold_ranges = Vec::new();
 9982        let mut buffers_affected = HashMap::default();
 9983        let multi_buffer = self.buffer().read(cx);
 9984        for (fold_range, fold_text) in ranges {
 9985            if let Some((_, buffer, _)) =
 9986                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
 9987            {
 9988                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
 9989            };
 9990            fold_ranges.push((fold_range, fold_text));
 9991        }
 9992
 9993        let mut ranges = fold_ranges.into_iter().peekable();
 9994        if ranges.peek().is_some() {
 9995            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
 9996
 9997            if auto_scroll {
 9998                self.request_autoscroll(Autoscroll::fit(), cx);
 9999            }
10000
10001            for buffer in buffers_affected.into_values() {
10002                self.sync_expanded_diff_hunks(buffer, cx);
10003            }
10004
10005            cx.notify();
10006
10007            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10008                // Clear diagnostics block when folding a range that contains it.
10009                let snapshot = self.snapshot(cx);
10010                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10011                    drop(snapshot);
10012                    self.active_diagnostics = Some(active_diagnostics);
10013                    self.dismiss_diagnostics(cx);
10014                } else {
10015                    self.active_diagnostics = Some(active_diagnostics);
10016                }
10017            }
10018
10019            self.scrollbar_marker_state.dirty = true;
10020        }
10021    }
10022
10023    pub fn unfold_ranges<T: ToOffset + Clone>(
10024        &mut self,
10025        ranges: impl IntoIterator<Item = Range<T>>,
10026        inclusive: bool,
10027        auto_scroll: bool,
10028        cx: &mut ViewContext<Self>,
10029    ) {
10030        let mut unfold_ranges = Vec::new();
10031        let mut buffers_affected = HashMap::default();
10032        let multi_buffer = self.buffer().read(cx);
10033        for range in ranges {
10034            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10035                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10036            };
10037            unfold_ranges.push(range);
10038        }
10039
10040        let mut ranges = unfold_ranges.into_iter().peekable();
10041        if ranges.peek().is_some() {
10042            self.display_map
10043                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10044            if auto_scroll {
10045                self.request_autoscroll(Autoscroll::fit(), cx);
10046            }
10047
10048            for buffer in buffers_affected.into_values() {
10049                self.sync_expanded_diff_hunks(buffer, cx);
10050            }
10051
10052            cx.notify();
10053            self.scrollbar_marker_state.dirty = true;
10054            self.active_indent_guides_state.dirty = true;
10055        }
10056    }
10057
10058    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10059        if hovered != self.gutter_hovered {
10060            self.gutter_hovered = hovered;
10061            cx.notify();
10062        }
10063    }
10064
10065    pub fn insert_blocks(
10066        &mut self,
10067        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10068        autoscroll: Option<Autoscroll>,
10069        cx: &mut ViewContext<Self>,
10070    ) -> Vec<BlockId> {
10071        let blocks = self
10072            .display_map
10073            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10074        if let Some(autoscroll) = autoscroll {
10075            self.request_autoscroll(autoscroll, cx);
10076        }
10077        blocks
10078    }
10079
10080    pub fn replace_blocks(
10081        &mut self,
10082        blocks: HashMap<BlockId, (Option<u8>, RenderBlock)>,
10083        autoscroll: Option<Autoscroll>,
10084        cx: &mut ViewContext<Self>,
10085    ) {
10086        self.display_map
10087            .update(cx, |display_map, cx| display_map.replace_blocks(blocks, cx));
10088        if let Some(autoscroll) = autoscroll {
10089            self.request_autoscroll(autoscroll, cx);
10090        }
10091    }
10092
10093    pub fn remove_blocks(
10094        &mut self,
10095        block_ids: HashSet<BlockId>,
10096        autoscroll: Option<Autoscroll>,
10097        cx: &mut ViewContext<Self>,
10098    ) {
10099        self.display_map.update(cx, |display_map, cx| {
10100            display_map.remove_blocks(block_ids, cx)
10101        });
10102        if let Some(autoscroll) = autoscroll {
10103            self.request_autoscroll(autoscroll, cx);
10104        }
10105    }
10106
10107    pub fn row_for_block(
10108        &self,
10109        block_id: BlockId,
10110        cx: &mut ViewContext<Self>,
10111    ) -> Option<DisplayRow> {
10112        self.display_map
10113            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10114    }
10115
10116    pub fn insert_creases(
10117        &mut self,
10118        creases: impl IntoIterator<Item = Crease>,
10119        cx: &mut ViewContext<Self>,
10120    ) -> Vec<CreaseId> {
10121        self.display_map
10122            .update(cx, |map, cx| map.insert_creases(creases, cx))
10123    }
10124
10125    pub fn remove_creases(
10126        &mut self,
10127        ids: impl IntoIterator<Item = CreaseId>,
10128        cx: &mut ViewContext<Self>,
10129    ) {
10130        self.display_map
10131            .update(cx, |map, cx| map.remove_creases(ids, cx));
10132    }
10133
10134    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10135        self.display_map
10136            .update(cx, |map, cx| map.snapshot(cx))
10137            .longest_row()
10138    }
10139
10140    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10141        self.display_map
10142            .update(cx, |map, cx| map.snapshot(cx))
10143            .max_point()
10144    }
10145
10146    pub fn text(&self, cx: &AppContext) -> String {
10147        self.buffer.read(cx).read(cx).text()
10148    }
10149
10150    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10151        let text = self.text(cx);
10152        let text = text.trim();
10153
10154        if text.is_empty() {
10155            return None;
10156        }
10157
10158        Some(text.to_string())
10159    }
10160
10161    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10162        self.transact(cx, |this, cx| {
10163            this.buffer
10164                .read(cx)
10165                .as_singleton()
10166                .expect("you can only call set_text on editors for singleton buffers")
10167                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10168        });
10169    }
10170
10171    pub fn display_text(&self, cx: &mut AppContext) -> String {
10172        self.display_map
10173            .update(cx, |map, cx| map.snapshot(cx))
10174            .text()
10175    }
10176
10177    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10178        let mut wrap_guides = smallvec::smallvec![];
10179
10180        if self.show_wrap_guides == Some(false) {
10181            return wrap_guides;
10182        }
10183
10184        let settings = self.buffer.read(cx).settings_at(0, cx);
10185        if settings.show_wrap_guides {
10186            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10187                wrap_guides.push((soft_wrap as usize, true));
10188            }
10189            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10190        }
10191
10192        wrap_guides
10193    }
10194
10195    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10196        let settings = self.buffer.read(cx).settings_at(0, cx);
10197        let mode = self
10198            .soft_wrap_mode_override
10199            .unwrap_or_else(|| settings.soft_wrap);
10200        match mode {
10201            language_settings::SoftWrap::None => SoftWrap::None,
10202            language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10203            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10204            language_settings::SoftWrap::PreferredLineLength => {
10205                SoftWrap::Column(settings.preferred_line_length)
10206            }
10207        }
10208    }
10209
10210    pub fn set_soft_wrap_mode(
10211        &mut self,
10212        mode: language_settings::SoftWrap,
10213        cx: &mut ViewContext<Self>,
10214    ) {
10215        self.soft_wrap_mode_override = Some(mode);
10216        cx.notify();
10217    }
10218
10219    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10220        let rem_size = cx.rem_size();
10221        self.display_map.update(cx, |map, cx| {
10222            map.set_font(
10223                style.text.font(),
10224                style.text.font_size.to_pixels(rem_size),
10225                cx,
10226            )
10227        });
10228        self.style = Some(style);
10229    }
10230
10231    pub fn style(&self) -> Option<&EditorStyle> {
10232        self.style.as_ref()
10233    }
10234
10235    // Called by the element. This method is not designed to be called outside of the editor
10236    // element's layout code because it does not notify when rewrapping is computed synchronously.
10237    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10238        self.display_map
10239            .update(cx, |map, cx| map.set_wrap_width(width, cx))
10240    }
10241
10242    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10243        if self.soft_wrap_mode_override.is_some() {
10244            self.soft_wrap_mode_override.take();
10245        } else {
10246            let soft_wrap = match self.soft_wrap_mode(cx) {
10247                SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10248                SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10249                    language_settings::SoftWrap::PreferLine
10250                }
10251            };
10252            self.soft_wrap_mode_override = Some(soft_wrap);
10253        }
10254        cx.notify();
10255    }
10256
10257    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10258        let Some(workspace) = self.workspace() else {
10259            return;
10260        };
10261        let fs = workspace.read(cx).app_state().fs.clone();
10262        let current_show = TabBarSettings::get_global(cx).show;
10263        update_settings_file::<TabBarSettings>(fs, cx, move |setting| {
10264            setting.show = Some(!current_show);
10265        });
10266    }
10267
10268    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10269        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10270            self.buffer
10271                .read(cx)
10272                .settings_at(0, cx)
10273                .indent_guides
10274                .enabled
10275        });
10276        self.show_indent_guides = Some(!currently_enabled);
10277        cx.notify();
10278    }
10279
10280    fn should_show_indent_guides(&self) -> Option<bool> {
10281        self.show_indent_guides
10282    }
10283
10284    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10285        let mut editor_settings = EditorSettings::get_global(cx).clone();
10286        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10287        EditorSettings::override_global(editor_settings, cx);
10288    }
10289
10290    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10291        self.show_gutter = show_gutter;
10292        cx.notify();
10293    }
10294
10295    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10296        self.show_line_numbers = Some(show_line_numbers);
10297        cx.notify();
10298    }
10299
10300    pub fn set_show_git_diff_gutter(
10301        &mut self,
10302        show_git_diff_gutter: bool,
10303        cx: &mut ViewContext<Self>,
10304    ) {
10305        self.show_git_diff_gutter = Some(show_git_diff_gutter);
10306        cx.notify();
10307    }
10308
10309    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10310        self.show_code_actions = Some(show_code_actions);
10311        cx.notify();
10312    }
10313
10314    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10315        self.show_runnables = Some(show_runnables);
10316        cx.notify();
10317    }
10318
10319    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10320        self.show_wrap_guides = Some(show_wrap_guides);
10321        cx.notify();
10322    }
10323
10324    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10325        self.show_indent_guides = Some(show_indent_guides);
10326        cx.notify();
10327    }
10328
10329    pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
10330        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10331            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10332                cx.reveal_path(&file.abs_path(cx));
10333            }
10334        }
10335    }
10336
10337    pub fn copy_path(&mut self, _: &CopyPath, 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.abs_path(cx).to_str() {
10341                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10342                }
10343            }
10344        }
10345    }
10346
10347    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10348        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10349            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10350                if let Some(path) = file.path().to_str() {
10351                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10352                }
10353            }
10354        }
10355    }
10356
10357    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10358        self.show_git_blame_gutter = !self.show_git_blame_gutter;
10359
10360        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10361            self.start_git_blame(true, cx);
10362        }
10363
10364        cx.notify();
10365    }
10366
10367    pub fn toggle_git_blame_inline(
10368        &mut self,
10369        _: &ToggleGitBlameInline,
10370        cx: &mut ViewContext<Self>,
10371    ) {
10372        self.toggle_git_blame_inline_internal(true, cx);
10373        cx.notify();
10374    }
10375
10376    pub fn git_blame_inline_enabled(&self) -> bool {
10377        self.git_blame_inline_enabled
10378    }
10379
10380    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10381        self.show_selection_menu = self
10382            .show_selection_menu
10383            .map(|show_selections_menu| !show_selections_menu)
10384            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10385
10386        cx.notify();
10387    }
10388
10389    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10390        self.show_selection_menu
10391            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10392    }
10393
10394    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10395        if let Some(project) = self.project.as_ref() {
10396            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10397                return;
10398            };
10399
10400            if buffer.read(cx).file().is_none() {
10401                return;
10402            }
10403
10404            let focused = self.focus_handle(cx).contains_focused(cx);
10405
10406            let project = project.clone();
10407            let blame =
10408                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10409            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10410            self.blame = Some(blame);
10411        }
10412    }
10413
10414    fn toggle_git_blame_inline_internal(
10415        &mut self,
10416        user_triggered: bool,
10417        cx: &mut ViewContext<Self>,
10418    ) {
10419        if self.git_blame_inline_enabled {
10420            self.git_blame_inline_enabled = false;
10421            self.show_git_blame_inline = false;
10422            self.show_git_blame_inline_delay_task.take();
10423        } else {
10424            self.git_blame_inline_enabled = true;
10425            self.start_git_blame_inline(user_triggered, cx);
10426        }
10427
10428        cx.notify();
10429    }
10430
10431    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10432        self.start_git_blame(user_triggered, cx);
10433
10434        if ProjectSettings::get_global(cx)
10435            .git
10436            .inline_blame_delay()
10437            .is_some()
10438        {
10439            self.start_inline_blame_timer(cx);
10440        } else {
10441            self.show_git_blame_inline = true
10442        }
10443    }
10444
10445    pub fn blame(&self) -> Option<&Model<GitBlame>> {
10446        self.blame.as_ref()
10447    }
10448
10449    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10450        self.show_git_blame_gutter && self.has_blame_entries(cx)
10451    }
10452
10453    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10454        self.show_git_blame_inline
10455            && self.focus_handle.is_focused(cx)
10456            && !self.newest_selection_head_on_empty_line(cx)
10457            && self.has_blame_entries(cx)
10458    }
10459
10460    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10461        self.blame()
10462            .map_or(false, |blame| blame.read(cx).has_generated_entries())
10463    }
10464
10465    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10466        let cursor_anchor = self.selections.newest_anchor().head();
10467
10468        let snapshot = self.buffer.read(cx).snapshot(cx);
10469        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10470
10471        snapshot.line_len(buffer_row) == 0
10472    }
10473
10474    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10475        let (path, selection, repo) = maybe!({
10476            let project_handle = self.project.as_ref()?.clone();
10477            let project = project_handle.read(cx);
10478
10479            let selection = self.selections.newest::<Point>(cx);
10480            let selection_range = selection.range();
10481
10482            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10483                (buffer, selection_range.start.row..selection_range.end.row)
10484            } else {
10485                let buffer_ranges = self
10486                    .buffer()
10487                    .read(cx)
10488                    .range_to_buffer_ranges(selection_range, cx);
10489
10490                let (buffer, range, _) = if selection.reversed {
10491                    buffer_ranges.first()
10492                } else {
10493                    buffer_ranges.last()
10494                }?;
10495
10496                let snapshot = buffer.read(cx).snapshot();
10497                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10498                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
10499                (buffer.clone(), selection)
10500            };
10501
10502            let path = buffer
10503                .read(cx)
10504                .file()?
10505                .as_local()?
10506                .path()
10507                .to_str()?
10508                .to_string();
10509            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10510            Some((path, selection, repo))
10511        })
10512        .ok_or_else(|| anyhow!("unable to open git repository"))?;
10513
10514        const REMOTE_NAME: &str = "origin";
10515        let origin_url = repo
10516            .remote_url(REMOTE_NAME)
10517            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10518        let sha = repo
10519            .head_sha()
10520            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10521
10522        let (provider, remote) =
10523            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10524                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10525
10526        Ok(provider.build_permalink(
10527            remote,
10528            BuildPermalinkParams {
10529                sha: &sha,
10530                path: &path,
10531                selection: Some(selection),
10532            },
10533        ))
10534    }
10535
10536    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10537        let permalink = self.get_permalink_to_line(cx);
10538
10539        match permalink {
10540            Ok(permalink) => {
10541                cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
10542            }
10543            Err(err) => {
10544                let message = format!("Failed to copy permalink: {err}");
10545
10546                Err::<(), anyhow::Error>(err).log_err();
10547
10548                if let Some(workspace) = self.workspace() {
10549                    workspace.update(cx, |workspace, cx| {
10550                        struct CopyPermalinkToLine;
10551
10552                        workspace.show_toast(
10553                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10554                            cx,
10555                        )
10556                    })
10557                }
10558            }
10559        }
10560    }
10561
10562    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10563        let permalink = self.get_permalink_to_line(cx);
10564
10565        match permalink {
10566            Ok(permalink) => {
10567                cx.open_url(permalink.as_ref());
10568            }
10569            Err(err) => {
10570                let message = format!("Failed to open permalink: {err}");
10571
10572                Err::<(), anyhow::Error>(err).log_err();
10573
10574                if let Some(workspace) = self.workspace() {
10575                    workspace.update(cx, |workspace, cx| {
10576                        struct OpenPermalinkToLine;
10577
10578                        workspace.show_toast(
10579                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10580                            cx,
10581                        )
10582                    })
10583                }
10584            }
10585        }
10586    }
10587
10588    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10589    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10590    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10591    pub fn highlight_rows<T: 'static>(
10592        &mut self,
10593        rows: RangeInclusive<Anchor>,
10594        color: Option<Hsla>,
10595        should_autoscroll: bool,
10596        cx: &mut ViewContext<Self>,
10597    ) {
10598        let snapshot = self.buffer().read(cx).snapshot(cx);
10599        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10600        let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10601            highlight
10602                .range
10603                .start()
10604                .cmp(&rows.start(), &snapshot)
10605                .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10606        });
10607        match (color, existing_highlight_index) {
10608            (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10609                ix,
10610                RowHighlight {
10611                    index: post_inc(&mut self.highlight_order),
10612                    range: rows,
10613                    should_autoscroll,
10614                    color,
10615                },
10616            ),
10617            (None, Ok(i)) => {
10618                row_highlights.remove(i);
10619            }
10620        }
10621    }
10622
10623    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10624    pub fn clear_row_highlights<T: 'static>(&mut self) {
10625        self.highlighted_rows.remove(&TypeId::of::<T>());
10626    }
10627
10628    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10629    pub fn highlighted_rows<T: 'static>(
10630        &self,
10631    ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10632        Some(
10633            self.highlighted_rows
10634                .get(&TypeId::of::<T>())?
10635                .iter()
10636                .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10637        )
10638    }
10639
10640    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10641    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10642    /// Allows to ignore certain kinds of highlights.
10643    pub fn highlighted_display_rows(
10644        &mut self,
10645        cx: &mut WindowContext,
10646    ) -> BTreeMap<DisplayRow, Hsla> {
10647        let snapshot = self.snapshot(cx);
10648        let mut used_highlight_orders = HashMap::default();
10649        self.highlighted_rows
10650            .iter()
10651            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10652            .fold(
10653                BTreeMap::<DisplayRow, Hsla>::new(),
10654                |mut unique_rows, highlight| {
10655                    let start_row = highlight.range.start().to_display_point(&snapshot).row();
10656                    let end_row = highlight.range.end().to_display_point(&snapshot).row();
10657                    for row in start_row.0..=end_row.0 {
10658                        let used_index =
10659                            used_highlight_orders.entry(row).or_insert(highlight.index);
10660                        if highlight.index >= *used_index {
10661                            *used_index = highlight.index;
10662                            match highlight.color {
10663                                Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10664                                None => unique_rows.remove(&DisplayRow(row)),
10665                            };
10666                        }
10667                    }
10668                    unique_rows
10669                },
10670            )
10671    }
10672
10673    pub fn highlighted_display_row_for_autoscroll(
10674        &self,
10675        snapshot: &DisplaySnapshot,
10676    ) -> Option<DisplayRow> {
10677        self.highlighted_rows
10678            .values()
10679            .flat_map(|highlighted_rows| highlighted_rows.iter())
10680            .filter_map(|highlight| {
10681                if highlight.color.is_none() || !highlight.should_autoscroll {
10682                    return None;
10683                }
10684                Some(highlight.range.start().to_display_point(&snapshot).row())
10685            })
10686            .min()
10687    }
10688
10689    pub fn set_search_within_ranges(
10690        &mut self,
10691        ranges: &[Range<Anchor>],
10692        cx: &mut ViewContext<Self>,
10693    ) {
10694        self.highlight_background::<SearchWithinRange>(
10695            ranges,
10696            |colors| colors.editor_document_highlight_read_background,
10697            cx,
10698        )
10699    }
10700
10701    pub fn set_breadcrumb_header(&mut self, new_header: String) {
10702        self.breadcrumb_header = Some(new_header);
10703    }
10704
10705    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10706        self.clear_background_highlights::<SearchWithinRange>(cx);
10707    }
10708
10709    pub fn highlight_background<T: 'static>(
10710        &mut self,
10711        ranges: &[Range<Anchor>],
10712        color_fetcher: fn(&ThemeColors) -> Hsla,
10713        cx: &mut ViewContext<Self>,
10714    ) {
10715        let snapshot = self.snapshot(cx);
10716        // this is to try and catch a panic sooner
10717        for range in ranges {
10718            snapshot
10719                .buffer_snapshot
10720                .summary_for_anchor::<usize>(&range.start);
10721            snapshot
10722                .buffer_snapshot
10723                .summary_for_anchor::<usize>(&range.end);
10724        }
10725
10726        self.background_highlights
10727            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10728        self.scrollbar_marker_state.dirty = true;
10729        cx.notify();
10730    }
10731
10732    pub fn clear_background_highlights<T: 'static>(
10733        &mut self,
10734        cx: &mut ViewContext<Self>,
10735    ) -> Option<BackgroundHighlight> {
10736        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10737        if !text_highlights.1.is_empty() {
10738            self.scrollbar_marker_state.dirty = true;
10739            cx.notify();
10740        }
10741        Some(text_highlights)
10742    }
10743
10744    pub fn highlight_gutter<T: 'static>(
10745        &mut self,
10746        ranges: &[Range<Anchor>],
10747        color_fetcher: fn(&AppContext) -> Hsla,
10748        cx: &mut ViewContext<Self>,
10749    ) {
10750        self.gutter_highlights
10751            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10752        cx.notify();
10753    }
10754
10755    pub fn clear_gutter_highlights<T: 'static>(
10756        &mut self,
10757        cx: &mut ViewContext<Self>,
10758    ) -> Option<GutterHighlight> {
10759        cx.notify();
10760        self.gutter_highlights.remove(&TypeId::of::<T>())
10761    }
10762
10763    #[cfg(feature = "test-support")]
10764    pub fn all_text_background_highlights(
10765        &mut self,
10766        cx: &mut ViewContext<Self>,
10767    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10768        let snapshot = self.snapshot(cx);
10769        let buffer = &snapshot.buffer_snapshot;
10770        let start = buffer.anchor_before(0);
10771        let end = buffer.anchor_after(buffer.len());
10772        let theme = cx.theme().colors();
10773        self.background_highlights_in_range(start..end, &snapshot, theme)
10774    }
10775
10776    #[cfg(feature = "test-support")]
10777    pub fn search_background_highlights(
10778        &mut self,
10779        cx: &mut ViewContext<Self>,
10780    ) -> Vec<Range<Point>> {
10781        let snapshot = self.buffer().read(cx).snapshot(cx);
10782
10783        let highlights = self
10784            .background_highlights
10785            .get(&TypeId::of::<items::BufferSearchHighlights>());
10786
10787        if let Some((_color, ranges)) = highlights {
10788            ranges
10789                .iter()
10790                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
10791                .collect_vec()
10792        } else {
10793            vec![]
10794        }
10795    }
10796
10797    fn document_highlights_for_position<'a>(
10798        &'a self,
10799        position: Anchor,
10800        buffer: &'a MultiBufferSnapshot,
10801    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
10802        let read_highlights = self
10803            .background_highlights
10804            .get(&TypeId::of::<DocumentHighlightRead>())
10805            .map(|h| &h.1);
10806        let write_highlights = self
10807            .background_highlights
10808            .get(&TypeId::of::<DocumentHighlightWrite>())
10809            .map(|h| &h.1);
10810        let left_position = position.bias_left(buffer);
10811        let right_position = position.bias_right(buffer);
10812        read_highlights
10813            .into_iter()
10814            .chain(write_highlights)
10815            .flat_map(move |ranges| {
10816                let start_ix = match ranges.binary_search_by(|probe| {
10817                    let cmp = probe.end.cmp(&left_position, buffer);
10818                    if cmp.is_ge() {
10819                        Ordering::Greater
10820                    } else {
10821                        Ordering::Less
10822                    }
10823                }) {
10824                    Ok(i) | Err(i) => i,
10825                };
10826
10827                ranges[start_ix..]
10828                    .iter()
10829                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
10830            })
10831    }
10832
10833    pub fn has_background_highlights<T: 'static>(&self) -> bool {
10834        self.background_highlights
10835            .get(&TypeId::of::<T>())
10836            .map_or(false, |(_, highlights)| !highlights.is_empty())
10837    }
10838
10839    pub fn background_highlights_in_range(
10840        &self,
10841        search_range: Range<Anchor>,
10842        display_snapshot: &DisplaySnapshot,
10843        theme: &ThemeColors,
10844    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10845        let mut results = Vec::new();
10846        for (color_fetcher, ranges) in self.background_highlights.values() {
10847            let color = color_fetcher(theme);
10848            let start_ix = match ranges.binary_search_by(|probe| {
10849                let cmp = probe
10850                    .end
10851                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10852                if cmp.is_gt() {
10853                    Ordering::Greater
10854                } else {
10855                    Ordering::Less
10856                }
10857            }) {
10858                Ok(i) | Err(i) => i,
10859            };
10860            for range in &ranges[start_ix..] {
10861                if range
10862                    .start
10863                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10864                    .is_ge()
10865                {
10866                    break;
10867                }
10868
10869                let start = range.start.to_display_point(&display_snapshot);
10870                let end = range.end.to_display_point(&display_snapshot);
10871                results.push((start..end, color))
10872            }
10873        }
10874        results
10875    }
10876
10877    pub fn background_highlight_row_ranges<T: 'static>(
10878        &self,
10879        search_range: Range<Anchor>,
10880        display_snapshot: &DisplaySnapshot,
10881        count: usize,
10882    ) -> Vec<RangeInclusive<DisplayPoint>> {
10883        let mut results = Vec::new();
10884        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
10885            return vec![];
10886        };
10887
10888        let start_ix = match ranges.binary_search_by(|probe| {
10889            let cmp = probe
10890                .end
10891                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10892            if cmp.is_gt() {
10893                Ordering::Greater
10894            } else {
10895                Ordering::Less
10896            }
10897        }) {
10898            Ok(i) | Err(i) => i,
10899        };
10900        let mut push_region = |start: Option<Point>, end: Option<Point>| {
10901            if let (Some(start_display), Some(end_display)) = (start, end) {
10902                results.push(
10903                    start_display.to_display_point(display_snapshot)
10904                        ..=end_display.to_display_point(display_snapshot),
10905                );
10906            }
10907        };
10908        let mut start_row: Option<Point> = None;
10909        let mut end_row: Option<Point> = None;
10910        if ranges.len() > count {
10911            return Vec::new();
10912        }
10913        for range in &ranges[start_ix..] {
10914            if range
10915                .start
10916                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10917                .is_ge()
10918            {
10919                break;
10920            }
10921            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
10922            if let Some(current_row) = &end_row {
10923                if end.row == current_row.row {
10924                    continue;
10925                }
10926            }
10927            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
10928            if start_row.is_none() {
10929                assert_eq!(end_row, None);
10930                start_row = Some(start);
10931                end_row = Some(end);
10932                continue;
10933            }
10934            if let Some(current_end) = end_row.as_mut() {
10935                if start.row > current_end.row + 1 {
10936                    push_region(start_row, end_row);
10937                    start_row = Some(start);
10938                    end_row = Some(end);
10939                } else {
10940                    // Merge two hunks.
10941                    *current_end = end;
10942                }
10943            } else {
10944                unreachable!();
10945            }
10946        }
10947        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
10948        push_region(start_row, end_row);
10949        results
10950    }
10951
10952    pub fn gutter_highlights_in_range(
10953        &self,
10954        search_range: Range<Anchor>,
10955        display_snapshot: &DisplaySnapshot,
10956        cx: &AppContext,
10957    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10958        let mut results = Vec::new();
10959        for (color_fetcher, ranges) in self.gutter_highlights.values() {
10960            let color = color_fetcher(cx);
10961            let start_ix = match ranges.binary_search_by(|probe| {
10962                let cmp = probe
10963                    .end
10964                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10965                if cmp.is_gt() {
10966                    Ordering::Greater
10967                } else {
10968                    Ordering::Less
10969                }
10970            }) {
10971                Ok(i) | Err(i) => i,
10972            };
10973            for range in &ranges[start_ix..] {
10974                if range
10975                    .start
10976                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10977                    .is_ge()
10978                {
10979                    break;
10980                }
10981
10982                let start = range.start.to_display_point(&display_snapshot);
10983                let end = range.end.to_display_point(&display_snapshot);
10984                results.push((start..end, color))
10985            }
10986        }
10987        results
10988    }
10989
10990    /// Get the text ranges corresponding to the redaction query
10991    pub fn redacted_ranges(
10992        &self,
10993        search_range: Range<Anchor>,
10994        display_snapshot: &DisplaySnapshot,
10995        cx: &WindowContext,
10996    ) -> Vec<Range<DisplayPoint>> {
10997        display_snapshot
10998            .buffer_snapshot
10999            .redacted_ranges(search_range, |file| {
11000                if let Some(file) = file {
11001                    file.is_private()
11002                        && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11003                } else {
11004                    false
11005                }
11006            })
11007            .map(|range| {
11008                range.start.to_display_point(display_snapshot)
11009                    ..range.end.to_display_point(display_snapshot)
11010            })
11011            .collect()
11012    }
11013
11014    pub fn highlight_text<T: 'static>(
11015        &mut self,
11016        ranges: Vec<Range<Anchor>>,
11017        style: HighlightStyle,
11018        cx: &mut ViewContext<Self>,
11019    ) {
11020        self.display_map.update(cx, |map, _| {
11021            map.highlight_text(TypeId::of::<T>(), ranges, style)
11022        });
11023        cx.notify();
11024    }
11025
11026    pub(crate) fn highlight_inlays<T: 'static>(
11027        &mut self,
11028        highlights: Vec<InlayHighlight>,
11029        style: HighlightStyle,
11030        cx: &mut ViewContext<Self>,
11031    ) {
11032        self.display_map.update(cx, |map, _| {
11033            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11034        });
11035        cx.notify();
11036    }
11037
11038    pub fn text_highlights<'a, T: 'static>(
11039        &'a self,
11040        cx: &'a AppContext,
11041    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11042        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11043    }
11044
11045    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11046        let cleared = self
11047            .display_map
11048            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11049        if cleared {
11050            cx.notify();
11051        }
11052    }
11053
11054    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11055        (self.read_only(cx) || self.blink_manager.read(cx).visible())
11056            && self.focus_handle.is_focused(cx)
11057    }
11058
11059    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11060        self.show_cursor_when_unfocused = is_enabled;
11061        cx.notify();
11062    }
11063
11064    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11065        cx.notify();
11066    }
11067
11068    fn on_buffer_event(
11069        &mut self,
11070        multibuffer: Model<MultiBuffer>,
11071        event: &multi_buffer::Event,
11072        cx: &mut ViewContext<Self>,
11073    ) {
11074        match event {
11075            multi_buffer::Event::Edited {
11076                singleton_buffer_edited,
11077            } => {
11078                self.scrollbar_marker_state.dirty = true;
11079                self.active_indent_guides_state.dirty = true;
11080                self.refresh_active_diagnostics(cx);
11081                self.refresh_code_actions(cx);
11082                if self.has_active_inline_completion(cx) {
11083                    self.update_visible_inline_completion(cx);
11084                }
11085                cx.emit(EditorEvent::BufferEdited);
11086                cx.emit(SearchEvent::MatchesInvalidated);
11087                if *singleton_buffer_edited {
11088                    if let Some(project) = &self.project {
11089                        let project = project.read(cx);
11090                        let languages_affected = multibuffer
11091                            .read(cx)
11092                            .all_buffers()
11093                            .into_iter()
11094                            .filter_map(|buffer| {
11095                                let buffer = buffer.read(cx);
11096                                let language = buffer.language()?;
11097                                if project.is_local()
11098                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
11099                                {
11100                                    None
11101                                } else {
11102                                    Some(language)
11103                                }
11104                            })
11105                            .cloned()
11106                            .collect::<HashSet<_>>();
11107                        if !languages_affected.is_empty() {
11108                            self.refresh_inlay_hints(
11109                                InlayHintRefreshReason::BufferEdited(languages_affected),
11110                                cx,
11111                            );
11112                        }
11113                    }
11114                }
11115
11116                let Some(project) = &self.project else { return };
11117                let telemetry = project.read(cx).client().telemetry().clone();
11118                refresh_linked_ranges(self, cx);
11119                telemetry.log_edit_event("editor");
11120            }
11121            multi_buffer::Event::ExcerptsAdded {
11122                buffer,
11123                predecessor,
11124                excerpts,
11125            } => {
11126                self.tasks_update_task = Some(self.refresh_runnables(cx));
11127                cx.emit(EditorEvent::ExcerptsAdded {
11128                    buffer: buffer.clone(),
11129                    predecessor: *predecessor,
11130                    excerpts: excerpts.clone(),
11131                });
11132                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11133            }
11134            multi_buffer::Event::ExcerptsRemoved { ids } => {
11135                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11136                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11137            }
11138            multi_buffer::Event::ExcerptsEdited { ids } => {
11139                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11140            }
11141            multi_buffer::Event::ExcerptsExpanded { ids } => {
11142                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11143            }
11144            multi_buffer::Event::Reparsed(buffer_id) => {
11145                self.tasks_update_task = Some(self.refresh_runnables(cx));
11146
11147                cx.emit(EditorEvent::Reparsed(*buffer_id));
11148            }
11149            multi_buffer::Event::LanguageChanged(buffer_id) => {
11150                linked_editing_ranges::refresh_linked_ranges(self, cx);
11151                cx.emit(EditorEvent::Reparsed(*buffer_id));
11152                cx.notify();
11153            }
11154            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11155            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11156            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11157                cx.emit(EditorEvent::TitleChanged)
11158            }
11159            multi_buffer::Event::DiffBaseChanged => {
11160                self.scrollbar_marker_state.dirty = true;
11161                cx.emit(EditorEvent::DiffBaseChanged);
11162                cx.notify();
11163            }
11164            multi_buffer::Event::DiffUpdated { buffer } => {
11165                self.sync_expanded_diff_hunks(buffer.clone(), cx);
11166                cx.notify();
11167            }
11168            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11169            multi_buffer::Event::DiagnosticsUpdated => {
11170                self.refresh_active_diagnostics(cx);
11171                self.scrollbar_marker_state.dirty = true;
11172                cx.notify();
11173            }
11174            _ => {}
11175        };
11176    }
11177
11178    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11179        cx.notify();
11180    }
11181
11182    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11183        self.tasks_update_task = Some(self.refresh_runnables(cx));
11184        self.refresh_inline_completion(true, cx);
11185        self.refresh_inlay_hints(
11186            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11187                self.selections.newest_anchor().head(),
11188                &self.buffer.read(cx).snapshot(cx),
11189                cx,
11190            )),
11191            cx,
11192        );
11193        let editor_settings = EditorSettings::get_global(cx);
11194        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11195        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11196
11197        if self.mode == EditorMode::Full {
11198            let inline_blame_enabled = ProjectSettings::get_global(cx).git.inline_blame_enabled();
11199            if self.git_blame_inline_enabled != inline_blame_enabled {
11200                self.toggle_git_blame_inline_internal(false, cx);
11201            }
11202        }
11203
11204        cx.notify();
11205    }
11206
11207    pub fn set_searchable(&mut self, searchable: bool) {
11208        self.searchable = searchable;
11209    }
11210
11211    pub fn searchable(&self) -> bool {
11212        self.searchable
11213    }
11214
11215    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11216        self.open_excerpts_common(true, cx)
11217    }
11218
11219    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11220        self.open_excerpts_common(false, cx)
11221    }
11222
11223    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11224        let buffer = self.buffer.read(cx);
11225        if buffer.is_singleton() {
11226            cx.propagate();
11227            return;
11228        }
11229
11230        let Some(workspace) = self.workspace() else {
11231            cx.propagate();
11232            return;
11233        };
11234
11235        let mut new_selections_by_buffer = HashMap::default();
11236        for selection in self.selections.all::<usize>(cx) {
11237            for (buffer, mut range, _) in
11238                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11239            {
11240                if selection.reversed {
11241                    mem::swap(&mut range.start, &mut range.end);
11242                }
11243                new_selections_by_buffer
11244                    .entry(buffer)
11245                    .or_insert(Vec::new())
11246                    .push(range)
11247            }
11248        }
11249
11250        // We defer the pane interaction because we ourselves are a workspace item
11251        // and activating a new item causes the pane to call a method on us reentrantly,
11252        // which panics if we're on the stack.
11253        cx.window_context().defer(move |cx| {
11254            workspace.update(cx, |workspace, cx| {
11255                let pane = if split {
11256                    workspace.adjacent_pane(cx)
11257                } else {
11258                    workspace.active_pane().clone()
11259                };
11260
11261                for (buffer, ranges) in new_selections_by_buffer {
11262                    let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
11263                    editor.update(cx, |editor, cx| {
11264                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11265                            s.select_ranges(ranges);
11266                        });
11267                    });
11268                }
11269            })
11270        });
11271    }
11272
11273    fn jump(
11274        &mut self,
11275        path: ProjectPath,
11276        position: Point,
11277        anchor: language::Anchor,
11278        offset_from_top: u32,
11279        cx: &mut ViewContext<Self>,
11280    ) {
11281        let workspace = self.workspace();
11282        cx.spawn(|_, mut cx| async move {
11283            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11284            let editor = workspace.update(&mut cx, |workspace, cx| {
11285                // Reset the preview item id before opening the new item
11286                workspace.active_pane().update(cx, |pane, cx| {
11287                    pane.set_preview_item_id(None, cx);
11288                });
11289                workspace.open_path_preview(path, None, true, true, cx)
11290            })?;
11291            let editor = editor
11292                .await?
11293                .downcast::<Editor>()
11294                .ok_or_else(|| anyhow!("opened item was not an editor"))?
11295                .downgrade();
11296            editor.update(&mut cx, |editor, cx| {
11297                let buffer = editor
11298                    .buffer()
11299                    .read(cx)
11300                    .as_singleton()
11301                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11302                let buffer = buffer.read(cx);
11303                let cursor = if buffer.can_resolve(&anchor) {
11304                    language::ToPoint::to_point(&anchor, buffer)
11305                } else {
11306                    buffer.clip_point(position, Bias::Left)
11307                };
11308
11309                let nav_history = editor.nav_history.take();
11310                editor.change_selections(
11311                    Some(Autoscroll::top_relative(offset_from_top as usize)),
11312                    cx,
11313                    |s| {
11314                        s.select_ranges([cursor..cursor]);
11315                    },
11316                );
11317                editor.nav_history = nav_history;
11318
11319                anyhow::Ok(())
11320            })??;
11321
11322            anyhow::Ok(())
11323        })
11324        .detach_and_log_err(cx);
11325    }
11326
11327    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11328        let snapshot = self.buffer.read(cx).read(cx);
11329        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11330        Some(
11331            ranges
11332                .iter()
11333                .map(move |range| {
11334                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11335                })
11336                .collect(),
11337        )
11338    }
11339
11340    fn selection_replacement_ranges(
11341        &self,
11342        range: Range<OffsetUtf16>,
11343        cx: &AppContext,
11344    ) -> Vec<Range<OffsetUtf16>> {
11345        let selections = self.selections.all::<OffsetUtf16>(cx);
11346        let newest_selection = selections
11347            .iter()
11348            .max_by_key(|selection| selection.id)
11349            .unwrap();
11350        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11351        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11352        let snapshot = self.buffer.read(cx).read(cx);
11353        selections
11354            .into_iter()
11355            .map(|mut selection| {
11356                selection.start.0 =
11357                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
11358                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11359                snapshot.clip_offset_utf16(selection.start, Bias::Left)
11360                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11361            })
11362            .collect()
11363    }
11364
11365    fn report_editor_event(
11366        &self,
11367        operation: &'static str,
11368        file_extension: Option<String>,
11369        cx: &AppContext,
11370    ) {
11371        if cfg!(any(test, feature = "test-support")) {
11372            return;
11373        }
11374
11375        let Some(project) = &self.project else { return };
11376
11377        // If None, we are in a file without an extension
11378        let file = self
11379            .buffer
11380            .read(cx)
11381            .as_singleton()
11382            .and_then(|b| b.read(cx).file());
11383        let file_extension = file_extension.or(file
11384            .as_ref()
11385            .and_then(|file| Path::new(file.file_name(cx)).extension())
11386            .and_then(|e| e.to_str())
11387            .map(|a| a.to_string()));
11388
11389        let vim_mode = cx
11390            .global::<SettingsStore>()
11391            .raw_user_settings()
11392            .get("vim_mode")
11393            == Some(&serde_json::Value::Bool(true));
11394
11395        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11396            == language::language_settings::InlineCompletionProvider::Copilot;
11397        let copilot_enabled_for_language = self
11398            .buffer
11399            .read(cx)
11400            .settings_at(0, cx)
11401            .show_inline_completions;
11402
11403        let telemetry = project.read(cx).client().telemetry().clone();
11404        telemetry.report_editor_event(
11405            file_extension,
11406            vim_mode,
11407            operation,
11408            copilot_enabled,
11409            copilot_enabled_for_language,
11410        )
11411    }
11412
11413    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11414    /// with each line being an array of {text, highlight} objects.
11415    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11416        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11417            return;
11418        };
11419
11420        #[derive(Serialize)]
11421        struct Chunk<'a> {
11422            text: String,
11423            highlight: Option<&'a str>,
11424        }
11425
11426        let snapshot = buffer.read(cx).snapshot();
11427        let range = self
11428            .selected_text_range(cx)
11429            .and_then(|selected_range| {
11430                if selected_range.is_empty() {
11431                    None
11432                } else {
11433                    Some(selected_range)
11434                }
11435            })
11436            .unwrap_or_else(|| 0..snapshot.len());
11437
11438        let chunks = snapshot.chunks(range, true);
11439        let mut lines = Vec::new();
11440        let mut line: VecDeque<Chunk> = VecDeque::new();
11441
11442        let Some(style) = self.style.as_ref() else {
11443            return;
11444        };
11445
11446        for chunk in chunks {
11447            let highlight = chunk
11448                .syntax_highlight_id
11449                .and_then(|id| id.name(&style.syntax));
11450            let mut chunk_lines = chunk.text.split('\n').peekable();
11451            while let Some(text) = chunk_lines.next() {
11452                let mut merged_with_last_token = false;
11453                if let Some(last_token) = line.back_mut() {
11454                    if last_token.highlight == highlight {
11455                        last_token.text.push_str(text);
11456                        merged_with_last_token = true;
11457                    }
11458                }
11459
11460                if !merged_with_last_token {
11461                    line.push_back(Chunk {
11462                        text: text.into(),
11463                        highlight,
11464                    });
11465                }
11466
11467                if chunk_lines.peek().is_some() {
11468                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
11469                        line.pop_front();
11470                    }
11471                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
11472                        line.pop_back();
11473                    }
11474
11475                    lines.push(mem::take(&mut line));
11476                }
11477            }
11478        }
11479
11480        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11481            return;
11482        };
11483        cx.write_to_clipboard(ClipboardItem::new(lines));
11484    }
11485
11486    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11487        &self.inlay_hint_cache
11488    }
11489
11490    pub fn replay_insert_event(
11491        &mut self,
11492        text: &str,
11493        relative_utf16_range: Option<Range<isize>>,
11494        cx: &mut ViewContext<Self>,
11495    ) {
11496        if !self.input_enabled {
11497            cx.emit(EditorEvent::InputIgnored { text: text.into() });
11498            return;
11499        }
11500        if let Some(relative_utf16_range) = relative_utf16_range {
11501            let selections = self.selections.all::<OffsetUtf16>(cx);
11502            self.change_selections(None, cx, |s| {
11503                let new_ranges = selections.into_iter().map(|range| {
11504                    let start = OffsetUtf16(
11505                        range
11506                            .head()
11507                            .0
11508                            .saturating_add_signed(relative_utf16_range.start),
11509                    );
11510                    let end = OffsetUtf16(
11511                        range
11512                            .head()
11513                            .0
11514                            .saturating_add_signed(relative_utf16_range.end),
11515                    );
11516                    start..end
11517                });
11518                s.select_ranges(new_ranges);
11519            });
11520        }
11521
11522        self.handle_input(text, cx);
11523    }
11524
11525    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11526        let Some(project) = self.project.as_ref() else {
11527            return false;
11528        };
11529        let project = project.read(cx);
11530
11531        let mut supports = false;
11532        self.buffer().read(cx).for_each_buffer(|buffer| {
11533            if !supports {
11534                supports = project
11535                    .language_servers_for_buffer(buffer.read(cx), cx)
11536                    .any(
11537                        |(_, server)| match server.capabilities().inlay_hint_provider {
11538                            Some(lsp::OneOf::Left(enabled)) => enabled,
11539                            Some(lsp::OneOf::Right(_)) => true,
11540                            None => false,
11541                        },
11542                    )
11543            }
11544        });
11545        supports
11546    }
11547
11548    pub fn focus(&self, cx: &mut WindowContext) {
11549        cx.focus(&self.focus_handle)
11550    }
11551
11552    pub fn is_focused(&self, cx: &WindowContext) -> bool {
11553        self.focus_handle.is_focused(cx)
11554    }
11555
11556    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11557        cx.emit(EditorEvent::Focused);
11558
11559        if let Some(descendant) = self
11560            .last_focused_descendant
11561            .take()
11562            .and_then(|descendant| descendant.upgrade())
11563        {
11564            cx.focus(&descendant);
11565        } else {
11566            if let Some(blame) = self.blame.as_ref() {
11567                blame.update(cx, GitBlame::focus)
11568            }
11569
11570            self.blink_manager.update(cx, BlinkManager::enable);
11571            self.show_cursor_names(cx);
11572            self.buffer.update(cx, |buffer, cx| {
11573                buffer.finalize_last_transaction(cx);
11574                if self.leader_peer_id.is_none() {
11575                    buffer.set_active_selections(
11576                        &self.selections.disjoint_anchors(),
11577                        self.selections.line_mode,
11578                        self.cursor_shape,
11579                        cx,
11580                    );
11581                }
11582            });
11583        }
11584    }
11585
11586    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11587        if event.blurred != self.focus_handle {
11588            self.last_focused_descendant = Some(event.blurred);
11589        }
11590    }
11591
11592    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11593        self.blink_manager.update(cx, BlinkManager::disable);
11594        self.buffer
11595            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11596
11597        if let Some(blame) = self.blame.as_ref() {
11598            blame.update(cx, GitBlame::blur)
11599        }
11600        self.hide_context_menu(cx);
11601        hide_hover(self, cx);
11602        cx.emit(EditorEvent::Blurred);
11603        cx.notify();
11604    }
11605
11606    pub fn register_action<A: Action>(
11607        &mut self,
11608        listener: impl Fn(&A, &mut WindowContext) + 'static,
11609    ) -> Subscription {
11610        let id = self.next_editor_action_id.post_inc();
11611        let listener = Arc::new(listener);
11612        self.editor_actions.borrow_mut().insert(
11613            id,
11614            Box::new(move |cx| {
11615                let _view = cx.view().clone();
11616                let cx = cx.window_context();
11617                let listener = listener.clone();
11618                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11619                    let action = action.downcast_ref().unwrap();
11620                    if phase == DispatchPhase::Bubble {
11621                        listener(action, cx)
11622                    }
11623                })
11624            }),
11625        );
11626
11627        let editor_actions = self.editor_actions.clone();
11628        Subscription::new(move || {
11629            editor_actions.borrow_mut().remove(&id);
11630        })
11631    }
11632
11633    pub fn file_header_size(&self) -> u8 {
11634        self.file_header_size
11635    }
11636}
11637
11638fn hunks_for_selections(
11639    multi_buffer_snapshot: &MultiBufferSnapshot,
11640    selections: &[Selection<Anchor>],
11641) -> Vec<DiffHunk<MultiBufferRow>> {
11642    let mut hunks = Vec::with_capacity(selections.len());
11643    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11644        HashMap::default();
11645    let buffer_rows_for_selections = selections.iter().map(|selection| {
11646        let head = selection.head();
11647        let tail = selection.tail();
11648        let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11649        let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11650        if start > end {
11651            end..start
11652        } else {
11653            start..end
11654        }
11655    });
11656
11657    for selected_multi_buffer_rows in buffer_rows_for_selections {
11658        let query_rows =
11659            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11660        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11661            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11662            // when the caret is just above or just below the deleted hunk.
11663            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11664            let related_to_selection = if allow_adjacent {
11665                hunk.associated_range.overlaps(&query_rows)
11666                    || hunk.associated_range.start == query_rows.end
11667                    || hunk.associated_range.end == query_rows.start
11668            } else {
11669                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11670                // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11671                hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11672                    || selected_multi_buffer_rows.end == hunk.associated_range.start
11673            };
11674            if related_to_selection {
11675                if !processed_buffer_rows
11676                    .entry(hunk.buffer_id)
11677                    .or_default()
11678                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
11679                {
11680                    continue;
11681                }
11682                hunks.push(hunk);
11683            }
11684        }
11685    }
11686
11687    hunks
11688}
11689
11690pub trait CollaborationHub {
11691    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
11692    fn user_participant_indices<'a>(
11693        &self,
11694        cx: &'a AppContext,
11695    ) -> &'a HashMap<u64, ParticipantIndex>;
11696    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
11697}
11698
11699impl CollaborationHub for Model<Project> {
11700    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
11701        self.read(cx).collaborators()
11702    }
11703
11704    fn user_participant_indices<'a>(
11705        &self,
11706        cx: &'a AppContext,
11707    ) -> &'a HashMap<u64, ParticipantIndex> {
11708        self.read(cx).user_store().read(cx).participant_indices()
11709    }
11710
11711    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
11712        let this = self.read(cx);
11713        let user_ids = this.collaborators().values().map(|c| c.user_id);
11714        this.user_store().read_with(cx, |user_store, cx| {
11715            user_store.participant_names(user_ids, cx)
11716        })
11717    }
11718}
11719
11720pub trait CompletionProvider {
11721    fn completions(
11722        &self,
11723        buffer: &Model<Buffer>,
11724        buffer_position: text::Anchor,
11725        trigger: CompletionContext,
11726        cx: &mut ViewContext<Editor>,
11727    ) -> Task<Result<Vec<Completion>>>;
11728
11729    fn resolve_completions(
11730        &self,
11731        buffer: Model<Buffer>,
11732        completion_indices: Vec<usize>,
11733        completions: Arc<RwLock<Box<[Completion]>>>,
11734        cx: &mut ViewContext<Editor>,
11735    ) -> Task<Result<bool>>;
11736
11737    fn apply_additional_edits_for_completion(
11738        &self,
11739        buffer: Model<Buffer>,
11740        completion: Completion,
11741        push_to_history: bool,
11742        cx: &mut ViewContext<Editor>,
11743    ) -> Task<Result<Option<language::Transaction>>>;
11744
11745    fn is_completion_trigger(
11746        &self,
11747        buffer: &Model<Buffer>,
11748        position: language::Anchor,
11749        text: &str,
11750        trigger_in_words: bool,
11751        cx: &mut ViewContext<Editor>,
11752    ) -> bool;
11753}
11754
11755impl CompletionProvider for Model<Project> {
11756    fn completions(
11757        &self,
11758        buffer: &Model<Buffer>,
11759        buffer_position: text::Anchor,
11760        options: CompletionContext,
11761        cx: &mut ViewContext<Editor>,
11762    ) -> Task<Result<Vec<Completion>>> {
11763        self.update(cx, |project, cx| {
11764            project.completions(&buffer, buffer_position, options, cx)
11765        })
11766    }
11767
11768    fn resolve_completions(
11769        &self,
11770        buffer: Model<Buffer>,
11771        completion_indices: Vec<usize>,
11772        completions: Arc<RwLock<Box<[Completion]>>>,
11773        cx: &mut ViewContext<Editor>,
11774    ) -> Task<Result<bool>> {
11775        self.update(cx, |project, cx| {
11776            project.resolve_completions(buffer, completion_indices, completions, cx)
11777        })
11778    }
11779
11780    fn apply_additional_edits_for_completion(
11781        &self,
11782        buffer: Model<Buffer>,
11783        completion: Completion,
11784        push_to_history: bool,
11785        cx: &mut ViewContext<Editor>,
11786    ) -> Task<Result<Option<language::Transaction>>> {
11787        self.update(cx, |project, cx| {
11788            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
11789        })
11790    }
11791
11792    fn is_completion_trigger(
11793        &self,
11794        buffer: &Model<Buffer>,
11795        position: language::Anchor,
11796        text: &str,
11797        trigger_in_words: bool,
11798        cx: &mut ViewContext<Editor>,
11799    ) -> bool {
11800        if !EditorSettings::get_global(cx).show_completions_on_input {
11801            return false;
11802        }
11803
11804        let mut chars = text.chars();
11805        let char = if let Some(char) = chars.next() {
11806            char
11807        } else {
11808            return false;
11809        };
11810        if chars.next().is_some() {
11811            return false;
11812        }
11813
11814        let buffer = buffer.read(cx);
11815        let scope = buffer.snapshot().language_scope_at(position);
11816        if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
11817            return true;
11818        }
11819
11820        buffer
11821            .completion_triggers()
11822            .iter()
11823            .any(|string| string == text)
11824    }
11825}
11826
11827fn inlay_hint_settings(
11828    location: Anchor,
11829    snapshot: &MultiBufferSnapshot,
11830    cx: &mut ViewContext<'_, Editor>,
11831) -> InlayHintSettings {
11832    let file = snapshot.file_at(location);
11833    let language = snapshot.language_at(location);
11834    let settings = all_language_settings(file, cx);
11835    settings
11836        .language(language.map(|l| l.name()).as_deref())
11837        .inlay_hints
11838}
11839
11840fn consume_contiguous_rows(
11841    contiguous_row_selections: &mut Vec<Selection<Point>>,
11842    selection: &Selection<Point>,
11843    display_map: &DisplaySnapshot,
11844    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
11845) -> (MultiBufferRow, MultiBufferRow) {
11846    contiguous_row_selections.push(selection.clone());
11847    let start_row = MultiBufferRow(selection.start.row);
11848    let mut end_row = ending_row(selection, display_map);
11849
11850    while let Some(next_selection) = selections.peek() {
11851        if next_selection.start.row <= end_row.0 {
11852            end_row = ending_row(next_selection, display_map);
11853            contiguous_row_selections.push(selections.next().unwrap().clone());
11854        } else {
11855            break;
11856        }
11857    }
11858    (start_row, end_row)
11859}
11860
11861fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
11862    if next_selection.end.column > 0 || next_selection.is_empty() {
11863        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
11864    } else {
11865        MultiBufferRow(next_selection.end.row)
11866    }
11867}
11868
11869impl EditorSnapshot {
11870    pub fn remote_selections_in_range<'a>(
11871        &'a self,
11872        range: &'a Range<Anchor>,
11873        collaboration_hub: &dyn CollaborationHub,
11874        cx: &'a AppContext,
11875    ) -> impl 'a + Iterator<Item = RemoteSelection> {
11876        let participant_names = collaboration_hub.user_names(cx);
11877        let participant_indices = collaboration_hub.user_participant_indices(cx);
11878        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
11879        let collaborators_by_replica_id = collaborators_by_peer_id
11880            .iter()
11881            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
11882            .collect::<HashMap<_, _>>();
11883        self.buffer_snapshot
11884            .selections_in_range(range, false)
11885            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
11886                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
11887                let participant_index = participant_indices.get(&collaborator.user_id).copied();
11888                let user_name = participant_names.get(&collaborator.user_id).cloned();
11889                Some(RemoteSelection {
11890                    replica_id,
11891                    selection,
11892                    cursor_shape,
11893                    line_mode,
11894                    participant_index,
11895                    peer_id: collaborator.peer_id,
11896                    user_name,
11897                })
11898            })
11899    }
11900
11901    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
11902        self.display_snapshot.buffer_snapshot.language_at(position)
11903    }
11904
11905    pub fn is_focused(&self) -> bool {
11906        self.is_focused
11907    }
11908
11909    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
11910        self.placeholder_text.as_ref()
11911    }
11912
11913    pub fn scroll_position(&self) -> gpui::Point<f32> {
11914        self.scroll_anchor.scroll_position(&self.display_snapshot)
11915    }
11916
11917    pub fn gutter_dimensions(
11918        &self,
11919        font_id: FontId,
11920        font_size: Pixels,
11921        em_width: Pixels,
11922        max_line_number_width: Pixels,
11923        cx: &AppContext,
11924    ) -> GutterDimensions {
11925        if !self.show_gutter {
11926            return GutterDimensions::default();
11927        }
11928        let descent = cx.text_system().descent(font_id, font_size);
11929
11930        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
11931            matches!(
11932                ProjectSettings::get_global(cx).git.git_gutter,
11933                Some(GitGutterSetting::TrackedFiles)
11934            )
11935        });
11936        let gutter_settings = EditorSettings::get_global(cx).gutter;
11937        let show_line_numbers = self
11938            .show_line_numbers
11939            .unwrap_or(gutter_settings.line_numbers);
11940        let line_gutter_width = if show_line_numbers {
11941            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
11942            let min_width_for_number_on_gutter = em_width * 4.0;
11943            max_line_number_width.max(min_width_for_number_on_gutter)
11944        } else {
11945            0.0.into()
11946        };
11947
11948        let show_code_actions = self
11949            .show_code_actions
11950            .unwrap_or(gutter_settings.code_actions);
11951
11952        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
11953
11954        let git_blame_entries_width = self
11955            .render_git_blame_gutter
11956            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
11957
11958        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
11959        left_padding += if show_code_actions || show_runnables {
11960            em_width * 3.0
11961        } else if show_git_gutter && show_line_numbers {
11962            em_width * 2.0
11963        } else if show_git_gutter || show_line_numbers {
11964            em_width
11965        } else {
11966            px(0.)
11967        };
11968
11969        let right_padding = if gutter_settings.folds && show_line_numbers {
11970            em_width * 4.0
11971        } else if gutter_settings.folds {
11972            em_width * 3.0
11973        } else if show_line_numbers {
11974            em_width
11975        } else {
11976            px(0.)
11977        };
11978
11979        GutterDimensions {
11980            left_padding,
11981            right_padding,
11982            width: line_gutter_width + left_padding + right_padding,
11983            margin: -descent,
11984            git_blame_entries_width,
11985        }
11986    }
11987
11988    pub fn render_fold_toggle(
11989        &self,
11990        buffer_row: MultiBufferRow,
11991        row_contains_cursor: bool,
11992        editor: View<Editor>,
11993        cx: &mut WindowContext,
11994    ) -> Option<AnyElement> {
11995        let folded = self.is_line_folded(buffer_row);
11996
11997        if let Some(crease) = self
11998            .crease_snapshot
11999            .query_row(buffer_row, &self.buffer_snapshot)
12000        {
12001            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12002                if folded {
12003                    editor.update(cx, |editor, cx| {
12004                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12005                    });
12006                } else {
12007                    editor.update(cx, |editor, cx| {
12008                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12009                    });
12010                }
12011            });
12012
12013            Some((crease.render_toggle)(
12014                buffer_row,
12015                folded,
12016                toggle_callback,
12017                cx,
12018            ))
12019        } else if folded
12020            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12021        {
12022            Some(
12023                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12024                    .selected(folded)
12025                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12026                        if folded {
12027                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
12028                        } else {
12029                            this.fold_at(&FoldAt { buffer_row }, cx);
12030                        }
12031                    }))
12032                    .into_any_element(),
12033            )
12034        } else {
12035            None
12036        }
12037    }
12038
12039    pub fn render_crease_trailer(
12040        &self,
12041        buffer_row: MultiBufferRow,
12042        cx: &mut WindowContext,
12043    ) -> Option<AnyElement> {
12044        let folded = self.is_line_folded(buffer_row);
12045        let crease = self
12046            .crease_snapshot
12047            .query_row(buffer_row, &self.buffer_snapshot)?;
12048        Some((crease.render_trailer)(buffer_row, folded, cx))
12049    }
12050}
12051
12052impl Deref for EditorSnapshot {
12053    type Target = DisplaySnapshot;
12054
12055    fn deref(&self) -> &Self::Target {
12056        &self.display_snapshot
12057    }
12058}
12059
12060#[derive(Clone, Debug, PartialEq, Eq)]
12061pub enum EditorEvent {
12062    InputIgnored {
12063        text: Arc<str>,
12064    },
12065    InputHandled {
12066        utf16_range_to_replace: Option<Range<isize>>,
12067        text: Arc<str>,
12068    },
12069    ExcerptsAdded {
12070        buffer: Model<Buffer>,
12071        predecessor: ExcerptId,
12072        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12073    },
12074    ExcerptsRemoved {
12075        ids: Vec<ExcerptId>,
12076    },
12077    ExcerptsEdited {
12078        ids: Vec<ExcerptId>,
12079    },
12080    ExcerptsExpanded {
12081        ids: Vec<ExcerptId>,
12082    },
12083    BufferEdited,
12084    Edited {
12085        transaction_id: clock::Lamport,
12086    },
12087    Reparsed(BufferId),
12088    Focused,
12089    Blurred,
12090    DirtyChanged,
12091    Saved,
12092    TitleChanged,
12093    DiffBaseChanged,
12094    SelectionsChanged {
12095        local: bool,
12096    },
12097    ScrollPositionChanged {
12098        local: bool,
12099        autoscroll: bool,
12100    },
12101    Closed,
12102    TransactionUndone {
12103        transaction_id: clock::Lamport,
12104    },
12105    TransactionBegun {
12106        transaction_id: clock::Lamport,
12107    },
12108}
12109
12110impl EventEmitter<EditorEvent> for Editor {}
12111
12112impl FocusableView for Editor {
12113    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12114        self.focus_handle.clone()
12115    }
12116}
12117
12118impl Render for Editor {
12119    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12120        let settings = ThemeSettings::get_global(cx);
12121
12122        let text_style = match self.mode {
12123            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12124                color: cx.theme().colors().editor_foreground,
12125                font_family: settings.ui_font.family.clone(),
12126                font_features: settings.ui_font.features.clone(),
12127                font_size: rems(0.875).into(),
12128                font_weight: settings.ui_font.weight,
12129                font_style: FontStyle::Normal,
12130                line_height: relative(settings.buffer_line_height.value()),
12131                background_color: None,
12132                underline: None,
12133                strikethrough: None,
12134                white_space: WhiteSpace::Normal,
12135            },
12136            EditorMode::Full => TextStyle {
12137                color: cx.theme().colors().editor_foreground,
12138                font_family: settings.buffer_font.family.clone(),
12139                font_features: settings.buffer_font.features.clone(),
12140                font_size: settings.buffer_font_size(cx).into(),
12141                font_weight: settings.buffer_font.weight,
12142                font_style: FontStyle::Normal,
12143                line_height: relative(settings.buffer_line_height.value()),
12144                background_color: None,
12145                underline: None,
12146                strikethrough: None,
12147                white_space: WhiteSpace::Normal,
12148            },
12149        };
12150
12151        let background = match self.mode {
12152            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12153            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12154            EditorMode::Full => cx.theme().colors().editor_background,
12155        };
12156
12157        EditorElement::new(
12158            cx.view(),
12159            EditorStyle {
12160                background,
12161                local_player: cx.theme().players().local(),
12162                text: text_style,
12163                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12164                syntax: cx.theme().syntax().clone(),
12165                status: cx.theme().status().clone(),
12166                inlay_hints_style: HighlightStyle {
12167                    color: Some(cx.theme().status().hint),
12168                    ..HighlightStyle::default()
12169                },
12170                suggestions_style: HighlightStyle {
12171                    color: Some(cx.theme().status().predictive),
12172                    ..HighlightStyle::default()
12173                },
12174            },
12175        )
12176    }
12177}
12178
12179impl ViewInputHandler for Editor {
12180    fn text_for_range(
12181        &mut self,
12182        range_utf16: Range<usize>,
12183        cx: &mut ViewContext<Self>,
12184    ) -> Option<String> {
12185        Some(
12186            self.buffer
12187                .read(cx)
12188                .read(cx)
12189                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12190                .collect(),
12191        )
12192    }
12193
12194    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12195        // Prevent the IME menu from appearing when holding down an alphabetic key
12196        // while input is disabled.
12197        if !self.input_enabled {
12198            return None;
12199        }
12200
12201        let range = self.selections.newest::<OffsetUtf16>(cx).range();
12202        Some(range.start.0..range.end.0)
12203    }
12204
12205    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12206        let snapshot = self.buffer.read(cx).read(cx);
12207        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12208        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12209    }
12210
12211    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12212        self.clear_highlights::<InputComposition>(cx);
12213        self.ime_transaction.take();
12214    }
12215
12216    fn replace_text_in_range(
12217        &mut self,
12218        range_utf16: Option<Range<usize>>,
12219        text: &str,
12220        cx: &mut ViewContext<Self>,
12221    ) {
12222        if !self.input_enabled {
12223            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12224            return;
12225        }
12226
12227        self.transact(cx, |this, cx| {
12228            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12229                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12230                Some(this.selection_replacement_ranges(range_utf16, cx))
12231            } else {
12232                this.marked_text_ranges(cx)
12233            };
12234
12235            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12236                let newest_selection_id = this.selections.newest_anchor().id;
12237                this.selections
12238                    .all::<OffsetUtf16>(cx)
12239                    .iter()
12240                    .zip(ranges_to_replace.iter())
12241                    .find_map(|(selection, range)| {
12242                        if selection.id == newest_selection_id {
12243                            Some(
12244                                (range.start.0 as isize - selection.head().0 as isize)
12245                                    ..(range.end.0 as isize - selection.head().0 as isize),
12246                            )
12247                        } else {
12248                            None
12249                        }
12250                    })
12251            });
12252
12253            cx.emit(EditorEvent::InputHandled {
12254                utf16_range_to_replace: range_to_replace,
12255                text: text.into(),
12256            });
12257
12258            if let Some(new_selected_ranges) = new_selected_ranges {
12259                this.change_selections(None, cx, |selections| {
12260                    selections.select_ranges(new_selected_ranges)
12261                });
12262                this.backspace(&Default::default(), cx);
12263            }
12264
12265            this.handle_input(text, cx);
12266        });
12267
12268        if let Some(transaction) = self.ime_transaction {
12269            self.buffer.update(cx, |buffer, cx| {
12270                buffer.group_until_transaction(transaction, cx);
12271            });
12272        }
12273
12274        self.unmark_text(cx);
12275    }
12276
12277    fn replace_and_mark_text_in_range(
12278        &mut self,
12279        range_utf16: Option<Range<usize>>,
12280        text: &str,
12281        new_selected_range_utf16: Option<Range<usize>>,
12282        cx: &mut ViewContext<Self>,
12283    ) {
12284        if !self.input_enabled {
12285            return;
12286        }
12287
12288        let transaction = self.transact(cx, |this, cx| {
12289            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12290                let snapshot = this.buffer.read(cx).read(cx);
12291                if let Some(relative_range_utf16) = range_utf16.as_ref() {
12292                    for marked_range in &mut marked_ranges {
12293                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12294                        marked_range.start.0 += relative_range_utf16.start;
12295                        marked_range.start =
12296                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12297                        marked_range.end =
12298                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12299                    }
12300                }
12301                Some(marked_ranges)
12302            } else if let Some(range_utf16) = range_utf16 {
12303                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12304                Some(this.selection_replacement_ranges(range_utf16, cx))
12305            } else {
12306                None
12307            };
12308
12309            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12310                let newest_selection_id = this.selections.newest_anchor().id;
12311                this.selections
12312                    .all::<OffsetUtf16>(cx)
12313                    .iter()
12314                    .zip(ranges_to_replace.iter())
12315                    .find_map(|(selection, range)| {
12316                        if selection.id == newest_selection_id {
12317                            Some(
12318                                (range.start.0 as isize - selection.head().0 as isize)
12319                                    ..(range.end.0 as isize - selection.head().0 as isize),
12320                            )
12321                        } else {
12322                            None
12323                        }
12324                    })
12325            });
12326
12327            cx.emit(EditorEvent::InputHandled {
12328                utf16_range_to_replace: range_to_replace,
12329                text: text.into(),
12330            });
12331
12332            if let Some(ranges) = ranges_to_replace {
12333                this.change_selections(None, cx, |s| s.select_ranges(ranges));
12334            }
12335
12336            let marked_ranges = {
12337                let snapshot = this.buffer.read(cx).read(cx);
12338                this.selections
12339                    .disjoint_anchors()
12340                    .iter()
12341                    .map(|selection| {
12342                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12343                    })
12344                    .collect::<Vec<_>>()
12345            };
12346
12347            if text.is_empty() {
12348                this.unmark_text(cx);
12349            } else {
12350                this.highlight_text::<InputComposition>(
12351                    marked_ranges.clone(),
12352                    HighlightStyle {
12353                        underline: Some(UnderlineStyle {
12354                            thickness: px(1.),
12355                            color: None,
12356                            wavy: false,
12357                        }),
12358                        ..Default::default()
12359                    },
12360                    cx,
12361                );
12362            }
12363
12364            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12365            let use_autoclose = this.use_autoclose;
12366            let use_auto_surround = this.use_auto_surround;
12367            this.set_use_autoclose(false);
12368            this.set_use_auto_surround(false);
12369            this.handle_input(text, cx);
12370            this.set_use_autoclose(use_autoclose);
12371            this.set_use_auto_surround(use_auto_surround);
12372
12373            if let Some(new_selected_range) = new_selected_range_utf16 {
12374                let snapshot = this.buffer.read(cx).read(cx);
12375                let new_selected_ranges = marked_ranges
12376                    .into_iter()
12377                    .map(|marked_range| {
12378                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12379                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12380                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12381                        snapshot.clip_offset_utf16(new_start, Bias::Left)
12382                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12383                    })
12384                    .collect::<Vec<_>>();
12385
12386                drop(snapshot);
12387                this.change_selections(None, cx, |selections| {
12388                    selections.select_ranges(new_selected_ranges)
12389                });
12390            }
12391        });
12392
12393        self.ime_transaction = self.ime_transaction.or(transaction);
12394        if let Some(transaction) = self.ime_transaction {
12395            self.buffer.update(cx, |buffer, cx| {
12396                buffer.group_until_transaction(transaction, cx);
12397            });
12398        }
12399
12400        if self.text_highlights::<InputComposition>(cx).is_none() {
12401            self.ime_transaction.take();
12402        }
12403    }
12404
12405    fn bounds_for_range(
12406        &mut self,
12407        range_utf16: Range<usize>,
12408        element_bounds: gpui::Bounds<Pixels>,
12409        cx: &mut ViewContext<Self>,
12410    ) -> Option<gpui::Bounds<Pixels>> {
12411        let text_layout_details = self.text_layout_details(cx);
12412        let style = &text_layout_details.editor_style;
12413        let font_id = cx.text_system().resolve_font(&style.text.font());
12414        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12415        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12416
12417        let em_width = cx
12418            .text_system()
12419            .typographic_bounds(font_id, font_size, 'm')
12420            .unwrap()
12421            .size
12422            .width;
12423
12424        let snapshot = self.snapshot(cx);
12425        let scroll_position = snapshot.scroll_position();
12426        let scroll_left = scroll_position.x * em_width;
12427
12428        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12429        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12430            + self.gutter_dimensions.width;
12431        let y = line_height * (start.row().as_f32() - scroll_position.y);
12432
12433        Some(Bounds {
12434            origin: element_bounds.origin + point(x, y),
12435            size: size(em_width, line_height),
12436        })
12437    }
12438}
12439
12440trait SelectionExt {
12441    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12442    fn spanned_rows(
12443        &self,
12444        include_end_if_at_line_start: bool,
12445        map: &DisplaySnapshot,
12446    ) -> Range<MultiBufferRow>;
12447}
12448
12449impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12450    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12451        let start = self
12452            .start
12453            .to_point(&map.buffer_snapshot)
12454            .to_display_point(map);
12455        let end = self
12456            .end
12457            .to_point(&map.buffer_snapshot)
12458            .to_display_point(map);
12459        if self.reversed {
12460            end..start
12461        } else {
12462            start..end
12463        }
12464    }
12465
12466    fn spanned_rows(
12467        &self,
12468        include_end_if_at_line_start: bool,
12469        map: &DisplaySnapshot,
12470    ) -> Range<MultiBufferRow> {
12471        let start = self.start.to_point(&map.buffer_snapshot);
12472        let mut end = self.end.to_point(&map.buffer_snapshot);
12473        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12474            end.row -= 1;
12475        }
12476
12477        let buffer_start = map.prev_line_boundary(start).0;
12478        let buffer_end = map.next_line_boundary(end).0;
12479        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12480    }
12481}
12482
12483impl<T: InvalidationRegion> InvalidationStack<T> {
12484    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12485    where
12486        S: Clone + ToOffset,
12487    {
12488        while let Some(region) = self.last() {
12489            let all_selections_inside_invalidation_ranges =
12490                if selections.len() == region.ranges().len() {
12491                    selections
12492                        .iter()
12493                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12494                        .all(|(selection, invalidation_range)| {
12495                            let head = selection.head().to_offset(buffer);
12496                            invalidation_range.start <= head && invalidation_range.end >= head
12497                        })
12498                } else {
12499                    false
12500                };
12501
12502            if all_selections_inside_invalidation_ranges {
12503                break;
12504            } else {
12505                self.pop();
12506            }
12507        }
12508    }
12509}
12510
12511impl<T> Default for InvalidationStack<T> {
12512    fn default() -> Self {
12513        Self(Default::default())
12514    }
12515}
12516
12517impl<T> Deref for InvalidationStack<T> {
12518    type Target = Vec<T>;
12519
12520    fn deref(&self) -> &Self::Target {
12521        &self.0
12522    }
12523}
12524
12525impl<T> DerefMut for InvalidationStack<T> {
12526    fn deref_mut(&mut self) -> &mut Self::Target {
12527        &mut self.0
12528    }
12529}
12530
12531impl InvalidationRegion for SnippetState {
12532    fn ranges(&self) -> &[Range<Anchor>] {
12533        &self.ranges[self.active_index]
12534    }
12535}
12536
12537pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
12538    let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
12539
12540    Box::new(move |cx: &mut BlockContext| {
12541        let group_id: SharedString = cx.block_id.to_string().into();
12542
12543        let mut text_style = cx.text_style().clone();
12544        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
12545        let theme_settings = ThemeSettings::get_global(cx);
12546        text_style.font_family = theme_settings.buffer_font.family.clone();
12547        text_style.font_style = theme_settings.buffer_font.style;
12548        text_style.font_features = theme_settings.buffer_font.features.clone();
12549        text_style.font_weight = theme_settings.buffer_font.weight;
12550
12551        let multi_line_diagnostic = diagnostic.message.contains('\n');
12552
12553        let buttons = |diagnostic: &Diagnostic, block_id: usize| {
12554            if multi_line_diagnostic {
12555                v_flex()
12556            } else {
12557                h_flex()
12558            }
12559            .children(diagnostic.is_primary.then(|| {
12560                IconButton::new(("close-block", block_id), IconName::XCircle)
12561                    .icon_color(Color::Muted)
12562                    .size(ButtonSize::Compact)
12563                    .style(ButtonStyle::Transparent)
12564                    .visible_on_hover(group_id.clone())
12565                    .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
12566                    .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
12567            }))
12568            .child(
12569                IconButton::new(("copy-block", block_id), IconName::Copy)
12570                    .icon_color(Color::Muted)
12571                    .size(ButtonSize::Compact)
12572                    .style(ButtonStyle::Transparent)
12573                    .visible_on_hover(group_id.clone())
12574                    .on_click({
12575                        let message = diagnostic.message.clone();
12576                        move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
12577                    })
12578                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
12579            )
12580        };
12581
12582        let icon_size = buttons(&diagnostic, cx.block_id)
12583            .into_any_element()
12584            .layout_as_root(AvailableSpace::min_size(), cx);
12585
12586        h_flex()
12587            .id(cx.block_id)
12588            .group(group_id.clone())
12589            .relative()
12590            .size_full()
12591            .pl(cx.gutter_dimensions.width)
12592            .w(cx.max_width + cx.gutter_dimensions.width)
12593            .child(
12594                div()
12595                    .flex()
12596                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
12597                    .flex_shrink(),
12598            )
12599            .child(buttons(&diagnostic, cx.block_id))
12600            .child(div().flex().flex_shrink_0().child(
12601                StyledText::new(text_without_backticks.clone()).with_highlights(
12602                    &text_style,
12603                    code_ranges.iter().map(|range| {
12604                        (
12605                            range.clone(),
12606                            HighlightStyle {
12607                                font_weight: Some(FontWeight::BOLD),
12608                                ..Default::default()
12609                            },
12610                        )
12611                    }),
12612                ),
12613            ))
12614            .into_any_element()
12615    })
12616}
12617
12618pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
12619    let mut text_without_backticks = String::new();
12620    let mut code_ranges = Vec::new();
12621
12622    if let Some(source) = &diagnostic.source {
12623        text_without_backticks.push_str(&source);
12624        code_ranges.push(0..source.len());
12625        text_without_backticks.push_str(": ");
12626    }
12627
12628    let mut prev_offset = 0;
12629    let mut in_code_block = false;
12630    for (ix, _) in diagnostic
12631        .message
12632        .match_indices('`')
12633        .chain([(diagnostic.message.len(), "")])
12634    {
12635        let prev_len = text_without_backticks.len();
12636        text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
12637        prev_offset = ix + 1;
12638        if in_code_block {
12639            code_ranges.push(prev_len..text_without_backticks.len());
12640        }
12641        in_code_block = !in_code_block;
12642    }
12643
12644    (text_without_backticks.into(), code_ranges)
12645}
12646
12647fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
12648    match severity {
12649        DiagnosticSeverity::ERROR => colors.error,
12650        DiagnosticSeverity::WARNING => colors.warning,
12651        DiagnosticSeverity::INFORMATION => colors.info,
12652        DiagnosticSeverity::HINT => colors.info,
12653        _ => colors.ignored,
12654    }
12655}
12656
12657pub fn styled_runs_for_code_label<'a>(
12658    label: &'a CodeLabel,
12659    syntax_theme: &'a theme::SyntaxTheme,
12660) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
12661    let fade_out = HighlightStyle {
12662        fade_out: Some(0.35),
12663        ..Default::default()
12664    };
12665
12666    let mut prev_end = label.filter_range.end;
12667    label
12668        .runs
12669        .iter()
12670        .enumerate()
12671        .flat_map(move |(ix, (range, highlight_id))| {
12672            let style = if let Some(style) = highlight_id.style(syntax_theme) {
12673                style
12674            } else {
12675                return Default::default();
12676            };
12677            let mut muted_style = style;
12678            muted_style.highlight(fade_out);
12679
12680            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
12681            if range.start >= label.filter_range.end {
12682                if range.start > prev_end {
12683                    runs.push((prev_end..range.start, fade_out));
12684                }
12685                runs.push((range.clone(), muted_style));
12686            } else if range.end <= label.filter_range.end {
12687                runs.push((range.clone(), style));
12688            } else {
12689                runs.push((range.start..label.filter_range.end, style));
12690                runs.push((label.filter_range.end..range.end, muted_style));
12691            }
12692            prev_end = cmp::max(prev_end, range.end);
12693
12694            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
12695                runs.push((prev_end..label.text.len(), fade_out));
12696            }
12697
12698            runs
12699        })
12700}
12701
12702pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
12703    let mut prev_index = 0;
12704    let mut prev_codepoint: Option<char> = None;
12705    text.char_indices()
12706        .chain([(text.len(), '\0')])
12707        .filter_map(move |(index, codepoint)| {
12708            let prev_codepoint = prev_codepoint.replace(codepoint)?;
12709            let is_boundary = index == text.len()
12710                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
12711                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
12712            if is_boundary {
12713                let chunk = &text[prev_index..index];
12714                prev_index = index;
12715                Some(chunk)
12716            } else {
12717                None
12718            }
12719        })
12720}
12721
12722trait RangeToAnchorExt {
12723    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
12724}
12725
12726impl<T: ToOffset> RangeToAnchorExt for Range<T> {
12727    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
12728        let start_offset = self.start.to_offset(snapshot);
12729        let end_offset = self.end.to_offset(snapshot);
12730        if start_offset == end_offset {
12731            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
12732        } else {
12733            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
12734        }
12735    }
12736}
12737
12738pub trait RowExt {
12739    fn as_f32(&self) -> f32;
12740
12741    fn next_row(&self) -> Self;
12742
12743    fn previous_row(&self) -> Self;
12744
12745    fn minus(&self, other: Self) -> u32;
12746}
12747
12748impl RowExt for DisplayRow {
12749    fn as_f32(&self) -> f32 {
12750        self.0 as f32
12751    }
12752
12753    fn next_row(&self) -> Self {
12754        Self(self.0 + 1)
12755    }
12756
12757    fn previous_row(&self) -> Self {
12758        Self(self.0.saturating_sub(1))
12759    }
12760
12761    fn minus(&self, other: Self) -> u32 {
12762        self.0 - other.0
12763    }
12764}
12765
12766impl RowExt for MultiBufferRow {
12767    fn as_f32(&self) -> f32 {
12768        self.0 as f32
12769    }
12770
12771    fn next_row(&self) -> Self {
12772        Self(self.0 + 1)
12773    }
12774
12775    fn previous_row(&self) -> Self {
12776        Self(self.0.saturating_sub(1))
12777    }
12778
12779    fn minus(&self, other: Self) -> u32 {
12780        self.0 - other.0
12781    }
12782}
12783
12784trait RowRangeExt {
12785    type Row;
12786
12787    fn len(&self) -> usize;
12788
12789    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
12790}
12791
12792impl RowRangeExt for Range<MultiBufferRow> {
12793    type Row = MultiBufferRow;
12794
12795    fn len(&self) -> usize {
12796        (self.end.0 - self.start.0) as usize
12797    }
12798
12799    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
12800        (self.start.0..self.end.0).map(MultiBufferRow)
12801    }
12802}
12803
12804impl RowRangeExt for Range<DisplayRow> {
12805    type Row = DisplayRow;
12806
12807    fn len(&self) -> usize {
12808        (self.end.0 - self.start.0) as usize
12809    }
12810
12811    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
12812        (self.start.0..self.end.0).map(DisplayRow)
12813    }
12814}
12815
12816fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
12817    if hunk.diff_base_byte_range.is_empty() {
12818        DiffHunkStatus::Added
12819    } else if hunk.associated_range.is_empty() {
12820        DiffHunkStatus::Removed
12821    } else {
12822        DiffHunkStatus::Modified
12823    }
12824}