editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behaviour.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod debounced_delay;
   19pub mod display_map;
   20mod editor_settings;
   21mod element;
   22mod git;
   23mod highlight_matching_bracket;
   24mod hover_links;
   25mod hover_popover;
   26mod hunk_diff;
   27mod indent_guides;
   28mod inlay_hint_cache;
   29mod inline_completion_provider;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod mouse_context_menu;
   33pub mod movement;
   34mod persistence;
   35mod rust_analyzer_ext;
   36pub mod scroll;
   37mod selections_collection;
   38pub mod tasks;
   39
   40#[cfg(test)]
   41mod editor_tests;
   42#[cfg(any(test, feature = "test-support"))]
   43pub mod test;
   44use ::git::diff::{DiffHunk, DiffHunkStatus};
   45use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
   46pub(crate) use actions::*;
   47use aho_corasick::AhoCorasick;
   48use anyhow::{anyhow, Context as _, Result};
   49use blink_manager::BlinkManager;
   50use client::{Collaborator, ParticipantIndex};
   51use clock::ReplicaId;
   52use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   53use convert_case::{Case, Casing};
   54use debounced_delay::DebouncedDelay;
   55use display_map::*;
   56pub use display_map::{DisplayPoint, FoldPlaceholder};
   57pub use editor_settings::{CurrentLineHighlight, EditorSettings};
   58use element::LineWithInvisibles;
   59pub use element::{
   60    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   61};
   62use futures::FutureExt;
   63use fuzzy::{StringMatch, StringMatchCandidate};
   64use git::blame::GitBlame;
   65use git::diff_hunk_to_display;
   66use gpui::{
   67    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   68    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardItem,
   69    Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView,
   70    FontId, FontStyle, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext,
   71    ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString,
   72    Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle, UnderlineStyle,
   73    UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
   74    WeakView, WhiteSpace, WindowContext,
   75};
   76use highlight_matching_bracket::refresh_matching_bracket_highlights;
   77use hover_popover::{hide_hover, HoverState};
   78use hunk_diff::ExpandedHunks;
   79pub(crate) use hunk_diff::HunkToExpand;
   80use indent_guides::ActiveIndentGuidesState;
   81use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   82pub use inline_completion_provider::*;
   83pub use items::MAX_TAB_TITLE_LEN;
   84use itertools::Itertools;
   85use language::{
   86    char_kind,
   87    language_settings::{self, all_language_settings, InlayHintSettings},
   88    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   89    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   90    Point, Selection, SelectionGoal, TransactionId,
   91};
   92use language::{BufferRow, Runnable, RunnableRange};
   93use linked_editing_ranges::refresh_linked_ranges;
   94use task::{ResolvedTask, TaskTemplate, TaskVariables};
   95
   96use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
   97pub use lsp::CompletionContext;
   98use lsp::{CompletionTriggerKind, DiagnosticSeverity, LanguageServerId};
   99use mouse_context_menu::MouseContextMenu;
  100use movement::TextLayoutDetails;
  101pub use multi_buffer::{
  102    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  103    ToPoint,
  104};
  105use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
  106use ordered_float::OrderedFloat;
  107use parking_lot::{Mutex, RwLock};
  108use project::project_settings::{GitGutterSetting, ProjectSettings};
  109use project::{
  110    CodeAction, Completion, FormatTrigger, Item, Location, Project, ProjectPath,
  111    ProjectTransaction, TaskSourceKind, WorktreeId,
  112};
  113use rand::prelude::*;
  114use rpc::{proto::*, ErrorExt};
  115use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  116use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  117use serde::{Deserialize, Serialize};
  118use settings::{update_settings_file, Settings, SettingsStore};
  119use smallvec::SmallVec;
  120use snippet::Snippet;
  121use std::{
  122    any::TypeId,
  123    borrow::Cow,
  124    cell::RefCell,
  125    cmp::{self, Ordering, Reverse},
  126    mem,
  127    num::NonZeroU32,
  128    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  129    path::Path,
  130    rc::Rc,
  131    sync::Arc,
  132    time::{Duration, Instant},
  133};
  134pub use sum_tree::Bias;
  135use sum_tree::TreeMap;
  136use text::{BufferId, OffsetUtf16, Rope};
  137use theme::{
  138    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  139    ThemeColors, ThemeSettings,
  140};
  141use ui::{
  142    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  143    ListItem, Popover, Tooltip,
  144};
  145use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  146use workspace::item::{ItemHandle, PreviewTabsSettings};
  147use workspace::notifications::{DetachAndPromptErr, NotificationId};
  148use workspace::{
  149    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  150};
  151use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  152
  153use crate::hover_links::find_url;
  154
  155pub const FILE_HEADER_HEIGHT: u8 = 1;
  156pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u8 = 1;
  157pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u8 = 1;
  158pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  159const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  160const MAX_LINE_LEN: usize = 1024;
  161const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  162const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  163pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  164#[doc(hidden)]
  165pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  166#[doc(hidden)]
  167pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  168
  169pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  170
  171pub fn render_parsed_markdown(
  172    element_id: impl Into<ElementId>,
  173    parsed: &language::ParsedMarkdown,
  174    editor_style: &EditorStyle,
  175    workspace: Option<WeakView<Workspace>>,
  176    cx: &mut WindowContext,
  177) -> InteractiveText {
  178    let code_span_background_color = cx
  179        .theme()
  180        .colors()
  181        .editor_document_highlight_read_background;
  182
  183    let highlights = gpui::combine_highlights(
  184        parsed.highlights.iter().filter_map(|(range, highlight)| {
  185            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  186            Some((range.clone(), highlight))
  187        }),
  188        parsed
  189            .regions
  190            .iter()
  191            .zip(&parsed.region_ranges)
  192            .filter_map(|(region, range)| {
  193                if region.code {
  194                    Some((
  195                        range.clone(),
  196                        HighlightStyle {
  197                            background_color: Some(code_span_background_color),
  198                            ..Default::default()
  199                        },
  200                    ))
  201                } else {
  202                    None
  203                }
  204            }),
  205    );
  206
  207    let mut links = Vec::new();
  208    let mut link_ranges = Vec::new();
  209    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  210        if let Some(link) = region.link.clone() {
  211            links.push(link);
  212            link_ranges.push(range.clone());
  213        }
  214    }
  215
  216    InteractiveText::new(
  217        element_id,
  218        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  219    )
  220    .on_click(link_ranges, move |clicked_range_ix, cx| {
  221        match &links[clicked_range_ix] {
  222            markdown::Link::Web { url } => cx.open_url(url),
  223            markdown::Link::Path { path } => {
  224                if let Some(workspace) = &workspace {
  225                    _ = workspace.update(cx, |workspace, cx| {
  226                        workspace.open_abs_path(path.clone(), false, cx).detach();
  227                    });
  228                }
  229            }
  230        }
  231    })
  232}
  233
  234#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  235pub(crate) enum InlayId {
  236    Suggestion(usize),
  237    Hint(usize),
  238}
  239
  240impl InlayId {
  241    fn id(&self) -> usize {
  242        match self {
  243            Self::Suggestion(id) => *id,
  244            Self::Hint(id) => *id,
  245        }
  246    }
  247}
  248
  249enum DiffRowHighlight {}
  250enum DocumentHighlightRead {}
  251enum DocumentHighlightWrite {}
  252enum InputComposition {}
  253
  254#[derive(Copy, Clone, PartialEq, Eq)]
  255pub enum Direction {
  256    Prev,
  257    Next,
  258}
  259
  260pub fn init_settings(cx: &mut AppContext) {
  261    EditorSettings::register(cx);
  262}
  263
  264pub fn init(cx: &mut AppContext) {
  265    init_settings(cx);
  266
  267    workspace::register_project_item::<Editor>(cx);
  268    workspace::register_followable_item::<Editor>(cx);
  269    workspace::register_deserializable_item::<Editor>(cx);
  270    cx.observe_new_views(
  271        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  272            workspace.register_action(Editor::new_file);
  273            workspace.register_action(Editor::new_file_in_direction);
  274        },
  275    )
  276    .detach();
  277
  278    cx.on_action(move |_: &workspace::NewFile, cx| {
  279        let app_state = workspace::AppState::global(cx);
  280        if let Some(app_state) = app_state.upgrade() {
  281            workspace::open_new(app_state, cx, |workspace, cx| {
  282                Editor::new_file(workspace, &Default::default(), cx)
  283            })
  284            .detach();
  285        }
  286    });
  287    cx.on_action(move |_: &workspace::NewWindow, cx| {
  288        let app_state = workspace::AppState::global(cx);
  289        if let Some(app_state) = app_state.upgrade() {
  290            workspace::open_new(app_state, cx, |workspace, cx| {
  291                Editor::new_file(workspace, &Default::default(), cx)
  292            })
  293            .detach();
  294        }
  295    });
  296}
  297
  298pub struct SearchWithinRange;
  299
  300trait InvalidationRegion {
  301    fn ranges(&self) -> &[Range<Anchor>];
  302}
  303
  304#[derive(Clone, Debug, PartialEq)]
  305pub enum SelectPhase {
  306    Begin {
  307        position: DisplayPoint,
  308        add: bool,
  309        click_count: usize,
  310    },
  311    BeginColumnar {
  312        position: DisplayPoint,
  313        reset: bool,
  314        goal_column: u32,
  315    },
  316    Extend {
  317        position: DisplayPoint,
  318        click_count: usize,
  319    },
  320    Update {
  321        position: DisplayPoint,
  322        goal_column: u32,
  323        scroll_delta: gpui::Point<f32>,
  324    },
  325    End,
  326}
  327
  328#[derive(Clone, Debug)]
  329pub enum SelectMode {
  330    Character,
  331    Word(Range<Anchor>),
  332    Line(Range<Anchor>),
  333    All,
  334}
  335
  336#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  337pub enum EditorMode {
  338    SingleLine { auto_width: bool },
  339    AutoHeight { max_lines: usize },
  340    Full,
  341}
  342
  343#[derive(Clone, Debug)]
  344pub enum SoftWrap {
  345    None,
  346    PreferLine,
  347    EditorWidth,
  348    Column(u32),
  349}
  350
  351#[derive(Clone)]
  352pub struct EditorStyle {
  353    pub background: Hsla,
  354    pub local_player: PlayerColor,
  355    pub text: TextStyle,
  356    pub scrollbar_width: Pixels,
  357    pub syntax: Arc<SyntaxTheme>,
  358    pub status: StatusColors,
  359    pub inlay_hints_style: HighlightStyle,
  360    pub suggestions_style: HighlightStyle,
  361}
  362
  363impl Default for EditorStyle {
  364    fn default() -> Self {
  365        Self {
  366            background: Hsla::default(),
  367            local_player: PlayerColor::default(),
  368            text: TextStyle::default(),
  369            scrollbar_width: Pixels::default(),
  370            syntax: Default::default(),
  371            // HACK: Status colors don't have a real default.
  372            // We should look into removing the status colors from the editor
  373            // style and retrieve them directly from the theme.
  374            status: StatusColors::dark(),
  375            inlay_hints_style: HighlightStyle::default(),
  376            suggestions_style: HighlightStyle::default(),
  377        }
  378    }
  379}
  380
  381type CompletionId = usize;
  382
  383#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  384struct EditorActionId(usize);
  385
  386impl EditorActionId {
  387    pub fn post_inc(&mut self) -> Self {
  388        let answer = self.0;
  389
  390        *self = Self(answer + 1);
  391
  392        Self(answer)
  393    }
  394}
  395
  396// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  397// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  398
  399type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  400type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  401
  402struct ScrollbarMarkerState {
  403    scrollbar_size: Size<Pixels>,
  404    dirty: bool,
  405    markers: Arc<[PaintQuad]>,
  406    pending_refresh: Option<Task<Result<()>>>,
  407}
  408
  409impl ScrollbarMarkerState {
  410    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  411        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  412    }
  413}
  414
  415impl Default for ScrollbarMarkerState {
  416    fn default() -> Self {
  417        Self {
  418            scrollbar_size: Size::default(),
  419            dirty: false,
  420            markers: Arc::from([]),
  421            pending_refresh: None,
  422        }
  423    }
  424}
  425
  426#[derive(Clone, Debug)]
  427struct RunnableTasks {
  428    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  429    offset: MultiBufferOffset,
  430    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  431    column: u32,
  432    // Values of all named captures, including those starting with '_'
  433    extra_variables: HashMap<String, String>,
  434    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  435    context_range: Range<BufferOffset>,
  436}
  437
  438#[derive(Clone)]
  439struct ResolvedTasks {
  440    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  441    position: Anchor,
  442}
  443#[derive(Copy, Clone, Debug)]
  444struct MultiBufferOffset(usize);
  445#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  446struct BufferOffset(usize);
  447/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  448///
  449/// See the [module level documentation](self) for more information.
  450pub struct Editor {
  451    focus_handle: FocusHandle,
  452    last_focused_descendant: Option<WeakFocusHandle>,
  453    /// The text buffer being edited
  454    buffer: Model<MultiBuffer>,
  455    /// Map of how text in the buffer should be displayed.
  456    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  457    pub display_map: Model<DisplayMap>,
  458    pub selections: SelectionsCollection,
  459    pub scroll_manager: ScrollManager,
  460    /// When inline assist editors are linked, they all render cursors because
  461    /// typing enters text into each of them, even the ones that aren't focused.
  462    pub(crate) show_cursor_when_unfocused: bool,
  463    columnar_selection_tail: Option<Anchor>,
  464    add_selections_state: Option<AddSelectionsState>,
  465    select_next_state: Option<SelectNextState>,
  466    select_prev_state: Option<SelectNextState>,
  467    selection_history: SelectionHistory,
  468    autoclose_regions: Vec<AutocloseRegion>,
  469    snippet_stack: InvalidationStack<SnippetState>,
  470    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  471    ime_transaction: Option<TransactionId>,
  472    active_diagnostics: Option<ActiveDiagnosticGroup>,
  473    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  474    project: Option<Model<Project>>,
  475    completion_provider: Option<Box<dyn CompletionProvider>>,
  476    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  477    blink_manager: Model<BlinkManager>,
  478    show_cursor_names: bool,
  479    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  480    pub show_local_selections: bool,
  481    mode: EditorMode,
  482    show_breadcrumbs: bool,
  483    show_gutter: bool,
  484    show_line_numbers: Option<bool>,
  485    show_git_diff_gutter: Option<bool>,
  486    show_code_actions: Option<bool>,
  487    show_runnables: Option<bool>,
  488    show_wrap_guides: Option<bool>,
  489    show_indent_guides: Option<bool>,
  490    placeholder_text: Option<Arc<str>>,
  491    highlight_order: usize,
  492    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  493    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  494    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  495    scrollbar_marker_state: ScrollbarMarkerState,
  496    active_indent_guides_state: ActiveIndentGuidesState,
  497    nav_history: Option<ItemNavHistory>,
  498    context_menu: RwLock<Option<ContextMenu>>,
  499    mouse_context_menu: Option<MouseContextMenu>,
  500    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  501    find_all_references_task_sources: Vec<Anchor>,
  502    next_completion_id: CompletionId,
  503    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  504    available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
  505    code_actions_task: Option<Task<()>>,
  506    document_highlights_task: Option<Task<()>>,
  507    linked_editing_range_task: Option<Task<Option<()>>>,
  508    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  509    pending_rename: Option<RenameState>,
  510    searchable: bool,
  511    cursor_shape: CursorShape,
  512    current_line_highlight: Option<CurrentLineHighlight>,
  513    collapse_matches: bool,
  514    autoindent_mode: Option<AutoindentMode>,
  515    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  516    keymap_context_layers: BTreeMap<TypeId, KeyContext>,
  517    input_enabled: bool,
  518    use_modal_editing: bool,
  519    read_only: bool,
  520    leader_peer_id: Option<PeerId>,
  521    remote_id: Option<ViewId>,
  522    hover_state: HoverState,
  523    gutter_hovered: bool,
  524    hovered_link_state: Option<HoveredLinkState>,
  525    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  526    active_inline_completion: Option<Inlay>,
  527    show_inline_completions: bool,
  528    inlay_hint_cache: InlayHintCache,
  529    expanded_hunks: ExpandedHunks,
  530    next_inlay_id: usize,
  531    _subscriptions: Vec<Subscription>,
  532    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  533    gutter_dimensions: GutterDimensions,
  534    pub vim_replace_map: HashMap<Range<usize>, String>,
  535    style: Option<EditorStyle>,
  536    next_editor_action_id: EditorActionId,
  537    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  538    use_autoclose: bool,
  539    use_auto_surround: bool,
  540    auto_replace_emoji_shortcode: bool,
  541    show_git_blame_gutter: bool,
  542    show_git_blame_inline: bool,
  543    show_git_blame_inline_delay_task: Option<Task<()>>,
  544    git_blame_inline_enabled: bool,
  545    show_selection_menu: Option<bool>,
  546    blame: Option<Model<GitBlame>>,
  547    blame_subscription: Option<Subscription>,
  548    custom_context_menu: Option<
  549        Box<
  550            dyn 'static
  551                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  552        >,
  553    >,
  554    last_bounds: Option<Bounds<Pixels>>,
  555    expect_bounds_change: Option<Bounds<Pixels>>,
  556    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  557    tasks_update_task: Option<Task<()>>,
  558    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  559    file_header_size: u8,
  560    breadcrumb_header: Option<String>,
  561}
  562
  563#[derive(Clone)]
  564pub struct EditorSnapshot {
  565    pub mode: EditorMode,
  566    show_gutter: bool,
  567    show_line_numbers: Option<bool>,
  568    show_git_diff_gutter: Option<bool>,
  569    show_code_actions: Option<bool>,
  570    show_runnables: Option<bool>,
  571    render_git_blame_gutter: bool,
  572    pub display_snapshot: DisplaySnapshot,
  573    pub placeholder_text: Option<Arc<str>>,
  574    is_focused: bool,
  575    scroll_anchor: ScrollAnchor,
  576    ongoing_scroll: OngoingScroll,
  577    current_line_highlight: CurrentLineHighlight,
  578    gutter_hovered: bool,
  579}
  580
  581const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
  582
  583#[derive(Debug, Clone, Copy)]
  584pub struct GutterDimensions {
  585    pub left_padding: Pixels,
  586    pub right_padding: Pixels,
  587    pub width: Pixels,
  588    pub margin: Pixels,
  589    pub git_blame_entries_width: Option<Pixels>,
  590}
  591
  592impl GutterDimensions {
  593    /// The full width of the space taken up by the gutter.
  594    pub fn full_width(&self) -> Pixels {
  595        self.margin + self.width
  596    }
  597
  598    /// The width of the space reserved for the fold indicators,
  599    /// use alongside 'justify_end' and `gutter_width` to
  600    /// right align content with the line numbers
  601    pub fn fold_area_width(&self) -> Pixels {
  602        self.margin + self.right_padding
  603    }
  604}
  605
  606impl Default for GutterDimensions {
  607    fn default() -> Self {
  608        Self {
  609            left_padding: Pixels::ZERO,
  610            right_padding: Pixels::ZERO,
  611            width: Pixels::ZERO,
  612            margin: Pixels::ZERO,
  613            git_blame_entries_width: None,
  614        }
  615    }
  616}
  617
  618#[derive(Debug)]
  619pub struct RemoteSelection {
  620    pub replica_id: ReplicaId,
  621    pub selection: Selection<Anchor>,
  622    pub cursor_shape: CursorShape,
  623    pub peer_id: PeerId,
  624    pub line_mode: bool,
  625    pub participant_index: Option<ParticipantIndex>,
  626    pub user_name: Option<SharedString>,
  627}
  628
  629#[derive(Clone, Debug)]
  630struct SelectionHistoryEntry {
  631    selections: Arc<[Selection<Anchor>]>,
  632    select_next_state: Option<SelectNextState>,
  633    select_prev_state: Option<SelectNextState>,
  634    add_selections_state: Option<AddSelectionsState>,
  635}
  636
  637enum SelectionHistoryMode {
  638    Normal,
  639    Undoing,
  640    Redoing,
  641}
  642
  643#[derive(Clone, PartialEq, Eq, Hash)]
  644struct HoveredCursor {
  645    replica_id: u16,
  646    selection_id: usize,
  647}
  648
  649impl Default for SelectionHistoryMode {
  650    fn default() -> Self {
  651        Self::Normal
  652    }
  653}
  654
  655#[derive(Default)]
  656struct SelectionHistory {
  657    #[allow(clippy::type_complexity)]
  658    selections_by_transaction:
  659        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  660    mode: SelectionHistoryMode,
  661    undo_stack: VecDeque<SelectionHistoryEntry>,
  662    redo_stack: VecDeque<SelectionHistoryEntry>,
  663}
  664
  665impl SelectionHistory {
  666    fn insert_transaction(
  667        &mut self,
  668        transaction_id: TransactionId,
  669        selections: Arc<[Selection<Anchor>]>,
  670    ) {
  671        self.selections_by_transaction
  672            .insert(transaction_id, (selections, None));
  673    }
  674
  675    #[allow(clippy::type_complexity)]
  676    fn transaction(
  677        &self,
  678        transaction_id: TransactionId,
  679    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  680        self.selections_by_transaction.get(&transaction_id)
  681    }
  682
  683    #[allow(clippy::type_complexity)]
  684    fn transaction_mut(
  685        &mut self,
  686        transaction_id: TransactionId,
  687    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  688        self.selections_by_transaction.get_mut(&transaction_id)
  689    }
  690
  691    fn push(&mut self, entry: SelectionHistoryEntry) {
  692        if !entry.selections.is_empty() {
  693            match self.mode {
  694                SelectionHistoryMode::Normal => {
  695                    self.push_undo(entry);
  696                    self.redo_stack.clear();
  697                }
  698                SelectionHistoryMode::Undoing => self.push_redo(entry),
  699                SelectionHistoryMode::Redoing => self.push_undo(entry),
  700            }
  701        }
  702    }
  703
  704    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  705        if self
  706            .undo_stack
  707            .back()
  708            .map_or(true, |e| e.selections != entry.selections)
  709        {
  710            self.undo_stack.push_back(entry);
  711            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  712                self.undo_stack.pop_front();
  713            }
  714        }
  715    }
  716
  717    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  718        if self
  719            .redo_stack
  720            .back()
  721            .map_or(true, |e| e.selections != entry.selections)
  722        {
  723            self.redo_stack.push_back(entry);
  724            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  725                self.redo_stack.pop_front();
  726            }
  727        }
  728    }
  729}
  730
  731struct RowHighlight {
  732    index: usize,
  733    range: RangeInclusive<Anchor>,
  734    color: Option<Hsla>,
  735    should_autoscroll: bool,
  736}
  737
  738#[derive(Clone, Debug)]
  739struct AddSelectionsState {
  740    above: bool,
  741    stack: Vec<usize>,
  742}
  743
  744#[derive(Clone)]
  745struct SelectNextState {
  746    query: AhoCorasick,
  747    wordwise: bool,
  748    done: bool,
  749}
  750
  751impl std::fmt::Debug for SelectNextState {
  752    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  753        f.debug_struct(std::any::type_name::<Self>())
  754            .field("wordwise", &self.wordwise)
  755            .field("done", &self.done)
  756            .finish()
  757    }
  758}
  759
  760#[derive(Debug)]
  761struct AutocloseRegion {
  762    selection_id: usize,
  763    range: Range<Anchor>,
  764    pair: BracketPair,
  765}
  766
  767#[derive(Debug)]
  768struct SnippetState {
  769    ranges: Vec<Vec<Range<Anchor>>>,
  770    active_index: usize,
  771}
  772
  773#[doc(hidden)]
  774pub struct RenameState {
  775    pub range: Range<Anchor>,
  776    pub old_name: Arc<str>,
  777    pub editor: View<Editor>,
  778    block_id: BlockId,
  779}
  780
  781struct InvalidationStack<T>(Vec<T>);
  782
  783struct RegisteredInlineCompletionProvider {
  784    provider: Arc<dyn InlineCompletionProviderHandle>,
  785    _subscription: Subscription,
  786}
  787
  788enum ContextMenu {
  789    Completions(CompletionsMenu),
  790    CodeActions(CodeActionsMenu),
  791}
  792
  793impl ContextMenu {
  794    fn select_first(
  795        &mut self,
  796        project: Option<&Model<Project>>,
  797        cx: &mut ViewContext<Editor>,
  798    ) -> bool {
  799        if self.visible() {
  800            match self {
  801                ContextMenu::Completions(menu) => menu.select_first(project, cx),
  802                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  803            }
  804            true
  805        } else {
  806            false
  807        }
  808    }
  809
  810    fn select_prev(
  811        &mut self,
  812        project: Option<&Model<Project>>,
  813        cx: &mut ViewContext<Editor>,
  814    ) -> bool {
  815        if self.visible() {
  816            match self {
  817                ContextMenu::Completions(menu) => menu.select_prev(project, cx),
  818                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  819            }
  820            true
  821        } else {
  822            false
  823        }
  824    }
  825
  826    fn select_next(
  827        &mut self,
  828        project: Option<&Model<Project>>,
  829        cx: &mut ViewContext<Editor>,
  830    ) -> bool {
  831        if self.visible() {
  832            match self {
  833                ContextMenu::Completions(menu) => menu.select_next(project, cx),
  834                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  835            }
  836            true
  837        } else {
  838            false
  839        }
  840    }
  841
  842    fn select_last(
  843        &mut self,
  844        project: Option<&Model<Project>>,
  845        cx: &mut ViewContext<Editor>,
  846    ) -> bool {
  847        if self.visible() {
  848            match self {
  849                ContextMenu::Completions(menu) => menu.select_last(project, cx),
  850                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  851            }
  852            true
  853        } else {
  854            false
  855        }
  856    }
  857
  858    fn visible(&self) -> bool {
  859        match self {
  860            ContextMenu::Completions(menu) => menu.visible(),
  861            ContextMenu::CodeActions(menu) => menu.visible(),
  862        }
  863    }
  864
  865    fn render(
  866        &self,
  867        cursor_position: DisplayPoint,
  868        style: &EditorStyle,
  869        max_height: Pixels,
  870        workspace: Option<WeakView<Workspace>>,
  871        cx: &mut ViewContext<Editor>,
  872    ) -> (ContextMenuOrigin, AnyElement) {
  873        match self {
  874            ContextMenu::Completions(menu) => (
  875                ContextMenuOrigin::EditorPoint(cursor_position),
  876                menu.render(style, max_height, workspace, cx),
  877            ),
  878            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  879        }
  880    }
  881}
  882
  883enum ContextMenuOrigin {
  884    EditorPoint(DisplayPoint),
  885    GutterIndicator(DisplayRow),
  886}
  887
  888#[derive(Clone)]
  889struct CompletionsMenu {
  890    id: CompletionId,
  891    initial_position: Anchor,
  892    buffer: Model<Buffer>,
  893    completions: Arc<RwLock<Box<[Completion]>>>,
  894    match_candidates: Arc<[StringMatchCandidate]>,
  895    matches: Arc<[StringMatch]>,
  896    selected_item: usize,
  897    scroll_handle: UniformListScrollHandle,
  898    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  899}
  900
  901impl CompletionsMenu {
  902    fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  903        self.selected_item = 0;
  904        self.scroll_handle.scroll_to_item(self.selected_item);
  905        self.attempt_resolve_selected_completion_documentation(project, cx);
  906        cx.notify();
  907    }
  908
  909    fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  910        if self.selected_item > 0 {
  911            self.selected_item -= 1;
  912        } else {
  913            self.selected_item = self.matches.len() - 1;
  914        }
  915        self.scroll_handle.scroll_to_item(self.selected_item);
  916        self.attempt_resolve_selected_completion_documentation(project, cx);
  917        cx.notify();
  918    }
  919
  920    fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  921        if self.selected_item + 1 < self.matches.len() {
  922            self.selected_item += 1;
  923        } else {
  924            self.selected_item = 0;
  925        }
  926        self.scroll_handle.scroll_to_item(self.selected_item);
  927        self.attempt_resolve_selected_completion_documentation(project, cx);
  928        cx.notify();
  929    }
  930
  931    fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  932        self.selected_item = self.matches.len() - 1;
  933        self.scroll_handle.scroll_to_item(self.selected_item);
  934        self.attempt_resolve_selected_completion_documentation(project, cx);
  935        cx.notify();
  936    }
  937
  938    fn pre_resolve_completion_documentation(
  939        buffer: Model<Buffer>,
  940        completions: Arc<RwLock<Box<[Completion]>>>,
  941        matches: Arc<[StringMatch]>,
  942        editor: &Editor,
  943        cx: &mut ViewContext<Editor>,
  944    ) -> Task<()> {
  945        let settings = EditorSettings::get_global(cx);
  946        if !settings.show_completion_documentation {
  947            return Task::ready(());
  948        }
  949
  950        let Some(provider) = editor.completion_provider.as_ref() else {
  951            return Task::ready(());
  952        };
  953
  954        let resolve_task = provider.resolve_completions(
  955            buffer,
  956            matches.iter().map(|m| m.candidate_id).collect(),
  957            completions.clone(),
  958            cx,
  959        );
  960
  961        return cx.spawn(move |this, mut cx| async move {
  962            if let Some(true) = resolve_task.await.log_err() {
  963                this.update(&mut cx, |_, cx| cx.notify()).ok();
  964            }
  965        });
  966    }
  967
  968    fn attempt_resolve_selected_completion_documentation(
  969        &mut self,
  970        project: Option<&Model<Project>>,
  971        cx: &mut ViewContext<Editor>,
  972    ) {
  973        let settings = EditorSettings::get_global(cx);
  974        if !settings.show_completion_documentation {
  975            return;
  976        }
  977
  978        let completion_index = self.matches[self.selected_item].candidate_id;
  979        let Some(project) = project else {
  980            return;
  981        };
  982
  983        let resolve_task = project.update(cx, |project, cx| {
  984            project.resolve_completions(
  985                self.buffer.clone(),
  986                vec![completion_index],
  987                self.completions.clone(),
  988                cx,
  989            )
  990        });
  991
  992        let delay_ms =
  993            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
  994        let delay = Duration::from_millis(delay_ms);
  995
  996        self.selected_completion_documentation_resolve_debounce
  997            .lock()
  998            .fire_new(delay, cx, |_, cx| {
  999                cx.spawn(move |this, mut cx| async move {
 1000                    if let Some(true) = resolve_task.await.log_err() {
 1001                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1002                    }
 1003                })
 1004            });
 1005    }
 1006
 1007    fn visible(&self) -> bool {
 1008        !self.matches.is_empty()
 1009    }
 1010
 1011    fn render(
 1012        &self,
 1013        style: &EditorStyle,
 1014        max_height: Pixels,
 1015        workspace: Option<WeakView<Workspace>>,
 1016        cx: &mut ViewContext<Editor>,
 1017    ) -> AnyElement {
 1018        let settings = EditorSettings::get_global(cx);
 1019        let show_completion_documentation = settings.show_completion_documentation;
 1020
 1021        let widest_completion_ix = self
 1022            .matches
 1023            .iter()
 1024            .enumerate()
 1025            .max_by_key(|(_, mat)| {
 1026                let completions = self.completions.read();
 1027                let completion = &completions[mat.candidate_id];
 1028                let documentation = &completion.documentation;
 1029
 1030                let mut len = completion.label.text.chars().count();
 1031                if let Some(Documentation::SingleLine(text)) = documentation {
 1032                    if show_completion_documentation {
 1033                        len += text.chars().count();
 1034                    }
 1035                }
 1036
 1037                len
 1038            })
 1039            .map(|(ix, _)| ix);
 1040
 1041        let completions = self.completions.clone();
 1042        let matches = self.matches.clone();
 1043        let selected_item = self.selected_item;
 1044        let style = style.clone();
 1045
 1046        let multiline_docs = if show_completion_documentation {
 1047            let mat = &self.matches[selected_item];
 1048            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1049                Some(Documentation::MultiLinePlainText(text)) => {
 1050                    Some(div().child(SharedString::from(text.clone())))
 1051                }
 1052                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1053                    Some(div().child(render_parsed_markdown(
 1054                        "completions_markdown",
 1055                        parsed,
 1056                        &style,
 1057                        workspace,
 1058                        cx,
 1059                    )))
 1060                }
 1061                _ => None,
 1062            };
 1063            multiline_docs.map(|div| {
 1064                div.id("multiline_docs")
 1065                    .max_h(max_height)
 1066                    .flex_1()
 1067                    .px_1p5()
 1068                    .py_1()
 1069                    .min_w(px(260.))
 1070                    .max_w(px(640.))
 1071                    .w(px(500.))
 1072                    .overflow_y_scroll()
 1073                    .occlude()
 1074            })
 1075        } else {
 1076            None
 1077        };
 1078
 1079        let list = uniform_list(
 1080            cx.view().clone(),
 1081            "completions",
 1082            matches.len(),
 1083            move |_editor, range, cx| {
 1084                let start_ix = range.start;
 1085                let completions_guard = completions.read();
 1086
 1087                matches[range]
 1088                    .iter()
 1089                    .enumerate()
 1090                    .map(|(ix, mat)| {
 1091                        let item_ix = start_ix + ix;
 1092                        let candidate_id = mat.candidate_id;
 1093                        let completion = &completions_guard[candidate_id];
 1094
 1095                        let documentation = if show_completion_documentation {
 1096                            &completion.documentation
 1097                        } else {
 1098                            &None
 1099                        };
 1100
 1101                        let highlights = gpui::combine_highlights(
 1102                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1103                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1104                                |(range, mut highlight)| {
 1105                                    // Ignore font weight for syntax highlighting, as we'll use it
 1106                                    // for fuzzy matches.
 1107                                    highlight.font_weight = None;
 1108
 1109                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1110                                        highlight.strikethrough = Some(StrikethroughStyle {
 1111                                            thickness: 1.0.into(),
 1112                                            ..Default::default()
 1113                                        });
 1114                                        highlight.color = Some(cx.theme().colors().text_muted);
 1115                                    }
 1116
 1117                                    (range, highlight)
 1118                                },
 1119                            ),
 1120                        );
 1121                        let completion_label = StyledText::new(completion.label.text.clone())
 1122                            .with_highlights(&style.text, highlights);
 1123                        let documentation_label =
 1124                            if let Some(Documentation::SingleLine(text)) = documentation {
 1125                                if text.trim().is_empty() {
 1126                                    None
 1127                                } else {
 1128                                    Some(
 1129                                        h_flex().ml_4().child(
 1130                                            Label::new(text.clone())
 1131                                                .size(LabelSize::Small)
 1132                                                .color(Color::Muted),
 1133                                        ),
 1134                                    )
 1135                                }
 1136                            } else {
 1137                                None
 1138                            };
 1139
 1140                        div().min_w(px(220.)).max_w(px(540.)).child(
 1141                            ListItem::new(mat.candidate_id)
 1142                                .inset(true)
 1143                                .selected(item_ix == selected_item)
 1144                                .on_click(cx.listener(move |editor, _event, cx| {
 1145                                    cx.stop_propagation();
 1146                                    if let Some(task) = editor.confirm_completion(
 1147                                        &ConfirmCompletion {
 1148                                            item_ix: Some(item_ix),
 1149                                        },
 1150                                        cx,
 1151                                    ) {
 1152                                        task.detach_and_log_err(cx)
 1153                                    }
 1154                                }))
 1155                                .child(h_flex().overflow_hidden().child(completion_label))
 1156                                .end_slot::<Div>(documentation_label),
 1157                        )
 1158                    })
 1159                    .collect()
 1160            },
 1161        )
 1162        .occlude()
 1163        .max_h(max_height)
 1164        .track_scroll(self.scroll_handle.clone())
 1165        .with_width_from_item(widest_completion_ix)
 1166        .with_sizing_behavior(ListSizingBehavior::Infer);
 1167
 1168        Popover::new()
 1169            .child(list)
 1170            .when_some(multiline_docs, |popover, multiline_docs| {
 1171                popover.aside(multiline_docs)
 1172            })
 1173            .into_any_element()
 1174    }
 1175
 1176    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1177        let mut matches = if let Some(query) = query {
 1178            fuzzy::match_strings(
 1179                &self.match_candidates,
 1180                query,
 1181                query.chars().any(|c| c.is_uppercase()),
 1182                100,
 1183                &Default::default(),
 1184                executor,
 1185            )
 1186            .await
 1187        } else {
 1188            self.match_candidates
 1189                .iter()
 1190                .enumerate()
 1191                .map(|(candidate_id, candidate)| StringMatch {
 1192                    candidate_id,
 1193                    score: Default::default(),
 1194                    positions: Default::default(),
 1195                    string: candidate.string.clone(),
 1196                })
 1197                .collect()
 1198        };
 1199
 1200        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1201        if let Some(query) = query {
 1202            if let Some(query_start) = query.chars().next() {
 1203                matches.retain(|string_match| {
 1204                    split_words(&string_match.string).any(|word| {
 1205                        // Check that the first codepoint of the word as lowercase matches the first
 1206                        // codepoint of the query as lowercase
 1207                        word.chars()
 1208                            .flat_map(|codepoint| codepoint.to_lowercase())
 1209                            .zip(query_start.to_lowercase())
 1210                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1211                    })
 1212                });
 1213            }
 1214        }
 1215
 1216        let completions = self.completions.read();
 1217        matches.sort_unstable_by_key(|mat| {
 1218            // We do want to strike a balance here between what the language server tells us
 1219            // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1220            // `Creat` and there is a local variable called `CreateComponent`).
 1221            // So what we do is: we bucket all matches into two buckets
 1222            // - Strong matches
 1223            // - Weak matches
 1224            // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1225            // and the Weak matches are the rest.
 1226            //
 1227            // For the strong matches, we sort by the language-servers score first and for the weak
 1228            // matches, we prefer our fuzzy finder first.
 1229            //
 1230            // The thinking behind that: it's useless to take the sort_text the language-server gives
 1231            // us into account when it's obviously a bad match.
 1232
 1233            #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1234            enum MatchScore<'a> {
 1235                Strong {
 1236                    sort_text: Option<&'a str>,
 1237                    score: Reverse<OrderedFloat<f64>>,
 1238                    sort_key: (usize, &'a str),
 1239                },
 1240                Weak {
 1241                    score: Reverse<OrderedFloat<f64>>,
 1242                    sort_text: Option<&'a str>,
 1243                    sort_key: (usize, &'a str),
 1244                },
 1245            }
 1246
 1247            let completion = &completions[mat.candidate_id];
 1248            let sort_key = completion.sort_key();
 1249            let sort_text = completion.lsp_completion.sort_text.as_deref();
 1250            let score = Reverse(OrderedFloat(mat.score));
 1251
 1252            if mat.score >= 0.2 {
 1253                MatchScore::Strong {
 1254                    sort_text,
 1255                    score,
 1256                    sort_key,
 1257                }
 1258            } else {
 1259                MatchScore::Weak {
 1260                    score,
 1261                    sort_text,
 1262                    sort_key,
 1263                }
 1264            }
 1265        });
 1266
 1267        for mat in &mut matches {
 1268            let completion = &completions[mat.candidate_id];
 1269            mat.string.clone_from(&completion.label.text);
 1270            for position in &mut mat.positions {
 1271                *position += completion.label.filter_range.start;
 1272            }
 1273        }
 1274        drop(completions);
 1275
 1276        self.matches = matches.into();
 1277        self.selected_item = 0;
 1278    }
 1279}
 1280
 1281#[derive(Clone)]
 1282struct CodeActionContents {
 1283    tasks: Option<Arc<ResolvedTasks>>,
 1284    actions: Option<Arc<[CodeAction]>>,
 1285}
 1286
 1287impl CodeActionContents {
 1288    fn len(&self) -> usize {
 1289        match (&self.tasks, &self.actions) {
 1290            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1291            (Some(tasks), None) => tasks.templates.len(),
 1292            (None, Some(actions)) => actions.len(),
 1293            (None, None) => 0,
 1294        }
 1295    }
 1296
 1297    fn is_empty(&self) -> bool {
 1298        match (&self.tasks, &self.actions) {
 1299            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1300            (Some(tasks), None) => tasks.templates.is_empty(),
 1301            (None, Some(actions)) => actions.is_empty(),
 1302            (None, None) => true,
 1303        }
 1304    }
 1305
 1306    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1307        self.tasks
 1308            .iter()
 1309            .flat_map(|tasks| {
 1310                tasks
 1311                    .templates
 1312                    .iter()
 1313                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1314            })
 1315            .chain(self.actions.iter().flat_map(|actions| {
 1316                actions
 1317                    .iter()
 1318                    .map(|action| CodeActionsItem::CodeAction(action.clone()))
 1319            }))
 1320    }
 1321    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1322        match (&self.tasks, &self.actions) {
 1323            (Some(tasks), Some(actions)) => {
 1324                if index < tasks.templates.len() {
 1325                    tasks
 1326                        .templates
 1327                        .get(index)
 1328                        .cloned()
 1329                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1330                } else {
 1331                    actions
 1332                        .get(index - tasks.templates.len())
 1333                        .cloned()
 1334                        .map(CodeActionsItem::CodeAction)
 1335                }
 1336            }
 1337            (Some(tasks), None) => tasks
 1338                .templates
 1339                .get(index)
 1340                .cloned()
 1341                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1342            (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
 1343            (None, None) => None,
 1344        }
 1345    }
 1346}
 1347
 1348#[allow(clippy::large_enum_variant)]
 1349#[derive(Clone)]
 1350enum CodeActionsItem {
 1351    Task(TaskSourceKind, ResolvedTask),
 1352    CodeAction(CodeAction),
 1353}
 1354
 1355impl CodeActionsItem {
 1356    fn as_task(&self) -> Option<&ResolvedTask> {
 1357        let Self::Task(_, task) = self else {
 1358            return None;
 1359        };
 1360        Some(task)
 1361    }
 1362    fn as_code_action(&self) -> Option<&CodeAction> {
 1363        let Self::CodeAction(action) = self else {
 1364            return None;
 1365        };
 1366        Some(action)
 1367    }
 1368    fn label(&self) -> String {
 1369        match self {
 1370            Self::CodeAction(action) => action.lsp_action.title.clone(),
 1371            Self::Task(_, task) => task.resolved_label.clone(),
 1372        }
 1373    }
 1374}
 1375
 1376struct CodeActionsMenu {
 1377    actions: CodeActionContents,
 1378    buffer: Model<Buffer>,
 1379    selected_item: usize,
 1380    scroll_handle: UniformListScrollHandle,
 1381    deployed_from_indicator: Option<DisplayRow>,
 1382}
 1383
 1384impl CodeActionsMenu {
 1385    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1386        self.selected_item = 0;
 1387        self.scroll_handle.scroll_to_item(self.selected_item);
 1388        cx.notify()
 1389    }
 1390
 1391    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1392        if self.selected_item > 0 {
 1393            self.selected_item -= 1;
 1394        } else {
 1395            self.selected_item = self.actions.len() - 1;
 1396        }
 1397        self.scroll_handle.scroll_to_item(self.selected_item);
 1398        cx.notify();
 1399    }
 1400
 1401    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1402        if self.selected_item + 1 < self.actions.len() {
 1403            self.selected_item += 1;
 1404        } else {
 1405            self.selected_item = 0;
 1406        }
 1407        self.scroll_handle.scroll_to_item(self.selected_item);
 1408        cx.notify();
 1409    }
 1410
 1411    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1412        self.selected_item = self.actions.len() - 1;
 1413        self.scroll_handle.scroll_to_item(self.selected_item);
 1414        cx.notify()
 1415    }
 1416
 1417    fn visible(&self) -> bool {
 1418        !self.actions.is_empty()
 1419    }
 1420
 1421    fn render(
 1422        &self,
 1423        cursor_position: DisplayPoint,
 1424        _style: &EditorStyle,
 1425        max_height: Pixels,
 1426        cx: &mut ViewContext<Editor>,
 1427    ) -> (ContextMenuOrigin, AnyElement) {
 1428        let actions = self.actions.clone();
 1429        let selected_item = self.selected_item;
 1430        let element = uniform_list(
 1431            cx.view().clone(),
 1432            "code_actions_menu",
 1433            self.actions.len(),
 1434            move |_this, range, cx| {
 1435                actions
 1436                    .iter()
 1437                    .skip(range.start)
 1438                    .take(range.end - range.start)
 1439                    .enumerate()
 1440                    .map(|(ix, action)| {
 1441                        let item_ix = range.start + ix;
 1442                        let selected = selected_item == item_ix;
 1443                        let colors = cx.theme().colors();
 1444                        div()
 1445                            .px_2()
 1446                            .text_color(colors.text)
 1447                            .when(selected, |style| {
 1448                                style
 1449                                    .bg(colors.element_active)
 1450                                    .text_color(colors.text_accent)
 1451                            })
 1452                            .hover(|style| {
 1453                                style
 1454                                    .bg(colors.element_hover)
 1455                                    .text_color(colors.text_accent)
 1456                            })
 1457                            .whitespace_nowrap()
 1458                            .when_some(action.as_code_action(), |this, action| {
 1459                                this.on_mouse_down(
 1460                                    MouseButton::Left,
 1461                                    cx.listener(move |editor, _, cx| {
 1462                                        cx.stop_propagation();
 1463                                        if let Some(task) = editor.confirm_code_action(
 1464                                            &ConfirmCodeAction {
 1465                                                item_ix: Some(item_ix),
 1466                                            },
 1467                                            cx,
 1468                                        ) {
 1469                                            task.detach_and_log_err(cx)
 1470                                        }
 1471                                    }),
 1472                                )
 1473                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1474                                .child(SharedString::from(action.lsp_action.title.clone()))
 1475                            })
 1476                            .when_some(action.as_task(), |this, task| {
 1477                                this.on_mouse_down(
 1478                                    MouseButton::Left,
 1479                                    cx.listener(move |editor, _, cx| {
 1480                                        cx.stop_propagation();
 1481                                        if let Some(task) = editor.confirm_code_action(
 1482                                            &ConfirmCodeAction {
 1483                                                item_ix: Some(item_ix),
 1484                                            },
 1485                                            cx,
 1486                                        ) {
 1487                                            task.detach_and_log_err(cx)
 1488                                        }
 1489                                    }),
 1490                                )
 1491                                .child(SharedString::from(task.resolved_label.clone()))
 1492                            })
 1493                    })
 1494                    .collect()
 1495            },
 1496        )
 1497        .elevation_1(cx)
 1498        .px_2()
 1499        .py_1()
 1500        .max_h(max_height)
 1501        .occlude()
 1502        .track_scroll(self.scroll_handle.clone())
 1503        .with_width_from_item(
 1504            self.actions
 1505                .iter()
 1506                .enumerate()
 1507                .max_by_key(|(_, action)| match action {
 1508                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1509                    CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
 1510                })
 1511                .map(|(ix, _)| ix),
 1512        )
 1513        .with_sizing_behavior(ListSizingBehavior::Infer)
 1514        .into_any_element();
 1515
 1516        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1517            ContextMenuOrigin::GutterIndicator(row)
 1518        } else {
 1519            ContextMenuOrigin::EditorPoint(cursor_position)
 1520        };
 1521
 1522        (cursor_position, element)
 1523    }
 1524}
 1525
 1526#[derive(Debug)]
 1527struct ActiveDiagnosticGroup {
 1528    primary_range: Range<Anchor>,
 1529    primary_message: String,
 1530    group_id: usize,
 1531    blocks: HashMap<BlockId, Diagnostic>,
 1532    is_valid: bool,
 1533}
 1534
 1535#[derive(Serialize, Deserialize, Clone, Debug)]
 1536pub struct ClipboardSelection {
 1537    pub len: usize,
 1538    pub is_entire_line: bool,
 1539    pub first_line_indent: u32,
 1540}
 1541
 1542#[derive(Debug)]
 1543pub(crate) struct NavigationData {
 1544    cursor_anchor: Anchor,
 1545    cursor_position: Point,
 1546    scroll_anchor: ScrollAnchor,
 1547    scroll_top_row: u32,
 1548}
 1549
 1550enum GotoDefinitionKind {
 1551    Symbol,
 1552    Type,
 1553    Implementation,
 1554}
 1555
 1556#[derive(Debug, Clone)]
 1557enum InlayHintRefreshReason {
 1558    Toggle(bool),
 1559    SettingsChange(InlayHintSettings),
 1560    NewLinesShown,
 1561    BufferEdited(HashSet<Arc<Language>>),
 1562    RefreshRequested,
 1563    ExcerptsRemoved(Vec<ExcerptId>),
 1564}
 1565
 1566impl InlayHintRefreshReason {
 1567    fn description(&self) -> &'static str {
 1568        match self {
 1569            Self::Toggle(_) => "toggle",
 1570            Self::SettingsChange(_) => "settings change",
 1571            Self::NewLinesShown => "new lines shown",
 1572            Self::BufferEdited(_) => "buffer edited",
 1573            Self::RefreshRequested => "refresh requested",
 1574            Self::ExcerptsRemoved(_) => "excerpts removed",
 1575        }
 1576    }
 1577}
 1578
 1579impl Editor {
 1580    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1581        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1582        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1583        Self::new(
 1584            EditorMode::SingleLine { auto_width: false },
 1585            buffer,
 1586            None,
 1587            false,
 1588            cx,
 1589        )
 1590    }
 1591
 1592    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1593        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1594        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1595        Self::new(EditorMode::Full, buffer, None, false, cx)
 1596    }
 1597
 1598    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1599        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1600        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1601        Self::new(
 1602            EditorMode::SingleLine { auto_width: true },
 1603            buffer,
 1604            None,
 1605            false,
 1606            cx,
 1607        )
 1608    }
 1609
 1610    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1611        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1612        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1613        Self::new(
 1614            EditorMode::AutoHeight { max_lines },
 1615            buffer,
 1616            None,
 1617            false,
 1618            cx,
 1619        )
 1620    }
 1621
 1622    pub fn for_buffer(
 1623        buffer: Model<Buffer>,
 1624        project: Option<Model<Project>>,
 1625        cx: &mut ViewContext<Self>,
 1626    ) -> Self {
 1627        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1628        Self::new(EditorMode::Full, buffer, project, false, cx)
 1629    }
 1630
 1631    pub fn for_multibuffer(
 1632        buffer: Model<MultiBuffer>,
 1633        project: Option<Model<Project>>,
 1634        show_excerpt_controls: bool,
 1635        cx: &mut ViewContext<Self>,
 1636    ) -> Self {
 1637        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1638    }
 1639
 1640    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1641        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1642        let mut clone = Self::new(
 1643            self.mode,
 1644            self.buffer.clone(),
 1645            self.project.clone(),
 1646            show_excerpt_controls,
 1647            cx,
 1648        );
 1649        self.display_map.update(cx, |display_map, cx| {
 1650            let snapshot = display_map.snapshot(cx);
 1651            clone.display_map.update(cx, |display_map, cx| {
 1652                display_map.set_state(&snapshot, cx);
 1653            });
 1654        });
 1655        clone.selections.clone_state(&self.selections);
 1656        clone.scroll_manager.clone_state(&self.scroll_manager);
 1657        clone.searchable = self.searchable;
 1658        clone
 1659    }
 1660
 1661    pub fn new(
 1662        mode: EditorMode,
 1663        buffer: Model<MultiBuffer>,
 1664        project: Option<Model<Project>>,
 1665        show_excerpt_controls: bool,
 1666        cx: &mut ViewContext<Self>,
 1667    ) -> Self {
 1668        let style = cx.text_style();
 1669        let font_size = style.font_size.to_pixels(cx.rem_size());
 1670        let editor = cx.view().downgrade();
 1671        let fold_placeholder = FoldPlaceholder {
 1672            constrain_width: true,
 1673            render: Arc::new(move |fold_id, fold_range, cx| {
 1674                let editor = editor.clone();
 1675                div()
 1676                    .id(fold_id)
 1677                    .bg(cx.theme().colors().ghost_element_background)
 1678                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1679                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1680                    .rounded_sm()
 1681                    .size_full()
 1682                    .cursor_pointer()
 1683                    .child("")
 1684                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1685                    .on_click(move |_, cx| {
 1686                        editor
 1687                            .update(cx, |editor, cx| {
 1688                                editor.unfold_ranges(
 1689                                    [fold_range.start..fold_range.end],
 1690                                    true,
 1691                                    false,
 1692                                    cx,
 1693                                );
 1694                                cx.stop_propagation();
 1695                            })
 1696                            .ok();
 1697                    })
 1698                    .into_any()
 1699            }),
 1700            merge_adjacent: true,
 1701        };
 1702        let file_header_size = if show_excerpt_controls { 3 } else { 2 };
 1703        let display_map = cx.new_model(|cx| {
 1704            DisplayMap::new(
 1705                buffer.clone(),
 1706                style.font(),
 1707                font_size,
 1708                None,
 1709                show_excerpt_controls,
 1710                file_header_size,
 1711                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1712                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1713                fold_placeholder,
 1714                cx,
 1715            )
 1716        });
 1717
 1718        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1719
 1720        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1721
 1722        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1723            .then(|| language_settings::SoftWrap::PreferLine);
 1724
 1725        let mut project_subscriptions = Vec::new();
 1726        if mode == EditorMode::Full {
 1727            if let Some(project) = project.as_ref() {
 1728                if buffer.read(cx).is_singleton() {
 1729                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1730                        cx.emit(EditorEvent::TitleChanged);
 1731                    }));
 1732                }
 1733                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1734                    if let project::Event::RefreshInlayHints = event {
 1735                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1736                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1737                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1738                            let focus_handle = editor.focus_handle(cx);
 1739                            if focus_handle.is_focused(cx) {
 1740                                let snapshot = buffer.read(cx).snapshot();
 1741                                for (range, snippet) in snippet_edits {
 1742                                    let editor_range =
 1743                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1744                                    editor
 1745                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1746                                        .ok();
 1747                                }
 1748                            }
 1749                        }
 1750                    }
 1751                }));
 1752                let task_inventory = project.read(cx).task_inventory().clone();
 1753                project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1754                    editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1755                }));
 1756            }
 1757        }
 1758
 1759        let inlay_hint_settings = inlay_hint_settings(
 1760            selections.newest_anchor().head(),
 1761            &buffer.read(cx).snapshot(cx),
 1762            cx,
 1763        );
 1764        let focus_handle = cx.focus_handle();
 1765        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1766        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1767            .detach();
 1768        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1769
 1770        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1771            Some(false)
 1772        } else {
 1773            None
 1774        };
 1775
 1776        let mut this = Self {
 1777            focus_handle,
 1778            show_cursor_when_unfocused: false,
 1779            last_focused_descendant: None,
 1780            buffer: buffer.clone(),
 1781            display_map: display_map.clone(),
 1782            selections,
 1783            scroll_manager: ScrollManager::new(cx),
 1784            columnar_selection_tail: None,
 1785            add_selections_state: None,
 1786            select_next_state: None,
 1787            select_prev_state: None,
 1788            selection_history: Default::default(),
 1789            autoclose_regions: Default::default(),
 1790            snippet_stack: Default::default(),
 1791            select_larger_syntax_node_stack: Vec::new(),
 1792            ime_transaction: Default::default(),
 1793            active_diagnostics: None,
 1794            soft_wrap_mode_override,
 1795            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1796            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1797            project,
 1798            blink_manager: blink_manager.clone(),
 1799            show_local_selections: true,
 1800            mode,
 1801            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1802            show_gutter: mode == EditorMode::Full,
 1803            show_line_numbers: None,
 1804            show_git_diff_gutter: None,
 1805            show_code_actions: None,
 1806            show_runnables: None,
 1807            show_wrap_guides: None,
 1808            show_indent_guides,
 1809            placeholder_text: None,
 1810            highlight_order: 0,
 1811            highlighted_rows: HashMap::default(),
 1812            background_highlights: Default::default(),
 1813            gutter_highlights: TreeMap::default(),
 1814            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1815            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1816            nav_history: None,
 1817            context_menu: RwLock::new(None),
 1818            mouse_context_menu: None,
 1819            completion_tasks: Default::default(),
 1820            find_all_references_task_sources: Vec::new(),
 1821            next_completion_id: 0,
 1822            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1823            next_inlay_id: 0,
 1824            available_code_actions: Default::default(),
 1825            code_actions_task: Default::default(),
 1826            document_highlights_task: Default::default(),
 1827            linked_editing_range_task: Default::default(),
 1828            pending_rename: Default::default(),
 1829            searchable: true,
 1830            cursor_shape: Default::default(),
 1831            current_line_highlight: None,
 1832            autoindent_mode: Some(AutoindentMode::EachLine),
 1833            collapse_matches: false,
 1834            workspace: None,
 1835            keymap_context_layers: Default::default(),
 1836            input_enabled: true,
 1837            use_modal_editing: mode == EditorMode::Full,
 1838            read_only: false,
 1839            use_autoclose: true,
 1840            use_auto_surround: true,
 1841            auto_replace_emoji_shortcode: false,
 1842            leader_peer_id: None,
 1843            remote_id: None,
 1844            hover_state: Default::default(),
 1845            hovered_link_state: Default::default(),
 1846            inline_completion_provider: None,
 1847            active_inline_completion: None,
 1848            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1849            expanded_hunks: ExpandedHunks::default(),
 1850            gutter_hovered: false,
 1851            pixel_position_of_newest_cursor: None,
 1852            last_bounds: None,
 1853            expect_bounds_change: None,
 1854            gutter_dimensions: GutterDimensions::default(),
 1855            style: None,
 1856            show_cursor_names: false,
 1857            hovered_cursors: Default::default(),
 1858            next_editor_action_id: EditorActionId::default(),
 1859            editor_actions: Rc::default(),
 1860            vim_replace_map: Default::default(),
 1861            show_inline_completions: mode == EditorMode::Full,
 1862            custom_context_menu: None,
 1863            show_git_blame_gutter: false,
 1864            show_git_blame_inline: false,
 1865            show_selection_menu: None,
 1866            show_git_blame_inline_delay_task: None,
 1867            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1868            blame: None,
 1869            blame_subscription: None,
 1870            file_header_size,
 1871            tasks: Default::default(),
 1872            _subscriptions: vec![
 1873                cx.observe(&buffer, Self::on_buffer_changed),
 1874                cx.subscribe(&buffer, Self::on_buffer_event),
 1875                cx.observe(&display_map, Self::on_display_map_changed),
 1876                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1877                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1878                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1879                cx.observe_window_activation(|editor, cx| {
 1880                    let active = cx.is_window_active();
 1881                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1882                        if active {
 1883                            blink_manager.enable(cx);
 1884                        } else {
 1885                            blink_manager.show_cursor(cx);
 1886                            blink_manager.disable(cx);
 1887                        }
 1888                    });
 1889                }),
 1890            ],
 1891            tasks_update_task: None,
 1892            linked_edit_ranges: Default::default(),
 1893            previous_search_ranges: None,
 1894            breadcrumb_header: None,
 1895        };
 1896        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1897        this._subscriptions.extend(project_subscriptions);
 1898
 1899        this.end_selection(cx);
 1900        this.scroll_manager.show_scrollbar(cx);
 1901
 1902        if mode == EditorMode::Full {
 1903            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1904            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1905
 1906            if this.git_blame_inline_enabled {
 1907                this.git_blame_inline_enabled = true;
 1908                this.start_git_blame_inline(false, cx);
 1909            }
 1910        }
 1911
 1912        this.report_editor_event("open", None, cx);
 1913        this
 1914    }
 1915
 1916    pub fn mouse_menu_is_focused(&self, cx: &mut WindowContext) -> bool {
 1917        self.mouse_context_menu
 1918            .as_ref()
 1919            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1920    }
 1921
 1922    fn key_context(&self, cx: &AppContext) -> KeyContext {
 1923        let mut key_context = KeyContext::new_with_defaults();
 1924        key_context.add("Editor");
 1925        let mode = match self.mode {
 1926            EditorMode::SingleLine { .. } => "single_line",
 1927            EditorMode::AutoHeight { .. } => "auto_height",
 1928            EditorMode::Full => "full",
 1929        };
 1930        key_context.set("mode", mode);
 1931        if self.pending_rename.is_some() {
 1932            key_context.add("renaming");
 1933        }
 1934        if self.context_menu_visible() {
 1935            match self.context_menu.read().as_ref() {
 1936                Some(ContextMenu::Completions(_)) => {
 1937                    key_context.add("menu");
 1938                    key_context.add("showing_completions")
 1939                }
 1940                Some(ContextMenu::CodeActions(_)) => {
 1941                    key_context.add("menu");
 1942                    key_context.add("showing_code_actions")
 1943                }
 1944                None => {}
 1945            }
 1946        }
 1947
 1948        for layer in self.keymap_context_layers.values() {
 1949            key_context.extend(layer);
 1950        }
 1951
 1952        if let Some(extension) = self
 1953            .buffer
 1954            .read(cx)
 1955            .as_singleton()
 1956            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1957        {
 1958            key_context.set("extension", extension.to_string());
 1959        }
 1960
 1961        if self.has_active_inline_completion(cx) {
 1962            key_context.add("copilot_suggestion");
 1963            key_context.add("inline_completion");
 1964        }
 1965
 1966        key_context
 1967    }
 1968
 1969    pub fn new_file(
 1970        workspace: &mut Workspace,
 1971        _: &workspace::NewFile,
 1972        cx: &mut ViewContext<Workspace>,
 1973    ) {
 1974        let project = workspace.project().clone();
 1975        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1976
 1977        cx.spawn(|workspace, mut cx| async move {
 1978            let buffer = create.await?;
 1979            workspace.update(&mut cx, |workspace, cx| {
 1980                workspace.add_item_to_active_pane(
 1981                    Box::new(
 1982                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1983                    ),
 1984                    None,
 1985                    cx,
 1986                )
 1987            })
 1988        })
 1989        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1990            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1991                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1992                e.error_tag("required").unwrap_or("the latest version")
 1993            )),
 1994            _ => None,
 1995        });
 1996    }
 1997
 1998    pub fn new_file_in_direction(
 1999        workspace: &mut Workspace,
 2000        action: &workspace::NewFileInDirection,
 2001        cx: &mut ViewContext<Workspace>,
 2002    ) {
 2003        let project = workspace.project().clone();
 2004        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2005        let direction = action.0;
 2006
 2007        cx.spawn(|workspace, mut cx| async move {
 2008            let buffer = create.await?;
 2009            workspace.update(&mut cx, move |workspace, cx| {
 2010                workspace.split_item(
 2011                    direction,
 2012                    Box::new(
 2013                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2014                    ),
 2015                    cx,
 2016                )
 2017            })?;
 2018            anyhow::Ok(())
 2019        })
 2020        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2021            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2022                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2023                e.error_tag("required").unwrap_or("the latest version")
 2024            )),
 2025            _ => None,
 2026        });
 2027    }
 2028
 2029    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
 2030        self.buffer.read(cx).replica_id()
 2031    }
 2032
 2033    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2034        self.leader_peer_id
 2035    }
 2036
 2037    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2038        &self.buffer
 2039    }
 2040
 2041    pub fn workspace(&self) -> Option<View<Workspace>> {
 2042        self.workspace.as_ref()?.0.upgrade()
 2043    }
 2044
 2045    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2046        self.buffer().read(cx).title(cx)
 2047    }
 2048
 2049    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2050        EditorSnapshot {
 2051            mode: self.mode,
 2052            show_gutter: self.show_gutter,
 2053            show_line_numbers: self.show_line_numbers,
 2054            show_git_diff_gutter: self.show_git_diff_gutter,
 2055            show_code_actions: self.show_code_actions,
 2056            show_runnables: self.show_runnables,
 2057            render_git_blame_gutter: self.render_git_blame_gutter(cx),
 2058            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2059            scroll_anchor: self.scroll_manager.anchor(),
 2060            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2061            placeholder_text: self.placeholder_text.clone(),
 2062            is_focused: self.focus_handle.is_focused(cx),
 2063            current_line_highlight: self
 2064                .current_line_highlight
 2065                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2066            gutter_hovered: self.gutter_hovered,
 2067        }
 2068    }
 2069
 2070    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2071        self.buffer.read(cx).language_at(point, cx)
 2072    }
 2073
 2074    pub fn file_at<T: ToOffset>(
 2075        &self,
 2076        point: T,
 2077        cx: &AppContext,
 2078    ) -> Option<Arc<dyn language::File>> {
 2079        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2080    }
 2081
 2082    pub fn active_excerpt(
 2083        &self,
 2084        cx: &AppContext,
 2085    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2086        self.buffer
 2087            .read(cx)
 2088            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2089    }
 2090
 2091    pub fn mode(&self) -> EditorMode {
 2092        self.mode
 2093    }
 2094
 2095    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2096        self.collaboration_hub.as_deref()
 2097    }
 2098
 2099    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2100        self.collaboration_hub = Some(hub);
 2101    }
 2102
 2103    pub fn set_custom_context_menu(
 2104        &mut self,
 2105        f: impl 'static
 2106            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2107    ) {
 2108        self.custom_context_menu = Some(Box::new(f))
 2109    }
 2110
 2111    pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
 2112        self.completion_provider = Some(provider);
 2113    }
 2114
 2115    pub fn set_inline_completion_provider<T>(
 2116        &mut self,
 2117        provider: Option<Model<T>>,
 2118        cx: &mut ViewContext<Self>,
 2119    ) where
 2120        T: InlineCompletionProvider,
 2121    {
 2122        self.inline_completion_provider =
 2123            provider.map(|provider| RegisteredInlineCompletionProvider {
 2124                _subscription: cx.observe(&provider, |this, _, cx| {
 2125                    if this.focus_handle.is_focused(cx) {
 2126                        this.update_visible_inline_completion(cx);
 2127                    }
 2128                }),
 2129                provider: Arc::new(provider),
 2130            });
 2131        self.refresh_inline_completion(false, cx);
 2132    }
 2133
 2134    pub fn placeholder_text(&self, _cx: &mut WindowContext) -> Option<&str> {
 2135        self.placeholder_text.as_deref()
 2136    }
 2137
 2138    pub fn set_placeholder_text(
 2139        &mut self,
 2140        placeholder_text: impl Into<Arc<str>>,
 2141        cx: &mut ViewContext<Self>,
 2142    ) {
 2143        let placeholder_text = Some(placeholder_text.into());
 2144        if self.placeholder_text != placeholder_text {
 2145            self.placeholder_text = placeholder_text;
 2146            cx.notify();
 2147        }
 2148    }
 2149
 2150    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2151        self.cursor_shape = cursor_shape;
 2152        cx.notify();
 2153    }
 2154
 2155    pub fn set_current_line_highlight(
 2156        &mut self,
 2157        current_line_highlight: Option<CurrentLineHighlight>,
 2158    ) {
 2159        self.current_line_highlight = current_line_highlight;
 2160    }
 2161
 2162    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2163        self.collapse_matches = collapse_matches;
 2164    }
 2165
 2166    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2167        if self.collapse_matches {
 2168            return range.start..range.start;
 2169        }
 2170        range.clone()
 2171    }
 2172
 2173    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2174        if self.display_map.read(cx).clip_at_line_ends != clip {
 2175            self.display_map
 2176                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2177        }
 2178    }
 2179
 2180    pub fn set_keymap_context_layer<Tag: 'static>(
 2181        &mut self,
 2182        context: KeyContext,
 2183        cx: &mut ViewContext<Self>,
 2184    ) {
 2185        self.keymap_context_layers
 2186            .insert(TypeId::of::<Tag>(), context);
 2187        cx.notify();
 2188    }
 2189
 2190    pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
 2191        self.keymap_context_layers.remove(&TypeId::of::<Tag>());
 2192        cx.notify();
 2193    }
 2194
 2195    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2196        self.input_enabled = input_enabled;
 2197    }
 2198
 2199    pub fn set_autoindent(&mut self, autoindent: bool) {
 2200        if autoindent {
 2201            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2202        } else {
 2203            self.autoindent_mode = None;
 2204        }
 2205    }
 2206
 2207    pub fn read_only(&self, cx: &AppContext) -> bool {
 2208        self.read_only || self.buffer.read(cx).read_only()
 2209    }
 2210
 2211    pub fn set_read_only(&mut self, read_only: bool) {
 2212        self.read_only = read_only;
 2213    }
 2214
 2215    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2216        self.use_autoclose = autoclose;
 2217    }
 2218
 2219    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2220        self.use_auto_surround = auto_surround;
 2221    }
 2222
 2223    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2224        self.auto_replace_emoji_shortcode = auto_replace;
 2225    }
 2226
 2227    pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
 2228        self.show_inline_completions = show_inline_completions;
 2229    }
 2230
 2231    pub fn set_use_modal_editing(&mut self, to: bool) {
 2232        self.use_modal_editing = to;
 2233    }
 2234
 2235    pub fn use_modal_editing(&self) -> bool {
 2236        self.use_modal_editing
 2237    }
 2238
 2239    fn selections_did_change(
 2240        &mut self,
 2241        local: bool,
 2242        old_cursor_position: &Anchor,
 2243        show_completions: bool,
 2244        cx: &mut ViewContext<Self>,
 2245    ) {
 2246        // Copy selections to primary selection buffer
 2247        #[cfg(target_os = "linux")]
 2248        if local {
 2249            let selections = self.selections.all::<usize>(cx);
 2250            let buffer_handle = self.buffer.read(cx).read(cx);
 2251
 2252            let mut text = String::new();
 2253            for (index, selection) in selections.iter().enumerate() {
 2254                let text_for_selection = buffer_handle
 2255                    .text_for_range(selection.start..selection.end)
 2256                    .collect::<String>();
 2257
 2258                text.push_str(&text_for_selection);
 2259                if index != selections.len() - 1 {
 2260                    text.push('\n');
 2261                }
 2262            }
 2263
 2264            if !text.is_empty() {
 2265                cx.write_to_primary(ClipboardItem::new(text));
 2266            }
 2267        }
 2268
 2269        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2270            self.buffer.update(cx, |buffer, cx| {
 2271                buffer.set_active_selections(
 2272                    &self.selections.disjoint_anchors(),
 2273                    self.selections.line_mode,
 2274                    self.cursor_shape,
 2275                    cx,
 2276                )
 2277            });
 2278        }
 2279        let display_map = self
 2280            .display_map
 2281            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2282        let buffer = &display_map.buffer_snapshot;
 2283        self.add_selections_state = None;
 2284        self.select_next_state = None;
 2285        self.select_prev_state = None;
 2286        self.select_larger_syntax_node_stack.clear();
 2287        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2288        self.snippet_stack
 2289            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2290        self.take_rename(false, cx);
 2291
 2292        let new_cursor_position = self.selections.newest_anchor().head();
 2293
 2294        self.push_to_nav_history(
 2295            *old_cursor_position,
 2296            Some(new_cursor_position.to_point(buffer)),
 2297            cx,
 2298        );
 2299
 2300        if local {
 2301            let new_cursor_position = self.selections.newest_anchor().head();
 2302            let mut context_menu = self.context_menu.write();
 2303            let completion_menu = match context_menu.as_ref() {
 2304                Some(ContextMenu::Completions(menu)) => Some(menu),
 2305
 2306                _ => {
 2307                    *context_menu = None;
 2308                    None
 2309                }
 2310            };
 2311
 2312            if let Some(completion_menu) = completion_menu {
 2313                let cursor_position = new_cursor_position.to_offset(buffer);
 2314                let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
 2315                if kind == Some(CharKind::Word)
 2316                    && word_range.to_inclusive().contains(&cursor_position)
 2317                {
 2318                    let mut completion_menu = completion_menu.clone();
 2319                    drop(context_menu);
 2320
 2321                    let query = Self::completion_query(buffer, cursor_position);
 2322                    cx.spawn(move |this, mut cx| async move {
 2323                        completion_menu
 2324                            .filter(query.as_deref(), cx.background_executor().clone())
 2325                            .await;
 2326
 2327                        this.update(&mut cx, |this, cx| {
 2328                            let mut context_menu = this.context_menu.write();
 2329                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2330                                return;
 2331                            };
 2332
 2333                            if menu.id > completion_menu.id {
 2334                                return;
 2335                            }
 2336
 2337                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2338                            drop(context_menu);
 2339                            cx.notify();
 2340                        })
 2341                    })
 2342                    .detach();
 2343
 2344                    if show_completions {
 2345                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2346                    }
 2347                } else {
 2348                    drop(context_menu);
 2349                    self.hide_context_menu(cx);
 2350                }
 2351            } else {
 2352                drop(context_menu);
 2353            }
 2354
 2355            hide_hover(self, cx);
 2356
 2357            if old_cursor_position.to_display_point(&display_map).row()
 2358                != new_cursor_position.to_display_point(&display_map).row()
 2359            {
 2360                self.available_code_actions.take();
 2361            }
 2362            self.refresh_code_actions(cx);
 2363            self.refresh_document_highlights(cx);
 2364            refresh_matching_bracket_highlights(self, cx);
 2365            self.discard_inline_completion(false, cx);
 2366            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2367            if self.git_blame_inline_enabled {
 2368                self.start_inline_blame_timer(cx);
 2369            }
 2370        }
 2371
 2372        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2373        cx.emit(EditorEvent::SelectionsChanged { local });
 2374
 2375        if self.selections.disjoint_anchors().len() == 1 {
 2376            cx.emit(SearchEvent::ActiveMatchChanged)
 2377        }
 2378        cx.notify();
 2379    }
 2380
 2381    pub fn change_selections<R>(
 2382        &mut self,
 2383        autoscroll: Option<Autoscroll>,
 2384        cx: &mut ViewContext<Self>,
 2385        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2386    ) -> R {
 2387        self.change_selections_inner(autoscroll, true, cx, change)
 2388    }
 2389
 2390    pub fn change_selections_inner<R>(
 2391        &mut self,
 2392        autoscroll: Option<Autoscroll>,
 2393        request_completions: bool,
 2394        cx: &mut ViewContext<Self>,
 2395        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2396    ) -> R {
 2397        let old_cursor_position = self.selections.newest_anchor().head();
 2398        self.push_to_selection_history();
 2399
 2400        let (changed, result) = self.selections.change_with(cx, change);
 2401
 2402        if changed {
 2403            if let Some(autoscroll) = autoscroll {
 2404                self.request_autoscroll(autoscroll, cx);
 2405            }
 2406            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2407        }
 2408
 2409        result
 2410    }
 2411
 2412    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2413    where
 2414        I: IntoIterator<Item = (Range<S>, T)>,
 2415        S: ToOffset,
 2416        T: Into<Arc<str>>,
 2417    {
 2418        if self.read_only(cx) {
 2419            return;
 2420        }
 2421
 2422        self.buffer
 2423            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2424    }
 2425
 2426    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2427    where
 2428        I: IntoIterator<Item = (Range<S>, T)>,
 2429        S: ToOffset,
 2430        T: Into<Arc<str>>,
 2431    {
 2432        if self.read_only(cx) {
 2433            return;
 2434        }
 2435
 2436        self.buffer.update(cx, |buffer, cx| {
 2437            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2438        });
 2439    }
 2440
 2441    pub fn edit_with_block_indent<I, S, T>(
 2442        &mut self,
 2443        edits: I,
 2444        original_indent_columns: Vec<u32>,
 2445        cx: &mut ViewContext<Self>,
 2446    ) where
 2447        I: IntoIterator<Item = (Range<S>, T)>,
 2448        S: ToOffset,
 2449        T: Into<Arc<str>>,
 2450    {
 2451        if self.read_only(cx) {
 2452            return;
 2453        }
 2454
 2455        self.buffer.update(cx, |buffer, cx| {
 2456            buffer.edit(
 2457                edits,
 2458                Some(AutoindentMode::Block {
 2459                    original_indent_columns,
 2460                }),
 2461                cx,
 2462            )
 2463        });
 2464    }
 2465
 2466    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2467        self.hide_context_menu(cx);
 2468
 2469        match phase {
 2470            SelectPhase::Begin {
 2471                position,
 2472                add,
 2473                click_count,
 2474            } => self.begin_selection(position, add, click_count, cx),
 2475            SelectPhase::BeginColumnar {
 2476                position,
 2477                goal_column,
 2478                reset,
 2479            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2480            SelectPhase::Extend {
 2481                position,
 2482                click_count,
 2483            } => self.extend_selection(position, click_count, cx),
 2484            SelectPhase::Update {
 2485                position,
 2486                goal_column,
 2487                scroll_delta,
 2488            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2489            SelectPhase::End => self.end_selection(cx),
 2490        }
 2491    }
 2492
 2493    fn extend_selection(
 2494        &mut self,
 2495        position: DisplayPoint,
 2496        click_count: usize,
 2497        cx: &mut ViewContext<Self>,
 2498    ) {
 2499        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2500        let tail = self.selections.newest::<usize>(cx).tail();
 2501        self.begin_selection(position, false, click_count, cx);
 2502
 2503        let position = position.to_offset(&display_map, Bias::Left);
 2504        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2505
 2506        let mut pending_selection = self
 2507            .selections
 2508            .pending_anchor()
 2509            .expect("extend_selection not called with pending selection");
 2510        if position >= tail {
 2511            pending_selection.start = tail_anchor;
 2512        } else {
 2513            pending_selection.end = tail_anchor;
 2514            pending_selection.reversed = true;
 2515        }
 2516
 2517        let mut pending_mode = self.selections.pending_mode().unwrap();
 2518        match &mut pending_mode {
 2519            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2520            _ => {}
 2521        }
 2522
 2523        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2524            s.set_pending(pending_selection, pending_mode)
 2525        });
 2526    }
 2527
 2528    fn begin_selection(
 2529        &mut self,
 2530        position: DisplayPoint,
 2531        add: bool,
 2532        click_count: usize,
 2533        cx: &mut ViewContext<Self>,
 2534    ) {
 2535        if !self.focus_handle.is_focused(cx) {
 2536            self.last_focused_descendant = None;
 2537            cx.focus(&self.focus_handle);
 2538        }
 2539
 2540        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2541        let buffer = &display_map.buffer_snapshot;
 2542        let newest_selection = self.selections.newest_anchor().clone();
 2543        let position = display_map.clip_point(position, Bias::Left);
 2544
 2545        let start;
 2546        let end;
 2547        let mode;
 2548        let auto_scroll;
 2549        match click_count {
 2550            1 => {
 2551                start = buffer.anchor_before(position.to_point(&display_map));
 2552                end = start;
 2553                mode = SelectMode::Character;
 2554                auto_scroll = true;
 2555            }
 2556            2 => {
 2557                let range = movement::surrounding_word(&display_map, position);
 2558                start = buffer.anchor_before(range.start.to_point(&display_map));
 2559                end = buffer.anchor_before(range.end.to_point(&display_map));
 2560                mode = SelectMode::Word(start..end);
 2561                auto_scroll = true;
 2562            }
 2563            3 => {
 2564                let position = display_map
 2565                    .clip_point(position, Bias::Left)
 2566                    .to_point(&display_map);
 2567                let line_start = display_map.prev_line_boundary(position).0;
 2568                let next_line_start = buffer.clip_point(
 2569                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2570                    Bias::Left,
 2571                );
 2572                start = buffer.anchor_before(line_start);
 2573                end = buffer.anchor_before(next_line_start);
 2574                mode = SelectMode::Line(start..end);
 2575                auto_scroll = true;
 2576            }
 2577            _ => {
 2578                start = buffer.anchor_before(0);
 2579                end = buffer.anchor_before(buffer.len());
 2580                mode = SelectMode::All;
 2581                auto_scroll = false;
 2582            }
 2583        }
 2584
 2585        let point_to_delete: Option<usize> = {
 2586            let selected_points: Vec<Selection<Point>> =
 2587                self.selections.disjoint_in_range(start..end, cx);
 2588
 2589            if !add || click_count > 1 {
 2590                None
 2591            } else if selected_points.len() > 0 {
 2592                Some(selected_points[0].id)
 2593            } else {
 2594                let clicked_point_already_selected =
 2595                    self.selections.disjoint.iter().find(|selection| {
 2596                        selection.start.to_point(buffer) == start.to_point(buffer)
 2597                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2598                    });
 2599
 2600                if let Some(selection) = clicked_point_already_selected {
 2601                    Some(selection.id)
 2602                } else {
 2603                    None
 2604                }
 2605            }
 2606        };
 2607
 2608        let selections_count = self.selections.count();
 2609
 2610        self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
 2611            if let Some(point_to_delete) = point_to_delete {
 2612                s.delete(point_to_delete);
 2613
 2614                if selections_count == 1 {
 2615                    s.set_pending_anchor_range(start..end, mode);
 2616                }
 2617            } else {
 2618                if !add {
 2619                    s.clear_disjoint();
 2620                } else if click_count > 1 {
 2621                    s.delete(newest_selection.id)
 2622                }
 2623
 2624                s.set_pending_anchor_range(start..end, mode);
 2625            }
 2626        });
 2627    }
 2628
 2629    fn begin_columnar_selection(
 2630        &mut self,
 2631        position: DisplayPoint,
 2632        goal_column: u32,
 2633        reset: bool,
 2634        cx: &mut ViewContext<Self>,
 2635    ) {
 2636        if !self.focus_handle.is_focused(cx) {
 2637            self.last_focused_descendant = None;
 2638            cx.focus(&self.focus_handle);
 2639        }
 2640
 2641        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2642
 2643        if reset {
 2644            let pointer_position = display_map
 2645                .buffer_snapshot
 2646                .anchor_before(position.to_point(&display_map));
 2647
 2648            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2649                s.clear_disjoint();
 2650                s.set_pending_anchor_range(
 2651                    pointer_position..pointer_position,
 2652                    SelectMode::Character,
 2653                );
 2654            });
 2655        }
 2656
 2657        let tail = self.selections.newest::<Point>(cx).tail();
 2658        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2659
 2660        if !reset {
 2661            self.select_columns(
 2662                tail.to_display_point(&display_map),
 2663                position,
 2664                goal_column,
 2665                &display_map,
 2666                cx,
 2667            );
 2668        }
 2669    }
 2670
 2671    fn update_selection(
 2672        &mut self,
 2673        position: DisplayPoint,
 2674        goal_column: u32,
 2675        scroll_delta: gpui::Point<f32>,
 2676        cx: &mut ViewContext<Self>,
 2677    ) {
 2678        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2679
 2680        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2681            let tail = tail.to_display_point(&display_map);
 2682            self.select_columns(tail, position, goal_column, &display_map, cx);
 2683        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2684            let buffer = self.buffer.read(cx).snapshot(cx);
 2685            let head;
 2686            let tail;
 2687            let mode = self.selections.pending_mode().unwrap();
 2688            match &mode {
 2689                SelectMode::Character => {
 2690                    head = position.to_point(&display_map);
 2691                    tail = pending.tail().to_point(&buffer);
 2692                }
 2693                SelectMode::Word(original_range) => {
 2694                    let original_display_range = original_range.start.to_display_point(&display_map)
 2695                        ..original_range.end.to_display_point(&display_map);
 2696                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2697                        ..original_display_range.end.to_point(&display_map);
 2698                    if movement::is_inside_word(&display_map, position)
 2699                        || original_display_range.contains(&position)
 2700                    {
 2701                        let word_range = movement::surrounding_word(&display_map, position);
 2702                        if word_range.start < original_display_range.start {
 2703                            head = word_range.start.to_point(&display_map);
 2704                        } else {
 2705                            head = word_range.end.to_point(&display_map);
 2706                        }
 2707                    } else {
 2708                        head = position.to_point(&display_map);
 2709                    }
 2710
 2711                    if head <= original_buffer_range.start {
 2712                        tail = original_buffer_range.end;
 2713                    } else {
 2714                        tail = original_buffer_range.start;
 2715                    }
 2716                }
 2717                SelectMode::Line(original_range) => {
 2718                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2719
 2720                    let position = display_map
 2721                        .clip_point(position, Bias::Left)
 2722                        .to_point(&display_map);
 2723                    let line_start = display_map.prev_line_boundary(position).0;
 2724                    let next_line_start = buffer.clip_point(
 2725                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2726                        Bias::Left,
 2727                    );
 2728
 2729                    if line_start < original_range.start {
 2730                        head = line_start
 2731                    } else {
 2732                        head = next_line_start
 2733                    }
 2734
 2735                    if head <= original_range.start {
 2736                        tail = original_range.end;
 2737                    } else {
 2738                        tail = original_range.start;
 2739                    }
 2740                }
 2741                SelectMode::All => {
 2742                    return;
 2743                }
 2744            };
 2745
 2746            if head < tail {
 2747                pending.start = buffer.anchor_before(head);
 2748                pending.end = buffer.anchor_before(tail);
 2749                pending.reversed = true;
 2750            } else {
 2751                pending.start = buffer.anchor_before(tail);
 2752                pending.end = buffer.anchor_before(head);
 2753                pending.reversed = false;
 2754            }
 2755
 2756            self.change_selections(None, cx, |s| {
 2757                s.set_pending(pending, mode);
 2758            });
 2759        } else {
 2760            log::error!("update_selection dispatched with no pending selection");
 2761            return;
 2762        }
 2763
 2764        self.apply_scroll_delta(scroll_delta, cx);
 2765        cx.notify();
 2766    }
 2767
 2768    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2769        self.columnar_selection_tail.take();
 2770        if self.selections.pending_anchor().is_some() {
 2771            let selections = self.selections.all::<usize>(cx);
 2772            self.change_selections(None, cx, |s| {
 2773                s.select(selections);
 2774                s.clear_pending();
 2775            });
 2776        }
 2777    }
 2778
 2779    fn select_columns(
 2780        &mut self,
 2781        tail: DisplayPoint,
 2782        head: DisplayPoint,
 2783        goal_column: u32,
 2784        display_map: &DisplaySnapshot,
 2785        cx: &mut ViewContext<Self>,
 2786    ) {
 2787        let start_row = cmp::min(tail.row(), head.row());
 2788        let end_row = cmp::max(tail.row(), head.row());
 2789        let start_column = cmp::min(tail.column(), goal_column);
 2790        let end_column = cmp::max(tail.column(), goal_column);
 2791        let reversed = start_column < tail.column();
 2792
 2793        let selection_ranges = (start_row.0..=end_row.0)
 2794            .map(DisplayRow)
 2795            .filter_map(|row| {
 2796                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2797                    let start = display_map
 2798                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2799                        .to_point(display_map);
 2800                    let end = display_map
 2801                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2802                        .to_point(display_map);
 2803                    if reversed {
 2804                        Some(end..start)
 2805                    } else {
 2806                        Some(start..end)
 2807                    }
 2808                } else {
 2809                    None
 2810                }
 2811            })
 2812            .collect::<Vec<_>>();
 2813
 2814        self.change_selections(None, cx, |s| {
 2815            s.select_ranges(selection_ranges);
 2816        });
 2817        cx.notify();
 2818    }
 2819
 2820    pub fn has_pending_nonempty_selection(&self) -> bool {
 2821        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2822            Some(Selection { start, end, .. }) => start != end,
 2823            None => false,
 2824        };
 2825
 2826        pending_nonempty_selection
 2827            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2828    }
 2829
 2830    pub fn has_pending_selection(&self) -> bool {
 2831        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2832    }
 2833
 2834    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2835        self.clear_expanded_diff_hunks(cx);
 2836        if self.dismiss_menus_and_popups(true, cx) {
 2837            return;
 2838        }
 2839
 2840        if self.mode == EditorMode::Full {
 2841            if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
 2842                return;
 2843            }
 2844        }
 2845
 2846        cx.propagate();
 2847    }
 2848
 2849    pub fn dismiss_menus_and_popups(
 2850        &mut self,
 2851        should_report_inline_completion_event: bool,
 2852        cx: &mut ViewContext<Self>,
 2853    ) -> bool {
 2854        if self.take_rename(false, cx).is_some() {
 2855            return true;
 2856        }
 2857
 2858        if hide_hover(self, cx) {
 2859            return true;
 2860        }
 2861
 2862        if self.hide_context_menu(cx).is_some() {
 2863            return true;
 2864        }
 2865
 2866        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2867            return true;
 2868        }
 2869
 2870        if self.snippet_stack.pop().is_some() {
 2871            return true;
 2872        }
 2873
 2874        if self.mode == EditorMode::Full {
 2875            if self.active_diagnostics.is_some() {
 2876                self.dismiss_diagnostics(cx);
 2877                return true;
 2878            }
 2879        }
 2880
 2881        false
 2882    }
 2883
 2884    fn linked_editing_ranges_for(
 2885        &self,
 2886        selection: Range<text::Anchor>,
 2887        cx: &AppContext,
 2888    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2889        if self.linked_edit_ranges.is_empty() {
 2890            return None;
 2891        }
 2892        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2893            selection.end.buffer_id.and_then(|end_buffer_id| {
 2894                if selection.start.buffer_id != Some(end_buffer_id) {
 2895                    return None;
 2896                }
 2897                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2898                let snapshot = buffer.read(cx).snapshot();
 2899                self.linked_edit_ranges
 2900                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2901                    .map(|ranges| (ranges, snapshot, buffer))
 2902            })?;
 2903        use text::ToOffset as TO;
 2904        // find offset from the start of current range to current cursor position
 2905        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2906
 2907        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2908        let start_difference = start_offset - start_byte_offset;
 2909        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2910        let end_difference = end_offset - start_byte_offset;
 2911        // Current range has associated linked ranges.
 2912        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2913        for range in linked_ranges.iter() {
 2914            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2915            let end_offset = start_offset + end_difference;
 2916            let start_offset = start_offset + start_difference;
 2917            let start = buffer_snapshot.anchor_after(start_offset);
 2918            let end = buffer_snapshot.anchor_after(end_offset);
 2919            linked_edits
 2920                .entry(buffer.clone())
 2921                .or_default()
 2922                .push(start..end);
 2923        }
 2924        Some(linked_edits)
 2925    }
 2926
 2927    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2928        let text: Arc<str> = text.into();
 2929
 2930        if self.read_only(cx) {
 2931            return;
 2932        }
 2933
 2934        let selections = self.selections.all_adjusted(cx);
 2935        let mut brace_inserted = false;
 2936        let mut edits = Vec::new();
 2937        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2938        let mut new_selections = Vec::with_capacity(selections.len());
 2939        let mut new_autoclose_regions = Vec::new();
 2940        let snapshot = self.buffer.read(cx).read(cx);
 2941
 2942        for (selection, autoclose_region) in
 2943            self.selections_with_autoclose_regions(selections, &snapshot)
 2944        {
 2945            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2946                // Determine if the inserted text matches the opening or closing
 2947                // bracket of any of this language's bracket pairs.
 2948                let mut bracket_pair = None;
 2949                let mut is_bracket_pair_start = false;
 2950                let mut is_bracket_pair_end = false;
 2951                if !text.is_empty() {
 2952                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2953                    //  and they are removing the character that triggered IME popup.
 2954                    for (pair, enabled) in scope.brackets() {
 2955                        if !pair.close && !pair.surround {
 2956                            continue;
 2957                        }
 2958
 2959                        if enabled && pair.start.ends_with(text.as_ref()) {
 2960                            bracket_pair = Some(pair.clone());
 2961                            is_bracket_pair_start = true;
 2962                            break;
 2963                        }
 2964                        if pair.end.as_str() == text.as_ref() {
 2965                            bracket_pair = Some(pair.clone());
 2966                            is_bracket_pair_end = true;
 2967                            break;
 2968                        }
 2969                    }
 2970                }
 2971
 2972                if let Some(bracket_pair) = bracket_pair {
 2973                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2974                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2975                    let auto_surround =
 2976                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2977                    if selection.is_empty() {
 2978                        if is_bracket_pair_start {
 2979                            let prefix_len = bracket_pair.start.len() - text.len();
 2980
 2981                            // If the inserted text is a suffix of an opening bracket and the
 2982                            // selection is preceded by the rest of the opening bracket, then
 2983                            // insert the closing bracket.
 2984                            let following_text_allows_autoclose = snapshot
 2985                                .chars_at(selection.start)
 2986                                .next()
 2987                                .map_or(true, |c| scope.should_autoclose_before(c));
 2988                            let preceding_text_matches_prefix = prefix_len == 0
 2989                                || (selection.start.column >= (prefix_len as u32)
 2990                                    && snapshot.contains_str_at(
 2991                                        Point::new(
 2992                                            selection.start.row,
 2993                                            selection.start.column - (prefix_len as u32),
 2994                                        ),
 2995                                        &bracket_pair.start[..prefix_len],
 2996                                    ));
 2997                            if autoclose
 2998                                && bracket_pair.close
 2999                                && following_text_allows_autoclose
 3000                                && preceding_text_matches_prefix
 3001                            {
 3002                                let anchor = snapshot.anchor_before(selection.end);
 3003                                new_selections.push((selection.map(|_| anchor), text.len()));
 3004                                new_autoclose_regions.push((
 3005                                    anchor,
 3006                                    text.len(),
 3007                                    selection.id,
 3008                                    bracket_pair.clone(),
 3009                                ));
 3010                                edits.push((
 3011                                    selection.range(),
 3012                                    format!("{}{}", text, bracket_pair.end).into(),
 3013                                ));
 3014                                brace_inserted = true;
 3015                                continue;
 3016                            }
 3017                        }
 3018
 3019                        if let Some(region) = autoclose_region {
 3020                            // If the selection is followed by an auto-inserted closing bracket,
 3021                            // then don't insert that closing bracket again; just move the selection
 3022                            // past the closing bracket.
 3023                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3024                                && text.as_ref() == region.pair.end.as_str();
 3025                            if should_skip {
 3026                                let anchor = snapshot.anchor_after(selection.end);
 3027                                new_selections
 3028                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3029                                continue;
 3030                            }
 3031                        }
 3032
 3033                        let always_treat_brackets_as_autoclosed = snapshot
 3034                            .settings_at(selection.start, cx)
 3035                            .always_treat_brackets_as_autoclosed;
 3036                        if always_treat_brackets_as_autoclosed
 3037                            && is_bracket_pair_end
 3038                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3039                        {
 3040                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3041                            // and the inserted text is a closing bracket and the selection is followed
 3042                            // by the closing bracket then move the selection past the closing bracket.
 3043                            let anchor = snapshot.anchor_after(selection.end);
 3044                            new_selections.push((selection.map(|_| anchor), text.len()));
 3045                            continue;
 3046                        }
 3047                    }
 3048                    // If an opening bracket is 1 character long and is typed while
 3049                    // text is selected, then surround that text with the bracket pair.
 3050                    else if auto_surround
 3051                        && bracket_pair.surround
 3052                        && is_bracket_pair_start
 3053                        && bracket_pair.start.chars().count() == 1
 3054                    {
 3055                        edits.push((selection.start..selection.start, text.clone()));
 3056                        edits.push((
 3057                            selection.end..selection.end,
 3058                            bracket_pair.end.as_str().into(),
 3059                        ));
 3060                        brace_inserted = true;
 3061                        new_selections.push((
 3062                            Selection {
 3063                                id: selection.id,
 3064                                start: snapshot.anchor_after(selection.start),
 3065                                end: snapshot.anchor_before(selection.end),
 3066                                reversed: selection.reversed,
 3067                                goal: selection.goal,
 3068                            },
 3069                            0,
 3070                        ));
 3071                        continue;
 3072                    }
 3073                }
 3074            }
 3075
 3076            if self.auto_replace_emoji_shortcode
 3077                && selection.is_empty()
 3078                && text.as_ref().ends_with(':')
 3079            {
 3080                if let Some(possible_emoji_short_code) =
 3081                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3082                {
 3083                    if !possible_emoji_short_code.is_empty() {
 3084                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3085                            let emoji_shortcode_start = Point::new(
 3086                                selection.start.row,
 3087                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3088                            );
 3089
 3090                            // Remove shortcode from buffer
 3091                            edits.push((
 3092                                emoji_shortcode_start..selection.start,
 3093                                "".to_string().into(),
 3094                            ));
 3095                            new_selections.push((
 3096                                Selection {
 3097                                    id: selection.id,
 3098                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3099                                    end: snapshot.anchor_before(selection.start),
 3100                                    reversed: selection.reversed,
 3101                                    goal: selection.goal,
 3102                                },
 3103                                0,
 3104                            ));
 3105
 3106                            // Insert emoji
 3107                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3108                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3109                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3110
 3111                            continue;
 3112                        }
 3113                    }
 3114                }
 3115            }
 3116
 3117            // If not handling any auto-close operation, then just replace the selected
 3118            // text with the given input and move the selection to the end of the
 3119            // newly inserted text.
 3120            let anchor = snapshot.anchor_after(selection.end);
 3121            if !self.linked_edit_ranges.is_empty() {
 3122                let start_anchor = snapshot.anchor_before(selection.start);
 3123                if let Some(ranges) =
 3124                    self.linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3125                {
 3126                    for (buffer, edits) in ranges {
 3127                        linked_edits
 3128                            .entry(buffer.clone())
 3129                            .or_default()
 3130                            .extend(edits.into_iter().map(|range| (range, text.clone())));
 3131                    }
 3132                }
 3133            }
 3134
 3135            new_selections.push((selection.map(|_| anchor), 0));
 3136            edits.push((selection.start..selection.end, text.clone()));
 3137        }
 3138
 3139        drop(snapshot);
 3140
 3141        self.transact(cx, |this, cx| {
 3142            this.buffer.update(cx, |buffer, cx| {
 3143                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3144            });
 3145            for (buffer, edits) in linked_edits {
 3146                buffer.update(cx, |buffer, cx| {
 3147                    let snapshot = buffer.snapshot();
 3148                    let edits = edits
 3149                        .into_iter()
 3150                        .map(|(range, text)| {
 3151                            use text::ToPoint as TP;
 3152                            let end_point = TP::to_point(&range.end, &snapshot);
 3153                            let start_point = TP::to_point(&range.start, &snapshot);
 3154                            (start_point..end_point, text)
 3155                        })
 3156                        .sorted_by_key(|(range, _)| range.start)
 3157                        .collect::<Vec<_>>();
 3158                    buffer.edit(edits, None, cx);
 3159                })
 3160            }
 3161            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3162            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3163            let snapshot = this.buffer.read(cx).read(cx);
 3164            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3165                .zip(new_selection_deltas)
 3166                .map(|(selection, delta)| Selection {
 3167                    id: selection.id,
 3168                    start: selection.start + delta,
 3169                    end: selection.end + delta,
 3170                    reversed: selection.reversed,
 3171                    goal: SelectionGoal::None,
 3172                })
 3173                .collect::<Vec<_>>();
 3174
 3175            let mut i = 0;
 3176            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3177                let position = position.to_offset(&snapshot) + delta;
 3178                let start = snapshot.anchor_before(position);
 3179                let end = snapshot.anchor_after(position);
 3180                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3181                    match existing_state.range.start.cmp(&start, &snapshot) {
 3182                        Ordering::Less => i += 1,
 3183                        Ordering::Greater => break,
 3184                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3185                            Ordering::Less => i += 1,
 3186                            Ordering::Equal => break,
 3187                            Ordering::Greater => break,
 3188                        },
 3189                    }
 3190                }
 3191                this.autoclose_regions.insert(
 3192                    i,
 3193                    AutocloseRegion {
 3194                        selection_id,
 3195                        range: start..end,
 3196                        pair,
 3197                    },
 3198                );
 3199            }
 3200
 3201            drop(snapshot);
 3202            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3203            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3204                s.select(new_selections)
 3205            });
 3206
 3207            if !brace_inserted && EditorSettings::get_global(cx).use_on_type_format {
 3208                if let Some(on_type_format_task) =
 3209                    this.trigger_on_type_formatting(text.to_string(), cx)
 3210                {
 3211                    on_type_format_task.detach_and_log_err(cx);
 3212                }
 3213            }
 3214
 3215            let trigger_in_words = !had_active_inline_completion;
 3216            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3217            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3218            this.refresh_inline_completion(true, cx);
 3219        });
 3220    }
 3221
 3222    fn find_possible_emoji_shortcode_at_position(
 3223        snapshot: &MultiBufferSnapshot,
 3224        position: Point,
 3225    ) -> Option<String> {
 3226        let mut chars = Vec::new();
 3227        let mut found_colon = false;
 3228        for char in snapshot.reversed_chars_at(position).take(100) {
 3229            // Found a possible emoji shortcode in the middle of the buffer
 3230            if found_colon {
 3231                if char.is_whitespace() {
 3232                    chars.reverse();
 3233                    return Some(chars.iter().collect());
 3234                }
 3235                // If the previous character is not a whitespace, we are in the middle of a word
 3236                // and we only want to complete the shortcode if the word is made up of other emojis
 3237                let mut containing_word = String::new();
 3238                for ch in snapshot
 3239                    .reversed_chars_at(position)
 3240                    .skip(chars.len() + 1)
 3241                    .take(100)
 3242                {
 3243                    if ch.is_whitespace() {
 3244                        break;
 3245                    }
 3246                    containing_word.push(ch);
 3247                }
 3248                let containing_word = containing_word.chars().rev().collect::<String>();
 3249                if util::word_consists_of_emojis(containing_word.as_str()) {
 3250                    chars.reverse();
 3251                    return Some(chars.iter().collect());
 3252                }
 3253            }
 3254
 3255            if char.is_whitespace() || !char.is_ascii() {
 3256                return None;
 3257            }
 3258            if char == ':' {
 3259                found_colon = true;
 3260            } else {
 3261                chars.push(char);
 3262            }
 3263        }
 3264        // Found a possible emoji shortcode at the beginning of the buffer
 3265        chars.reverse();
 3266        Some(chars.iter().collect())
 3267    }
 3268
 3269    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3270        self.transact(cx, |this, cx| {
 3271            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3272                let selections = this.selections.all::<usize>(cx);
 3273                let multi_buffer = this.buffer.read(cx);
 3274                let buffer = multi_buffer.snapshot(cx);
 3275                selections
 3276                    .iter()
 3277                    .map(|selection| {
 3278                        let start_point = selection.start.to_point(&buffer);
 3279                        let mut indent =
 3280                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3281                        indent.len = cmp::min(indent.len, start_point.column);
 3282                        let start = selection.start;
 3283                        let end = selection.end;
 3284                        let selection_is_empty = start == end;
 3285                        let language_scope = buffer.language_scope_at(start);
 3286                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3287                            &language_scope
 3288                        {
 3289                            let leading_whitespace_len = buffer
 3290                                .reversed_chars_at(start)
 3291                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3292                                .map(|c| c.len_utf8())
 3293                                .sum::<usize>();
 3294
 3295                            let trailing_whitespace_len = buffer
 3296                                .chars_at(end)
 3297                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3298                                .map(|c| c.len_utf8())
 3299                                .sum::<usize>();
 3300
 3301                            let insert_extra_newline =
 3302                                language.brackets().any(|(pair, enabled)| {
 3303                                    let pair_start = pair.start.trim_end();
 3304                                    let pair_end = pair.end.trim_start();
 3305
 3306                                    enabled
 3307                                        && pair.newline
 3308                                        && buffer.contains_str_at(
 3309                                            end + trailing_whitespace_len,
 3310                                            pair_end,
 3311                                        )
 3312                                        && buffer.contains_str_at(
 3313                                            (start - leading_whitespace_len)
 3314                                                .saturating_sub(pair_start.len()),
 3315                                            pair_start,
 3316                                        )
 3317                                });
 3318
 3319                            // Comment extension on newline is allowed only for cursor selections
 3320                            let comment_delimiter = maybe!({
 3321                                if !selection_is_empty {
 3322                                    return None;
 3323                                }
 3324
 3325                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3326                                    return None;
 3327                                }
 3328
 3329                                let delimiters = language.line_comment_prefixes();
 3330                                let max_len_of_delimiter =
 3331                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3332                                let (snapshot, range) =
 3333                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3334
 3335                                let mut index_of_first_non_whitespace = 0;
 3336                                let comment_candidate = snapshot
 3337                                    .chars_for_range(range)
 3338                                    .skip_while(|c| {
 3339                                        let should_skip = c.is_whitespace();
 3340                                        if should_skip {
 3341                                            index_of_first_non_whitespace += 1;
 3342                                        }
 3343                                        should_skip
 3344                                    })
 3345                                    .take(max_len_of_delimiter)
 3346                                    .collect::<String>();
 3347                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3348                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3349                                })?;
 3350                                let cursor_is_placed_after_comment_marker =
 3351                                    index_of_first_non_whitespace + comment_prefix.len()
 3352                                        <= start_point.column as usize;
 3353                                if cursor_is_placed_after_comment_marker {
 3354                                    Some(comment_prefix.clone())
 3355                                } else {
 3356                                    None
 3357                                }
 3358                            });
 3359                            (comment_delimiter, insert_extra_newline)
 3360                        } else {
 3361                            (None, false)
 3362                        };
 3363
 3364                        let capacity_for_delimiter = comment_delimiter
 3365                            .as_deref()
 3366                            .map(str::len)
 3367                            .unwrap_or_default();
 3368                        let mut new_text =
 3369                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3370                        new_text.push_str("\n");
 3371                        new_text.extend(indent.chars());
 3372                        if let Some(delimiter) = &comment_delimiter {
 3373                            new_text.push_str(&delimiter);
 3374                        }
 3375                        if insert_extra_newline {
 3376                            new_text = new_text.repeat(2);
 3377                        }
 3378
 3379                        let anchor = buffer.anchor_after(end);
 3380                        let new_selection = selection.map(|_| anchor);
 3381                        (
 3382                            (start..end, new_text),
 3383                            (insert_extra_newline, new_selection),
 3384                        )
 3385                    })
 3386                    .unzip()
 3387            };
 3388
 3389            this.edit_with_autoindent(edits, cx);
 3390            let buffer = this.buffer.read(cx).snapshot(cx);
 3391            let new_selections = selection_fixup_info
 3392                .into_iter()
 3393                .map(|(extra_newline_inserted, new_selection)| {
 3394                    let mut cursor = new_selection.end.to_point(&buffer);
 3395                    if extra_newline_inserted {
 3396                        cursor.row -= 1;
 3397                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3398                    }
 3399                    new_selection.map(|_| cursor)
 3400                })
 3401                .collect();
 3402
 3403            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3404            this.refresh_inline_completion(true, cx);
 3405        });
 3406    }
 3407
 3408    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3409        let buffer = self.buffer.read(cx);
 3410        let snapshot = buffer.snapshot(cx);
 3411
 3412        let mut edits = Vec::new();
 3413        let mut rows = Vec::new();
 3414
 3415        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3416            let cursor = selection.head();
 3417            let row = cursor.row;
 3418
 3419            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3420
 3421            let newline = "\n".to_string();
 3422            edits.push((start_of_line..start_of_line, newline));
 3423
 3424            rows.push(row + rows_inserted as u32);
 3425        }
 3426
 3427        self.transact(cx, |editor, cx| {
 3428            editor.edit(edits, cx);
 3429
 3430            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3431                let mut index = 0;
 3432                s.move_cursors_with(|map, _, _| {
 3433                    let row = rows[index];
 3434                    index += 1;
 3435
 3436                    let point = Point::new(row, 0);
 3437                    let boundary = map.next_line_boundary(point).1;
 3438                    let clipped = map.clip_point(boundary, Bias::Left);
 3439
 3440                    (clipped, SelectionGoal::None)
 3441                });
 3442            });
 3443
 3444            let mut indent_edits = Vec::new();
 3445            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3446            for row in rows {
 3447                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3448                for (row, indent) in indents {
 3449                    if indent.len == 0 {
 3450                        continue;
 3451                    }
 3452
 3453                    let text = match indent.kind {
 3454                        IndentKind::Space => " ".repeat(indent.len as usize),
 3455                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3456                    };
 3457                    let point = Point::new(row.0, 0);
 3458                    indent_edits.push((point..point, text));
 3459                }
 3460            }
 3461            editor.edit(indent_edits, cx);
 3462        });
 3463    }
 3464
 3465    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3466        let buffer = self.buffer.read(cx);
 3467        let snapshot = buffer.snapshot(cx);
 3468
 3469        let mut edits = Vec::new();
 3470        let mut rows = Vec::new();
 3471        let mut rows_inserted = 0;
 3472
 3473        for selection in self.selections.all_adjusted(cx) {
 3474            let cursor = selection.head();
 3475            let row = cursor.row;
 3476
 3477            let point = Point::new(row + 1, 0);
 3478            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3479
 3480            let newline = "\n".to_string();
 3481            edits.push((start_of_line..start_of_line, newline));
 3482
 3483            rows_inserted += 1;
 3484            rows.push(row + rows_inserted);
 3485        }
 3486
 3487        self.transact(cx, |editor, cx| {
 3488            editor.edit(edits, cx);
 3489
 3490            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3491                let mut index = 0;
 3492                s.move_cursors_with(|map, _, _| {
 3493                    let row = rows[index];
 3494                    index += 1;
 3495
 3496                    let point = Point::new(row, 0);
 3497                    let boundary = map.next_line_boundary(point).1;
 3498                    let clipped = map.clip_point(boundary, Bias::Left);
 3499
 3500                    (clipped, SelectionGoal::None)
 3501                });
 3502            });
 3503
 3504            let mut indent_edits = Vec::new();
 3505            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3506            for row in rows {
 3507                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3508                for (row, indent) in indents {
 3509                    if indent.len == 0 {
 3510                        continue;
 3511                    }
 3512
 3513                    let text = match indent.kind {
 3514                        IndentKind::Space => " ".repeat(indent.len as usize),
 3515                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3516                    };
 3517                    let point = Point::new(row.0, 0);
 3518                    indent_edits.push((point..point, text));
 3519                }
 3520            }
 3521            editor.edit(indent_edits, cx);
 3522        });
 3523    }
 3524
 3525    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3526        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3527            original_indent_columns: Vec::new(),
 3528        });
 3529        self.insert_with_autoindent_mode(text, autoindent, cx);
 3530    }
 3531
 3532    fn insert_with_autoindent_mode(
 3533        &mut self,
 3534        text: &str,
 3535        autoindent_mode: Option<AutoindentMode>,
 3536        cx: &mut ViewContext<Self>,
 3537    ) {
 3538        if self.read_only(cx) {
 3539            return;
 3540        }
 3541
 3542        let text: Arc<str> = text.into();
 3543        self.transact(cx, |this, cx| {
 3544            let old_selections = this.selections.all_adjusted(cx);
 3545            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3546                let anchors = {
 3547                    let snapshot = buffer.read(cx);
 3548                    old_selections
 3549                        .iter()
 3550                        .map(|s| {
 3551                            let anchor = snapshot.anchor_after(s.head());
 3552                            s.map(|_| anchor)
 3553                        })
 3554                        .collect::<Vec<_>>()
 3555                };
 3556                buffer.edit(
 3557                    old_selections
 3558                        .iter()
 3559                        .map(|s| (s.start..s.end, text.clone())),
 3560                    autoindent_mode,
 3561                    cx,
 3562                );
 3563                anchors
 3564            });
 3565
 3566            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3567                s.select_anchors(selection_anchors);
 3568            })
 3569        });
 3570    }
 3571
 3572    fn trigger_completion_on_input(
 3573        &mut self,
 3574        text: &str,
 3575        trigger_in_words: bool,
 3576        cx: &mut ViewContext<Self>,
 3577    ) {
 3578        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3579            self.show_completions(
 3580                &ShowCompletions {
 3581                    trigger: text.chars().last(),
 3582                },
 3583                cx,
 3584            );
 3585        } else {
 3586            self.hide_context_menu(cx);
 3587        }
 3588    }
 3589
 3590    fn is_completion_trigger(
 3591        &self,
 3592        text: &str,
 3593        trigger_in_words: bool,
 3594        cx: &mut ViewContext<Self>,
 3595    ) -> bool {
 3596        let position = self.selections.newest_anchor().head();
 3597        let multibuffer = self.buffer.read(cx);
 3598        let Some(buffer) = position
 3599            .buffer_id
 3600            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3601        else {
 3602            return false;
 3603        };
 3604
 3605        if let Some(completion_provider) = &self.completion_provider {
 3606            completion_provider.is_completion_trigger(
 3607                &buffer,
 3608                position.text_anchor,
 3609                text,
 3610                trigger_in_words,
 3611                cx,
 3612            )
 3613        } else {
 3614            false
 3615        }
 3616    }
 3617
 3618    /// If any empty selections is touching the start of its innermost containing autoclose
 3619    /// region, expand it to select the brackets.
 3620    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3621        let selections = self.selections.all::<usize>(cx);
 3622        let buffer = self.buffer.read(cx).read(cx);
 3623        let new_selections = self
 3624            .selections_with_autoclose_regions(selections, &buffer)
 3625            .map(|(mut selection, region)| {
 3626                if !selection.is_empty() {
 3627                    return selection;
 3628                }
 3629
 3630                if let Some(region) = region {
 3631                    let mut range = region.range.to_offset(&buffer);
 3632                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3633                        range.start -= region.pair.start.len();
 3634                        if buffer.contains_str_at(range.start, &region.pair.start)
 3635                            && buffer.contains_str_at(range.end, &region.pair.end)
 3636                        {
 3637                            range.end += region.pair.end.len();
 3638                            selection.start = range.start;
 3639                            selection.end = range.end;
 3640
 3641                            return selection;
 3642                        }
 3643                    }
 3644                }
 3645
 3646                let always_treat_brackets_as_autoclosed = buffer
 3647                    .settings_at(selection.start, cx)
 3648                    .always_treat_brackets_as_autoclosed;
 3649
 3650                if !always_treat_brackets_as_autoclosed {
 3651                    return selection;
 3652                }
 3653
 3654                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3655                    for (pair, enabled) in scope.brackets() {
 3656                        if !enabled || !pair.close {
 3657                            continue;
 3658                        }
 3659
 3660                        if buffer.contains_str_at(selection.start, &pair.end) {
 3661                            let pair_start_len = pair.start.len();
 3662                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3663                            {
 3664                                selection.start -= pair_start_len;
 3665                                selection.end += pair.end.len();
 3666
 3667                                return selection;
 3668                            }
 3669                        }
 3670                    }
 3671                }
 3672
 3673                selection
 3674            })
 3675            .collect();
 3676
 3677        drop(buffer);
 3678        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3679    }
 3680
 3681    /// Iterate the given selections, and for each one, find the smallest surrounding
 3682    /// autoclose region. This uses the ordering of the selections and the autoclose
 3683    /// regions to avoid repeated comparisons.
 3684    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3685        &'a self,
 3686        selections: impl IntoIterator<Item = Selection<D>>,
 3687        buffer: &'a MultiBufferSnapshot,
 3688    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3689        let mut i = 0;
 3690        let mut regions = self.autoclose_regions.as_slice();
 3691        selections.into_iter().map(move |selection| {
 3692            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3693
 3694            let mut enclosing = None;
 3695            while let Some(pair_state) = regions.get(i) {
 3696                if pair_state.range.end.to_offset(buffer) < range.start {
 3697                    regions = &regions[i + 1..];
 3698                    i = 0;
 3699                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3700                    break;
 3701                } else {
 3702                    if pair_state.selection_id == selection.id {
 3703                        enclosing = Some(pair_state);
 3704                    }
 3705                    i += 1;
 3706                }
 3707            }
 3708
 3709            (selection.clone(), enclosing)
 3710        })
 3711    }
 3712
 3713    /// Remove any autoclose regions that no longer contain their selection.
 3714    fn invalidate_autoclose_regions(
 3715        &mut self,
 3716        mut selections: &[Selection<Anchor>],
 3717        buffer: &MultiBufferSnapshot,
 3718    ) {
 3719        self.autoclose_regions.retain(|state| {
 3720            let mut i = 0;
 3721            while let Some(selection) = selections.get(i) {
 3722                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3723                    selections = &selections[1..];
 3724                    continue;
 3725                }
 3726                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3727                    break;
 3728                }
 3729                if selection.id == state.selection_id {
 3730                    return true;
 3731                } else {
 3732                    i += 1;
 3733                }
 3734            }
 3735            false
 3736        });
 3737    }
 3738
 3739    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3740        let offset = position.to_offset(buffer);
 3741        let (word_range, kind) = buffer.surrounding_word(offset);
 3742        if offset > word_range.start && kind == Some(CharKind::Word) {
 3743            Some(
 3744                buffer
 3745                    .text_for_range(word_range.start..offset)
 3746                    .collect::<String>(),
 3747            )
 3748        } else {
 3749            None
 3750        }
 3751    }
 3752
 3753    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3754        self.refresh_inlay_hints(
 3755            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3756            cx,
 3757        );
 3758    }
 3759
 3760    pub fn inlay_hints_enabled(&self) -> bool {
 3761        self.inlay_hint_cache.enabled
 3762    }
 3763
 3764    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3765        if self.project.is_none() || self.mode != EditorMode::Full {
 3766            return;
 3767        }
 3768
 3769        let reason_description = reason.description();
 3770        let ignore_debounce = matches!(
 3771            reason,
 3772            InlayHintRefreshReason::SettingsChange(_)
 3773                | InlayHintRefreshReason::Toggle(_)
 3774                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3775        );
 3776        let (invalidate_cache, required_languages) = match reason {
 3777            InlayHintRefreshReason::Toggle(enabled) => {
 3778                self.inlay_hint_cache.enabled = enabled;
 3779                if enabled {
 3780                    (InvalidationStrategy::RefreshRequested, None)
 3781                } else {
 3782                    self.inlay_hint_cache.clear();
 3783                    self.splice_inlays(
 3784                        self.visible_inlay_hints(cx)
 3785                            .iter()
 3786                            .map(|inlay| inlay.id)
 3787                            .collect(),
 3788                        Vec::new(),
 3789                        cx,
 3790                    );
 3791                    return;
 3792                }
 3793            }
 3794            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3795                match self.inlay_hint_cache.update_settings(
 3796                    &self.buffer,
 3797                    new_settings,
 3798                    self.visible_inlay_hints(cx),
 3799                    cx,
 3800                ) {
 3801                    ControlFlow::Break(Some(InlaySplice {
 3802                        to_remove,
 3803                        to_insert,
 3804                    })) => {
 3805                        self.splice_inlays(to_remove, to_insert, cx);
 3806                        return;
 3807                    }
 3808                    ControlFlow::Break(None) => return,
 3809                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3810                }
 3811            }
 3812            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3813                if let Some(InlaySplice {
 3814                    to_remove,
 3815                    to_insert,
 3816                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3817                {
 3818                    self.splice_inlays(to_remove, to_insert, cx);
 3819                }
 3820                return;
 3821            }
 3822            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3823            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3824                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3825            }
 3826            InlayHintRefreshReason::RefreshRequested => {
 3827                (InvalidationStrategy::RefreshRequested, None)
 3828            }
 3829        };
 3830
 3831        if let Some(InlaySplice {
 3832            to_remove,
 3833            to_insert,
 3834        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3835            reason_description,
 3836            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3837            invalidate_cache,
 3838            ignore_debounce,
 3839            cx,
 3840        ) {
 3841            self.splice_inlays(to_remove, to_insert, cx);
 3842        }
 3843    }
 3844
 3845    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3846        self.display_map
 3847            .read(cx)
 3848            .current_inlays()
 3849            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3850            .cloned()
 3851            .collect()
 3852    }
 3853
 3854    pub fn excerpts_for_inlay_hints_query(
 3855        &self,
 3856        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3857        cx: &mut ViewContext<Editor>,
 3858    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3859        let Some(project) = self.project.as_ref() else {
 3860            return HashMap::default();
 3861        };
 3862        let project = project.read(cx);
 3863        let multi_buffer = self.buffer().read(cx);
 3864        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3865        let multi_buffer_visible_start = self
 3866            .scroll_manager
 3867            .anchor()
 3868            .anchor
 3869            .to_point(&multi_buffer_snapshot);
 3870        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3871            multi_buffer_visible_start
 3872                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3873            Bias::Left,
 3874        );
 3875        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3876        multi_buffer
 3877            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3878            .into_iter()
 3879            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3880            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3881                let buffer = buffer_handle.read(cx);
 3882                let buffer_file = project::File::from_dyn(buffer.file())?;
 3883                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3884                let worktree_entry = buffer_worktree
 3885                    .read(cx)
 3886                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3887                if worktree_entry.is_ignored {
 3888                    return None;
 3889                }
 3890
 3891                let language = buffer.language()?;
 3892                if let Some(restrict_to_languages) = restrict_to_languages {
 3893                    if !restrict_to_languages.contains(language) {
 3894                        return None;
 3895                    }
 3896                }
 3897                Some((
 3898                    excerpt_id,
 3899                    (
 3900                        buffer_handle,
 3901                        buffer.version().clone(),
 3902                        excerpt_visible_range,
 3903                    ),
 3904                ))
 3905            })
 3906            .collect()
 3907    }
 3908
 3909    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3910        TextLayoutDetails {
 3911            text_system: cx.text_system().clone(),
 3912            editor_style: self.style.clone().unwrap(),
 3913            rem_size: cx.rem_size(),
 3914            scroll_anchor: self.scroll_manager.anchor(),
 3915            visible_rows: self.visible_line_count(),
 3916            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3917        }
 3918    }
 3919
 3920    fn splice_inlays(
 3921        &self,
 3922        to_remove: Vec<InlayId>,
 3923        to_insert: Vec<Inlay>,
 3924        cx: &mut ViewContext<Self>,
 3925    ) {
 3926        self.display_map.update(cx, |display_map, cx| {
 3927            display_map.splice_inlays(to_remove, to_insert, cx);
 3928        });
 3929        cx.notify();
 3930    }
 3931
 3932    fn trigger_on_type_formatting(
 3933        &self,
 3934        input: String,
 3935        cx: &mut ViewContext<Self>,
 3936    ) -> Option<Task<Result<()>>> {
 3937        if input.len() != 1 {
 3938            return None;
 3939        }
 3940
 3941        let project = self.project.as_ref()?;
 3942        let position = self.selections.newest_anchor().head();
 3943        let (buffer, buffer_position) = self
 3944            .buffer
 3945            .read(cx)
 3946            .text_anchor_for_position(position, cx)?;
 3947
 3948        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3949        // hence we do LSP request & edit on host side only — add formats to host's history.
 3950        let push_to_lsp_host_history = true;
 3951        // If this is not the host, append its history with new edits.
 3952        let push_to_client_history = project.read(cx).is_remote();
 3953
 3954        let on_type_formatting = project.update(cx, |project, cx| {
 3955            project.on_type_format(
 3956                buffer.clone(),
 3957                buffer_position,
 3958                input,
 3959                push_to_lsp_host_history,
 3960                cx,
 3961            )
 3962        });
 3963        Some(cx.spawn(|editor, mut cx| async move {
 3964            if let Some(transaction) = on_type_formatting.await? {
 3965                if push_to_client_history {
 3966                    buffer
 3967                        .update(&mut cx, |buffer, _| {
 3968                            buffer.push_transaction(transaction, Instant::now());
 3969                        })
 3970                        .ok();
 3971                }
 3972                editor.update(&mut cx, |editor, cx| {
 3973                    editor.refresh_document_highlights(cx);
 3974                })?;
 3975            }
 3976            Ok(())
 3977        }))
 3978    }
 3979
 3980    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3981        if self.pending_rename.is_some() {
 3982            return;
 3983        }
 3984
 3985        let Some(provider) = self.completion_provider.as_ref() else {
 3986            return;
 3987        };
 3988
 3989        let position = self.selections.newest_anchor().head();
 3990        let (buffer, buffer_position) =
 3991            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3992                output
 3993            } else {
 3994                return;
 3995            };
 3996
 3997        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3998        let is_followup_invoke = {
 3999            let context_menu_state = self.context_menu.read();
 4000            matches!(
 4001                context_menu_state.deref(),
 4002                Some(ContextMenu::Completions(_))
 4003            )
 4004        };
 4005        let trigger_kind = match (options.trigger, is_followup_invoke) {
 4006            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4007            (Some(_), _) => CompletionTriggerKind::TRIGGER_CHARACTER,
 4008            _ => CompletionTriggerKind::INVOKED,
 4009        };
 4010        let completion_context = CompletionContext {
 4011            trigger_character: options.trigger.and_then(|c| {
 4012                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4013                    Some(String::from(c))
 4014                } else {
 4015                    None
 4016                }
 4017            }),
 4018            trigger_kind,
 4019        };
 4020        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4021
 4022        let id = post_inc(&mut self.next_completion_id);
 4023        let task = cx.spawn(|this, mut cx| {
 4024            async move {
 4025                this.update(&mut cx, |this, _| {
 4026                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4027                })?;
 4028                let completions = completions.await.log_err();
 4029                let menu = if let Some(completions) = completions {
 4030                    let mut menu = CompletionsMenu {
 4031                        id,
 4032                        initial_position: position,
 4033                        match_candidates: completions
 4034                            .iter()
 4035                            .enumerate()
 4036                            .map(|(id, completion)| {
 4037                                StringMatchCandidate::new(
 4038                                    id,
 4039                                    completion.label.text[completion.label.filter_range.clone()]
 4040                                        .into(),
 4041                                )
 4042                            })
 4043                            .collect(),
 4044                        buffer: buffer.clone(),
 4045                        completions: Arc::new(RwLock::new(completions.into())),
 4046                        matches: Vec::new().into(),
 4047                        selected_item: 0,
 4048                        scroll_handle: UniformListScrollHandle::new(),
 4049                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4050                            DebouncedDelay::new(),
 4051                        )),
 4052                    };
 4053                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4054                        .await;
 4055
 4056                    if menu.matches.is_empty() {
 4057                        None
 4058                    } else {
 4059                        this.update(&mut cx, |editor, cx| {
 4060                            let completions = menu.completions.clone();
 4061                            let matches = menu.matches.clone();
 4062
 4063                            let delay_ms = EditorSettings::get_global(cx)
 4064                                .completion_documentation_secondary_query_debounce;
 4065                            let delay = Duration::from_millis(delay_ms);
 4066                            editor
 4067                                .completion_documentation_pre_resolve_debounce
 4068                                .fire_new(delay, cx, |editor, cx| {
 4069                                    CompletionsMenu::pre_resolve_completion_documentation(
 4070                                        buffer,
 4071                                        completions,
 4072                                        matches,
 4073                                        editor,
 4074                                        cx,
 4075                                    )
 4076                                });
 4077                        })
 4078                        .ok();
 4079                        Some(menu)
 4080                    }
 4081                } else {
 4082                    None
 4083                };
 4084
 4085                this.update(&mut cx, |this, cx| {
 4086                    let mut context_menu = this.context_menu.write();
 4087                    match context_menu.as_ref() {
 4088                        None => {}
 4089
 4090                        Some(ContextMenu::Completions(prev_menu)) => {
 4091                            if prev_menu.id > id {
 4092                                return;
 4093                            }
 4094                        }
 4095
 4096                        _ => return,
 4097                    }
 4098
 4099                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4100                        let menu = menu.unwrap();
 4101                        *context_menu = Some(ContextMenu::Completions(menu));
 4102                        drop(context_menu);
 4103                        this.discard_inline_completion(false, cx);
 4104                        cx.notify();
 4105                    } else if this.completion_tasks.len() <= 1 {
 4106                        // If there are no more completion tasks and the last menu was
 4107                        // empty, we should hide it. If it was already hidden, we should
 4108                        // also show the copilot completion when available.
 4109                        drop(context_menu);
 4110                        if this.hide_context_menu(cx).is_none() {
 4111                            this.update_visible_inline_completion(cx);
 4112                        }
 4113                    }
 4114                })?;
 4115
 4116                Ok::<_, anyhow::Error>(())
 4117            }
 4118            .log_err()
 4119        });
 4120
 4121        self.completion_tasks.push((id, task));
 4122    }
 4123
 4124    pub fn confirm_completion(
 4125        &mut self,
 4126        action: &ConfirmCompletion,
 4127        cx: &mut ViewContext<Self>,
 4128    ) -> Option<Task<Result<()>>> {
 4129        use language::ToOffset as _;
 4130
 4131        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4132            menu
 4133        } else {
 4134            return None;
 4135        };
 4136
 4137        let mat = completions_menu
 4138            .matches
 4139            .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
 4140        let buffer_handle = completions_menu.buffer;
 4141        let completions = completions_menu.completions.read();
 4142        let completion = completions.get(mat.candidate_id)?;
 4143        cx.stop_propagation();
 4144
 4145        let snippet;
 4146        let text;
 4147
 4148        if completion.is_snippet() {
 4149            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4150            text = snippet.as_ref().unwrap().text.clone();
 4151        } else {
 4152            snippet = None;
 4153            text = completion.new_text.clone();
 4154        };
 4155        let selections = self.selections.all::<usize>(cx);
 4156        let buffer = buffer_handle.read(cx);
 4157        let old_range = completion.old_range.to_offset(buffer);
 4158        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4159
 4160        let newest_selection = self.selections.newest_anchor();
 4161        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4162            return None;
 4163        }
 4164
 4165        let lookbehind = newest_selection
 4166            .start
 4167            .text_anchor
 4168            .to_offset(buffer)
 4169            .saturating_sub(old_range.start);
 4170        let lookahead = old_range
 4171            .end
 4172            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4173        let mut common_prefix_len = old_text
 4174            .bytes()
 4175            .zip(text.bytes())
 4176            .take_while(|(a, b)| a == b)
 4177            .count();
 4178
 4179        let snapshot = self.buffer.read(cx).snapshot(cx);
 4180        let mut range_to_replace: Option<Range<isize>> = None;
 4181        let mut ranges = Vec::new();
 4182        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4183        for selection in &selections {
 4184            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4185                let start = selection.start.saturating_sub(lookbehind);
 4186                let end = selection.end + lookahead;
 4187                if selection.id == newest_selection.id {
 4188                    range_to_replace = Some(
 4189                        ((start + common_prefix_len) as isize - selection.start as isize)
 4190                            ..(end as isize - selection.start as isize),
 4191                    );
 4192                }
 4193                ranges.push(start + common_prefix_len..end);
 4194            } else {
 4195                common_prefix_len = 0;
 4196                ranges.clear();
 4197                ranges.extend(selections.iter().map(|s| {
 4198                    if s.id == newest_selection.id {
 4199                        range_to_replace = Some(
 4200                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4201                                - selection.start as isize
 4202                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4203                                    - selection.start as isize,
 4204                        );
 4205                        old_range.clone()
 4206                    } else {
 4207                        s.start..s.end
 4208                    }
 4209                }));
 4210                break;
 4211            }
 4212            if !self.linked_edit_ranges.is_empty() {
 4213                let start_anchor = snapshot.anchor_before(selection.head());
 4214                let end_anchor = snapshot.anchor_after(selection.tail());
 4215                if let Some(ranges) = self
 4216                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4217                {
 4218                    for (buffer, edits) in ranges {
 4219                        linked_edits.entry(buffer.clone()).or_default().extend(
 4220                            edits
 4221                                .into_iter()
 4222                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4223                        );
 4224                    }
 4225                }
 4226            }
 4227        }
 4228        let text = &text[common_prefix_len..];
 4229
 4230        cx.emit(EditorEvent::InputHandled {
 4231            utf16_range_to_replace: range_to_replace,
 4232            text: text.into(),
 4233        });
 4234
 4235        self.transact(cx, |this, cx| {
 4236            if let Some(mut snippet) = snippet {
 4237                snippet.text = text.to_string();
 4238                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4239                    tabstop.start -= common_prefix_len as isize;
 4240                    tabstop.end -= common_prefix_len as isize;
 4241                }
 4242
 4243                this.insert_snippet(&ranges, snippet, cx).log_err();
 4244            } else {
 4245                this.buffer.update(cx, |buffer, cx| {
 4246                    buffer.edit(
 4247                        ranges.iter().map(|range| (range.clone(), text)),
 4248                        this.autoindent_mode.clone(),
 4249                        cx,
 4250                    );
 4251                });
 4252            }
 4253            for (buffer, edits) in linked_edits {
 4254                buffer.update(cx, |buffer, cx| {
 4255                    let snapshot = buffer.snapshot();
 4256                    let edits = edits
 4257                        .into_iter()
 4258                        .map(|(range, text)| {
 4259                            use text::ToPoint as TP;
 4260                            let end_point = TP::to_point(&range.end, &snapshot);
 4261                            let start_point = TP::to_point(&range.start, &snapshot);
 4262                            (start_point..end_point, text)
 4263                        })
 4264                        .sorted_by_key(|(range, _)| range.start)
 4265                        .collect::<Vec<_>>();
 4266                    buffer.edit(edits, None, cx);
 4267                })
 4268            }
 4269
 4270            this.refresh_inline_completion(true, cx);
 4271        });
 4272
 4273        if let Some(confirm) = completion.confirm.as_ref() {
 4274            (confirm)(cx);
 4275        }
 4276
 4277        if completion.show_new_completions_on_confirm {
 4278            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4279        }
 4280
 4281        let provider = self.completion_provider.as_ref()?;
 4282        let apply_edits = provider.apply_additional_edits_for_completion(
 4283            buffer_handle,
 4284            completion.clone(),
 4285            true,
 4286            cx,
 4287        );
 4288        Some(cx.foreground_executor().spawn(async move {
 4289            apply_edits.await?;
 4290            Ok(())
 4291        }))
 4292    }
 4293
 4294    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4295        let mut context_menu = self.context_menu.write();
 4296        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4297            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4298                // Toggle if we're selecting the same one
 4299                *context_menu = None;
 4300                cx.notify();
 4301                return;
 4302            } else {
 4303                // Otherwise, clear it and start a new one
 4304                *context_menu = None;
 4305                cx.notify();
 4306            }
 4307        }
 4308        drop(context_menu);
 4309        let snapshot = self.snapshot(cx);
 4310        let deployed_from_indicator = action.deployed_from_indicator;
 4311        let mut task = self.code_actions_task.take();
 4312        let action = action.clone();
 4313        cx.spawn(|editor, mut cx| async move {
 4314            while let Some(prev_task) = task {
 4315                prev_task.await;
 4316                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4317            }
 4318
 4319            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4320                if editor.focus_handle.is_focused(cx) {
 4321                    let multibuffer_point = action
 4322                        .deployed_from_indicator
 4323                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4324                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4325                    let (buffer, buffer_row) = snapshot
 4326                        .buffer_snapshot
 4327                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4328                        .and_then(|(buffer_snapshot, range)| {
 4329                            editor
 4330                                .buffer
 4331                                .read(cx)
 4332                                .buffer(buffer_snapshot.remote_id())
 4333                                .map(|buffer| (buffer, range.start.row))
 4334                        })?;
 4335                    let (_, code_actions) = editor
 4336                        .available_code_actions
 4337                        .clone()
 4338                        .and_then(|(location, code_actions)| {
 4339                            let snapshot = location.buffer.read(cx).snapshot();
 4340                            let point_range = location.range.to_point(&snapshot);
 4341                            let point_range = point_range.start.row..=point_range.end.row;
 4342                            if point_range.contains(&buffer_row) {
 4343                                Some((location, code_actions))
 4344                            } else {
 4345                                None
 4346                            }
 4347                        })
 4348                        .unzip();
 4349                    let buffer_id = buffer.read(cx).remote_id();
 4350                    let tasks = editor
 4351                        .tasks
 4352                        .get(&(buffer_id, buffer_row))
 4353                        .map(|t| Arc::new(t.to_owned()));
 4354                    if tasks.is_none() && code_actions.is_none() {
 4355                        return None;
 4356                    }
 4357
 4358                    editor.completion_tasks.clear();
 4359                    editor.discard_inline_completion(false, cx);
 4360                    let task_context =
 4361                        tasks
 4362                            .as_ref()
 4363                            .zip(editor.project.clone())
 4364                            .map(|(tasks, project)| {
 4365                                let position = Point::new(buffer_row, tasks.column);
 4366                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4367                                let location = Location {
 4368                                    buffer: buffer.clone(),
 4369                                    range: range_start..range_start,
 4370                                };
 4371                                // Fill in the environmental variables from the tree-sitter captures
 4372                                let mut captured_task_variables = TaskVariables::default();
 4373                                for (capture_name, value) in tasks.extra_variables.clone() {
 4374                                    captured_task_variables.insert(
 4375                                        task::VariableName::Custom(capture_name.into()),
 4376                                        value.clone(),
 4377                                    );
 4378                                }
 4379                                project.update(cx, |project, cx| {
 4380                                    project.task_context_for_location(
 4381                                        captured_task_variables,
 4382                                        location,
 4383                                        cx,
 4384                                    )
 4385                                })
 4386                            });
 4387
 4388                    Some(cx.spawn(|editor, mut cx| async move {
 4389                        let task_context = match task_context {
 4390                            Some(task_context) => task_context.await,
 4391                            None => None,
 4392                        };
 4393                        let resolved_tasks =
 4394                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4395                                Arc::new(ResolvedTasks {
 4396                                    templates: tasks
 4397                                        .templates
 4398                                        .iter()
 4399                                        .filter_map(|(kind, template)| {
 4400                                            template
 4401                                                .resolve_task(&kind.to_id_base(), &task_context)
 4402                                                .map(|task| (kind.clone(), task))
 4403                                        })
 4404                                        .collect(),
 4405                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4406                                        multibuffer_point.row,
 4407                                        tasks.column,
 4408                                    )),
 4409                                })
 4410                            });
 4411                        let spawn_straight_away = resolved_tasks
 4412                            .as_ref()
 4413                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4414                            && code_actions
 4415                                .as_ref()
 4416                                .map_or(true, |actions| actions.is_empty());
 4417                        if let Some(task) = editor
 4418                            .update(&mut cx, |editor, cx| {
 4419                                *editor.context_menu.write() =
 4420                                    Some(ContextMenu::CodeActions(CodeActionsMenu {
 4421                                        buffer,
 4422                                        actions: CodeActionContents {
 4423                                            tasks: resolved_tasks,
 4424                                            actions: code_actions,
 4425                                        },
 4426                                        selected_item: Default::default(),
 4427                                        scroll_handle: UniformListScrollHandle::default(),
 4428                                        deployed_from_indicator,
 4429                                    }));
 4430                                if spawn_straight_away {
 4431                                    if let Some(task) = editor.confirm_code_action(
 4432                                        &ConfirmCodeAction { item_ix: Some(0) },
 4433                                        cx,
 4434                                    ) {
 4435                                        cx.notify();
 4436                                        return task;
 4437                                    }
 4438                                }
 4439                                cx.notify();
 4440                                Task::ready(Ok(()))
 4441                            })
 4442                            .ok()
 4443                        {
 4444                            task.await
 4445                        } else {
 4446                            Ok(())
 4447                        }
 4448                    }))
 4449                } else {
 4450                    Some(Task::ready(Ok(())))
 4451                }
 4452            })?;
 4453            if let Some(task) = spawned_test_task {
 4454                task.await?;
 4455            }
 4456
 4457            Ok::<_, anyhow::Error>(())
 4458        })
 4459        .detach_and_log_err(cx);
 4460    }
 4461
 4462    pub fn confirm_code_action(
 4463        &mut self,
 4464        action: &ConfirmCodeAction,
 4465        cx: &mut ViewContext<Self>,
 4466    ) -> Option<Task<Result<()>>> {
 4467        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4468            menu
 4469        } else {
 4470            return None;
 4471        };
 4472        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4473        let action = actions_menu.actions.get(action_ix)?;
 4474        let title = action.label();
 4475        let buffer = actions_menu.buffer;
 4476        let workspace = self.workspace()?;
 4477
 4478        match action {
 4479            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4480                workspace.update(cx, |workspace, cx| {
 4481                    workspace::tasks::schedule_resolved_task(
 4482                        workspace,
 4483                        task_source_kind,
 4484                        resolved_task,
 4485                        false,
 4486                        cx,
 4487                    );
 4488
 4489                    Some(Task::ready(Ok(())))
 4490                })
 4491            }
 4492            CodeActionsItem::CodeAction(action) => {
 4493                let apply_code_actions = workspace
 4494                    .read(cx)
 4495                    .project()
 4496                    .clone()
 4497                    .update(cx, |project, cx| {
 4498                        project.apply_code_action(buffer, action, true, cx)
 4499                    });
 4500                let workspace = workspace.downgrade();
 4501                Some(cx.spawn(|editor, cx| async move {
 4502                    let project_transaction = apply_code_actions.await?;
 4503                    Self::open_project_transaction(
 4504                        &editor,
 4505                        workspace,
 4506                        project_transaction,
 4507                        title,
 4508                        cx,
 4509                    )
 4510                    .await
 4511                }))
 4512            }
 4513        }
 4514    }
 4515
 4516    pub async fn open_project_transaction(
 4517        this: &WeakView<Editor>,
 4518        workspace: WeakView<Workspace>,
 4519        transaction: ProjectTransaction,
 4520        title: String,
 4521        mut cx: AsyncWindowContext,
 4522    ) -> Result<()> {
 4523        let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
 4524
 4525        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4526        cx.update(|cx| {
 4527            entries.sort_unstable_by_key(|(buffer, _)| {
 4528                buffer.read(cx).file().map(|f| f.path().clone())
 4529            });
 4530        })?;
 4531
 4532        // If the project transaction's edits are all contained within this editor, then
 4533        // avoid opening a new editor to display them.
 4534
 4535        if let Some((buffer, transaction)) = entries.first() {
 4536            if entries.len() == 1 {
 4537                let excerpt = this.update(&mut cx, |editor, cx| {
 4538                    editor
 4539                        .buffer()
 4540                        .read(cx)
 4541                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4542                })?;
 4543                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4544                    if excerpted_buffer == *buffer {
 4545                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4546                            let excerpt_range = excerpt_range.to_offset(buffer);
 4547                            buffer
 4548                                .edited_ranges_for_transaction::<usize>(transaction)
 4549                                .all(|range| {
 4550                                    excerpt_range.start <= range.start
 4551                                        && excerpt_range.end >= range.end
 4552                                })
 4553                        })?;
 4554
 4555                        if all_edits_within_excerpt {
 4556                            return Ok(());
 4557                        }
 4558                    }
 4559                }
 4560            }
 4561        } else {
 4562            return Ok(());
 4563        }
 4564
 4565        let mut ranges_to_highlight = Vec::new();
 4566        let excerpt_buffer = cx.new_model(|cx| {
 4567            let mut multibuffer =
 4568                MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
 4569            for (buffer_handle, transaction) in &entries {
 4570                let buffer = buffer_handle.read(cx);
 4571                ranges_to_highlight.extend(
 4572                    multibuffer.push_excerpts_with_context_lines(
 4573                        buffer_handle.clone(),
 4574                        buffer
 4575                            .edited_ranges_for_transaction::<usize>(transaction)
 4576                            .collect(),
 4577                        DEFAULT_MULTIBUFFER_CONTEXT,
 4578                        cx,
 4579                    ),
 4580                );
 4581            }
 4582            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4583            multibuffer
 4584        })?;
 4585
 4586        workspace.update(&mut cx, |workspace, cx| {
 4587            let project = workspace.project().clone();
 4588            let editor =
 4589                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4590            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, cx);
 4591            editor.update(cx, |editor, cx| {
 4592                editor.highlight_background::<Self>(
 4593                    &ranges_to_highlight,
 4594                    |theme| theme.editor_highlighted_line_background,
 4595                    cx,
 4596                );
 4597            });
 4598        })?;
 4599
 4600        Ok(())
 4601    }
 4602
 4603    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4604        let project = self.project.clone()?;
 4605        let buffer = self.buffer.read(cx);
 4606        let newest_selection = self.selections.newest_anchor().clone();
 4607        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4608        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4609        if start_buffer != end_buffer {
 4610            return None;
 4611        }
 4612
 4613        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4614            cx.background_executor()
 4615                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4616                .await;
 4617
 4618            let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
 4619                project.code_actions(&start_buffer, start..end, cx)
 4620            }) {
 4621                code_actions.await
 4622            } else {
 4623                Vec::new()
 4624            };
 4625
 4626            this.update(&mut cx, |this, cx| {
 4627                this.available_code_actions = if actions.is_empty() {
 4628                    None
 4629                } else {
 4630                    Some((
 4631                        Location {
 4632                            buffer: start_buffer,
 4633                            range: start..end,
 4634                        },
 4635                        actions.into(),
 4636                    ))
 4637                };
 4638                cx.notify();
 4639            })
 4640            .log_err();
 4641        }));
 4642        None
 4643    }
 4644
 4645    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4646        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4647            self.show_git_blame_inline = false;
 4648
 4649            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4650                cx.background_executor().timer(delay).await;
 4651
 4652                this.update(&mut cx, |this, cx| {
 4653                    this.show_git_blame_inline = true;
 4654                    cx.notify();
 4655                })
 4656                .log_err();
 4657            }));
 4658        }
 4659    }
 4660
 4661    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4662        if self.pending_rename.is_some() {
 4663            return None;
 4664        }
 4665
 4666        let project = self.project.clone()?;
 4667        let buffer = self.buffer.read(cx);
 4668        let newest_selection = self.selections.newest_anchor().clone();
 4669        let cursor_position = newest_selection.head();
 4670        let (cursor_buffer, cursor_buffer_position) =
 4671            buffer.text_anchor_for_position(cursor_position, cx)?;
 4672        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4673        if cursor_buffer != tail_buffer {
 4674            return None;
 4675        }
 4676
 4677        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4678            cx.background_executor()
 4679                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 4680                .await;
 4681
 4682            let highlights = if let Some(highlights) = project
 4683                .update(&mut cx, |project, cx| {
 4684                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4685                })
 4686                .log_err()
 4687            {
 4688                highlights.await.log_err()
 4689            } else {
 4690                None
 4691            };
 4692
 4693            if let Some(highlights) = highlights {
 4694                this.update(&mut cx, |this, cx| {
 4695                    if this.pending_rename.is_some() {
 4696                        return;
 4697                    }
 4698
 4699                    let buffer_id = cursor_position.buffer_id;
 4700                    let buffer = this.buffer.read(cx);
 4701                    if !buffer
 4702                        .text_anchor_for_position(cursor_position, cx)
 4703                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4704                    {
 4705                        return;
 4706                    }
 4707
 4708                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4709                    let mut write_ranges = Vec::new();
 4710                    let mut read_ranges = Vec::new();
 4711                    for highlight in highlights {
 4712                        for (excerpt_id, excerpt_range) in
 4713                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4714                        {
 4715                            let start = highlight
 4716                                .range
 4717                                .start
 4718                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4719                            let end = highlight
 4720                                .range
 4721                                .end
 4722                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4723                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4724                                continue;
 4725                            }
 4726
 4727                            let range = Anchor {
 4728                                buffer_id,
 4729                                excerpt_id: excerpt_id,
 4730                                text_anchor: start,
 4731                            }..Anchor {
 4732                                buffer_id,
 4733                                excerpt_id,
 4734                                text_anchor: end,
 4735                            };
 4736                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4737                                write_ranges.push(range);
 4738                            } else {
 4739                                read_ranges.push(range);
 4740                            }
 4741                        }
 4742                    }
 4743
 4744                    this.highlight_background::<DocumentHighlightRead>(
 4745                        &read_ranges,
 4746                        |theme| theme.editor_document_highlight_read_background,
 4747                        cx,
 4748                    );
 4749                    this.highlight_background::<DocumentHighlightWrite>(
 4750                        &write_ranges,
 4751                        |theme| theme.editor_document_highlight_write_background,
 4752                        cx,
 4753                    );
 4754                    cx.notify();
 4755                })
 4756                .log_err();
 4757            }
 4758        }));
 4759        None
 4760    }
 4761
 4762    fn refresh_inline_completion(
 4763        &mut self,
 4764        debounce: bool,
 4765        cx: &mut ViewContext<Self>,
 4766    ) -> Option<()> {
 4767        let provider = self.inline_completion_provider()?;
 4768        let cursor = self.selections.newest_anchor().head();
 4769        let (buffer, cursor_buffer_position) =
 4770            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4771        if !self.show_inline_completions
 4772            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4773        {
 4774            self.discard_inline_completion(false, cx);
 4775            return None;
 4776        }
 4777
 4778        self.update_visible_inline_completion(cx);
 4779        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4780        Some(())
 4781    }
 4782
 4783    fn cycle_inline_completion(
 4784        &mut self,
 4785        direction: Direction,
 4786        cx: &mut ViewContext<Self>,
 4787    ) -> Option<()> {
 4788        let provider = self.inline_completion_provider()?;
 4789        let cursor = self.selections.newest_anchor().head();
 4790        let (buffer, cursor_buffer_position) =
 4791            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4792        if !self.show_inline_completions
 4793            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4794        {
 4795            return None;
 4796        }
 4797
 4798        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4799        self.update_visible_inline_completion(cx);
 4800
 4801        Some(())
 4802    }
 4803
 4804    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4805        if !self.has_active_inline_completion(cx) {
 4806            self.refresh_inline_completion(false, cx);
 4807            return;
 4808        }
 4809
 4810        self.update_visible_inline_completion(cx);
 4811    }
 4812
 4813    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4814        self.show_cursor_names(cx);
 4815    }
 4816
 4817    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4818        self.show_cursor_names = true;
 4819        cx.notify();
 4820        cx.spawn(|this, mut cx| async move {
 4821            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4822            this.update(&mut cx, |this, cx| {
 4823                this.show_cursor_names = false;
 4824                cx.notify()
 4825            })
 4826            .ok()
 4827        })
 4828        .detach();
 4829    }
 4830
 4831    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4832        if self.has_active_inline_completion(cx) {
 4833            self.cycle_inline_completion(Direction::Next, cx);
 4834        } else {
 4835            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4836            if is_copilot_disabled {
 4837                cx.propagate();
 4838            }
 4839        }
 4840    }
 4841
 4842    pub fn previous_inline_completion(
 4843        &mut self,
 4844        _: &PreviousInlineCompletion,
 4845        cx: &mut ViewContext<Self>,
 4846    ) {
 4847        if self.has_active_inline_completion(cx) {
 4848            self.cycle_inline_completion(Direction::Prev, cx);
 4849        } else {
 4850            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4851            if is_copilot_disabled {
 4852                cx.propagate();
 4853            }
 4854        }
 4855    }
 4856
 4857    pub fn accept_inline_completion(
 4858        &mut self,
 4859        _: &AcceptInlineCompletion,
 4860        cx: &mut ViewContext<Self>,
 4861    ) {
 4862        let Some(completion) = self.take_active_inline_completion(cx) else {
 4863            return;
 4864        };
 4865        if let Some(provider) = self.inline_completion_provider() {
 4866            provider.accept(cx);
 4867        }
 4868
 4869        cx.emit(EditorEvent::InputHandled {
 4870            utf16_range_to_replace: None,
 4871            text: completion.text.to_string().into(),
 4872        });
 4873        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 4874        self.refresh_inline_completion(true, cx);
 4875        cx.notify();
 4876    }
 4877
 4878    pub fn accept_partial_inline_completion(
 4879        &mut self,
 4880        _: &AcceptPartialInlineCompletion,
 4881        cx: &mut ViewContext<Self>,
 4882    ) {
 4883        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 4884            if let Some(completion) = self.take_active_inline_completion(cx) {
 4885                let mut partial_completion = completion
 4886                    .text
 4887                    .chars()
 4888                    .by_ref()
 4889                    .take_while(|c| c.is_alphabetic())
 4890                    .collect::<String>();
 4891                if partial_completion.is_empty() {
 4892                    partial_completion = completion
 4893                        .text
 4894                        .chars()
 4895                        .by_ref()
 4896                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4897                        .collect::<String>();
 4898                }
 4899
 4900                cx.emit(EditorEvent::InputHandled {
 4901                    utf16_range_to_replace: None,
 4902                    text: partial_completion.clone().into(),
 4903                });
 4904                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4905                self.refresh_inline_completion(true, cx);
 4906                cx.notify();
 4907            }
 4908        }
 4909    }
 4910
 4911    fn discard_inline_completion(
 4912        &mut self,
 4913        should_report_inline_completion_event: bool,
 4914        cx: &mut ViewContext<Self>,
 4915    ) -> bool {
 4916        if let Some(provider) = self.inline_completion_provider() {
 4917            provider.discard(should_report_inline_completion_event, cx);
 4918        }
 4919
 4920        self.take_active_inline_completion(cx).is_some()
 4921    }
 4922
 4923    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 4924        if let Some(completion) = self.active_inline_completion.as_ref() {
 4925            let buffer = self.buffer.read(cx).read(cx);
 4926            completion.position.is_valid(&buffer)
 4927        } else {
 4928            false
 4929        }
 4930    }
 4931
 4932    fn take_active_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
 4933        let completion = self.active_inline_completion.take()?;
 4934        self.display_map.update(cx, |map, cx| {
 4935            map.splice_inlays(vec![completion.id], Default::default(), cx);
 4936        });
 4937        let buffer = self.buffer.read(cx).read(cx);
 4938
 4939        if completion.position.is_valid(&buffer) {
 4940            Some(completion)
 4941        } else {
 4942            None
 4943        }
 4944    }
 4945
 4946    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 4947        let selection = self.selections.newest_anchor();
 4948        let cursor = selection.head();
 4949
 4950        if self.context_menu.read().is_none()
 4951            && self.completion_tasks.is_empty()
 4952            && selection.start == selection.end
 4953        {
 4954            if let Some(provider) = self.inline_completion_provider() {
 4955                if let Some((buffer, cursor_buffer_position)) =
 4956                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4957                {
 4958                    if let Some(text) =
 4959                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 4960                    {
 4961                        let text = Rope::from(text);
 4962                        let mut to_remove = Vec::new();
 4963                        if let Some(completion) = self.active_inline_completion.take() {
 4964                            to_remove.push(completion.id);
 4965                        }
 4966
 4967                        let completion_inlay =
 4968                            Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
 4969                        self.active_inline_completion = Some(completion_inlay.clone());
 4970                        self.display_map.update(cx, move |map, cx| {
 4971                            map.splice_inlays(to_remove, vec![completion_inlay], cx)
 4972                        });
 4973                        cx.notify();
 4974                        return;
 4975                    }
 4976                }
 4977            }
 4978        }
 4979
 4980        self.discard_inline_completion(false, cx);
 4981    }
 4982
 4983    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4984        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4985    }
 4986
 4987    fn render_code_actions_indicator(
 4988        &self,
 4989        _style: &EditorStyle,
 4990        row: DisplayRow,
 4991        is_active: bool,
 4992        cx: &mut ViewContext<Self>,
 4993    ) -> Option<IconButton> {
 4994        if self.available_code_actions.is_some() {
 4995            Some(
 4996                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4997                    .shape(ui::IconButtonShape::Square)
 4998                    .icon_size(IconSize::XSmall)
 4999                    .icon_color(Color::Muted)
 5000                    .selected(is_active)
 5001                    .on_click(cx.listener(move |editor, _e, cx| {
 5002                        editor.focus(cx);
 5003                        editor.toggle_code_actions(
 5004                            &ToggleCodeActions {
 5005                                deployed_from_indicator: Some(row),
 5006                            },
 5007                            cx,
 5008                        );
 5009                    })),
 5010            )
 5011        } else {
 5012            None
 5013        }
 5014    }
 5015
 5016    fn clear_tasks(&mut self) {
 5017        self.tasks.clear()
 5018    }
 5019
 5020    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5021        if let Some(_) = self.tasks.insert(key, value) {
 5022            // This case should hopefully be rare, but just in case...
 5023            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5024        }
 5025    }
 5026
 5027    fn render_run_indicator(
 5028        &self,
 5029        _style: &EditorStyle,
 5030        is_active: bool,
 5031        row: DisplayRow,
 5032        cx: &mut ViewContext<Self>,
 5033    ) -> IconButton {
 5034        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5035            .shape(ui::IconButtonShape::Square)
 5036            .icon_size(IconSize::XSmall)
 5037            .icon_color(Color::Muted)
 5038            .selected(is_active)
 5039            .on_click(cx.listener(move |editor, _e, cx| {
 5040                editor.focus(cx);
 5041                editor.toggle_code_actions(
 5042                    &ToggleCodeActions {
 5043                        deployed_from_indicator: Some(row),
 5044                    },
 5045                    cx,
 5046                );
 5047            }))
 5048    }
 5049
 5050    pub fn context_menu_visible(&self) -> bool {
 5051        self.context_menu
 5052            .read()
 5053            .as_ref()
 5054            .map_or(false, |menu| menu.visible())
 5055    }
 5056
 5057    fn render_context_menu(
 5058        &self,
 5059        cursor_position: DisplayPoint,
 5060        style: &EditorStyle,
 5061        max_height: Pixels,
 5062        cx: &mut ViewContext<Editor>,
 5063    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5064        self.context_menu.read().as_ref().map(|menu| {
 5065            menu.render(
 5066                cursor_position,
 5067                style,
 5068                max_height,
 5069                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5070                cx,
 5071            )
 5072        })
 5073    }
 5074
 5075    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5076        cx.notify();
 5077        self.completion_tasks.clear();
 5078        let context_menu = self.context_menu.write().take();
 5079        if context_menu.is_some() {
 5080            self.update_visible_inline_completion(cx);
 5081        }
 5082        context_menu
 5083    }
 5084
 5085    pub fn insert_snippet(
 5086        &mut self,
 5087        insertion_ranges: &[Range<usize>],
 5088        snippet: Snippet,
 5089        cx: &mut ViewContext<Self>,
 5090    ) -> Result<()> {
 5091        struct Tabstop<T> {
 5092            is_end_tabstop: bool,
 5093            ranges: Vec<Range<T>>,
 5094        }
 5095
 5096        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5097            let snippet_text: Arc<str> = snippet.text.clone().into();
 5098            buffer.edit(
 5099                insertion_ranges
 5100                    .iter()
 5101                    .cloned()
 5102                    .map(|range| (range, snippet_text.clone())),
 5103                Some(AutoindentMode::EachLine),
 5104                cx,
 5105            );
 5106
 5107            let snapshot = &*buffer.read(cx);
 5108            let snippet = &snippet;
 5109            snippet
 5110                .tabstops
 5111                .iter()
 5112                .map(|tabstop| {
 5113                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5114                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5115                    });
 5116                    let mut tabstop_ranges = tabstop
 5117                        .iter()
 5118                        .flat_map(|tabstop_range| {
 5119                            let mut delta = 0_isize;
 5120                            insertion_ranges.iter().map(move |insertion_range| {
 5121                                let insertion_start = insertion_range.start as isize + delta;
 5122                                delta +=
 5123                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5124
 5125                                let start = ((insertion_start + tabstop_range.start) as usize)
 5126                                    .min(snapshot.len());
 5127                                let end = ((insertion_start + tabstop_range.end) as usize)
 5128                                    .min(snapshot.len());
 5129                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5130                            })
 5131                        })
 5132                        .collect::<Vec<_>>();
 5133                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5134
 5135                    Tabstop {
 5136                        is_end_tabstop,
 5137                        ranges: tabstop_ranges,
 5138                    }
 5139                })
 5140                .collect::<Vec<_>>()
 5141        });
 5142
 5143        if let Some(tabstop) = tabstops.first() {
 5144            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5145                s.select_ranges(tabstop.ranges.iter().cloned());
 5146            });
 5147
 5148            // If we're already at the last tabstop and it's at the end of the snippet,
 5149            // we're done, we don't need to keep the state around.
 5150            if !tabstop.is_end_tabstop {
 5151                let ranges = tabstops
 5152                    .into_iter()
 5153                    .map(|tabstop| tabstop.ranges)
 5154                    .collect::<Vec<_>>();
 5155                self.snippet_stack.push(SnippetState {
 5156                    active_index: 0,
 5157                    ranges,
 5158                });
 5159            }
 5160
 5161            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5162            if self.autoclose_regions.is_empty() {
 5163                let snapshot = self.buffer.read(cx).snapshot(cx);
 5164                for selection in &mut self.selections.all::<Point>(cx) {
 5165                    let selection_head = selection.head();
 5166                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5167                        continue;
 5168                    };
 5169
 5170                    let mut bracket_pair = None;
 5171                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5172                    let prev_chars = snapshot
 5173                        .reversed_chars_at(selection_head)
 5174                        .collect::<String>();
 5175                    for (pair, enabled) in scope.brackets() {
 5176                        if enabled
 5177                            && pair.close
 5178                            && prev_chars.starts_with(pair.start.as_str())
 5179                            && next_chars.starts_with(pair.end.as_str())
 5180                        {
 5181                            bracket_pair = Some(pair.clone());
 5182                            break;
 5183                        }
 5184                    }
 5185                    if let Some(pair) = bracket_pair {
 5186                        let start = snapshot.anchor_after(selection_head);
 5187                        let end = snapshot.anchor_after(selection_head);
 5188                        self.autoclose_regions.push(AutocloseRegion {
 5189                            selection_id: selection.id,
 5190                            range: start..end,
 5191                            pair,
 5192                        });
 5193                    }
 5194                }
 5195            }
 5196        }
 5197        Ok(())
 5198    }
 5199
 5200    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5201        self.move_to_snippet_tabstop(Bias::Right, cx)
 5202    }
 5203
 5204    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5205        self.move_to_snippet_tabstop(Bias::Left, cx)
 5206    }
 5207
 5208    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5209        if let Some(mut snippet) = self.snippet_stack.pop() {
 5210            match bias {
 5211                Bias::Left => {
 5212                    if snippet.active_index > 0 {
 5213                        snippet.active_index -= 1;
 5214                    } else {
 5215                        self.snippet_stack.push(snippet);
 5216                        return false;
 5217                    }
 5218                }
 5219                Bias::Right => {
 5220                    if snippet.active_index + 1 < snippet.ranges.len() {
 5221                        snippet.active_index += 1;
 5222                    } else {
 5223                        self.snippet_stack.push(snippet);
 5224                        return false;
 5225                    }
 5226                }
 5227            }
 5228            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5229                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5230                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5231                });
 5232                // If snippet state is not at the last tabstop, push it back on the stack
 5233                if snippet.active_index + 1 < snippet.ranges.len() {
 5234                    self.snippet_stack.push(snippet);
 5235                }
 5236                return true;
 5237            }
 5238        }
 5239
 5240        false
 5241    }
 5242
 5243    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5244        self.transact(cx, |this, cx| {
 5245            this.select_all(&SelectAll, cx);
 5246            this.insert("", cx);
 5247        });
 5248    }
 5249
 5250    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5251        self.transact(cx, |this, cx| {
 5252            this.select_autoclose_pair(cx);
 5253            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5254            if !this.linked_edit_ranges.is_empty() {
 5255                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5256                let snapshot = this.buffer.read(cx).snapshot(cx);
 5257
 5258                for selection in selections.iter() {
 5259                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5260                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5261                    if selection_start.buffer_id != selection_end.buffer_id {
 5262                        continue;
 5263                    }
 5264                    if let Some(ranges) =
 5265                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5266                    {
 5267                        for (buffer, entries) in ranges {
 5268                            linked_ranges.entry(buffer).or_default().extend(entries);
 5269                        }
 5270                    }
 5271                }
 5272            }
 5273
 5274            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5275            if !this.selections.line_mode {
 5276                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5277                for selection in &mut selections {
 5278                    if selection.is_empty() {
 5279                        let old_head = selection.head();
 5280                        let mut new_head =
 5281                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5282                                .to_point(&display_map);
 5283                        if let Some((buffer, line_buffer_range)) = display_map
 5284                            .buffer_snapshot
 5285                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5286                        {
 5287                            let indent_size =
 5288                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5289                            let indent_len = match indent_size.kind {
 5290                                IndentKind::Space => {
 5291                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5292                                }
 5293                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5294                            };
 5295                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5296                                let indent_len = indent_len.get();
 5297                                new_head = cmp::min(
 5298                                    new_head,
 5299                                    MultiBufferPoint::new(
 5300                                        old_head.row,
 5301                                        ((old_head.column - 1) / indent_len) * indent_len,
 5302                                    ),
 5303                                );
 5304                            }
 5305                        }
 5306
 5307                        selection.set_head(new_head, SelectionGoal::None);
 5308                    }
 5309                }
 5310            }
 5311
 5312            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5313            this.insert("", cx);
 5314            let empty_str: Arc<str> = Arc::from("");
 5315            for (buffer, edits) in linked_ranges {
 5316                let snapshot = buffer.read(cx).snapshot();
 5317                use text::ToPoint as TP;
 5318
 5319                let edits = edits
 5320                    .into_iter()
 5321                    .map(|range| {
 5322                        let end_point = TP::to_point(&range.end, &snapshot);
 5323                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5324
 5325                        if end_point == start_point {
 5326                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5327                                .saturating_sub(1);
 5328                            start_point = TP::to_point(&offset, &snapshot);
 5329                        };
 5330
 5331                        (start_point..end_point, empty_str.clone())
 5332                    })
 5333                    .sorted_by_key(|(range, _)| range.start)
 5334                    .collect::<Vec<_>>();
 5335                buffer.update(cx, |this, cx| {
 5336                    this.edit(edits, None, cx);
 5337                })
 5338            }
 5339            this.refresh_inline_completion(true, cx);
 5340            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5341        });
 5342    }
 5343
 5344    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5345        self.transact(cx, |this, cx| {
 5346            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5347                let line_mode = s.line_mode;
 5348                s.move_with(|map, selection| {
 5349                    if selection.is_empty() && !line_mode {
 5350                        let cursor = movement::right(map, selection.head());
 5351                        selection.end = cursor;
 5352                        selection.reversed = true;
 5353                        selection.goal = SelectionGoal::None;
 5354                    }
 5355                })
 5356            });
 5357            this.insert("", cx);
 5358            this.refresh_inline_completion(true, cx);
 5359        });
 5360    }
 5361
 5362    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5363        if self.move_to_prev_snippet_tabstop(cx) {
 5364            return;
 5365        }
 5366
 5367        self.outdent(&Outdent, cx);
 5368    }
 5369
 5370    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5371        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5372            return;
 5373        }
 5374
 5375        let mut selections = self.selections.all_adjusted(cx);
 5376        let buffer = self.buffer.read(cx);
 5377        let snapshot = buffer.snapshot(cx);
 5378        let rows_iter = selections.iter().map(|s| s.head().row);
 5379        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5380
 5381        let mut edits = Vec::new();
 5382        let mut prev_edited_row = 0;
 5383        let mut row_delta = 0;
 5384        for selection in &mut selections {
 5385            if selection.start.row != prev_edited_row {
 5386                row_delta = 0;
 5387            }
 5388            prev_edited_row = selection.end.row;
 5389
 5390            // If the selection is non-empty, then increase the indentation of the selected lines.
 5391            if !selection.is_empty() {
 5392                row_delta =
 5393                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5394                continue;
 5395            }
 5396
 5397            // If the selection is empty and the cursor is in the leading whitespace before the
 5398            // suggested indentation, then auto-indent the line.
 5399            let cursor = selection.head();
 5400            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5401            if let Some(suggested_indent) =
 5402                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5403            {
 5404                if cursor.column < suggested_indent.len
 5405                    && cursor.column <= current_indent.len
 5406                    && current_indent.len <= suggested_indent.len
 5407                {
 5408                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5409                    selection.end = selection.start;
 5410                    if row_delta == 0 {
 5411                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5412                            cursor.row,
 5413                            current_indent,
 5414                            suggested_indent,
 5415                        ));
 5416                        row_delta = suggested_indent.len - current_indent.len;
 5417                    }
 5418                    continue;
 5419                }
 5420            }
 5421
 5422            // Otherwise, insert a hard or soft tab.
 5423            let settings = buffer.settings_at(cursor, cx);
 5424            let tab_size = if settings.hard_tabs {
 5425                IndentSize::tab()
 5426            } else {
 5427                let tab_size = settings.tab_size.get();
 5428                let char_column = snapshot
 5429                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5430                    .flat_map(str::chars)
 5431                    .count()
 5432                    + row_delta as usize;
 5433                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5434                IndentSize::spaces(chars_to_next_tab_stop)
 5435            };
 5436            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5437            selection.end = selection.start;
 5438            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5439            row_delta += tab_size.len;
 5440        }
 5441
 5442        self.transact(cx, |this, cx| {
 5443            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5444            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5445            this.refresh_inline_completion(true, cx);
 5446        });
 5447    }
 5448
 5449    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5450        if self.read_only(cx) {
 5451            return;
 5452        }
 5453        let mut selections = self.selections.all::<Point>(cx);
 5454        let mut prev_edited_row = 0;
 5455        let mut row_delta = 0;
 5456        let mut edits = Vec::new();
 5457        let buffer = self.buffer.read(cx);
 5458        let snapshot = buffer.snapshot(cx);
 5459        for selection in &mut selections {
 5460            if selection.start.row != prev_edited_row {
 5461                row_delta = 0;
 5462            }
 5463            prev_edited_row = selection.end.row;
 5464
 5465            row_delta =
 5466                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5467        }
 5468
 5469        self.transact(cx, |this, cx| {
 5470            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5471            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5472        });
 5473    }
 5474
 5475    fn indent_selection(
 5476        buffer: &MultiBuffer,
 5477        snapshot: &MultiBufferSnapshot,
 5478        selection: &mut Selection<Point>,
 5479        edits: &mut Vec<(Range<Point>, String)>,
 5480        delta_for_start_row: u32,
 5481        cx: &AppContext,
 5482    ) -> u32 {
 5483        let settings = buffer.settings_at(selection.start, cx);
 5484        let tab_size = settings.tab_size.get();
 5485        let indent_kind = if settings.hard_tabs {
 5486            IndentKind::Tab
 5487        } else {
 5488            IndentKind::Space
 5489        };
 5490        let mut start_row = selection.start.row;
 5491        let mut end_row = selection.end.row + 1;
 5492
 5493        // If a selection ends at the beginning of a line, don't indent
 5494        // that last line.
 5495        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5496            end_row -= 1;
 5497        }
 5498
 5499        // Avoid re-indenting a row that has already been indented by a
 5500        // previous selection, but still update this selection's column
 5501        // to reflect that indentation.
 5502        if delta_for_start_row > 0 {
 5503            start_row += 1;
 5504            selection.start.column += delta_for_start_row;
 5505            if selection.end.row == selection.start.row {
 5506                selection.end.column += delta_for_start_row;
 5507            }
 5508        }
 5509
 5510        let mut delta_for_end_row = 0;
 5511        let has_multiple_rows = start_row + 1 != end_row;
 5512        for row in start_row..end_row {
 5513            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5514            let indent_delta = match (current_indent.kind, indent_kind) {
 5515                (IndentKind::Space, IndentKind::Space) => {
 5516                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5517                    IndentSize::spaces(columns_to_next_tab_stop)
 5518                }
 5519                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5520                (_, IndentKind::Tab) => IndentSize::tab(),
 5521            };
 5522
 5523            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5524                0
 5525            } else {
 5526                selection.start.column
 5527            };
 5528            let row_start = Point::new(row, start);
 5529            edits.push((
 5530                row_start..row_start,
 5531                indent_delta.chars().collect::<String>(),
 5532            ));
 5533
 5534            // Update this selection's endpoints to reflect the indentation.
 5535            if row == selection.start.row {
 5536                selection.start.column += indent_delta.len;
 5537            }
 5538            if row == selection.end.row {
 5539                selection.end.column += indent_delta.len;
 5540                delta_for_end_row = indent_delta.len;
 5541            }
 5542        }
 5543
 5544        if selection.start.row == selection.end.row {
 5545            delta_for_start_row + delta_for_end_row
 5546        } else {
 5547            delta_for_end_row
 5548        }
 5549    }
 5550
 5551    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5552        if self.read_only(cx) {
 5553            return;
 5554        }
 5555        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5556        let selections = self.selections.all::<Point>(cx);
 5557        let mut deletion_ranges = Vec::new();
 5558        let mut last_outdent = None;
 5559        {
 5560            let buffer = self.buffer.read(cx);
 5561            let snapshot = buffer.snapshot(cx);
 5562            for selection in &selections {
 5563                let settings = buffer.settings_at(selection.start, cx);
 5564                let tab_size = settings.tab_size.get();
 5565                let mut rows = selection.spanned_rows(false, &display_map);
 5566
 5567                // Avoid re-outdenting a row that has already been outdented by a
 5568                // previous selection.
 5569                if let Some(last_row) = last_outdent {
 5570                    if last_row == rows.start {
 5571                        rows.start = rows.start.next_row();
 5572                    }
 5573                }
 5574                let has_multiple_rows = rows.len() > 1;
 5575                for row in rows.iter_rows() {
 5576                    let indent_size = snapshot.indent_size_for_line(row);
 5577                    if indent_size.len > 0 {
 5578                        let deletion_len = match indent_size.kind {
 5579                            IndentKind::Space => {
 5580                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5581                                if columns_to_prev_tab_stop == 0 {
 5582                                    tab_size
 5583                                } else {
 5584                                    columns_to_prev_tab_stop
 5585                                }
 5586                            }
 5587                            IndentKind::Tab => 1,
 5588                        };
 5589                        let start = if has_multiple_rows
 5590                            || deletion_len > selection.start.column
 5591                            || indent_size.len < selection.start.column
 5592                        {
 5593                            0
 5594                        } else {
 5595                            selection.start.column - deletion_len
 5596                        };
 5597                        deletion_ranges.push(
 5598                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5599                        );
 5600                        last_outdent = Some(row);
 5601                    }
 5602                }
 5603            }
 5604        }
 5605
 5606        self.transact(cx, |this, cx| {
 5607            this.buffer.update(cx, |buffer, cx| {
 5608                let empty_str: Arc<str> = "".into();
 5609                buffer.edit(
 5610                    deletion_ranges
 5611                        .into_iter()
 5612                        .map(|range| (range, empty_str.clone())),
 5613                    None,
 5614                    cx,
 5615                );
 5616            });
 5617            let selections = this.selections.all::<usize>(cx);
 5618            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5619        });
 5620    }
 5621
 5622    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5623        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5624        let selections = self.selections.all::<Point>(cx);
 5625
 5626        let mut new_cursors = Vec::new();
 5627        let mut edit_ranges = Vec::new();
 5628        let mut selections = selections.iter().peekable();
 5629        while let Some(selection) = selections.next() {
 5630            let mut rows = selection.spanned_rows(false, &display_map);
 5631            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5632
 5633            // Accumulate contiguous regions of rows that we want to delete.
 5634            while let Some(next_selection) = selections.peek() {
 5635                let next_rows = next_selection.spanned_rows(false, &display_map);
 5636                if next_rows.start <= rows.end {
 5637                    rows.end = next_rows.end;
 5638                    selections.next().unwrap();
 5639                } else {
 5640                    break;
 5641                }
 5642            }
 5643
 5644            let buffer = &display_map.buffer_snapshot;
 5645            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5646            let edit_end;
 5647            let cursor_buffer_row;
 5648            if buffer.max_point().row >= rows.end.0 {
 5649                // If there's a line after the range, delete the \n from the end of the row range
 5650                // and position the cursor on the next line.
 5651                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5652                cursor_buffer_row = rows.end;
 5653            } else {
 5654                // If there isn't a line after the range, delete the \n from the line before the
 5655                // start of the row range and position the cursor there.
 5656                edit_start = edit_start.saturating_sub(1);
 5657                edit_end = buffer.len();
 5658                cursor_buffer_row = rows.start.previous_row();
 5659            }
 5660
 5661            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5662            *cursor.column_mut() =
 5663                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5664
 5665            new_cursors.push((
 5666                selection.id,
 5667                buffer.anchor_after(cursor.to_point(&display_map)),
 5668            ));
 5669            edit_ranges.push(edit_start..edit_end);
 5670        }
 5671
 5672        self.transact(cx, |this, cx| {
 5673            let buffer = this.buffer.update(cx, |buffer, cx| {
 5674                let empty_str: Arc<str> = "".into();
 5675                buffer.edit(
 5676                    edit_ranges
 5677                        .into_iter()
 5678                        .map(|range| (range, empty_str.clone())),
 5679                    None,
 5680                    cx,
 5681                );
 5682                buffer.snapshot(cx)
 5683            });
 5684            let new_selections = new_cursors
 5685                .into_iter()
 5686                .map(|(id, cursor)| {
 5687                    let cursor = cursor.to_point(&buffer);
 5688                    Selection {
 5689                        id,
 5690                        start: cursor,
 5691                        end: cursor,
 5692                        reversed: false,
 5693                        goal: SelectionGoal::None,
 5694                    }
 5695                })
 5696                .collect();
 5697
 5698            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5699                s.select(new_selections);
 5700            });
 5701        });
 5702    }
 5703
 5704    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5705        if self.read_only(cx) {
 5706            return;
 5707        }
 5708        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5709        for selection in self.selections.all::<Point>(cx) {
 5710            let start = MultiBufferRow(selection.start.row);
 5711            let end = if selection.start.row == selection.end.row {
 5712                MultiBufferRow(selection.start.row + 1)
 5713            } else {
 5714                MultiBufferRow(selection.end.row)
 5715            };
 5716
 5717            if let Some(last_row_range) = row_ranges.last_mut() {
 5718                if start <= last_row_range.end {
 5719                    last_row_range.end = end;
 5720                    continue;
 5721                }
 5722            }
 5723            row_ranges.push(start..end);
 5724        }
 5725
 5726        let snapshot = self.buffer.read(cx).snapshot(cx);
 5727        let mut cursor_positions = Vec::new();
 5728        for row_range in &row_ranges {
 5729            let anchor = snapshot.anchor_before(Point::new(
 5730                row_range.end.previous_row().0,
 5731                snapshot.line_len(row_range.end.previous_row()),
 5732            ));
 5733            cursor_positions.push(anchor..anchor);
 5734        }
 5735
 5736        self.transact(cx, |this, cx| {
 5737            for row_range in row_ranges.into_iter().rev() {
 5738                for row in row_range.iter_rows().rev() {
 5739                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5740                    let next_line_row = row.next_row();
 5741                    let indent = snapshot.indent_size_for_line(next_line_row);
 5742                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5743
 5744                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5745                        " "
 5746                    } else {
 5747                        ""
 5748                    };
 5749
 5750                    this.buffer.update(cx, |buffer, cx| {
 5751                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5752                    });
 5753                }
 5754            }
 5755
 5756            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5757                s.select_anchor_ranges(cursor_positions)
 5758            });
 5759        });
 5760    }
 5761
 5762    pub fn sort_lines_case_sensitive(
 5763        &mut self,
 5764        _: &SortLinesCaseSensitive,
 5765        cx: &mut ViewContext<Self>,
 5766    ) {
 5767        self.manipulate_lines(cx, |lines| lines.sort())
 5768    }
 5769
 5770    pub fn sort_lines_case_insensitive(
 5771        &mut self,
 5772        _: &SortLinesCaseInsensitive,
 5773        cx: &mut ViewContext<Self>,
 5774    ) {
 5775        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5776    }
 5777
 5778    pub fn unique_lines_case_insensitive(
 5779        &mut self,
 5780        _: &UniqueLinesCaseInsensitive,
 5781        cx: &mut ViewContext<Self>,
 5782    ) {
 5783        self.manipulate_lines(cx, |lines| {
 5784            let mut seen = HashSet::default();
 5785            lines.retain(|line| seen.insert(line.to_lowercase()));
 5786        })
 5787    }
 5788
 5789    pub fn unique_lines_case_sensitive(
 5790        &mut self,
 5791        _: &UniqueLinesCaseSensitive,
 5792        cx: &mut ViewContext<Self>,
 5793    ) {
 5794        self.manipulate_lines(cx, |lines| {
 5795            let mut seen = HashSet::default();
 5796            lines.retain(|line| seen.insert(*line));
 5797        })
 5798    }
 5799
 5800    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5801        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 5802        if !revert_changes.is_empty() {
 5803            self.transact(cx, |editor, cx| {
 5804                editor.buffer().update(cx, |multi_buffer, cx| {
 5805                    for (buffer_id, changes) in revert_changes {
 5806                        if let Some(buffer) = multi_buffer.buffer(buffer_id) {
 5807                            buffer.update(cx, |buffer, cx| {
 5808                                buffer.edit(
 5809                                    changes.into_iter().map(|(range, text)| {
 5810                                        (range, text.to_string().map(Arc::<str>::from))
 5811                                    }),
 5812                                    None,
 5813                                    cx,
 5814                                );
 5815                            });
 5816                        }
 5817                    }
 5818                });
 5819                editor.change_selections(None, cx, |selections| selections.refresh());
 5820            });
 5821        }
 5822    }
 5823
 5824    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5825        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5826            let project_path = buffer.read(cx).project_path(cx)?;
 5827            let project = self.project.as_ref()?.read(cx);
 5828            let entry = project.entry_for_path(&project_path, cx)?;
 5829            let abs_path = project.absolute_path(&project_path, cx)?;
 5830            let parent = if entry.is_symlink {
 5831                abs_path.canonicalize().ok()?
 5832            } else {
 5833                abs_path
 5834            }
 5835            .parent()?
 5836            .to_path_buf();
 5837            Some(parent)
 5838        }) {
 5839            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5840        }
 5841    }
 5842
 5843    fn gather_revert_changes(
 5844        &mut self,
 5845        selections: &[Selection<Anchor>],
 5846        cx: &mut ViewContext<'_, Editor>,
 5847    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 5848        let mut revert_changes = HashMap::default();
 5849        self.buffer.update(cx, |multi_buffer, cx| {
 5850            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 5851            for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 5852                Self::prepare_revert_change(&mut revert_changes, &multi_buffer, &hunk, cx);
 5853            }
 5854        });
 5855        revert_changes
 5856    }
 5857
 5858    fn prepare_revert_change(
 5859        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 5860        multi_buffer: &MultiBuffer,
 5861        hunk: &DiffHunk<MultiBufferRow>,
 5862        cx: &mut AppContext,
 5863    ) -> Option<()> {
 5864        let buffer = multi_buffer.buffer(hunk.buffer_id)?;
 5865        let buffer = buffer.read(cx);
 5866        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 5867        let buffer_snapshot = buffer.snapshot();
 5868        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5869        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5870            probe
 5871                .0
 5872                .start
 5873                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5874                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5875        }) {
 5876            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 5877            Some(())
 5878        } else {
 5879            None
 5880        }
 5881    }
 5882
 5883    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5884        self.manipulate_lines(cx, |lines| lines.reverse())
 5885    }
 5886
 5887    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5888        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5889    }
 5890
 5891    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5892    where
 5893        Fn: FnMut(&mut Vec<&str>),
 5894    {
 5895        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5896        let buffer = self.buffer.read(cx).snapshot(cx);
 5897
 5898        let mut edits = Vec::new();
 5899
 5900        let selections = self.selections.all::<Point>(cx);
 5901        let mut selections = selections.iter().peekable();
 5902        let mut contiguous_row_selections = Vec::new();
 5903        let mut new_selections = Vec::new();
 5904        let mut added_lines = 0;
 5905        let mut removed_lines = 0;
 5906
 5907        while let Some(selection) = selections.next() {
 5908            let (start_row, end_row) = consume_contiguous_rows(
 5909                &mut contiguous_row_selections,
 5910                selection,
 5911                &display_map,
 5912                &mut selections,
 5913            );
 5914
 5915            let start_point = Point::new(start_row.0, 0);
 5916            let end_point = Point::new(
 5917                end_row.previous_row().0,
 5918                buffer.line_len(end_row.previous_row()),
 5919            );
 5920            let text = buffer
 5921                .text_for_range(start_point..end_point)
 5922                .collect::<String>();
 5923
 5924            let mut lines = text.split('\n').collect_vec();
 5925
 5926            let lines_before = lines.len();
 5927            callback(&mut lines);
 5928            let lines_after = lines.len();
 5929
 5930            edits.push((start_point..end_point, lines.join("\n")));
 5931
 5932            // Selections must change based on added and removed line count
 5933            let start_row =
 5934                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 5935            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 5936            new_selections.push(Selection {
 5937                id: selection.id,
 5938                start: start_row,
 5939                end: end_row,
 5940                goal: SelectionGoal::None,
 5941                reversed: selection.reversed,
 5942            });
 5943
 5944            if lines_after > lines_before {
 5945                added_lines += lines_after - lines_before;
 5946            } else if lines_before > lines_after {
 5947                removed_lines += lines_before - lines_after;
 5948            }
 5949        }
 5950
 5951        self.transact(cx, |this, cx| {
 5952            let buffer = this.buffer.update(cx, |buffer, cx| {
 5953                buffer.edit(edits, None, cx);
 5954                buffer.snapshot(cx)
 5955            });
 5956
 5957            // Recalculate offsets on newly edited buffer
 5958            let new_selections = new_selections
 5959                .iter()
 5960                .map(|s| {
 5961                    let start_point = Point::new(s.start.0, 0);
 5962                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 5963                    Selection {
 5964                        id: s.id,
 5965                        start: buffer.point_to_offset(start_point),
 5966                        end: buffer.point_to_offset(end_point),
 5967                        goal: s.goal,
 5968                        reversed: s.reversed,
 5969                    }
 5970                })
 5971                .collect();
 5972
 5973            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5974                s.select(new_selections);
 5975            });
 5976
 5977            this.request_autoscroll(Autoscroll::fit(), cx);
 5978        });
 5979    }
 5980
 5981    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 5982        self.manipulate_text(cx, |text| text.to_uppercase())
 5983    }
 5984
 5985    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 5986        self.manipulate_text(cx, |text| text.to_lowercase())
 5987    }
 5988
 5989    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 5990        self.manipulate_text(cx, |text| {
 5991            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 5992            // https://github.com/rutrum/convert-case/issues/16
 5993            text.split('\n')
 5994                .map(|line| line.to_case(Case::Title))
 5995                .join("\n")
 5996        })
 5997    }
 5998
 5999    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6000        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6001    }
 6002
 6003    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6004        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6005    }
 6006
 6007    pub fn convert_to_upper_camel_case(
 6008        &mut self,
 6009        _: &ConvertToUpperCamelCase,
 6010        cx: &mut ViewContext<Self>,
 6011    ) {
 6012        self.manipulate_text(cx, |text| {
 6013            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6014            // https://github.com/rutrum/convert-case/issues/16
 6015            text.split('\n')
 6016                .map(|line| line.to_case(Case::UpperCamel))
 6017                .join("\n")
 6018        })
 6019    }
 6020
 6021    pub fn convert_to_lower_camel_case(
 6022        &mut self,
 6023        _: &ConvertToLowerCamelCase,
 6024        cx: &mut ViewContext<Self>,
 6025    ) {
 6026        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6027    }
 6028
 6029    pub fn convert_to_opposite_case(
 6030        &mut self,
 6031        _: &ConvertToOppositeCase,
 6032        cx: &mut ViewContext<Self>,
 6033    ) {
 6034        self.manipulate_text(cx, |text| {
 6035            text.chars()
 6036                .fold(String::with_capacity(text.len()), |mut t, c| {
 6037                    if c.is_uppercase() {
 6038                        t.extend(c.to_lowercase());
 6039                    } else {
 6040                        t.extend(c.to_uppercase());
 6041                    }
 6042                    t
 6043                })
 6044        })
 6045    }
 6046
 6047    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6048    where
 6049        Fn: FnMut(&str) -> String,
 6050    {
 6051        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6052        let buffer = self.buffer.read(cx).snapshot(cx);
 6053
 6054        let mut new_selections = Vec::new();
 6055        let mut edits = Vec::new();
 6056        let mut selection_adjustment = 0i32;
 6057
 6058        for selection in self.selections.all::<usize>(cx) {
 6059            let selection_is_empty = selection.is_empty();
 6060
 6061            let (start, end) = if selection_is_empty {
 6062                let word_range = movement::surrounding_word(
 6063                    &display_map,
 6064                    selection.start.to_display_point(&display_map),
 6065                );
 6066                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6067                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6068                (start, end)
 6069            } else {
 6070                (selection.start, selection.end)
 6071            };
 6072
 6073            let text = buffer.text_for_range(start..end).collect::<String>();
 6074            let old_length = text.len() as i32;
 6075            let text = callback(&text);
 6076
 6077            new_selections.push(Selection {
 6078                start: (start as i32 - selection_adjustment) as usize,
 6079                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6080                goal: SelectionGoal::None,
 6081                ..selection
 6082            });
 6083
 6084            selection_adjustment += old_length - text.len() as i32;
 6085
 6086            edits.push((start..end, text));
 6087        }
 6088
 6089        self.transact(cx, |this, cx| {
 6090            this.buffer.update(cx, |buffer, cx| {
 6091                buffer.edit(edits, None, cx);
 6092            });
 6093
 6094            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6095                s.select(new_selections);
 6096            });
 6097
 6098            this.request_autoscroll(Autoscroll::fit(), cx);
 6099        });
 6100    }
 6101
 6102    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6103        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6104        let buffer = &display_map.buffer_snapshot;
 6105        let selections = self.selections.all::<Point>(cx);
 6106
 6107        let mut edits = Vec::new();
 6108        let mut selections_iter = selections.iter().peekable();
 6109        while let Some(selection) = selections_iter.next() {
 6110            // Avoid duplicating the same lines twice.
 6111            let mut rows = selection.spanned_rows(false, &display_map);
 6112
 6113            while let Some(next_selection) = selections_iter.peek() {
 6114                let next_rows = next_selection.spanned_rows(false, &display_map);
 6115                if next_rows.start < rows.end {
 6116                    rows.end = next_rows.end;
 6117                    selections_iter.next().unwrap();
 6118                } else {
 6119                    break;
 6120                }
 6121            }
 6122
 6123            // Copy the text from the selected row region and splice it either at the start
 6124            // or end of the region.
 6125            let start = Point::new(rows.start.0, 0);
 6126            let end = Point::new(
 6127                rows.end.previous_row().0,
 6128                buffer.line_len(rows.end.previous_row()),
 6129            );
 6130            let text = buffer
 6131                .text_for_range(start..end)
 6132                .chain(Some("\n"))
 6133                .collect::<String>();
 6134            let insert_location = if upwards {
 6135                Point::new(rows.end.0, 0)
 6136            } else {
 6137                start
 6138            };
 6139            edits.push((insert_location..insert_location, text));
 6140        }
 6141
 6142        self.transact(cx, |this, cx| {
 6143            this.buffer.update(cx, |buffer, cx| {
 6144                buffer.edit(edits, None, cx);
 6145            });
 6146
 6147            this.request_autoscroll(Autoscroll::fit(), cx);
 6148        });
 6149    }
 6150
 6151    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6152        self.duplicate_line(true, cx);
 6153    }
 6154
 6155    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6156        self.duplicate_line(false, cx);
 6157    }
 6158
 6159    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6160        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6161        let buffer = self.buffer.read(cx).snapshot(cx);
 6162
 6163        let mut edits = Vec::new();
 6164        let mut unfold_ranges = Vec::new();
 6165        let mut refold_ranges = Vec::new();
 6166
 6167        let selections = self.selections.all::<Point>(cx);
 6168        let mut selections = selections.iter().peekable();
 6169        let mut contiguous_row_selections = Vec::new();
 6170        let mut new_selections = Vec::new();
 6171
 6172        while let Some(selection) = selections.next() {
 6173            // Find all the selections that span a contiguous row range
 6174            let (start_row, end_row) = consume_contiguous_rows(
 6175                &mut contiguous_row_selections,
 6176                selection,
 6177                &display_map,
 6178                &mut selections,
 6179            );
 6180
 6181            // Move the text spanned by the row range to be before the line preceding the row range
 6182            if start_row.0 > 0 {
 6183                let range_to_move = Point::new(
 6184                    start_row.previous_row().0,
 6185                    buffer.line_len(start_row.previous_row()),
 6186                )
 6187                    ..Point::new(
 6188                        end_row.previous_row().0,
 6189                        buffer.line_len(end_row.previous_row()),
 6190                    );
 6191                let insertion_point = display_map
 6192                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6193                    .0;
 6194
 6195                // Don't move lines across excerpts
 6196                if buffer
 6197                    .excerpt_boundaries_in_range((
 6198                        Bound::Excluded(insertion_point),
 6199                        Bound::Included(range_to_move.end),
 6200                    ))
 6201                    .next()
 6202                    .is_none()
 6203                {
 6204                    let text = buffer
 6205                        .text_for_range(range_to_move.clone())
 6206                        .flat_map(|s| s.chars())
 6207                        .skip(1)
 6208                        .chain(['\n'])
 6209                        .collect::<String>();
 6210
 6211                    edits.push((
 6212                        buffer.anchor_after(range_to_move.start)
 6213                            ..buffer.anchor_before(range_to_move.end),
 6214                        String::new(),
 6215                    ));
 6216                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6217                    edits.push((insertion_anchor..insertion_anchor, text));
 6218
 6219                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6220
 6221                    // Move selections up
 6222                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6223                        |mut selection| {
 6224                            selection.start.row -= row_delta;
 6225                            selection.end.row -= row_delta;
 6226                            selection
 6227                        },
 6228                    ));
 6229
 6230                    // Move folds up
 6231                    unfold_ranges.push(range_to_move.clone());
 6232                    for fold in display_map.folds_in_range(
 6233                        buffer.anchor_before(range_to_move.start)
 6234                            ..buffer.anchor_after(range_to_move.end),
 6235                    ) {
 6236                        let mut start = fold.range.start.to_point(&buffer);
 6237                        let mut end = fold.range.end.to_point(&buffer);
 6238                        start.row -= row_delta;
 6239                        end.row -= row_delta;
 6240                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6241                    }
 6242                }
 6243            }
 6244
 6245            // If we didn't move line(s), preserve the existing selections
 6246            new_selections.append(&mut contiguous_row_selections);
 6247        }
 6248
 6249        self.transact(cx, |this, cx| {
 6250            this.unfold_ranges(unfold_ranges, true, true, cx);
 6251            this.buffer.update(cx, |buffer, cx| {
 6252                for (range, text) in edits {
 6253                    buffer.edit([(range, text)], None, cx);
 6254                }
 6255            });
 6256            this.fold_ranges(refold_ranges, true, cx);
 6257            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6258                s.select(new_selections);
 6259            })
 6260        });
 6261    }
 6262
 6263    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6264        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6265        let buffer = self.buffer.read(cx).snapshot(cx);
 6266
 6267        let mut edits = Vec::new();
 6268        let mut unfold_ranges = Vec::new();
 6269        let mut refold_ranges = Vec::new();
 6270
 6271        let selections = self.selections.all::<Point>(cx);
 6272        let mut selections = selections.iter().peekable();
 6273        let mut contiguous_row_selections = Vec::new();
 6274        let mut new_selections = Vec::new();
 6275
 6276        while let Some(selection) = selections.next() {
 6277            // Find all the selections that span a contiguous row range
 6278            let (start_row, end_row) = consume_contiguous_rows(
 6279                &mut contiguous_row_selections,
 6280                selection,
 6281                &display_map,
 6282                &mut selections,
 6283            );
 6284
 6285            // Move the text spanned by the row range to be after the last line of the row range
 6286            if end_row.0 <= buffer.max_point().row {
 6287                let range_to_move =
 6288                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6289                let insertion_point = display_map
 6290                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6291                    .0;
 6292
 6293                // Don't move lines across excerpt boundaries
 6294                if buffer
 6295                    .excerpt_boundaries_in_range((
 6296                        Bound::Excluded(range_to_move.start),
 6297                        Bound::Included(insertion_point),
 6298                    ))
 6299                    .next()
 6300                    .is_none()
 6301                {
 6302                    let mut text = String::from("\n");
 6303                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6304                    text.pop(); // Drop trailing newline
 6305                    edits.push((
 6306                        buffer.anchor_after(range_to_move.start)
 6307                            ..buffer.anchor_before(range_to_move.end),
 6308                        String::new(),
 6309                    ));
 6310                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6311                    edits.push((insertion_anchor..insertion_anchor, text));
 6312
 6313                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6314
 6315                    // Move selections down
 6316                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6317                        |mut selection| {
 6318                            selection.start.row += row_delta;
 6319                            selection.end.row += row_delta;
 6320                            selection
 6321                        },
 6322                    ));
 6323
 6324                    // Move folds down
 6325                    unfold_ranges.push(range_to_move.clone());
 6326                    for fold in display_map.folds_in_range(
 6327                        buffer.anchor_before(range_to_move.start)
 6328                            ..buffer.anchor_after(range_to_move.end),
 6329                    ) {
 6330                        let mut start = fold.range.start.to_point(&buffer);
 6331                        let mut end = fold.range.end.to_point(&buffer);
 6332                        start.row += row_delta;
 6333                        end.row += row_delta;
 6334                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6335                    }
 6336                }
 6337            }
 6338
 6339            // If we didn't move line(s), preserve the existing selections
 6340            new_selections.append(&mut contiguous_row_selections);
 6341        }
 6342
 6343        self.transact(cx, |this, cx| {
 6344            this.unfold_ranges(unfold_ranges, true, true, cx);
 6345            this.buffer.update(cx, |buffer, cx| {
 6346                for (range, text) in edits {
 6347                    buffer.edit([(range, text)], None, cx);
 6348                }
 6349            });
 6350            this.fold_ranges(refold_ranges, true, cx);
 6351            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6352        });
 6353    }
 6354
 6355    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6356        let text_layout_details = &self.text_layout_details(cx);
 6357        self.transact(cx, |this, cx| {
 6358            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6359                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6360                let line_mode = s.line_mode;
 6361                s.move_with(|display_map, selection| {
 6362                    if !selection.is_empty() || line_mode {
 6363                        return;
 6364                    }
 6365
 6366                    let mut head = selection.head();
 6367                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6368                    if head.column() == display_map.line_len(head.row()) {
 6369                        transpose_offset = display_map
 6370                            .buffer_snapshot
 6371                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6372                    }
 6373
 6374                    if transpose_offset == 0 {
 6375                        return;
 6376                    }
 6377
 6378                    *head.column_mut() += 1;
 6379                    head = display_map.clip_point(head, Bias::Right);
 6380                    let goal = SelectionGoal::HorizontalPosition(
 6381                        display_map
 6382                            .x_for_display_point(head, &text_layout_details)
 6383                            .into(),
 6384                    );
 6385                    selection.collapse_to(head, goal);
 6386
 6387                    let transpose_start = display_map
 6388                        .buffer_snapshot
 6389                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6390                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6391                        let transpose_end = display_map
 6392                            .buffer_snapshot
 6393                            .clip_offset(transpose_offset + 1, Bias::Right);
 6394                        if let Some(ch) =
 6395                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6396                        {
 6397                            edits.push((transpose_start..transpose_offset, String::new()));
 6398                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6399                        }
 6400                    }
 6401                });
 6402                edits
 6403            });
 6404            this.buffer
 6405                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6406            let selections = this.selections.all::<usize>(cx);
 6407            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6408                s.select(selections);
 6409            });
 6410        });
 6411    }
 6412
 6413    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6414        let mut text = String::new();
 6415        let buffer = self.buffer.read(cx).snapshot(cx);
 6416        let mut selections = self.selections.all::<Point>(cx);
 6417        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6418        {
 6419            let max_point = buffer.max_point();
 6420            let mut is_first = true;
 6421            for selection in &mut selections {
 6422                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6423                if is_entire_line {
 6424                    selection.start = Point::new(selection.start.row, 0);
 6425                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6426                    selection.goal = SelectionGoal::None;
 6427                }
 6428                if is_first {
 6429                    is_first = false;
 6430                } else {
 6431                    text += "\n";
 6432                }
 6433                let mut len = 0;
 6434                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6435                    text.push_str(chunk);
 6436                    len += chunk.len();
 6437                }
 6438                clipboard_selections.push(ClipboardSelection {
 6439                    len,
 6440                    is_entire_line,
 6441                    first_line_indent: buffer
 6442                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6443                        .len,
 6444                });
 6445            }
 6446        }
 6447
 6448        self.transact(cx, |this, cx| {
 6449            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6450                s.select(selections);
 6451            });
 6452            this.insert("", cx);
 6453            cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6454        });
 6455    }
 6456
 6457    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6458        let selections = self.selections.all::<Point>(cx);
 6459        let buffer = self.buffer.read(cx).read(cx);
 6460        let mut text = String::new();
 6461
 6462        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6463        {
 6464            let max_point = buffer.max_point();
 6465            let mut is_first = true;
 6466            for selection in selections.iter() {
 6467                let mut start = selection.start;
 6468                let mut end = selection.end;
 6469                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6470                if is_entire_line {
 6471                    start = Point::new(start.row, 0);
 6472                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6473                }
 6474                if is_first {
 6475                    is_first = false;
 6476                } else {
 6477                    text += "\n";
 6478                }
 6479                let mut len = 0;
 6480                for chunk in buffer.text_for_range(start..end) {
 6481                    text.push_str(chunk);
 6482                    len += chunk.len();
 6483                }
 6484                clipboard_selections.push(ClipboardSelection {
 6485                    len,
 6486                    is_entire_line,
 6487                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6488                });
 6489            }
 6490        }
 6491
 6492        cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6493    }
 6494
 6495    pub fn do_paste(
 6496        &mut self,
 6497        text: &String,
 6498        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6499        handle_entire_lines: bool,
 6500        cx: &mut ViewContext<Self>,
 6501    ) {
 6502        if self.read_only(cx) {
 6503            return;
 6504        }
 6505
 6506        let clipboard_text = Cow::Borrowed(text);
 6507
 6508        self.transact(cx, |this, cx| {
 6509            if let Some(mut clipboard_selections) = clipboard_selections {
 6510                let old_selections = this.selections.all::<usize>(cx);
 6511                let all_selections_were_entire_line =
 6512                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6513                let first_selection_indent_column =
 6514                    clipboard_selections.first().map(|s| s.first_line_indent);
 6515                if clipboard_selections.len() != old_selections.len() {
 6516                    clipboard_selections.drain(..);
 6517                }
 6518
 6519                this.buffer.update(cx, |buffer, cx| {
 6520                    let snapshot = buffer.read(cx);
 6521                    let mut start_offset = 0;
 6522                    let mut edits = Vec::new();
 6523                    let mut original_indent_columns = Vec::new();
 6524                    for (ix, selection) in old_selections.iter().enumerate() {
 6525                        let to_insert;
 6526                        let entire_line;
 6527                        let original_indent_column;
 6528                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6529                            let end_offset = start_offset + clipboard_selection.len;
 6530                            to_insert = &clipboard_text[start_offset..end_offset];
 6531                            entire_line = clipboard_selection.is_entire_line;
 6532                            start_offset = end_offset + 1;
 6533                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6534                        } else {
 6535                            to_insert = clipboard_text.as_str();
 6536                            entire_line = all_selections_were_entire_line;
 6537                            original_indent_column = first_selection_indent_column
 6538                        }
 6539
 6540                        // If the corresponding selection was empty when this slice of the
 6541                        // clipboard text was written, then the entire line containing the
 6542                        // selection was copied. If this selection is also currently empty,
 6543                        // then paste the line before the current line of the buffer.
 6544                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6545                            let column = selection.start.to_point(&snapshot).column as usize;
 6546                            let line_start = selection.start - column;
 6547                            line_start..line_start
 6548                        } else {
 6549                            selection.range()
 6550                        };
 6551
 6552                        edits.push((range, to_insert));
 6553                        original_indent_columns.extend(original_indent_column);
 6554                    }
 6555                    drop(snapshot);
 6556
 6557                    buffer.edit(
 6558                        edits,
 6559                        Some(AutoindentMode::Block {
 6560                            original_indent_columns,
 6561                        }),
 6562                        cx,
 6563                    );
 6564                });
 6565
 6566                let selections = this.selections.all::<usize>(cx);
 6567                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6568            } else {
 6569                this.insert(&clipboard_text, cx);
 6570            }
 6571        });
 6572    }
 6573
 6574    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6575        if let Some(item) = cx.read_from_clipboard() {
 6576            self.do_paste(
 6577                item.text(),
 6578                item.metadata::<Vec<ClipboardSelection>>(),
 6579                true,
 6580                cx,
 6581            )
 6582        };
 6583    }
 6584
 6585    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6586        if self.read_only(cx) {
 6587            return;
 6588        }
 6589
 6590        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6591            if let Some((selections, _)) =
 6592                self.selection_history.transaction(transaction_id).cloned()
 6593            {
 6594                self.change_selections(None, cx, |s| {
 6595                    s.select_anchors(selections.to_vec());
 6596                });
 6597            }
 6598            self.request_autoscroll(Autoscroll::fit(), cx);
 6599            self.unmark_text(cx);
 6600            self.refresh_inline_completion(true, cx);
 6601            cx.emit(EditorEvent::Edited { transaction_id });
 6602            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 6603        }
 6604    }
 6605
 6606    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 6607        if self.read_only(cx) {
 6608            return;
 6609        }
 6610
 6611        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 6612            if let Some((_, Some(selections))) =
 6613                self.selection_history.transaction(transaction_id).cloned()
 6614            {
 6615                self.change_selections(None, cx, |s| {
 6616                    s.select_anchors(selections.to_vec());
 6617                });
 6618            }
 6619            self.request_autoscroll(Autoscroll::fit(), cx);
 6620            self.unmark_text(cx);
 6621            self.refresh_inline_completion(true, cx);
 6622            cx.emit(EditorEvent::Edited { transaction_id });
 6623        }
 6624    }
 6625
 6626    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 6627        self.buffer
 6628            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 6629    }
 6630
 6631    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 6632        self.buffer
 6633            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 6634    }
 6635
 6636    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 6637        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6638            let line_mode = s.line_mode;
 6639            s.move_with(|map, selection| {
 6640                let cursor = if selection.is_empty() && !line_mode {
 6641                    movement::left(map, selection.start)
 6642                } else {
 6643                    selection.start
 6644                };
 6645                selection.collapse_to(cursor, SelectionGoal::None);
 6646            });
 6647        })
 6648    }
 6649
 6650    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 6651        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6652            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 6653        })
 6654    }
 6655
 6656    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 6657        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6658            let line_mode = s.line_mode;
 6659            s.move_with(|map, selection| {
 6660                let cursor = if selection.is_empty() && !line_mode {
 6661                    movement::right(map, selection.end)
 6662                } else {
 6663                    selection.end
 6664                };
 6665                selection.collapse_to(cursor, SelectionGoal::None)
 6666            });
 6667        })
 6668    }
 6669
 6670    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 6671        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6672            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 6673        })
 6674    }
 6675
 6676    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 6677        if self.take_rename(true, cx).is_some() {
 6678            return;
 6679        }
 6680
 6681        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6682            cx.propagate();
 6683            return;
 6684        }
 6685
 6686        let text_layout_details = &self.text_layout_details(cx);
 6687        let selection_count = self.selections.count();
 6688        let first_selection = self.selections.first_anchor();
 6689
 6690        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6691            let line_mode = s.line_mode;
 6692            s.move_with(|map, selection| {
 6693                if !selection.is_empty() && !line_mode {
 6694                    selection.goal = SelectionGoal::None;
 6695                }
 6696                let (cursor, goal) = movement::up(
 6697                    map,
 6698                    selection.start,
 6699                    selection.goal,
 6700                    false,
 6701                    &text_layout_details,
 6702                );
 6703                selection.collapse_to(cursor, goal);
 6704            });
 6705        });
 6706
 6707        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6708        {
 6709            cx.propagate();
 6710        }
 6711    }
 6712
 6713    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 6714        if self.take_rename(true, cx).is_some() {
 6715            return;
 6716        }
 6717
 6718        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6719            cx.propagate();
 6720            return;
 6721        }
 6722
 6723        let text_layout_details = &self.text_layout_details(cx);
 6724
 6725        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6726            let line_mode = s.line_mode;
 6727            s.move_with(|map, selection| {
 6728                if !selection.is_empty() && !line_mode {
 6729                    selection.goal = SelectionGoal::None;
 6730                }
 6731                let (cursor, goal) = movement::up_by_rows(
 6732                    map,
 6733                    selection.start,
 6734                    action.lines,
 6735                    selection.goal,
 6736                    false,
 6737                    &text_layout_details,
 6738                );
 6739                selection.collapse_to(cursor, goal);
 6740            });
 6741        })
 6742    }
 6743
 6744    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 6745        if self.take_rename(true, cx).is_some() {
 6746            return;
 6747        }
 6748
 6749        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6750            cx.propagate();
 6751            return;
 6752        }
 6753
 6754        let text_layout_details = &self.text_layout_details(cx);
 6755
 6756        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6757            let line_mode = s.line_mode;
 6758            s.move_with(|map, selection| {
 6759                if !selection.is_empty() && !line_mode {
 6760                    selection.goal = SelectionGoal::None;
 6761                }
 6762                let (cursor, goal) = movement::down_by_rows(
 6763                    map,
 6764                    selection.start,
 6765                    action.lines,
 6766                    selection.goal,
 6767                    false,
 6768                    &text_layout_details,
 6769                );
 6770                selection.collapse_to(cursor, goal);
 6771            });
 6772        })
 6773    }
 6774
 6775    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 6776        let text_layout_details = &self.text_layout_details(cx);
 6777        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6778            s.move_heads_with(|map, head, goal| {
 6779                movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6780            })
 6781        })
 6782    }
 6783
 6784    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 6785        let text_layout_details = &self.text_layout_details(cx);
 6786        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6787            s.move_heads_with(|map, head, goal| {
 6788                movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6789            })
 6790        })
 6791    }
 6792
 6793    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 6794        let Some(row_count) = self.visible_row_count() else {
 6795            return;
 6796        };
 6797
 6798        let text_layout_details = &self.text_layout_details(cx);
 6799
 6800        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6801            s.move_heads_with(|map, head, goal| {
 6802                movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
 6803            })
 6804        })
 6805    }
 6806
 6807    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 6808        if self.take_rename(true, cx).is_some() {
 6809            return;
 6810        }
 6811
 6812        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6813            cx.propagate();
 6814            return;
 6815        }
 6816
 6817        let Some(row_count) = self.visible_row_count() else {
 6818            return;
 6819        };
 6820
 6821        let autoscroll = if action.center_cursor {
 6822            Autoscroll::center()
 6823        } else {
 6824            Autoscroll::fit()
 6825        };
 6826
 6827        let text_layout_details = &self.text_layout_details(cx);
 6828
 6829        self.change_selections(Some(autoscroll), cx, |s| {
 6830            let line_mode = s.line_mode;
 6831            s.move_with(|map, selection| {
 6832                if !selection.is_empty() && !line_mode {
 6833                    selection.goal = SelectionGoal::None;
 6834                }
 6835                let (cursor, goal) = movement::up_by_rows(
 6836                    map,
 6837                    selection.end,
 6838                    row_count,
 6839                    selection.goal,
 6840                    false,
 6841                    &text_layout_details,
 6842                );
 6843                selection.collapse_to(cursor, goal);
 6844            });
 6845        });
 6846    }
 6847
 6848    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 6849        let text_layout_details = &self.text_layout_details(cx);
 6850        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6851            s.move_heads_with(|map, head, goal| {
 6852                movement::up(map, head, goal, false, &text_layout_details)
 6853            })
 6854        })
 6855    }
 6856
 6857    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 6858        self.take_rename(true, cx);
 6859
 6860        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6861            cx.propagate();
 6862            return;
 6863        }
 6864
 6865        let text_layout_details = &self.text_layout_details(cx);
 6866        let selection_count = self.selections.count();
 6867        let first_selection = self.selections.first_anchor();
 6868
 6869        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6870            let line_mode = s.line_mode;
 6871            s.move_with(|map, selection| {
 6872                if !selection.is_empty() && !line_mode {
 6873                    selection.goal = SelectionGoal::None;
 6874                }
 6875                let (cursor, goal) = movement::down(
 6876                    map,
 6877                    selection.end,
 6878                    selection.goal,
 6879                    false,
 6880                    &text_layout_details,
 6881                );
 6882                selection.collapse_to(cursor, goal);
 6883            });
 6884        });
 6885
 6886        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6887        {
 6888            cx.propagate();
 6889        }
 6890    }
 6891
 6892    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 6893        let Some(row_count) = self.visible_row_count() else {
 6894            return;
 6895        };
 6896
 6897        let text_layout_details = &self.text_layout_details(cx);
 6898
 6899        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6900            s.move_heads_with(|map, head, goal| {
 6901                movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
 6902            })
 6903        })
 6904    }
 6905
 6906    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 6907        if self.take_rename(true, cx).is_some() {
 6908            return;
 6909        }
 6910
 6911        if self
 6912            .context_menu
 6913            .write()
 6914            .as_mut()
 6915            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 6916            .unwrap_or(false)
 6917        {
 6918            return;
 6919        }
 6920
 6921        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6922            cx.propagate();
 6923            return;
 6924        }
 6925
 6926        let Some(row_count) = self.visible_row_count() else {
 6927            return;
 6928        };
 6929
 6930        let autoscroll = if action.center_cursor {
 6931            Autoscroll::center()
 6932        } else {
 6933            Autoscroll::fit()
 6934        };
 6935
 6936        let text_layout_details = &self.text_layout_details(cx);
 6937        self.change_selections(Some(autoscroll), cx, |s| {
 6938            let line_mode = s.line_mode;
 6939            s.move_with(|map, selection| {
 6940                if !selection.is_empty() && !line_mode {
 6941                    selection.goal = SelectionGoal::None;
 6942                }
 6943                let (cursor, goal) = movement::down_by_rows(
 6944                    map,
 6945                    selection.end,
 6946                    row_count,
 6947                    selection.goal,
 6948                    false,
 6949                    &text_layout_details,
 6950                );
 6951                selection.collapse_to(cursor, goal);
 6952            });
 6953        });
 6954    }
 6955
 6956    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 6957        let text_layout_details = &self.text_layout_details(cx);
 6958        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6959            s.move_heads_with(|map, head, goal| {
 6960                movement::down(map, head, goal, false, &text_layout_details)
 6961            })
 6962        });
 6963    }
 6964
 6965    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 6966        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6967            context_menu.select_first(self.project.as_ref(), cx);
 6968        }
 6969    }
 6970
 6971    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 6972        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6973            context_menu.select_prev(self.project.as_ref(), cx);
 6974        }
 6975    }
 6976
 6977    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 6978        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6979            context_menu.select_next(self.project.as_ref(), cx);
 6980        }
 6981    }
 6982
 6983    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 6984        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6985            context_menu.select_last(self.project.as_ref(), cx);
 6986        }
 6987    }
 6988
 6989    pub fn move_to_previous_word_start(
 6990        &mut self,
 6991        _: &MoveToPreviousWordStart,
 6992        cx: &mut ViewContext<Self>,
 6993    ) {
 6994        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6995            s.move_cursors_with(|map, head, _| {
 6996                (
 6997                    movement::previous_word_start(map, head),
 6998                    SelectionGoal::None,
 6999                )
 7000            });
 7001        })
 7002    }
 7003
 7004    pub fn move_to_previous_subword_start(
 7005        &mut self,
 7006        _: &MoveToPreviousSubwordStart,
 7007        cx: &mut ViewContext<Self>,
 7008    ) {
 7009        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7010            s.move_cursors_with(|map, head, _| {
 7011                (
 7012                    movement::previous_subword_start(map, head),
 7013                    SelectionGoal::None,
 7014                )
 7015            });
 7016        })
 7017    }
 7018
 7019    pub fn select_to_previous_word_start(
 7020        &mut self,
 7021        _: &SelectToPreviousWordStart,
 7022        cx: &mut ViewContext<Self>,
 7023    ) {
 7024        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7025            s.move_heads_with(|map, head, _| {
 7026                (
 7027                    movement::previous_word_start(map, head),
 7028                    SelectionGoal::None,
 7029                )
 7030            });
 7031        })
 7032    }
 7033
 7034    pub fn select_to_previous_subword_start(
 7035        &mut self,
 7036        _: &SelectToPreviousSubwordStart,
 7037        cx: &mut ViewContext<Self>,
 7038    ) {
 7039        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7040            s.move_heads_with(|map, head, _| {
 7041                (
 7042                    movement::previous_subword_start(map, head),
 7043                    SelectionGoal::None,
 7044                )
 7045            });
 7046        })
 7047    }
 7048
 7049    pub fn delete_to_previous_word_start(
 7050        &mut self,
 7051        _: &DeleteToPreviousWordStart,
 7052        cx: &mut ViewContext<Self>,
 7053    ) {
 7054        self.transact(cx, |this, cx| {
 7055            this.select_autoclose_pair(cx);
 7056            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7057                let line_mode = s.line_mode;
 7058                s.move_with(|map, selection| {
 7059                    if selection.is_empty() && !line_mode {
 7060                        let cursor = movement::previous_word_start(map, selection.head());
 7061                        selection.set_head(cursor, SelectionGoal::None);
 7062                    }
 7063                });
 7064            });
 7065            this.insert("", cx);
 7066        });
 7067    }
 7068
 7069    pub fn delete_to_previous_subword_start(
 7070        &mut self,
 7071        _: &DeleteToPreviousSubwordStart,
 7072        cx: &mut ViewContext<Self>,
 7073    ) {
 7074        self.transact(cx, |this, cx| {
 7075            this.select_autoclose_pair(cx);
 7076            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7077                let line_mode = s.line_mode;
 7078                s.move_with(|map, selection| {
 7079                    if selection.is_empty() && !line_mode {
 7080                        let cursor = movement::previous_subword_start(map, selection.head());
 7081                        selection.set_head(cursor, SelectionGoal::None);
 7082                    }
 7083                });
 7084            });
 7085            this.insert("", cx);
 7086        });
 7087    }
 7088
 7089    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7090        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7091            s.move_cursors_with(|map, head, _| {
 7092                (movement::next_word_end(map, head), SelectionGoal::None)
 7093            });
 7094        })
 7095    }
 7096
 7097    pub fn move_to_next_subword_end(
 7098        &mut self,
 7099        _: &MoveToNextSubwordEnd,
 7100        cx: &mut ViewContext<Self>,
 7101    ) {
 7102        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7103            s.move_cursors_with(|map, head, _| {
 7104                (movement::next_subword_end(map, head), SelectionGoal::None)
 7105            });
 7106        })
 7107    }
 7108
 7109    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7110        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7111            s.move_heads_with(|map, head, _| {
 7112                (movement::next_word_end(map, head), SelectionGoal::None)
 7113            });
 7114        })
 7115    }
 7116
 7117    pub fn select_to_next_subword_end(
 7118        &mut self,
 7119        _: &SelectToNextSubwordEnd,
 7120        cx: &mut ViewContext<Self>,
 7121    ) {
 7122        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7123            s.move_heads_with(|map, head, _| {
 7124                (movement::next_subword_end(map, head), SelectionGoal::None)
 7125            });
 7126        })
 7127    }
 7128
 7129    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
 7130        self.transact(cx, |this, cx| {
 7131            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7132                let line_mode = s.line_mode;
 7133                s.move_with(|map, selection| {
 7134                    if selection.is_empty() && !line_mode {
 7135                        let cursor = movement::next_word_end(map, selection.head());
 7136                        selection.set_head(cursor, SelectionGoal::None);
 7137                    }
 7138                });
 7139            });
 7140            this.insert("", cx);
 7141        });
 7142    }
 7143
 7144    pub fn delete_to_next_subword_end(
 7145        &mut self,
 7146        _: &DeleteToNextSubwordEnd,
 7147        cx: &mut ViewContext<Self>,
 7148    ) {
 7149        self.transact(cx, |this, cx| {
 7150            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7151                s.move_with(|map, selection| {
 7152                    if selection.is_empty() {
 7153                        let cursor = movement::next_subword_end(map, selection.head());
 7154                        selection.set_head(cursor, SelectionGoal::None);
 7155                    }
 7156                });
 7157            });
 7158            this.insert("", cx);
 7159        });
 7160    }
 7161
 7162    pub fn move_to_beginning_of_line(
 7163        &mut self,
 7164        action: &MoveToBeginningOfLine,
 7165        cx: &mut ViewContext<Self>,
 7166    ) {
 7167        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7168            s.move_cursors_with(|map, head, _| {
 7169                (
 7170                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7171                    SelectionGoal::None,
 7172                )
 7173            });
 7174        })
 7175    }
 7176
 7177    pub fn select_to_beginning_of_line(
 7178        &mut self,
 7179        action: &SelectToBeginningOfLine,
 7180        cx: &mut ViewContext<Self>,
 7181    ) {
 7182        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7183            s.move_heads_with(|map, head, _| {
 7184                (
 7185                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7186                    SelectionGoal::None,
 7187                )
 7188            });
 7189        });
 7190    }
 7191
 7192    pub fn delete_to_beginning_of_line(
 7193        &mut self,
 7194        _: &DeleteToBeginningOfLine,
 7195        cx: &mut ViewContext<Self>,
 7196    ) {
 7197        self.transact(cx, |this, cx| {
 7198            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7199                s.move_with(|_, selection| {
 7200                    selection.reversed = true;
 7201                });
 7202            });
 7203
 7204            this.select_to_beginning_of_line(
 7205                &SelectToBeginningOfLine {
 7206                    stop_at_soft_wraps: false,
 7207                },
 7208                cx,
 7209            );
 7210            this.backspace(&Backspace, cx);
 7211        });
 7212    }
 7213
 7214    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7215        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7216            s.move_cursors_with(|map, head, _| {
 7217                (
 7218                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7219                    SelectionGoal::None,
 7220                )
 7221            });
 7222        })
 7223    }
 7224
 7225    pub fn select_to_end_of_line(
 7226        &mut self,
 7227        action: &SelectToEndOfLine,
 7228        cx: &mut ViewContext<Self>,
 7229    ) {
 7230        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7231            s.move_heads_with(|map, head, _| {
 7232                (
 7233                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7234                    SelectionGoal::None,
 7235                )
 7236            });
 7237        })
 7238    }
 7239
 7240    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7241        self.transact(cx, |this, cx| {
 7242            this.select_to_end_of_line(
 7243                &SelectToEndOfLine {
 7244                    stop_at_soft_wraps: false,
 7245                },
 7246                cx,
 7247            );
 7248            this.delete(&Delete, cx);
 7249        });
 7250    }
 7251
 7252    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7253        self.transact(cx, |this, cx| {
 7254            this.select_to_end_of_line(
 7255                &SelectToEndOfLine {
 7256                    stop_at_soft_wraps: false,
 7257                },
 7258                cx,
 7259            );
 7260            this.cut(&Cut, cx);
 7261        });
 7262    }
 7263
 7264    pub fn move_to_start_of_paragraph(
 7265        &mut self,
 7266        _: &MoveToStartOfParagraph,
 7267        cx: &mut ViewContext<Self>,
 7268    ) {
 7269        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7270            cx.propagate();
 7271            return;
 7272        }
 7273
 7274        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7275            s.move_with(|map, selection| {
 7276                selection.collapse_to(
 7277                    movement::start_of_paragraph(map, selection.head(), 1),
 7278                    SelectionGoal::None,
 7279                )
 7280            });
 7281        })
 7282    }
 7283
 7284    pub fn move_to_end_of_paragraph(
 7285        &mut self,
 7286        _: &MoveToEndOfParagraph,
 7287        cx: &mut ViewContext<Self>,
 7288    ) {
 7289        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7290            cx.propagate();
 7291            return;
 7292        }
 7293
 7294        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7295            s.move_with(|map, selection| {
 7296                selection.collapse_to(
 7297                    movement::end_of_paragraph(map, selection.head(), 1),
 7298                    SelectionGoal::None,
 7299                )
 7300            });
 7301        })
 7302    }
 7303
 7304    pub fn select_to_start_of_paragraph(
 7305        &mut self,
 7306        _: &SelectToStartOfParagraph,
 7307        cx: &mut ViewContext<Self>,
 7308    ) {
 7309        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7310            cx.propagate();
 7311            return;
 7312        }
 7313
 7314        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7315            s.move_heads_with(|map, head, _| {
 7316                (
 7317                    movement::start_of_paragraph(map, head, 1),
 7318                    SelectionGoal::None,
 7319                )
 7320            });
 7321        })
 7322    }
 7323
 7324    pub fn select_to_end_of_paragraph(
 7325        &mut self,
 7326        _: &SelectToEndOfParagraph,
 7327        cx: &mut ViewContext<Self>,
 7328    ) {
 7329        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7330            cx.propagate();
 7331            return;
 7332        }
 7333
 7334        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7335            s.move_heads_with(|map, head, _| {
 7336                (
 7337                    movement::end_of_paragraph(map, head, 1),
 7338                    SelectionGoal::None,
 7339                )
 7340            });
 7341        })
 7342    }
 7343
 7344    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7345        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7346            cx.propagate();
 7347            return;
 7348        }
 7349
 7350        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7351            s.select_ranges(vec![0..0]);
 7352        });
 7353    }
 7354
 7355    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7356        let mut selection = self.selections.last::<Point>(cx);
 7357        selection.set_head(Point::zero(), SelectionGoal::None);
 7358
 7359        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7360            s.select(vec![selection]);
 7361        });
 7362    }
 7363
 7364    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7365        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7366            cx.propagate();
 7367            return;
 7368        }
 7369
 7370        let cursor = self.buffer.read(cx).read(cx).len();
 7371        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7372            s.select_ranges(vec![cursor..cursor])
 7373        });
 7374    }
 7375
 7376    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7377        self.nav_history = nav_history;
 7378    }
 7379
 7380    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7381        self.nav_history.as_ref()
 7382    }
 7383
 7384    fn push_to_nav_history(
 7385        &mut self,
 7386        cursor_anchor: Anchor,
 7387        new_position: Option<Point>,
 7388        cx: &mut ViewContext<Self>,
 7389    ) {
 7390        if let Some(nav_history) = self.nav_history.as_mut() {
 7391            let buffer = self.buffer.read(cx).read(cx);
 7392            let cursor_position = cursor_anchor.to_point(&buffer);
 7393            let scroll_state = self.scroll_manager.anchor();
 7394            let scroll_top_row = scroll_state.top_row(&buffer);
 7395            drop(buffer);
 7396
 7397            if let Some(new_position) = new_position {
 7398                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7399                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7400                    return;
 7401                }
 7402            }
 7403
 7404            nav_history.push(
 7405                Some(NavigationData {
 7406                    cursor_anchor,
 7407                    cursor_position,
 7408                    scroll_anchor: scroll_state,
 7409                    scroll_top_row,
 7410                }),
 7411                cx,
 7412            );
 7413        }
 7414    }
 7415
 7416    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7417        let buffer = self.buffer.read(cx).snapshot(cx);
 7418        let mut selection = self.selections.first::<usize>(cx);
 7419        selection.set_head(buffer.len(), SelectionGoal::None);
 7420        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7421            s.select(vec![selection]);
 7422        });
 7423    }
 7424
 7425    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7426        let end = self.buffer.read(cx).read(cx).len();
 7427        self.change_selections(None, cx, |s| {
 7428            s.select_ranges(vec![0..end]);
 7429        });
 7430    }
 7431
 7432    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7433        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7434        let mut selections = self.selections.all::<Point>(cx);
 7435        let max_point = display_map.buffer_snapshot.max_point();
 7436        for selection in &mut selections {
 7437            let rows = selection.spanned_rows(true, &display_map);
 7438            selection.start = Point::new(rows.start.0, 0);
 7439            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7440            selection.reversed = false;
 7441        }
 7442        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7443            s.select(selections);
 7444        });
 7445    }
 7446
 7447    pub fn split_selection_into_lines(
 7448        &mut self,
 7449        _: &SplitSelectionIntoLines,
 7450        cx: &mut ViewContext<Self>,
 7451    ) {
 7452        let mut to_unfold = Vec::new();
 7453        let mut new_selection_ranges = Vec::new();
 7454        {
 7455            let selections = self.selections.all::<Point>(cx);
 7456            let buffer = self.buffer.read(cx).read(cx);
 7457            for selection in selections {
 7458                for row in selection.start.row..selection.end.row {
 7459                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7460                    new_selection_ranges.push(cursor..cursor);
 7461                }
 7462                new_selection_ranges.push(selection.end..selection.end);
 7463                to_unfold.push(selection.start..selection.end);
 7464            }
 7465        }
 7466        self.unfold_ranges(to_unfold, true, true, cx);
 7467        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7468            s.select_ranges(new_selection_ranges);
 7469        });
 7470    }
 7471
 7472    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7473        self.add_selection(true, cx);
 7474    }
 7475
 7476    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7477        self.add_selection(false, cx);
 7478    }
 7479
 7480    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7481        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7482        let mut selections = self.selections.all::<Point>(cx);
 7483        let text_layout_details = self.text_layout_details(cx);
 7484        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7485            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7486            let range = oldest_selection.display_range(&display_map).sorted();
 7487
 7488            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7489            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7490            let positions = start_x.min(end_x)..start_x.max(end_x);
 7491
 7492            selections.clear();
 7493            let mut stack = Vec::new();
 7494            for row in range.start.row().0..=range.end.row().0 {
 7495                if let Some(selection) = self.selections.build_columnar_selection(
 7496                    &display_map,
 7497                    DisplayRow(row),
 7498                    &positions,
 7499                    oldest_selection.reversed,
 7500                    &text_layout_details,
 7501                ) {
 7502                    stack.push(selection.id);
 7503                    selections.push(selection);
 7504                }
 7505            }
 7506
 7507            if above {
 7508                stack.reverse();
 7509            }
 7510
 7511            AddSelectionsState { above, stack }
 7512        });
 7513
 7514        let last_added_selection = *state.stack.last().unwrap();
 7515        let mut new_selections = Vec::new();
 7516        if above == state.above {
 7517            let end_row = if above {
 7518                DisplayRow(0)
 7519            } else {
 7520                display_map.max_point().row()
 7521            };
 7522
 7523            'outer: for selection in selections {
 7524                if selection.id == last_added_selection {
 7525                    let range = selection.display_range(&display_map).sorted();
 7526                    debug_assert_eq!(range.start.row(), range.end.row());
 7527                    let mut row = range.start.row();
 7528                    let positions =
 7529                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7530                            px(start)..px(end)
 7531                        } else {
 7532                            let start_x =
 7533                                display_map.x_for_display_point(range.start, &text_layout_details);
 7534                            let end_x =
 7535                                display_map.x_for_display_point(range.end, &text_layout_details);
 7536                            start_x.min(end_x)..start_x.max(end_x)
 7537                        };
 7538
 7539                    while row != end_row {
 7540                        if above {
 7541                            row.0 -= 1;
 7542                        } else {
 7543                            row.0 += 1;
 7544                        }
 7545
 7546                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7547                            &display_map,
 7548                            row,
 7549                            &positions,
 7550                            selection.reversed,
 7551                            &text_layout_details,
 7552                        ) {
 7553                            state.stack.push(new_selection.id);
 7554                            if above {
 7555                                new_selections.push(new_selection);
 7556                                new_selections.push(selection);
 7557                            } else {
 7558                                new_selections.push(selection);
 7559                                new_selections.push(new_selection);
 7560                            }
 7561
 7562                            continue 'outer;
 7563                        }
 7564                    }
 7565                }
 7566
 7567                new_selections.push(selection);
 7568            }
 7569        } else {
 7570            new_selections = selections;
 7571            new_selections.retain(|s| s.id != last_added_selection);
 7572            state.stack.pop();
 7573        }
 7574
 7575        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7576            s.select(new_selections);
 7577        });
 7578        if state.stack.len() > 1 {
 7579            self.add_selections_state = Some(state);
 7580        }
 7581    }
 7582
 7583    pub fn select_next_match_internal(
 7584        &mut self,
 7585        display_map: &DisplaySnapshot,
 7586        replace_newest: bool,
 7587        autoscroll: Option<Autoscroll>,
 7588        cx: &mut ViewContext<Self>,
 7589    ) -> Result<()> {
 7590        fn select_next_match_ranges(
 7591            this: &mut Editor,
 7592            range: Range<usize>,
 7593            replace_newest: bool,
 7594            auto_scroll: Option<Autoscroll>,
 7595            cx: &mut ViewContext<Editor>,
 7596        ) {
 7597            this.unfold_ranges([range.clone()], false, true, cx);
 7598            this.change_selections(auto_scroll, cx, |s| {
 7599                if replace_newest {
 7600                    s.delete(s.newest_anchor().id);
 7601                }
 7602                s.insert_range(range.clone());
 7603            });
 7604        }
 7605
 7606        let buffer = &display_map.buffer_snapshot;
 7607        let mut selections = self.selections.all::<usize>(cx);
 7608        if let Some(mut select_next_state) = self.select_next_state.take() {
 7609            let query = &select_next_state.query;
 7610            if !select_next_state.done {
 7611                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7612                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7613                let mut next_selected_range = None;
 7614
 7615                let bytes_after_last_selection =
 7616                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7617                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7618                let query_matches = query
 7619                    .stream_find_iter(bytes_after_last_selection)
 7620                    .map(|result| (last_selection.end, result))
 7621                    .chain(
 7622                        query
 7623                            .stream_find_iter(bytes_before_first_selection)
 7624                            .map(|result| (0, result)),
 7625                    );
 7626
 7627                for (start_offset, query_match) in query_matches {
 7628                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7629                    let offset_range =
 7630                        start_offset + query_match.start()..start_offset + query_match.end();
 7631                    let display_range = offset_range.start.to_display_point(&display_map)
 7632                        ..offset_range.end.to_display_point(&display_map);
 7633
 7634                    if !select_next_state.wordwise
 7635                        || (!movement::is_inside_word(&display_map, display_range.start)
 7636                            && !movement::is_inside_word(&display_map, display_range.end))
 7637                    {
 7638                        // TODO: This is n^2, because we might check all the selections
 7639                        if !selections
 7640                            .iter()
 7641                            .any(|selection| selection.range().overlaps(&offset_range))
 7642                        {
 7643                            next_selected_range = Some(offset_range);
 7644                            break;
 7645                        }
 7646                    }
 7647                }
 7648
 7649                if let Some(next_selected_range) = next_selected_range {
 7650                    select_next_match_ranges(
 7651                        self,
 7652                        next_selected_range,
 7653                        replace_newest,
 7654                        autoscroll,
 7655                        cx,
 7656                    );
 7657                } else {
 7658                    select_next_state.done = true;
 7659                }
 7660            }
 7661
 7662            self.select_next_state = Some(select_next_state);
 7663        } else {
 7664            let mut only_carets = true;
 7665            let mut same_text_selected = true;
 7666            let mut selected_text = None;
 7667
 7668            let mut selections_iter = selections.iter().peekable();
 7669            while let Some(selection) = selections_iter.next() {
 7670                if selection.start != selection.end {
 7671                    only_carets = false;
 7672                }
 7673
 7674                if same_text_selected {
 7675                    if selected_text.is_none() {
 7676                        selected_text =
 7677                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7678                    }
 7679
 7680                    if let Some(next_selection) = selections_iter.peek() {
 7681                        if next_selection.range().len() == selection.range().len() {
 7682                            let next_selected_text = buffer
 7683                                .text_for_range(next_selection.range())
 7684                                .collect::<String>();
 7685                            if Some(next_selected_text) != selected_text {
 7686                                same_text_selected = false;
 7687                                selected_text = None;
 7688                            }
 7689                        } else {
 7690                            same_text_selected = false;
 7691                            selected_text = None;
 7692                        }
 7693                    }
 7694                }
 7695            }
 7696
 7697            if only_carets {
 7698                for selection in &mut selections {
 7699                    let word_range = movement::surrounding_word(
 7700                        &display_map,
 7701                        selection.start.to_display_point(&display_map),
 7702                    );
 7703                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7704                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7705                    selection.goal = SelectionGoal::None;
 7706                    selection.reversed = false;
 7707                    select_next_match_ranges(
 7708                        self,
 7709                        selection.start..selection.end,
 7710                        replace_newest,
 7711                        autoscroll,
 7712                        cx,
 7713                    );
 7714                }
 7715
 7716                if selections.len() == 1 {
 7717                    let selection = selections
 7718                        .last()
 7719                        .expect("ensured that there's only one selection");
 7720                    let query = buffer
 7721                        .text_for_range(selection.start..selection.end)
 7722                        .collect::<String>();
 7723                    let is_empty = query.is_empty();
 7724                    let select_state = SelectNextState {
 7725                        query: AhoCorasick::new(&[query])?,
 7726                        wordwise: true,
 7727                        done: is_empty,
 7728                    };
 7729                    self.select_next_state = Some(select_state);
 7730                } else {
 7731                    self.select_next_state = None;
 7732                }
 7733            } else if let Some(selected_text) = selected_text {
 7734                self.select_next_state = Some(SelectNextState {
 7735                    query: AhoCorasick::new(&[selected_text])?,
 7736                    wordwise: false,
 7737                    done: false,
 7738                });
 7739                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 7740            }
 7741        }
 7742        Ok(())
 7743    }
 7744
 7745    pub fn select_all_matches(
 7746        &mut self,
 7747        _action: &SelectAllMatches,
 7748        cx: &mut ViewContext<Self>,
 7749    ) -> Result<()> {
 7750        self.push_to_selection_history();
 7751        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7752
 7753        self.select_next_match_internal(&display_map, false, None, cx)?;
 7754        let Some(select_next_state) = self.select_next_state.as_mut() else {
 7755            return Ok(());
 7756        };
 7757        if select_next_state.done {
 7758            return Ok(());
 7759        }
 7760
 7761        let mut new_selections = self.selections.all::<usize>(cx);
 7762
 7763        let buffer = &display_map.buffer_snapshot;
 7764        let query_matches = select_next_state
 7765            .query
 7766            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 7767
 7768        for query_match in query_matches {
 7769            let query_match = query_match.unwrap(); // can only fail due to I/O
 7770            let offset_range = query_match.start()..query_match.end();
 7771            let display_range = offset_range.start.to_display_point(&display_map)
 7772                ..offset_range.end.to_display_point(&display_map);
 7773
 7774            if !select_next_state.wordwise
 7775                || (!movement::is_inside_word(&display_map, display_range.start)
 7776                    && !movement::is_inside_word(&display_map, display_range.end))
 7777            {
 7778                self.selections.change_with(cx, |selections| {
 7779                    new_selections.push(Selection {
 7780                        id: selections.new_selection_id(),
 7781                        start: offset_range.start,
 7782                        end: offset_range.end,
 7783                        reversed: false,
 7784                        goal: SelectionGoal::None,
 7785                    });
 7786                });
 7787            }
 7788        }
 7789
 7790        new_selections.sort_by_key(|selection| selection.start);
 7791        let mut ix = 0;
 7792        while ix + 1 < new_selections.len() {
 7793            let current_selection = &new_selections[ix];
 7794            let next_selection = &new_selections[ix + 1];
 7795            if current_selection.range().overlaps(&next_selection.range()) {
 7796                if current_selection.id < next_selection.id {
 7797                    new_selections.remove(ix + 1);
 7798                } else {
 7799                    new_selections.remove(ix);
 7800                }
 7801            } else {
 7802                ix += 1;
 7803            }
 7804        }
 7805
 7806        select_next_state.done = true;
 7807        self.unfold_ranges(
 7808            new_selections.iter().map(|selection| selection.range()),
 7809            false,
 7810            false,
 7811            cx,
 7812        );
 7813        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 7814            selections.select(new_selections)
 7815        });
 7816
 7817        Ok(())
 7818    }
 7819
 7820    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 7821        self.push_to_selection_history();
 7822        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7823        self.select_next_match_internal(
 7824            &display_map,
 7825            action.replace_newest,
 7826            Some(Autoscroll::newest()),
 7827            cx,
 7828        )?;
 7829        Ok(())
 7830    }
 7831
 7832    pub fn select_previous(
 7833        &mut self,
 7834        action: &SelectPrevious,
 7835        cx: &mut ViewContext<Self>,
 7836    ) -> Result<()> {
 7837        self.push_to_selection_history();
 7838        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7839        let buffer = &display_map.buffer_snapshot;
 7840        let mut selections = self.selections.all::<usize>(cx);
 7841        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 7842            let query = &select_prev_state.query;
 7843            if !select_prev_state.done {
 7844                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7845                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7846                let mut next_selected_range = None;
 7847                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 7848                let bytes_before_last_selection =
 7849                    buffer.reversed_bytes_in_range(0..last_selection.start);
 7850                let bytes_after_first_selection =
 7851                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 7852                let query_matches = query
 7853                    .stream_find_iter(bytes_before_last_selection)
 7854                    .map(|result| (last_selection.start, result))
 7855                    .chain(
 7856                        query
 7857                            .stream_find_iter(bytes_after_first_selection)
 7858                            .map(|result| (buffer.len(), result)),
 7859                    );
 7860                for (end_offset, query_match) in query_matches {
 7861                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7862                    let offset_range =
 7863                        end_offset - query_match.end()..end_offset - query_match.start();
 7864                    let display_range = offset_range.start.to_display_point(&display_map)
 7865                        ..offset_range.end.to_display_point(&display_map);
 7866
 7867                    if !select_prev_state.wordwise
 7868                        || (!movement::is_inside_word(&display_map, display_range.start)
 7869                            && !movement::is_inside_word(&display_map, display_range.end))
 7870                    {
 7871                        next_selected_range = Some(offset_range);
 7872                        break;
 7873                    }
 7874                }
 7875
 7876                if let Some(next_selected_range) = next_selected_range {
 7877                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 7878                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7879                        if action.replace_newest {
 7880                            s.delete(s.newest_anchor().id);
 7881                        }
 7882                        s.insert_range(next_selected_range);
 7883                    });
 7884                } else {
 7885                    select_prev_state.done = true;
 7886                }
 7887            }
 7888
 7889            self.select_prev_state = Some(select_prev_state);
 7890        } else {
 7891            let mut only_carets = true;
 7892            let mut same_text_selected = true;
 7893            let mut selected_text = None;
 7894
 7895            let mut selections_iter = selections.iter().peekable();
 7896            while let Some(selection) = selections_iter.next() {
 7897                if selection.start != selection.end {
 7898                    only_carets = false;
 7899                }
 7900
 7901                if same_text_selected {
 7902                    if selected_text.is_none() {
 7903                        selected_text =
 7904                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7905                    }
 7906
 7907                    if let Some(next_selection) = selections_iter.peek() {
 7908                        if next_selection.range().len() == selection.range().len() {
 7909                            let next_selected_text = buffer
 7910                                .text_for_range(next_selection.range())
 7911                                .collect::<String>();
 7912                            if Some(next_selected_text) != selected_text {
 7913                                same_text_selected = false;
 7914                                selected_text = None;
 7915                            }
 7916                        } else {
 7917                            same_text_selected = false;
 7918                            selected_text = None;
 7919                        }
 7920                    }
 7921                }
 7922            }
 7923
 7924            if only_carets {
 7925                for selection in &mut selections {
 7926                    let word_range = movement::surrounding_word(
 7927                        &display_map,
 7928                        selection.start.to_display_point(&display_map),
 7929                    );
 7930                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7931                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7932                    selection.goal = SelectionGoal::None;
 7933                    selection.reversed = false;
 7934                }
 7935                if selections.len() == 1 {
 7936                    let selection = selections
 7937                        .last()
 7938                        .expect("ensured that there's only one selection");
 7939                    let query = buffer
 7940                        .text_for_range(selection.start..selection.end)
 7941                        .collect::<String>();
 7942                    let is_empty = query.is_empty();
 7943                    let select_state = SelectNextState {
 7944                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 7945                        wordwise: true,
 7946                        done: is_empty,
 7947                    };
 7948                    self.select_prev_state = Some(select_state);
 7949                } else {
 7950                    self.select_prev_state = None;
 7951                }
 7952
 7953                self.unfold_ranges(
 7954                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 7955                    false,
 7956                    true,
 7957                    cx,
 7958                );
 7959                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7960                    s.select(selections);
 7961                });
 7962            } else if let Some(selected_text) = selected_text {
 7963                self.select_prev_state = Some(SelectNextState {
 7964                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 7965                    wordwise: false,
 7966                    done: false,
 7967                });
 7968                self.select_previous(action, cx)?;
 7969            }
 7970        }
 7971        Ok(())
 7972    }
 7973
 7974    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 7975        let text_layout_details = &self.text_layout_details(cx);
 7976        self.transact(cx, |this, cx| {
 7977            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7978            let mut edits = Vec::new();
 7979            let mut selection_edit_ranges = Vec::new();
 7980            let mut last_toggled_row = None;
 7981            let snapshot = this.buffer.read(cx).read(cx);
 7982            let empty_str: Arc<str> = "".into();
 7983            let mut suffixes_inserted = Vec::new();
 7984
 7985            fn comment_prefix_range(
 7986                snapshot: &MultiBufferSnapshot,
 7987                row: MultiBufferRow,
 7988                comment_prefix: &str,
 7989                comment_prefix_whitespace: &str,
 7990            ) -> Range<Point> {
 7991                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 7992
 7993                let mut line_bytes = snapshot
 7994                    .bytes_in_range(start..snapshot.max_point())
 7995                    .flatten()
 7996                    .copied();
 7997
 7998                // If this line currently begins with the line comment prefix, then record
 7999                // the range containing the prefix.
 8000                if line_bytes
 8001                    .by_ref()
 8002                    .take(comment_prefix.len())
 8003                    .eq(comment_prefix.bytes())
 8004                {
 8005                    // Include any whitespace that matches the comment prefix.
 8006                    let matching_whitespace_len = line_bytes
 8007                        .zip(comment_prefix_whitespace.bytes())
 8008                        .take_while(|(a, b)| a == b)
 8009                        .count() as u32;
 8010                    let end = Point::new(
 8011                        start.row,
 8012                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8013                    );
 8014                    start..end
 8015                } else {
 8016                    start..start
 8017                }
 8018            }
 8019
 8020            fn comment_suffix_range(
 8021                snapshot: &MultiBufferSnapshot,
 8022                row: MultiBufferRow,
 8023                comment_suffix: &str,
 8024                comment_suffix_has_leading_space: bool,
 8025            ) -> Range<Point> {
 8026                let end = Point::new(row.0, snapshot.line_len(row));
 8027                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8028
 8029                let mut line_end_bytes = snapshot
 8030                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8031                    .flatten()
 8032                    .copied();
 8033
 8034                let leading_space_len = if suffix_start_column > 0
 8035                    && line_end_bytes.next() == Some(b' ')
 8036                    && comment_suffix_has_leading_space
 8037                {
 8038                    1
 8039                } else {
 8040                    0
 8041                };
 8042
 8043                // If this line currently begins with the line comment prefix, then record
 8044                // the range containing the prefix.
 8045                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8046                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8047                    start..end
 8048                } else {
 8049                    end..end
 8050                }
 8051            }
 8052
 8053            // TODO: Handle selections that cross excerpts
 8054            for selection in &mut selections {
 8055                let start_column = snapshot
 8056                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8057                    .len;
 8058                let language = if let Some(language) =
 8059                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8060                {
 8061                    language
 8062                } else {
 8063                    continue;
 8064                };
 8065
 8066                selection_edit_ranges.clear();
 8067
 8068                // If multiple selections contain a given row, avoid processing that
 8069                // row more than once.
 8070                let mut start_row = MultiBufferRow(selection.start.row);
 8071                if last_toggled_row == Some(start_row) {
 8072                    start_row = start_row.next_row();
 8073                }
 8074                let end_row =
 8075                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8076                        MultiBufferRow(selection.end.row - 1)
 8077                    } else {
 8078                        MultiBufferRow(selection.end.row)
 8079                    };
 8080                last_toggled_row = Some(end_row);
 8081
 8082                if start_row > end_row {
 8083                    continue;
 8084                }
 8085
 8086                // If the language has line comments, toggle those.
 8087                let full_comment_prefixes = language.line_comment_prefixes();
 8088                if !full_comment_prefixes.is_empty() {
 8089                    let first_prefix = full_comment_prefixes
 8090                        .first()
 8091                        .expect("prefixes is non-empty");
 8092                    let prefix_trimmed_lengths = full_comment_prefixes
 8093                        .iter()
 8094                        .map(|p| p.trim_end_matches(' ').len())
 8095                        .collect::<SmallVec<[usize; 4]>>();
 8096
 8097                    let mut all_selection_lines_are_comments = true;
 8098
 8099                    for row in start_row.0..=end_row.0 {
 8100                        let row = MultiBufferRow(row);
 8101                        if start_row < end_row && snapshot.is_line_blank(row) {
 8102                            continue;
 8103                        }
 8104
 8105                        let prefix_range = full_comment_prefixes
 8106                            .iter()
 8107                            .zip(prefix_trimmed_lengths.iter().copied())
 8108                            .map(|(prefix, trimmed_prefix_len)| {
 8109                                comment_prefix_range(
 8110                                    snapshot.deref(),
 8111                                    row,
 8112                                    &prefix[..trimmed_prefix_len],
 8113                                    &prefix[trimmed_prefix_len..],
 8114                                )
 8115                            })
 8116                            .max_by_key(|range| range.end.column - range.start.column)
 8117                            .expect("prefixes is non-empty");
 8118
 8119                        if prefix_range.is_empty() {
 8120                            all_selection_lines_are_comments = false;
 8121                        }
 8122
 8123                        selection_edit_ranges.push(prefix_range);
 8124                    }
 8125
 8126                    if all_selection_lines_are_comments {
 8127                        edits.extend(
 8128                            selection_edit_ranges
 8129                                .iter()
 8130                                .cloned()
 8131                                .map(|range| (range, empty_str.clone())),
 8132                        );
 8133                    } else {
 8134                        let min_column = selection_edit_ranges
 8135                            .iter()
 8136                            .map(|range| range.start.column)
 8137                            .min()
 8138                            .unwrap_or(0);
 8139                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8140                            let position = Point::new(range.start.row, min_column);
 8141                            (position..position, first_prefix.clone())
 8142                        }));
 8143                    }
 8144                } else if let Some((full_comment_prefix, comment_suffix)) =
 8145                    language.block_comment_delimiters()
 8146                {
 8147                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8148                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8149                    let prefix_range = comment_prefix_range(
 8150                        snapshot.deref(),
 8151                        start_row,
 8152                        comment_prefix,
 8153                        comment_prefix_whitespace,
 8154                    );
 8155                    let suffix_range = comment_suffix_range(
 8156                        snapshot.deref(),
 8157                        end_row,
 8158                        comment_suffix.trim_start_matches(' '),
 8159                        comment_suffix.starts_with(' '),
 8160                    );
 8161
 8162                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8163                        edits.push((
 8164                            prefix_range.start..prefix_range.start,
 8165                            full_comment_prefix.clone(),
 8166                        ));
 8167                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8168                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8169                    } else {
 8170                        edits.push((prefix_range, empty_str.clone()));
 8171                        edits.push((suffix_range, empty_str.clone()));
 8172                    }
 8173                } else {
 8174                    continue;
 8175                }
 8176            }
 8177
 8178            drop(snapshot);
 8179            this.buffer.update(cx, |buffer, cx| {
 8180                buffer.edit(edits, None, cx);
 8181            });
 8182
 8183            // Adjust selections so that they end before any comment suffixes that
 8184            // were inserted.
 8185            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8186            let mut selections = this.selections.all::<Point>(cx);
 8187            let snapshot = this.buffer.read(cx).read(cx);
 8188            for selection in &mut selections {
 8189                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8190                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8191                        Ordering::Less => {
 8192                            suffixes_inserted.next();
 8193                            continue;
 8194                        }
 8195                        Ordering::Greater => break,
 8196                        Ordering::Equal => {
 8197                            if selection.end.column == snapshot.line_len(row) {
 8198                                if selection.is_empty() {
 8199                                    selection.start.column -= suffix_len as u32;
 8200                                }
 8201                                selection.end.column -= suffix_len as u32;
 8202                            }
 8203                            break;
 8204                        }
 8205                    }
 8206                }
 8207            }
 8208
 8209            drop(snapshot);
 8210            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8211
 8212            let selections = this.selections.all::<Point>(cx);
 8213            let selections_on_single_row = selections.windows(2).all(|selections| {
 8214                selections[0].start.row == selections[1].start.row
 8215                    && selections[0].end.row == selections[1].end.row
 8216                    && selections[0].start.row == selections[0].end.row
 8217            });
 8218            let selections_selecting = selections
 8219                .iter()
 8220                .any(|selection| selection.start != selection.end);
 8221            let advance_downwards = action.advance_downwards
 8222                && selections_on_single_row
 8223                && !selections_selecting
 8224                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8225
 8226            if advance_downwards {
 8227                let snapshot = this.buffer.read(cx).snapshot(cx);
 8228
 8229                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8230                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8231                        let mut point = display_point.to_point(display_snapshot);
 8232                        point.row += 1;
 8233                        point = snapshot.clip_point(point, Bias::Left);
 8234                        let display_point = point.to_display_point(display_snapshot);
 8235                        let goal = SelectionGoal::HorizontalPosition(
 8236                            display_snapshot
 8237                                .x_for_display_point(display_point, &text_layout_details)
 8238                                .into(),
 8239                        );
 8240                        (display_point, goal)
 8241                    })
 8242                });
 8243            }
 8244        });
 8245    }
 8246
 8247    pub fn select_enclosing_symbol(
 8248        &mut self,
 8249        _: &SelectEnclosingSymbol,
 8250        cx: &mut ViewContext<Self>,
 8251    ) {
 8252        let buffer = self.buffer.read(cx).snapshot(cx);
 8253        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8254
 8255        fn update_selection(
 8256            selection: &Selection<usize>,
 8257            buffer_snap: &MultiBufferSnapshot,
 8258        ) -> Option<Selection<usize>> {
 8259            let cursor = selection.head();
 8260            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8261            for symbol in symbols.iter().rev() {
 8262                let start = symbol.range.start.to_offset(&buffer_snap);
 8263                let end = symbol.range.end.to_offset(&buffer_snap);
 8264                let new_range = start..end;
 8265                if start < selection.start || end > selection.end {
 8266                    return Some(Selection {
 8267                        id: selection.id,
 8268                        start: new_range.start,
 8269                        end: new_range.end,
 8270                        goal: SelectionGoal::None,
 8271                        reversed: selection.reversed,
 8272                    });
 8273                }
 8274            }
 8275            None
 8276        }
 8277
 8278        let mut selected_larger_symbol = false;
 8279        let new_selections = old_selections
 8280            .iter()
 8281            .map(|selection| match update_selection(selection, &buffer) {
 8282                Some(new_selection) => {
 8283                    if new_selection.range() != selection.range() {
 8284                        selected_larger_symbol = true;
 8285                    }
 8286                    new_selection
 8287                }
 8288                None => selection.clone(),
 8289            })
 8290            .collect::<Vec<_>>();
 8291
 8292        if selected_larger_symbol {
 8293            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8294                s.select(new_selections);
 8295            });
 8296        }
 8297    }
 8298
 8299    pub fn select_larger_syntax_node(
 8300        &mut self,
 8301        _: &SelectLargerSyntaxNode,
 8302        cx: &mut ViewContext<Self>,
 8303    ) {
 8304        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8305        let buffer = self.buffer.read(cx).snapshot(cx);
 8306        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8307
 8308        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8309        let mut selected_larger_node = false;
 8310        let new_selections = old_selections
 8311            .iter()
 8312            .map(|selection| {
 8313                let old_range = selection.start..selection.end;
 8314                let mut new_range = old_range.clone();
 8315                while let Some(containing_range) =
 8316                    buffer.range_for_syntax_ancestor(new_range.clone())
 8317                {
 8318                    new_range = containing_range;
 8319                    if !display_map.intersects_fold(new_range.start)
 8320                        && !display_map.intersects_fold(new_range.end)
 8321                    {
 8322                        break;
 8323                    }
 8324                }
 8325
 8326                selected_larger_node |= new_range != old_range;
 8327                Selection {
 8328                    id: selection.id,
 8329                    start: new_range.start,
 8330                    end: new_range.end,
 8331                    goal: SelectionGoal::None,
 8332                    reversed: selection.reversed,
 8333                }
 8334            })
 8335            .collect::<Vec<_>>();
 8336
 8337        if selected_larger_node {
 8338            stack.push(old_selections);
 8339            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8340                s.select(new_selections);
 8341            });
 8342        }
 8343        self.select_larger_syntax_node_stack = stack;
 8344    }
 8345
 8346    pub fn select_smaller_syntax_node(
 8347        &mut self,
 8348        _: &SelectSmallerSyntaxNode,
 8349        cx: &mut ViewContext<Self>,
 8350    ) {
 8351        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8352        if let Some(selections) = stack.pop() {
 8353            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8354                s.select(selections.to_vec());
 8355            });
 8356        }
 8357        self.select_larger_syntax_node_stack = stack;
 8358    }
 8359
 8360    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8361        if !EditorSettings::get_global(cx).gutter.runnables {
 8362            self.clear_tasks();
 8363            return Task::ready(());
 8364        }
 8365        let project = self.project.clone();
 8366        cx.spawn(|this, mut cx| async move {
 8367            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8368                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8369            }) else {
 8370                return;
 8371            };
 8372
 8373            let Some(project) = project else {
 8374                return;
 8375            };
 8376
 8377            let hide_runnables = project
 8378                .update(&mut cx, |project, cx| {
 8379                    // Do not display any test indicators in non-dev server remote projects.
 8380                    project.is_remote() && project.ssh_connection_string(cx).is_none()
 8381                })
 8382                .unwrap_or(true);
 8383            if hide_runnables {
 8384                return;
 8385            }
 8386            let new_rows =
 8387                cx.background_executor()
 8388                    .spawn({
 8389                        let snapshot = display_snapshot.clone();
 8390                        async move {
 8391                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8392                        }
 8393                    })
 8394                    .await;
 8395            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8396
 8397            this.update(&mut cx, |this, _| {
 8398                this.clear_tasks();
 8399                for (key, value) in rows {
 8400                    this.insert_tasks(key, value);
 8401                }
 8402            })
 8403            .ok();
 8404        })
 8405    }
 8406    fn fetch_runnable_ranges(
 8407        snapshot: &DisplaySnapshot,
 8408        range: Range<Anchor>,
 8409    ) -> Vec<language::RunnableRange> {
 8410        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8411    }
 8412
 8413    fn runnable_rows(
 8414        project: Model<Project>,
 8415        snapshot: DisplaySnapshot,
 8416        runnable_ranges: Vec<RunnableRange>,
 8417        mut cx: AsyncWindowContext,
 8418    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8419        runnable_ranges
 8420            .into_iter()
 8421            .filter_map(|mut runnable| {
 8422                let tasks = cx
 8423                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8424                    .ok()?;
 8425                if tasks.is_empty() {
 8426                    return None;
 8427                }
 8428
 8429                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8430
 8431                let row = snapshot
 8432                    .buffer_snapshot
 8433                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8434                    .1
 8435                    .start
 8436                    .row;
 8437
 8438                let context_range =
 8439                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8440                Some((
 8441                    (runnable.buffer_id, row),
 8442                    RunnableTasks {
 8443                        templates: tasks,
 8444                        offset: MultiBufferOffset(runnable.run_range.start),
 8445                        context_range,
 8446                        column: point.column,
 8447                        extra_variables: runnable.extra_captures,
 8448                    },
 8449                ))
 8450            })
 8451            .collect()
 8452    }
 8453
 8454    fn templates_with_tags(
 8455        project: &Model<Project>,
 8456        runnable: &mut Runnable,
 8457        cx: &WindowContext<'_>,
 8458    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8459        let (inventory, worktree_id) = project.read_with(cx, |project, cx| {
 8460            let worktree_id = project
 8461                .buffer_for_id(runnable.buffer)
 8462                .and_then(|buffer| buffer.read(cx).file())
 8463                .map(|file| WorktreeId::from_usize(file.worktree_id()));
 8464
 8465            (project.task_inventory().clone(), worktree_id)
 8466        });
 8467
 8468        let inventory = inventory.read(cx);
 8469        let tags = mem::take(&mut runnable.tags);
 8470        let mut tags: Vec<_> = tags
 8471            .into_iter()
 8472            .flat_map(|tag| {
 8473                let tag = tag.0.clone();
 8474                inventory
 8475                    .list_tasks(Some(runnable.language.clone()), worktree_id)
 8476                    .into_iter()
 8477                    .filter(move |(_, template)| {
 8478                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8479                    })
 8480            })
 8481            .sorted_by_key(|(kind, _)| kind.to_owned())
 8482            .collect();
 8483        if let Some((leading_tag_source, _)) = tags.first() {
 8484            // Strongest source wins; if we have worktree tag binding, prefer that to
 8485            // global and language bindings;
 8486            // if we have a global binding, prefer that to language binding.
 8487            let first_mismatch = tags
 8488                .iter()
 8489                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8490            if let Some(index) = first_mismatch {
 8491                tags.truncate(index);
 8492            }
 8493        }
 8494
 8495        tags
 8496    }
 8497
 8498    pub fn move_to_enclosing_bracket(
 8499        &mut self,
 8500        _: &MoveToEnclosingBracket,
 8501        cx: &mut ViewContext<Self>,
 8502    ) {
 8503        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8504            s.move_offsets_with(|snapshot, selection| {
 8505                let Some(enclosing_bracket_ranges) =
 8506                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8507                else {
 8508                    return;
 8509                };
 8510
 8511                let mut best_length = usize::MAX;
 8512                let mut best_inside = false;
 8513                let mut best_in_bracket_range = false;
 8514                let mut best_destination = None;
 8515                for (open, close) in enclosing_bracket_ranges {
 8516                    let close = close.to_inclusive();
 8517                    let length = close.end() - open.start;
 8518                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8519                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8520                        || close.contains(&selection.head());
 8521
 8522                    // If best is next to a bracket and current isn't, skip
 8523                    if !in_bracket_range && best_in_bracket_range {
 8524                        continue;
 8525                    }
 8526
 8527                    // Prefer smaller lengths unless best is inside and current isn't
 8528                    if length > best_length && (best_inside || !inside) {
 8529                        continue;
 8530                    }
 8531
 8532                    best_length = length;
 8533                    best_inside = inside;
 8534                    best_in_bracket_range = in_bracket_range;
 8535                    best_destination = Some(
 8536                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8537                            if inside {
 8538                                open.end
 8539                            } else {
 8540                                open.start
 8541                            }
 8542                        } else {
 8543                            if inside {
 8544                                *close.start()
 8545                            } else {
 8546                                *close.end()
 8547                            }
 8548                        },
 8549                    );
 8550                }
 8551
 8552                if let Some(destination) = best_destination {
 8553                    selection.collapse_to(destination, SelectionGoal::None);
 8554                }
 8555            })
 8556        });
 8557    }
 8558
 8559    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 8560        self.end_selection(cx);
 8561        self.selection_history.mode = SelectionHistoryMode::Undoing;
 8562        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 8563            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8564            self.select_next_state = entry.select_next_state;
 8565            self.select_prev_state = entry.select_prev_state;
 8566            self.add_selections_state = entry.add_selections_state;
 8567            self.request_autoscroll(Autoscroll::newest(), cx);
 8568        }
 8569        self.selection_history.mode = SelectionHistoryMode::Normal;
 8570    }
 8571
 8572    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 8573        self.end_selection(cx);
 8574        self.selection_history.mode = SelectionHistoryMode::Redoing;
 8575        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 8576            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8577            self.select_next_state = entry.select_next_state;
 8578            self.select_prev_state = entry.select_prev_state;
 8579            self.add_selections_state = entry.add_selections_state;
 8580            self.request_autoscroll(Autoscroll::newest(), cx);
 8581        }
 8582        self.selection_history.mode = SelectionHistoryMode::Normal;
 8583    }
 8584
 8585    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 8586        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 8587    }
 8588
 8589    pub fn expand_excerpts_down(
 8590        &mut self,
 8591        action: &ExpandExcerptsDown,
 8592        cx: &mut ViewContext<Self>,
 8593    ) {
 8594        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 8595    }
 8596
 8597    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 8598        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 8599    }
 8600
 8601    pub fn expand_excerpts_for_direction(
 8602        &mut self,
 8603        lines: u32,
 8604        direction: ExpandExcerptDirection,
 8605        cx: &mut ViewContext<Self>,
 8606    ) {
 8607        let selections = self.selections.disjoint_anchors();
 8608
 8609        let lines = if lines == 0 {
 8610            EditorSettings::get_global(cx).expand_excerpt_lines
 8611        } else {
 8612            lines
 8613        };
 8614
 8615        self.buffer.update(cx, |buffer, cx| {
 8616            buffer.expand_excerpts(
 8617                selections
 8618                    .into_iter()
 8619                    .map(|selection| selection.head().excerpt_id)
 8620                    .dedup(),
 8621                lines,
 8622                direction,
 8623                cx,
 8624            )
 8625        })
 8626    }
 8627
 8628    pub fn expand_excerpt(
 8629        &mut self,
 8630        excerpt: ExcerptId,
 8631        direction: ExpandExcerptDirection,
 8632        cx: &mut ViewContext<Self>,
 8633    ) {
 8634        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 8635        self.buffer.update(cx, |buffer, cx| {
 8636            buffer.expand_excerpts([excerpt], lines, direction, cx)
 8637        })
 8638    }
 8639
 8640    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8641        self.go_to_diagnostic_impl(Direction::Next, cx)
 8642    }
 8643
 8644    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8645        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8646    }
 8647
 8648    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8649        let buffer = self.buffer.read(cx).snapshot(cx);
 8650        let selection = self.selections.newest::<usize>(cx);
 8651
 8652        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8653        if direction == Direction::Next {
 8654            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8655                let (group_id, jump_to) = popover.activation_info();
 8656                if self.activate_diagnostics(group_id, cx) {
 8657                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8658                        let mut new_selection = s.newest_anchor().clone();
 8659                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 8660                        s.select_anchors(vec![new_selection.clone()]);
 8661                    });
 8662                }
 8663                return;
 8664            }
 8665        }
 8666
 8667        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 8668            active_diagnostics
 8669                .primary_range
 8670                .to_offset(&buffer)
 8671                .to_inclusive()
 8672        });
 8673        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 8674            if active_primary_range.contains(&selection.head()) {
 8675                *active_primary_range.start()
 8676            } else {
 8677                selection.head()
 8678            }
 8679        } else {
 8680            selection.head()
 8681        };
 8682        let snapshot = self.snapshot(cx);
 8683        loop {
 8684            let diagnostics = if direction == Direction::Prev {
 8685                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 8686            } else {
 8687                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 8688            }
 8689            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 8690            let group = diagnostics
 8691                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 8692                // be sorted in a stable way
 8693                // skip until we are at current active diagnostic, if it exists
 8694                .skip_while(|entry| {
 8695                    (match direction {
 8696                        Direction::Prev => entry.range.start >= search_start,
 8697                        Direction::Next => entry.range.start <= search_start,
 8698                    }) && self
 8699                        .active_diagnostics
 8700                        .as_ref()
 8701                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 8702                })
 8703                .find_map(|entry| {
 8704                    if entry.diagnostic.is_primary
 8705                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 8706                        && !entry.range.is_empty()
 8707                        // if we match with the active diagnostic, skip it
 8708                        && Some(entry.diagnostic.group_id)
 8709                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 8710                    {
 8711                        Some((entry.range, entry.diagnostic.group_id))
 8712                    } else {
 8713                        None
 8714                    }
 8715                });
 8716
 8717            if let Some((primary_range, group_id)) = group {
 8718                if self.activate_diagnostics(group_id, cx) {
 8719                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8720                        s.select(vec![Selection {
 8721                            id: selection.id,
 8722                            start: primary_range.start,
 8723                            end: primary_range.start,
 8724                            reversed: false,
 8725                            goal: SelectionGoal::None,
 8726                        }]);
 8727                    });
 8728                }
 8729                break;
 8730            } else {
 8731                // Cycle around to the start of the buffer, potentially moving back to the start of
 8732                // the currently active diagnostic.
 8733                active_primary_range.take();
 8734                if direction == Direction::Prev {
 8735                    if search_start == buffer.len() {
 8736                        break;
 8737                    } else {
 8738                        search_start = buffer.len();
 8739                    }
 8740                } else if search_start == 0 {
 8741                    break;
 8742                } else {
 8743                    search_start = 0;
 8744                }
 8745            }
 8746        }
 8747    }
 8748
 8749    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 8750        let snapshot = self
 8751            .display_map
 8752            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8753        let selection = self.selections.newest::<Point>(cx);
 8754
 8755        if !self.seek_in_direction(
 8756            &snapshot,
 8757            selection.head(),
 8758            false,
 8759            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8760                MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
 8761            ),
 8762            cx,
 8763        ) {
 8764            let wrapped_point = Point::zero();
 8765            self.seek_in_direction(
 8766                &snapshot,
 8767                wrapped_point,
 8768                true,
 8769                snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8770                    MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 8771                ),
 8772                cx,
 8773            );
 8774        }
 8775    }
 8776
 8777    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 8778        let snapshot = self
 8779            .display_map
 8780            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8781        let selection = self.selections.newest::<Point>(cx);
 8782
 8783        if !self.seek_in_direction(
 8784            &snapshot,
 8785            selection.head(),
 8786            false,
 8787            snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8788                MultiBufferRow(0)..MultiBufferRow(selection.head().row),
 8789            ),
 8790            cx,
 8791        ) {
 8792            let wrapped_point = snapshot.buffer_snapshot.max_point();
 8793            self.seek_in_direction(
 8794                &snapshot,
 8795                wrapped_point,
 8796                true,
 8797                snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8798                    MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
 8799                ),
 8800                cx,
 8801            );
 8802        }
 8803    }
 8804
 8805    fn seek_in_direction(
 8806        &mut self,
 8807        snapshot: &DisplaySnapshot,
 8808        initial_point: Point,
 8809        is_wrapped: bool,
 8810        hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
 8811        cx: &mut ViewContext<Editor>,
 8812    ) -> bool {
 8813        let display_point = initial_point.to_display_point(snapshot);
 8814        let mut hunks = hunks
 8815            .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
 8816            .filter(|hunk| {
 8817                if is_wrapped {
 8818                    true
 8819                } else {
 8820                    !hunk.contains_display_row(display_point.row())
 8821                }
 8822            })
 8823            .dedup();
 8824
 8825        if let Some(hunk) = hunks.next() {
 8826            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8827                let row = hunk.start_display_row();
 8828                let point = DisplayPoint::new(row, 0);
 8829                s.select_display_ranges([point..point]);
 8830            });
 8831
 8832            true
 8833        } else {
 8834            false
 8835        }
 8836    }
 8837
 8838    pub fn go_to_definition(
 8839        &mut self,
 8840        _: &GoToDefinition,
 8841        cx: &mut ViewContext<Self>,
 8842    ) -> Task<Result<bool>> {
 8843        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
 8844    }
 8845
 8846    pub fn go_to_implementation(
 8847        &mut self,
 8848        _: &GoToImplementation,
 8849        cx: &mut ViewContext<Self>,
 8850    ) -> Task<Result<bool>> {
 8851        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 8852    }
 8853
 8854    pub fn go_to_implementation_split(
 8855        &mut self,
 8856        _: &GoToImplementationSplit,
 8857        cx: &mut ViewContext<Self>,
 8858    ) -> Task<Result<bool>> {
 8859        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 8860    }
 8861
 8862    pub fn go_to_type_definition(
 8863        &mut self,
 8864        _: &GoToTypeDefinition,
 8865        cx: &mut ViewContext<Self>,
 8866    ) -> Task<Result<bool>> {
 8867        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 8868    }
 8869
 8870    pub fn go_to_definition_split(
 8871        &mut self,
 8872        _: &GoToDefinitionSplit,
 8873        cx: &mut ViewContext<Self>,
 8874    ) -> Task<Result<bool>> {
 8875        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 8876    }
 8877
 8878    pub fn go_to_type_definition_split(
 8879        &mut self,
 8880        _: &GoToTypeDefinitionSplit,
 8881        cx: &mut ViewContext<Self>,
 8882    ) -> Task<Result<bool>> {
 8883        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 8884    }
 8885
 8886    fn go_to_definition_of_kind(
 8887        &mut self,
 8888        kind: GotoDefinitionKind,
 8889        split: bool,
 8890        cx: &mut ViewContext<Self>,
 8891    ) -> Task<Result<bool>> {
 8892        let Some(workspace) = self.workspace() else {
 8893            return Task::ready(Ok(false));
 8894        };
 8895        let buffer = self.buffer.read(cx);
 8896        let head = self.selections.newest::<usize>(cx).head();
 8897        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 8898            text_anchor
 8899        } else {
 8900            return Task::ready(Ok(false));
 8901        };
 8902
 8903        let project = workspace.read(cx).project().clone();
 8904        let definitions = project.update(cx, |project, cx| match kind {
 8905            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 8906            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 8907            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 8908        });
 8909
 8910        cx.spawn(|editor, mut cx| async move {
 8911            let definitions = definitions.await?;
 8912            let navigated = editor
 8913                .update(&mut cx, |editor, cx| {
 8914                    editor.navigate_to_hover_links(
 8915                        Some(kind),
 8916                        definitions
 8917                            .into_iter()
 8918                            .filter(|location| {
 8919                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 8920                            })
 8921                            .map(HoverLink::Text)
 8922                            .collect::<Vec<_>>(),
 8923                        split,
 8924                        cx,
 8925                    )
 8926                })?
 8927                .await?;
 8928            anyhow::Ok(navigated)
 8929        })
 8930    }
 8931
 8932    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 8933        let position = self.selections.newest_anchor().head();
 8934        let Some((buffer, buffer_position)) =
 8935            self.buffer.read(cx).text_anchor_for_position(position, cx)
 8936        else {
 8937            return;
 8938        };
 8939
 8940        cx.spawn(|editor, mut cx| async move {
 8941            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 8942                editor.update(&mut cx, |_, cx| {
 8943                    cx.open_url(&url);
 8944                })
 8945            } else {
 8946                Ok(())
 8947            }
 8948        })
 8949        .detach();
 8950    }
 8951
 8952    pub(crate) fn navigate_to_hover_links(
 8953        &mut self,
 8954        kind: Option<GotoDefinitionKind>,
 8955        mut definitions: Vec<HoverLink>,
 8956        split: bool,
 8957        cx: &mut ViewContext<Editor>,
 8958    ) -> Task<Result<bool>> {
 8959        // If there is one definition, just open it directly
 8960        if definitions.len() == 1 {
 8961            let definition = definitions.pop().unwrap();
 8962            let target_task = match definition {
 8963                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 8964                HoverLink::InlayHint(lsp_location, server_id) => {
 8965                    self.compute_target_location(lsp_location, server_id, cx)
 8966                }
 8967                HoverLink::Url(url) => {
 8968                    cx.open_url(&url);
 8969                    Task::ready(Ok(None))
 8970                }
 8971            };
 8972            cx.spawn(|editor, mut cx| async move {
 8973                let target = target_task.await.context("target resolution task")?;
 8974                if let Some(target) = target {
 8975                    editor.update(&mut cx, |editor, cx| {
 8976                        let Some(workspace) = editor.workspace() else {
 8977                            return false;
 8978                        };
 8979                        let pane = workspace.read(cx).active_pane().clone();
 8980
 8981                        let range = target.range.to_offset(target.buffer.read(cx));
 8982                        let range = editor.range_for_match(&range);
 8983
 8984                        /// If select range has more than one line, we
 8985                        /// just point the cursor to range.start.
 8986                        fn check_multiline_range(
 8987                            buffer: &Buffer,
 8988                            range: Range<usize>,
 8989                        ) -> Range<usize> {
 8990                            if buffer.offset_to_point(range.start).row
 8991                                == buffer.offset_to_point(range.end).row
 8992                            {
 8993                                range
 8994                            } else {
 8995                                range.start..range.start
 8996                            }
 8997                        }
 8998
 8999                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9000                            let buffer = target.buffer.read(cx);
 9001                            let range = check_multiline_range(buffer, range);
 9002                            editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 9003                                s.select_ranges([range]);
 9004                            });
 9005                        } else {
 9006                            cx.window_context().defer(move |cx| {
 9007                                let target_editor: View<Self> =
 9008                                    workspace.update(cx, |workspace, cx| {
 9009                                        let pane = if split {
 9010                                            workspace.adjacent_pane(cx)
 9011                                        } else {
 9012                                            workspace.active_pane().clone()
 9013                                        };
 9014
 9015                                        workspace.open_project_item(pane, target.buffer.clone(), cx)
 9016                                    });
 9017                                target_editor.update(cx, |target_editor, cx| {
 9018                                    // When selecting a definition in a different buffer, disable the nav history
 9019                                    // to avoid creating a history entry at the previous cursor location.
 9020                                    pane.update(cx, |pane, _| pane.disable_history());
 9021                                    let buffer = target.buffer.read(cx);
 9022                                    let range = check_multiline_range(buffer, range);
 9023                                    target_editor.change_selections(
 9024                                        Some(Autoscroll::focused()),
 9025                                        cx,
 9026                                        |s| {
 9027                                            s.select_ranges([range]);
 9028                                        },
 9029                                    );
 9030                                    pane.update(cx, |pane, _| pane.enable_history());
 9031                                });
 9032                            });
 9033                        }
 9034                        true
 9035                    })
 9036                } else {
 9037                    Ok(false)
 9038                }
 9039            })
 9040        } else if !definitions.is_empty() {
 9041            let replica_id = self.replica_id(cx);
 9042            cx.spawn(|editor, mut cx| async move {
 9043                let (title, location_tasks, workspace) = editor
 9044                    .update(&mut cx, |editor, cx| {
 9045                        let tab_kind = match kind {
 9046                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9047                            _ => "Definitions",
 9048                        };
 9049                        let title = definitions
 9050                            .iter()
 9051                            .find_map(|definition| match definition {
 9052                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9053                                    let buffer = origin.buffer.read(cx);
 9054                                    format!(
 9055                                        "{} for {}",
 9056                                        tab_kind,
 9057                                        buffer
 9058                                            .text_for_range(origin.range.clone())
 9059                                            .collect::<String>()
 9060                                    )
 9061                                }),
 9062                                HoverLink::InlayHint(_, _) => None,
 9063                                HoverLink::Url(_) => None,
 9064                            })
 9065                            .unwrap_or(tab_kind.to_string());
 9066                        let location_tasks = definitions
 9067                            .into_iter()
 9068                            .map(|definition| match definition {
 9069                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9070                                HoverLink::InlayHint(lsp_location, server_id) => {
 9071                                    editor.compute_target_location(lsp_location, server_id, cx)
 9072                                }
 9073                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9074                            })
 9075                            .collect::<Vec<_>>();
 9076                        (title, location_tasks, editor.workspace().clone())
 9077                    })
 9078                    .context("location tasks preparation")?;
 9079
 9080                let locations = futures::future::join_all(location_tasks)
 9081                    .await
 9082                    .into_iter()
 9083                    .filter_map(|location| location.transpose())
 9084                    .collect::<Result<_>>()
 9085                    .context("location tasks")?;
 9086
 9087                let Some(workspace) = workspace else {
 9088                    return Ok(false);
 9089                };
 9090                let opened = workspace
 9091                    .update(&mut cx, |workspace, cx| {
 9092                        Self::open_locations_in_multibuffer(
 9093                            workspace, locations, replica_id, title, split, cx,
 9094                        )
 9095                    })
 9096                    .ok();
 9097
 9098                anyhow::Ok(opened.is_some())
 9099            })
 9100        } else {
 9101            Task::ready(Ok(false))
 9102        }
 9103    }
 9104
 9105    fn compute_target_location(
 9106        &self,
 9107        lsp_location: lsp::Location,
 9108        server_id: LanguageServerId,
 9109        cx: &mut ViewContext<Editor>,
 9110    ) -> Task<anyhow::Result<Option<Location>>> {
 9111        let Some(project) = self.project.clone() else {
 9112            return Task::Ready(Some(Ok(None)));
 9113        };
 9114
 9115        cx.spawn(move |editor, mut cx| async move {
 9116            let location_task = editor.update(&mut cx, |editor, cx| {
 9117                project.update(cx, |project, cx| {
 9118                    let language_server_name =
 9119                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 9120                            project
 9121                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 9122                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 9123                        });
 9124                    language_server_name.map(|language_server_name| {
 9125                        project.open_local_buffer_via_lsp(
 9126                            lsp_location.uri.clone(),
 9127                            server_id,
 9128                            language_server_name,
 9129                            cx,
 9130                        )
 9131                    })
 9132                })
 9133            })?;
 9134            let location = match location_task {
 9135                Some(task) => Some({
 9136                    let target_buffer_handle = task.await.context("open local buffer")?;
 9137                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9138                        let target_start = target_buffer
 9139                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9140                        let target_end = target_buffer
 9141                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9142                        target_buffer.anchor_after(target_start)
 9143                            ..target_buffer.anchor_before(target_end)
 9144                    })?;
 9145                    Location {
 9146                        buffer: target_buffer_handle,
 9147                        range,
 9148                    }
 9149                }),
 9150                None => None,
 9151            };
 9152            Ok(location)
 9153        })
 9154    }
 9155
 9156    pub fn find_all_references(
 9157        &mut self,
 9158        _: &FindAllReferences,
 9159        cx: &mut ViewContext<Self>,
 9160    ) -> Option<Task<Result<()>>> {
 9161        let multi_buffer = self.buffer.read(cx);
 9162        let selection = self.selections.newest::<usize>(cx);
 9163        let head = selection.head();
 9164
 9165        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9166        let head_anchor = multi_buffer_snapshot.anchor_at(
 9167            head,
 9168            if head < selection.tail() {
 9169                Bias::Right
 9170            } else {
 9171                Bias::Left
 9172            },
 9173        );
 9174
 9175        match self
 9176            .find_all_references_task_sources
 9177            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9178        {
 9179            Ok(_) => {
 9180                log::info!(
 9181                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9182                );
 9183                return None;
 9184            }
 9185            Err(i) => {
 9186                self.find_all_references_task_sources.insert(i, head_anchor);
 9187            }
 9188        }
 9189
 9190        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9191        let replica_id = self.replica_id(cx);
 9192        let workspace = self.workspace()?;
 9193        let project = workspace.read(cx).project().clone();
 9194        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9195        Some(cx.spawn(|editor, mut cx| async move {
 9196            let _cleanup = defer({
 9197                let mut cx = cx.clone();
 9198                move || {
 9199                    let _ = editor.update(&mut cx, |editor, _| {
 9200                        if let Ok(i) =
 9201                            editor
 9202                                .find_all_references_task_sources
 9203                                .binary_search_by(|anchor| {
 9204                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9205                                })
 9206                        {
 9207                            editor.find_all_references_task_sources.remove(i);
 9208                        }
 9209                    });
 9210                }
 9211            });
 9212
 9213            let locations = references.await?;
 9214            if locations.is_empty() {
 9215                return anyhow::Ok(());
 9216            }
 9217
 9218            workspace.update(&mut cx, |workspace, cx| {
 9219                let title = locations
 9220                    .first()
 9221                    .as_ref()
 9222                    .map(|location| {
 9223                        let buffer = location.buffer.read(cx);
 9224                        format!(
 9225                            "References to `{}`",
 9226                            buffer
 9227                                .text_for_range(location.range.clone())
 9228                                .collect::<String>()
 9229                        )
 9230                    })
 9231                    .unwrap();
 9232                Self::open_locations_in_multibuffer(
 9233                    workspace, locations, replica_id, title, false, cx,
 9234                );
 9235            })
 9236        }))
 9237    }
 9238
 9239    /// Opens a multibuffer with the given project locations in it
 9240    pub fn open_locations_in_multibuffer(
 9241        workspace: &mut Workspace,
 9242        mut locations: Vec<Location>,
 9243        replica_id: ReplicaId,
 9244        title: String,
 9245        split: bool,
 9246        cx: &mut ViewContext<Workspace>,
 9247    ) {
 9248        // If there are multiple definitions, open them in a multibuffer
 9249        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9250        let mut locations = locations.into_iter().peekable();
 9251        let mut ranges_to_highlight = Vec::new();
 9252        let capability = workspace.project().read(cx).capability();
 9253
 9254        let excerpt_buffer = cx.new_model(|cx| {
 9255            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 9256            while let Some(location) = locations.next() {
 9257                let buffer = location.buffer.read(cx);
 9258                let mut ranges_for_buffer = Vec::new();
 9259                let range = location.range.to_offset(buffer);
 9260                ranges_for_buffer.push(range.clone());
 9261
 9262                while let Some(next_location) = locations.peek() {
 9263                    if next_location.buffer == location.buffer {
 9264                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9265                        locations.next();
 9266                    } else {
 9267                        break;
 9268                    }
 9269                }
 9270
 9271                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9272                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9273                    location.buffer.clone(),
 9274                    ranges_for_buffer,
 9275                    DEFAULT_MULTIBUFFER_CONTEXT,
 9276                    cx,
 9277                ))
 9278            }
 9279
 9280            multibuffer.with_title(title)
 9281        });
 9282
 9283        let editor = cx.new_view(|cx| {
 9284            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9285        });
 9286        editor.update(cx, |editor, cx| {
 9287            if let Some(first_range) = ranges_to_highlight.first() {
 9288                editor.change_selections(None, cx, |selections| {
 9289                    selections.clear_disjoint();
 9290                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9291                });
 9292            }
 9293            editor.highlight_background::<Self>(
 9294                &ranges_to_highlight,
 9295                |theme| theme.editor_highlighted_line_background,
 9296                cx,
 9297            );
 9298        });
 9299
 9300        let item = Box::new(editor);
 9301        let item_id = item.item_id();
 9302
 9303        if split {
 9304            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9305        } else {
 9306            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9307                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9308                    pane.close_current_preview_item(cx)
 9309                } else {
 9310                    None
 9311                }
 9312            });
 9313            workspace.add_item_to_active_pane(item.clone(), destination_index, cx);
 9314        }
 9315        workspace.active_pane().update(cx, |pane, cx| {
 9316            pane.set_preview_item_id(Some(item_id), cx);
 9317        });
 9318    }
 9319
 9320    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9321        use language::ToOffset as _;
 9322
 9323        let project = self.project.clone()?;
 9324        let selection = self.selections.newest_anchor().clone();
 9325        let (cursor_buffer, cursor_buffer_position) = self
 9326            .buffer
 9327            .read(cx)
 9328            .text_anchor_for_position(selection.head(), cx)?;
 9329        let (tail_buffer, cursor_buffer_position_end) = self
 9330            .buffer
 9331            .read(cx)
 9332            .text_anchor_for_position(selection.tail(), cx)?;
 9333        if tail_buffer != cursor_buffer {
 9334            return None;
 9335        }
 9336
 9337        let snapshot = cursor_buffer.read(cx).snapshot();
 9338        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9339        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9340        let prepare_rename = project.update(cx, |project, cx| {
 9341            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 9342        });
 9343        drop(snapshot);
 9344
 9345        Some(cx.spawn(|this, mut cx| async move {
 9346            let rename_range = if let Some(range) = prepare_rename.await? {
 9347                Some(range)
 9348            } else {
 9349                this.update(&mut cx, |this, cx| {
 9350                    let buffer = this.buffer.read(cx).snapshot(cx);
 9351                    let mut buffer_highlights = this
 9352                        .document_highlights_for_position(selection.head(), &buffer)
 9353                        .filter(|highlight| {
 9354                            highlight.start.excerpt_id == selection.head().excerpt_id
 9355                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9356                        });
 9357                    buffer_highlights
 9358                        .next()
 9359                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9360                })?
 9361            };
 9362            if let Some(rename_range) = rename_range {
 9363                this.update(&mut cx, |this, cx| {
 9364                    let snapshot = cursor_buffer.read(cx).snapshot();
 9365                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9366                    let cursor_offset_in_rename_range =
 9367                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9368                    let cursor_offset_in_rename_range_end =
 9369                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9370
 9371                    this.take_rename(false, cx);
 9372                    let buffer = this.buffer.read(cx).read(cx);
 9373                    let cursor_offset = selection.head().to_offset(&buffer);
 9374                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9375                    let rename_end = rename_start + rename_buffer_range.len();
 9376                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9377                    let mut old_highlight_id = None;
 9378                    let old_name: Arc<str> = buffer
 9379                        .chunks(rename_start..rename_end, true)
 9380                        .map(|chunk| {
 9381                            if old_highlight_id.is_none() {
 9382                                old_highlight_id = chunk.syntax_highlight_id;
 9383                            }
 9384                            chunk.text
 9385                        })
 9386                        .collect::<String>()
 9387                        .into();
 9388
 9389                    drop(buffer);
 9390
 9391                    // Position the selection in the rename editor so that it matches the current selection.
 9392                    this.show_local_selections = false;
 9393                    let rename_editor = cx.new_view(|cx| {
 9394                        let mut editor = Editor::single_line(cx);
 9395                        editor.buffer.update(cx, |buffer, cx| {
 9396                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9397                        });
 9398                        let rename_selection_range = match cursor_offset_in_rename_range
 9399                            .cmp(&cursor_offset_in_rename_range_end)
 9400                        {
 9401                            Ordering::Equal => {
 9402                                editor.select_all(&SelectAll, cx);
 9403                                return editor;
 9404                            }
 9405                            Ordering::Less => {
 9406                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9407                            }
 9408                            Ordering::Greater => {
 9409                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9410                            }
 9411                        };
 9412                        if rename_selection_range.end > old_name.len() {
 9413                            editor.select_all(&SelectAll, cx);
 9414                        } else {
 9415                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9416                                s.select_ranges([rename_selection_range]);
 9417                            });
 9418                        }
 9419                        editor
 9420                    });
 9421
 9422                    let write_highlights =
 9423                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9424                    let read_highlights =
 9425                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9426                    let ranges = write_highlights
 9427                        .iter()
 9428                        .flat_map(|(_, ranges)| ranges.iter())
 9429                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9430                        .cloned()
 9431                        .collect();
 9432
 9433                    this.highlight_text::<Rename>(
 9434                        ranges,
 9435                        HighlightStyle {
 9436                            fade_out: Some(0.6),
 9437                            ..Default::default()
 9438                        },
 9439                        cx,
 9440                    );
 9441                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9442                    cx.focus(&rename_focus_handle);
 9443                    let block_id = this.insert_blocks(
 9444                        [BlockProperties {
 9445                            style: BlockStyle::Flex,
 9446                            position: range.start,
 9447                            height: 1,
 9448                            render: Box::new({
 9449                                let rename_editor = rename_editor.clone();
 9450                                move |cx: &mut BlockContext| {
 9451                                    let mut text_style = cx.editor_style.text.clone();
 9452                                    if let Some(highlight_style) = old_highlight_id
 9453                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 9454                                    {
 9455                                        text_style = text_style.highlight(highlight_style);
 9456                                    }
 9457                                    div()
 9458                                        .pl(cx.anchor_x)
 9459                                        .child(EditorElement::new(
 9460                                            &rename_editor,
 9461                                            EditorStyle {
 9462                                                background: cx.theme().system().transparent,
 9463                                                local_player: cx.editor_style.local_player,
 9464                                                text: text_style,
 9465                                                scrollbar_width: cx.editor_style.scrollbar_width,
 9466                                                syntax: cx.editor_style.syntax.clone(),
 9467                                                status: cx.editor_style.status.clone(),
 9468                                                inlay_hints_style: HighlightStyle {
 9469                                                    color: Some(cx.theme().status().hint),
 9470                                                    font_weight: Some(FontWeight::BOLD),
 9471                                                    ..HighlightStyle::default()
 9472                                                },
 9473                                                suggestions_style: HighlightStyle {
 9474                                                    color: Some(cx.theme().status().predictive),
 9475                                                    ..HighlightStyle::default()
 9476                                                },
 9477                                            },
 9478                                        ))
 9479                                        .into_any_element()
 9480                                }
 9481                            }),
 9482                            disposition: BlockDisposition::Below,
 9483                        }],
 9484                        Some(Autoscroll::fit()),
 9485                        cx,
 9486                    )[0];
 9487                    this.pending_rename = Some(RenameState {
 9488                        range,
 9489                        old_name,
 9490                        editor: rename_editor,
 9491                        block_id,
 9492                    });
 9493                })?;
 9494            }
 9495
 9496            Ok(())
 9497        }))
 9498    }
 9499
 9500    pub fn confirm_rename(
 9501        &mut self,
 9502        _: &ConfirmRename,
 9503        cx: &mut ViewContext<Self>,
 9504    ) -> Option<Task<Result<()>>> {
 9505        let rename = self.take_rename(false, cx)?;
 9506        let workspace = self.workspace()?;
 9507        let (start_buffer, start) = self
 9508            .buffer
 9509            .read(cx)
 9510            .text_anchor_for_position(rename.range.start, cx)?;
 9511        let (end_buffer, end) = self
 9512            .buffer
 9513            .read(cx)
 9514            .text_anchor_for_position(rename.range.end, cx)?;
 9515        if start_buffer != end_buffer {
 9516            return None;
 9517        }
 9518
 9519        let buffer = start_buffer;
 9520        let range = start..end;
 9521        let old_name = rename.old_name;
 9522        let new_name = rename.editor.read(cx).text(cx);
 9523
 9524        let rename = workspace
 9525            .read(cx)
 9526            .project()
 9527            .clone()
 9528            .update(cx, |project, cx| {
 9529                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 9530            });
 9531        let workspace = workspace.downgrade();
 9532
 9533        Some(cx.spawn(|editor, mut cx| async move {
 9534            let project_transaction = rename.await?;
 9535            Self::open_project_transaction(
 9536                &editor,
 9537                workspace,
 9538                project_transaction,
 9539                format!("Rename: {}{}", old_name, new_name),
 9540                cx.clone(),
 9541            )
 9542            .await?;
 9543
 9544            editor.update(&mut cx, |editor, cx| {
 9545                editor.refresh_document_highlights(cx);
 9546            })?;
 9547            Ok(())
 9548        }))
 9549    }
 9550
 9551    fn take_rename(
 9552        &mut self,
 9553        moving_cursor: bool,
 9554        cx: &mut ViewContext<Self>,
 9555    ) -> Option<RenameState> {
 9556        let rename = self.pending_rename.take()?;
 9557        if rename.editor.focus_handle(cx).is_focused(cx) {
 9558            cx.focus(&self.focus_handle);
 9559        }
 9560
 9561        self.remove_blocks(
 9562            [rename.block_id].into_iter().collect(),
 9563            Some(Autoscroll::fit()),
 9564            cx,
 9565        );
 9566        self.clear_highlights::<Rename>(cx);
 9567        self.show_local_selections = true;
 9568
 9569        if moving_cursor {
 9570            let rename_editor = rename.editor.read(cx);
 9571            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 9572
 9573            // Update the selection to match the position of the selection inside
 9574            // the rename editor.
 9575            let snapshot = self.buffer.read(cx).read(cx);
 9576            let rename_range = rename.range.to_offset(&snapshot);
 9577            let cursor_in_editor = snapshot
 9578                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 9579                .min(rename_range.end);
 9580            drop(snapshot);
 9581
 9582            self.change_selections(None, cx, |s| {
 9583                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 9584            });
 9585        } else {
 9586            self.refresh_document_highlights(cx);
 9587        }
 9588
 9589        Some(rename)
 9590    }
 9591
 9592    pub fn pending_rename(&self) -> Option<&RenameState> {
 9593        self.pending_rename.as_ref()
 9594    }
 9595
 9596    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9597        let project = match &self.project {
 9598            Some(project) => project.clone(),
 9599            None => return None,
 9600        };
 9601
 9602        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 9603    }
 9604
 9605    fn perform_format(
 9606        &mut self,
 9607        project: Model<Project>,
 9608        trigger: FormatTrigger,
 9609        cx: &mut ViewContext<Self>,
 9610    ) -> Task<Result<()>> {
 9611        let buffer = self.buffer().clone();
 9612        let mut buffers = buffer.read(cx).all_buffers();
 9613        if trigger == FormatTrigger::Save {
 9614            buffers.retain(|buffer| buffer.read(cx).is_dirty());
 9615        }
 9616
 9617        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 9618        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 9619
 9620        cx.spawn(|_, mut cx| async move {
 9621            let transaction = futures::select_biased! {
 9622                () = timeout => {
 9623                    log::warn!("timed out waiting for formatting");
 9624                    None
 9625                }
 9626                transaction = format.log_err().fuse() => transaction,
 9627            };
 9628
 9629            buffer
 9630                .update(&mut cx, |buffer, cx| {
 9631                    if let Some(transaction) = transaction {
 9632                        if !buffer.is_singleton() {
 9633                            buffer.push_transaction(&transaction.0, cx);
 9634                        }
 9635                    }
 9636
 9637                    cx.notify();
 9638                })
 9639                .ok();
 9640
 9641            Ok(())
 9642        })
 9643    }
 9644
 9645    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
 9646        if let Some(project) = self.project.clone() {
 9647            self.buffer.update(cx, |multi_buffer, cx| {
 9648                project.update(cx, |project, cx| {
 9649                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
 9650                });
 9651            })
 9652        }
 9653    }
 9654
 9655    fn cancel_language_server_work(
 9656        &mut self,
 9657        _: &CancelLanguageServerWork,
 9658        cx: &mut ViewContext<Self>,
 9659    ) {
 9660        if let Some(project) = self.project.clone() {
 9661            self.buffer.update(cx, |multi_buffer, cx| {
 9662                project.update(cx, |project, cx| {
 9663                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
 9664                });
 9665            })
 9666        }
 9667    }
 9668
 9669    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 9670        cx.show_character_palette();
 9671    }
 9672
 9673    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
 9674        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
 9675            let buffer = self.buffer.read(cx).snapshot(cx);
 9676            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
 9677            let is_valid = buffer
 9678                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
 9679                .any(|entry| {
 9680                    entry.diagnostic.is_primary
 9681                        && !entry.range.is_empty()
 9682                        && entry.range.start == primary_range_start
 9683                        && entry.diagnostic.message == active_diagnostics.primary_message
 9684                });
 9685
 9686            if is_valid != active_diagnostics.is_valid {
 9687                active_diagnostics.is_valid = is_valid;
 9688                let mut new_styles = HashMap::default();
 9689                for (block_id, diagnostic) in &active_diagnostics.blocks {
 9690                    new_styles.insert(
 9691                        *block_id,
 9692                        (
 9693                            None,
 9694                            diagnostic_block_renderer(diagnostic.clone(), is_valid),
 9695                        ),
 9696                    );
 9697                }
 9698                self.display_map.update(cx, |display_map, cx| {
 9699                    display_map.replace_blocks(new_styles, cx)
 9700                });
 9701            }
 9702        }
 9703    }
 9704
 9705    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
 9706        self.dismiss_diagnostics(cx);
 9707        let snapshot = self.snapshot(cx);
 9708        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
 9709            let buffer = self.buffer.read(cx).snapshot(cx);
 9710
 9711            let mut primary_range = None;
 9712            let mut primary_message = None;
 9713            let mut group_end = Point::zero();
 9714            let diagnostic_group = buffer
 9715                .diagnostic_group::<MultiBufferPoint>(group_id)
 9716                .filter_map(|entry| {
 9717                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
 9718                        && (entry.range.start.row == entry.range.end.row
 9719                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
 9720                    {
 9721                        return None;
 9722                    }
 9723                    if entry.range.end > group_end {
 9724                        group_end = entry.range.end;
 9725                    }
 9726                    if entry.diagnostic.is_primary {
 9727                        primary_range = Some(entry.range.clone());
 9728                        primary_message = Some(entry.diagnostic.message.clone());
 9729                    }
 9730                    Some(entry)
 9731                })
 9732                .collect::<Vec<_>>();
 9733            let primary_range = primary_range?;
 9734            let primary_message = primary_message?;
 9735            let primary_range =
 9736                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
 9737
 9738            let blocks = display_map
 9739                .insert_blocks(
 9740                    diagnostic_group.iter().map(|entry| {
 9741                        let diagnostic = entry.diagnostic.clone();
 9742                        let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
 9743                        BlockProperties {
 9744                            style: BlockStyle::Fixed,
 9745                            position: buffer.anchor_after(entry.range.start),
 9746                            height: message_height,
 9747                            render: diagnostic_block_renderer(diagnostic, true),
 9748                            disposition: BlockDisposition::Below,
 9749                        }
 9750                    }),
 9751                    cx,
 9752                )
 9753                .into_iter()
 9754                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
 9755                .collect();
 9756
 9757            Some(ActiveDiagnosticGroup {
 9758                primary_range,
 9759                primary_message,
 9760                group_id,
 9761                blocks,
 9762                is_valid: true,
 9763            })
 9764        });
 9765        self.active_diagnostics.is_some()
 9766    }
 9767
 9768    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
 9769        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
 9770            self.display_map.update(cx, |display_map, cx| {
 9771                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
 9772            });
 9773            cx.notify();
 9774        }
 9775    }
 9776
 9777    pub fn set_selections_from_remote(
 9778        &mut self,
 9779        selections: Vec<Selection<Anchor>>,
 9780        pending_selection: Option<Selection<Anchor>>,
 9781        cx: &mut ViewContext<Self>,
 9782    ) {
 9783        let old_cursor_position = self.selections.newest_anchor().head();
 9784        self.selections.change_with(cx, |s| {
 9785            s.select_anchors(selections);
 9786            if let Some(pending_selection) = pending_selection {
 9787                s.set_pending(pending_selection, SelectMode::Character);
 9788            } else {
 9789                s.clear_pending();
 9790            }
 9791        });
 9792        self.selections_did_change(false, &old_cursor_position, true, cx);
 9793    }
 9794
 9795    fn push_to_selection_history(&mut self) {
 9796        self.selection_history.push(SelectionHistoryEntry {
 9797            selections: self.selections.disjoint_anchors(),
 9798            select_next_state: self.select_next_state.clone(),
 9799            select_prev_state: self.select_prev_state.clone(),
 9800            add_selections_state: self.add_selections_state.clone(),
 9801        });
 9802    }
 9803
 9804    pub fn transact(
 9805        &mut self,
 9806        cx: &mut ViewContext<Self>,
 9807        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
 9808    ) -> Option<TransactionId> {
 9809        self.start_transaction_at(Instant::now(), cx);
 9810        update(self, cx);
 9811        self.end_transaction_at(Instant::now(), cx)
 9812    }
 9813
 9814    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
 9815        self.end_selection(cx);
 9816        if let Some(tx_id) = self
 9817            .buffer
 9818            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
 9819        {
 9820            self.selection_history
 9821                .insert_transaction(tx_id, self.selections.disjoint_anchors());
 9822            cx.emit(EditorEvent::TransactionBegun {
 9823                transaction_id: tx_id,
 9824            })
 9825        }
 9826    }
 9827
 9828    fn end_transaction_at(
 9829        &mut self,
 9830        now: Instant,
 9831        cx: &mut ViewContext<Self>,
 9832    ) -> Option<TransactionId> {
 9833        if let Some(transaction_id) = self
 9834            .buffer
 9835            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 9836        {
 9837            if let Some((_, end_selections)) =
 9838                self.selection_history.transaction_mut(transaction_id)
 9839            {
 9840                *end_selections = Some(self.selections.disjoint_anchors());
 9841            } else {
 9842                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
 9843            }
 9844
 9845            cx.emit(EditorEvent::Edited { transaction_id });
 9846            Some(transaction_id)
 9847        } else {
 9848            None
 9849        }
 9850    }
 9851
 9852    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
 9853        let mut fold_ranges = Vec::new();
 9854
 9855        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9856
 9857        let selections = self.selections.all_adjusted(cx);
 9858        for selection in selections {
 9859            let range = selection.range().sorted();
 9860            let buffer_start_row = range.start.row;
 9861
 9862            for row in (0..=range.end.row).rev() {
 9863                if let Some((foldable_range, fold_text)) =
 9864                    display_map.foldable_range(MultiBufferRow(row))
 9865                {
 9866                    if foldable_range.end.row >= buffer_start_row {
 9867                        fold_ranges.push((foldable_range, fold_text));
 9868                        if row <= range.start.row {
 9869                            break;
 9870                        }
 9871                    }
 9872                }
 9873            }
 9874        }
 9875
 9876        self.fold_ranges(fold_ranges, true, cx);
 9877    }
 9878
 9879    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
 9880        let buffer_row = fold_at.buffer_row;
 9881        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9882
 9883        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
 9884            let autoscroll = self
 9885                .selections
 9886                .all::<Point>(cx)
 9887                .iter()
 9888                .any(|selection| fold_range.overlaps(&selection.range()));
 9889
 9890            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
 9891        }
 9892    }
 9893
 9894    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
 9895        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9896        let buffer = &display_map.buffer_snapshot;
 9897        let selections = self.selections.all::<Point>(cx);
 9898        let ranges = selections
 9899            .iter()
 9900            .map(|s| {
 9901                let range = s.display_range(&display_map).sorted();
 9902                let mut start = range.start.to_point(&display_map);
 9903                let mut end = range.end.to_point(&display_map);
 9904                start.column = 0;
 9905                end.column = buffer.line_len(MultiBufferRow(end.row));
 9906                start..end
 9907            })
 9908            .collect::<Vec<_>>();
 9909
 9910        self.unfold_ranges(ranges, true, true, cx);
 9911    }
 9912
 9913    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
 9914        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9915
 9916        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
 9917            ..Point::new(
 9918                unfold_at.buffer_row.0,
 9919                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
 9920            );
 9921
 9922        let autoscroll = self
 9923            .selections
 9924            .all::<Point>(cx)
 9925            .iter()
 9926            .any(|selection| selection.range().overlaps(&intersection_range));
 9927
 9928        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
 9929    }
 9930
 9931    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
 9932        let selections = self.selections.all::<Point>(cx);
 9933        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9934        let line_mode = self.selections.line_mode;
 9935        let ranges = selections.into_iter().map(|s| {
 9936            if line_mode {
 9937                let start = Point::new(s.start.row, 0);
 9938                let end = Point::new(
 9939                    s.end.row,
 9940                    display_map
 9941                        .buffer_snapshot
 9942                        .line_len(MultiBufferRow(s.end.row)),
 9943                );
 9944                (start..end, display_map.fold_placeholder.clone())
 9945            } else {
 9946                (s.start..s.end, display_map.fold_placeholder.clone())
 9947            }
 9948        });
 9949        self.fold_ranges(ranges, true, cx);
 9950    }
 9951
 9952    pub fn fold_ranges<T: ToOffset + Clone>(
 9953        &mut self,
 9954        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
 9955        auto_scroll: bool,
 9956        cx: &mut ViewContext<Self>,
 9957    ) {
 9958        let mut fold_ranges = Vec::new();
 9959        let mut buffers_affected = HashMap::default();
 9960        let multi_buffer = self.buffer().read(cx);
 9961        for (fold_range, fold_text) in ranges {
 9962            if let Some((_, buffer, _)) =
 9963                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
 9964            {
 9965                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
 9966            };
 9967            fold_ranges.push((fold_range, fold_text));
 9968        }
 9969
 9970        let mut ranges = fold_ranges.into_iter().peekable();
 9971        if ranges.peek().is_some() {
 9972            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
 9973
 9974            if auto_scroll {
 9975                self.request_autoscroll(Autoscroll::fit(), cx);
 9976            }
 9977
 9978            for buffer in buffers_affected.into_values() {
 9979                self.sync_expanded_diff_hunks(buffer, cx);
 9980            }
 9981
 9982            cx.notify();
 9983
 9984            if let Some(active_diagnostics) = self.active_diagnostics.take() {
 9985                // Clear diagnostics block when folding a range that contains it.
 9986                let snapshot = self.snapshot(cx);
 9987                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
 9988                    drop(snapshot);
 9989                    self.active_diagnostics = Some(active_diagnostics);
 9990                    self.dismiss_diagnostics(cx);
 9991                } else {
 9992                    self.active_diagnostics = Some(active_diagnostics);
 9993                }
 9994            }
 9995
 9996            self.scrollbar_marker_state.dirty = true;
 9997        }
 9998    }
 9999
10000    pub fn unfold_ranges<T: ToOffset + Clone>(
10001        &mut self,
10002        ranges: impl IntoIterator<Item = Range<T>>,
10003        inclusive: bool,
10004        auto_scroll: bool,
10005        cx: &mut ViewContext<Self>,
10006    ) {
10007        let mut unfold_ranges = Vec::new();
10008        let mut buffers_affected = HashMap::default();
10009        let multi_buffer = self.buffer().read(cx);
10010        for range in ranges {
10011            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10012                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10013            };
10014            unfold_ranges.push(range);
10015        }
10016
10017        let mut ranges = unfold_ranges.into_iter().peekable();
10018        if ranges.peek().is_some() {
10019            self.display_map
10020                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10021            if auto_scroll {
10022                self.request_autoscroll(Autoscroll::fit(), cx);
10023            }
10024
10025            for buffer in buffers_affected.into_values() {
10026                self.sync_expanded_diff_hunks(buffer, cx);
10027            }
10028
10029            cx.notify();
10030            self.scrollbar_marker_state.dirty = true;
10031            self.active_indent_guides_state.dirty = true;
10032        }
10033    }
10034
10035    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10036        if hovered != self.gutter_hovered {
10037            self.gutter_hovered = hovered;
10038            cx.notify();
10039        }
10040    }
10041
10042    pub fn insert_blocks(
10043        &mut self,
10044        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10045        autoscroll: Option<Autoscroll>,
10046        cx: &mut ViewContext<Self>,
10047    ) -> Vec<BlockId> {
10048        let blocks = self
10049            .display_map
10050            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10051        if let Some(autoscroll) = autoscroll {
10052            self.request_autoscroll(autoscroll, cx);
10053        }
10054        blocks
10055    }
10056
10057    pub fn replace_blocks(
10058        &mut self,
10059        blocks: HashMap<BlockId, (Option<u8>, RenderBlock)>,
10060        autoscroll: Option<Autoscroll>,
10061        cx: &mut ViewContext<Self>,
10062    ) {
10063        self.display_map
10064            .update(cx, |display_map, cx| display_map.replace_blocks(blocks, cx));
10065        if let Some(autoscroll) = autoscroll {
10066            self.request_autoscroll(autoscroll, cx);
10067        }
10068    }
10069
10070    pub fn remove_blocks(
10071        &mut self,
10072        block_ids: HashSet<BlockId>,
10073        autoscroll: Option<Autoscroll>,
10074        cx: &mut ViewContext<Self>,
10075    ) {
10076        self.display_map.update(cx, |display_map, cx| {
10077            display_map.remove_blocks(block_ids, cx)
10078        });
10079        if let Some(autoscroll) = autoscroll {
10080            self.request_autoscroll(autoscroll, cx);
10081        }
10082    }
10083
10084    pub fn row_for_block(
10085        &self,
10086        block_id: BlockId,
10087        cx: &mut ViewContext<Self>,
10088    ) -> Option<DisplayRow> {
10089        self.display_map
10090            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10091    }
10092
10093    pub fn insert_creases(
10094        &mut self,
10095        creases: impl IntoIterator<Item = Crease>,
10096        cx: &mut ViewContext<Self>,
10097    ) -> Vec<CreaseId> {
10098        self.display_map
10099            .update(cx, |map, cx| map.insert_creases(creases, cx))
10100    }
10101
10102    pub fn remove_creases(
10103        &mut self,
10104        ids: impl IntoIterator<Item = CreaseId>,
10105        cx: &mut ViewContext<Self>,
10106    ) {
10107        self.display_map
10108            .update(cx, |map, cx| map.remove_creases(ids, cx));
10109    }
10110
10111    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10112        self.display_map
10113            .update(cx, |map, cx| map.snapshot(cx))
10114            .longest_row()
10115    }
10116
10117    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10118        self.display_map
10119            .update(cx, |map, cx| map.snapshot(cx))
10120            .max_point()
10121    }
10122
10123    pub fn text(&self, cx: &AppContext) -> String {
10124        self.buffer.read(cx).read(cx).text()
10125    }
10126
10127    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10128        let text = self.text(cx);
10129        let text = text.trim();
10130
10131        if text.is_empty() {
10132            return None;
10133        }
10134
10135        Some(text.to_string())
10136    }
10137
10138    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10139        self.transact(cx, |this, cx| {
10140            this.buffer
10141                .read(cx)
10142                .as_singleton()
10143                .expect("you can only call set_text on editors for singleton buffers")
10144                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10145        });
10146    }
10147
10148    pub fn display_text(&self, cx: &mut AppContext) -> String {
10149        self.display_map
10150            .update(cx, |map, cx| map.snapshot(cx))
10151            .text()
10152    }
10153
10154    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10155        let mut wrap_guides = smallvec::smallvec![];
10156
10157        if self.show_wrap_guides == Some(false) {
10158            return wrap_guides;
10159        }
10160
10161        let settings = self.buffer.read(cx).settings_at(0, cx);
10162        if settings.show_wrap_guides {
10163            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10164                wrap_guides.push((soft_wrap as usize, true));
10165            }
10166            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10167        }
10168
10169        wrap_guides
10170    }
10171
10172    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10173        let settings = self.buffer.read(cx).settings_at(0, cx);
10174        let mode = self
10175            .soft_wrap_mode_override
10176            .unwrap_or_else(|| settings.soft_wrap);
10177        match mode {
10178            language_settings::SoftWrap::None => SoftWrap::None,
10179            language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10180            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10181            language_settings::SoftWrap::PreferredLineLength => {
10182                SoftWrap::Column(settings.preferred_line_length)
10183            }
10184        }
10185    }
10186
10187    pub fn set_soft_wrap_mode(
10188        &mut self,
10189        mode: language_settings::SoftWrap,
10190        cx: &mut ViewContext<Self>,
10191    ) {
10192        self.soft_wrap_mode_override = Some(mode);
10193        cx.notify();
10194    }
10195
10196    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10197        let rem_size = cx.rem_size();
10198        self.display_map.update(cx, |map, cx| {
10199            map.set_font(
10200                style.text.font(),
10201                style.text.font_size.to_pixels(rem_size),
10202                cx,
10203            )
10204        });
10205        self.style = Some(style);
10206    }
10207
10208    pub fn style(&self) -> Option<&EditorStyle> {
10209        self.style.as_ref()
10210    }
10211
10212    // Called by the element. This method is not designed to be called outside of the editor
10213    // element's layout code because it does not notify when rewrapping is computed synchronously.
10214    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10215        self.display_map
10216            .update(cx, |map, cx| map.set_wrap_width(width, cx))
10217    }
10218
10219    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10220        if self.soft_wrap_mode_override.is_some() {
10221            self.soft_wrap_mode_override.take();
10222        } else {
10223            let soft_wrap = match self.soft_wrap_mode(cx) {
10224                SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10225                SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10226                    language_settings::SoftWrap::PreferLine
10227                }
10228            };
10229            self.soft_wrap_mode_override = Some(soft_wrap);
10230        }
10231        cx.notify();
10232    }
10233
10234    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10235        let Some(workspace) = self.workspace() else {
10236            return;
10237        };
10238        let fs = workspace.read(cx).app_state().fs.clone();
10239        let current_show = TabBarSettings::get_global(cx).show;
10240        update_settings_file::<TabBarSettings>(fs, cx, move |setting| {
10241            setting.show = Some(!current_show);
10242        });
10243    }
10244
10245    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10246        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10247            self.buffer
10248                .read(cx)
10249                .settings_at(0, cx)
10250                .indent_guides
10251                .enabled
10252        });
10253        self.show_indent_guides = Some(!currently_enabled);
10254        cx.notify();
10255    }
10256
10257    fn should_show_indent_guides(&self) -> Option<bool> {
10258        self.show_indent_guides
10259    }
10260
10261    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10262        let mut editor_settings = EditorSettings::get_global(cx).clone();
10263        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10264        EditorSettings::override_global(editor_settings, cx);
10265    }
10266
10267    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10268        self.show_gutter = show_gutter;
10269        cx.notify();
10270    }
10271
10272    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10273        self.show_line_numbers = Some(show_line_numbers);
10274        cx.notify();
10275    }
10276
10277    pub fn set_show_git_diff_gutter(
10278        &mut self,
10279        show_git_diff_gutter: bool,
10280        cx: &mut ViewContext<Self>,
10281    ) {
10282        self.show_git_diff_gutter = Some(show_git_diff_gutter);
10283        cx.notify();
10284    }
10285
10286    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10287        self.show_code_actions = Some(show_code_actions);
10288        cx.notify();
10289    }
10290
10291    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10292        self.show_runnables = Some(show_runnables);
10293        cx.notify();
10294    }
10295
10296    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10297        self.show_wrap_guides = Some(show_wrap_guides);
10298        cx.notify();
10299    }
10300
10301    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10302        self.show_indent_guides = Some(show_indent_guides);
10303        cx.notify();
10304    }
10305
10306    pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
10307        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10308            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10309                cx.reveal_path(&file.abs_path(cx));
10310            }
10311        }
10312    }
10313
10314    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10315        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10316            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10317                if let Some(path) = file.abs_path(cx).to_str() {
10318                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10319                }
10320            }
10321        }
10322    }
10323
10324    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10325        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10326            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10327                if let Some(path) = file.path().to_str() {
10328                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10329                }
10330            }
10331        }
10332    }
10333
10334    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10335        self.show_git_blame_gutter = !self.show_git_blame_gutter;
10336
10337        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10338            self.start_git_blame(true, cx);
10339        }
10340
10341        cx.notify();
10342    }
10343
10344    pub fn toggle_git_blame_inline(
10345        &mut self,
10346        _: &ToggleGitBlameInline,
10347        cx: &mut ViewContext<Self>,
10348    ) {
10349        self.toggle_git_blame_inline_internal(true, cx);
10350        cx.notify();
10351    }
10352
10353    pub fn git_blame_inline_enabled(&self) -> bool {
10354        self.git_blame_inline_enabled
10355    }
10356
10357    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10358        self.show_selection_menu = self
10359            .show_selection_menu
10360            .map(|show_selections_menu| !show_selections_menu)
10361            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10362
10363        cx.notify();
10364    }
10365
10366    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10367        self.show_selection_menu
10368            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10369    }
10370
10371    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10372        if let Some(project) = self.project.as_ref() {
10373            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10374                return;
10375            };
10376
10377            if buffer.read(cx).file().is_none() {
10378                return;
10379            }
10380
10381            let focused = self.focus_handle(cx).contains_focused(cx);
10382
10383            let project = project.clone();
10384            let blame =
10385                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10386            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10387            self.blame = Some(blame);
10388        }
10389    }
10390
10391    fn toggle_git_blame_inline_internal(
10392        &mut self,
10393        user_triggered: bool,
10394        cx: &mut ViewContext<Self>,
10395    ) {
10396        if self.git_blame_inline_enabled {
10397            self.git_blame_inline_enabled = false;
10398            self.show_git_blame_inline = false;
10399            self.show_git_blame_inline_delay_task.take();
10400        } else {
10401            self.git_blame_inline_enabled = true;
10402            self.start_git_blame_inline(user_triggered, cx);
10403        }
10404
10405        cx.notify();
10406    }
10407
10408    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10409        self.start_git_blame(user_triggered, cx);
10410
10411        if ProjectSettings::get_global(cx)
10412            .git
10413            .inline_blame_delay()
10414            .is_some()
10415        {
10416            self.start_inline_blame_timer(cx);
10417        } else {
10418            self.show_git_blame_inline = true
10419        }
10420    }
10421
10422    pub fn blame(&self) -> Option<&Model<GitBlame>> {
10423        self.blame.as_ref()
10424    }
10425
10426    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10427        self.show_git_blame_gutter && self.has_blame_entries(cx)
10428    }
10429
10430    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10431        self.show_git_blame_inline
10432            && self.focus_handle.is_focused(cx)
10433            && !self.newest_selection_head_on_empty_line(cx)
10434            && self.has_blame_entries(cx)
10435    }
10436
10437    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10438        self.blame()
10439            .map_or(false, |blame| blame.read(cx).has_generated_entries())
10440    }
10441
10442    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10443        let cursor_anchor = self.selections.newest_anchor().head();
10444
10445        let snapshot = self.buffer.read(cx).snapshot(cx);
10446        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10447
10448        snapshot.line_len(buffer_row) == 0
10449    }
10450
10451    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10452        let (path, selection, repo) = maybe!({
10453            let project_handle = self.project.as_ref()?.clone();
10454            let project = project_handle.read(cx);
10455
10456            let selection = self.selections.newest::<Point>(cx);
10457            let selection_range = selection.range();
10458
10459            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10460                (buffer, selection_range.start.row..selection_range.end.row)
10461            } else {
10462                let buffer_ranges = self
10463                    .buffer()
10464                    .read(cx)
10465                    .range_to_buffer_ranges(selection_range, cx);
10466
10467                let (buffer, range, _) = if selection.reversed {
10468                    buffer_ranges.first()
10469                } else {
10470                    buffer_ranges.last()
10471                }?;
10472
10473                let snapshot = buffer.read(cx).snapshot();
10474                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10475                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
10476                (buffer.clone(), selection)
10477            };
10478
10479            let path = buffer
10480                .read(cx)
10481                .file()?
10482                .as_local()?
10483                .path()
10484                .to_str()?
10485                .to_string();
10486            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10487            Some((path, selection, repo))
10488        })
10489        .ok_or_else(|| anyhow!("unable to open git repository"))?;
10490
10491        const REMOTE_NAME: &str = "origin";
10492        let origin_url = repo
10493            .remote_url(REMOTE_NAME)
10494            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10495        let sha = repo
10496            .head_sha()
10497            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10498
10499        let (provider, remote) =
10500            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10501                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10502
10503        Ok(provider.build_permalink(
10504            remote,
10505            BuildPermalinkParams {
10506                sha: &sha,
10507                path: &path,
10508                selection: Some(selection),
10509            },
10510        ))
10511    }
10512
10513    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10514        let permalink = self.get_permalink_to_line(cx);
10515
10516        match permalink {
10517            Ok(permalink) => {
10518                cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
10519            }
10520            Err(err) => {
10521                let message = format!("Failed to copy permalink: {err}");
10522
10523                Err::<(), anyhow::Error>(err).log_err();
10524
10525                if let Some(workspace) = self.workspace() {
10526                    workspace.update(cx, |workspace, cx| {
10527                        struct CopyPermalinkToLine;
10528
10529                        workspace.show_toast(
10530                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10531                            cx,
10532                        )
10533                    })
10534                }
10535            }
10536        }
10537    }
10538
10539    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10540        let permalink = self.get_permalink_to_line(cx);
10541
10542        match permalink {
10543            Ok(permalink) => {
10544                cx.open_url(permalink.as_ref());
10545            }
10546            Err(err) => {
10547                let message = format!("Failed to open permalink: {err}");
10548
10549                Err::<(), anyhow::Error>(err).log_err();
10550
10551                if let Some(workspace) = self.workspace() {
10552                    workspace.update(cx, |workspace, cx| {
10553                        struct OpenPermalinkToLine;
10554
10555                        workspace.show_toast(
10556                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10557                            cx,
10558                        )
10559                    })
10560                }
10561            }
10562        }
10563    }
10564
10565    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10566    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10567    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10568    pub fn highlight_rows<T: 'static>(
10569        &mut self,
10570        rows: RangeInclusive<Anchor>,
10571        color: Option<Hsla>,
10572        should_autoscroll: bool,
10573        cx: &mut ViewContext<Self>,
10574    ) {
10575        let snapshot = self.buffer().read(cx).snapshot(cx);
10576        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10577        let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10578            highlight
10579                .range
10580                .start()
10581                .cmp(&rows.start(), &snapshot)
10582                .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10583        });
10584        match (color, existing_highlight_index) {
10585            (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10586                ix,
10587                RowHighlight {
10588                    index: post_inc(&mut self.highlight_order),
10589                    range: rows,
10590                    should_autoscroll,
10591                    color,
10592                },
10593            ),
10594            (None, Ok(i)) => {
10595                row_highlights.remove(i);
10596            }
10597        }
10598    }
10599
10600    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10601    pub fn clear_row_highlights<T: 'static>(&mut self) {
10602        self.highlighted_rows.remove(&TypeId::of::<T>());
10603    }
10604
10605    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10606    pub fn highlighted_rows<T: 'static>(
10607        &self,
10608    ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10609        Some(
10610            self.highlighted_rows
10611                .get(&TypeId::of::<T>())?
10612                .iter()
10613                .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10614        )
10615    }
10616
10617    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10618    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10619    /// Allows to ignore certain kinds of highlights.
10620    pub fn highlighted_display_rows(
10621        &mut self,
10622        cx: &mut WindowContext,
10623    ) -> BTreeMap<DisplayRow, Hsla> {
10624        let snapshot = self.snapshot(cx);
10625        let mut used_highlight_orders = HashMap::default();
10626        self.highlighted_rows
10627            .iter()
10628            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10629            .fold(
10630                BTreeMap::<DisplayRow, Hsla>::new(),
10631                |mut unique_rows, highlight| {
10632                    let start_row = highlight.range.start().to_display_point(&snapshot).row();
10633                    let end_row = highlight.range.end().to_display_point(&snapshot).row();
10634                    for row in start_row.0..=end_row.0 {
10635                        let used_index =
10636                            used_highlight_orders.entry(row).or_insert(highlight.index);
10637                        if highlight.index >= *used_index {
10638                            *used_index = highlight.index;
10639                            match highlight.color {
10640                                Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10641                                None => unique_rows.remove(&DisplayRow(row)),
10642                            };
10643                        }
10644                    }
10645                    unique_rows
10646                },
10647            )
10648    }
10649
10650    pub fn highlighted_display_row_for_autoscroll(
10651        &self,
10652        snapshot: &DisplaySnapshot,
10653    ) -> Option<DisplayRow> {
10654        self.highlighted_rows
10655            .values()
10656            .flat_map(|highlighted_rows| highlighted_rows.iter())
10657            .filter_map(|highlight| {
10658                if highlight.color.is_none() || !highlight.should_autoscroll {
10659                    return None;
10660                }
10661                Some(highlight.range.start().to_display_point(&snapshot).row())
10662            })
10663            .min()
10664    }
10665
10666    pub fn set_search_within_ranges(
10667        &mut self,
10668        ranges: &[Range<Anchor>],
10669        cx: &mut ViewContext<Self>,
10670    ) {
10671        self.highlight_background::<SearchWithinRange>(
10672            ranges,
10673            |colors| colors.editor_document_highlight_read_background,
10674            cx,
10675        )
10676    }
10677
10678    pub fn set_breadcrumb_header(&mut self, new_header: String) {
10679        self.breadcrumb_header = Some(new_header);
10680    }
10681
10682    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10683        self.clear_background_highlights::<SearchWithinRange>(cx);
10684    }
10685
10686    pub fn highlight_background<T: 'static>(
10687        &mut self,
10688        ranges: &[Range<Anchor>],
10689        color_fetcher: fn(&ThemeColors) -> Hsla,
10690        cx: &mut ViewContext<Self>,
10691    ) {
10692        let snapshot = self.snapshot(cx);
10693        // this is to try and catch a panic sooner
10694        for range in ranges {
10695            snapshot
10696                .buffer_snapshot
10697                .summary_for_anchor::<usize>(&range.start);
10698            snapshot
10699                .buffer_snapshot
10700                .summary_for_anchor::<usize>(&range.end);
10701        }
10702
10703        self.background_highlights
10704            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10705        self.scrollbar_marker_state.dirty = true;
10706        cx.notify();
10707    }
10708
10709    pub fn clear_background_highlights<T: 'static>(
10710        &mut self,
10711        cx: &mut ViewContext<Self>,
10712    ) -> Option<BackgroundHighlight> {
10713        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10714        if !text_highlights.1.is_empty() {
10715            self.scrollbar_marker_state.dirty = true;
10716            cx.notify();
10717        }
10718        Some(text_highlights)
10719    }
10720
10721    pub fn highlight_gutter<T: 'static>(
10722        &mut self,
10723        ranges: &[Range<Anchor>],
10724        color_fetcher: fn(&AppContext) -> Hsla,
10725        cx: &mut ViewContext<Self>,
10726    ) {
10727        self.gutter_highlights
10728            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10729        cx.notify();
10730    }
10731
10732    pub fn clear_gutter_highlights<T: 'static>(
10733        &mut self,
10734        cx: &mut ViewContext<Self>,
10735    ) -> Option<GutterHighlight> {
10736        cx.notify();
10737        self.gutter_highlights.remove(&TypeId::of::<T>())
10738    }
10739
10740    #[cfg(feature = "test-support")]
10741    pub fn all_text_background_highlights(
10742        &mut self,
10743        cx: &mut ViewContext<Self>,
10744    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10745        let snapshot = self.snapshot(cx);
10746        let buffer = &snapshot.buffer_snapshot;
10747        let start = buffer.anchor_before(0);
10748        let end = buffer.anchor_after(buffer.len());
10749        let theme = cx.theme().colors();
10750        self.background_highlights_in_range(start..end, &snapshot, theme)
10751    }
10752
10753    #[cfg(feature = "test-support")]
10754    pub fn search_background_highlights(
10755        &mut self,
10756        cx: &mut ViewContext<Self>,
10757    ) -> Vec<Range<Point>> {
10758        let snapshot = self.buffer().read(cx).snapshot(cx);
10759
10760        let highlights = self
10761            .background_highlights
10762            .get(&TypeId::of::<items::BufferSearchHighlights>());
10763
10764        if let Some((_color, ranges)) = highlights {
10765            ranges
10766                .iter()
10767                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
10768                .collect_vec()
10769        } else {
10770            vec![]
10771        }
10772    }
10773
10774    fn document_highlights_for_position<'a>(
10775        &'a self,
10776        position: Anchor,
10777        buffer: &'a MultiBufferSnapshot,
10778    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
10779        let read_highlights = self
10780            .background_highlights
10781            .get(&TypeId::of::<DocumentHighlightRead>())
10782            .map(|h| &h.1);
10783        let write_highlights = self
10784            .background_highlights
10785            .get(&TypeId::of::<DocumentHighlightWrite>())
10786            .map(|h| &h.1);
10787        let left_position = position.bias_left(buffer);
10788        let right_position = position.bias_right(buffer);
10789        read_highlights
10790            .into_iter()
10791            .chain(write_highlights)
10792            .flat_map(move |ranges| {
10793                let start_ix = match ranges.binary_search_by(|probe| {
10794                    let cmp = probe.end.cmp(&left_position, buffer);
10795                    if cmp.is_ge() {
10796                        Ordering::Greater
10797                    } else {
10798                        Ordering::Less
10799                    }
10800                }) {
10801                    Ok(i) | Err(i) => i,
10802                };
10803
10804                ranges[start_ix..]
10805                    .iter()
10806                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
10807            })
10808    }
10809
10810    pub fn has_background_highlights<T: 'static>(&self) -> bool {
10811        self.background_highlights
10812            .get(&TypeId::of::<T>())
10813            .map_or(false, |(_, highlights)| !highlights.is_empty())
10814    }
10815
10816    pub fn background_highlights_in_range(
10817        &self,
10818        search_range: Range<Anchor>,
10819        display_snapshot: &DisplaySnapshot,
10820        theme: &ThemeColors,
10821    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10822        let mut results = Vec::new();
10823        for (color_fetcher, ranges) in self.background_highlights.values() {
10824            let color = color_fetcher(theme);
10825            let start_ix = match ranges.binary_search_by(|probe| {
10826                let cmp = probe
10827                    .end
10828                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10829                if cmp.is_gt() {
10830                    Ordering::Greater
10831                } else {
10832                    Ordering::Less
10833                }
10834            }) {
10835                Ok(i) | Err(i) => i,
10836            };
10837            for range in &ranges[start_ix..] {
10838                if range
10839                    .start
10840                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10841                    .is_ge()
10842                {
10843                    break;
10844                }
10845
10846                let start = range.start.to_display_point(&display_snapshot);
10847                let end = range.end.to_display_point(&display_snapshot);
10848                results.push((start..end, color))
10849            }
10850        }
10851        results
10852    }
10853
10854    pub fn background_highlight_row_ranges<T: 'static>(
10855        &self,
10856        search_range: Range<Anchor>,
10857        display_snapshot: &DisplaySnapshot,
10858        count: usize,
10859    ) -> Vec<RangeInclusive<DisplayPoint>> {
10860        let mut results = Vec::new();
10861        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
10862            return vec![];
10863        };
10864
10865        let start_ix = match ranges.binary_search_by(|probe| {
10866            let cmp = probe
10867                .end
10868                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10869            if cmp.is_gt() {
10870                Ordering::Greater
10871            } else {
10872                Ordering::Less
10873            }
10874        }) {
10875            Ok(i) | Err(i) => i,
10876        };
10877        let mut push_region = |start: Option<Point>, end: Option<Point>| {
10878            if let (Some(start_display), Some(end_display)) = (start, end) {
10879                results.push(
10880                    start_display.to_display_point(display_snapshot)
10881                        ..=end_display.to_display_point(display_snapshot),
10882                );
10883            }
10884        };
10885        let mut start_row: Option<Point> = None;
10886        let mut end_row: Option<Point> = None;
10887        if ranges.len() > count {
10888            return Vec::new();
10889        }
10890        for range in &ranges[start_ix..] {
10891            if range
10892                .start
10893                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10894                .is_ge()
10895            {
10896                break;
10897            }
10898            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
10899            if let Some(current_row) = &end_row {
10900                if end.row == current_row.row {
10901                    continue;
10902                }
10903            }
10904            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
10905            if start_row.is_none() {
10906                assert_eq!(end_row, None);
10907                start_row = Some(start);
10908                end_row = Some(end);
10909                continue;
10910            }
10911            if let Some(current_end) = end_row.as_mut() {
10912                if start.row > current_end.row + 1 {
10913                    push_region(start_row, end_row);
10914                    start_row = Some(start);
10915                    end_row = Some(end);
10916                } else {
10917                    // Merge two hunks.
10918                    *current_end = end;
10919                }
10920            } else {
10921                unreachable!();
10922            }
10923        }
10924        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
10925        push_region(start_row, end_row);
10926        results
10927    }
10928
10929    pub fn gutter_highlights_in_range(
10930        &self,
10931        search_range: Range<Anchor>,
10932        display_snapshot: &DisplaySnapshot,
10933        cx: &AppContext,
10934    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10935        let mut results = Vec::new();
10936        for (color_fetcher, ranges) in self.gutter_highlights.values() {
10937            let color = color_fetcher(cx);
10938            let start_ix = match ranges.binary_search_by(|probe| {
10939                let cmp = probe
10940                    .end
10941                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10942                if cmp.is_gt() {
10943                    Ordering::Greater
10944                } else {
10945                    Ordering::Less
10946                }
10947            }) {
10948                Ok(i) | Err(i) => i,
10949            };
10950            for range in &ranges[start_ix..] {
10951                if range
10952                    .start
10953                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10954                    .is_ge()
10955                {
10956                    break;
10957                }
10958
10959                let start = range.start.to_display_point(&display_snapshot);
10960                let end = range.end.to_display_point(&display_snapshot);
10961                results.push((start..end, color))
10962            }
10963        }
10964        results
10965    }
10966
10967    /// Get the text ranges corresponding to the redaction query
10968    pub fn redacted_ranges(
10969        &self,
10970        search_range: Range<Anchor>,
10971        display_snapshot: &DisplaySnapshot,
10972        cx: &WindowContext,
10973    ) -> Vec<Range<DisplayPoint>> {
10974        display_snapshot
10975            .buffer_snapshot
10976            .redacted_ranges(search_range, |file| {
10977                if let Some(file) = file {
10978                    file.is_private()
10979                        && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
10980                } else {
10981                    false
10982                }
10983            })
10984            .map(|range| {
10985                range.start.to_display_point(display_snapshot)
10986                    ..range.end.to_display_point(display_snapshot)
10987            })
10988            .collect()
10989    }
10990
10991    pub fn highlight_text<T: 'static>(
10992        &mut self,
10993        ranges: Vec<Range<Anchor>>,
10994        style: HighlightStyle,
10995        cx: &mut ViewContext<Self>,
10996    ) {
10997        self.display_map.update(cx, |map, _| {
10998            map.highlight_text(TypeId::of::<T>(), ranges, style)
10999        });
11000        cx.notify();
11001    }
11002
11003    pub(crate) fn highlight_inlays<T: 'static>(
11004        &mut self,
11005        highlights: Vec<InlayHighlight>,
11006        style: HighlightStyle,
11007        cx: &mut ViewContext<Self>,
11008    ) {
11009        self.display_map.update(cx, |map, _| {
11010            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11011        });
11012        cx.notify();
11013    }
11014
11015    pub fn text_highlights<'a, T: 'static>(
11016        &'a self,
11017        cx: &'a AppContext,
11018    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11019        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11020    }
11021
11022    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11023        let cleared = self
11024            .display_map
11025            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11026        if cleared {
11027            cx.notify();
11028        }
11029    }
11030
11031    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11032        (self.read_only(cx) || self.blink_manager.read(cx).visible())
11033            && self.focus_handle.is_focused(cx)
11034    }
11035
11036    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11037        self.show_cursor_when_unfocused = is_enabled;
11038        cx.notify();
11039    }
11040
11041    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11042        cx.notify();
11043    }
11044
11045    fn on_buffer_event(
11046        &mut self,
11047        multibuffer: Model<MultiBuffer>,
11048        event: &multi_buffer::Event,
11049        cx: &mut ViewContext<Self>,
11050    ) {
11051        match event {
11052            multi_buffer::Event::Edited {
11053                singleton_buffer_edited,
11054            } => {
11055                self.scrollbar_marker_state.dirty = true;
11056                self.active_indent_guides_state.dirty = true;
11057                self.refresh_active_diagnostics(cx);
11058                self.refresh_code_actions(cx);
11059                if self.has_active_inline_completion(cx) {
11060                    self.update_visible_inline_completion(cx);
11061                }
11062                cx.emit(EditorEvent::BufferEdited);
11063                cx.emit(SearchEvent::MatchesInvalidated);
11064                if *singleton_buffer_edited {
11065                    if let Some(project) = &self.project {
11066                        let project = project.read(cx);
11067                        let languages_affected = multibuffer
11068                            .read(cx)
11069                            .all_buffers()
11070                            .into_iter()
11071                            .filter_map(|buffer| {
11072                                let buffer = buffer.read(cx);
11073                                let language = buffer.language()?;
11074                                if project.is_local()
11075                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
11076                                {
11077                                    None
11078                                } else {
11079                                    Some(language)
11080                                }
11081                            })
11082                            .cloned()
11083                            .collect::<HashSet<_>>();
11084                        if !languages_affected.is_empty() {
11085                            self.refresh_inlay_hints(
11086                                InlayHintRefreshReason::BufferEdited(languages_affected),
11087                                cx,
11088                            );
11089                        }
11090                    }
11091                }
11092
11093                let Some(project) = &self.project else { return };
11094                let telemetry = project.read(cx).client().telemetry().clone();
11095                refresh_linked_ranges(self, cx);
11096                telemetry.log_edit_event("editor");
11097            }
11098            multi_buffer::Event::ExcerptsAdded {
11099                buffer,
11100                predecessor,
11101                excerpts,
11102            } => {
11103                self.tasks_update_task = Some(self.refresh_runnables(cx));
11104                cx.emit(EditorEvent::ExcerptsAdded {
11105                    buffer: buffer.clone(),
11106                    predecessor: *predecessor,
11107                    excerpts: excerpts.clone(),
11108                });
11109                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11110            }
11111            multi_buffer::Event::ExcerptsRemoved { ids } => {
11112                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11113                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11114            }
11115            multi_buffer::Event::ExcerptsEdited { ids } => {
11116                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11117            }
11118            multi_buffer::Event::ExcerptsExpanded { ids } => {
11119                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11120            }
11121            multi_buffer::Event::Reparsed(buffer_id) => {
11122                self.tasks_update_task = Some(self.refresh_runnables(cx));
11123
11124                cx.emit(EditorEvent::Reparsed(*buffer_id));
11125            }
11126            multi_buffer::Event::LanguageChanged(buffer_id) => {
11127                linked_editing_ranges::refresh_linked_ranges(self, cx);
11128                cx.emit(EditorEvent::Reparsed(*buffer_id));
11129                cx.notify();
11130            }
11131            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11132            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11133            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11134                cx.emit(EditorEvent::TitleChanged)
11135            }
11136            multi_buffer::Event::DiffBaseChanged => {
11137                self.scrollbar_marker_state.dirty = true;
11138                cx.emit(EditorEvent::DiffBaseChanged);
11139                cx.notify();
11140            }
11141            multi_buffer::Event::DiffUpdated { buffer } => {
11142                self.sync_expanded_diff_hunks(buffer.clone(), cx);
11143                cx.notify();
11144            }
11145            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11146            multi_buffer::Event::DiagnosticsUpdated => {
11147                self.refresh_active_diagnostics(cx);
11148                self.scrollbar_marker_state.dirty = true;
11149                cx.notify();
11150            }
11151            _ => {}
11152        };
11153    }
11154
11155    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11156        cx.notify();
11157    }
11158
11159    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11160        self.tasks_update_task = Some(self.refresh_runnables(cx));
11161        self.refresh_inline_completion(true, cx);
11162        self.refresh_inlay_hints(
11163            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11164                self.selections.newest_anchor().head(),
11165                &self.buffer.read(cx).snapshot(cx),
11166                cx,
11167            )),
11168            cx,
11169        );
11170        let editor_settings = EditorSettings::get_global(cx);
11171        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11172        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11173
11174        if self.mode == EditorMode::Full {
11175            let inline_blame_enabled = ProjectSettings::get_global(cx).git.inline_blame_enabled();
11176            if self.git_blame_inline_enabled != inline_blame_enabled {
11177                self.toggle_git_blame_inline_internal(false, cx);
11178            }
11179        }
11180
11181        cx.notify();
11182    }
11183
11184    pub fn set_searchable(&mut self, searchable: bool) {
11185        self.searchable = searchable;
11186    }
11187
11188    pub fn searchable(&self) -> bool {
11189        self.searchable
11190    }
11191
11192    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11193        self.open_excerpts_common(true, cx)
11194    }
11195
11196    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11197        self.open_excerpts_common(false, cx)
11198    }
11199
11200    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11201        let buffer = self.buffer.read(cx);
11202        if buffer.is_singleton() {
11203            cx.propagate();
11204            return;
11205        }
11206
11207        let Some(workspace) = self.workspace() else {
11208            cx.propagate();
11209            return;
11210        };
11211
11212        let mut new_selections_by_buffer = HashMap::default();
11213        for selection in self.selections.all::<usize>(cx) {
11214            for (buffer, mut range, _) in
11215                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11216            {
11217                if selection.reversed {
11218                    mem::swap(&mut range.start, &mut range.end);
11219                }
11220                new_selections_by_buffer
11221                    .entry(buffer)
11222                    .or_insert(Vec::new())
11223                    .push(range)
11224            }
11225        }
11226
11227        // We defer the pane interaction because we ourselves are a workspace item
11228        // and activating a new item causes the pane to call a method on us reentrantly,
11229        // which panics if we're on the stack.
11230        cx.window_context().defer(move |cx| {
11231            workspace.update(cx, |workspace, cx| {
11232                let pane = if split {
11233                    workspace.adjacent_pane(cx)
11234                } else {
11235                    workspace.active_pane().clone()
11236                };
11237
11238                for (buffer, ranges) in new_selections_by_buffer {
11239                    let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
11240                    editor.update(cx, |editor, cx| {
11241                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11242                            s.select_ranges(ranges);
11243                        });
11244                    });
11245                }
11246            })
11247        });
11248    }
11249
11250    fn jump(
11251        &mut self,
11252        path: ProjectPath,
11253        position: Point,
11254        anchor: language::Anchor,
11255        offset_from_top: u32,
11256        cx: &mut ViewContext<Self>,
11257    ) {
11258        let workspace = self.workspace();
11259        cx.spawn(|_, mut cx| async move {
11260            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11261            let editor = workspace.update(&mut cx, |workspace, cx| {
11262                // Reset the preview item id before opening the new item
11263                workspace.active_pane().update(cx, |pane, cx| {
11264                    pane.set_preview_item_id(None, cx);
11265                });
11266                workspace.open_path_preview(path, None, true, true, cx)
11267            })?;
11268            let editor = editor
11269                .await?
11270                .downcast::<Editor>()
11271                .ok_or_else(|| anyhow!("opened item was not an editor"))?
11272                .downgrade();
11273            editor.update(&mut cx, |editor, cx| {
11274                let buffer = editor
11275                    .buffer()
11276                    .read(cx)
11277                    .as_singleton()
11278                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11279                let buffer = buffer.read(cx);
11280                let cursor = if buffer.can_resolve(&anchor) {
11281                    language::ToPoint::to_point(&anchor, buffer)
11282                } else {
11283                    buffer.clip_point(position, Bias::Left)
11284                };
11285
11286                let nav_history = editor.nav_history.take();
11287                editor.change_selections(
11288                    Some(Autoscroll::top_relative(offset_from_top as usize)),
11289                    cx,
11290                    |s| {
11291                        s.select_ranges([cursor..cursor]);
11292                    },
11293                );
11294                editor.nav_history = nav_history;
11295
11296                anyhow::Ok(())
11297            })??;
11298
11299            anyhow::Ok(())
11300        })
11301        .detach_and_log_err(cx);
11302    }
11303
11304    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11305        let snapshot = self.buffer.read(cx).read(cx);
11306        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11307        Some(
11308            ranges
11309                .iter()
11310                .map(move |range| {
11311                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11312                })
11313                .collect(),
11314        )
11315    }
11316
11317    fn selection_replacement_ranges(
11318        &self,
11319        range: Range<OffsetUtf16>,
11320        cx: &AppContext,
11321    ) -> Vec<Range<OffsetUtf16>> {
11322        let selections = self.selections.all::<OffsetUtf16>(cx);
11323        let newest_selection = selections
11324            .iter()
11325            .max_by_key(|selection| selection.id)
11326            .unwrap();
11327        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11328        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11329        let snapshot = self.buffer.read(cx).read(cx);
11330        selections
11331            .into_iter()
11332            .map(|mut selection| {
11333                selection.start.0 =
11334                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
11335                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11336                snapshot.clip_offset_utf16(selection.start, Bias::Left)
11337                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11338            })
11339            .collect()
11340    }
11341
11342    fn report_editor_event(
11343        &self,
11344        operation: &'static str,
11345        file_extension: Option<String>,
11346        cx: &AppContext,
11347    ) {
11348        if cfg!(any(test, feature = "test-support")) {
11349            return;
11350        }
11351
11352        let Some(project) = &self.project else { return };
11353
11354        // If None, we are in a file without an extension
11355        let file = self
11356            .buffer
11357            .read(cx)
11358            .as_singleton()
11359            .and_then(|b| b.read(cx).file());
11360        let file_extension = file_extension.or(file
11361            .as_ref()
11362            .and_then(|file| Path::new(file.file_name(cx)).extension())
11363            .and_then(|e| e.to_str())
11364            .map(|a| a.to_string()));
11365
11366        let vim_mode = cx
11367            .global::<SettingsStore>()
11368            .raw_user_settings()
11369            .get("vim_mode")
11370            == Some(&serde_json::Value::Bool(true));
11371
11372        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11373            == language::language_settings::InlineCompletionProvider::Copilot;
11374        let copilot_enabled_for_language = self
11375            .buffer
11376            .read(cx)
11377            .settings_at(0, cx)
11378            .show_inline_completions;
11379
11380        let telemetry = project.read(cx).client().telemetry().clone();
11381        telemetry.report_editor_event(
11382            file_extension,
11383            vim_mode,
11384            operation,
11385            copilot_enabled,
11386            copilot_enabled_for_language,
11387        )
11388    }
11389
11390    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11391    /// with each line being an array of {text, highlight} objects.
11392    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11393        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11394            return;
11395        };
11396
11397        #[derive(Serialize)]
11398        struct Chunk<'a> {
11399            text: String,
11400            highlight: Option<&'a str>,
11401        }
11402
11403        let snapshot = buffer.read(cx).snapshot();
11404        let range = self
11405            .selected_text_range(cx)
11406            .and_then(|selected_range| {
11407                if selected_range.is_empty() {
11408                    None
11409                } else {
11410                    Some(selected_range)
11411                }
11412            })
11413            .unwrap_or_else(|| 0..snapshot.len());
11414
11415        let chunks = snapshot.chunks(range, true);
11416        let mut lines = Vec::new();
11417        let mut line: VecDeque<Chunk> = VecDeque::new();
11418
11419        let Some(style) = self.style.as_ref() else {
11420            return;
11421        };
11422
11423        for chunk in chunks {
11424            let highlight = chunk
11425                .syntax_highlight_id
11426                .and_then(|id| id.name(&style.syntax));
11427            let mut chunk_lines = chunk.text.split('\n').peekable();
11428            while let Some(text) = chunk_lines.next() {
11429                let mut merged_with_last_token = false;
11430                if let Some(last_token) = line.back_mut() {
11431                    if last_token.highlight == highlight {
11432                        last_token.text.push_str(text);
11433                        merged_with_last_token = true;
11434                    }
11435                }
11436
11437                if !merged_with_last_token {
11438                    line.push_back(Chunk {
11439                        text: text.into(),
11440                        highlight,
11441                    });
11442                }
11443
11444                if chunk_lines.peek().is_some() {
11445                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
11446                        line.pop_front();
11447                    }
11448                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
11449                        line.pop_back();
11450                    }
11451
11452                    lines.push(mem::take(&mut line));
11453                }
11454            }
11455        }
11456
11457        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11458            return;
11459        };
11460        cx.write_to_clipboard(ClipboardItem::new(lines));
11461    }
11462
11463    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11464        &self.inlay_hint_cache
11465    }
11466
11467    pub fn replay_insert_event(
11468        &mut self,
11469        text: &str,
11470        relative_utf16_range: Option<Range<isize>>,
11471        cx: &mut ViewContext<Self>,
11472    ) {
11473        if !self.input_enabled {
11474            cx.emit(EditorEvent::InputIgnored { text: text.into() });
11475            return;
11476        }
11477        if let Some(relative_utf16_range) = relative_utf16_range {
11478            let selections = self.selections.all::<OffsetUtf16>(cx);
11479            self.change_selections(None, cx, |s| {
11480                let new_ranges = selections.into_iter().map(|range| {
11481                    let start = OffsetUtf16(
11482                        range
11483                            .head()
11484                            .0
11485                            .saturating_add_signed(relative_utf16_range.start),
11486                    );
11487                    let end = OffsetUtf16(
11488                        range
11489                            .head()
11490                            .0
11491                            .saturating_add_signed(relative_utf16_range.end),
11492                    );
11493                    start..end
11494                });
11495                s.select_ranges(new_ranges);
11496            });
11497        }
11498
11499        self.handle_input(text, cx);
11500    }
11501
11502    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11503        let Some(project) = self.project.as_ref() else {
11504            return false;
11505        };
11506        let project = project.read(cx);
11507
11508        let mut supports = false;
11509        self.buffer().read(cx).for_each_buffer(|buffer| {
11510            if !supports {
11511                supports = project
11512                    .language_servers_for_buffer(buffer.read(cx), cx)
11513                    .any(
11514                        |(_, server)| match server.capabilities().inlay_hint_provider {
11515                            Some(lsp::OneOf::Left(enabled)) => enabled,
11516                            Some(lsp::OneOf::Right(_)) => true,
11517                            None => false,
11518                        },
11519                    )
11520            }
11521        });
11522        supports
11523    }
11524
11525    pub fn focus(&self, cx: &mut WindowContext) {
11526        cx.focus(&self.focus_handle)
11527    }
11528
11529    pub fn is_focused(&self, cx: &WindowContext) -> bool {
11530        self.focus_handle.is_focused(cx)
11531    }
11532
11533    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11534        cx.emit(EditorEvent::Focused);
11535
11536        if let Some(descendant) = self
11537            .last_focused_descendant
11538            .take()
11539            .and_then(|descendant| descendant.upgrade())
11540        {
11541            cx.focus(&descendant);
11542        } else {
11543            if let Some(blame) = self.blame.as_ref() {
11544                blame.update(cx, GitBlame::focus)
11545            }
11546
11547            self.blink_manager.update(cx, BlinkManager::enable);
11548            self.show_cursor_names(cx);
11549            self.buffer.update(cx, |buffer, cx| {
11550                buffer.finalize_last_transaction(cx);
11551                if self.leader_peer_id.is_none() {
11552                    buffer.set_active_selections(
11553                        &self.selections.disjoint_anchors(),
11554                        self.selections.line_mode,
11555                        self.cursor_shape,
11556                        cx,
11557                    );
11558                }
11559            });
11560        }
11561    }
11562
11563    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11564        if event.blurred != self.focus_handle {
11565            self.last_focused_descendant = Some(event.blurred);
11566        }
11567    }
11568
11569    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11570        self.blink_manager.update(cx, BlinkManager::disable);
11571        self.buffer
11572            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11573
11574        if let Some(blame) = self.blame.as_ref() {
11575            blame.update(cx, GitBlame::blur)
11576        }
11577        self.hide_context_menu(cx);
11578        hide_hover(self, cx);
11579        cx.emit(EditorEvent::Blurred);
11580        cx.notify();
11581    }
11582
11583    pub fn register_action<A: Action>(
11584        &mut self,
11585        listener: impl Fn(&A, &mut WindowContext) + 'static,
11586    ) -> Subscription {
11587        let id = self.next_editor_action_id.post_inc();
11588        let listener = Arc::new(listener);
11589        self.editor_actions.borrow_mut().insert(
11590            id,
11591            Box::new(move |cx| {
11592                let _view = cx.view().clone();
11593                let cx = cx.window_context();
11594                let listener = listener.clone();
11595                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11596                    let action = action.downcast_ref().unwrap();
11597                    if phase == DispatchPhase::Bubble {
11598                        listener(action, cx)
11599                    }
11600                })
11601            }),
11602        );
11603
11604        let editor_actions = self.editor_actions.clone();
11605        Subscription::new(move || {
11606            editor_actions.borrow_mut().remove(&id);
11607        })
11608    }
11609
11610    pub fn file_header_size(&self) -> u8 {
11611        self.file_header_size
11612    }
11613}
11614
11615fn hunks_for_selections(
11616    multi_buffer_snapshot: &MultiBufferSnapshot,
11617    selections: &[Selection<Anchor>],
11618) -> Vec<DiffHunk<MultiBufferRow>> {
11619    let mut hunks = Vec::with_capacity(selections.len());
11620    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11621        HashMap::default();
11622    let buffer_rows_for_selections = selections.iter().map(|selection| {
11623        let head = selection.head();
11624        let tail = selection.tail();
11625        let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11626        let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11627        if start > end {
11628            end..start
11629        } else {
11630            start..end
11631        }
11632    });
11633
11634    for selected_multi_buffer_rows in buffer_rows_for_selections {
11635        let query_rows =
11636            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11637        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11638            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11639            // when the caret is just above or just below the deleted hunk.
11640            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11641            let related_to_selection = if allow_adjacent {
11642                hunk.associated_range.overlaps(&query_rows)
11643                    || hunk.associated_range.start == query_rows.end
11644                    || hunk.associated_range.end == query_rows.start
11645            } else {
11646                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11647                // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11648                hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11649                    || selected_multi_buffer_rows.end == hunk.associated_range.start
11650            };
11651            if related_to_selection {
11652                if !processed_buffer_rows
11653                    .entry(hunk.buffer_id)
11654                    .or_default()
11655                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
11656                {
11657                    continue;
11658                }
11659                hunks.push(hunk);
11660            }
11661        }
11662    }
11663
11664    hunks
11665}
11666
11667pub trait CollaborationHub {
11668    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
11669    fn user_participant_indices<'a>(
11670        &self,
11671        cx: &'a AppContext,
11672    ) -> &'a HashMap<u64, ParticipantIndex>;
11673    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
11674}
11675
11676impl CollaborationHub for Model<Project> {
11677    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
11678        self.read(cx).collaborators()
11679    }
11680
11681    fn user_participant_indices<'a>(
11682        &self,
11683        cx: &'a AppContext,
11684    ) -> &'a HashMap<u64, ParticipantIndex> {
11685        self.read(cx).user_store().read(cx).participant_indices()
11686    }
11687
11688    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
11689        let this = self.read(cx);
11690        let user_ids = this.collaborators().values().map(|c| c.user_id);
11691        this.user_store().read_with(cx, |user_store, cx| {
11692            user_store.participant_names(user_ids, cx)
11693        })
11694    }
11695}
11696
11697pub trait CompletionProvider {
11698    fn completions(
11699        &self,
11700        buffer: &Model<Buffer>,
11701        buffer_position: text::Anchor,
11702        trigger: CompletionContext,
11703        cx: &mut ViewContext<Editor>,
11704    ) -> Task<Result<Vec<Completion>>>;
11705
11706    fn resolve_completions(
11707        &self,
11708        buffer: Model<Buffer>,
11709        completion_indices: Vec<usize>,
11710        completions: Arc<RwLock<Box<[Completion]>>>,
11711        cx: &mut ViewContext<Editor>,
11712    ) -> Task<Result<bool>>;
11713
11714    fn apply_additional_edits_for_completion(
11715        &self,
11716        buffer: Model<Buffer>,
11717        completion: Completion,
11718        push_to_history: bool,
11719        cx: &mut ViewContext<Editor>,
11720    ) -> Task<Result<Option<language::Transaction>>>;
11721
11722    fn is_completion_trigger(
11723        &self,
11724        buffer: &Model<Buffer>,
11725        position: language::Anchor,
11726        text: &str,
11727        trigger_in_words: bool,
11728        cx: &mut ViewContext<Editor>,
11729    ) -> bool;
11730}
11731
11732impl CompletionProvider for Model<Project> {
11733    fn completions(
11734        &self,
11735        buffer: &Model<Buffer>,
11736        buffer_position: text::Anchor,
11737        options: CompletionContext,
11738        cx: &mut ViewContext<Editor>,
11739    ) -> Task<Result<Vec<Completion>>> {
11740        self.update(cx, |project, cx| {
11741            project.completions(&buffer, buffer_position, options, cx)
11742        })
11743    }
11744
11745    fn resolve_completions(
11746        &self,
11747        buffer: Model<Buffer>,
11748        completion_indices: Vec<usize>,
11749        completions: Arc<RwLock<Box<[Completion]>>>,
11750        cx: &mut ViewContext<Editor>,
11751    ) -> Task<Result<bool>> {
11752        self.update(cx, |project, cx| {
11753            project.resolve_completions(buffer, completion_indices, completions, cx)
11754        })
11755    }
11756
11757    fn apply_additional_edits_for_completion(
11758        &self,
11759        buffer: Model<Buffer>,
11760        completion: Completion,
11761        push_to_history: bool,
11762        cx: &mut ViewContext<Editor>,
11763    ) -> Task<Result<Option<language::Transaction>>> {
11764        self.update(cx, |project, cx| {
11765            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
11766        })
11767    }
11768
11769    fn is_completion_trigger(
11770        &self,
11771        buffer: &Model<Buffer>,
11772        position: language::Anchor,
11773        text: &str,
11774        trigger_in_words: bool,
11775        cx: &mut ViewContext<Editor>,
11776    ) -> bool {
11777        if !EditorSettings::get_global(cx).show_completions_on_input {
11778            return false;
11779        }
11780
11781        let mut chars = text.chars();
11782        let char = if let Some(char) = chars.next() {
11783            char
11784        } else {
11785            return false;
11786        };
11787        if chars.next().is_some() {
11788            return false;
11789        }
11790
11791        let buffer = buffer.read(cx);
11792        let scope = buffer.snapshot().language_scope_at(position);
11793        if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
11794            return true;
11795        }
11796
11797        buffer
11798            .completion_triggers()
11799            .iter()
11800            .any(|string| string == text)
11801    }
11802}
11803
11804fn inlay_hint_settings(
11805    location: Anchor,
11806    snapshot: &MultiBufferSnapshot,
11807    cx: &mut ViewContext<'_, Editor>,
11808) -> InlayHintSettings {
11809    let file = snapshot.file_at(location);
11810    let language = snapshot.language_at(location);
11811    let settings = all_language_settings(file, cx);
11812    settings
11813        .language(language.map(|l| l.name()).as_deref())
11814        .inlay_hints
11815}
11816
11817fn consume_contiguous_rows(
11818    contiguous_row_selections: &mut Vec<Selection<Point>>,
11819    selection: &Selection<Point>,
11820    display_map: &DisplaySnapshot,
11821    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
11822) -> (MultiBufferRow, MultiBufferRow) {
11823    contiguous_row_selections.push(selection.clone());
11824    let start_row = MultiBufferRow(selection.start.row);
11825    let mut end_row = ending_row(selection, display_map);
11826
11827    while let Some(next_selection) = selections.peek() {
11828        if next_selection.start.row <= end_row.0 {
11829            end_row = ending_row(next_selection, display_map);
11830            contiguous_row_selections.push(selections.next().unwrap().clone());
11831        } else {
11832            break;
11833        }
11834    }
11835    (start_row, end_row)
11836}
11837
11838fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
11839    if next_selection.end.column > 0 || next_selection.is_empty() {
11840        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
11841    } else {
11842        MultiBufferRow(next_selection.end.row)
11843    }
11844}
11845
11846impl EditorSnapshot {
11847    pub fn remote_selections_in_range<'a>(
11848        &'a self,
11849        range: &'a Range<Anchor>,
11850        collaboration_hub: &dyn CollaborationHub,
11851        cx: &'a AppContext,
11852    ) -> impl 'a + Iterator<Item = RemoteSelection> {
11853        let participant_names = collaboration_hub.user_names(cx);
11854        let participant_indices = collaboration_hub.user_participant_indices(cx);
11855        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
11856        let collaborators_by_replica_id = collaborators_by_peer_id
11857            .iter()
11858            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
11859            .collect::<HashMap<_, _>>();
11860        self.buffer_snapshot
11861            .selections_in_range(range, false)
11862            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
11863                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
11864                let participant_index = participant_indices.get(&collaborator.user_id).copied();
11865                let user_name = participant_names.get(&collaborator.user_id).cloned();
11866                Some(RemoteSelection {
11867                    replica_id,
11868                    selection,
11869                    cursor_shape,
11870                    line_mode,
11871                    participant_index,
11872                    peer_id: collaborator.peer_id,
11873                    user_name,
11874                })
11875            })
11876    }
11877
11878    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
11879        self.display_snapshot.buffer_snapshot.language_at(position)
11880    }
11881
11882    pub fn is_focused(&self) -> bool {
11883        self.is_focused
11884    }
11885
11886    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
11887        self.placeholder_text.as_ref()
11888    }
11889
11890    pub fn scroll_position(&self) -> gpui::Point<f32> {
11891        self.scroll_anchor.scroll_position(&self.display_snapshot)
11892    }
11893
11894    pub fn gutter_dimensions(
11895        &self,
11896        font_id: FontId,
11897        font_size: Pixels,
11898        em_width: Pixels,
11899        max_line_number_width: Pixels,
11900        cx: &AppContext,
11901    ) -> GutterDimensions {
11902        if !self.show_gutter {
11903            return GutterDimensions::default();
11904        }
11905        let descent = cx.text_system().descent(font_id, font_size);
11906
11907        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
11908            matches!(
11909                ProjectSettings::get_global(cx).git.git_gutter,
11910                Some(GitGutterSetting::TrackedFiles)
11911            )
11912        });
11913        let gutter_settings = EditorSettings::get_global(cx).gutter;
11914        let show_line_numbers = self
11915            .show_line_numbers
11916            .unwrap_or(gutter_settings.line_numbers);
11917        let line_gutter_width = if show_line_numbers {
11918            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
11919            let min_width_for_number_on_gutter = em_width * 4.0;
11920            max_line_number_width.max(min_width_for_number_on_gutter)
11921        } else {
11922            0.0.into()
11923        };
11924
11925        let show_code_actions = self
11926            .show_code_actions
11927            .unwrap_or(gutter_settings.code_actions);
11928
11929        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
11930
11931        let git_blame_entries_width = self
11932            .render_git_blame_gutter
11933            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
11934
11935        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
11936        left_padding += if show_code_actions || show_runnables {
11937            em_width * 3.0
11938        } else if show_git_gutter && show_line_numbers {
11939            em_width * 2.0
11940        } else if show_git_gutter || show_line_numbers {
11941            em_width
11942        } else {
11943            px(0.)
11944        };
11945
11946        let right_padding = if gutter_settings.folds && show_line_numbers {
11947            em_width * 4.0
11948        } else if gutter_settings.folds {
11949            em_width * 3.0
11950        } else if show_line_numbers {
11951            em_width
11952        } else {
11953            px(0.)
11954        };
11955
11956        GutterDimensions {
11957            left_padding,
11958            right_padding,
11959            width: line_gutter_width + left_padding + right_padding,
11960            margin: -descent,
11961            git_blame_entries_width,
11962        }
11963    }
11964
11965    pub fn render_fold_toggle(
11966        &self,
11967        buffer_row: MultiBufferRow,
11968        row_contains_cursor: bool,
11969        editor: View<Editor>,
11970        cx: &mut WindowContext,
11971    ) -> Option<AnyElement> {
11972        let folded = self.is_line_folded(buffer_row);
11973
11974        if let Some(crease) = self
11975            .crease_snapshot
11976            .query_row(buffer_row, &self.buffer_snapshot)
11977        {
11978            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
11979                if folded {
11980                    editor.update(cx, |editor, cx| {
11981                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
11982                    });
11983                } else {
11984                    editor.update(cx, |editor, cx| {
11985                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
11986                    });
11987                }
11988            });
11989
11990            Some((crease.render_toggle)(
11991                buffer_row,
11992                folded,
11993                toggle_callback,
11994                cx,
11995            ))
11996        } else if folded
11997            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
11998        {
11999            Some(
12000                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12001                    .selected(folded)
12002                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12003                        if folded {
12004                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
12005                        } else {
12006                            this.fold_at(&FoldAt { buffer_row }, cx);
12007                        }
12008                    }))
12009                    .into_any_element(),
12010            )
12011        } else {
12012            None
12013        }
12014    }
12015
12016    pub fn render_crease_trailer(
12017        &self,
12018        buffer_row: MultiBufferRow,
12019        cx: &mut WindowContext,
12020    ) -> Option<AnyElement> {
12021        let folded = self.is_line_folded(buffer_row);
12022        let crease = self
12023            .crease_snapshot
12024            .query_row(buffer_row, &self.buffer_snapshot)?;
12025        Some((crease.render_trailer)(buffer_row, folded, cx))
12026    }
12027}
12028
12029impl Deref for EditorSnapshot {
12030    type Target = DisplaySnapshot;
12031
12032    fn deref(&self) -> &Self::Target {
12033        &self.display_snapshot
12034    }
12035}
12036
12037#[derive(Clone, Debug, PartialEq, Eq)]
12038pub enum EditorEvent {
12039    InputIgnored {
12040        text: Arc<str>,
12041    },
12042    InputHandled {
12043        utf16_range_to_replace: Option<Range<isize>>,
12044        text: Arc<str>,
12045    },
12046    ExcerptsAdded {
12047        buffer: Model<Buffer>,
12048        predecessor: ExcerptId,
12049        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12050    },
12051    ExcerptsRemoved {
12052        ids: Vec<ExcerptId>,
12053    },
12054    ExcerptsEdited {
12055        ids: Vec<ExcerptId>,
12056    },
12057    ExcerptsExpanded {
12058        ids: Vec<ExcerptId>,
12059    },
12060    BufferEdited,
12061    Edited {
12062        transaction_id: clock::Lamport,
12063    },
12064    Reparsed(BufferId),
12065    Focused,
12066    Blurred,
12067    DirtyChanged,
12068    Saved,
12069    TitleChanged,
12070    DiffBaseChanged,
12071    SelectionsChanged {
12072        local: bool,
12073    },
12074    ScrollPositionChanged {
12075        local: bool,
12076        autoscroll: bool,
12077    },
12078    Closed,
12079    TransactionUndone {
12080        transaction_id: clock::Lamport,
12081    },
12082    TransactionBegun {
12083        transaction_id: clock::Lamport,
12084    },
12085}
12086
12087impl EventEmitter<EditorEvent> for Editor {}
12088
12089impl FocusableView for Editor {
12090    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12091        self.focus_handle.clone()
12092    }
12093}
12094
12095impl Render for Editor {
12096    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12097        let settings = ThemeSettings::get_global(cx);
12098
12099        let text_style = match self.mode {
12100            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12101                color: cx.theme().colors().editor_foreground,
12102                font_family: settings.ui_font.family.clone(),
12103                font_features: settings.ui_font.features.clone(),
12104                font_size: rems(0.875).into(),
12105                font_weight: settings.ui_font.weight,
12106                font_style: FontStyle::Normal,
12107                line_height: relative(settings.buffer_line_height.value()),
12108                background_color: None,
12109                underline: None,
12110                strikethrough: None,
12111                white_space: WhiteSpace::Normal,
12112            },
12113            EditorMode::Full => TextStyle {
12114                color: cx.theme().colors().editor_foreground,
12115                font_family: settings.buffer_font.family.clone(),
12116                font_features: settings.buffer_font.features.clone(),
12117                font_size: settings.buffer_font_size(cx).into(),
12118                font_weight: settings.buffer_font.weight,
12119                font_style: FontStyle::Normal,
12120                line_height: relative(settings.buffer_line_height.value()),
12121                background_color: None,
12122                underline: None,
12123                strikethrough: None,
12124                white_space: WhiteSpace::Normal,
12125            },
12126        };
12127
12128        let background = match self.mode {
12129            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12130            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12131            EditorMode::Full => cx.theme().colors().editor_background,
12132        };
12133
12134        EditorElement::new(
12135            cx.view(),
12136            EditorStyle {
12137                background,
12138                local_player: cx.theme().players().local(),
12139                text: text_style,
12140                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12141                syntax: cx.theme().syntax().clone(),
12142                status: cx.theme().status().clone(),
12143                inlay_hints_style: HighlightStyle {
12144                    color: Some(cx.theme().status().hint),
12145                    ..HighlightStyle::default()
12146                },
12147                suggestions_style: HighlightStyle {
12148                    color: Some(cx.theme().status().predictive),
12149                    ..HighlightStyle::default()
12150                },
12151            },
12152        )
12153    }
12154}
12155
12156impl ViewInputHandler for Editor {
12157    fn text_for_range(
12158        &mut self,
12159        range_utf16: Range<usize>,
12160        cx: &mut ViewContext<Self>,
12161    ) -> Option<String> {
12162        Some(
12163            self.buffer
12164                .read(cx)
12165                .read(cx)
12166                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12167                .collect(),
12168        )
12169    }
12170
12171    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12172        // Prevent the IME menu from appearing when holding down an alphabetic key
12173        // while input is disabled.
12174        if !self.input_enabled {
12175            return None;
12176        }
12177
12178        let range = self.selections.newest::<OffsetUtf16>(cx).range();
12179        Some(range.start.0..range.end.0)
12180    }
12181
12182    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12183        let snapshot = self.buffer.read(cx).read(cx);
12184        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12185        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12186    }
12187
12188    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12189        self.clear_highlights::<InputComposition>(cx);
12190        self.ime_transaction.take();
12191    }
12192
12193    fn replace_text_in_range(
12194        &mut self,
12195        range_utf16: Option<Range<usize>>,
12196        text: &str,
12197        cx: &mut ViewContext<Self>,
12198    ) {
12199        if !self.input_enabled {
12200            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12201            return;
12202        }
12203
12204        self.transact(cx, |this, cx| {
12205            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12206                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12207                Some(this.selection_replacement_ranges(range_utf16, cx))
12208            } else {
12209                this.marked_text_ranges(cx)
12210            };
12211
12212            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12213                let newest_selection_id = this.selections.newest_anchor().id;
12214                this.selections
12215                    .all::<OffsetUtf16>(cx)
12216                    .iter()
12217                    .zip(ranges_to_replace.iter())
12218                    .find_map(|(selection, range)| {
12219                        if selection.id == newest_selection_id {
12220                            Some(
12221                                (range.start.0 as isize - selection.head().0 as isize)
12222                                    ..(range.end.0 as isize - selection.head().0 as isize),
12223                            )
12224                        } else {
12225                            None
12226                        }
12227                    })
12228            });
12229
12230            cx.emit(EditorEvent::InputHandled {
12231                utf16_range_to_replace: range_to_replace,
12232                text: text.into(),
12233            });
12234
12235            if let Some(new_selected_ranges) = new_selected_ranges {
12236                this.change_selections(None, cx, |selections| {
12237                    selections.select_ranges(new_selected_ranges)
12238                });
12239                this.backspace(&Default::default(), cx);
12240            }
12241
12242            this.handle_input(text, cx);
12243        });
12244
12245        if let Some(transaction) = self.ime_transaction {
12246            self.buffer.update(cx, |buffer, cx| {
12247                buffer.group_until_transaction(transaction, cx);
12248            });
12249        }
12250
12251        self.unmark_text(cx);
12252    }
12253
12254    fn replace_and_mark_text_in_range(
12255        &mut self,
12256        range_utf16: Option<Range<usize>>,
12257        text: &str,
12258        new_selected_range_utf16: Option<Range<usize>>,
12259        cx: &mut ViewContext<Self>,
12260    ) {
12261        if !self.input_enabled {
12262            return;
12263        }
12264
12265        let transaction = self.transact(cx, |this, cx| {
12266            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12267                let snapshot = this.buffer.read(cx).read(cx);
12268                if let Some(relative_range_utf16) = range_utf16.as_ref() {
12269                    for marked_range in &mut marked_ranges {
12270                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12271                        marked_range.start.0 += relative_range_utf16.start;
12272                        marked_range.start =
12273                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12274                        marked_range.end =
12275                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12276                    }
12277                }
12278                Some(marked_ranges)
12279            } else if let Some(range_utf16) = range_utf16 {
12280                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12281                Some(this.selection_replacement_ranges(range_utf16, cx))
12282            } else {
12283                None
12284            };
12285
12286            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12287                let newest_selection_id = this.selections.newest_anchor().id;
12288                this.selections
12289                    .all::<OffsetUtf16>(cx)
12290                    .iter()
12291                    .zip(ranges_to_replace.iter())
12292                    .find_map(|(selection, range)| {
12293                        if selection.id == newest_selection_id {
12294                            Some(
12295                                (range.start.0 as isize - selection.head().0 as isize)
12296                                    ..(range.end.0 as isize - selection.head().0 as isize),
12297                            )
12298                        } else {
12299                            None
12300                        }
12301                    })
12302            });
12303
12304            cx.emit(EditorEvent::InputHandled {
12305                utf16_range_to_replace: range_to_replace,
12306                text: text.into(),
12307            });
12308
12309            if let Some(ranges) = ranges_to_replace {
12310                this.change_selections(None, cx, |s| s.select_ranges(ranges));
12311            }
12312
12313            let marked_ranges = {
12314                let snapshot = this.buffer.read(cx).read(cx);
12315                this.selections
12316                    .disjoint_anchors()
12317                    .iter()
12318                    .map(|selection| {
12319                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12320                    })
12321                    .collect::<Vec<_>>()
12322            };
12323
12324            if text.is_empty() {
12325                this.unmark_text(cx);
12326            } else {
12327                this.highlight_text::<InputComposition>(
12328                    marked_ranges.clone(),
12329                    HighlightStyle {
12330                        underline: Some(UnderlineStyle {
12331                            thickness: px(1.),
12332                            color: None,
12333                            wavy: false,
12334                        }),
12335                        ..Default::default()
12336                    },
12337                    cx,
12338                );
12339            }
12340
12341            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12342            let use_autoclose = this.use_autoclose;
12343            let use_auto_surround = this.use_auto_surround;
12344            this.set_use_autoclose(false);
12345            this.set_use_auto_surround(false);
12346            this.handle_input(text, cx);
12347            this.set_use_autoclose(use_autoclose);
12348            this.set_use_auto_surround(use_auto_surround);
12349
12350            if let Some(new_selected_range) = new_selected_range_utf16 {
12351                let snapshot = this.buffer.read(cx).read(cx);
12352                let new_selected_ranges = marked_ranges
12353                    .into_iter()
12354                    .map(|marked_range| {
12355                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12356                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12357                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12358                        snapshot.clip_offset_utf16(new_start, Bias::Left)
12359                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12360                    })
12361                    .collect::<Vec<_>>();
12362
12363                drop(snapshot);
12364                this.change_selections(None, cx, |selections| {
12365                    selections.select_ranges(new_selected_ranges)
12366                });
12367            }
12368        });
12369
12370        self.ime_transaction = self.ime_transaction.or(transaction);
12371        if let Some(transaction) = self.ime_transaction {
12372            self.buffer.update(cx, |buffer, cx| {
12373                buffer.group_until_transaction(transaction, cx);
12374            });
12375        }
12376
12377        if self.text_highlights::<InputComposition>(cx).is_none() {
12378            self.ime_transaction.take();
12379        }
12380    }
12381
12382    fn bounds_for_range(
12383        &mut self,
12384        range_utf16: Range<usize>,
12385        element_bounds: gpui::Bounds<Pixels>,
12386        cx: &mut ViewContext<Self>,
12387    ) -> Option<gpui::Bounds<Pixels>> {
12388        let text_layout_details = self.text_layout_details(cx);
12389        let style = &text_layout_details.editor_style;
12390        let font_id = cx.text_system().resolve_font(&style.text.font());
12391        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12392        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12393
12394        let em_width = cx
12395            .text_system()
12396            .typographic_bounds(font_id, font_size, 'm')
12397            .unwrap()
12398            .size
12399            .width;
12400
12401        let snapshot = self.snapshot(cx);
12402        let scroll_position = snapshot.scroll_position();
12403        let scroll_left = scroll_position.x * em_width;
12404
12405        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12406        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12407            + self.gutter_dimensions.width;
12408        let y = line_height * (start.row().as_f32() - scroll_position.y);
12409
12410        Some(Bounds {
12411            origin: element_bounds.origin + point(x, y),
12412            size: size(em_width, line_height),
12413        })
12414    }
12415}
12416
12417trait SelectionExt {
12418    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12419    fn spanned_rows(
12420        &self,
12421        include_end_if_at_line_start: bool,
12422        map: &DisplaySnapshot,
12423    ) -> Range<MultiBufferRow>;
12424}
12425
12426impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12427    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12428        let start = self
12429            .start
12430            .to_point(&map.buffer_snapshot)
12431            .to_display_point(map);
12432        let end = self
12433            .end
12434            .to_point(&map.buffer_snapshot)
12435            .to_display_point(map);
12436        if self.reversed {
12437            end..start
12438        } else {
12439            start..end
12440        }
12441    }
12442
12443    fn spanned_rows(
12444        &self,
12445        include_end_if_at_line_start: bool,
12446        map: &DisplaySnapshot,
12447    ) -> Range<MultiBufferRow> {
12448        let start = self.start.to_point(&map.buffer_snapshot);
12449        let mut end = self.end.to_point(&map.buffer_snapshot);
12450        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12451            end.row -= 1;
12452        }
12453
12454        let buffer_start = map.prev_line_boundary(start).0;
12455        let buffer_end = map.next_line_boundary(end).0;
12456        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12457    }
12458}
12459
12460impl<T: InvalidationRegion> InvalidationStack<T> {
12461    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12462    where
12463        S: Clone + ToOffset,
12464    {
12465        while let Some(region) = self.last() {
12466            let all_selections_inside_invalidation_ranges =
12467                if selections.len() == region.ranges().len() {
12468                    selections
12469                        .iter()
12470                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12471                        .all(|(selection, invalidation_range)| {
12472                            let head = selection.head().to_offset(buffer);
12473                            invalidation_range.start <= head && invalidation_range.end >= head
12474                        })
12475                } else {
12476                    false
12477                };
12478
12479            if all_selections_inside_invalidation_ranges {
12480                break;
12481            } else {
12482                self.pop();
12483            }
12484        }
12485    }
12486}
12487
12488impl<T> Default for InvalidationStack<T> {
12489    fn default() -> Self {
12490        Self(Default::default())
12491    }
12492}
12493
12494impl<T> Deref for InvalidationStack<T> {
12495    type Target = Vec<T>;
12496
12497    fn deref(&self) -> &Self::Target {
12498        &self.0
12499    }
12500}
12501
12502impl<T> DerefMut for InvalidationStack<T> {
12503    fn deref_mut(&mut self) -> &mut Self::Target {
12504        &mut self.0
12505    }
12506}
12507
12508impl InvalidationRegion for SnippetState {
12509    fn ranges(&self) -> &[Range<Anchor>] {
12510        &self.ranges[self.active_index]
12511    }
12512}
12513
12514pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
12515    let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
12516
12517    Box::new(move |cx: &mut BlockContext| {
12518        let group_id: SharedString = cx.block_id.to_string().into();
12519
12520        let mut text_style = cx.text_style().clone();
12521        text_style.color = diagnostic_style(diagnostic.severity, true, cx.theme().status());
12522        let theme_settings = ThemeSettings::get_global(cx);
12523        text_style.font_family = theme_settings.buffer_font.family.clone();
12524        text_style.font_style = theme_settings.buffer_font.style;
12525        text_style.font_features = theme_settings.buffer_font.features.clone();
12526        text_style.font_weight = theme_settings.buffer_font.weight;
12527
12528        let multi_line_diagnostic = diagnostic.message.contains('\n');
12529
12530        let buttons = |diagnostic: &Diagnostic, block_id: usize| {
12531            if multi_line_diagnostic {
12532                v_flex()
12533            } else {
12534                h_flex()
12535            }
12536            .children(diagnostic.is_primary.then(|| {
12537                IconButton::new(("close-block", block_id), IconName::XCircle)
12538                    .icon_color(Color::Muted)
12539                    .size(ButtonSize::Compact)
12540                    .style(ButtonStyle::Transparent)
12541                    .visible_on_hover(group_id.clone())
12542                    .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
12543                    .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
12544            }))
12545            .child(
12546                IconButton::new(("copy-block", block_id), IconName::Copy)
12547                    .icon_color(Color::Muted)
12548                    .size(ButtonSize::Compact)
12549                    .style(ButtonStyle::Transparent)
12550                    .visible_on_hover(group_id.clone())
12551                    .on_click({
12552                        let message = diagnostic.message.clone();
12553                        move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
12554                    })
12555                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
12556            )
12557        };
12558
12559        let icon_size = buttons(&diagnostic, cx.block_id)
12560            .into_any_element()
12561            .layout_as_root(AvailableSpace::min_size(), cx);
12562
12563        h_flex()
12564            .id(cx.block_id)
12565            .group(group_id.clone())
12566            .relative()
12567            .size_full()
12568            .pl(cx.gutter_dimensions.width)
12569            .w(cx.max_width + cx.gutter_dimensions.width)
12570            .child(
12571                div()
12572                    .flex()
12573                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
12574                    .flex_shrink(),
12575            )
12576            .child(buttons(&diagnostic, cx.block_id))
12577            .child(div().flex().flex_shrink_0().child(
12578                StyledText::new(text_without_backticks.clone()).with_highlights(
12579                    &text_style,
12580                    code_ranges.iter().map(|range| {
12581                        (
12582                            range.clone(),
12583                            HighlightStyle {
12584                                font_weight: Some(FontWeight::BOLD),
12585                                ..Default::default()
12586                            },
12587                        )
12588                    }),
12589                ),
12590            ))
12591            .into_any_element()
12592    })
12593}
12594
12595pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
12596    let mut text_without_backticks = String::new();
12597    let mut code_ranges = Vec::new();
12598
12599    if let Some(source) = &diagnostic.source {
12600        text_without_backticks.push_str(&source);
12601        code_ranges.push(0..source.len());
12602        text_without_backticks.push_str(": ");
12603    }
12604
12605    let mut prev_offset = 0;
12606    let mut in_code_block = false;
12607    for (ix, _) in diagnostic
12608        .message
12609        .match_indices('`')
12610        .chain([(diagnostic.message.len(), "")])
12611    {
12612        let prev_len = text_without_backticks.len();
12613        text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
12614        prev_offset = ix + 1;
12615        if in_code_block {
12616            code_ranges.push(prev_len..text_without_backticks.len());
12617            in_code_block = false;
12618        } else {
12619            in_code_block = true;
12620        }
12621    }
12622
12623    (text_without_backticks.into(), code_ranges)
12624}
12625
12626fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, colors: &StatusColors) -> Hsla {
12627    match (severity, valid) {
12628        (DiagnosticSeverity::ERROR, true) => colors.error,
12629        (DiagnosticSeverity::ERROR, false) => colors.error,
12630        (DiagnosticSeverity::WARNING, true) => colors.warning,
12631        (DiagnosticSeverity::WARNING, false) => colors.warning,
12632        (DiagnosticSeverity::INFORMATION, true) => colors.info,
12633        (DiagnosticSeverity::INFORMATION, false) => colors.info,
12634        (DiagnosticSeverity::HINT, true) => colors.info,
12635        (DiagnosticSeverity::HINT, false) => colors.info,
12636        _ => colors.ignored,
12637    }
12638}
12639
12640pub fn styled_runs_for_code_label<'a>(
12641    label: &'a CodeLabel,
12642    syntax_theme: &'a theme::SyntaxTheme,
12643) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
12644    let fade_out = HighlightStyle {
12645        fade_out: Some(0.35),
12646        ..Default::default()
12647    };
12648
12649    let mut prev_end = label.filter_range.end;
12650    label
12651        .runs
12652        .iter()
12653        .enumerate()
12654        .flat_map(move |(ix, (range, highlight_id))| {
12655            let style = if let Some(style) = highlight_id.style(syntax_theme) {
12656                style
12657            } else {
12658                return Default::default();
12659            };
12660            let mut muted_style = style;
12661            muted_style.highlight(fade_out);
12662
12663            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
12664            if range.start >= label.filter_range.end {
12665                if range.start > prev_end {
12666                    runs.push((prev_end..range.start, fade_out));
12667                }
12668                runs.push((range.clone(), muted_style));
12669            } else if range.end <= label.filter_range.end {
12670                runs.push((range.clone(), style));
12671            } else {
12672                runs.push((range.start..label.filter_range.end, style));
12673                runs.push((label.filter_range.end..range.end, muted_style));
12674            }
12675            prev_end = cmp::max(prev_end, range.end);
12676
12677            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
12678                runs.push((prev_end..label.text.len(), fade_out));
12679            }
12680
12681            runs
12682        })
12683}
12684
12685pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
12686    let mut prev_index = 0;
12687    let mut prev_codepoint: Option<char> = None;
12688    text.char_indices()
12689        .chain([(text.len(), '\0')])
12690        .filter_map(move |(index, codepoint)| {
12691            let prev_codepoint = prev_codepoint.replace(codepoint)?;
12692            let is_boundary = index == text.len()
12693                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
12694                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
12695            if is_boundary {
12696                let chunk = &text[prev_index..index];
12697                prev_index = index;
12698                Some(chunk)
12699            } else {
12700                None
12701            }
12702        })
12703}
12704
12705trait RangeToAnchorExt {
12706    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
12707}
12708
12709impl<T: ToOffset> RangeToAnchorExt for Range<T> {
12710    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
12711        let start_offset = self.start.to_offset(snapshot);
12712        let end_offset = self.end.to_offset(snapshot);
12713        if start_offset == end_offset {
12714            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
12715        } else {
12716            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
12717        }
12718    }
12719}
12720
12721pub trait RowExt {
12722    fn as_f32(&self) -> f32;
12723
12724    fn next_row(&self) -> Self;
12725
12726    fn previous_row(&self) -> Self;
12727
12728    fn minus(&self, other: Self) -> u32;
12729}
12730
12731impl RowExt for DisplayRow {
12732    fn as_f32(&self) -> f32 {
12733        self.0 as f32
12734    }
12735
12736    fn next_row(&self) -> Self {
12737        Self(self.0 + 1)
12738    }
12739
12740    fn previous_row(&self) -> Self {
12741        Self(self.0.saturating_sub(1))
12742    }
12743
12744    fn minus(&self, other: Self) -> u32 {
12745        self.0 - other.0
12746    }
12747}
12748
12749impl RowExt for MultiBufferRow {
12750    fn as_f32(&self) -> f32 {
12751        self.0 as f32
12752    }
12753
12754    fn next_row(&self) -> Self {
12755        Self(self.0 + 1)
12756    }
12757
12758    fn previous_row(&self) -> Self {
12759        Self(self.0.saturating_sub(1))
12760    }
12761
12762    fn minus(&self, other: Self) -> u32 {
12763        self.0 - other.0
12764    }
12765}
12766
12767trait RowRangeExt {
12768    type Row;
12769
12770    fn len(&self) -> usize;
12771
12772    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
12773}
12774
12775impl RowRangeExt for Range<MultiBufferRow> {
12776    type Row = MultiBufferRow;
12777
12778    fn len(&self) -> usize {
12779        (self.end.0 - self.start.0) as usize
12780    }
12781
12782    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
12783        (self.start.0..self.end.0).map(MultiBufferRow)
12784    }
12785}
12786
12787impl RowRangeExt for Range<DisplayRow> {
12788    type Row = DisplayRow;
12789
12790    fn len(&self) -> usize {
12791        (self.end.0 - self.start.0) as usize
12792    }
12793
12794    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
12795        (self.start.0..self.end.0).map(DisplayRow)
12796    }
12797}
12798
12799fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
12800    if hunk.diff_base_byte_range.is_empty() {
12801        DiffHunkStatus::Added
12802    } else if hunk.associated_range.is_empty() {
12803        DiffHunkStatus::Removed
12804    } else {
12805        DiffHunkStatus::Modified
12806    }
12807}