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