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 matches!(self.mode, EditorMode::SingleLine { .. }) {
 6816            cx.propagate();
 6817            return;
 6818        }
 6819
 6820        let Some(row_count) = self.visible_row_count() else {
 6821            return;
 6822        };
 6823
 6824        let autoscroll = if action.center_cursor {
 6825            Autoscroll::center()
 6826        } else {
 6827            Autoscroll::fit()
 6828        };
 6829
 6830        let text_layout_details = &self.text_layout_details(cx);
 6831
 6832        self.change_selections(Some(autoscroll), cx, |s| {
 6833            let line_mode = s.line_mode;
 6834            s.move_with(|map, selection| {
 6835                if !selection.is_empty() && !line_mode {
 6836                    selection.goal = SelectionGoal::None;
 6837                }
 6838                let (cursor, goal) = movement::up_by_rows(
 6839                    map,
 6840                    selection.end,
 6841                    row_count,
 6842                    selection.goal,
 6843                    false,
 6844                    &text_layout_details,
 6845                );
 6846                selection.collapse_to(cursor, goal);
 6847            });
 6848        });
 6849    }
 6850
 6851    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 6852        let text_layout_details = &self.text_layout_details(cx);
 6853        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6854            s.move_heads_with(|map, head, goal| {
 6855                movement::up(map, head, goal, false, &text_layout_details)
 6856            })
 6857        })
 6858    }
 6859
 6860    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 6861        self.take_rename(true, cx);
 6862
 6863        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6864            cx.propagate();
 6865            return;
 6866        }
 6867
 6868        let text_layout_details = &self.text_layout_details(cx);
 6869        let selection_count = self.selections.count();
 6870        let first_selection = self.selections.first_anchor();
 6871
 6872        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6873            let line_mode = s.line_mode;
 6874            s.move_with(|map, selection| {
 6875                if !selection.is_empty() && !line_mode {
 6876                    selection.goal = SelectionGoal::None;
 6877                }
 6878                let (cursor, goal) = movement::down(
 6879                    map,
 6880                    selection.end,
 6881                    selection.goal,
 6882                    false,
 6883                    &text_layout_details,
 6884                );
 6885                selection.collapse_to(cursor, goal);
 6886            });
 6887        });
 6888
 6889        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6890        {
 6891            cx.propagate();
 6892        }
 6893    }
 6894
 6895    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 6896        let Some(row_count) = self.visible_row_count() else {
 6897            return;
 6898        };
 6899
 6900        let text_layout_details = &self.text_layout_details(cx);
 6901
 6902        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6903            s.move_heads_with(|map, head, goal| {
 6904                movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
 6905            })
 6906        })
 6907    }
 6908
 6909    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 6910        if self.take_rename(true, cx).is_some() {
 6911            return;
 6912        }
 6913
 6914        if self
 6915            .context_menu
 6916            .write()
 6917            .as_mut()
 6918            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 6919            .unwrap_or(false)
 6920        {
 6921            return;
 6922        }
 6923
 6924        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6925            cx.propagate();
 6926            return;
 6927        }
 6928
 6929        let Some(row_count) = self.visible_row_count() else {
 6930            return;
 6931        };
 6932
 6933        let autoscroll = if action.center_cursor {
 6934            Autoscroll::center()
 6935        } else {
 6936            Autoscroll::fit()
 6937        };
 6938
 6939        let text_layout_details = &self.text_layout_details(cx);
 6940        self.change_selections(Some(autoscroll), cx, |s| {
 6941            let line_mode = s.line_mode;
 6942            s.move_with(|map, selection| {
 6943                if !selection.is_empty() && !line_mode {
 6944                    selection.goal = SelectionGoal::None;
 6945                }
 6946                let (cursor, goal) = movement::down_by_rows(
 6947                    map,
 6948                    selection.end,
 6949                    row_count,
 6950                    selection.goal,
 6951                    false,
 6952                    &text_layout_details,
 6953                );
 6954                selection.collapse_to(cursor, goal);
 6955            });
 6956        });
 6957    }
 6958
 6959    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 6960        let text_layout_details = &self.text_layout_details(cx);
 6961        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6962            s.move_heads_with(|map, head, goal| {
 6963                movement::down(map, head, goal, false, &text_layout_details)
 6964            })
 6965        });
 6966    }
 6967
 6968    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 6969        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6970            context_menu.select_first(self.project.as_ref(), cx);
 6971        }
 6972    }
 6973
 6974    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 6975        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6976            context_menu.select_prev(self.project.as_ref(), cx);
 6977        }
 6978    }
 6979
 6980    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 6981        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6982            context_menu.select_next(self.project.as_ref(), cx);
 6983        }
 6984    }
 6985
 6986    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 6987        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6988            context_menu.select_last(self.project.as_ref(), cx);
 6989        }
 6990    }
 6991
 6992    pub fn move_to_previous_word_start(
 6993        &mut self,
 6994        _: &MoveToPreviousWordStart,
 6995        cx: &mut ViewContext<Self>,
 6996    ) {
 6997        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6998            s.move_cursors_with(|map, head, _| {
 6999                (
 7000                    movement::previous_word_start(map, head),
 7001                    SelectionGoal::None,
 7002                )
 7003            });
 7004        })
 7005    }
 7006
 7007    pub fn move_to_previous_subword_start(
 7008        &mut self,
 7009        _: &MoveToPreviousSubwordStart,
 7010        cx: &mut ViewContext<Self>,
 7011    ) {
 7012        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7013            s.move_cursors_with(|map, head, _| {
 7014                (
 7015                    movement::previous_subword_start(map, head),
 7016                    SelectionGoal::None,
 7017                )
 7018            });
 7019        })
 7020    }
 7021
 7022    pub fn select_to_previous_word_start(
 7023        &mut self,
 7024        _: &SelectToPreviousWordStart,
 7025        cx: &mut ViewContext<Self>,
 7026    ) {
 7027        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7028            s.move_heads_with(|map, head, _| {
 7029                (
 7030                    movement::previous_word_start(map, head),
 7031                    SelectionGoal::None,
 7032                )
 7033            });
 7034        })
 7035    }
 7036
 7037    pub fn select_to_previous_subword_start(
 7038        &mut self,
 7039        _: &SelectToPreviousSubwordStart,
 7040        cx: &mut ViewContext<Self>,
 7041    ) {
 7042        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7043            s.move_heads_with(|map, head, _| {
 7044                (
 7045                    movement::previous_subword_start(map, head),
 7046                    SelectionGoal::None,
 7047                )
 7048            });
 7049        })
 7050    }
 7051
 7052    pub fn delete_to_previous_word_start(
 7053        &mut self,
 7054        _: &DeleteToPreviousWordStart,
 7055        cx: &mut ViewContext<Self>,
 7056    ) {
 7057        self.transact(cx, |this, cx| {
 7058            this.select_autoclose_pair(cx);
 7059            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7060                let line_mode = s.line_mode;
 7061                s.move_with(|map, selection| {
 7062                    if selection.is_empty() && !line_mode {
 7063                        let cursor = movement::previous_word_start(map, selection.head());
 7064                        selection.set_head(cursor, SelectionGoal::None);
 7065                    }
 7066                });
 7067            });
 7068            this.insert("", cx);
 7069        });
 7070    }
 7071
 7072    pub fn delete_to_previous_subword_start(
 7073        &mut self,
 7074        _: &DeleteToPreviousSubwordStart,
 7075        cx: &mut ViewContext<Self>,
 7076    ) {
 7077        self.transact(cx, |this, cx| {
 7078            this.select_autoclose_pair(cx);
 7079            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7080                let line_mode = s.line_mode;
 7081                s.move_with(|map, selection| {
 7082                    if selection.is_empty() && !line_mode {
 7083                        let cursor = movement::previous_subword_start(map, selection.head());
 7084                        selection.set_head(cursor, SelectionGoal::None);
 7085                    }
 7086                });
 7087            });
 7088            this.insert("", cx);
 7089        });
 7090    }
 7091
 7092    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7093        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7094            s.move_cursors_with(|map, head, _| {
 7095                (movement::next_word_end(map, head), SelectionGoal::None)
 7096            });
 7097        })
 7098    }
 7099
 7100    pub fn move_to_next_subword_end(
 7101        &mut self,
 7102        _: &MoveToNextSubwordEnd,
 7103        cx: &mut ViewContext<Self>,
 7104    ) {
 7105        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7106            s.move_cursors_with(|map, head, _| {
 7107                (movement::next_subword_end(map, head), SelectionGoal::None)
 7108            });
 7109        })
 7110    }
 7111
 7112    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7113        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7114            s.move_heads_with(|map, head, _| {
 7115                (movement::next_word_end(map, head), SelectionGoal::None)
 7116            });
 7117        })
 7118    }
 7119
 7120    pub fn select_to_next_subword_end(
 7121        &mut self,
 7122        _: &SelectToNextSubwordEnd,
 7123        cx: &mut ViewContext<Self>,
 7124    ) {
 7125        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7126            s.move_heads_with(|map, head, _| {
 7127                (movement::next_subword_end(map, head), SelectionGoal::None)
 7128            });
 7129        })
 7130    }
 7131
 7132    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
 7133        self.transact(cx, |this, cx| {
 7134            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7135                let line_mode = s.line_mode;
 7136                s.move_with(|map, selection| {
 7137                    if selection.is_empty() && !line_mode {
 7138                        let cursor = movement::next_word_end(map, selection.head());
 7139                        selection.set_head(cursor, SelectionGoal::None);
 7140                    }
 7141                });
 7142            });
 7143            this.insert("", cx);
 7144        });
 7145    }
 7146
 7147    pub fn delete_to_next_subword_end(
 7148        &mut self,
 7149        _: &DeleteToNextSubwordEnd,
 7150        cx: &mut ViewContext<Self>,
 7151    ) {
 7152        self.transact(cx, |this, cx| {
 7153            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7154                s.move_with(|map, selection| {
 7155                    if selection.is_empty() {
 7156                        let cursor = movement::next_subword_end(map, selection.head());
 7157                        selection.set_head(cursor, SelectionGoal::None);
 7158                    }
 7159                });
 7160            });
 7161            this.insert("", cx);
 7162        });
 7163    }
 7164
 7165    pub fn move_to_beginning_of_line(
 7166        &mut self,
 7167        action: &MoveToBeginningOfLine,
 7168        cx: &mut ViewContext<Self>,
 7169    ) {
 7170        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7171            s.move_cursors_with(|map, head, _| {
 7172                (
 7173                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7174                    SelectionGoal::None,
 7175                )
 7176            });
 7177        })
 7178    }
 7179
 7180    pub fn select_to_beginning_of_line(
 7181        &mut self,
 7182        action: &SelectToBeginningOfLine,
 7183        cx: &mut ViewContext<Self>,
 7184    ) {
 7185        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7186            s.move_heads_with(|map, head, _| {
 7187                (
 7188                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7189                    SelectionGoal::None,
 7190                )
 7191            });
 7192        });
 7193    }
 7194
 7195    pub fn delete_to_beginning_of_line(
 7196        &mut self,
 7197        _: &DeleteToBeginningOfLine,
 7198        cx: &mut ViewContext<Self>,
 7199    ) {
 7200        self.transact(cx, |this, cx| {
 7201            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7202                s.move_with(|_, selection| {
 7203                    selection.reversed = true;
 7204                });
 7205            });
 7206
 7207            this.select_to_beginning_of_line(
 7208                &SelectToBeginningOfLine {
 7209                    stop_at_soft_wraps: false,
 7210                },
 7211                cx,
 7212            );
 7213            this.backspace(&Backspace, cx);
 7214        });
 7215    }
 7216
 7217    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7218        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7219            s.move_cursors_with(|map, head, _| {
 7220                (
 7221                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7222                    SelectionGoal::None,
 7223                )
 7224            });
 7225        })
 7226    }
 7227
 7228    pub fn select_to_end_of_line(
 7229        &mut self,
 7230        action: &SelectToEndOfLine,
 7231        cx: &mut ViewContext<Self>,
 7232    ) {
 7233        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7234            s.move_heads_with(|map, head, _| {
 7235                (
 7236                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7237                    SelectionGoal::None,
 7238                )
 7239            });
 7240        })
 7241    }
 7242
 7243    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7244        self.transact(cx, |this, cx| {
 7245            this.select_to_end_of_line(
 7246                &SelectToEndOfLine {
 7247                    stop_at_soft_wraps: false,
 7248                },
 7249                cx,
 7250            );
 7251            this.delete(&Delete, cx);
 7252        });
 7253    }
 7254
 7255    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7256        self.transact(cx, |this, cx| {
 7257            this.select_to_end_of_line(
 7258                &SelectToEndOfLine {
 7259                    stop_at_soft_wraps: false,
 7260                },
 7261                cx,
 7262            );
 7263            this.cut(&Cut, cx);
 7264        });
 7265    }
 7266
 7267    pub fn move_to_start_of_paragraph(
 7268        &mut self,
 7269        _: &MoveToStartOfParagraph,
 7270        cx: &mut ViewContext<Self>,
 7271    ) {
 7272        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7273            cx.propagate();
 7274            return;
 7275        }
 7276
 7277        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7278            s.move_with(|map, selection| {
 7279                selection.collapse_to(
 7280                    movement::start_of_paragraph(map, selection.head(), 1),
 7281                    SelectionGoal::None,
 7282                )
 7283            });
 7284        })
 7285    }
 7286
 7287    pub fn move_to_end_of_paragraph(
 7288        &mut self,
 7289        _: &MoveToEndOfParagraph,
 7290        cx: &mut ViewContext<Self>,
 7291    ) {
 7292        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7293            cx.propagate();
 7294            return;
 7295        }
 7296
 7297        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7298            s.move_with(|map, selection| {
 7299                selection.collapse_to(
 7300                    movement::end_of_paragraph(map, selection.head(), 1),
 7301                    SelectionGoal::None,
 7302                )
 7303            });
 7304        })
 7305    }
 7306
 7307    pub fn select_to_start_of_paragraph(
 7308        &mut self,
 7309        _: &SelectToStartOfParagraph,
 7310        cx: &mut ViewContext<Self>,
 7311    ) {
 7312        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7313            cx.propagate();
 7314            return;
 7315        }
 7316
 7317        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7318            s.move_heads_with(|map, head, _| {
 7319                (
 7320                    movement::start_of_paragraph(map, head, 1),
 7321                    SelectionGoal::None,
 7322                )
 7323            });
 7324        })
 7325    }
 7326
 7327    pub fn select_to_end_of_paragraph(
 7328        &mut self,
 7329        _: &SelectToEndOfParagraph,
 7330        cx: &mut ViewContext<Self>,
 7331    ) {
 7332        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7333            cx.propagate();
 7334            return;
 7335        }
 7336
 7337        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7338            s.move_heads_with(|map, head, _| {
 7339                (
 7340                    movement::end_of_paragraph(map, head, 1),
 7341                    SelectionGoal::None,
 7342                )
 7343            });
 7344        })
 7345    }
 7346
 7347    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7348        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7349            cx.propagate();
 7350            return;
 7351        }
 7352
 7353        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7354            s.select_ranges(vec![0..0]);
 7355        });
 7356    }
 7357
 7358    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7359        let mut selection = self.selections.last::<Point>(cx);
 7360        selection.set_head(Point::zero(), SelectionGoal::None);
 7361
 7362        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7363            s.select(vec![selection]);
 7364        });
 7365    }
 7366
 7367    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7368        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7369            cx.propagate();
 7370            return;
 7371        }
 7372
 7373        let cursor = self.buffer.read(cx).read(cx).len();
 7374        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7375            s.select_ranges(vec![cursor..cursor])
 7376        });
 7377    }
 7378
 7379    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7380        self.nav_history = nav_history;
 7381    }
 7382
 7383    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7384        self.nav_history.as_ref()
 7385    }
 7386
 7387    fn push_to_nav_history(
 7388        &mut self,
 7389        cursor_anchor: Anchor,
 7390        new_position: Option<Point>,
 7391        cx: &mut ViewContext<Self>,
 7392    ) {
 7393        if let Some(nav_history) = self.nav_history.as_mut() {
 7394            let buffer = self.buffer.read(cx).read(cx);
 7395            let cursor_position = cursor_anchor.to_point(&buffer);
 7396            let scroll_state = self.scroll_manager.anchor();
 7397            let scroll_top_row = scroll_state.top_row(&buffer);
 7398            drop(buffer);
 7399
 7400            if let Some(new_position) = new_position {
 7401                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7402                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7403                    return;
 7404                }
 7405            }
 7406
 7407            nav_history.push(
 7408                Some(NavigationData {
 7409                    cursor_anchor,
 7410                    cursor_position,
 7411                    scroll_anchor: scroll_state,
 7412                    scroll_top_row,
 7413                }),
 7414                cx,
 7415            );
 7416        }
 7417    }
 7418
 7419    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7420        let buffer = self.buffer.read(cx).snapshot(cx);
 7421        let mut selection = self.selections.first::<usize>(cx);
 7422        selection.set_head(buffer.len(), SelectionGoal::None);
 7423        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7424            s.select(vec![selection]);
 7425        });
 7426    }
 7427
 7428    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7429        let end = self.buffer.read(cx).read(cx).len();
 7430        self.change_selections(None, cx, |s| {
 7431            s.select_ranges(vec![0..end]);
 7432        });
 7433    }
 7434
 7435    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7436        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7437        let mut selections = self.selections.all::<Point>(cx);
 7438        let max_point = display_map.buffer_snapshot.max_point();
 7439        for selection in &mut selections {
 7440            let rows = selection.spanned_rows(true, &display_map);
 7441            selection.start = Point::new(rows.start.0, 0);
 7442            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7443            selection.reversed = false;
 7444        }
 7445        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7446            s.select(selections);
 7447        });
 7448    }
 7449
 7450    pub fn split_selection_into_lines(
 7451        &mut self,
 7452        _: &SplitSelectionIntoLines,
 7453        cx: &mut ViewContext<Self>,
 7454    ) {
 7455        let mut to_unfold = Vec::new();
 7456        let mut new_selection_ranges = Vec::new();
 7457        {
 7458            let selections = self.selections.all::<Point>(cx);
 7459            let buffer = self.buffer.read(cx).read(cx);
 7460            for selection in selections {
 7461                for row in selection.start.row..selection.end.row {
 7462                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7463                    new_selection_ranges.push(cursor..cursor);
 7464                }
 7465                new_selection_ranges.push(selection.end..selection.end);
 7466                to_unfold.push(selection.start..selection.end);
 7467            }
 7468        }
 7469        self.unfold_ranges(to_unfold, true, true, cx);
 7470        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7471            s.select_ranges(new_selection_ranges);
 7472        });
 7473    }
 7474
 7475    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7476        self.add_selection(true, cx);
 7477    }
 7478
 7479    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7480        self.add_selection(false, cx);
 7481    }
 7482
 7483    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7484        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7485        let mut selections = self.selections.all::<Point>(cx);
 7486        let text_layout_details = self.text_layout_details(cx);
 7487        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7488            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7489            let range = oldest_selection.display_range(&display_map).sorted();
 7490
 7491            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7492            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7493            let positions = start_x.min(end_x)..start_x.max(end_x);
 7494
 7495            selections.clear();
 7496            let mut stack = Vec::new();
 7497            for row in range.start.row().0..=range.end.row().0 {
 7498                if let Some(selection) = self.selections.build_columnar_selection(
 7499                    &display_map,
 7500                    DisplayRow(row),
 7501                    &positions,
 7502                    oldest_selection.reversed,
 7503                    &text_layout_details,
 7504                ) {
 7505                    stack.push(selection.id);
 7506                    selections.push(selection);
 7507                }
 7508            }
 7509
 7510            if above {
 7511                stack.reverse();
 7512            }
 7513
 7514            AddSelectionsState { above, stack }
 7515        });
 7516
 7517        let last_added_selection = *state.stack.last().unwrap();
 7518        let mut new_selections = Vec::new();
 7519        if above == state.above {
 7520            let end_row = if above {
 7521                DisplayRow(0)
 7522            } else {
 7523                display_map.max_point().row()
 7524            };
 7525
 7526            'outer: for selection in selections {
 7527                if selection.id == last_added_selection {
 7528                    let range = selection.display_range(&display_map).sorted();
 7529                    debug_assert_eq!(range.start.row(), range.end.row());
 7530                    let mut row = range.start.row();
 7531                    let positions =
 7532                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7533                            px(start)..px(end)
 7534                        } else {
 7535                            let start_x =
 7536                                display_map.x_for_display_point(range.start, &text_layout_details);
 7537                            let end_x =
 7538                                display_map.x_for_display_point(range.end, &text_layout_details);
 7539                            start_x.min(end_x)..start_x.max(end_x)
 7540                        };
 7541
 7542                    while row != end_row {
 7543                        if above {
 7544                            row.0 -= 1;
 7545                        } else {
 7546                            row.0 += 1;
 7547                        }
 7548
 7549                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7550                            &display_map,
 7551                            row,
 7552                            &positions,
 7553                            selection.reversed,
 7554                            &text_layout_details,
 7555                        ) {
 7556                            state.stack.push(new_selection.id);
 7557                            if above {
 7558                                new_selections.push(new_selection);
 7559                                new_selections.push(selection);
 7560                            } else {
 7561                                new_selections.push(selection);
 7562                                new_selections.push(new_selection);
 7563                            }
 7564
 7565                            continue 'outer;
 7566                        }
 7567                    }
 7568                }
 7569
 7570                new_selections.push(selection);
 7571            }
 7572        } else {
 7573            new_selections = selections;
 7574            new_selections.retain(|s| s.id != last_added_selection);
 7575            state.stack.pop();
 7576        }
 7577
 7578        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7579            s.select(new_selections);
 7580        });
 7581        if state.stack.len() > 1 {
 7582            self.add_selections_state = Some(state);
 7583        }
 7584    }
 7585
 7586    pub fn select_next_match_internal(
 7587        &mut self,
 7588        display_map: &DisplaySnapshot,
 7589        replace_newest: bool,
 7590        autoscroll: Option<Autoscroll>,
 7591        cx: &mut ViewContext<Self>,
 7592    ) -> Result<()> {
 7593        fn select_next_match_ranges(
 7594            this: &mut Editor,
 7595            range: Range<usize>,
 7596            replace_newest: bool,
 7597            auto_scroll: Option<Autoscroll>,
 7598            cx: &mut ViewContext<Editor>,
 7599        ) {
 7600            this.unfold_ranges([range.clone()], false, true, cx);
 7601            this.change_selections(auto_scroll, cx, |s| {
 7602                if replace_newest {
 7603                    s.delete(s.newest_anchor().id);
 7604                }
 7605                s.insert_range(range.clone());
 7606            });
 7607        }
 7608
 7609        let buffer = &display_map.buffer_snapshot;
 7610        let mut selections = self.selections.all::<usize>(cx);
 7611        if let Some(mut select_next_state) = self.select_next_state.take() {
 7612            let query = &select_next_state.query;
 7613            if !select_next_state.done {
 7614                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7615                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7616                let mut next_selected_range = None;
 7617
 7618                let bytes_after_last_selection =
 7619                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7620                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7621                let query_matches = query
 7622                    .stream_find_iter(bytes_after_last_selection)
 7623                    .map(|result| (last_selection.end, result))
 7624                    .chain(
 7625                        query
 7626                            .stream_find_iter(bytes_before_first_selection)
 7627                            .map(|result| (0, result)),
 7628                    );
 7629
 7630                for (start_offset, query_match) in query_matches {
 7631                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7632                    let offset_range =
 7633                        start_offset + query_match.start()..start_offset + query_match.end();
 7634                    let display_range = offset_range.start.to_display_point(&display_map)
 7635                        ..offset_range.end.to_display_point(&display_map);
 7636
 7637                    if !select_next_state.wordwise
 7638                        || (!movement::is_inside_word(&display_map, display_range.start)
 7639                            && !movement::is_inside_word(&display_map, display_range.end))
 7640                    {
 7641                        // TODO: This is n^2, because we might check all the selections
 7642                        if !selections
 7643                            .iter()
 7644                            .any(|selection| selection.range().overlaps(&offset_range))
 7645                        {
 7646                            next_selected_range = Some(offset_range);
 7647                            break;
 7648                        }
 7649                    }
 7650                }
 7651
 7652                if let Some(next_selected_range) = next_selected_range {
 7653                    select_next_match_ranges(
 7654                        self,
 7655                        next_selected_range,
 7656                        replace_newest,
 7657                        autoscroll,
 7658                        cx,
 7659                    );
 7660                } else {
 7661                    select_next_state.done = true;
 7662                }
 7663            }
 7664
 7665            self.select_next_state = Some(select_next_state);
 7666        } else {
 7667            let mut only_carets = true;
 7668            let mut same_text_selected = true;
 7669            let mut selected_text = None;
 7670
 7671            let mut selections_iter = selections.iter().peekable();
 7672            while let Some(selection) = selections_iter.next() {
 7673                if selection.start != selection.end {
 7674                    only_carets = false;
 7675                }
 7676
 7677                if same_text_selected {
 7678                    if selected_text.is_none() {
 7679                        selected_text =
 7680                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7681                    }
 7682
 7683                    if let Some(next_selection) = selections_iter.peek() {
 7684                        if next_selection.range().len() == selection.range().len() {
 7685                            let next_selected_text = buffer
 7686                                .text_for_range(next_selection.range())
 7687                                .collect::<String>();
 7688                            if Some(next_selected_text) != selected_text {
 7689                                same_text_selected = false;
 7690                                selected_text = None;
 7691                            }
 7692                        } else {
 7693                            same_text_selected = false;
 7694                            selected_text = None;
 7695                        }
 7696                    }
 7697                }
 7698            }
 7699
 7700            if only_carets {
 7701                for selection in &mut selections {
 7702                    let word_range = movement::surrounding_word(
 7703                        &display_map,
 7704                        selection.start.to_display_point(&display_map),
 7705                    );
 7706                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7707                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7708                    selection.goal = SelectionGoal::None;
 7709                    selection.reversed = false;
 7710                    select_next_match_ranges(
 7711                        self,
 7712                        selection.start..selection.end,
 7713                        replace_newest,
 7714                        autoscroll,
 7715                        cx,
 7716                    );
 7717                }
 7718
 7719                if selections.len() == 1 {
 7720                    let selection = selections
 7721                        .last()
 7722                        .expect("ensured that there's only one selection");
 7723                    let query = buffer
 7724                        .text_for_range(selection.start..selection.end)
 7725                        .collect::<String>();
 7726                    let is_empty = query.is_empty();
 7727                    let select_state = SelectNextState {
 7728                        query: AhoCorasick::new(&[query])?,
 7729                        wordwise: true,
 7730                        done: is_empty,
 7731                    };
 7732                    self.select_next_state = Some(select_state);
 7733                } else {
 7734                    self.select_next_state = None;
 7735                }
 7736            } else if let Some(selected_text) = selected_text {
 7737                self.select_next_state = Some(SelectNextState {
 7738                    query: AhoCorasick::new(&[selected_text])?,
 7739                    wordwise: false,
 7740                    done: false,
 7741                });
 7742                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 7743            }
 7744        }
 7745        Ok(())
 7746    }
 7747
 7748    pub fn select_all_matches(
 7749        &mut self,
 7750        _action: &SelectAllMatches,
 7751        cx: &mut ViewContext<Self>,
 7752    ) -> Result<()> {
 7753        self.push_to_selection_history();
 7754        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7755
 7756        self.select_next_match_internal(&display_map, false, None, cx)?;
 7757        let Some(select_next_state) = self.select_next_state.as_mut() else {
 7758            return Ok(());
 7759        };
 7760        if select_next_state.done {
 7761            return Ok(());
 7762        }
 7763
 7764        let mut new_selections = self.selections.all::<usize>(cx);
 7765
 7766        let buffer = &display_map.buffer_snapshot;
 7767        let query_matches = select_next_state
 7768            .query
 7769            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 7770
 7771        for query_match in query_matches {
 7772            let query_match = query_match.unwrap(); // can only fail due to I/O
 7773            let offset_range = query_match.start()..query_match.end();
 7774            let display_range = offset_range.start.to_display_point(&display_map)
 7775                ..offset_range.end.to_display_point(&display_map);
 7776
 7777            if !select_next_state.wordwise
 7778                || (!movement::is_inside_word(&display_map, display_range.start)
 7779                    && !movement::is_inside_word(&display_map, display_range.end))
 7780            {
 7781                self.selections.change_with(cx, |selections| {
 7782                    new_selections.push(Selection {
 7783                        id: selections.new_selection_id(),
 7784                        start: offset_range.start,
 7785                        end: offset_range.end,
 7786                        reversed: false,
 7787                        goal: SelectionGoal::None,
 7788                    });
 7789                });
 7790            }
 7791        }
 7792
 7793        new_selections.sort_by_key(|selection| selection.start);
 7794        let mut ix = 0;
 7795        while ix + 1 < new_selections.len() {
 7796            let current_selection = &new_selections[ix];
 7797            let next_selection = &new_selections[ix + 1];
 7798            if current_selection.range().overlaps(&next_selection.range()) {
 7799                if current_selection.id < next_selection.id {
 7800                    new_selections.remove(ix + 1);
 7801                } else {
 7802                    new_selections.remove(ix);
 7803                }
 7804            } else {
 7805                ix += 1;
 7806            }
 7807        }
 7808
 7809        select_next_state.done = true;
 7810        self.unfold_ranges(
 7811            new_selections.iter().map(|selection| selection.range()),
 7812            false,
 7813            false,
 7814            cx,
 7815        );
 7816        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 7817            selections.select(new_selections)
 7818        });
 7819
 7820        Ok(())
 7821    }
 7822
 7823    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 7824        self.push_to_selection_history();
 7825        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7826        self.select_next_match_internal(
 7827            &display_map,
 7828            action.replace_newest,
 7829            Some(Autoscroll::newest()),
 7830            cx,
 7831        )?;
 7832        Ok(())
 7833    }
 7834
 7835    pub fn select_previous(
 7836        &mut self,
 7837        action: &SelectPrevious,
 7838        cx: &mut ViewContext<Self>,
 7839    ) -> Result<()> {
 7840        self.push_to_selection_history();
 7841        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7842        let buffer = &display_map.buffer_snapshot;
 7843        let mut selections = self.selections.all::<usize>(cx);
 7844        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 7845            let query = &select_prev_state.query;
 7846            if !select_prev_state.done {
 7847                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7848                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7849                let mut next_selected_range = None;
 7850                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 7851                let bytes_before_last_selection =
 7852                    buffer.reversed_bytes_in_range(0..last_selection.start);
 7853                let bytes_after_first_selection =
 7854                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 7855                let query_matches = query
 7856                    .stream_find_iter(bytes_before_last_selection)
 7857                    .map(|result| (last_selection.start, result))
 7858                    .chain(
 7859                        query
 7860                            .stream_find_iter(bytes_after_first_selection)
 7861                            .map(|result| (buffer.len(), result)),
 7862                    );
 7863                for (end_offset, query_match) in query_matches {
 7864                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7865                    let offset_range =
 7866                        end_offset - query_match.end()..end_offset - query_match.start();
 7867                    let display_range = offset_range.start.to_display_point(&display_map)
 7868                        ..offset_range.end.to_display_point(&display_map);
 7869
 7870                    if !select_prev_state.wordwise
 7871                        || (!movement::is_inside_word(&display_map, display_range.start)
 7872                            && !movement::is_inside_word(&display_map, display_range.end))
 7873                    {
 7874                        next_selected_range = Some(offset_range);
 7875                        break;
 7876                    }
 7877                }
 7878
 7879                if let Some(next_selected_range) = next_selected_range {
 7880                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 7881                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7882                        if action.replace_newest {
 7883                            s.delete(s.newest_anchor().id);
 7884                        }
 7885                        s.insert_range(next_selected_range);
 7886                    });
 7887                } else {
 7888                    select_prev_state.done = true;
 7889                }
 7890            }
 7891
 7892            self.select_prev_state = Some(select_prev_state);
 7893        } else {
 7894            let mut only_carets = true;
 7895            let mut same_text_selected = true;
 7896            let mut selected_text = None;
 7897
 7898            let mut selections_iter = selections.iter().peekable();
 7899            while let Some(selection) = selections_iter.next() {
 7900                if selection.start != selection.end {
 7901                    only_carets = false;
 7902                }
 7903
 7904                if same_text_selected {
 7905                    if selected_text.is_none() {
 7906                        selected_text =
 7907                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7908                    }
 7909
 7910                    if let Some(next_selection) = selections_iter.peek() {
 7911                        if next_selection.range().len() == selection.range().len() {
 7912                            let next_selected_text = buffer
 7913                                .text_for_range(next_selection.range())
 7914                                .collect::<String>();
 7915                            if Some(next_selected_text) != selected_text {
 7916                                same_text_selected = false;
 7917                                selected_text = None;
 7918                            }
 7919                        } else {
 7920                            same_text_selected = false;
 7921                            selected_text = None;
 7922                        }
 7923                    }
 7924                }
 7925            }
 7926
 7927            if only_carets {
 7928                for selection in &mut selections {
 7929                    let word_range = movement::surrounding_word(
 7930                        &display_map,
 7931                        selection.start.to_display_point(&display_map),
 7932                    );
 7933                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7934                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7935                    selection.goal = SelectionGoal::None;
 7936                    selection.reversed = false;
 7937                }
 7938                if selections.len() == 1 {
 7939                    let selection = selections
 7940                        .last()
 7941                        .expect("ensured that there's only one selection");
 7942                    let query = buffer
 7943                        .text_for_range(selection.start..selection.end)
 7944                        .collect::<String>();
 7945                    let is_empty = query.is_empty();
 7946                    let select_state = SelectNextState {
 7947                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 7948                        wordwise: true,
 7949                        done: is_empty,
 7950                    };
 7951                    self.select_prev_state = Some(select_state);
 7952                } else {
 7953                    self.select_prev_state = None;
 7954                }
 7955
 7956                self.unfold_ranges(
 7957                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 7958                    false,
 7959                    true,
 7960                    cx,
 7961                );
 7962                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7963                    s.select(selections);
 7964                });
 7965            } else if let Some(selected_text) = selected_text {
 7966                self.select_prev_state = Some(SelectNextState {
 7967                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 7968                    wordwise: false,
 7969                    done: false,
 7970                });
 7971                self.select_previous(action, cx)?;
 7972            }
 7973        }
 7974        Ok(())
 7975    }
 7976
 7977    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 7978        let text_layout_details = &self.text_layout_details(cx);
 7979        self.transact(cx, |this, cx| {
 7980            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7981            let mut edits = Vec::new();
 7982            let mut selection_edit_ranges = Vec::new();
 7983            let mut last_toggled_row = None;
 7984            let snapshot = this.buffer.read(cx).read(cx);
 7985            let empty_str: Arc<str> = "".into();
 7986            let mut suffixes_inserted = Vec::new();
 7987
 7988            fn comment_prefix_range(
 7989                snapshot: &MultiBufferSnapshot,
 7990                row: MultiBufferRow,
 7991                comment_prefix: &str,
 7992                comment_prefix_whitespace: &str,
 7993            ) -> Range<Point> {
 7994                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 7995
 7996                let mut line_bytes = snapshot
 7997                    .bytes_in_range(start..snapshot.max_point())
 7998                    .flatten()
 7999                    .copied();
 8000
 8001                // If this line currently begins with the line comment prefix, then record
 8002                // the range containing the prefix.
 8003                if line_bytes
 8004                    .by_ref()
 8005                    .take(comment_prefix.len())
 8006                    .eq(comment_prefix.bytes())
 8007                {
 8008                    // Include any whitespace that matches the comment prefix.
 8009                    let matching_whitespace_len = line_bytes
 8010                        .zip(comment_prefix_whitespace.bytes())
 8011                        .take_while(|(a, b)| a == b)
 8012                        .count() as u32;
 8013                    let end = Point::new(
 8014                        start.row,
 8015                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8016                    );
 8017                    start..end
 8018                } else {
 8019                    start..start
 8020                }
 8021            }
 8022
 8023            fn comment_suffix_range(
 8024                snapshot: &MultiBufferSnapshot,
 8025                row: MultiBufferRow,
 8026                comment_suffix: &str,
 8027                comment_suffix_has_leading_space: bool,
 8028            ) -> Range<Point> {
 8029                let end = Point::new(row.0, snapshot.line_len(row));
 8030                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8031
 8032                let mut line_end_bytes = snapshot
 8033                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8034                    .flatten()
 8035                    .copied();
 8036
 8037                let leading_space_len = if suffix_start_column > 0
 8038                    && line_end_bytes.next() == Some(b' ')
 8039                    && comment_suffix_has_leading_space
 8040                {
 8041                    1
 8042                } else {
 8043                    0
 8044                };
 8045
 8046                // If this line currently begins with the line comment prefix, then record
 8047                // the range containing the prefix.
 8048                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8049                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8050                    start..end
 8051                } else {
 8052                    end..end
 8053                }
 8054            }
 8055
 8056            // TODO: Handle selections that cross excerpts
 8057            for selection in &mut selections {
 8058                let start_column = snapshot
 8059                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8060                    .len;
 8061                let language = if let Some(language) =
 8062                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8063                {
 8064                    language
 8065                } else {
 8066                    continue;
 8067                };
 8068
 8069                selection_edit_ranges.clear();
 8070
 8071                // If multiple selections contain a given row, avoid processing that
 8072                // row more than once.
 8073                let mut start_row = MultiBufferRow(selection.start.row);
 8074                if last_toggled_row == Some(start_row) {
 8075                    start_row = start_row.next_row();
 8076                }
 8077                let end_row =
 8078                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8079                        MultiBufferRow(selection.end.row - 1)
 8080                    } else {
 8081                        MultiBufferRow(selection.end.row)
 8082                    };
 8083                last_toggled_row = Some(end_row);
 8084
 8085                if start_row > end_row {
 8086                    continue;
 8087                }
 8088
 8089                // If the language has line comments, toggle those.
 8090                let full_comment_prefixes = language.line_comment_prefixes();
 8091                if !full_comment_prefixes.is_empty() {
 8092                    let first_prefix = full_comment_prefixes
 8093                        .first()
 8094                        .expect("prefixes is non-empty");
 8095                    let prefix_trimmed_lengths = full_comment_prefixes
 8096                        .iter()
 8097                        .map(|p| p.trim_end_matches(' ').len())
 8098                        .collect::<SmallVec<[usize; 4]>>();
 8099
 8100                    let mut all_selection_lines_are_comments = true;
 8101
 8102                    for row in start_row.0..=end_row.0 {
 8103                        let row = MultiBufferRow(row);
 8104                        if start_row < end_row && snapshot.is_line_blank(row) {
 8105                            continue;
 8106                        }
 8107
 8108                        let prefix_range = full_comment_prefixes
 8109                            .iter()
 8110                            .zip(prefix_trimmed_lengths.iter().copied())
 8111                            .map(|(prefix, trimmed_prefix_len)| {
 8112                                comment_prefix_range(
 8113                                    snapshot.deref(),
 8114                                    row,
 8115                                    &prefix[..trimmed_prefix_len],
 8116                                    &prefix[trimmed_prefix_len..],
 8117                                )
 8118                            })
 8119                            .max_by_key(|range| range.end.column - range.start.column)
 8120                            .expect("prefixes is non-empty");
 8121
 8122                        if prefix_range.is_empty() {
 8123                            all_selection_lines_are_comments = false;
 8124                        }
 8125
 8126                        selection_edit_ranges.push(prefix_range);
 8127                    }
 8128
 8129                    if all_selection_lines_are_comments {
 8130                        edits.extend(
 8131                            selection_edit_ranges
 8132                                .iter()
 8133                                .cloned()
 8134                                .map(|range| (range, empty_str.clone())),
 8135                        );
 8136                    } else {
 8137                        let min_column = selection_edit_ranges
 8138                            .iter()
 8139                            .map(|range| range.start.column)
 8140                            .min()
 8141                            .unwrap_or(0);
 8142                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8143                            let position = Point::new(range.start.row, min_column);
 8144                            (position..position, first_prefix.clone())
 8145                        }));
 8146                    }
 8147                } else if let Some((full_comment_prefix, comment_suffix)) =
 8148                    language.block_comment_delimiters()
 8149                {
 8150                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8151                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8152                    let prefix_range = comment_prefix_range(
 8153                        snapshot.deref(),
 8154                        start_row,
 8155                        comment_prefix,
 8156                        comment_prefix_whitespace,
 8157                    );
 8158                    let suffix_range = comment_suffix_range(
 8159                        snapshot.deref(),
 8160                        end_row,
 8161                        comment_suffix.trim_start_matches(' '),
 8162                        comment_suffix.starts_with(' '),
 8163                    );
 8164
 8165                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8166                        edits.push((
 8167                            prefix_range.start..prefix_range.start,
 8168                            full_comment_prefix.clone(),
 8169                        ));
 8170                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8171                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8172                    } else {
 8173                        edits.push((prefix_range, empty_str.clone()));
 8174                        edits.push((suffix_range, empty_str.clone()));
 8175                    }
 8176                } else {
 8177                    continue;
 8178                }
 8179            }
 8180
 8181            drop(snapshot);
 8182            this.buffer.update(cx, |buffer, cx| {
 8183                buffer.edit(edits, None, cx);
 8184            });
 8185
 8186            // Adjust selections so that they end before any comment suffixes that
 8187            // were inserted.
 8188            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8189            let mut selections = this.selections.all::<Point>(cx);
 8190            let snapshot = this.buffer.read(cx).read(cx);
 8191            for selection in &mut selections {
 8192                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8193                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8194                        Ordering::Less => {
 8195                            suffixes_inserted.next();
 8196                            continue;
 8197                        }
 8198                        Ordering::Greater => break,
 8199                        Ordering::Equal => {
 8200                            if selection.end.column == snapshot.line_len(row) {
 8201                                if selection.is_empty() {
 8202                                    selection.start.column -= suffix_len as u32;
 8203                                }
 8204                                selection.end.column -= suffix_len as u32;
 8205                            }
 8206                            break;
 8207                        }
 8208                    }
 8209                }
 8210            }
 8211
 8212            drop(snapshot);
 8213            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8214
 8215            let selections = this.selections.all::<Point>(cx);
 8216            let selections_on_single_row = selections.windows(2).all(|selections| {
 8217                selections[0].start.row == selections[1].start.row
 8218                    && selections[0].end.row == selections[1].end.row
 8219                    && selections[0].start.row == selections[0].end.row
 8220            });
 8221            let selections_selecting = selections
 8222                .iter()
 8223                .any(|selection| selection.start != selection.end);
 8224            let advance_downwards = action.advance_downwards
 8225                && selections_on_single_row
 8226                && !selections_selecting
 8227                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8228
 8229            if advance_downwards {
 8230                let snapshot = this.buffer.read(cx).snapshot(cx);
 8231
 8232                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8233                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8234                        let mut point = display_point.to_point(display_snapshot);
 8235                        point.row += 1;
 8236                        point = snapshot.clip_point(point, Bias::Left);
 8237                        let display_point = point.to_display_point(display_snapshot);
 8238                        let goal = SelectionGoal::HorizontalPosition(
 8239                            display_snapshot
 8240                                .x_for_display_point(display_point, &text_layout_details)
 8241                                .into(),
 8242                        );
 8243                        (display_point, goal)
 8244                    })
 8245                });
 8246            }
 8247        });
 8248    }
 8249
 8250    pub fn select_enclosing_symbol(
 8251        &mut self,
 8252        _: &SelectEnclosingSymbol,
 8253        cx: &mut ViewContext<Self>,
 8254    ) {
 8255        let buffer = self.buffer.read(cx).snapshot(cx);
 8256        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8257
 8258        fn update_selection(
 8259            selection: &Selection<usize>,
 8260            buffer_snap: &MultiBufferSnapshot,
 8261        ) -> Option<Selection<usize>> {
 8262            let cursor = selection.head();
 8263            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8264            for symbol in symbols.iter().rev() {
 8265                let start = symbol.range.start.to_offset(&buffer_snap);
 8266                let end = symbol.range.end.to_offset(&buffer_snap);
 8267                let new_range = start..end;
 8268                if start < selection.start || end > selection.end {
 8269                    return Some(Selection {
 8270                        id: selection.id,
 8271                        start: new_range.start,
 8272                        end: new_range.end,
 8273                        goal: SelectionGoal::None,
 8274                        reversed: selection.reversed,
 8275                    });
 8276                }
 8277            }
 8278            None
 8279        }
 8280
 8281        let mut selected_larger_symbol = false;
 8282        let new_selections = old_selections
 8283            .iter()
 8284            .map(|selection| match update_selection(selection, &buffer) {
 8285                Some(new_selection) => {
 8286                    if new_selection.range() != selection.range() {
 8287                        selected_larger_symbol = true;
 8288                    }
 8289                    new_selection
 8290                }
 8291                None => selection.clone(),
 8292            })
 8293            .collect::<Vec<_>>();
 8294
 8295        if selected_larger_symbol {
 8296            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8297                s.select(new_selections);
 8298            });
 8299        }
 8300    }
 8301
 8302    pub fn select_larger_syntax_node(
 8303        &mut self,
 8304        _: &SelectLargerSyntaxNode,
 8305        cx: &mut ViewContext<Self>,
 8306    ) {
 8307        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8308        let buffer = self.buffer.read(cx).snapshot(cx);
 8309        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8310
 8311        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8312        let mut selected_larger_node = false;
 8313        let new_selections = old_selections
 8314            .iter()
 8315            .map(|selection| {
 8316                let old_range = selection.start..selection.end;
 8317                let mut new_range = old_range.clone();
 8318                while let Some(containing_range) =
 8319                    buffer.range_for_syntax_ancestor(new_range.clone())
 8320                {
 8321                    new_range = containing_range;
 8322                    if !display_map.intersects_fold(new_range.start)
 8323                        && !display_map.intersects_fold(new_range.end)
 8324                    {
 8325                        break;
 8326                    }
 8327                }
 8328
 8329                selected_larger_node |= new_range != old_range;
 8330                Selection {
 8331                    id: selection.id,
 8332                    start: new_range.start,
 8333                    end: new_range.end,
 8334                    goal: SelectionGoal::None,
 8335                    reversed: selection.reversed,
 8336                }
 8337            })
 8338            .collect::<Vec<_>>();
 8339
 8340        if selected_larger_node {
 8341            stack.push(old_selections);
 8342            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8343                s.select(new_selections);
 8344            });
 8345        }
 8346        self.select_larger_syntax_node_stack = stack;
 8347    }
 8348
 8349    pub fn select_smaller_syntax_node(
 8350        &mut self,
 8351        _: &SelectSmallerSyntaxNode,
 8352        cx: &mut ViewContext<Self>,
 8353    ) {
 8354        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8355        if let Some(selections) = stack.pop() {
 8356            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8357                s.select(selections.to_vec());
 8358            });
 8359        }
 8360        self.select_larger_syntax_node_stack = stack;
 8361    }
 8362
 8363    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8364        if !EditorSettings::get_global(cx).gutter.runnables {
 8365            self.clear_tasks();
 8366            return Task::ready(());
 8367        }
 8368        let project = self.project.clone();
 8369        cx.spawn(|this, mut cx| async move {
 8370            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8371                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8372            }) else {
 8373                return;
 8374            };
 8375
 8376            let Some(project) = project else {
 8377                return;
 8378            };
 8379
 8380            let hide_runnables = project
 8381                .update(&mut cx, |project, cx| {
 8382                    // Do not display any test indicators in non-dev server remote projects.
 8383                    project.is_remote() && project.ssh_connection_string(cx).is_none()
 8384                })
 8385                .unwrap_or(true);
 8386            if hide_runnables {
 8387                return;
 8388            }
 8389            let new_rows =
 8390                cx.background_executor()
 8391                    .spawn({
 8392                        let snapshot = display_snapshot.clone();
 8393                        async move {
 8394                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8395                        }
 8396                    })
 8397                    .await;
 8398            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8399
 8400            this.update(&mut cx, |this, _| {
 8401                this.clear_tasks();
 8402                for (key, value) in rows {
 8403                    this.insert_tasks(key, value);
 8404                }
 8405            })
 8406            .ok();
 8407        })
 8408    }
 8409    fn fetch_runnable_ranges(
 8410        snapshot: &DisplaySnapshot,
 8411        range: Range<Anchor>,
 8412    ) -> Vec<language::RunnableRange> {
 8413        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8414    }
 8415
 8416    fn runnable_rows(
 8417        project: Model<Project>,
 8418        snapshot: DisplaySnapshot,
 8419        runnable_ranges: Vec<RunnableRange>,
 8420        mut cx: AsyncWindowContext,
 8421    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8422        runnable_ranges
 8423            .into_iter()
 8424            .filter_map(|mut runnable| {
 8425                let tasks = cx
 8426                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8427                    .ok()?;
 8428                if tasks.is_empty() {
 8429                    return None;
 8430                }
 8431
 8432                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8433
 8434                let row = snapshot
 8435                    .buffer_snapshot
 8436                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8437                    .1
 8438                    .start
 8439                    .row;
 8440
 8441                let context_range =
 8442                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8443                Some((
 8444                    (runnable.buffer_id, row),
 8445                    RunnableTasks {
 8446                        templates: tasks,
 8447                        offset: MultiBufferOffset(runnable.run_range.start),
 8448                        context_range,
 8449                        column: point.column,
 8450                        extra_variables: runnable.extra_captures,
 8451                    },
 8452                ))
 8453            })
 8454            .collect()
 8455    }
 8456
 8457    fn templates_with_tags(
 8458        project: &Model<Project>,
 8459        runnable: &mut Runnable,
 8460        cx: &WindowContext<'_>,
 8461    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8462        let (inventory, worktree_id) = project.read_with(cx, |project, cx| {
 8463            let worktree_id = project
 8464                .buffer_for_id(runnable.buffer)
 8465                .and_then(|buffer| buffer.read(cx).file())
 8466                .map(|file| WorktreeId::from_usize(file.worktree_id()));
 8467
 8468            (project.task_inventory().clone(), worktree_id)
 8469        });
 8470
 8471        let inventory = inventory.read(cx);
 8472        let tags = mem::take(&mut runnable.tags);
 8473        let mut tags: Vec<_> = tags
 8474            .into_iter()
 8475            .flat_map(|tag| {
 8476                let tag = tag.0.clone();
 8477                inventory
 8478                    .list_tasks(Some(runnable.language.clone()), worktree_id)
 8479                    .into_iter()
 8480                    .filter(move |(_, template)| {
 8481                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8482                    })
 8483            })
 8484            .sorted_by_key(|(kind, _)| kind.to_owned())
 8485            .collect();
 8486        if let Some((leading_tag_source, _)) = tags.first() {
 8487            // Strongest source wins; if we have worktree tag binding, prefer that to
 8488            // global and language bindings;
 8489            // if we have a global binding, prefer that to language binding.
 8490            let first_mismatch = tags
 8491                .iter()
 8492                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8493            if let Some(index) = first_mismatch {
 8494                tags.truncate(index);
 8495            }
 8496        }
 8497
 8498        tags
 8499    }
 8500
 8501    pub fn move_to_enclosing_bracket(
 8502        &mut self,
 8503        _: &MoveToEnclosingBracket,
 8504        cx: &mut ViewContext<Self>,
 8505    ) {
 8506        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8507            s.move_offsets_with(|snapshot, selection| {
 8508                let Some(enclosing_bracket_ranges) =
 8509                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8510                else {
 8511                    return;
 8512                };
 8513
 8514                let mut best_length = usize::MAX;
 8515                let mut best_inside = false;
 8516                let mut best_in_bracket_range = false;
 8517                let mut best_destination = None;
 8518                for (open, close) in enclosing_bracket_ranges {
 8519                    let close = close.to_inclusive();
 8520                    let length = close.end() - open.start;
 8521                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8522                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8523                        || close.contains(&selection.head());
 8524
 8525                    // If best is next to a bracket and current isn't, skip
 8526                    if !in_bracket_range && best_in_bracket_range {
 8527                        continue;
 8528                    }
 8529
 8530                    // Prefer smaller lengths unless best is inside and current isn't
 8531                    if length > best_length && (best_inside || !inside) {
 8532                        continue;
 8533                    }
 8534
 8535                    best_length = length;
 8536                    best_inside = inside;
 8537                    best_in_bracket_range = in_bracket_range;
 8538                    best_destination = Some(
 8539                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8540                            if inside {
 8541                                open.end
 8542                            } else {
 8543                                open.start
 8544                            }
 8545                        } else {
 8546                            if inside {
 8547                                *close.start()
 8548                            } else {
 8549                                *close.end()
 8550                            }
 8551                        },
 8552                    );
 8553                }
 8554
 8555                if let Some(destination) = best_destination {
 8556                    selection.collapse_to(destination, SelectionGoal::None);
 8557                }
 8558            })
 8559        });
 8560    }
 8561
 8562    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 8563        self.end_selection(cx);
 8564        self.selection_history.mode = SelectionHistoryMode::Undoing;
 8565        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 8566            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8567            self.select_next_state = entry.select_next_state;
 8568            self.select_prev_state = entry.select_prev_state;
 8569            self.add_selections_state = entry.add_selections_state;
 8570            self.request_autoscroll(Autoscroll::newest(), cx);
 8571        }
 8572        self.selection_history.mode = SelectionHistoryMode::Normal;
 8573    }
 8574
 8575    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 8576        self.end_selection(cx);
 8577        self.selection_history.mode = SelectionHistoryMode::Redoing;
 8578        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 8579            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8580            self.select_next_state = entry.select_next_state;
 8581            self.select_prev_state = entry.select_prev_state;
 8582            self.add_selections_state = entry.add_selections_state;
 8583            self.request_autoscroll(Autoscroll::newest(), cx);
 8584        }
 8585        self.selection_history.mode = SelectionHistoryMode::Normal;
 8586    }
 8587
 8588    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 8589        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 8590    }
 8591
 8592    pub fn expand_excerpts_down(
 8593        &mut self,
 8594        action: &ExpandExcerptsDown,
 8595        cx: &mut ViewContext<Self>,
 8596    ) {
 8597        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 8598    }
 8599
 8600    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 8601        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 8602    }
 8603
 8604    pub fn expand_excerpts_for_direction(
 8605        &mut self,
 8606        lines: u32,
 8607        direction: ExpandExcerptDirection,
 8608        cx: &mut ViewContext<Self>,
 8609    ) {
 8610        let selections = self.selections.disjoint_anchors();
 8611
 8612        let lines = if lines == 0 {
 8613            EditorSettings::get_global(cx).expand_excerpt_lines
 8614        } else {
 8615            lines
 8616        };
 8617
 8618        self.buffer.update(cx, |buffer, cx| {
 8619            buffer.expand_excerpts(
 8620                selections
 8621                    .into_iter()
 8622                    .map(|selection| selection.head().excerpt_id)
 8623                    .dedup(),
 8624                lines,
 8625                direction,
 8626                cx,
 8627            )
 8628        })
 8629    }
 8630
 8631    pub fn expand_excerpt(
 8632        &mut self,
 8633        excerpt: ExcerptId,
 8634        direction: ExpandExcerptDirection,
 8635        cx: &mut ViewContext<Self>,
 8636    ) {
 8637        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 8638        self.buffer.update(cx, |buffer, cx| {
 8639            buffer.expand_excerpts([excerpt], lines, direction, cx)
 8640        })
 8641    }
 8642
 8643    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8644        self.go_to_diagnostic_impl(Direction::Next, cx)
 8645    }
 8646
 8647    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8648        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8649    }
 8650
 8651    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8652        let buffer = self.buffer.read(cx).snapshot(cx);
 8653        let selection = self.selections.newest::<usize>(cx);
 8654
 8655        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8656        if direction == Direction::Next {
 8657            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8658                let (group_id, jump_to) = popover.activation_info();
 8659                if self.activate_diagnostics(group_id, cx) {
 8660                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8661                        let mut new_selection = s.newest_anchor().clone();
 8662                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 8663                        s.select_anchors(vec![new_selection.clone()]);
 8664                    });
 8665                }
 8666                return;
 8667            }
 8668        }
 8669
 8670        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 8671            active_diagnostics
 8672                .primary_range
 8673                .to_offset(&buffer)
 8674                .to_inclusive()
 8675        });
 8676        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 8677            if active_primary_range.contains(&selection.head()) {
 8678                *active_primary_range.start()
 8679            } else {
 8680                selection.head()
 8681            }
 8682        } else {
 8683            selection.head()
 8684        };
 8685        let snapshot = self.snapshot(cx);
 8686        loop {
 8687            let diagnostics = if direction == Direction::Prev {
 8688                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 8689            } else {
 8690                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 8691            }
 8692            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 8693            let group = diagnostics
 8694                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 8695                // be sorted in a stable way
 8696                // skip until we are at current active diagnostic, if it exists
 8697                .skip_while(|entry| {
 8698                    (match direction {
 8699                        Direction::Prev => entry.range.start >= search_start,
 8700                        Direction::Next => entry.range.start <= search_start,
 8701                    }) && self
 8702                        .active_diagnostics
 8703                        .as_ref()
 8704                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 8705                })
 8706                .find_map(|entry| {
 8707                    if entry.diagnostic.is_primary
 8708                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 8709                        && !entry.range.is_empty()
 8710                        // if we match with the active diagnostic, skip it
 8711                        && Some(entry.diagnostic.group_id)
 8712                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 8713                    {
 8714                        Some((entry.range, entry.diagnostic.group_id))
 8715                    } else {
 8716                        None
 8717                    }
 8718                });
 8719
 8720            if let Some((primary_range, group_id)) = group {
 8721                if self.activate_diagnostics(group_id, cx) {
 8722                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8723                        s.select(vec![Selection {
 8724                            id: selection.id,
 8725                            start: primary_range.start,
 8726                            end: primary_range.start,
 8727                            reversed: false,
 8728                            goal: SelectionGoal::None,
 8729                        }]);
 8730                    });
 8731                }
 8732                break;
 8733            } else {
 8734                // Cycle around to the start of the buffer, potentially moving back to the start of
 8735                // the currently active diagnostic.
 8736                active_primary_range.take();
 8737                if direction == Direction::Prev {
 8738                    if search_start == buffer.len() {
 8739                        break;
 8740                    } else {
 8741                        search_start = buffer.len();
 8742                    }
 8743                } else if search_start == 0 {
 8744                    break;
 8745                } else {
 8746                    search_start = 0;
 8747                }
 8748            }
 8749        }
 8750    }
 8751
 8752    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 8753        let snapshot = self
 8754            .display_map
 8755            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8756        let selection = self.selections.newest::<Point>(cx);
 8757
 8758        if !self.seek_in_direction(
 8759            &snapshot,
 8760            selection.head(),
 8761            false,
 8762            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8763                MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
 8764            ),
 8765            cx,
 8766        ) {
 8767            let wrapped_point = Point::zero();
 8768            self.seek_in_direction(
 8769                &snapshot,
 8770                wrapped_point,
 8771                true,
 8772                snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8773                    MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 8774                ),
 8775                cx,
 8776            );
 8777        }
 8778    }
 8779
 8780    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 8781        let snapshot = self
 8782            .display_map
 8783            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8784        let selection = self.selections.newest::<Point>(cx);
 8785
 8786        if !self.seek_in_direction(
 8787            &snapshot,
 8788            selection.head(),
 8789            false,
 8790            snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8791                MultiBufferRow(0)..MultiBufferRow(selection.head().row),
 8792            ),
 8793            cx,
 8794        ) {
 8795            let wrapped_point = snapshot.buffer_snapshot.max_point();
 8796            self.seek_in_direction(
 8797                &snapshot,
 8798                wrapped_point,
 8799                true,
 8800                snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8801                    MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
 8802                ),
 8803                cx,
 8804            );
 8805        }
 8806    }
 8807
 8808    fn seek_in_direction(
 8809        &mut self,
 8810        snapshot: &DisplaySnapshot,
 8811        initial_point: Point,
 8812        is_wrapped: bool,
 8813        hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
 8814        cx: &mut ViewContext<Editor>,
 8815    ) -> bool {
 8816        let display_point = initial_point.to_display_point(snapshot);
 8817        let mut hunks = hunks
 8818            .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
 8819            .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
 8820            .dedup();
 8821
 8822        if let Some(hunk) = hunks.next() {
 8823            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8824                let row = hunk.start_display_row();
 8825                let point = DisplayPoint::new(row, 0);
 8826                s.select_display_ranges([point..point]);
 8827            });
 8828
 8829            true
 8830        } else {
 8831            false
 8832        }
 8833    }
 8834
 8835    pub fn go_to_definition(
 8836        &mut self,
 8837        _: &GoToDefinition,
 8838        cx: &mut ViewContext<Self>,
 8839    ) -> Task<Result<bool>> {
 8840        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
 8841    }
 8842
 8843    pub fn go_to_implementation(
 8844        &mut self,
 8845        _: &GoToImplementation,
 8846        cx: &mut ViewContext<Self>,
 8847    ) -> Task<Result<bool>> {
 8848        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 8849    }
 8850
 8851    pub fn go_to_implementation_split(
 8852        &mut self,
 8853        _: &GoToImplementationSplit,
 8854        cx: &mut ViewContext<Self>,
 8855    ) -> Task<Result<bool>> {
 8856        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 8857    }
 8858
 8859    pub fn go_to_type_definition(
 8860        &mut self,
 8861        _: &GoToTypeDefinition,
 8862        cx: &mut ViewContext<Self>,
 8863    ) -> Task<Result<bool>> {
 8864        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 8865    }
 8866
 8867    pub fn go_to_definition_split(
 8868        &mut self,
 8869        _: &GoToDefinitionSplit,
 8870        cx: &mut ViewContext<Self>,
 8871    ) -> Task<Result<bool>> {
 8872        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 8873    }
 8874
 8875    pub fn go_to_type_definition_split(
 8876        &mut self,
 8877        _: &GoToTypeDefinitionSplit,
 8878        cx: &mut ViewContext<Self>,
 8879    ) -> Task<Result<bool>> {
 8880        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 8881    }
 8882
 8883    fn go_to_definition_of_kind(
 8884        &mut self,
 8885        kind: GotoDefinitionKind,
 8886        split: bool,
 8887        cx: &mut ViewContext<Self>,
 8888    ) -> Task<Result<bool>> {
 8889        let Some(workspace) = self.workspace() else {
 8890            return Task::ready(Ok(false));
 8891        };
 8892        let buffer = self.buffer.read(cx);
 8893        let head = self.selections.newest::<usize>(cx).head();
 8894        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 8895            text_anchor
 8896        } else {
 8897            return Task::ready(Ok(false));
 8898        };
 8899
 8900        let project = workspace.read(cx).project().clone();
 8901        let definitions = project.update(cx, |project, cx| match kind {
 8902            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 8903            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 8904            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 8905        });
 8906
 8907        cx.spawn(|editor, mut cx| async move {
 8908            let definitions = definitions.await?;
 8909            let navigated = editor
 8910                .update(&mut cx, |editor, cx| {
 8911                    editor.navigate_to_hover_links(
 8912                        Some(kind),
 8913                        definitions
 8914                            .into_iter()
 8915                            .filter(|location| {
 8916                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 8917                            })
 8918                            .map(HoverLink::Text)
 8919                            .collect::<Vec<_>>(),
 8920                        split,
 8921                        cx,
 8922                    )
 8923                })?
 8924                .await?;
 8925            anyhow::Ok(navigated)
 8926        })
 8927    }
 8928
 8929    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 8930        let position = self.selections.newest_anchor().head();
 8931        let Some((buffer, buffer_position)) =
 8932            self.buffer.read(cx).text_anchor_for_position(position, cx)
 8933        else {
 8934            return;
 8935        };
 8936
 8937        cx.spawn(|editor, mut cx| async move {
 8938            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 8939                editor.update(&mut cx, |_, cx| {
 8940                    cx.open_url(&url);
 8941                })
 8942            } else {
 8943                Ok(())
 8944            }
 8945        })
 8946        .detach();
 8947    }
 8948
 8949    pub(crate) fn navigate_to_hover_links(
 8950        &mut self,
 8951        kind: Option<GotoDefinitionKind>,
 8952        mut definitions: Vec<HoverLink>,
 8953        split: bool,
 8954        cx: &mut ViewContext<Editor>,
 8955    ) -> Task<Result<bool>> {
 8956        // If there is one definition, just open it directly
 8957        if definitions.len() == 1 {
 8958            let definition = definitions.pop().unwrap();
 8959            let target_task = match definition {
 8960                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 8961                HoverLink::InlayHint(lsp_location, server_id) => {
 8962                    self.compute_target_location(lsp_location, server_id, cx)
 8963                }
 8964                HoverLink::Url(url) => {
 8965                    cx.open_url(&url);
 8966                    Task::ready(Ok(None))
 8967                }
 8968            };
 8969            cx.spawn(|editor, mut cx| async move {
 8970                let target = target_task.await.context("target resolution task")?;
 8971                if let Some(target) = target {
 8972                    editor.update(&mut cx, |editor, cx| {
 8973                        let Some(workspace) = editor.workspace() else {
 8974                            return false;
 8975                        };
 8976                        let pane = workspace.read(cx).active_pane().clone();
 8977
 8978                        let range = target.range.to_offset(target.buffer.read(cx));
 8979                        let range = editor.range_for_match(&range);
 8980
 8981                        /// If select range has more than one line, we
 8982                        /// just point the cursor to range.start.
 8983                        fn check_multiline_range(
 8984                            buffer: &Buffer,
 8985                            range: Range<usize>,
 8986                        ) -> Range<usize> {
 8987                            if buffer.offset_to_point(range.start).row
 8988                                == buffer.offset_to_point(range.end).row
 8989                            {
 8990                                range
 8991                            } else {
 8992                                range.start..range.start
 8993                            }
 8994                        }
 8995
 8996                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 8997                            let buffer = target.buffer.read(cx);
 8998                            let range = check_multiline_range(buffer, range);
 8999                            editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 9000                                s.select_ranges([range]);
 9001                            });
 9002                        } else {
 9003                            cx.window_context().defer(move |cx| {
 9004                                let target_editor: View<Self> =
 9005                                    workspace.update(cx, |workspace, cx| {
 9006                                        let pane = if split {
 9007                                            workspace.adjacent_pane(cx)
 9008                                        } else {
 9009                                            workspace.active_pane().clone()
 9010                                        };
 9011
 9012                                        workspace.open_project_item(pane, target.buffer.clone(), cx)
 9013                                    });
 9014                                target_editor.update(cx, |target_editor, cx| {
 9015                                    // When selecting a definition in a different buffer, disable the nav history
 9016                                    // to avoid creating a history entry at the previous cursor location.
 9017                                    pane.update(cx, |pane, _| pane.disable_history());
 9018                                    let buffer = target.buffer.read(cx);
 9019                                    let range = check_multiline_range(buffer, range);
 9020                                    target_editor.change_selections(
 9021                                        Some(Autoscroll::focused()),
 9022                                        cx,
 9023                                        |s| {
 9024                                            s.select_ranges([range]);
 9025                                        },
 9026                                    );
 9027                                    pane.update(cx, |pane, _| pane.enable_history());
 9028                                });
 9029                            });
 9030                        }
 9031                        true
 9032                    })
 9033                } else {
 9034                    Ok(false)
 9035                }
 9036            })
 9037        } else if !definitions.is_empty() {
 9038            let replica_id = self.replica_id(cx);
 9039            cx.spawn(|editor, mut cx| async move {
 9040                let (title, location_tasks, workspace) = editor
 9041                    .update(&mut cx, |editor, cx| {
 9042                        let tab_kind = match kind {
 9043                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9044                            _ => "Definitions",
 9045                        };
 9046                        let title = definitions
 9047                            .iter()
 9048                            .find_map(|definition| match definition {
 9049                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9050                                    let buffer = origin.buffer.read(cx);
 9051                                    format!(
 9052                                        "{} for {}",
 9053                                        tab_kind,
 9054                                        buffer
 9055                                            .text_for_range(origin.range.clone())
 9056                                            .collect::<String>()
 9057                                    )
 9058                                }),
 9059                                HoverLink::InlayHint(_, _) => None,
 9060                                HoverLink::Url(_) => None,
 9061                            })
 9062                            .unwrap_or(tab_kind.to_string());
 9063                        let location_tasks = definitions
 9064                            .into_iter()
 9065                            .map(|definition| match definition {
 9066                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9067                                HoverLink::InlayHint(lsp_location, server_id) => {
 9068                                    editor.compute_target_location(lsp_location, server_id, cx)
 9069                                }
 9070                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9071                            })
 9072                            .collect::<Vec<_>>();
 9073                        (title, location_tasks, editor.workspace().clone())
 9074                    })
 9075                    .context("location tasks preparation")?;
 9076
 9077                let locations = futures::future::join_all(location_tasks)
 9078                    .await
 9079                    .into_iter()
 9080                    .filter_map(|location| location.transpose())
 9081                    .collect::<Result<_>>()
 9082                    .context("location tasks")?;
 9083
 9084                let Some(workspace) = workspace else {
 9085                    return Ok(false);
 9086                };
 9087                let opened = workspace
 9088                    .update(&mut cx, |workspace, cx| {
 9089                        Self::open_locations_in_multibuffer(
 9090                            workspace, locations, replica_id, title, split, cx,
 9091                        )
 9092                    })
 9093                    .ok();
 9094
 9095                anyhow::Ok(opened.is_some())
 9096            })
 9097        } else {
 9098            Task::ready(Ok(false))
 9099        }
 9100    }
 9101
 9102    fn compute_target_location(
 9103        &self,
 9104        lsp_location: lsp::Location,
 9105        server_id: LanguageServerId,
 9106        cx: &mut ViewContext<Editor>,
 9107    ) -> Task<anyhow::Result<Option<Location>>> {
 9108        let Some(project) = self.project.clone() else {
 9109            return Task::Ready(Some(Ok(None)));
 9110        };
 9111
 9112        cx.spawn(move |editor, mut cx| async move {
 9113            let location_task = editor.update(&mut cx, |editor, cx| {
 9114                project.update(cx, |project, cx| {
 9115                    let language_server_name =
 9116                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 9117                            project
 9118                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 9119                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 9120                        });
 9121                    language_server_name.map(|language_server_name| {
 9122                        project.open_local_buffer_via_lsp(
 9123                            lsp_location.uri.clone(),
 9124                            server_id,
 9125                            language_server_name,
 9126                            cx,
 9127                        )
 9128                    })
 9129                })
 9130            })?;
 9131            let location = match location_task {
 9132                Some(task) => Some({
 9133                    let target_buffer_handle = task.await.context("open local buffer")?;
 9134                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9135                        let target_start = target_buffer
 9136                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9137                        let target_end = target_buffer
 9138                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9139                        target_buffer.anchor_after(target_start)
 9140                            ..target_buffer.anchor_before(target_end)
 9141                    })?;
 9142                    Location {
 9143                        buffer: target_buffer_handle,
 9144                        range,
 9145                    }
 9146                }),
 9147                None => None,
 9148            };
 9149            Ok(location)
 9150        })
 9151    }
 9152
 9153    pub fn find_all_references(
 9154        &mut self,
 9155        _: &FindAllReferences,
 9156        cx: &mut ViewContext<Self>,
 9157    ) -> Option<Task<Result<()>>> {
 9158        let multi_buffer = self.buffer.read(cx);
 9159        let selection = self.selections.newest::<usize>(cx);
 9160        let head = selection.head();
 9161
 9162        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9163        let head_anchor = multi_buffer_snapshot.anchor_at(
 9164            head,
 9165            if head < selection.tail() {
 9166                Bias::Right
 9167            } else {
 9168                Bias::Left
 9169            },
 9170        );
 9171
 9172        match self
 9173            .find_all_references_task_sources
 9174            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9175        {
 9176            Ok(_) => {
 9177                log::info!(
 9178                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9179                );
 9180                return None;
 9181            }
 9182            Err(i) => {
 9183                self.find_all_references_task_sources.insert(i, head_anchor);
 9184            }
 9185        }
 9186
 9187        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9188        let replica_id = self.replica_id(cx);
 9189        let workspace = self.workspace()?;
 9190        let project = workspace.read(cx).project().clone();
 9191        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9192        Some(cx.spawn(|editor, mut cx| async move {
 9193            let _cleanup = defer({
 9194                let mut cx = cx.clone();
 9195                move || {
 9196                    let _ = editor.update(&mut cx, |editor, _| {
 9197                        if let Ok(i) =
 9198                            editor
 9199                                .find_all_references_task_sources
 9200                                .binary_search_by(|anchor| {
 9201                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9202                                })
 9203                        {
 9204                            editor.find_all_references_task_sources.remove(i);
 9205                        }
 9206                    });
 9207                }
 9208            });
 9209
 9210            let locations = references.await?;
 9211            if locations.is_empty() {
 9212                return anyhow::Ok(());
 9213            }
 9214
 9215            workspace.update(&mut cx, |workspace, cx| {
 9216                let title = locations
 9217                    .first()
 9218                    .as_ref()
 9219                    .map(|location| {
 9220                        let buffer = location.buffer.read(cx);
 9221                        format!(
 9222                            "References to `{}`",
 9223                            buffer
 9224                                .text_for_range(location.range.clone())
 9225                                .collect::<String>()
 9226                        )
 9227                    })
 9228                    .unwrap();
 9229                Self::open_locations_in_multibuffer(
 9230                    workspace, locations, replica_id, title, false, cx,
 9231                );
 9232            })
 9233        }))
 9234    }
 9235
 9236    /// Opens a multibuffer with the given project locations in it
 9237    pub fn open_locations_in_multibuffer(
 9238        workspace: &mut Workspace,
 9239        mut locations: Vec<Location>,
 9240        replica_id: ReplicaId,
 9241        title: String,
 9242        split: bool,
 9243        cx: &mut ViewContext<Workspace>,
 9244    ) {
 9245        // If there are multiple definitions, open them in a multibuffer
 9246        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9247        let mut locations = locations.into_iter().peekable();
 9248        let mut ranges_to_highlight = Vec::new();
 9249        let capability = workspace.project().read(cx).capability();
 9250
 9251        let excerpt_buffer = cx.new_model(|cx| {
 9252            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 9253            while let Some(location) = locations.next() {
 9254                let buffer = location.buffer.read(cx);
 9255                let mut ranges_for_buffer = Vec::new();
 9256                let range = location.range.to_offset(buffer);
 9257                ranges_for_buffer.push(range.clone());
 9258
 9259                while let Some(next_location) = locations.peek() {
 9260                    if next_location.buffer == location.buffer {
 9261                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9262                        locations.next();
 9263                    } else {
 9264                        break;
 9265                    }
 9266                }
 9267
 9268                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9269                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9270                    location.buffer.clone(),
 9271                    ranges_for_buffer,
 9272                    DEFAULT_MULTIBUFFER_CONTEXT,
 9273                    cx,
 9274                ))
 9275            }
 9276
 9277            multibuffer.with_title(title)
 9278        });
 9279
 9280        let editor = cx.new_view(|cx| {
 9281            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9282        });
 9283        editor.update(cx, |editor, cx| {
 9284            if let Some(first_range) = ranges_to_highlight.first() {
 9285                editor.change_selections(None, cx, |selections| {
 9286                    selections.clear_disjoint();
 9287                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9288                });
 9289            }
 9290            editor.highlight_background::<Self>(
 9291                &ranges_to_highlight,
 9292                |theme| theme.editor_highlighted_line_background,
 9293                cx,
 9294            );
 9295        });
 9296
 9297        let item = Box::new(editor);
 9298        let item_id = item.item_id();
 9299
 9300        if split {
 9301            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9302        } else {
 9303            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9304                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9305                    pane.close_current_preview_item(cx)
 9306                } else {
 9307                    None
 9308                }
 9309            });
 9310            workspace.add_item_to_active_pane(item.clone(), destination_index, cx);
 9311        }
 9312        workspace.active_pane().update(cx, |pane, cx| {
 9313            pane.set_preview_item_id(Some(item_id), cx);
 9314        });
 9315    }
 9316
 9317    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9318        use language::ToOffset as _;
 9319
 9320        let project = self.project.clone()?;
 9321        let selection = self.selections.newest_anchor().clone();
 9322        let (cursor_buffer, cursor_buffer_position) = self
 9323            .buffer
 9324            .read(cx)
 9325            .text_anchor_for_position(selection.head(), cx)?;
 9326        let (tail_buffer, cursor_buffer_position_end) = self
 9327            .buffer
 9328            .read(cx)
 9329            .text_anchor_for_position(selection.tail(), cx)?;
 9330        if tail_buffer != cursor_buffer {
 9331            return None;
 9332        }
 9333
 9334        let snapshot = cursor_buffer.read(cx).snapshot();
 9335        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9336        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9337        let prepare_rename = project.update(cx, |project, cx| {
 9338            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 9339        });
 9340        drop(snapshot);
 9341
 9342        Some(cx.spawn(|this, mut cx| async move {
 9343            let rename_range = if let Some(range) = prepare_rename.await? {
 9344                Some(range)
 9345            } else {
 9346                this.update(&mut cx, |this, cx| {
 9347                    let buffer = this.buffer.read(cx).snapshot(cx);
 9348                    let mut buffer_highlights = this
 9349                        .document_highlights_for_position(selection.head(), &buffer)
 9350                        .filter(|highlight| {
 9351                            highlight.start.excerpt_id == selection.head().excerpt_id
 9352                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9353                        });
 9354                    buffer_highlights
 9355                        .next()
 9356                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9357                })?
 9358            };
 9359            if let Some(rename_range) = rename_range {
 9360                this.update(&mut cx, |this, cx| {
 9361                    let snapshot = cursor_buffer.read(cx).snapshot();
 9362                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9363                    let cursor_offset_in_rename_range =
 9364                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9365                    let cursor_offset_in_rename_range_end =
 9366                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9367
 9368                    this.take_rename(false, cx);
 9369                    let buffer = this.buffer.read(cx).read(cx);
 9370                    let cursor_offset = selection.head().to_offset(&buffer);
 9371                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9372                    let rename_end = rename_start + rename_buffer_range.len();
 9373                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9374                    let mut old_highlight_id = None;
 9375                    let old_name: Arc<str> = buffer
 9376                        .chunks(rename_start..rename_end, true)
 9377                        .map(|chunk| {
 9378                            if old_highlight_id.is_none() {
 9379                                old_highlight_id = chunk.syntax_highlight_id;
 9380                            }
 9381                            chunk.text
 9382                        })
 9383                        .collect::<String>()
 9384                        .into();
 9385
 9386                    drop(buffer);
 9387
 9388                    // Position the selection in the rename editor so that it matches the current selection.
 9389                    this.show_local_selections = false;
 9390                    let rename_editor = cx.new_view(|cx| {
 9391                        let mut editor = Editor::single_line(cx);
 9392                        editor.buffer.update(cx, |buffer, cx| {
 9393                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9394                        });
 9395                        let rename_selection_range = match cursor_offset_in_rename_range
 9396                            .cmp(&cursor_offset_in_rename_range_end)
 9397                        {
 9398                            Ordering::Equal => {
 9399                                editor.select_all(&SelectAll, cx);
 9400                                return editor;
 9401                            }
 9402                            Ordering::Less => {
 9403                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9404                            }
 9405                            Ordering::Greater => {
 9406                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9407                            }
 9408                        };
 9409                        if rename_selection_range.end > old_name.len() {
 9410                            editor.select_all(&SelectAll, cx);
 9411                        } else {
 9412                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9413                                s.select_ranges([rename_selection_range]);
 9414                            });
 9415                        }
 9416                        editor
 9417                    });
 9418
 9419                    let write_highlights =
 9420                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9421                    let read_highlights =
 9422                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9423                    let ranges = write_highlights
 9424                        .iter()
 9425                        .flat_map(|(_, ranges)| ranges.iter())
 9426                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9427                        .cloned()
 9428                        .collect();
 9429
 9430                    this.highlight_text::<Rename>(
 9431                        ranges,
 9432                        HighlightStyle {
 9433                            fade_out: Some(0.6),
 9434                            ..Default::default()
 9435                        },
 9436                        cx,
 9437                    );
 9438                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9439                    cx.focus(&rename_focus_handle);
 9440                    let block_id = this.insert_blocks(
 9441                        [BlockProperties {
 9442                            style: BlockStyle::Flex,
 9443                            position: range.start,
 9444                            height: 1,
 9445                            render: Box::new({
 9446                                let rename_editor = rename_editor.clone();
 9447                                move |cx: &mut BlockContext| {
 9448                                    let mut text_style = cx.editor_style.text.clone();
 9449                                    if let Some(highlight_style) = old_highlight_id
 9450                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 9451                                    {
 9452                                        text_style = text_style.highlight(highlight_style);
 9453                                    }
 9454                                    div()
 9455                                        .pl(cx.anchor_x)
 9456                                        .child(EditorElement::new(
 9457                                            &rename_editor,
 9458                                            EditorStyle {
 9459                                                background: cx.theme().system().transparent,
 9460                                                local_player: cx.editor_style.local_player,
 9461                                                text: text_style,
 9462                                                scrollbar_width: cx.editor_style.scrollbar_width,
 9463                                                syntax: cx.editor_style.syntax.clone(),
 9464                                                status: cx.editor_style.status.clone(),
 9465                                                inlay_hints_style: HighlightStyle {
 9466                                                    color: Some(cx.theme().status().hint),
 9467                                                    font_weight: Some(FontWeight::BOLD),
 9468                                                    ..HighlightStyle::default()
 9469                                                },
 9470                                                suggestions_style: HighlightStyle {
 9471                                                    color: Some(cx.theme().status().predictive),
 9472                                                    ..HighlightStyle::default()
 9473                                                },
 9474                                            },
 9475                                        ))
 9476                                        .into_any_element()
 9477                                }
 9478                            }),
 9479                            disposition: BlockDisposition::Below,
 9480                        }],
 9481                        Some(Autoscroll::fit()),
 9482                        cx,
 9483                    )[0];
 9484                    this.pending_rename = Some(RenameState {
 9485                        range,
 9486                        old_name,
 9487                        editor: rename_editor,
 9488                        block_id,
 9489                    });
 9490                })?;
 9491            }
 9492
 9493            Ok(())
 9494        }))
 9495    }
 9496
 9497    pub fn confirm_rename(
 9498        &mut self,
 9499        _: &ConfirmRename,
 9500        cx: &mut ViewContext<Self>,
 9501    ) -> Option<Task<Result<()>>> {
 9502        let rename = self.take_rename(false, cx)?;
 9503        let workspace = self.workspace()?;
 9504        let (start_buffer, start) = self
 9505            .buffer
 9506            .read(cx)
 9507            .text_anchor_for_position(rename.range.start, cx)?;
 9508        let (end_buffer, end) = self
 9509            .buffer
 9510            .read(cx)
 9511            .text_anchor_for_position(rename.range.end, cx)?;
 9512        if start_buffer != end_buffer {
 9513            return None;
 9514        }
 9515
 9516        let buffer = start_buffer;
 9517        let range = start..end;
 9518        let old_name = rename.old_name;
 9519        let new_name = rename.editor.read(cx).text(cx);
 9520
 9521        let rename = workspace
 9522            .read(cx)
 9523            .project()
 9524            .clone()
 9525            .update(cx, |project, cx| {
 9526                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 9527            });
 9528        let workspace = workspace.downgrade();
 9529
 9530        Some(cx.spawn(|editor, mut cx| async move {
 9531            let project_transaction = rename.await?;
 9532            Self::open_project_transaction(
 9533                &editor,
 9534                workspace,
 9535                project_transaction,
 9536                format!("Rename: {}{}", old_name, new_name),
 9537                cx.clone(),
 9538            )
 9539            .await?;
 9540
 9541            editor.update(&mut cx, |editor, cx| {
 9542                editor.refresh_document_highlights(cx);
 9543            })?;
 9544            Ok(())
 9545        }))
 9546    }
 9547
 9548    fn take_rename(
 9549        &mut self,
 9550        moving_cursor: bool,
 9551        cx: &mut ViewContext<Self>,
 9552    ) -> Option<RenameState> {
 9553        let rename = self.pending_rename.take()?;
 9554        if rename.editor.focus_handle(cx).is_focused(cx) {
 9555            cx.focus(&self.focus_handle);
 9556        }
 9557
 9558        self.remove_blocks(
 9559            [rename.block_id].into_iter().collect(),
 9560            Some(Autoscroll::fit()),
 9561            cx,
 9562        );
 9563        self.clear_highlights::<Rename>(cx);
 9564        self.show_local_selections = true;
 9565
 9566        if moving_cursor {
 9567            let rename_editor = rename.editor.read(cx);
 9568            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 9569
 9570            // Update the selection to match the position of the selection inside
 9571            // the rename editor.
 9572            let snapshot = self.buffer.read(cx).read(cx);
 9573            let rename_range = rename.range.to_offset(&snapshot);
 9574            let cursor_in_editor = snapshot
 9575                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 9576                .min(rename_range.end);
 9577            drop(snapshot);
 9578
 9579            self.change_selections(None, cx, |s| {
 9580                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 9581            });
 9582        } else {
 9583            self.refresh_document_highlights(cx);
 9584        }
 9585
 9586        Some(rename)
 9587    }
 9588
 9589    pub fn pending_rename(&self) -> Option<&RenameState> {
 9590        self.pending_rename.as_ref()
 9591    }
 9592
 9593    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9594        let project = match &self.project {
 9595            Some(project) => project.clone(),
 9596            None => return None,
 9597        };
 9598
 9599        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 9600    }
 9601
 9602    fn perform_format(
 9603        &mut self,
 9604        project: Model<Project>,
 9605        trigger: FormatTrigger,
 9606        cx: &mut ViewContext<Self>,
 9607    ) -> Task<Result<()>> {
 9608        let buffer = self.buffer().clone();
 9609        let mut buffers = buffer.read(cx).all_buffers();
 9610        if trigger == FormatTrigger::Save {
 9611            buffers.retain(|buffer| buffer.read(cx).is_dirty());
 9612        }
 9613
 9614        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 9615        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 9616
 9617        cx.spawn(|_, mut cx| async move {
 9618            let transaction = futures::select_biased! {
 9619                () = timeout => {
 9620                    log::warn!("timed out waiting for formatting");
 9621                    None
 9622                }
 9623                transaction = format.log_err().fuse() => transaction,
 9624            };
 9625
 9626            buffer
 9627                .update(&mut cx, |buffer, cx| {
 9628                    if let Some(transaction) = transaction {
 9629                        if !buffer.is_singleton() {
 9630                            buffer.push_transaction(&transaction.0, cx);
 9631                        }
 9632                    }
 9633
 9634                    cx.notify();
 9635                })
 9636                .ok();
 9637
 9638            Ok(())
 9639        })
 9640    }
 9641
 9642    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
 9643        if let Some(project) = self.project.clone() {
 9644            self.buffer.update(cx, |multi_buffer, cx| {
 9645                project.update(cx, |project, cx| {
 9646                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
 9647                });
 9648            })
 9649        }
 9650    }
 9651
 9652    fn cancel_language_server_work(
 9653        &mut self,
 9654        _: &CancelLanguageServerWork,
 9655        cx: &mut ViewContext<Self>,
 9656    ) {
 9657        if let Some(project) = self.project.clone() {
 9658            self.buffer.update(cx, |multi_buffer, cx| {
 9659                project.update(cx, |project, cx| {
 9660                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
 9661                });
 9662            })
 9663        }
 9664    }
 9665
 9666    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 9667        cx.show_character_palette();
 9668    }
 9669
 9670    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
 9671        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
 9672            let buffer = self.buffer.read(cx).snapshot(cx);
 9673            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
 9674            let is_valid = buffer
 9675                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
 9676                .any(|entry| {
 9677                    entry.diagnostic.is_primary
 9678                        && !entry.range.is_empty()
 9679                        && entry.range.start == primary_range_start
 9680                        && entry.diagnostic.message == active_diagnostics.primary_message
 9681                });
 9682
 9683            if is_valid != active_diagnostics.is_valid {
 9684                active_diagnostics.is_valid = is_valid;
 9685                let mut new_styles = HashMap::default();
 9686                for (block_id, diagnostic) in &active_diagnostics.blocks {
 9687                    new_styles.insert(
 9688                        *block_id,
 9689                        (
 9690                            None,
 9691                            diagnostic_block_renderer(diagnostic.clone(), is_valid),
 9692                        ),
 9693                    );
 9694                }
 9695                self.display_map.update(cx, |display_map, cx| {
 9696                    display_map.replace_blocks(new_styles, cx)
 9697                });
 9698            }
 9699        }
 9700    }
 9701
 9702    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
 9703        self.dismiss_diagnostics(cx);
 9704        let snapshot = self.snapshot(cx);
 9705        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
 9706            let buffer = self.buffer.read(cx).snapshot(cx);
 9707
 9708            let mut primary_range = None;
 9709            let mut primary_message = None;
 9710            let mut group_end = Point::zero();
 9711            let diagnostic_group = buffer
 9712                .diagnostic_group::<MultiBufferPoint>(group_id)
 9713                .filter_map(|entry| {
 9714                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
 9715                        && (entry.range.start.row == entry.range.end.row
 9716                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
 9717                    {
 9718                        return None;
 9719                    }
 9720                    if entry.range.end > group_end {
 9721                        group_end = entry.range.end;
 9722                    }
 9723                    if entry.diagnostic.is_primary {
 9724                        primary_range = Some(entry.range.clone());
 9725                        primary_message = Some(entry.diagnostic.message.clone());
 9726                    }
 9727                    Some(entry)
 9728                })
 9729                .collect::<Vec<_>>();
 9730            let primary_range = primary_range?;
 9731            let primary_message = primary_message?;
 9732            let primary_range =
 9733                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
 9734
 9735            let blocks = display_map
 9736                .insert_blocks(
 9737                    diagnostic_group.iter().map(|entry| {
 9738                        let diagnostic = entry.diagnostic.clone();
 9739                        let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
 9740                        BlockProperties {
 9741                            style: BlockStyle::Fixed,
 9742                            position: buffer.anchor_after(entry.range.start),
 9743                            height: message_height,
 9744                            render: diagnostic_block_renderer(diagnostic, true),
 9745                            disposition: BlockDisposition::Below,
 9746                        }
 9747                    }),
 9748                    cx,
 9749                )
 9750                .into_iter()
 9751                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
 9752                .collect();
 9753
 9754            Some(ActiveDiagnosticGroup {
 9755                primary_range,
 9756                primary_message,
 9757                group_id,
 9758                blocks,
 9759                is_valid: true,
 9760            })
 9761        });
 9762        self.active_diagnostics.is_some()
 9763    }
 9764
 9765    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
 9766        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
 9767            self.display_map.update(cx, |display_map, cx| {
 9768                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
 9769            });
 9770            cx.notify();
 9771        }
 9772    }
 9773
 9774    pub fn set_selections_from_remote(
 9775        &mut self,
 9776        selections: Vec<Selection<Anchor>>,
 9777        pending_selection: Option<Selection<Anchor>>,
 9778        cx: &mut ViewContext<Self>,
 9779    ) {
 9780        let old_cursor_position = self.selections.newest_anchor().head();
 9781        self.selections.change_with(cx, |s| {
 9782            s.select_anchors(selections);
 9783            if let Some(pending_selection) = pending_selection {
 9784                s.set_pending(pending_selection, SelectMode::Character);
 9785            } else {
 9786                s.clear_pending();
 9787            }
 9788        });
 9789        self.selections_did_change(false, &old_cursor_position, true, cx);
 9790    }
 9791
 9792    fn push_to_selection_history(&mut self) {
 9793        self.selection_history.push(SelectionHistoryEntry {
 9794            selections: self.selections.disjoint_anchors(),
 9795            select_next_state: self.select_next_state.clone(),
 9796            select_prev_state: self.select_prev_state.clone(),
 9797            add_selections_state: self.add_selections_state.clone(),
 9798        });
 9799    }
 9800
 9801    pub fn transact(
 9802        &mut self,
 9803        cx: &mut ViewContext<Self>,
 9804        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
 9805    ) -> Option<TransactionId> {
 9806        self.start_transaction_at(Instant::now(), cx);
 9807        update(self, cx);
 9808        self.end_transaction_at(Instant::now(), cx)
 9809    }
 9810
 9811    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
 9812        self.end_selection(cx);
 9813        if let Some(tx_id) = self
 9814            .buffer
 9815            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
 9816        {
 9817            self.selection_history
 9818                .insert_transaction(tx_id, self.selections.disjoint_anchors());
 9819            cx.emit(EditorEvent::TransactionBegun {
 9820                transaction_id: tx_id,
 9821            })
 9822        }
 9823    }
 9824
 9825    fn end_transaction_at(
 9826        &mut self,
 9827        now: Instant,
 9828        cx: &mut ViewContext<Self>,
 9829    ) -> Option<TransactionId> {
 9830        if let Some(transaction_id) = self
 9831            .buffer
 9832            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 9833        {
 9834            if let Some((_, end_selections)) =
 9835                self.selection_history.transaction_mut(transaction_id)
 9836            {
 9837                *end_selections = Some(self.selections.disjoint_anchors());
 9838            } else {
 9839                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
 9840            }
 9841
 9842            cx.emit(EditorEvent::Edited { transaction_id });
 9843            Some(transaction_id)
 9844        } else {
 9845            None
 9846        }
 9847    }
 9848
 9849    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
 9850        let mut fold_ranges = Vec::new();
 9851
 9852        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9853
 9854        let selections = self.selections.all_adjusted(cx);
 9855        for selection in selections {
 9856            let range = selection.range().sorted();
 9857            let buffer_start_row = range.start.row;
 9858
 9859            for row in (0..=range.end.row).rev() {
 9860                if let Some((foldable_range, fold_text)) =
 9861                    display_map.foldable_range(MultiBufferRow(row))
 9862                {
 9863                    if foldable_range.end.row >= buffer_start_row {
 9864                        fold_ranges.push((foldable_range, fold_text));
 9865                        if row <= range.start.row {
 9866                            break;
 9867                        }
 9868                    }
 9869                }
 9870            }
 9871        }
 9872
 9873        self.fold_ranges(fold_ranges, true, cx);
 9874    }
 9875
 9876    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
 9877        let buffer_row = fold_at.buffer_row;
 9878        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9879
 9880        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
 9881            let autoscroll = self
 9882                .selections
 9883                .all::<Point>(cx)
 9884                .iter()
 9885                .any(|selection| fold_range.overlaps(&selection.range()));
 9886
 9887            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
 9888        }
 9889    }
 9890
 9891    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
 9892        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9893        let buffer = &display_map.buffer_snapshot;
 9894        let selections = self.selections.all::<Point>(cx);
 9895        let ranges = selections
 9896            .iter()
 9897            .map(|s| {
 9898                let range = s.display_range(&display_map).sorted();
 9899                let mut start = range.start.to_point(&display_map);
 9900                let mut end = range.end.to_point(&display_map);
 9901                start.column = 0;
 9902                end.column = buffer.line_len(MultiBufferRow(end.row));
 9903                start..end
 9904            })
 9905            .collect::<Vec<_>>();
 9906
 9907        self.unfold_ranges(ranges, true, true, cx);
 9908    }
 9909
 9910    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
 9911        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9912
 9913        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
 9914            ..Point::new(
 9915                unfold_at.buffer_row.0,
 9916                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
 9917            );
 9918
 9919        let autoscroll = self
 9920            .selections
 9921            .all::<Point>(cx)
 9922            .iter()
 9923            .any(|selection| selection.range().overlaps(&intersection_range));
 9924
 9925        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
 9926    }
 9927
 9928    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
 9929        let selections = self.selections.all::<Point>(cx);
 9930        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9931        let line_mode = self.selections.line_mode;
 9932        let ranges = selections.into_iter().map(|s| {
 9933            if line_mode {
 9934                let start = Point::new(s.start.row, 0);
 9935                let end = Point::new(
 9936                    s.end.row,
 9937                    display_map
 9938                        .buffer_snapshot
 9939                        .line_len(MultiBufferRow(s.end.row)),
 9940                );
 9941                (start..end, display_map.fold_placeholder.clone())
 9942            } else {
 9943                (s.start..s.end, display_map.fold_placeholder.clone())
 9944            }
 9945        });
 9946        self.fold_ranges(ranges, true, cx);
 9947    }
 9948
 9949    pub fn fold_ranges<T: ToOffset + Clone>(
 9950        &mut self,
 9951        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
 9952        auto_scroll: bool,
 9953        cx: &mut ViewContext<Self>,
 9954    ) {
 9955        let mut fold_ranges = Vec::new();
 9956        let mut buffers_affected = HashMap::default();
 9957        let multi_buffer = self.buffer().read(cx);
 9958        for (fold_range, fold_text) in ranges {
 9959            if let Some((_, buffer, _)) =
 9960                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
 9961            {
 9962                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
 9963            };
 9964            fold_ranges.push((fold_range, fold_text));
 9965        }
 9966
 9967        let mut ranges = fold_ranges.into_iter().peekable();
 9968        if ranges.peek().is_some() {
 9969            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
 9970
 9971            if auto_scroll {
 9972                self.request_autoscroll(Autoscroll::fit(), cx);
 9973            }
 9974
 9975            for buffer in buffers_affected.into_values() {
 9976                self.sync_expanded_diff_hunks(buffer, cx);
 9977            }
 9978
 9979            cx.notify();
 9980
 9981            if let Some(active_diagnostics) = self.active_diagnostics.take() {
 9982                // Clear diagnostics block when folding a range that contains it.
 9983                let snapshot = self.snapshot(cx);
 9984                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
 9985                    drop(snapshot);
 9986                    self.active_diagnostics = Some(active_diagnostics);
 9987                    self.dismiss_diagnostics(cx);
 9988                } else {
 9989                    self.active_diagnostics = Some(active_diagnostics);
 9990                }
 9991            }
 9992
 9993            self.scrollbar_marker_state.dirty = true;
 9994        }
 9995    }
 9996
 9997    pub fn unfold_ranges<T: ToOffset + Clone>(
 9998        &mut self,
 9999        ranges: impl IntoIterator<Item = Range<T>>,
10000        inclusive: bool,
10001        auto_scroll: bool,
10002        cx: &mut ViewContext<Self>,
10003    ) {
10004        let mut unfold_ranges = Vec::new();
10005        let mut buffers_affected = HashMap::default();
10006        let multi_buffer = self.buffer().read(cx);
10007        for range in ranges {
10008            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10009                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10010            };
10011            unfold_ranges.push(range);
10012        }
10013
10014        let mut ranges = unfold_ranges.into_iter().peekable();
10015        if ranges.peek().is_some() {
10016            self.display_map
10017                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10018            if auto_scroll {
10019                self.request_autoscroll(Autoscroll::fit(), cx);
10020            }
10021
10022            for buffer in buffers_affected.into_values() {
10023                self.sync_expanded_diff_hunks(buffer, cx);
10024            }
10025
10026            cx.notify();
10027            self.scrollbar_marker_state.dirty = true;
10028            self.active_indent_guides_state.dirty = true;
10029        }
10030    }
10031
10032    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10033        if hovered != self.gutter_hovered {
10034            self.gutter_hovered = hovered;
10035            cx.notify();
10036        }
10037    }
10038
10039    pub fn insert_blocks(
10040        &mut self,
10041        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10042        autoscroll: Option<Autoscroll>,
10043        cx: &mut ViewContext<Self>,
10044    ) -> Vec<BlockId> {
10045        let blocks = self
10046            .display_map
10047            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10048        if let Some(autoscroll) = autoscroll {
10049            self.request_autoscroll(autoscroll, cx);
10050        }
10051        blocks
10052    }
10053
10054    pub fn replace_blocks(
10055        &mut self,
10056        blocks: HashMap<BlockId, (Option<u8>, RenderBlock)>,
10057        autoscroll: Option<Autoscroll>,
10058        cx: &mut ViewContext<Self>,
10059    ) {
10060        self.display_map
10061            .update(cx, |display_map, cx| display_map.replace_blocks(blocks, cx));
10062        if let Some(autoscroll) = autoscroll {
10063            self.request_autoscroll(autoscroll, cx);
10064        }
10065    }
10066
10067    pub fn remove_blocks(
10068        &mut self,
10069        block_ids: HashSet<BlockId>,
10070        autoscroll: Option<Autoscroll>,
10071        cx: &mut ViewContext<Self>,
10072    ) {
10073        self.display_map.update(cx, |display_map, cx| {
10074            display_map.remove_blocks(block_ids, cx)
10075        });
10076        if let Some(autoscroll) = autoscroll {
10077            self.request_autoscroll(autoscroll, cx);
10078        }
10079    }
10080
10081    pub fn row_for_block(
10082        &self,
10083        block_id: BlockId,
10084        cx: &mut ViewContext<Self>,
10085    ) -> Option<DisplayRow> {
10086        self.display_map
10087            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10088    }
10089
10090    pub fn insert_creases(
10091        &mut self,
10092        creases: impl IntoIterator<Item = Crease>,
10093        cx: &mut ViewContext<Self>,
10094    ) -> Vec<CreaseId> {
10095        self.display_map
10096            .update(cx, |map, cx| map.insert_creases(creases, cx))
10097    }
10098
10099    pub fn remove_creases(
10100        &mut self,
10101        ids: impl IntoIterator<Item = CreaseId>,
10102        cx: &mut ViewContext<Self>,
10103    ) {
10104        self.display_map
10105            .update(cx, |map, cx| map.remove_creases(ids, cx));
10106    }
10107
10108    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10109        self.display_map
10110            .update(cx, |map, cx| map.snapshot(cx))
10111            .longest_row()
10112    }
10113
10114    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10115        self.display_map
10116            .update(cx, |map, cx| map.snapshot(cx))
10117            .max_point()
10118    }
10119
10120    pub fn text(&self, cx: &AppContext) -> String {
10121        self.buffer.read(cx).read(cx).text()
10122    }
10123
10124    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10125        let text = self.text(cx);
10126        let text = text.trim();
10127
10128        if text.is_empty() {
10129            return None;
10130        }
10131
10132        Some(text.to_string())
10133    }
10134
10135    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10136        self.transact(cx, |this, cx| {
10137            this.buffer
10138                .read(cx)
10139                .as_singleton()
10140                .expect("you can only call set_text on editors for singleton buffers")
10141                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10142        });
10143    }
10144
10145    pub fn display_text(&self, cx: &mut AppContext) -> String {
10146        self.display_map
10147            .update(cx, |map, cx| map.snapshot(cx))
10148            .text()
10149    }
10150
10151    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10152        let mut wrap_guides = smallvec::smallvec![];
10153
10154        if self.show_wrap_guides == Some(false) {
10155            return wrap_guides;
10156        }
10157
10158        let settings = self.buffer.read(cx).settings_at(0, cx);
10159        if settings.show_wrap_guides {
10160            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10161                wrap_guides.push((soft_wrap as usize, true));
10162            }
10163            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10164        }
10165
10166        wrap_guides
10167    }
10168
10169    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10170        let settings = self.buffer.read(cx).settings_at(0, cx);
10171        let mode = self
10172            .soft_wrap_mode_override
10173            .unwrap_or_else(|| settings.soft_wrap);
10174        match mode {
10175            language_settings::SoftWrap::None => SoftWrap::None,
10176            language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10177            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10178            language_settings::SoftWrap::PreferredLineLength => {
10179                SoftWrap::Column(settings.preferred_line_length)
10180            }
10181        }
10182    }
10183
10184    pub fn set_soft_wrap_mode(
10185        &mut self,
10186        mode: language_settings::SoftWrap,
10187        cx: &mut ViewContext<Self>,
10188    ) {
10189        self.soft_wrap_mode_override = Some(mode);
10190        cx.notify();
10191    }
10192
10193    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10194        let rem_size = cx.rem_size();
10195        self.display_map.update(cx, |map, cx| {
10196            map.set_font(
10197                style.text.font(),
10198                style.text.font_size.to_pixels(rem_size),
10199                cx,
10200            )
10201        });
10202        self.style = Some(style);
10203    }
10204
10205    pub fn style(&self) -> Option<&EditorStyle> {
10206        self.style.as_ref()
10207    }
10208
10209    // Called by the element. This method is not designed to be called outside of the editor
10210    // element's layout code because it does not notify when rewrapping is computed synchronously.
10211    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10212        self.display_map
10213            .update(cx, |map, cx| map.set_wrap_width(width, cx))
10214    }
10215
10216    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10217        if self.soft_wrap_mode_override.is_some() {
10218            self.soft_wrap_mode_override.take();
10219        } else {
10220            let soft_wrap = match self.soft_wrap_mode(cx) {
10221                SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10222                SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10223                    language_settings::SoftWrap::PreferLine
10224                }
10225            };
10226            self.soft_wrap_mode_override = Some(soft_wrap);
10227        }
10228        cx.notify();
10229    }
10230
10231    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10232        let Some(workspace) = self.workspace() else {
10233            return;
10234        };
10235        let fs = workspace.read(cx).app_state().fs.clone();
10236        let current_show = TabBarSettings::get_global(cx).show;
10237        update_settings_file::<TabBarSettings>(fs, cx, move |setting| {
10238            setting.show = Some(!current_show);
10239        });
10240    }
10241
10242    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10243        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10244            self.buffer
10245                .read(cx)
10246                .settings_at(0, cx)
10247                .indent_guides
10248                .enabled
10249        });
10250        self.show_indent_guides = Some(!currently_enabled);
10251        cx.notify();
10252    }
10253
10254    fn should_show_indent_guides(&self) -> Option<bool> {
10255        self.show_indent_guides
10256    }
10257
10258    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10259        let mut editor_settings = EditorSettings::get_global(cx).clone();
10260        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10261        EditorSettings::override_global(editor_settings, cx);
10262    }
10263
10264    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10265        self.show_gutter = show_gutter;
10266        cx.notify();
10267    }
10268
10269    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10270        self.show_line_numbers = Some(show_line_numbers);
10271        cx.notify();
10272    }
10273
10274    pub fn set_show_git_diff_gutter(
10275        &mut self,
10276        show_git_diff_gutter: bool,
10277        cx: &mut ViewContext<Self>,
10278    ) {
10279        self.show_git_diff_gutter = Some(show_git_diff_gutter);
10280        cx.notify();
10281    }
10282
10283    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10284        self.show_code_actions = Some(show_code_actions);
10285        cx.notify();
10286    }
10287
10288    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10289        self.show_runnables = Some(show_runnables);
10290        cx.notify();
10291    }
10292
10293    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10294        self.show_wrap_guides = Some(show_wrap_guides);
10295        cx.notify();
10296    }
10297
10298    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10299        self.show_indent_guides = Some(show_indent_guides);
10300        cx.notify();
10301    }
10302
10303    pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
10304        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10305            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10306                cx.reveal_path(&file.abs_path(cx));
10307            }
10308        }
10309    }
10310
10311    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10312        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10313            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10314                if let Some(path) = file.abs_path(cx).to_str() {
10315                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10316                }
10317            }
10318        }
10319    }
10320
10321    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, 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.path().to_str() {
10325                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10326                }
10327            }
10328        }
10329    }
10330
10331    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10332        self.show_git_blame_gutter = !self.show_git_blame_gutter;
10333
10334        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10335            self.start_git_blame(true, cx);
10336        }
10337
10338        cx.notify();
10339    }
10340
10341    pub fn toggle_git_blame_inline(
10342        &mut self,
10343        _: &ToggleGitBlameInline,
10344        cx: &mut ViewContext<Self>,
10345    ) {
10346        self.toggle_git_blame_inline_internal(true, cx);
10347        cx.notify();
10348    }
10349
10350    pub fn git_blame_inline_enabled(&self) -> bool {
10351        self.git_blame_inline_enabled
10352    }
10353
10354    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10355        self.show_selection_menu = self
10356            .show_selection_menu
10357            .map(|show_selections_menu| !show_selections_menu)
10358            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10359
10360        cx.notify();
10361    }
10362
10363    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10364        self.show_selection_menu
10365            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10366    }
10367
10368    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10369        if let Some(project) = self.project.as_ref() {
10370            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10371                return;
10372            };
10373
10374            if buffer.read(cx).file().is_none() {
10375                return;
10376            }
10377
10378            let focused = self.focus_handle(cx).contains_focused(cx);
10379
10380            let project = project.clone();
10381            let blame =
10382                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10383            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10384            self.blame = Some(blame);
10385        }
10386    }
10387
10388    fn toggle_git_blame_inline_internal(
10389        &mut self,
10390        user_triggered: bool,
10391        cx: &mut ViewContext<Self>,
10392    ) {
10393        if self.git_blame_inline_enabled {
10394            self.git_blame_inline_enabled = false;
10395            self.show_git_blame_inline = false;
10396            self.show_git_blame_inline_delay_task.take();
10397        } else {
10398            self.git_blame_inline_enabled = true;
10399            self.start_git_blame_inline(user_triggered, cx);
10400        }
10401
10402        cx.notify();
10403    }
10404
10405    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10406        self.start_git_blame(user_triggered, cx);
10407
10408        if ProjectSettings::get_global(cx)
10409            .git
10410            .inline_blame_delay()
10411            .is_some()
10412        {
10413            self.start_inline_blame_timer(cx);
10414        } else {
10415            self.show_git_blame_inline = true
10416        }
10417    }
10418
10419    pub fn blame(&self) -> Option<&Model<GitBlame>> {
10420        self.blame.as_ref()
10421    }
10422
10423    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10424        self.show_git_blame_gutter && self.has_blame_entries(cx)
10425    }
10426
10427    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10428        self.show_git_blame_inline
10429            && self.focus_handle.is_focused(cx)
10430            && !self.newest_selection_head_on_empty_line(cx)
10431            && self.has_blame_entries(cx)
10432    }
10433
10434    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10435        self.blame()
10436            .map_or(false, |blame| blame.read(cx).has_generated_entries())
10437    }
10438
10439    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10440        let cursor_anchor = self.selections.newest_anchor().head();
10441
10442        let snapshot = self.buffer.read(cx).snapshot(cx);
10443        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10444
10445        snapshot.line_len(buffer_row) == 0
10446    }
10447
10448    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10449        let (path, selection, repo) = maybe!({
10450            let project_handle = self.project.as_ref()?.clone();
10451            let project = project_handle.read(cx);
10452
10453            let selection = self.selections.newest::<Point>(cx);
10454            let selection_range = selection.range();
10455
10456            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10457                (buffer, selection_range.start.row..selection_range.end.row)
10458            } else {
10459                let buffer_ranges = self
10460                    .buffer()
10461                    .read(cx)
10462                    .range_to_buffer_ranges(selection_range, cx);
10463
10464                let (buffer, range, _) = if selection.reversed {
10465                    buffer_ranges.first()
10466                } else {
10467                    buffer_ranges.last()
10468                }?;
10469
10470                let snapshot = buffer.read(cx).snapshot();
10471                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10472                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
10473                (buffer.clone(), selection)
10474            };
10475
10476            let path = buffer
10477                .read(cx)
10478                .file()?
10479                .as_local()?
10480                .path()
10481                .to_str()?
10482                .to_string();
10483            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10484            Some((path, selection, repo))
10485        })
10486        .ok_or_else(|| anyhow!("unable to open git repository"))?;
10487
10488        const REMOTE_NAME: &str = "origin";
10489        let origin_url = repo
10490            .remote_url(REMOTE_NAME)
10491            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10492        let sha = repo
10493            .head_sha()
10494            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10495
10496        let (provider, remote) =
10497            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10498                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10499
10500        Ok(provider.build_permalink(
10501            remote,
10502            BuildPermalinkParams {
10503                sha: &sha,
10504                path: &path,
10505                selection: Some(selection),
10506            },
10507        ))
10508    }
10509
10510    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10511        let permalink = self.get_permalink_to_line(cx);
10512
10513        match permalink {
10514            Ok(permalink) => {
10515                cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
10516            }
10517            Err(err) => {
10518                let message = format!("Failed to copy permalink: {err}");
10519
10520                Err::<(), anyhow::Error>(err).log_err();
10521
10522                if let Some(workspace) = self.workspace() {
10523                    workspace.update(cx, |workspace, cx| {
10524                        struct CopyPermalinkToLine;
10525
10526                        workspace.show_toast(
10527                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10528                            cx,
10529                        )
10530                    })
10531                }
10532            }
10533        }
10534    }
10535
10536    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10537        let permalink = self.get_permalink_to_line(cx);
10538
10539        match permalink {
10540            Ok(permalink) => {
10541                cx.open_url(permalink.as_ref());
10542            }
10543            Err(err) => {
10544                let message = format!("Failed to open permalink: {err}");
10545
10546                Err::<(), anyhow::Error>(err).log_err();
10547
10548                if let Some(workspace) = self.workspace() {
10549                    workspace.update(cx, |workspace, cx| {
10550                        struct OpenPermalinkToLine;
10551
10552                        workspace.show_toast(
10553                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10554                            cx,
10555                        )
10556                    })
10557                }
10558            }
10559        }
10560    }
10561
10562    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10563    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10564    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10565    pub fn highlight_rows<T: 'static>(
10566        &mut self,
10567        rows: RangeInclusive<Anchor>,
10568        color: Option<Hsla>,
10569        should_autoscroll: bool,
10570        cx: &mut ViewContext<Self>,
10571    ) {
10572        let snapshot = self.buffer().read(cx).snapshot(cx);
10573        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10574        let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10575            highlight
10576                .range
10577                .start()
10578                .cmp(&rows.start(), &snapshot)
10579                .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10580        });
10581        match (color, existing_highlight_index) {
10582            (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10583                ix,
10584                RowHighlight {
10585                    index: post_inc(&mut self.highlight_order),
10586                    range: rows,
10587                    should_autoscroll,
10588                    color,
10589                },
10590            ),
10591            (None, Ok(i)) => {
10592                row_highlights.remove(i);
10593            }
10594        }
10595    }
10596
10597    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10598    pub fn clear_row_highlights<T: 'static>(&mut self) {
10599        self.highlighted_rows.remove(&TypeId::of::<T>());
10600    }
10601
10602    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10603    pub fn highlighted_rows<T: 'static>(
10604        &self,
10605    ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10606        Some(
10607            self.highlighted_rows
10608                .get(&TypeId::of::<T>())?
10609                .iter()
10610                .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10611        )
10612    }
10613
10614    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10615    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10616    /// Allows to ignore certain kinds of highlights.
10617    pub fn highlighted_display_rows(
10618        &mut self,
10619        cx: &mut WindowContext,
10620    ) -> BTreeMap<DisplayRow, Hsla> {
10621        let snapshot = self.snapshot(cx);
10622        let mut used_highlight_orders = HashMap::default();
10623        self.highlighted_rows
10624            .iter()
10625            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10626            .fold(
10627                BTreeMap::<DisplayRow, Hsla>::new(),
10628                |mut unique_rows, highlight| {
10629                    let start_row = highlight.range.start().to_display_point(&snapshot).row();
10630                    let end_row = highlight.range.end().to_display_point(&snapshot).row();
10631                    for row in start_row.0..=end_row.0 {
10632                        let used_index =
10633                            used_highlight_orders.entry(row).or_insert(highlight.index);
10634                        if highlight.index >= *used_index {
10635                            *used_index = highlight.index;
10636                            match highlight.color {
10637                                Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10638                                None => unique_rows.remove(&DisplayRow(row)),
10639                            };
10640                        }
10641                    }
10642                    unique_rows
10643                },
10644            )
10645    }
10646
10647    pub fn highlighted_display_row_for_autoscroll(
10648        &self,
10649        snapshot: &DisplaySnapshot,
10650    ) -> Option<DisplayRow> {
10651        self.highlighted_rows
10652            .values()
10653            .flat_map(|highlighted_rows| highlighted_rows.iter())
10654            .filter_map(|highlight| {
10655                if highlight.color.is_none() || !highlight.should_autoscroll {
10656                    return None;
10657                }
10658                Some(highlight.range.start().to_display_point(&snapshot).row())
10659            })
10660            .min()
10661    }
10662
10663    pub fn set_search_within_ranges(
10664        &mut self,
10665        ranges: &[Range<Anchor>],
10666        cx: &mut ViewContext<Self>,
10667    ) {
10668        self.highlight_background::<SearchWithinRange>(
10669            ranges,
10670            |colors| colors.editor_document_highlight_read_background,
10671            cx,
10672        )
10673    }
10674
10675    pub fn set_breadcrumb_header(&mut self, new_header: String) {
10676        self.breadcrumb_header = Some(new_header);
10677    }
10678
10679    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10680        self.clear_background_highlights::<SearchWithinRange>(cx);
10681    }
10682
10683    pub fn highlight_background<T: 'static>(
10684        &mut self,
10685        ranges: &[Range<Anchor>],
10686        color_fetcher: fn(&ThemeColors) -> Hsla,
10687        cx: &mut ViewContext<Self>,
10688    ) {
10689        let snapshot = self.snapshot(cx);
10690        // this is to try and catch a panic sooner
10691        for range in ranges {
10692            snapshot
10693                .buffer_snapshot
10694                .summary_for_anchor::<usize>(&range.start);
10695            snapshot
10696                .buffer_snapshot
10697                .summary_for_anchor::<usize>(&range.end);
10698        }
10699
10700        self.background_highlights
10701            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10702        self.scrollbar_marker_state.dirty = true;
10703        cx.notify();
10704    }
10705
10706    pub fn clear_background_highlights<T: 'static>(
10707        &mut self,
10708        cx: &mut ViewContext<Self>,
10709    ) -> Option<BackgroundHighlight> {
10710        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10711        if !text_highlights.1.is_empty() {
10712            self.scrollbar_marker_state.dirty = true;
10713            cx.notify();
10714        }
10715        Some(text_highlights)
10716    }
10717
10718    pub fn highlight_gutter<T: 'static>(
10719        &mut self,
10720        ranges: &[Range<Anchor>],
10721        color_fetcher: fn(&AppContext) -> Hsla,
10722        cx: &mut ViewContext<Self>,
10723    ) {
10724        self.gutter_highlights
10725            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10726        cx.notify();
10727    }
10728
10729    pub fn clear_gutter_highlights<T: 'static>(
10730        &mut self,
10731        cx: &mut ViewContext<Self>,
10732    ) -> Option<GutterHighlight> {
10733        cx.notify();
10734        self.gutter_highlights.remove(&TypeId::of::<T>())
10735    }
10736
10737    #[cfg(feature = "test-support")]
10738    pub fn all_text_background_highlights(
10739        &mut self,
10740        cx: &mut ViewContext<Self>,
10741    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10742        let snapshot = self.snapshot(cx);
10743        let buffer = &snapshot.buffer_snapshot;
10744        let start = buffer.anchor_before(0);
10745        let end = buffer.anchor_after(buffer.len());
10746        let theme = cx.theme().colors();
10747        self.background_highlights_in_range(start..end, &snapshot, theme)
10748    }
10749
10750    #[cfg(feature = "test-support")]
10751    pub fn search_background_highlights(
10752        &mut self,
10753        cx: &mut ViewContext<Self>,
10754    ) -> Vec<Range<Point>> {
10755        let snapshot = self.buffer().read(cx).snapshot(cx);
10756
10757        let highlights = self
10758            .background_highlights
10759            .get(&TypeId::of::<items::BufferSearchHighlights>());
10760
10761        if let Some((_color, ranges)) = highlights {
10762            ranges
10763                .iter()
10764                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
10765                .collect_vec()
10766        } else {
10767            vec![]
10768        }
10769    }
10770
10771    fn document_highlights_for_position<'a>(
10772        &'a self,
10773        position: Anchor,
10774        buffer: &'a MultiBufferSnapshot,
10775    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
10776        let read_highlights = self
10777            .background_highlights
10778            .get(&TypeId::of::<DocumentHighlightRead>())
10779            .map(|h| &h.1);
10780        let write_highlights = self
10781            .background_highlights
10782            .get(&TypeId::of::<DocumentHighlightWrite>())
10783            .map(|h| &h.1);
10784        let left_position = position.bias_left(buffer);
10785        let right_position = position.bias_right(buffer);
10786        read_highlights
10787            .into_iter()
10788            .chain(write_highlights)
10789            .flat_map(move |ranges| {
10790                let start_ix = match ranges.binary_search_by(|probe| {
10791                    let cmp = probe.end.cmp(&left_position, buffer);
10792                    if cmp.is_ge() {
10793                        Ordering::Greater
10794                    } else {
10795                        Ordering::Less
10796                    }
10797                }) {
10798                    Ok(i) | Err(i) => i,
10799                };
10800
10801                ranges[start_ix..]
10802                    .iter()
10803                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
10804            })
10805    }
10806
10807    pub fn has_background_highlights<T: 'static>(&self) -> bool {
10808        self.background_highlights
10809            .get(&TypeId::of::<T>())
10810            .map_or(false, |(_, highlights)| !highlights.is_empty())
10811    }
10812
10813    pub fn background_highlights_in_range(
10814        &self,
10815        search_range: Range<Anchor>,
10816        display_snapshot: &DisplaySnapshot,
10817        theme: &ThemeColors,
10818    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10819        let mut results = Vec::new();
10820        for (color_fetcher, ranges) in self.background_highlights.values() {
10821            let color = color_fetcher(theme);
10822            let start_ix = match ranges.binary_search_by(|probe| {
10823                let cmp = probe
10824                    .end
10825                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10826                if cmp.is_gt() {
10827                    Ordering::Greater
10828                } else {
10829                    Ordering::Less
10830                }
10831            }) {
10832                Ok(i) | Err(i) => i,
10833            };
10834            for range in &ranges[start_ix..] {
10835                if range
10836                    .start
10837                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10838                    .is_ge()
10839                {
10840                    break;
10841                }
10842
10843                let start = range.start.to_display_point(&display_snapshot);
10844                let end = range.end.to_display_point(&display_snapshot);
10845                results.push((start..end, color))
10846            }
10847        }
10848        results
10849    }
10850
10851    pub fn background_highlight_row_ranges<T: 'static>(
10852        &self,
10853        search_range: Range<Anchor>,
10854        display_snapshot: &DisplaySnapshot,
10855        count: usize,
10856    ) -> Vec<RangeInclusive<DisplayPoint>> {
10857        let mut results = Vec::new();
10858        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
10859            return vec![];
10860        };
10861
10862        let start_ix = match ranges.binary_search_by(|probe| {
10863            let cmp = probe
10864                .end
10865                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10866            if cmp.is_gt() {
10867                Ordering::Greater
10868            } else {
10869                Ordering::Less
10870            }
10871        }) {
10872            Ok(i) | Err(i) => i,
10873        };
10874        let mut push_region = |start: Option<Point>, end: Option<Point>| {
10875            if let (Some(start_display), Some(end_display)) = (start, end) {
10876                results.push(
10877                    start_display.to_display_point(display_snapshot)
10878                        ..=end_display.to_display_point(display_snapshot),
10879                );
10880            }
10881        };
10882        let mut start_row: Option<Point> = None;
10883        let mut end_row: Option<Point> = None;
10884        if ranges.len() > count {
10885            return Vec::new();
10886        }
10887        for range in &ranges[start_ix..] {
10888            if range
10889                .start
10890                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10891                .is_ge()
10892            {
10893                break;
10894            }
10895            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
10896            if let Some(current_row) = &end_row {
10897                if end.row == current_row.row {
10898                    continue;
10899                }
10900            }
10901            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
10902            if start_row.is_none() {
10903                assert_eq!(end_row, None);
10904                start_row = Some(start);
10905                end_row = Some(end);
10906                continue;
10907            }
10908            if let Some(current_end) = end_row.as_mut() {
10909                if start.row > current_end.row + 1 {
10910                    push_region(start_row, end_row);
10911                    start_row = Some(start);
10912                    end_row = Some(end);
10913                } else {
10914                    // Merge two hunks.
10915                    *current_end = end;
10916                }
10917            } else {
10918                unreachable!();
10919            }
10920        }
10921        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
10922        push_region(start_row, end_row);
10923        results
10924    }
10925
10926    pub fn gutter_highlights_in_range(
10927        &self,
10928        search_range: Range<Anchor>,
10929        display_snapshot: &DisplaySnapshot,
10930        cx: &AppContext,
10931    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10932        let mut results = Vec::new();
10933        for (color_fetcher, ranges) in self.gutter_highlights.values() {
10934            let color = color_fetcher(cx);
10935            let start_ix = match ranges.binary_search_by(|probe| {
10936                let cmp = probe
10937                    .end
10938                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10939                if cmp.is_gt() {
10940                    Ordering::Greater
10941                } else {
10942                    Ordering::Less
10943                }
10944            }) {
10945                Ok(i) | Err(i) => i,
10946            };
10947            for range in &ranges[start_ix..] {
10948                if range
10949                    .start
10950                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10951                    .is_ge()
10952                {
10953                    break;
10954                }
10955
10956                let start = range.start.to_display_point(&display_snapshot);
10957                let end = range.end.to_display_point(&display_snapshot);
10958                results.push((start..end, color))
10959            }
10960        }
10961        results
10962    }
10963
10964    /// Get the text ranges corresponding to the redaction query
10965    pub fn redacted_ranges(
10966        &self,
10967        search_range: Range<Anchor>,
10968        display_snapshot: &DisplaySnapshot,
10969        cx: &WindowContext,
10970    ) -> Vec<Range<DisplayPoint>> {
10971        display_snapshot
10972            .buffer_snapshot
10973            .redacted_ranges(search_range, |file| {
10974                if let Some(file) = file {
10975                    file.is_private()
10976                        && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
10977                } else {
10978                    false
10979                }
10980            })
10981            .map(|range| {
10982                range.start.to_display_point(display_snapshot)
10983                    ..range.end.to_display_point(display_snapshot)
10984            })
10985            .collect()
10986    }
10987
10988    pub fn highlight_text<T: 'static>(
10989        &mut self,
10990        ranges: Vec<Range<Anchor>>,
10991        style: HighlightStyle,
10992        cx: &mut ViewContext<Self>,
10993    ) {
10994        self.display_map.update(cx, |map, _| {
10995            map.highlight_text(TypeId::of::<T>(), ranges, style)
10996        });
10997        cx.notify();
10998    }
10999
11000    pub(crate) fn highlight_inlays<T: 'static>(
11001        &mut self,
11002        highlights: Vec<InlayHighlight>,
11003        style: HighlightStyle,
11004        cx: &mut ViewContext<Self>,
11005    ) {
11006        self.display_map.update(cx, |map, _| {
11007            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11008        });
11009        cx.notify();
11010    }
11011
11012    pub fn text_highlights<'a, T: 'static>(
11013        &'a self,
11014        cx: &'a AppContext,
11015    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11016        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11017    }
11018
11019    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11020        let cleared = self
11021            .display_map
11022            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11023        if cleared {
11024            cx.notify();
11025        }
11026    }
11027
11028    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11029        (self.read_only(cx) || self.blink_manager.read(cx).visible())
11030            && self.focus_handle.is_focused(cx)
11031    }
11032
11033    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11034        self.show_cursor_when_unfocused = is_enabled;
11035        cx.notify();
11036    }
11037
11038    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11039        cx.notify();
11040    }
11041
11042    fn on_buffer_event(
11043        &mut self,
11044        multibuffer: Model<MultiBuffer>,
11045        event: &multi_buffer::Event,
11046        cx: &mut ViewContext<Self>,
11047    ) {
11048        match event {
11049            multi_buffer::Event::Edited {
11050                singleton_buffer_edited,
11051            } => {
11052                self.scrollbar_marker_state.dirty = true;
11053                self.active_indent_guides_state.dirty = true;
11054                self.refresh_active_diagnostics(cx);
11055                self.refresh_code_actions(cx);
11056                if self.has_active_inline_completion(cx) {
11057                    self.update_visible_inline_completion(cx);
11058                }
11059                cx.emit(EditorEvent::BufferEdited);
11060                cx.emit(SearchEvent::MatchesInvalidated);
11061                if *singleton_buffer_edited {
11062                    if let Some(project) = &self.project {
11063                        let project = project.read(cx);
11064                        let languages_affected = multibuffer
11065                            .read(cx)
11066                            .all_buffers()
11067                            .into_iter()
11068                            .filter_map(|buffer| {
11069                                let buffer = buffer.read(cx);
11070                                let language = buffer.language()?;
11071                                if project.is_local()
11072                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
11073                                {
11074                                    None
11075                                } else {
11076                                    Some(language)
11077                                }
11078                            })
11079                            .cloned()
11080                            .collect::<HashSet<_>>();
11081                        if !languages_affected.is_empty() {
11082                            self.refresh_inlay_hints(
11083                                InlayHintRefreshReason::BufferEdited(languages_affected),
11084                                cx,
11085                            );
11086                        }
11087                    }
11088                }
11089
11090                let Some(project) = &self.project else { return };
11091                let telemetry = project.read(cx).client().telemetry().clone();
11092                refresh_linked_ranges(self, cx);
11093                telemetry.log_edit_event("editor");
11094            }
11095            multi_buffer::Event::ExcerptsAdded {
11096                buffer,
11097                predecessor,
11098                excerpts,
11099            } => {
11100                self.tasks_update_task = Some(self.refresh_runnables(cx));
11101                cx.emit(EditorEvent::ExcerptsAdded {
11102                    buffer: buffer.clone(),
11103                    predecessor: *predecessor,
11104                    excerpts: excerpts.clone(),
11105                });
11106                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11107            }
11108            multi_buffer::Event::ExcerptsRemoved { ids } => {
11109                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11110                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11111            }
11112            multi_buffer::Event::ExcerptsEdited { ids } => {
11113                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11114            }
11115            multi_buffer::Event::ExcerptsExpanded { ids } => {
11116                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11117            }
11118            multi_buffer::Event::Reparsed(buffer_id) => {
11119                self.tasks_update_task = Some(self.refresh_runnables(cx));
11120
11121                cx.emit(EditorEvent::Reparsed(*buffer_id));
11122            }
11123            multi_buffer::Event::LanguageChanged(buffer_id) => {
11124                linked_editing_ranges::refresh_linked_ranges(self, cx);
11125                cx.emit(EditorEvent::Reparsed(*buffer_id));
11126                cx.notify();
11127            }
11128            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11129            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11130            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11131                cx.emit(EditorEvent::TitleChanged)
11132            }
11133            multi_buffer::Event::DiffBaseChanged => {
11134                self.scrollbar_marker_state.dirty = true;
11135                cx.emit(EditorEvent::DiffBaseChanged);
11136                cx.notify();
11137            }
11138            multi_buffer::Event::DiffUpdated { buffer } => {
11139                self.sync_expanded_diff_hunks(buffer.clone(), cx);
11140                cx.notify();
11141            }
11142            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11143            multi_buffer::Event::DiagnosticsUpdated => {
11144                self.refresh_active_diagnostics(cx);
11145                self.scrollbar_marker_state.dirty = true;
11146                cx.notify();
11147            }
11148            _ => {}
11149        };
11150    }
11151
11152    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11153        cx.notify();
11154    }
11155
11156    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11157        self.tasks_update_task = Some(self.refresh_runnables(cx));
11158        self.refresh_inline_completion(true, cx);
11159        self.refresh_inlay_hints(
11160            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11161                self.selections.newest_anchor().head(),
11162                &self.buffer.read(cx).snapshot(cx),
11163                cx,
11164            )),
11165            cx,
11166        );
11167        let editor_settings = EditorSettings::get_global(cx);
11168        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11169        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11170
11171        if self.mode == EditorMode::Full {
11172            let inline_blame_enabled = ProjectSettings::get_global(cx).git.inline_blame_enabled();
11173            if self.git_blame_inline_enabled != inline_blame_enabled {
11174                self.toggle_git_blame_inline_internal(false, cx);
11175            }
11176        }
11177
11178        cx.notify();
11179    }
11180
11181    pub fn set_searchable(&mut self, searchable: bool) {
11182        self.searchable = searchable;
11183    }
11184
11185    pub fn searchable(&self) -> bool {
11186        self.searchable
11187    }
11188
11189    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11190        self.open_excerpts_common(true, cx)
11191    }
11192
11193    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11194        self.open_excerpts_common(false, cx)
11195    }
11196
11197    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11198        let buffer = self.buffer.read(cx);
11199        if buffer.is_singleton() {
11200            cx.propagate();
11201            return;
11202        }
11203
11204        let Some(workspace) = self.workspace() else {
11205            cx.propagate();
11206            return;
11207        };
11208
11209        let mut new_selections_by_buffer = HashMap::default();
11210        for selection in self.selections.all::<usize>(cx) {
11211            for (buffer, mut range, _) in
11212                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11213            {
11214                if selection.reversed {
11215                    mem::swap(&mut range.start, &mut range.end);
11216                }
11217                new_selections_by_buffer
11218                    .entry(buffer)
11219                    .or_insert(Vec::new())
11220                    .push(range)
11221            }
11222        }
11223
11224        // We defer the pane interaction because we ourselves are a workspace item
11225        // and activating a new item causes the pane to call a method on us reentrantly,
11226        // which panics if we're on the stack.
11227        cx.window_context().defer(move |cx| {
11228            workspace.update(cx, |workspace, cx| {
11229                let pane = if split {
11230                    workspace.adjacent_pane(cx)
11231                } else {
11232                    workspace.active_pane().clone()
11233                };
11234
11235                for (buffer, ranges) in new_selections_by_buffer {
11236                    let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
11237                    editor.update(cx, |editor, cx| {
11238                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11239                            s.select_ranges(ranges);
11240                        });
11241                    });
11242                }
11243            })
11244        });
11245    }
11246
11247    fn jump(
11248        &mut self,
11249        path: ProjectPath,
11250        position: Point,
11251        anchor: language::Anchor,
11252        offset_from_top: u32,
11253        cx: &mut ViewContext<Self>,
11254    ) {
11255        let workspace = self.workspace();
11256        cx.spawn(|_, mut cx| async move {
11257            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11258            let editor = workspace.update(&mut cx, |workspace, cx| {
11259                // Reset the preview item id before opening the new item
11260                workspace.active_pane().update(cx, |pane, cx| {
11261                    pane.set_preview_item_id(None, cx);
11262                });
11263                workspace.open_path_preview(path, None, true, true, cx)
11264            })?;
11265            let editor = editor
11266                .await?
11267                .downcast::<Editor>()
11268                .ok_or_else(|| anyhow!("opened item was not an editor"))?
11269                .downgrade();
11270            editor.update(&mut cx, |editor, cx| {
11271                let buffer = editor
11272                    .buffer()
11273                    .read(cx)
11274                    .as_singleton()
11275                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11276                let buffer = buffer.read(cx);
11277                let cursor = if buffer.can_resolve(&anchor) {
11278                    language::ToPoint::to_point(&anchor, buffer)
11279                } else {
11280                    buffer.clip_point(position, Bias::Left)
11281                };
11282
11283                let nav_history = editor.nav_history.take();
11284                editor.change_selections(
11285                    Some(Autoscroll::top_relative(offset_from_top as usize)),
11286                    cx,
11287                    |s| {
11288                        s.select_ranges([cursor..cursor]);
11289                    },
11290                );
11291                editor.nav_history = nav_history;
11292
11293                anyhow::Ok(())
11294            })??;
11295
11296            anyhow::Ok(())
11297        })
11298        .detach_and_log_err(cx);
11299    }
11300
11301    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11302        let snapshot = self.buffer.read(cx).read(cx);
11303        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11304        Some(
11305            ranges
11306                .iter()
11307                .map(move |range| {
11308                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11309                })
11310                .collect(),
11311        )
11312    }
11313
11314    fn selection_replacement_ranges(
11315        &self,
11316        range: Range<OffsetUtf16>,
11317        cx: &AppContext,
11318    ) -> Vec<Range<OffsetUtf16>> {
11319        let selections = self.selections.all::<OffsetUtf16>(cx);
11320        let newest_selection = selections
11321            .iter()
11322            .max_by_key(|selection| selection.id)
11323            .unwrap();
11324        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11325        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11326        let snapshot = self.buffer.read(cx).read(cx);
11327        selections
11328            .into_iter()
11329            .map(|mut selection| {
11330                selection.start.0 =
11331                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
11332                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11333                snapshot.clip_offset_utf16(selection.start, Bias::Left)
11334                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11335            })
11336            .collect()
11337    }
11338
11339    fn report_editor_event(
11340        &self,
11341        operation: &'static str,
11342        file_extension: Option<String>,
11343        cx: &AppContext,
11344    ) {
11345        if cfg!(any(test, feature = "test-support")) {
11346            return;
11347        }
11348
11349        let Some(project) = &self.project else { return };
11350
11351        // If None, we are in a file without an extension
11352        let file = self
11353            .buffer
11354            .read(cx)
11355            .as_singleton()
11356            .and_then(|b| b.read(cx).file());
11357        let file_extension = file_extension.or(file
11358            .as_ref()
11359            .and_then(|file| Path::new(file.file_name(cx)).extension())
11360            .and_then(|e| e.to_str())
11361            .map(|a| a.to_string()));
11362
11363        let vim_mode = cx
11364            .global::<SettingsStore>()
11365            .raw_user_settings()
11366            .get("vim_mode")
11367            == Some(&serde_json::Value::Bool(true));
11368
11369        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11370            == language::language_settings::InlineCompletionProvider::Copilot;
11371        let copilot_enabled_for_language = self
11372            .buffer
11373            .read(cx)
11374            .settings_at(0, cx)
11375            .show_inline_completions;
11376
11377        let telemetry = project.read(cx).client().telemetry().clone();
11378        telemetry.report_editor_event(
11379            file_extension,
11380            vim_mode,
11381            operation,
11382            copilot_enabled,
11383            copilot_enabled_for_language,
11384        )
11385    }
11386
11387    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11388    /// with each line being an array of {text, highlight} objects.
11389    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11390        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11391            return;
11392        };
11393
11394        #[derive(Serialize)]
11395        struct Chunk<'a> {
11396            text: String,
11397            highlight: Option<&'a str>,
11398        }
11399
11400        let snapshot = buffer.read(cx).snapshot();
11401        let range = self
11402            .selected_text_range(cx)
11403            .and_then(|selected_range| {
11404                if selected_range.is_empty() {
11405                    None
11406                } else {
11407                    Some(selected_range)
11408                }
11409            })
11410            .unwrap_or_else(|| 0..snapshot.len());
11411
11412        let chunks = snapshot.chunks(range, true);
11413        let mut lines = Vec::new();
11414        let mut line: VecDeque<Chunk> = VecDeque::new();
11415
11416        let Some(style) = self.style.as_ref() else {
11417            return;
11418        };
11419
11420        for chunk in chunks {
11421            let highlight = chunk
11422                .syntax_highlight_id
11423                .and_then(|id| id.name(&style.syntax));
11424            let mut chunk_lines = chunk.text.split('\n').peekable();
11425            while let Some(text) = chunk_lines.next() {
11426                let mut merged_with_last_token = false;
11427                if let Some(last_token) = line.back_mut() {
11428                    if last_token.highlight == highlight {
11429                        last_token.text.push_str(text);
11430                        merged_with_last_token = true;
11431                    }
11432                }
11433
11434                if !merged_with_last_token {
11435                    line.push_back(Chunk {
11436                        text: text.into(),
11437                        highlight,
11438                    });
11439                }
11440
11441                if chunk_lines.peek().is_some() {
11442                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
11443                        line.pop_front();
11444                    }
11445                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
11446                        line.pop_back();
11447                    }
11448
11449                    lines.push(mem::take(&mut line));
11450                }
11451            }
11452        }
11453
11454        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11455            return;
11456        };
11457        cx.write_to_clipboard(ClipboardItem::new(lines));
11458    }
11459
11460    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11461        &self.inlay_hint_cache
11462    }
11463
11464    pub fn replay_insert_event(
11465        &mut self,
11466        text: &str,
11467        relative_utf16_range: Option<Range<isize>>,
11468        cx: &mut ViewContext<Self>,
11469    ) {
11470        if !self.input_enabled {
11471            cx.emit(EditorEvent::InputIgnored { text: text.into() });
11472            return;
11473        }
11474        if let Some(relative_utf16_range) = relative_utf16_range {
11475            let selections = self.selections.all::<OffsetUtf16>(cx);
11476            self.change_selections(None, cx, |s| {
11477                let new_ranges = selections.into_iter().map(|range| {
11478                    let start = OffsetUtf16(
11479                        range
11480                            .head()
11481                            .0
11482                            .saturating_add_signed(relative_utf16_range.start),
11483                    );
11484                    let end = OffsetUtf16(
11485                        range
11486                            .head()
11487                            .0
11488                            .saturating_add_signed(relative_utf16_range.end),
11489                    );
11490                    start..end
11491                });
11492                s.select_ranges(new_ranges);
11493            });
11494        }
11495
11496        self.handle_input(text, cx);
11497    }
11498
11499    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11500        let Some(project) = self.project.as_ref() else {
11501            return false;
11502        };
11503        let project = project.read(cx);
11504
11505        let mut supports = false;
11506        self.buffer().read(cx).for_each_buffer(|buffer| {
11507            if !supports {
11508                supports = project
11509                    .language_servers_for_buffer(buffer.read(cx), cx)
11510                    .any(
11511                        |(_, server)| match server.capabilities().inlay_hint_provider {
11512                            Some(lsp::OneOf::Left(enabled)) => enabled,
11513                            Some(lsp::OneOf::Right(_)) => true,
11514                            None => false,
11515                        },
11516                    )
11517            }
11518        });
11519        supports
11520    }
11521
11522    pub fn focus(&self, cx: &mut WindowContext) {
11523        cx.focus(&self.focus_handle)
11524    }
11525
11526    pub fn is_focused(&self, cx: &WindowContext) -> bool {
11527        self.focus_handle.is_focused(cx)
11528    }
11529
11530    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11531        cx.emit(EditorEvent::Focused);
11532
11533        if let Some(descendant) = self
11534            .last_focused_descendant
11535            .take()
11536            .and_then(|descendant| descendant.upgrade())
11537        {
11538            cx.focus(&descendant);
11539        } else {
11540            if let Some(blame) = self.blame.as_ref() {
11541                blame.update(cx, GitBlame::focus)
11542            }
11543
11544            self.blink_manager.update(cx, BlinkManager::enable);
11545            self.show_cursor_names(cx);
11546            self.buffer.update(cx, |buffer, cx| {
11547                buffer.finalize_last_transaction(cx);
11548                if self.leader_peer_id.is_none() {
11549                    buffer.set_active_selections(
11550                        &self.selections.disjoint_anchors(),
11551                        self.selections.line_mode,
11552                        self.cursor_shape,
11553                        cx,
11554                    );
11555                }
11556            });
11557        }
11558    }
11559
11560    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11561        if event.blurred != self.focus_handle {
11562            self.last_focused_descendant = Some(event.blurred);
11563        }
11564    }
11565
11566    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11567        self.blink_manager.update(cx, BlinkManager::disable);
11568        self.buffer
11569            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11570
11571        if let Some(blame) = self.blame.as_ref() {
11572            blame.update(cx, GitBlame::blur)
11573        }
11574        self.hide_context_menu(cx);
11575        hide_hover(self, cx);
11576        cx.emit(EditorEvent::Blurred);
11577        cx.notify();
11578    }
11579
11580    pub fn register_action<A: Action>(
11581        &mut self,
11582        listener: impl Fn(&A, &mut WindowContext) + 'static,
11583    ) -> Subscription {
11584        let id = self.next_editor_action_id.post_inc();
11585        let listener = Arc::new(listener);
11586        self.editor_actions.borrow_mut().insert(
11587            id,
11588            Box::new(move |cx| {
11589                let _view = cx.view().clone();
11590                let cx = cx.window_context();
11591                let listener = listener.clone();
11592                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11593                    let action = action.downcast_ref().unwrap();
11594                    if phase == DispatchPhase::Bubble {
11595                        listener(action, cx)
11596                    }
11597                })
11598            }),
11599        );
11600
11601        let editor_actions = self.editor_actions.clone();
11602        Subscription::new(move || {
11603            editor_actions.borrow_mut().remove(&id);
11604        })
11605    }
11606
11607    pub fn file_header_size(&self) -> u8 {
11608        self.file_header_size
11609    }
11610}
11611
11612fn hunks_for_selections(
11613    multi_buffer_snapshot: &MultiBufferSnapshot,
11614    selections: &[Selection<Anchor>],
11615) -> Vec<DiffHunk<MultiBufferRow>> {
11616    let mut hunks = Vec::with_capacity(selections.len());
11617    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11618        HashMap::default();
11619    let buffer_rows_for_selections = selections.iter().map(|selection| {
11620        let head = selection.head();
11621        let tail = selection.tail();
11622        let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11623        let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11624        if start > end {
11625            end..start
11626        } else {
11627            start..end
11628        }
11629    });
11630
11631    for selected_multi_buffer_rows in buffer_rows_for_selections {
11632        let query_rows =
11633            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11634        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11635            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11636            // when the caret is just above or just below the deleted hunk.
11637            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11638            let related_to_selection = if allow_adjacent {
11639                hunk.associated_range.overlaps(&query_rows)
11640                    || hunk.associated_range.start == query_rows.end
11641                    || hunk.associated_range.end == query_rows.start
11642            } else {
11643                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11644                // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11645                hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11646                    || selected_multi_buffer_rows.end == hunk.associated_range.start
11647            };
11648            if related_to_selection {
11649                if !processed_buffer_rows
11650                    .entry(hunk.buffer_id)
11651                    .or_default()
11652                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
11653                {
11654                    continue;
11655                }
11656                hunks.push(hunk);
11657            }
11658        }
11659    }
11660
11661    hunks
11662}
11663
11664pub trait CollaborationHub {
11665    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
11666    fn user_participant_indices<'a>(
11667        &self,
11668        cx: &'a AppContext,
11669    ) -> &'a HashMap<u64, ParticipantIndex>;
11670    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
11671}
11672
11673impl CollaborationHub for Model<Project> {
11674    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
11675        self.read(cx).collaborators()
11676    }
11677
11678    fn user_participant_indices<'a>(
11679        &self,
11680        cx: &'a AppContext,
11681    ) -> &'a HashMap<u64, ParticipantIndex> {
11682        self.read(cx).user_store().read(cx).participant_indices()
11683    }
11684
11685    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
11686        let this = self.read(cx);
11687        let user_ids = this.collaborators().values().map(|c| c.user_id);
11688        this.user_store().read_with(cx, |user_store, cx| {
11689            user_store.participant_names(user_ids, cx)
11690        })
11691    }
11692}
11693
11694pub trait CompletionProvider {
11695    fn completions(
11696        &self,
11697        buffer: &Model<Buffer>,
11698        buffer_position: text::Anchor,
11699        trigger: CompletionContext,
11700        cx: &mut ViewContext<Editor>,
11701    ) -> Task<Result<Vec<Completion>>>;
11702
11703    fn resolve_completions(
11704        &self,
11705        buffer: Model<Buffer>,
11706        completion_indices: Vec<usize>,
11707        completions: Arc<RwLock<Box<[Completion]>>>,
11708        cx: &mut ViewContext<Editor>,
11709    ) -> Task<Result<bool>>;
11710
11711    fn apply_additional_edits_for_completion(
11712        &self,
11713        buffer: Model<Buffer>,
11714        completion: Completion,
11715        push_to_history: bool,
11716        cx: &mut ViewContext<Editor>,
11717    ) -> Task<Result<Option<language::Transaction>>>;
11718
11719    fn is_completion_trigger(
11720        &self,
11721        buffer: &Model<Buffer>,
11722        position: language::Anchor,
11723        text: &str,
11724        trigger_in_words: bool,
11725        cx: &mut ViewContext<Editor>,
11726    ) -> bool;
11727}
11728
11729impl CompletionProvider for Model<Project> {
11730    fn completions(
11731        &self,
11732        buffer: &Model<Buffer>,
11733        buffer_position: text::Anchor,
11734        options: CompletionContext,
11735        cx: &mut ViewContext<Editor>,
11736    ) -> Task<Result<Vec<Completion>>> {
11737        self.update(cx, |project, cx| {
11738            project.completions(&buffer, buffer_position, options, cx)
11739        })
11740    }
11741
11742    fn resolve_completions(
11743        &self,
11744        buffer: Model<Buffer>,
11745        completion_indices: Vec<usize>,
11746        completions: Arc<RwLock<Box<[Completion]>>>,
11747        cx: &mut ViewContext<Editor>,
11748    ) -> Task<Result<bool>> {
11749        self.update(cx, |project, cx| {
11750            project.resolve_completions(buffer, completion_indices, completions, cx)
11751        })
11752    }
11753
11754    fn apply_additional_edits_for_completion(
11755        &self,
11756        buffer: Model<Buffer>,
11757        completion: Completion,
11758        push_to_history: bool,
11759        cx: &mut ViewContext<Editor>,
11760    ) -> Task<Result<Option<language::Transaction>>> {
11761        self.update(cx, |project, cx| {
11762            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
11763        })
11764    }
11765
11766    fn is_completion_trigger(
11767        &self,
11768        buffer: &Model<Buffer>,
11769        position: language::Anchor,
11770        text: &str,
11771        trigger_in_words: bool,
11772        cx: &mut ViewContext<Editor>,
11773    ) -> bool {
11774        if !EditorSettings::get_global(cx).show_completions_on_input {
11775            return false;
11776        }
11777
11778        let mut chars = text.chars();
11779        let char = if let Some(char) = chars.next() {
11780            char
11781        } else {
11782            return false;
11783        };
11784        if chars.next().is_some() {
11785            return false;
11786        }
11787
11788        let buffer = buffer.read(cx);
11789        let scope = buffer.snapshot().language_scope_at(position);
11790        if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
11791            return true;
11792        }
11793
11794        buffer
11795            .completion_triggers()
11796            .iter()
11797            .any(|string| string == text)
11798    }
11799}
11800
11801fn inlay_hint_settings(
11802    location: Anchor,
11803    snapshot: &MultiBufferSnapshot,
11804    cx: &mut ViewContext<'_, Editor>,
11805) -> InlayHintSettings {
11806    let file = snapshot.file_at(location);
11807    let language = snapshot.language_at(location);
11808    let settings = all_language_settings(file, cx);
11809    settings
11810        .language(language.map(|l| l.name()).as_deref())
11811        .inlay_hints
11812}
11813
11814fn consume_contiguous_rows(
11815    contiguous_row_selections: &mut Vec<Selection<Point>>,
11816    selection: &Selection<Point>,
11817    display_map: &DisplaySnapshot,
11818    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
11819) -> (MultiBufferRow, MultiBufferRow) {
11820    contiguous_row_selections.push(selection.clone());
11821    let start_row = MultiBufferRow(selection.start.row);
11822    let mut end_row = ending_row(selection, display_map);
11823
11824    while let Some(next_selection) = selections.peek() {
11825        if next_selection.start.row <= end_row.0 {
11826            end_row = ending_row(next_selection, display_map);
11827            contiguous_row_selections.push(selections.next().unwrap().clone());
11828        } else {
11829            break;
11830        }
11831    }
11832    (start_row, end_row)
11833}
11834
11835fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
11836    if next_selection.end.column > 0 || next_selection.is_empty() {
11837        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
11838    } else {
11839        MultiBufferRow(next_selection.end.row)
11840    }
11841}
11842
11843impl EditorSnapshot {
11844    pub fn remote_selections_in_range<'a>(
11845        &'a self,
11846        range: &'a Range<Anchor>,
11847        collaboration_hub: &dyn CollaborationHub,
11848        cx: &'a AppContext,
11849    ) -> impl 'a + Iterator<Item = RemoteSelection> {
11850        let participant_names = collaboration_hub.user_names(cx);
11851        let participant_indices = collaboration_hub.user_participant_indices(cx);
11852        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
11853        let collaborators_by_replica_id = collaborators_by_peer_id
11854            .iter()
11855            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
11856            .collect::<HashMap<_, _>>();
11857        self.buffer_snapshot
11858            .selections_in_range(range, false)
11859            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
11860                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
11861                let participant_index = participant_indices.get(&collaborator.user_id).copied();
11862                let user_name = participant_names.get(&collaborator.user_id).cloned();
11863                Some(RemoteSelection {
11864                    replica_id,
11865                    selection,
11866                    cursor_shape,
11867                    line_mode,
11868                    participant_index,
11869                    peer_id: collaborator.peer_id,
11870                    user_name,
11871                })
11872            })
11873    }
11874
11875    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
11876        self.display_snapshot.buffer_snapshot.language_at(position)
11877    }
11878
11879    pub fn is_focused(&self) -> bool {
11880        self.is_focused
11881    }
11882
11883    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
11884        self.placeholder_text.as_ref()
11885    }
11886
11887    pub fn scroll_position(&self) -> gpui::Point<f32> {
11888        self.scroll_anchor.scroll_position(&self.display_snapshot)
11889    }
11890
11891    pub fn gutter_dimensions(
11892        &self,
11893        font_id: FontId,
11894        font_size: Pixels,
11895        em_width: Pixels,
11896        max_line_number_width: Pixels,
11897        cx: &AppContext,
11898    ) -> GutterDimensions {
11899        if !self.show_gutter {
11900            return GutterDimensions::default();
11901        }
11902        let descent = cx.text_system().descent(font_id, font_size);
11903
11904        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
11905            matches!(
11906                ProjectSettings::get_global(cx).git.git_gutter,
11907                Some(GitGutterSetting::TrackedFiles)
11908            )
11909        });
11910        let gutter_settings = EditorSettings::get_global(cx).gutter;
11911        let show_line_numbers = self
11912            .show_line_numbers
11913            .unwrap_or(gutter_settings.line_numbers);
11914        let line_gutter_width = if show_line_numbers {
11915            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
11916            let min_width_for_number_on_gutter = em_width * 4.0;
11917            max_line_number_width.max(min_width_for_number_on_gutter)
11918        } else {
11919            0.0.into()
11920        };
11921
11922        let show_code_actions = self
11923            .show_code_actions
11924            .unwrap_or(gutter_settings.code_actions);
11925
11926        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
11927
11928        let git_blame_entries_width = self
11929            .render_git_blame_gutter
11930            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
11931
11932        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
11933        left_padding += if show_code_actions || show_runnables {
11934            em_width * 3.0
11935        } else if show_git_gutter && show_line_numbers {
11936            em_width * 2.0
11937        } else if show_git_gutter || show_line_numbers {
11938            em_width
11939        } else {
11940            px(0.)
11941        };
11942
11943        let right_padding = if gutter_settings.folds && show_line_numbers {
11944            em_width * 4.0
11945        } else if gutter_settings.folds {
11946            em_width * 3.0
11947        } else if show_line_numbers {
11948            em_width
11949        } else {
11950            px(0.)
11951        };
11952
11953        GutterDimensions {
11954            left_padding,
11955            right_padding,
11956            width: line_gutter_width + left_padding + right_padding,
11957            margin: -descent,
11958            git_blame_entries_width,
11959        }
11960    }
11961
11962    pub fn render_fold_toggle(
11963        &self,
11964        buffer_row: MultiBufferRow,
11965        row_contains_cursor: bool,
11966        editor: View<Editor>,
11967        cx: &mut WindowContext,
11968    ) -> Option<AnyElement> {
11969        let folded = self.is_line_folded(buffer_row);
11970
11971        if let Some(crease) = self
11972            .crease_snapshot
11973            .query_row(buffer_row, &self.buffer_snapshot)
11974        {
11975            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
11976                if folded {
11977                    editor.update(cx, |editor, cx| {
11978                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
11979                    });
11980                } else {
11981                    editor.update(cx, |editor, cx| {
11982                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
11983                    });
11984                }
11985            });
11986
11987            Some((crease.render_toggle)(
11988                buffer_row,
11989                folded,
11990                toggle_callback,
11991                cx,
11992            ))
11993        } else if folded
11994            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
11995        {
11996            Some(
11997                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
11998                    .selected(folded)
11999                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12000                        if folded {
12001                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
12002                        } else {
12003                            this.fold_at(&FoldAt { buffer_row }, cx);
12004                        }
12005                    }))
12006                    .into_any_element(),
12007            )
12008        } else {
12009            None
12010        }
12011    }
12012
12013    pub fn render_crease_trailer(
12014        &self,
12015        buffer_row: MultiBufferRow,
12016        cx: &mut WindowContext,
12017    ) -> Option<AnyElement> {
12018        let folded = self.is_line_folded(buffer_row);
12019        let crease = self
12020            .crease_snapshot
12021            .query_row(buffer_row, &self.buffer_snapshot)?;
12022        Some((crease.render_trailer)(buffer_row, folded, cx))
12023    }
12024}
12025
12026impl Deref for EditorSnapshot {
12027    type Target = DisplaySnapshot;
12028
12029    fn deref(&self) -> &Self::Target {
12030        &self.display_snapshot
12031    }
12032}
12033
12034#[derive(Clone, Debug, PartialEq, Eq)]
12035pub enum EditorEvent {
12036    InputIgnored {
12037        text: Arc<str>,
12038    },
12039    InputHandled {
12040        utf16_range_to_replace: Option<Range<isize>>,
12041        text: Arc<str>,
12042    },
12043    ExcerptsAdded {
12044        buffer: Model<Buffer>,
12045        predecessor: ExcerptId,
12046        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12047    },
12048    ExcerptsRemoved {
12049        ids: Vec<ExcerptId>,
12050    },
12051    ExcerptsEdited {
12052        ids: Vec<ExcerptId>,
12053    },
12054    ExcerptsExpanded {
12055        ids: Vec<ExcerptId>,
12056    },
12057    BufferEdited,
12058    Edited {
12059        transaction_id: clock::Lamport,
12060    },
12061    Reparsed(BufferId),
12062    Focused,
12063    Blurred,
12064    DirtyChanged,
12065    Saved,
12066    TitleChanged,
12067    DiffBaseChanged,
12068    SelectionsChanged {
12069        local: bool,
12070    },
12071    ScrollPositionChanged {
12072        local: bool,
12073        autoscroll: bool,
12074    },
12075    Closed,
12076    TransactionUndone {
12077        transaction_id: clock::Lamport,
12078    },
12079    TransactionBegun {
12080        transaction_id: clock::Lamport,
12081    },
12082}
12083
12084impl EventEmitter<EditorEvent> for Editor {}
12085
12086impl FocusableView for Editor {
12087    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12088        self.focus_handle.clone()
12089    }
12090}
12091
12092impl Render for Editor {
12093    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12094        let settings = ThemeSettings::get_global(cx);
12095
12096        let text_style = match self.mode {
12097            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12098                color: cx.theme().colors().editor_foreground,
12099                font_family: settings.ui_font.family.clone(),
12100                font_features: settings.ui_font.features.clone(),
12101                font_size: rems(0.875).into(),
12102                font_weight: settings.ui_font.weight,
12103                font_style: FontStyle::Normal,
12104                line_height: relative(settings.buffer_line_height.value()),
12105                background_color: None,
12106                underline: None,
12107                strikethrough: None,
12108                white_space: WhiteSpace::Normal,
12109            },
12110            EditorMode::Full => TextStyle {
12111                color: cx.theme().colors().editor_foreground,
12112                font_family: settings.buffer_font.family.clone(),
12113                font_features: settings.buffer_font.features.clone(),
12114                font_size: settings.buffer_font_size(cx).into(),
12115                font_weight: settings.buffer_font.weight,
12116                font_style: FontStyle::Normal,
12117                line_height: relative(settings.buffer_line_height.value()),
12118                background_color: None,
12119                underline: None,
12120                strikethrough: None,
12121                white_space: WhiteSpace::Normal,
12122            },
12123        };
12124
12125        let background = match self.mode {
12126            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12127            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12128            EditorMode::Full => cx.theme().colors().editor_background,
12129        };
12130
12131        EditorElement::new(
12132            cx.view(),
12133            EditorStyle {
12134                background,
12135                local_player: cx.theme().players().local(),
12136                text: text_style,
12137                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12138                syntax: cx.theme().syntax().clone(),
12139                status: cx.theme().status().clone(),
12140                inlay_hints_style: HighlightStyle {
12141                    color: Some(cx.theme().status().hint),
12142                    ..HighlightStyle::default()
12143                },
12144                suggestions_style: HighlightStyle {
12145                    color: Some(cx.theme().status().predictive),
12146                    ..HighlightStyle::default()
12147                },
12148            },
12149        )
12150    }
12151}
12152
12153impl ViewInputHandler for Editor {
12154    fn text_for_range(
12155        &mut self,
12156        range_utf16: Range<usize>,
12157        cx: &mut ViewContext<Self>,
12158    ) -> Option<String> {
12159        Some(
12160            self.buffer
12161                .read(cx)
12162                .read(cx)
12163                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12164                .collect(),
12165        )
12166    }
12167
12168    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12169        // Prevent the IME menu from appearing when holding down an alphabetic key
12170        // while input is disabled.
12171        if !self.input_enabled {
12172            return None;
12173        }
12174
12175        let range = self.selections.newest::<OffsetUtf16>(cx).range();
12176        Some(range.start.0..range.end.0)
12177    }
12178
12179    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12180        let snapshot = self.buffer.read(cx).read(cx);
12181        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12182        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12183    }
12184
12185    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12186        self.clear_highlights::<InputComposition>(cx);
12187        self.ime_transaction.take();
12188    }
12189
12190    fn replace_text_in_range(
12191        &mut self,
12192        range_utf16: Option<Range<usize>>,
12193        text: &str,
12194        cx: &mut ViewContext<Self>,
12195    ) {
12196        if !self.input_enabled {
12197            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12198            return;
12199        }
12200
12201        self.transact(cx, |this, cx| {
12202            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12203                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12204                Some(this.selection_replacement_ranges(range_utf16, cx))
12205            } else {
12206                this.marked_text_ranges(cx)
12207            };
12208
12209            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12210                let newest_selection_id = this.selections.newest_anchor().id;
12211                this.selections
12212                    .all::<OffsetUtf16>(cx)
12213                    .iter()
12214                    .zip(ranges_to_replace.iter())
12215                    .find_map(|(selection, range)| {
12216                        if selection.id == newest_selection_id {
12217                            Some(
12218                                (range.start.0 as isize - selection.head().0 as isize)
12219                                    ..(range.end.0 as isize - selection.head().0 as isize),
12220                            )
12221                        } else {
12222                            None
12223                        }
12224                    })
12225            });
12226
12227            cx.emit(EditorEvent::InputHandled {
12228                utf16_range_to_replace: range_to_replace,
12229                text: text.into(),
12230            });
12231
12232            if let Some(new_selected_ranges) = new_selected_ranges {
12233                this.change_selections(None, cx, |selections| {
12234                    selections.select_ranges(new_selected_ranges)
12235                });
12236                this.backspace(&Default::default(), cx);
12237            }
12238
12239            this.handle_input(text, cx);
12240        });
12241
12242        if let Some(transaction) = self.ime_transaction {
12243            self.buffer.update(cx, |buffer, cx| {
12244                buffer.group_until_transaction(transaction, cx);
12245            });
12246        }
12247
12248        self.unmark_text(cx);
12249    }
12250
12251    fn replace_and_mark_text_in_range(
12252        &mut self,
12253        range_utf16: Option<Range<usize>>,
12254        text: &str,
12255        new_selected_range_utf16: Option<Range<usize>>,
12256        cx: &mut ViewContext<Self>,
12257    ) {
12258        if !self.input_enabled {
12259            return;
12260        }
12261
12262        let transaction = self.transact(cx, |this, cx| {
12263            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12264                let snapshot = this.buffer.read(cx).read(cx);
12265                if let Some(relative_range_utf16) = range_utf16.as_ref() {
12266                    for marked_range in &mut marked_ranges {
12267                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12268                        marked_range.start.0 += relative_range_utf16.start;
12269                        marked_range.start =
12270                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12271                        marked_range.end =
12272                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12273                    }
12274                }
12275                Some(marked_ranges)
12276            } else if let Some(range_utf16) = range_utf16 {
12277                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12278                Some(this.selection_replacement_ranges(range_utf16, cx))
12279            } else {
12280                None
12281            };
12282
12283            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12284                let newest_selection_id = this.selections.newest_anchor().id;
12285                this.selections
12286                    .all::<OffsetUtf16>(cx)
12287                    .iter()
12288                    .zip(ranges_to_replace.iter())
12289                    .find_map(|(selection, range)| {
12290                        if selection.id == newest_selection_id {
12291                            Some(
12292                                (range.start.0 as isize - selection.head().0 as isize)
12293                                    ..(range.end.0 as isize - selection.head().0 as isize),
12294                            )
12295                        } else {
12296                            None
12297                        }
12298                    })
12299            });
12300
12301            cx.emit(EditorEvent::InputHandled {
12302                utf16_range_to_replace: range_to_replace,
12303                text: text.into(),
12304            });
12305
12306            if let Some(ranges) = ranges_to_replace {
12307                this.change_selections(None, cx, |s| s.select_ranges(ranges));
12308            }
12309
12310            let marked_ranges = {
12311                let snapshot = this.buffer.read(cx).read(cx);
12312                this.selections
12313                    .disjoint_anchors()
12314                    .iter()
12315                    .map(|selection| {
12316                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12317                    })
12318                    .collect::<Vec<_>>()
12319            };
12320
12321            if text.is_empty() {
12322                this.unmark_text(cx);
12323            } else {
12324                this.highlight_text::<InputComposition>(
12325                    marked_ranges.clone(),
12326                    HighlightStyle {
12327                        underline: Some(UnderlineStyle {
12328                            thickness: px(1.),
12329                            color: None,
12330                            wavy: false,
12331                        }),
12332                        ..Default::default()
12333                    },
12334                    cx,
12335                );
12336            }
12337
12338            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12339            let use_autoclose = this.use_autoclose;
12340            let use_auto_surround = this.use_auto_surround;
12341            this.set_use_autoclose(false);
12342            this.set_use_auto_surround(false);
12343            this.handle_input(text, cx);
12344            this.set_use_autoclose(use_autoclose);
12345            this.set_use_auto_surround(use_auto_surround);
12346
12347            if let Some(new_selected_range) = new_selected_range_utf16 {
12348                let snapshot = this.buffer.read(cx).read(cx);
12349                let new_selected_ranges = marked_ranges
12350                    .into_iter()
12351                    .map(|marked_range| {
12352                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12353                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12354                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12355                        snapshot.clip_offset_utf16(new_start, Bias::Left)
12356                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12357                    })
12358                    .collect::<Vec<_>>();
12359
12360                drop(snapshot);
12361                this.change_selections(None, cx, |selections| {
12362                    selections.select_ranges(new_selected_ranges)
12363                });
12364            }
12365        });
12366
12367        self.ime_transaction = self.ime_transaction.or(transaction);
12368        if let Some(transaction) = self.ime_transaction {
12369            self.buffer.update(cx, |buffer, cx| {
12370                buffer.group_until_transaction(transaction, cx);
12371            });
12372        }
12373
12374        if self.text_highlights::<InputComposition>(cx).is_none() {
12375            self.ime_transaction.take();
12376        }
12377    }
12378
12379    fn bounds_for_range(
12380        &mut self,
12381        range_utf16: Range<usize>,
12382        element_bounds: gpui::Bounds<Pixels>,
12383        cx: &mut ViewContext<Self>,
12384    ) -> Option<gpui::Bounds<Pixels>> {
12385        let text_layout_details = self.text_layout_details(cx);
12386        let style = &text_layout_details.editor_style;
12387        let font_id = cx.text_system().resolve_font(&style.text.font());
12388        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12389        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12390
12391        let em_width = cx
12392            .text_system()
12393            .typographic_bounds(font_id, font_size, 'm')
12394            .unwrap()
12395            .size
12396            .width;
12397
12398        let snapshot = self.snapshot(cx);
12399        let scroll_position = snapshot.scroll_position();
12400        let scroll_left = scroll_position.x * em_width;
12401
12402        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12403        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12404            + self.gutter_dimensions.width;
12405        let y = line_height * (start.row().as_f32() - scroll_position.y);
12406
12407        Some(Bounds {
12408            origin: element_bounds.origin + point(x, y),
12409            size: size(em_width, line_height),
12410        })
12411    }
12412}
12413
12414trait SelectionExt {
12415    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12416    fn spanned_rows(
12417        &self,
12418        include_end_if_at_line_start: bool,
12419        map: &DisplaySnapshot,
12420    ) -> Range<MultiBufferRow>;
12421}
12422
12423impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12424    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12425        let start = self
12426            .start
12427            .to_point(&map.buffer_snapshot)
12428            .to_display_point(map);
12429        let end = self
12430            .end
12431            .to_point(&map.buffer_snapshot)
12432            .to_display_point(map);
12433        if self.reversed {
12434            end..start
12435        } else {
12436            start..end
12437        }
12438    }
12439
12440    fn spanned_rows(
12441        &self,
12442        include_end_if_at_line_start: bool,
12443        map: &DisplaySnapshot,
12444    ) -> Range<MultiBufferRow> {
12445        let start = self.start.to_point(&map.buffer_snapshot);
12446        let mut end = self.end.to_point(&map.buffer_snapshot);
12447        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12448            end.row -= 1;
12449        }
12450
12451        let buffer_start = map.prev_line_boundary(start).0;
12452        let buffer_end = map.next_line_boundary(end).0;
12453        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12454    }
12455}
12456
12457impl<T: InvalidationRegion> InvalidationStack<T> {
12458    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12459    where
12460        S: Clone + ToOffset,
12461    {
12462        while let Some(region) = self.last() {
12463            let all_selections_inside_invalidation_ranges =
12464                if selections.len() == region.ranges().len() {
12465                    selections
12466                        .iter()
12467                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12468                        .all(|(selection, invalidation_range)| {
12469                            let head = selection.head().to_offset(buffer);
12470                            invalidation_range.start <= head && invalidation_range.end >= head
12471                        })
12472                } else {
12473                    false
12474                };
12475
12476            if all_selections_inside_invalidation_ranges {
12477                break;
12478            } else {
12479                self.pop();
12480            }
12481        }
12482    }
12483}
12484
12485impl<T> Default for InvalidationStack<T> {
12486    fn default() -> Self {
12487        Self(Default::default())
12488    }
12489}
12490
12491impl<T> Deref for InvalidationStack<T> {
12492    type Target = Vec<T>;
12493
12494    fn deref(&self) -> &Self::Target {
12495        &self.0
12496    }
12497}
12498
12499impl<T> DerefMut for InvalidationStack<T> {
12500    fn deref_mut(&mut self) -> &mut Self::Target {
12501        &mut self.0
12502    }
12503}
12504
12505impl InvalidationRegion for SnippetState {
12506    fn ranges(&self) -> &[Range<Anchor>] {
12507        &self.ranges[self.active_index]
12508    }
12509}
12510
12511pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
12512    let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
12513
12514    Box::new(move |cx: &mut BlockContext| {
12515        let group_id: SharedString = cx.block_id.to_string().into();
12516
12517        let mut text_style = cx.text_style().clone();
12518        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
12519        let theme_settings = ThemeSettings::get_global(cx);
12520        text_style.font_family = theme_settings.buffer_font.family.clone();
12521        text_style.font_style = theme_settings.buffer_font.style;
12522        text_style.font_features = theme_settings.buffer_font.features.clone();
12523        text_style.font_weight = theme_settings.buffer_font.weight;
12524
12525        let multi_line_diagnostic = diagnostic.message.contains('\n');
12526
12527        let buttons = |diagnostic: &Diagnostic, block_id: usize| {
12528            if multi_line_diagnostic {
12529                v_flex()
12530            } else {
12531                h_flex()
12532            }
12533            .children(diagnostic.is_primary.then(|| {
12534                IconButton::new(("close-block", block_id), IconName::XCircle)
12535                    .icon_color(Color::Muted)
12536                    .size(ButtonSize::Compact)
12537                    .style(ButtonStyle::Transparent)
12538                    .visible_on_hover(group_id.clone())
12539                    .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
12540                    .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
12541            }))
12542            .child(
12543                IconButton::new(("copy-block", block_id), IconName::Copy)
12544                    .icon_color(Color::Muted)
12545                    .size(ButtonSize::Compact)
12546                    .style(ButtonStyle::Transparent)
12547                    .visible_on_hover(group_id.clone())
12548                    .on_click({
12549                        let message = diagnostic.message.clone();
12550                        move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
12551                    })
12552                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
12553            )
12554        };
12555
12556        let icon_size = buttons(&diagnostic, cx.block_id)
12557            .into_any_element()
12558            .layout_as_root(AvailableSpace::min_size(), cx);
12559
12560        h_flex()
12561            .id(cx.block_id)
12562            .group(group_id.clone())
12563            .relative()
12564            .size_full()
12565            .pl(cx.gutter_dimensions.width)
12566            .w(cx.max_width + cx.gutter_dimensions.width)
12567            .child(
12568                div()
12569                    .flex()
12570                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
12571                    .flex_shrink(),
12572            )
12573            .child(buttons(&diagnostic, cx.block_id))
12574            .child(div().flex().flex_shrink_0().child(
12575                StyledText::new(text_without_backticks.clone()).with_highlights(
12576                    &text_style,
12577                    code_ranges.iter().map(|range| {
12578                        (
12579                            range.clone(),
12580                            HighlightStyle {
12581                                font_weight: Some(FontWeight::BOLD),
12582                                ..Default::default()
12583                            },
12584                        )
12585                    }),
12586                ),
12587            ))
12588            .into_any_element()
12589    })
12590}
12591
12592pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
12593    let mut text_without_backticks = String::new();
12594    let mut code_ranges = Vec::new();
12595
12596    if let Some(source) = &diagnostic.source {
12597        text_without_backticks.push_str(&source);
12598        code_ranges.push(0..source.len());
12599        text_without_backticks.push_str(": ");
12600    }
12601
12602    let mut prev_offset = 0;
12603    let mut in_code_block = false;
12604    for (ix, _) in diagnostic
12605        .message
12606        .match_indices('`')
12607        .chain([(diagnostic.message.len(), "")])
12608    {
12609        let prev_len = text_without_backticks.len();
12610        text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
12611        prev_offset = ix + 1;
12612        if in_code_block {
12613            code_ranges.push(prev_len..text_without_backticks.len());
12614        }
12615        in_code_block = !in_code_block;
12616    }
12617
12618    (text_without_backticks.into(), code_ranges)
12619}
12620
12621fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
12622    match severity {
12623        DiagnosticSeverity::ERROR => colors.error,
12624        DiagnosticSeverity::WARNING => colors.warning,
12625        DiagnosticSeverity::INFORMATION => colors.info,
12626        DiagnosticSeverity::HINT => colors.info,
12627        _ => colors.ignored,
12628    }
12629}
12630
12631pub fn styled_runs_for_code_label<'a>(
12632    label: &'a CodeLabel,
12633    syntax_theme: &'a theme::SyntaxTheme,
12634) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
12635    let fade_out = HighlightStyle {
12636        fade_out: Some(0.35),
12637        ..Default::default()
12638    };
12639
12640    let mut prev_end = label.filter_range.end;
12641    label
12642        .runs
12643        .iter()
12644        .enumerate()
12645        .flat_map(move |(ix, (range, highlight_id))| {
12646            let style = if let Some(style) = highlight_id.style(syntax_theme) {
12647                style
12648            } else {
12649                return Default::default();
12650            };
12651            let mut muted_style = style;
12652            muted_style.highlight(fade_out);
12653
12654            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
12655            if range.start >= label.filter_range.end {
12656                if range.start > prev_end {
12657                    runs.push((prev_end..range.start, fade_out));
12658                }
12659                runs.push((range.clone(), muted_style));
12660            } else if range.end <= label.filter_range.end {
12661                runs.push((range.clone(), style));
12662            } else {
12663                runs.push((range.start..label.filter_range.end, style));
12664                runs.push((label.filter_range.end..range.end, muted_style));
12665            }
12666            prev_end = cmp::max(prev_end, range.end);
12667
12668            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
12669                runs.push((prev_end..label.text.len(), fade_out));
12670            }
12671
12672            runs
12673        })
12674}
12675
12676pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
12677    let mut prev_index = 0;
12678    let mut prev_codepoint: Option<char> = None;
12679    text.char_indices()
12680        .chain([(text.len(), '\0')])
12681        .filter_map(move |(index, codepoint)| {
12682            let prev_codepoint = prev_codepoint.replace(codepoint)?;
12683            let is_boundary = index == text.len()
12684                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
12685                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
12686            if is_boundary {
12687                let chunk = &text[prev_index..index];
12688                prev_index = index;
12689                Some(chunk)
12690            } else {
12691                None
12692            }
12693        })
12694}
12695
12696trait RangeToAnchorExt {
12697    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
12698}
12699
12700impl<T: ToOffset> RangeToAnchorExt for Range<T> {
12701    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
12702        let start_offset = self.start.to_offset(snapshot);
12703        let end_offset = self.end.to_offset(snapshot);
12704        if start_offset == end_offset {
12705            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
12706        } else {
12707            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
12708        }
12709    }
12710}
12711
12712pub trait RowExt {
12713    fn as_f32(&self) -> f32;
12714
12715    fn next_row(&self) -> Self;
12716
12717    fn previous_row(&self) -> Self;
12718
12719    fn minus(&self, other: Self) -> u32;
12720}
12721
12722impl RowExt for DisplayRow {
12723    fn as_f32(&self) -> f32 {
12724        self.0 as f32
12725    }
12726
12727    fn next_row(&self) -> Self {
12728        Self(self.0 + 1)
12729    }
12730
12731    fn previous_row(&self) -> Self {
12732        Self(self.0.saturating_sub(1))
12733    }
12734
12735    fn minus(&self, other: Self) -> u32 {
12736        self.0 - other.0
12737    }
12738}
12739
12740impl RowExt for MultiBufferRow {
12741    fn as_f32(&self) -> f32 {
12742        self.0 as f32
12743    }
12744
12745    fn next_row(&self) -> Self {
12746        Self(self.0 + 1)
12747    }
12748
12749    fn previous_row(&self) -> Self {
12750        Self(self.0.saturating_sub(1))
12751    }
12752
12753    fn minus(&self, other: Self) -> u32 {
12754        self.0 - other.0
12755    }
12756}
12757
12758trait RowRangeExt {
12759    type Row;
12760
12761    fn len(&self) -> usize;
12762
12763    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
12764}
12765
12766impl RowRangeExt for Range<MultiBufferRow> {
12767    type Row = MultiBufferRow;
12768
12769    fn len(&self) -> usize {
12770        (self.end.0 - self.start.0) as usize
12771    }
12772
12773    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
12774        (self.start.0..self.end.0).map(MultiBufferRow)
12775    }
12776}
12777
12778impl RowRangeExt for Range<DisplayRow> {
12779    type Row = DisplayRow;
12780
12781    fn len(&self) -> usize {
12782        (self.end.0 - self.start.0) as usize
12783    }
12784
12785    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
12786        (self.start.0..self.end.0).map(DisplayRow)
12787    }
12788}
12789
12790fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
12791    if hunk.diff_base_byte_range.is_empty() {
12792        DiffHunkStatus::Added
12793    } else if hunk.associated_range.is_empty() {
12794        DiffHunkStatus::Removed
12795    } else {
12796        DiffHunkStatus::Modified
12797    }
12798}