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;
   42mod signature_help;
   43#[cfg(any(test, feature = "test-support"))]
   44pub mod test;
   45
   46use ::git::diff::{DiffHunk, DiffHunkStatus};
   47use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
   48pub(crate) use actions::*;
   49use aho_corasick::AhoCorasick;
   50use anyhow::{anyhow, Context as _, Result};
   51use blink_manager::BlinkManager;
   52use client::{Collaborator, ParticipantIndex};
   53use clock::ReplicaId;
   54use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   55use convert_case::{Case, Casing};
   56use debounced_delay::DebouncedDelay;
   57use display_map::*;
   58pub use display_map::{DisplayPoint, FoldPlaceholder};
   59pub use editor_settings::{CurrentLineHighlight, EditorSettings};
   60use element::LineWithInvisibles;
   61pub use element::{
   62    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   63};
   64use futures::FutureExt;
   65use fuzzy::{StringMatch, StringMatchCandidate};
   66use git::blame::GitBlame;
   67use git::diff_hunk_to_display;
   68use gpui::{
   69    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   70    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardItem,
   71    Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle, FocusOutEvent,
   72    FocusableView, FontId, FontStyle, FontWeight, HighlightStyle, Hsla, InteractiveText,
   73    KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
   74    SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
   75    UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext,
   76    WeakFocusHandle, WeakView, WhiteSpace, WindowContext,
   77};
   78use highlight_matching_bracket::refresh_matching_bracket_highlights;
   79use hover_popover::{hide_hover, HoverState};
   80use hunk_diff::ExpandedHunks;
   81pub(crate) use hunk_diff::HunkToExpand;
   82use indent_guides::ActiveIndentGuidesState;
   83use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   84pub use inline_completion_provider::*;
   85pub use items::MAX_TAB_TITLE_LEN;
   86use itertools::Itertools;
   87use language::{
   88    char_kind,
   89    language_settings::{self, all_language_settings, InlayHintSettings},
   90    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   91    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   92    Point, Selection, SelectionGoal, TransactionId,
   93};
   94use language::{point_to_lsp, BufferRow, Runnable, RunnableRange};
   95use linked_editing_ranges::refresh_linked_ranges;
   96use task::{ResolvedTask, TaskTemplate, TaskVariables};
   97
   98use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
   99pub use lsp::CompletionContext;
  100use lsp::{
  101    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  102    LanguageServerId,
  103};
  104use mouse_context_menu::MouseContextMenu;
  105use movement::TextLayoutDetails;
  106pub use multi_buffer::{
  107    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  108    ToPoint,
  109};
  110use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
  111use ordered_float::OrderedFloat;
  112use parking_lot::{Mutex, RwLock};
  113use project::project_settings::{GitGutterSetting, ProjectSettings};
  114use project::{
  115    CodeAction, Completion, FormatTrigger, Item, Location, Project, ProjectPath,
  116    ProjectTransaction, TaskSourceKind, WorktreeId,
  117};
  118use rand::prelude::*;
  119use rpc::{proto::*, ErrorExt};
  120use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  121use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  122use serde::{Deserialize, Serialize};
  123use settings::{update_settings_file, Settings, SettingsStore};
  124use smallvec::SmallVec;
  125use snippet::Snippet;
  126use std::{
  127    any::TypeId,
  128    borrow::Cow,
  129    cell::RefCell,
  130    cmp::{self, Ordering, Reverse},
  131    mem,
  132    num::NonZeroU32,
  133    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  134    path::{Path, PathBuf},
  135    rc::Rc,
  136    sync::Arc,
  137    time::{Duration, Instant},
  138};
  139pub use sum_tree::Bias;
  140use sum_tree::TreeMap;
  141use text::{BufferId, OffsetUtf16, Rope};
  142use theme::{
  143    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  144    ThemeColors, ThemeSettings,
  145};
  146use ui::{
  147    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  148    ListItem, Popover, Tooltip,
  149};
  150use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  151use workspace::item::{ItemHandle, PreviewTabsSettings};
  152use workspace::notifications::{DetachAndPromptErr, NotificationId};
  153use workspace::{
  154    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  155};
  156use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  157
  158use crate::hover_links::find_url;
  159use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  160
  161pub const FILE_HEADER_HEIGHT: u8 = 1;
  162pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u8 = 1;
  163pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u8 = 1;
  164pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  165const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  166const MAX_LINE_LEN: usize = 1024;
  167const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  168const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  169pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  170#[doc(hidden)]
  171pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  172#[doc(hidden)]
  173pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  174
  175pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  176
  177pub fn render_parsed_markdown(
  178    element_id: impl Into<ElementId>,
  179    parsed: &language::ParsedMarkdown,
  180    editor_style: &EditorStyle,
  181    workspace: Option<WeakView<Workspace>>,
  182    cx: &mut WindowContext,
  183) -> InteractiveText {
  184    let code_span_background_color = cx
  185        .theme()
  186        .colors()
  187        .editor_document_highlight_read_background;
  188
  189    let highlights = gpui::combine_highlights(
  190        parsed.highlights.iter().filter_map(|(range, highlight)| {
  191            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  192            Some((range.clone(), highlight))
  193        }),
  194        parsed
  195            .regions
  196            .iter()
  197            .zip(&parsed.region_ranges)
  198            .filter_map(|(region, range)| {
  199                if region.code {
  200                    Some((
  201                        range.clone(),
  202                        HighlightStyle {
  203                            background_color: Some(code_span_background_color),
  204                            ..Default::default()
  205                        },
  206                    ))
  207                } else {
  208                    None
  209                }
  210            }),
  211    );
  212
  213    let mut links = Vec::new();
  214    let mut link_ranges = Vec::new();
  215    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  216        if let Some(link) = region.link.clone() {
  217            links.push(link);
  218            link_ranges.push(range.clone());
  219        }
  220    }
  221
  222    InteractiveText::new(
  223        element_id,
  224        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  225    )
  226    .on_click(link_ranges, move |clicked_range_ix, cx| {
  227        match &links[clicked_range_ix] {
  228            markdown::Link::Web { url } => cx.open_url(url),
  229            markdown::Link::Path { path } => {
  230                if let Some(workspace) = &workspace {
  231                    _ = workspace.update(cx, |workspace, cx| {
  232                        workspace.open_abs_path(path.clone(), false, cx).detach();
  233                    });
  234                }
  235            }
  236        }
  237    })
  238}
  239
  240#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  241pub(crate) enum InlayId {
  242    Suggestion(usize),
  243    Hint(usize),
  244}
  245
  246impl InlayId {
  247    fn id(&self) -> usize {
  248        match self {
  249            Self::Suggestion(id) => *id,
  250            Self::Hint(id) => *id,
  251        }
  252    }
  253}
  254
  255enum DiffRowHighlight {}
  256enum DocumentHighlightRead {}
  257enum DocumentHighlightWrite {}
  258enum InputComposition {}
  259
  260#[derive(Copy, Clone, PartialEq, Eq)]
  261pub enum Direction {
  262    Prev,
  263    Next,
  264}
  265
  266pub fn init_settings(cx: &mut AppContext) {
  267    EditorSettings::register(cx);
  268}
  269
  270pub fn init(cx: &mut AppContext) {
  271    init_settings(cx);
  272
  273    workspace::register_project_item::<Editor>(cx);
  274    workspace::FollowableViewRegistry::register::<Editor>(cx);
  275    workspace::register_serializable_item::<Editor>(cx);
  276
  277    cx.observe_new_views(
  278        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  279            workspace.register_action(Editor::new_file);
  280            workspace.register_action(Editor::new_file_in_direction);
  281        },
  282    )
  283    .detach();
  284
  285    cx.on_action(move |_: &workspace::NewFile, cx| {
  286        let app_state = workspace::AppState::global(cx);
  287        if let Some(app_state) = app_state.upgrade() {
  288            workspace::open_new(app_state, cx, |workspace, cx| {
  289                Editor::new_file(workspace, &Default::default(), cx)
  290            })
  291            .detach();
  292        }
  293    });
  294    cx.on_action(move |_: &workspace::NewWindow, cx| {
  295        let app_state = workspace::AppState::global(cx);
  296        if let Some(app_state) = app_state.upgrade() {
  297            workspace::open_new(app_state, cx, |workspace, cx| {
  298                Editor::new_file(workspace, &Default::default(), cx)
  299            })
  300            .detach();
  301        }
  302    });
  303}
  304
  305pub struct SearchWithinRange;
  306
  307trait InvalidationRegion {
  308    fn ranges(&self) -> &[Range<Anchor>];
  309}
  310
  311#[derive(Clone, Debug, PartialEq)]
  312pub enum SelectPhase {
  313    Begin {
  314        position: DisplayPoint,
  315        add: bool,
  316        click_count: usize,
  317    },
  318    BeginColumnar {
  319        position: DisplayPoint,
  320        reset: bool,
  321        goal_column: u32,
  322    },
  323    Extend {
  324        position: DisplayPoint,
  325        click_count: usize,
  326    },
  327    Update {
  328        position: DisplayPoint,
  329        goal_column: u32,
  330        scroll_delta: gpui::Point<f32>,
  331    },
  332    End,
  333}
  334
  335#[derive(Clone, Debug)]
  336pub enum SelectMode {
  337    Character,
  338    Word(Range<Anchor>),
  339    Line(Range<Anchor>),
  340    All,
  341}
  342
  343#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  344pub enum EditorMode {
  345    SingleLine { auto_width: bool },
  346    AutoHeight { max_lines: usize },
  347    Full,
  348}
  349
  350#[derive(Clone, Debug)]
  351pub enum SoftWrap {
  352    None,
  353    PreferLine,
  354    EditorWidth,
  355    Column(u32),
  356}
  357
  358#[derive(Clone)]
  359pub struct EditorStyle {
  360    pub background: Hsla,
  361    pub local_player: PlayerColor,
  362    pub text: TextStyle,
  363    pub scrollbar_width: Pixels,
  364    pub syntax: Arc<SyntaxTheme>,
  365    pub status: StatusColors,
  366    pub inlay_hints_style: HighlightStyle,
  367    pub suggestions_style: HighlightStyle,
  368}
  369
  370impl Default for EditorStyle {
  371    fn default() -> Self {
  372        Self {
  373            background: Hsla::default(),
  374            local_player: PlayerColor::default(),
  375            text: TextStyle::default(),
  376            scrollbar_width: Pixels::default(),
  377            syntax: Default::default(),
  378            // HACK: Status colors don't have a real default.
  379            // We should look into removing the status colors from the editor
  380            // style and retrieve them directly from the theme.
  381            status: StatusColors::dark(),
  382            inlay_hints_style: HighlightStyle::default(),
  383            suggestions_style: HighlightStyle::default(),
  384        }
  385    }
  386}
  387
  388type CompletionId = usize;
  389
  390#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  391struct EditorActionId(usize);
  392
  393impl EditorActionId {
  394    pub fn post_inc(&mut self) -> Self {
  395        let answer = self.0;
  396
  397        *self = Self(answer + 1);
  398
  399        Self(answer)
  400    }
  401}
  402
  403// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  404// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  405
  406type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  407type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  408
  409struct ScrollbarMarkerState {
  410    scrollbar_size: Size<Pixels>,
  411    dirty: bool,
  412    markers: Arc<[PaintQuad]>,
  413    pending_refresh: Option<Task<Result<()>>>,
  414}
  415
  416impl ScrollbarMarkerState {
  417    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  418        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  419    }
  420}
  421
  422impl Default for ScrollbarMarkerState {
  423    fn default() -> Self {
  424        Self {
  425            scrollbar_size: Size::default(),
  426            dirty: false,
  427            markers: Arc::from([]),
  428            pending_refresh: None,
  429        }
  430    }
  431}
  432
  433#[derive(Clone, Debug)]
  434struct RunnableTasks {
  435    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  436    offset: MultiBufferOffset,
  437    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  438    column: u32,
  439    // Values of all named captures, including those starting with '_'
  440    extra_variables: HashMap<String, String>,
  441    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  442    context_range: Range<BufferOffset>,
  443}
  444
  445#[derive(Clone)]
  446struct ResolvedTasks {
  447    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  448    position: Anchor,
  449}
  450#[derive(Copy, Clone, Debug)]
  451struct MultiBufferOffset(usize);
  452#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  453struct BufferOffset(usize);
  454/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  455///
  456/// See the [module level documentation](self) for more information.
  457pub struct Editor {
  458    focus_handle: FocusHandle,
  459    last_focused_descendant: Option<WeakFocusHandle>,
  460    /// The text buffer being edited
  461    buffer: Model<MultiBuffer>,
  462    /// Map of how text in the buffer should be displayed.
  463    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  464    pub display_map: Model<DisplayMap>,
  465    pub selections: SelectionsCollection,
  466    pub scroll_manager: ScrollManager,
  467    /// When inline assist editors are linked, they all render cursors because
  468    /// typing enters text into each of them, even the ones that aren't focused.
  469    pub(crate) show_cursor_when_unfocused: bool,
  470    columnar_selection_tail: Option<Anchor>,
  471    add_selections_state: Option<AddSelectionsState>,
  472    select_next_state: Option<SelectNextState>,
  473    select_prev_state: Option<SelectNextState>,
  474    selection_history: SelectionHistory,
  475    autoclose_regions: Vec<AutocloseRegion>,
  476    snippet_stack: InvalidationStack<SnippetState>,
  477    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  478    ime_transaction: Option<TransactionId>,
  479    active_diagnostics: Option<ActiveDiagnosticGroup>,
  480    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  481    project: Option<Model<Project>>,
  482    completion_provider: Option<Box<dyn CompletionProvider>>,
  483    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  484    blink_manager: Model<BlinkManager>,
  485    show_cursor_names: bool,
  486    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  487    pub show_local_selections: bool,
  488    mode: EditorMode,
  489    show_breadcrumbs: bool,
  490    show_gutter: bool,
  491    show_line_numbers: Option<bool>,
  492    show_git_diff_gutter: Option<bool>,
  493    show_code_actions: Option<bool>,
  494    show_runnables: Option<bool>,
  495    show_wrap_guides: Option<bool>,
  496    show_indent_guides: Option<bool>,
  497    placeholder_text: Option<Arc<str>>,
  498    highlight_order: usize,
  499    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  500    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  501    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  502    scrollbar_marker_state: ScrollbarMarkerState,
  503    active_indent_guides_state: ActiveIndentGuidesState,
  504    nav_history: Option<ItemNavHistory>,
  505    context_menu: RwLock<Option<ContextMenu>>,
  506    mouse_context_menu: Option<MouseContextMenu>,
  507    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  508    signature_help_state: SignatureHelpState,
  509    auto_signature_help: Option<bool>,
  510    find_all_references_task_sources: Vec<Anchor>,
  511    next_completion_id: CompletionId,
  512    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  513    available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
  514    code_actions_task: Option<Task<()>>,
  515    document_highlights_task: Option<Task<()>>,
  516    linked_editing_range_task: Option<Task<Option<()>>>,
  517    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  518    pending_rename: Option<RenameState>,
  519    searchable: bool,
  520    cursor_shape: CursorShape,
  521    current_line_highlight: Option<CurrentLineHighlight>,
  522    collapse_matches: bool,
  523    autoindent_mode: Option<AutoindentMode>,
  524    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  525    keymap_context_layers: BTreeMap<TypeId, KeyContext>,
  526    input_enabled: bool,
  527    use_modal_editing: bool,
  528    read_only: bool,
  529    leader_peer_id: Option<PeerId>,
  530    remote_id: Option<ViewId>,
  531    hover_state: HoverState,
  532    gutter_hovered: bool,
  533    hovered_link_state: Option<HoveredLinkState>,
  534    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  535    active_inline_completion: Option<Inlay>,
  536    show_inline_completions: bool,
  537    inlay_hint_cache: InlayHintCache,
  538    expanded_hunks: ExpandedHunks,
  539    next_inlay_id: usize,
  540    _subscriptions: Vec<Subscription>,
  541    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  542    gutter_dimensions: GutterDimensions,
  543    pub vim_replace_map: HashMap<Range<usize>, String>,
  544    style: Option<EditorStyle>,
  545    next_editor_action_id: EditorActionId,
  546    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  547    use_autoclose: bool,
  548    use_auto_surround: bool,
  549    auto_replace_emoji_shortcode: bool,
  550    show_git_blame_gutter: bool,
  551    show_git_blame_inline: bool,
  552    show_git_blame_inline_delay_task: Option<Task<()>>,
  553    git_blame_inline_enabled: bool,
  554    serialize_dirty_buffers: bool,
  555    show_selection_menu: Option<bool>,
  556    blame: Option<Model<GitBlame>>,
  557    blame_subscription: Option<Subscription>,
  558    custom_context_menu: Option<
  559        Box<
  560            dyn 'static
  561                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  562        >,
  563    >,
  564    last_bounds: Option<Bounds<Pixels>>,
  565    expect_bounds_change: Option<Bounds<Pixels>>,
  566    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  567    tasks_update_task: Option<Task<()>>,
  568    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  569    file_header_size: u8,
  570    breadcrumb_header: Option<String>,
  571}
  572
  573#[derive(Clone)]
  574pub struct EditorSnapshot {
  575    pub mode: EditorMode,
  576    show_gutter: bool,
  577    show_line_numbers: Option<bool>,
  578    show_git_diff_gutter: Option<bool>,
  579    show_code_actions: Option<bool>,
  580    show_runnables: Option<bool>,
  581    render_git_blame_gutter: bool,
  582    pub display_snapshot: DisplaySnapshot,
  583    pub placeholder_text: Option<Arc<str>>,
  584    is_focused: bool,
  585    scroll_anchor: ScrollAnchor,
  586    ongoing_scroll: OngoingScroll,
  587    current_line_highlight: CurrentLineHighlight,
  588    gutter_hovered: bool,
  589}
  590
  591const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
  592
  593#[derive(Debug, Clone, Copy)]
  594pub struct GutterDimensions {
  595    pub left_padding: Pixels,
  596    pub right_padding: Pixels,
  597    pub width: Pixels,
  598    pub margin: Pixels,
  599    pub git_blame_entries_width: Option<Pixels>,
  600}
  601
  602impl GutterDimensions {
  603    /// The full width of the space taken up by the gutter.
  604    pub fn full_width(&self) -> Pixels {
  605        self.margin + self.width
  606    }
  607
  608    /// The width of the space reserved for the fold indicators,
  609    /// use alongside 'justify_end' and `gutter_width` to
  610    /// right align content with the line numbers
  611    pub fn fold_area_width(&self) -> Pixels {
  612        self.margin + self.right_padding
  613    }
  614}
  615
  616impl Default for GutterDimensions {
  617    fn default() -> Self {
  618        Self {
  619            left_padding: Pixels::ZERO,
  620            right_padding: Pixels::ZERO,
  621            width: Pixels::ZERO,
  622            margin: Pixels::ZERO,
  623            git_blame_entries_width: None,
  624        }
  625    }
  626}
  627
  628#[derive(Debug)]
  629pub struct RemoteSelection {
  630    pub replica_id: ReplicaId,
  631    pub selection: Selection<Anchor>,
  632    pub cursor_shape: CursorShape,
  633    pub peer_id: PeerId,
  634    pub line_mode: bool,
  635    pub participant_index: Option<ParticipantIndex>,
  636    pub user_name: Option<SharedString>,
  637}
  638
  639#[derive(Clone, Debug)]
  640struct SelectionHistoryEntry {
  641    selections: Arc<[Selection<Anchor>]>,
  642    select_next_state: Option<SelectNextState>,
  643    select_prev_state: Option<SelectNextState>,
  644    add_selections_state: Option<AddSelectionsState>,
  645}
  646
  647enum SelectionHistoryMode {
  648    Normal,
  649    Undoing,
  650    Redoing,
  651}
  652
  653#[derive(Clone, PartialEq, Eq, Hash)]
  654struct HoveredCursor {
  655    replica_id: u16,
  656    selection_id: usize,
  657}
  658
  659impl Default for SelectionHistoryMode {
  660    fn default() -> Self {
  661        Self::Normal
  662    }
  663}
  664
  665#[derive(Default)]
  666struct SelectionHistory {
  667    #[allow(clippy::type_complexity)]
  668    selections_by_transaction:
  669        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  670    mode: SelectionHistoryMode,
  671    undo_stack: VecDeque<SelectionHistoryEntry>,
  672    redo_stack: VecDeque<SelectionHistoryEntry>,
  673}
  674
  675impl SelectionHistory {
  676    fn insert_transaction(
  677        &mut self,
  678        transaction_id: TransactionId,
  679        selections: Arc<[Selection<Anchor>]>,
  680    ) {
  681        self.selections_by_transaction
  682            .insert(transaction_id, (selections, None));
  683    }
  684
  685    #[allow(clippy::type_complexity)]
  686    fn transaction(
  687        &self,
  688        transaction_id: TransactionId,
  689    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  690        self.selections_by_transaction.get(&transaction_id)
  691    }
  692
  693    #[allow(clippy::type_complexity)]
  694    fn transaction_mut(
  695        &mut self,
  696        transaction_id: TransactionId,
  697    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  698        self.selections_by_transaction.get_mut(&transaction_id)
  699    }
  700
  701    fn push(&mut self, entry: SelectionHistoryEntry) {
  702        if !entry.selections.is_empty() {
  703            match self.mode {
  704                SelectionHistoryMode::Normal => {
  705                    self.push_undo(entry);
  706                    self.redo_stack.clear();
  707                }
  708                SelectionHistoryMode::Undoing => self.push_redo(entry),
  709                SelectionHistoryMode::Redoing => self.push_undo(entry),
  710            }
  711        }
  712    }
  713
  714    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  715        if self
  716            .undo_stack
  717            .back()
  718            .map_or(true, |e| e.selections != entry.selections)
  719        {
  720            self.undo_stack.push_back(entry);
  721            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  722                self.undo_stack.pop_front();
  723            }
  724        }
  725    }
  726
  727    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  728        if self
  729            .redo_stack
  730            .back()
  731            .map_or(true, |e| e.selections != entry.selections)
  732        {
  733            self.redo_stack.push_back(entry);
  734            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  735                self.redo_stack.pop_front();
  736            }
  737        }
  738    }
  739}
  740
  741struct RowHighlight {
  742    index: usize,
  743    range: RangeInclusive<Anchor>,
  744    color: Option<Hsla>,
  745    should_autoscroll: bool,
  746}
  747
  748#[derive(Clone, Debug)]
  749struct AddSelectionsState {
  750    above: bool,
  751    stack: Vec<usize>,
  752}
  753
  754#[derive(Clone)]
  755struct SelectNextState {
  756    query: AhoCorasick,
  757    wordwise: bool,
  758    done: bool,
  759}
  760
  761impl std::fmt::Debug for SelectNextState {
  762    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  763        f.debug_struct(std::any::type_name::<Self>())
  764            .field("wordwise", &self.wordwise)
  765            .field("done", &self.done)
  766            .finish()
  767    }
  768}
  769
  770#[derive(Debug)]
  771struct AutocloseRegion {
  772    selection_id: usize,
  773    range: Range<Anchor>,
  774    pair: BracketPair,
  775}
  776
  777#[derive(Debug)]
  778struct SnippetState {
  779    ranges: Vec<Vec<Range<Anchor>>>,
  780    active_index: usize,
  781}
  782
  783#[doc(hidden)]
  784pub struct RenameState {
  785    pub range: Range<Anchor>,
  786    pub old_name: Arc<str>,
  787    pub editor: View<Editor>,
  788    block_id: BlockId,
  789}
  790
  791struct InvalidationStack<T>(Vec<T>);
  792
  793struct RegisteredInlineCompletionProvider {
  794    provider: Arc<dyn InlineCompletionProviderHandle>,
  795    _subscription: Subscription,
  796}
  797
  798enum ContextMenu {
  799    Completions(CompletionsMenu),
  800    CodeActions(CodeActionsMenu),
  801}
  802
  803impl ContextMenu {
  804    fn select_first(
  805        &mut self,
  806        project: Option<&Model<Project>>,
  807        cx: &mut ViewContext<Editor>,
  808    ) -> bool {
  809        if self.visible() {
  810            match self {
  811                ContextMenu::Completions(menu) => menu.select_first(project, cx),
  812                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  813            }
  814            true
  815        } else {
  816            false
  817        }
  818    }
  819
  820    fn select_prev(
  821        &mut self,
  822        project: Option<&Model<Project>>,
  823        cx: &mut ViewContext<Editor>,
  824    ) -> bool {
  825        if self.visible() {
  826            match self {
  827                ContextMenu::Completions(menu) => menu.select_prev(project, cx),
  828                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  829            }
  830            true
  831        } else {
  832            false
  833        }
  834    }
  835
  836    fn select_next(
  837        &mut self,
  838        project: Option<&Model<Project>>,
  839        cx: &mut ViewContext<Editor>,
  840    ) -> bool {
  841        if self.visible() {
  842            match self {
  843                ContextMenu::Completions(menu) => menu.select_next(project, cx),
  844                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  845            }
  846            true
  847        } else {
  848            false
  849        }
  850    }
  851
  852    fn select_last(
  853        &mut self,
  854        project: Option<&Model<Project>>,
  855        cx: &mut ViewContext<Editor>,
  856    ) -> bool {
  857        if self.visible() {
  858            match self {
  859                ContextMenu::Completions(menu) => menu.select_last(project, cx),
  860                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  861            }
  862            true
  863        } else {
  864            false
  865        }
  866    }
  867
  868    fn visible(&self) -> bool {
  869        match self {
  870            ContextMenu::Completions(menu) => menu.visible(),
  871            ContextMenu::CodeActions(menu) => menu.visible(),
  872        }
  873    }
  874
  875    fn render(
  876        &self,
  877        cursor_position: DisplayPoint,
  878        style: &EditorStyle,
  879        max_height: Pixels,
  880        workspace: Option<WeakView<Workspace>>,
  881        cx: &mut ViewContext<Editor>,
  882    ) -> (ContextMenuOrigin, AnyElement) {
  883        match self {
  884            ContextMenu::Completions(menu) => (
  885                ContextMenuOrigin::EditorPoint(cursor_position),
  886                menu.render(style, max_height, workspace, cx),
  887            ),
  888            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  889        }
  890    }
  891}
  892
  893enum ContextMenuOrigin {
  894    EditorPoint(DisplayPoint),
  895    GutterIndicator(DisplayRow),
  896}
  897
  898#[derive(Clone)]
  899struct CompletionsMenu {
  900    id: CompletionId,
  901    initial_position: Anchor,
  902    buffer: Model<Buffer>,
  903    completions: Arc<RwLock<Box<[Completion]>>>,
  904    match_candidates: Arc<[StringMatchCandidate]>,
  905    matches: Arc<[StringMatch]>,
  906    selected_item: usize,
  907    scroll_handle: UniformListScrollHandle,
  908    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  909}
  910
  911impl CompletionsMenu {
  912    fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  913        self.selected_item = 0;
  914        self.scroll_handle.scroll_to_item(self.selected_item);
  915        self.attempt_resolve_selected_completion_documentation(project, cx);
  916        cx.notify();
  917    }
  918
  919    fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  920        if self.selected_item > 0 {
  921            self.selected_item -= 1;
  922        } else {
  923            self.selected_item = self.matches.len() - 1;
  924        }
  925        self.scroll_handle.scroll_to_item(self.selected_item);
  926        self.attempt_resolve_selected_completion_documentation(project, cx);
  927        cx.notify();
  928    }
  929
  930    fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  931        if self.selected_item + 1 < self.matches.len() {
  932            self.selected_item += 1;
  933        } else {
  934            self.selected_item = 0;
  935        }
  936        self.scroll_handle.scroll_to_item(self.selected_item);
  937        self.attempt_resolve_selected_completion_documentation(project, cx);
  938        cx.notify();
  939    }
  940
  941    fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  942        self.selected_item = self.matches.len() - 1;
  943        self.scroll_handle.scroll_to_item(self.selected_item);
  944        self.attempt_resolve_selected_completion_documentation(project, cx);
  945        cx.notify();
  946    }
  947
  948    fn pre_resolve_completion_documentation(
  949        buffer: Model<Buffer>,
  950        completions: Arc<RwLock<Box<[Completion]>>>,
  951        matches: Arc<[StringMatch]>,
  952        editor: &Editor,
  953        cx: &mut ViewContext<Editor>,
  954    ) -> Task<()> {
  955        let settings = EditorSettings::get_global(cx);
  956        if !settings.show_completion_documentation {
  957            return Task::ready(());
  958        }
  959
  960        let Some(provider) = editor.completion_provider.as_ref() else {
  961            return Task::ready(());
  962        };
  963
  964        let resolve_task = provider.resolve_completions(
  965            buffer,
  966            matches.iter().map(|m| m.candidate_id).collect(),
  967            completions.clone(),
  968            cx,
  969        );
  970
  971        return cx.spawn(move |this, mut cx| async move {
  972            if let Some(true) = resolve_task.await.log_err() {
  973                this.update(&mut cx, |_, cx| cx.notify()).ok();
  974            }
  975        });
  976    }
  977
  978    fn attempt_resolve_selected_completion_documentation(
  979        &mut self,
  980        project: Option<&Model<Project>>,
  981        cx: &mut ViewContext<Editor>,
  982    ) {
  983        let settings = EditorSettings::get_global(cx);
  984        if !settings.show_completion_documentation {
  985            return;
  986        }
  987
  988        let completion_index = self.matches[self.selected_item].candidate_id;
  989        let Some(project) = project else {
  990            return;
  991        };
  992
  993        let resolve_task = project.update(cx, |project, cx| {
  994            project.resolve_completions(
  995                self.buffer.clone(),
  996                vec![completion_index],
  997                self.completions.clone(),
  998                cx,
  999            )
 1000        });
 1001
 1002        let delay_ms =
 1003            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1004        let delay = Duration::from_millis(delay_ms);
 1005
 1006        self.selected_completion_documentation_resolve_debounce
 1007            .lock()
 1008            .fire_new(delay, cx, |_, cx| {
 1009                cx.spawn(move |this, mut cx| async move {
 1010                    if let Some(true) = resolve_task.await.log_err() {
 1011                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1012                    }
 1013                })
 1014            });
 1015    }
 1016
 1017    fn visible(&self) -> bool {
 1018        !self.matches.is_empty()
 1019    }
 1020
 1021    fn render(
 1022        &self,
 1023        style: &EditorStyle,
 1024        max_height: Pixels,
 1025        workspace: Option<WeakView<Workspace>>,
 1026        cx: &mut ViewContext<Editor>,
 1027    ) -> AnyElement {
 1028        let settings = EditorSettings::get_global(cx);
 1029        let show_completion_documentation = settings.show_completion_documentation;
 1030
 1031        let widest_completion_ix = self
 1032            .matches
 1033            .iter()
 1034            .enumerate()
 1035            .max_by_key(|(_, mat)| {
 1036                let completions = self.completions.read();
 1037                let completion = &completions[mat.candidate_id];
 1038                let documentation = &completion.documentation;
 1039
 1040                let mut len = completion.label.text.chars().count();
 1041                if let Some(Documentation::SingleLine(text)) = documentation {
 1042                    if show_completion_documentation {
 1043                        len += text.chars().count();
 1044                    }
 1045                }
 1046
 1047                len
 1048            })
 1049            .map(|(ix, _)| ix);
 1050
 1051        let completions = self.completions.clone();
 1052        let matches = self.matches.clone();
 1053        let selected_item = self.selected_item;
 1054        let style = style.clone();
 1055
 1056        let multiline_docs = if show_completion_documentation {
 1057            let mat = &self.matches[selected_item];
 1058            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1059                Some(Documentation::MultiLinePlainText(text)) => {
 1060                    Some(div().child(SharedString::from(text.clone())))
 1061                }
 1062                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1063                    Some(div().child(render_parsed_markdown(
 1064                        "completions_markdown",
 1065                        parsed,
 1066                        &style,
 1067                        workspace,
 1068                        cx,
 1069                    )))
 1070                }
 1071                _ => None,
 1072            };
 1073            multiline_docs.map(|div| {
 1074                div.id("multiline_docs")
 1075                    .max_h(max_height)
 1076                    .flex_1()
 1077                    .px_1p5()
 1078                    .py_1()
 1079                    .min_w(px(260.))
 1080                    .max_w(px(640.))
 1081                    .w(px(500.))
 1082                    .overflow_y_scroll()
 1083                    .occlude()
 1084            })
 1085        } else {
 1086            None
 1087        };
 1088
 1089        let list = uniform_list(
 1090            cx.view().clone(),
 1091            "completions",
 1092            matches.len(),
 1093            move |_editor, range, cx| {
 1094                let start_ix = range.start;
 1095                let completions_guard = completions.read();
 1096
 1097                matches[range]
 1098                    .iter()
 1099                    .enumerate()
 1100                    .map(|(ix, mat)| {
 1101                        let item_ix = start_ix + ix;
 1102                        let candidate_id = mat.candidate_id;
 1103                        let completion = &completions_guard[candidate_id];
 1104
 1105                        let documentation = if show_completion_documentation {
 1106                            &completion.documentation
 1107                        } else {
 1108                            &None
 1109                        };
 1110
 1111                        let highlights = gpui::combine_highlights(
 1112                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1113                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1114                                |(range, mut highlight)| {
 1115                                    // Ignore font weight for syntax highlighting, as we'll use it
 1116                                    // for fuzzy matches.
 1117                                    highlight.font_weight = None;
 1118
 1119                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1120                                        highlight.strikethrough = Some(StrikethroughStyle {
 1121                                            thickness: 1.0.into(),
 1122                                            ..Default::default()
 1123                                        });
 1124                                        highlight.color = Some(cx.theme().colors().text_muted);
 1125                                    }
 1126
 1127                                    (range, highlight)
 1128                                },
 1129                            ),
 1130                        );
 1131                        let completion_label = StyledText::new(completion.label.text.clone())
 1132                            .with_highlights(&style.text, highlights);
 1133                        let documentation_label =
 1134                            if let Some(Documentation::SingleLine(text)) = documentation {
 1135                                if text.trim().is_empty() {
 1136                                    None
 1137                                } else {
 1138                                    Some(
 1139                                        Label::new(text.clone())
 1140                                            .ml_4()
 1141                                            .size(LabelSize::Small)
 1142                                            .color(Color::Muted),
 1143                                    )
 1144                                }
 1145                            } else {
 1146                                None
 1147                            };
 1148
 1149                        div().min_w(px(220.)).max_w(px(540.)).child(
 1150                            ListItem::new(mat.candidate_id)
 1151                                .inset(true)
 1152                                .selected(item_ix == selected_item)
 1153                                .on_click(cx.listener(move |editor, _event, cx| {
 1154                                    cx.stop_propagation();
 1155                                    if let Some(task) = editor.confirm_completion(
 1156                                        &ConfirmCompletion {
 1157                                            item_ix: Some(item_ix),
 1158                                        },
 1159                                        cx,
 1160                                    ) {
 1161                                        task.detach_and_log_err(cx)
 1162                                    }
 1163                                }))
 1164                                .child(h_flex().overflow_hidden().child(completion_label))
 1165                                .end_slot::<Label>(documentation_label),
 1166                        )
 1167                    })
 1168                    .collect()
 1169            },
 1170        )
 1171        .occlude()
 1172        .max_h(max_height)
 1173        .track_scroll(self.scroll_handle.clone())
 1174        .with_width_from_item(widest_completion_ix)
 1175        .with_sizing_behavior(ListSizingBehavior::Infer);
 1176
 1177        Popover::new()
 1178            .child(list)
 1179            .when_some(multiline_docs, |popover, multiline_docs| {
 1180                popover.aside(multiline_docs)
 1181            })
 1182            .into_any_element()
 1183    }
 1184
 1185    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1186        let mut matches = if let Some(query) = query {
 1187            fuzzy::match_strings(
 1188                &self.match_candidates,
 1189                query,
 1190                query.chars().any(|c| c.is_uppercase()),
 1191                100,
 1192                &Default::default(),
 1193                executor,
 1194            )
 1195            .await
 1196        } else {
 1197            self.match_candidates
 1198                .iter()
 1199                .enumerate()
 1200                .map(|(candidate_id, candidate)| StringMatch {
 1201                    candidate_id,
 1202                    score: Default::default(),
 1203                    positions: Default::default(),
 1204                    string: candidate.string.clone(),
 1205                })
 1206                .collect()
 1207        };
 1208
 1209        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1210        if let Some(query) = query {
 1211            if let Some(query_start) = query.chars().next() {
 1212                matches.retain(|string_match| {
 1213                    split_words(&string_match.string).any(|word| {
 1214                        // Check that the first codepoint of the word as lowercase matches the first
 1215                        // codepoint of the query as lowercase
 1216                        word.chars()
 1217                            .flat_map(|codepoint| codepoint.to_lowercase())
 1218                            .zip(query_start.to_lowercase())
 1219                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1220                    })
 1221                });
 1222            }
 1223        }
 1224
 1225        let completions = self.completions.read();
 1226        matches.sort_unstable_by_key(|mat| {
 1227            // We do want to strike a balance here between what the language server tells us
 1228            // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1229            // `Creat` and there is a local variable called `CreateComponent`).
 1230            // So what we do is: we bucket all matches into two buckets
 1231            // - Strong matches
 1232            // - Weak matches
 1233            // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1234            // and the Weak matches are the rest.
 1235            //
 1236            // For the strong matches, we sort by the language-servers score first and for the weak
 1237            // matches, we prefer our fuzzy finder first.
 1238            //
 1239            // The thinking behind that: it's useless to take the sort_text the language-server gives
 1240            // us into account when it's obviously a bad match.
 1241
 1242            #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1243            enum MatchScore<'a> {
 1244                Strong {
 1245                    sort_text: Option<&'a str>,
 1246                    score: Reverse<OrderedFloat<f64>>,
 1247                    sort_key: (usize, &'a str),
 1248                },
 1249                Weak {
 1250                    score: Reverse<OrderedFloat<f64>>,
 1251                    sort_text: Option<&'a str>,
 1252                    sort_key: (usize, &'a str),
 1253                },
 1254            }
 1255
 1256            let completion = &completions[mat.candidate_id];
 1257            let sort_key = completion.sort_key();
 1258            let sort_text = completion.lsp_completion.sort_text.as_deref();
 1259            let score = Reverse(OrderedFloat(mat.score));
 1260
 1261            if mat.score >= 0.2 {
 1262                MatchScore::Strong {
 1263                    sort_text,
 1264                    score,
 1265                    sort_key,
 1266                }
 1267            } else {
 1268                MatchScore::Weak {
 1269                    score,
 1270                    sort_text,
 1271                    sort_key,
 1272                }
 1273            }
 1274        });
 1275
 1276        for mat in &mut matches {
 1277            let completion = &completions[mat.candidate_id];
 1278            mat.string.clone_from(&completion.label.text);
 1279            for position in &mut mat.positions {
 1280                *position += completion.label.filter_range.start;
 1281            }
 1282        }
 1283        drop(completions);
 1284
 1285        self.matches = matches.into();
 1286        self.selected_item = 0;
 1287    }
 1288}
 1289
 1290#[derive(Clone)]
 1291struct CodeActionContents {
 1292    tasks: Option<Arc<ResolvedTasks>>,
 1293    actions: Option<Arc<[CodeAction]>>,
 1294}
 1295
 1296impl CodeActionContents {
 1297    fn len(&self) -> usize {
 1298        match (&self.tasks, &self.actions) {
 1299            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1300            (Some(tasks), None) => tasks.templates.len(),
 1301            (None, Some(actions)) => actions.len(),
 1302            (None, None) => 0,
 1303        }
 1304    }
 1305
 1306    fn is_empty(&self) -> bool {
 1307        match (&self.tasks, &self.actions) {
 1308            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1309            (Some(tasks), None) => tasks.templates.is_empty(),
 1310            (None, Some(actions)) => actions.is_empty(),
 1311            (None, None) => true,
 1312        }
 1313    }
 1314
 1315    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1316        self.tasks
 1317            .iter()
 1318            .flat_map(|tasks| {
 1319                tasks
 1320                    .templates
 1321                    .iter()
 1322                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1323            })
 1324            .chain(self.actions.iter().flat_map(|actions| {
 1325                actions
 1326                    .iter()
 1327                    .map(|action| CodeActionsItem::CodeAction(action.clone()))
 1328            }))
 1329    }
 1330    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1331        match (&self.tasks, &self.actions) {
 1332            (Some(tasks), Some(actions)) => {
 1333                if index < tasks.templates.len() {
 1334                    tasks
 1335                        .templates
 1336                        .get(index)
 1337                        .cloned()
 1338                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1339                } else {
 1340                    actions
 1341                        .get(index - tasks.templates.len())
 1342                        .cloned()
 1343                        .map(CodeActionsItem::CodeAction)
 1344                }
 1345            }
 1346            (Some(tasks), None) => tasks
 1347                .templates
 1348                .get(index)
 1349                .cloned()
 1350                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1351            (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
 1352            (None, None) => None,
 1353        }
 1354    }
 1355}
 1356
 1357#[allow(clippy::large_enum_variant)]
 1358#[derive(Clone)]
 1359enum CodeActionsItem {
 1360    Task(TaskSourceKind, ResolvedTask),
 1361    CodeAction(CodeAction),
 1362}
 1363
 1364impl CodeActionsItem {
 1365    fn as_task(&self) -> Option<&ResolvedTask> {
 1366        let Self::Task(_, task) = self else {
 1367            return None;
 1368        };
 1369        Some(task)
 1370    }
 1371    fn as_code_action(&self) -> Option<&CodeAction> {
 1372        let Self::CodeAction(action) = self else {
 1373            return None;
 1374        };
 1375        Some(action)
 1376    }
 1377    fn label(&self) -> String {
 1378        match self {
 1379            Self::CodeAction(action) => action.lsp_action.title.clone(),
 1380            Self::Task(_, task) => task.resolved_label.clone(),
 1381        }
 1382    }
 1383}
 1384
 1385struct CodeActionsMenu {
 1386    actions: CodeActionContents,
 1387    buffer: Model<Buffer>,
 1388    selected_item: usize,
 1389    scroll_handle: UniformListScrollHandle,
 1390    deployed_from_indicator: Option<DisplayRow>,
 1391}
 1392
 1393impl CodeActionsMenu {
 1394    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1395        self.selected_item = 0;
 1396        self.scroll_handle.scroll_to_item(self.selected_item);
 1397        cx.notify()
 1398    }
 1399
 1400    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1401        if self.selected_item > 0 {
 1402            self.selected_item -= 1;
 1403        } else {
 1404            self.selected_item = self.actions.len() - 1;
 1405        }
 1406        self.scroll_handle.scroll_to_item(self.selected_item);
 1407        cx.notify();
 1408    }
 1409
 1410    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1411        if self.selected_item + 1 < self.actions.len() {
 1412            self.selected_item += 1;
 1413        } else {
 1414            self.selected_item = 0;
 1415        }
 1416        self.scroll_handle.scroll_to_item(self.selected_item);
 1417        cx.notify();
 1418    }
 1419
 1420    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1421        self.selected_item = self.actions.len() - 1;
 1422        self.scroll_handle.scroll_to_item(self.selected_item);
 1423        cx.notify()
 1424    }
 1425
 1426    fn visible(&self) -> bool {
 1427        !self.actions.is_empty()
 1428    }
 1429
 1430    fn render(
 1431        &self,
 1432        cursor_position: DisplayPoint,
 1433        _style: &EditorStyle,
 1434        max_height: Pixels,
 1435        cx: &mut ViewContext<Editor>,
 1436    ) -> (ContextMenuOrigin, AnyElement) {
 1437        let actions = self.actions.clone();
 1438        let selected_item = self.selected_item;
 1439        let element = uniform_list(
 1440            cx.view().clone(),
 1441            "code_actions_menu",
 1442            self.actions.len(),
 1443            move |_this, range, cx| {
 1444                actions
 1445                    .iter()
 1446                    .skip(range.start)
 1447                    .take(range.end - range.start)
 1448                    .enumerate()
 1449                    .map(|(ix, action)| {
 1450                        let item_ix = range.start + ix;
 1451                        let selected = selected_item == item_ix;
 1452                        let colors = cx.theme().colors();
 1453                        div()
 1454                            .px_2()
 1455                            .text_color(colors.text)
 1456                            .when(selected, |style| {
 1457                                style
 1458                                    .bg(colors.element_active)
 1459                                    .text_color(colors.text_accent)
 1460                            })
 1461                            .hover(|style| {
 1462                                style
 1463                                    .bg(colors.element_hover)
 1464                                    .text_color(colors.text_accent)
 1465                            })
 1466                            .whitespace_nowrap()
 1467                            .when_some(action.as_code_action(), |this, action| {
 1468                                this.on_mouse_down(
 1469                                    MouseButton::Left,
 1470                                    cx.listener(move |editor, _, cx| {
 1471                                        cx.stop_propagation();
 1472                                        if let Some(task) = editor.confirm_code_action(
 1473                                            &ConfirmCodeAction {
 1474                                                item_ix: Some(item_ix),
 1475                                            },
 1476                                            cx,
 1477                                        ) {
 1478                                            task.detach_and_log_err(cx)
 1479                                        }
 1480                                    }),
 1481                                )
 1482                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1483                                .child(SharedString::from(action.lsp_action.title.clone()))
 1484                            })
 1485                            .when_some(action.as_task(), |this, task| {
 1486                                this.on_mouse_down(
 1487                                    MouseButton::Left,
 1488                                    cx.listener(move |editor, _, cx| {
 1489                                        cx.stop_propagation();
 1490                                        if let Some(task) = editor.confirm_code_action(
 1491                                            &ConfirmCodeAction {
 1492                                                item_ix: Some(item_ix),
 1493                                            },
 1494                                            cx,
 1495                                        ) {
 1496                                            task.detach_and_log_err(cx)
 1497                                        }
 1498                                    }),
 1499                                )
 1500                                .child(SharedString::from(task.resolved_label.clone()))
 1501                            })
 1502                    })
 1503                    .collect()
 1504            },
 1505        )
 1506        .elevation_1(cx)
 1507        .px_2()
 1508        .py_1()
 1509        .max_h(max_height)
 1510        .occlude()
 1511        .track_scroll(self.scroll_handle.clone())
 1512        .with_width_from_item(
 1513            self.actions
 1514                .iter()
 1515                .enumerate()
 1516                .max_by_key(|(_, action)| match action {
 1517                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1518                    CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
 1519                })
 1520                .map(|(ix, _)| ix),
 1521        )
 1522        .with_sizing_behavior(ListSizingBehavior::Infer)
 1523        .into_any_element();
 1524
 1525        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1526            ContextMenuOrigin::GutterIndicator(row)
 1527        } else {
 1528            ContextMenuOrigin::EditorPoint(cursor_position)
 1529        };
 1530
 1531        (cursor_position, element)
 1532    }
 1533}
 1534
 1535#[derive(Debug)]
 1536struct ActiveDiagnosticGroup {
 1537    primary_range: Range<Anchor>,
 1538    primary_message: String,
 1539    group_id: usize,
 1540    blocks: HashMap<BlockId, Diagnostic>,
 1541    is_valid: bool,
 1542}
 1543
 1544#[derive(Serialize, Deserialize, Clone, Debug)]
 1545pub struct ClipboardSelection {
 1546    pub len: usize,
 1547    pub is_entire_line: bool,
 1548    pub first_line_indent: u32,
 1549}
 1550
 1551#[derive(Debug)]
 1552pub(crate) struct NavigationData {
 1553    cursor_anchor: Anchor,
 1554    cursor_position: Point,
 1555    scroll_anchor: ScrollAnchor,
 1556    scroll_top_row: u32,
 1557}
 1558
 1559enum GotoDefinitionKind {
 1560    Symbol,
 1561    Type,
 1562    Implementation,
 1563}
 1564
 1565#[derive(Debug, Clone)]
 1566enum InlayHintRefreshReason {
 1567    Toggle(bool),
 1568    SettingsChange(InlayHintSettings),
 1569    NewLinesShown,
 1570    BufferEdited(HashSet<Arc<Language>>),
 1571    RefreshRequested,
 1572    ExcerptsRemoved(Vec<ExcerptId>),
 1573}
 1574
 1575impl InlayHintRefreshReason {
 1576    fn description(&self) -> &'static str {
 1577        match self {
 1578            Self::Toggle(_) => "toggle",
 1579            Self::SettingsChange(_) => "settings change",
 1580            Self::NewLinesShown => "new lines shown",
 1581            Self::BufferEdited(_) => "buffer edited",
 1582            Self::RefreshRequested => "refresh requested",
 1583            Self::ExcerptsRemoved(_) => "excerpts removed",
 1584        }
 1585    }
 1586}
 1587
 1588impl Editor {
 1589    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1590        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1591        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1592        Self::new(
 1593            EditorMode::SingleLine { auto_width: false },
 1594            buffer,
 1595            None,
 1596            false,
 1597            cx,
 1598        )
 1599    }
 1600
 1601    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1602        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1603        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1604        Self::new(EditorMode::Full, buffer, None, false, cx)
 1605    }
 1606
 1607    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1608        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1609        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1610        Self::new(
 1611            EditorMode::SingleLine { auto_width: true },
 1612            buffer,
 1613            None,
 1614            false,
 1615            cx,
 1616        )
 1617    }
 1618
 1619    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1620        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1621        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1622        Self::new(
 1623            EditorMode::AutoHeight { max_lines },
 1624            buffer,
 1625            None,
 1626            false,
 1627            cx,
 1628        )
 1629    }
 1630
 1631    pub fn for_buffer(
 1632        buffer: Model<Buffer>,
 1633        project: Option<Model<Project>>,
 1634        cx: &mut ViewContext<Self>,
 1635    ) -> Self {
 1636        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1637        Self::new(EditorMode::Full, buffer, project, false, cx)
 1638    }
 1639
 1640    pub fn for_multibuffer(
 1641        buffer: Model<MultiBuffer>,
 1642        project: Option<Model<Project>>,
 1643        show_excerpt_controls: bool,
 1644        cx: &mut ViewContext<Self>,
 1645    ) -> Self {
 1646        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1647    }
 1648
 1649    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1650        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1651        let mut clone = Self::new(
 1652            self.mode,
 1653            self.buffer.clone(),
 1654            self.project.clone(),
 1655            show_excerpt_controls,
 1656            cx,
 1657        );
 1658        self.display_map.update(cx, |display_map, cx| {
 1659            let snapshot = display_map.snapshot(cx);
 1660            clone.display_map.update(cx, |display_map, cx| {
 1661                display_map.set_state(&snapshot, cx);
 1662            });
 1663        });
 1664        clone.selections.clone_state(&self.selections);
 1665        clone.scroll_manager.clone_state(&self.scroll_manager);
 1666        clone.searchable = self.searchable;
 1667        clone
 1668    }
 1669
 1670    pub fn new(
 1671        mode: EditorMode,
 1672        buffer: Model<MultiBuffer>,
 1673        project: Option<Model<Project>>,
 1674        show_excerpt_controls: bool,
 1675        cx: &mut ViewContext<Self>,
 1676    ) -> Self {
 1677        let style = cx.text_style();
 1678        let font_size = style.font_size.to_pixels(cx.rem_size());
 1679        let editor = cx.view().downgrade();
 1680        let fold_placeholder = FoldPlaceholder {
 1681            constrain_width: true,
 1682            render: Arc::new(move |fold_id, fold_range, cx| {
 1683                let editor = editor.clone();
 1684                div()
 1685                    .id(fold_id)
 1686                    .bg(cx.theme().colors().ghost_element_background)
 1687                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1688                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1689                    .rounded_sm()
 1690                    .size_full()
 1691                    .cursor_pointer()
 1692                    .child("")
 1693                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1694                    .on_click(move |_, cx| {
 1695                        editor
 1696                            .update(cx, |editor, cx| {
 1697                                editor.unfold_ranges(
 1698                                    [fold_range.start..fold_range.end],
 1699                                    true,
 1700                                    false,
 1701                                    cx,
 1702                                );
 1703                                cx.stop_propagation();
 1704                            })
 1705                            .ok();
 1706                    })
 1707                    .into_any()
 1708            }),
 1709            merge_adjacent: true,
 1710        };
 1711        let file_header_size = if show_excerpt_controls { 3 } else { 2 };
 1712        let display_map = cx.new_model(|cx| {
 1713            DisplayMap::new(
 1714                buffer.clone(),
 1715                style.font(),
 1716                font_size,
 1717                None,
 1718                show_excerpt_controls,
 1719                file_header_size,
 1720                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1721                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1722                fold_placeholder,
 1723                cx,
 1724            )
 1725        });
 1726
 1727        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1728
 1729        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1730
 1731        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1732            .then(|| language_settings::SoftWrap::PreferLine);
 1733
 1734        let mut project_subscriptions = Vec::new();
 1735        if mode == EditorMode::Full {
 1736            if let Some(project) = project.as_ref() {
 1737                if buffer.read(cx).is_singleton() {
 1738                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1739                        cx.emit(EditorEvent::TitleChanged);
 1740                    }));
 1741                }
 1742                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1743                    if let project::Event::RefreshInlayHints = event {
 1744                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1745                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1746                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1747                            let focus_handle = editor.focus_handle(cx);
 1748                            if focus_handle.is_focused(cx) {
 1749                                let snapshot = buffer.read(cx).snapshot();
 1750                                for (range, snippet) in snippet_edits {
 1751                                    let editor_range =
 1752                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1753                                    editor
 1754                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1755                                        .ok();
 1756                                }
 1757                            }
 1758                        }
 1759                    }
 1760                }));
 1761                let task_inventory = project.read(cx).task_inventory().clone();
 1762                project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1763                    editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1764                }));
 1765            }
 1766        }
 1767
 1768        let inlay_hint_settings = inlay_hint_settings(
 1769            selections.newest_anchor().head(),
 1770            &buffer.read(cx).snapshot(cx),
 1771            cx,
 1772        );
 1773        let focus_handle = cx.focus_handle();
 1774        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1775        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1776            .detach();
 1777        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1778            .detach();
 1779        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1780
 1781        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1782            Some(false)
 1783        } else {
 1784            None
 1785        };
 1786
 1787        let mut this = Self {
 1788            focus_handle,
 1789            show_cursor_when_unfocused: false,
 1790            last_focused_descendant: None,
 1791            buffer: buffer.clone(),
 1792            display_map: display_map.clone(),
 1793            selections,
 1794            scroll_manager: ScrollManager::new(cx),
 1795            columnar_selection_tail: None,
 1796            add_selections_state: None,
 1797            select_next_state: None,
 1798            select_prev_state: None,
 1799            selection_history: Default::default(),
 1800            autoclose_regions: Default::default(),
 1801            snippet_stack: Default::default(),
 1802            select_larger_syntax_node_stack: Vec::new(),
 1803            ime_transaction: Default::default(),
 1804            active_diagnostics: None,
 1805            soft_wrap_mode_override,
 1806            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1807            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1808            project,
 1809            blink_manager: blink_manager.clone(),
 1810            show_local_selections: true,
 1811            mode,
 1812            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1813            show_gutter: mode == EditorMode::Full,
 1814            show_line_numbers: None,
 1815            show_git_diff_gutter: None,
 1816            show_code_actions: None,
 1817            show_runnables: None,
 1818            show_wrap_guides: None,
 1819            show_indent_guides,
 1820            placeholder_text: None,
 1821            highlight_order: 0,
 1822            highlighted_rows: HashMap::default(),
 1823            background_highlights: Default::default(),
 1824            gutter_highlights: TreeMap::default(),
 1825            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1826            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1827            nav_history: None,
 1828            context_menu: RwLock::new(None),
 1829            mouse_context_menu: None,
 1830            completion_tasks: Default::default(),
 1831            signature_help_state: SignatureHelpState::default(),
 1832            auto_signature_help: None,
 1833            find_all_references_task_sources: Vec::new(),
 1834            next_completion_id: 0,
 1835            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1836            next_inlay_id: 0,
 1837            available_code_actions: Default::default(),
 1838            code_actions_task: Default::default(),
 1839            document_highlights_task: Default::default(),
 1840            linked_editing_range_task: Default::default(),
 1841            pending_rename: Default::default(),
 1842            searchable: true,
 1843            cursor_shape: Default::default(),
 1844            current_line_highlight: None,
 1845            autoindent_mode: Some(AutoindentMode::EachLine),
 1846            collapse_matches: false,
 1847            workspace: None,
 1848            keymap_context_layers: Default::default(),
 1849            input_enabled: true,
 1850            use_modal_editing: mode == EditorMode::Full,
 1851            read_only: false,
 1852            use_autoclose: true,
 1853            use_auto_surround: true,
 1854            auto_replace_emoji_shortcode: false,
 1855            leader_peer_id: None,
 1856            remote_id: None,
 1857            hover_state: Default::default(),
 1858            hovered_link_state: Default::default(),
 1859            inline_completion_provider: None,
 1860            active_inline_completion: None,
 1861            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1862            expanded_hunks: ExpandedHunks::default(),
 1863            gutter_hovered: false,
 1864            pixel_position_of_newest_cursor: None,
 1865            last_bounds: None,
 1866            expect_bounds_change: None,
 1867            gutter_dimensions: GutterDimensions::default(),
 1868            style: None,
 1869            show_cursor_names: false,
 1870            hovered_cursors: Default::default(),
 1871            next_editor_action_id: EditorActionId::default(),
 1872            editor_actions: Rc::default(),
 1873            vim_replace_map: Default::default(),
 1874            show_inline_completions: mode == EditorMode::Full,
 1875            custom_context_menu: None,
 1876            show_git_blame_gutter: false,
 1877            show_git_blame_inline: false,
 1878            show_selection_menu: None,
 1879            show_git_blame_inline_delay_task: None,
 1880            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1881            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1882                .session
 1883                .restore_unsaved_buffers,
 1884            blame: None,
 1885            blame_subscription: None,
 1886            file_header_size,
 1887            tasks: Default::default(),
 1888            _subscriptions: vec![
 1889                cx.observe(&buffer, Self::on_buffer_changed),
 1890                cx.subscribe(&buffer, Self::on_buffer_event),
 1891                cx.observe(&display_map, Self::on_display_map_changed),
 1892                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1893                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1894                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1895                cx.observe_window_activation(|editor, cx| {
 1896                    let active = cx.is_window_active();
 1897                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1898                        if active {
 1899                            blink_manager.enable(cx);
 1900                        } else {
 1901                            blink_manager.show_cursor(cx);
 1902                            blink_manager.disable(cx);
 1903                        }
 1904                    });
 1905                }),
 1906            ],
 1907            tasks_update_task: None,
 1908            linked_edit_ranges: Default::default(),
 1909            previous_search_ranges: None,
 1910            breadcrumb_header: None,
 1911        };
 1912        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1913        this._subscriptions.extend(project_subscriptions);
 1914
 1915        this.end_selection(cx);
 1916        this.scroll_manager.show_scrollbar(cx);
 1917
 1918        if mode == EditorMode::Full {
 1919            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1920            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1921
 1922            if this.git_blame_inline_enabled {
 1923                this.git_blame_inline_enabled = true;
 1924                this.start_git_blame_inline(false, cx);
 1925            }
 1926        }
 1927
 1928        this.report_editor_event("open", None, cx);
 1929        this
 1930    }
 1931
 1932    pub fn mouse_menu_is_focused(&self, cx: &mut WindowContext) -> bool {
 1933        self.mouse_context_menu
 1934            .as_ref()
 1935            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1936    }
 1937
 1938    fn key_context(&self, cx: &AppContext) -> KeyContext {
 1939        let mut key_context = KeyContext::new_with_defaults();
 1940        key_context.add("Editor");
 1941        let mode = match self.mode {
 1942            EditorMode::SingleLine { .. } => "single_line",
 1943            EditorMode::AutoHeight { .. } => "auto_height",
 1944            EditorMode::Full => "full",
 1945        };
 1946
 1947        if EditorSettings::get_global(cx).jupyter.enabled {
 1948            key_context.add("jupyter");
 1949        }
 1950
 1951        key_context.set("mode", mode);
 1952        if self.pending_rename.is_some() {
 1953            key_context.add("renaming");
 1954        }
 1955        if self.context_menu_visible() {
 1956            match self.context_menu.read().as_ref() {
 1957                Some(ContextMenu::Completions(_)) => {
 1958                    key_context.add("menu");
 1959                    key_context.add("showing_completions")
 1960                }
 1961                Some(ContextMenu::CodeActions(_)) => {
 1962                    key_context.add("menu");
 1963                    key_context.add("showing_code_actions")
 1964                }
 1965                None => {}
 1966            }
 1967        }
 1968
 1969        for layer in self.keymap_context_layers.values() {
 1970            key_context.extend(layer);
 1971        }
 1972
 1973        if let Some(extension) = self
 1974            .buffer
 1975            .read(cx)
 1976            .as_singleton()
 1977            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1978        {
 1979            key_context.set("extension", extension.to_string());
 1980        }
 1981
 1982        if self.has_active_inline_completion(cx) {
 1983            key_context.add("copilot_suggestion");
 1984            key_context.add("inline_completion");
 1985        }
 1986
 1987        key_context
 1988    }
 1989
 1990    pub fn new_file(
 1991        workspace: &mut Workspace,
 1992        _: &workspace::NewFile,
 1993        cx: &mut ViewContext<Workspace>,
 1994    ) {
 1995        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1996            "Failed to create buffer",
 1997            cx,
 1998            |e, _| match e.error_code() {
 1999                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2000                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2001                e.error_tag("required").unwrap_or("the latest version")
 2002            )),
 2003                _ => None,
 2004            },
 2005        );
 2006    }
 2007
 2008    pub fn new_in_workspace(
 2009        workspace: &mut Workspace,
 2010        cx: &mut ViewContext<Workspace>,
 2011    ) -> Task<Result<View<Editor>>> {
 2012        let project = workspace.project().clone();
 2013        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2014
 2015        cx.spawn(|workspace, mut cx| async move {
 2016            let buffer = create.await?;
 2017            workspace.update(&mut cx, |workspace, cx| {
 2018                let editor =
 2019                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2020                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2021                editor
 2022            })
 2023        })
 2024    }
 2025
 2026    pub fn new_file_in_direction(
 2027        workspace: &mut Workspace,
 2028        action: &workspace::NewFileInDirection,
 2029        cx: &mut ViewContext<Workspace>,
 2030    ) {
 2031        let project = workspace.project().clone();
 2032        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2033        let direction = action.0;
 2034
 2035        cx.spawn(|workspace, mut cx| async move {
 2036            let buffer = create.await?;
 2037            workspace.update(&mut cx, move |workspace, cx| {
 2038                workspace.split_item(
 2039                    direction,
 2040                    Box::new(
 2041                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2042                    ),
 2043                    cx,
 2044                )
 2045            })?;
 2046            anyhow::Ok(())
 2047        })
 2048        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2049            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2050                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2051                e.error_tag("required").unwrap_or("the latest version")
 2052            )),
 2053            _ => None,
 2054        });
 2055    }
 2056
 2057    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
 2058        self.buffer.read(cx).replica_id()
 2059    }
 2060
 2061    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2062        self.leader_peer_id
 2063    }
 2064
 2065    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2066        &self.buffer
 2067    }
 2068
 2069    pub fn workspace(&self) -> Option<View<Workspace>> {
 2070        self.workspace.as_ref()?.0.upgrade()
 2071    }
 2072
 2073    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2074        self.buffer().read(cx).title(cx)
 2075    }
 2076
 2077    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2078        EditorSnapshot {
 2079            mode: self.mode,
 2080            show_gutter: self.show_gutter,
 2081            show_line_numbers: self.show_line_numbers,
 2082            show_git_diff_gutter: self.show_git_diff_gutter,
 2083            show_code_actions: self.show_code_actions,
 2084            show_runnables: self.show_runnables,
 2085            render_git_blame_gutter: self.render_git_blame_gutter(cx),
 2086            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2087            scroll_anchor: self.scroll_manager.anchor(),
 2088            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2089            placeholder_text: self.placeholder_text.clone(),
 2090            is_focused: self.focus_handle.is_focused(cx),
 2091            current_line_highlight: self
 2092                .current_line_highlight
 2093                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2094            gutter_hovered: self.gutter_hovered,
 2095        }
 2096    }
 2097
 2098    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2099        self.buffer.read(cx).language_at(point, cx)
 2100    }
 2101
 2102    pub fn file_at<T: ToOffset>(
 2103        &self,
 2104        point: T,
 2105        cx: &AppContext,
 2106    ) -> Option<Arc<dyn language::File>> {
 2107        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2108    }
 2109
 2110    pub fn active_excerpt(
 2111        &self,
 2112        cx: &AppContext,
 2113    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2114        self.buffer
 2115            .read(cx)
 2116            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2117    }
 2118
 2119    pub fn mode(&self) -> EditorMode {
 2120        self.mode
 2121    }
 2122
 2123    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2124        self.collaboration_hub.as_deref()
 2125    }
 2126
 2127    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2128        self.collaboration_hub = Some(hub);
 2129    }
 2130
 2131    pub fn set_custom_context_menu(
 2132        &mut self,
 2133        f: impl 'static
 2134            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2135    ) {
 2136        self.custom_context_menu = Some(Box::new(f))
 2137    }
 2138
 2139    pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
 2140        self.completion_provider = Some(provider);
 2141    }
 2142
 2143    pub fn set_inline_completion_provider<T>(
 2144        &mut self,
 2145        provider: Option<Model<T>>,
 2146        cx: &mut ViewContext<Self>,
 2147    ) where
 2148        T: InlineCompletionProvider,
 2149    {
 2150        self.inline_completion_provider =
 2151            provider.map(|provider| RegisteredInlineCompletionProvider {
 2152                _subscription: cx.observe(&provider, |this, _, cx| {
 2153                    if this.focus_handle.is_focused(cx) {
 2154                        this.update_visible_inline_completion(cx);
 2155                    }
 2156                }),
 2157                provider: Arc::new(provider),
 2158            });
 2159        self.refresh_inline_completion(false, cx);
 2160    }
 2161
 2162    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2163        self.placeholder_text.as_deref()
 2164    }
 2165
 2166    pub fn set_placeholder_text(
 2167        &mut self,
 2168        placeholder_text: impl Into<Arc<str>>,
 2169        cx: &mut ViewContext<Self>,
 2170    ) {
 2171        let placeholder_text = Some(placeholder_text.into());
 2172        if self.placeholder_text != placeholder_text {
 2173            self.placeholder_text = placeholder_text;
 2174            cx.notify();
 2175        }
 2176    }
 2177
 2178    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2179        self.cursor_shape = cursor_shape;
 2180
 2181        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2182        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2183
 2184        cx.notify();
 2185    }
 2186
 2187    pub fn set_current_line_highlight(
 2188        &mut self,
 2189        current_line_highlight: Option<CurrentLineHighlight>,
 2190    ) {
 2191        self.current_line_highlight = current_line_highlight;
 2192    }
 2193
 2194    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2195        self.collapse_matches = collapse_matches;
 2196    }
 2197
 2198    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2199        if self.collapse_matches {
 2200            return range.start..range.start;
 2201        }
 2202        range.clone()
 2203    }
 2204
 2205    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2206        if self.display_map.read(cx).clip_at_line_ends != clip {
 2207            self.display_map
 2208                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2209        }
 2210    }
 2211
 2212    pub fn set_keymap_context_layer<Tag: 'static>(
 2213        &mut self,
 2214        context: KeyContext,
 2215        cx: &mut ViewContext<Self>,
 2216    ) {
 2217        self.keymap_context_layers
 2218            .insert(TypeId::of::<Tag>(), context);
 2219        cx.notify();
 2220    }
 2221
 2222    pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
 2223        self.keymap_context_layers.remove(&TypeId::of::<Tag>());
 2224        cx.notify();
 2225    }
 2226
 2227    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2228        self.input_enabled = input_enabled;
 2229    }
 2230
 2231    pub fn set_autoindent(&mut self, autoindent: bool) {
 2232        if autoindent {
 2233            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2234        } else {
 2235            self.autoindent_mode = None;
 2236        }
 2237    }
 2238
 2239    pub fn read_only(&self, cx: &AppContext) -> bool {
 2240        self.read_only || self.buffer.read(cx).read_only()
 2241    }
 2242
 2243    pub fn set_read_only(&mut self, read_only: bool) {
 2244        self.read_only = read_only;
 2245    }
 2246
 2247    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2248        self.use_autoclose = autoclose;
 2249    }
 2250
 2251    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2252        self.use_auto_surround = auto_surround;
 2253    }
 2254
 2255    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2256        self.auto_replace_emoji_shortcode = auto_replace;
 2257    }
 2258
 2259    pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
 2260        self.show_inline_completions = show_inline_completions;
 2261    }
 2262
 2263    pub fn set_use_modal_editing(&mut self, to: bool) {
 2264        self.use_modal_editing = to;
 2265    }
 2266
 2267    pub fn use_modal_editing(&self) -> bool {
 2268        self.use_modal_editing
 2269    }
 2270
 2271    fn selections_did_change(
 2272        &mut self,
 2273        local: bool,
 2274        old_cursor_position: &Anchor,
 2275        show_completions: bool,
 2276        cx: &mut ViewContext<Self>,
 2277    ) {
 2278        // Copy selections to primary selection buffer
 2279        #[cfg(target_os = "linux")]
 2280        if local {
 2281            let selections = self.selections.all::<usize>(cx);
 2282            let buffer_handle = self.buffer.read(cx).read(cx);
 2283
 2284            let mut text = String::new();
 2285            for (index, selection) in selections.iter().enumerate() {
 2286                let text_for_selection = buffer_handle
 2287                    .text_for_range(selection.start..selection.end)
 2288                    .collect::<String>();
 2289
 2290                text.push_str(&text_for_selection);
 2291                if index != selections.len() - 1 {
 2292                    text.push('\n');
 2293                }
 2294            }
 2295
 2296            if !text.is_empty() {
 2297                cx.write_to_primary(ClipboardItem::new(text));
 2298            }
 2299        }
 2300
 2301        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2302            self.buffer.update(cx, |buffer, cx| {
 2303                buffer.set_active_selections(
 2304                    &self.selections.disjoint_anchors(),
 2305                    self.selections.line_mode,
 2306                    self.cursor_shape,
 2307                    cx,
 2308                )
 2309            });
 2310        }
 2311        let display_map = self
 2312            .display_map
 2313            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2314        let buffer = &display_map.buffer_snapshot;
 2315        self.add_selections_state = None;
 2316        self.select_next_state = None;
 2317        self.select_prev_state = None;
 2318        self.select_larger_syntax_node_stack.clear();
 2319        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2320        self.snippet_stack
 2321            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2322        self.take_rename(false, cx);
 2323
 2324        let new_cursor_position = self.selections.newest_anchor().head();
 2325
 2326        self.push_to_nav_history(
 2327            *old_cursor_position,
 2328            Some(new_cursor_position.to_point(buffer)),
 2329            cx,
 2330        );
 2331
 2332        if local {
 2333            let new_cursor_position = self.selections.newest_anchor().head();
 2334            let mut context_menu = self.context_menu.write();
 2335            let completion_menu = match context_menu.as_ref() {
 2336                Some(ContextMenu::Completions(menu)) => Some(menu),
 2337
 2338                _ => {
 2339                    *context_menu = None;
 2340                    None
 2341                }
 2342            };
 2343
 2344            if let Some(completion_menu) = completion_menu {
 2345                let cursor_position = new_cursor_position.to_offset(buffer);
 2346                let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
 2347                if kind == Some(CharKind::Word)
 2348                    && word_range.to_inclusive().contains(&cursor_position)
 2349                {
 2350                    let mut completion_menu = completion_menu.clone();
 2351                    drop(context_menu);
 2352
 2353                    let query = Self::completion_query(buffer, cursor_position);
 2354                    cx.spawn(move |this, mut cx| async move {
 2355                        completion_menu
 2356                            .filter(query.as_deref(), cx.background_executor().clone())
 2357                            .await;
 2358
 2359                        this.update(&mut cx, |this, cx| {
 2360                            let mut context_menu = this.context_menu.write();
 2361                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2362                                return;
 2363                            };
 2364
 2365                            if menu.id > completion_menu.id {
 2366                                return;
 2367                            }
 2368
 2369                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2370                            drop(context_menu);
 2371                            cx.notify();
 2372                        })
 2373                    })
 2374                    .detach();
 2375
 2376                    if show_completions {
 2377                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2378                    }
 2379                } else {
 2380                    drop(context_menu);
 2381                    self.hide_context_menu(cx);
 2382                }
 2383            } else {
 2384                drop(context_menu);
 2385            }
 2386
 2387            hide_hover(self, cx);
 2388
 2389            if old_cursor_position.to_display_point(&display_map).row()
 2390                != new_cursor_position.to_display_point(&display_map).row()
 2391            {
 2392                self.available_code_actions.take();
 2393            }
 2394            self.refresh_code_actions(cx);
 2395            self.refresh_document_highlights(cx);
 2396            refresh_matching_bracket_highlights(self, cx);
 2397            self.discard_inline_completion(false, cx);
 2398            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2399            if self.git_blame_inline_enabled {
 2400                self.start_inline_blame_timer(cx);
 2401            }
 2402        }
 2403
 2404        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2405        cx.emit(EditorEvent::SelectionsChanged { local });
 2406
 2407        if self.selections.disjoint_anchors().len() == 1 {
 2408            cx.emit(SearchEvent::ActiveMatchChanged)
 2409        }
 2410        cx.notify();
 2411    }
 2412
 2413    pub fn change_selections<R>(
 2414        &mut self,
 2415        autoscroll: Option<Autoscroll>,
 2416        cx: &mut ViewContext<Self>,
 2417        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2418    ) -> R {
 2419        self.change_selections_inner(autoscroll, true, cx, change)
 2420    }
 2421
 2422    pub fn change_selections_inner<R>(
 2423        &mut self,
 2424        autoscroll: Option<Autoscroll>,
 2425        request_completions: bool,
 2426        cx: &mut ViewContext<Self>,
 2427        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2428    ) -> R {
 2429        let old_cursor_position = self.selections.newest_anchor().head();
 2430        self.push_to_selection_history();
 2431
 2432        let (changed, result) = self.selections.change_with(cx, change);
 2433
 2434        if changed {
 2435            if let Some(autoscroll) = autoscroll {
 2436                self.request_autoscroll(autoscroll, cx);
 2437            }
 2438            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2439
 2440            if self.should_open_signature_help_automatically(
 2441                &old_cursor_position,
 2442                self.signature_help_state.backspace_pressed(),
 2443                cx,
 2444            ) {
 2445                self.show_signature_help(&ShowSignatureHelp, cx);
 2446            }
 2447            self.signature_help_state.set_backspace_pressed(false);
 2448        }
 2449
 2450        result
 2451    }
 2452
 2453    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2454    where
 2455        I: IntoIterator<Item = (Range<S>, T)>,
 2456        S: ToOffset,
 2457        T: Into<Arc<str>>,
 2458    {
 2459        if self.read_only(cx) {
 2460            return;
 2461        }
 2462
 2463        self.buffer
 2464            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2465    }
 2466
 2467    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2468    where
 2469        I: IntoIterator<Item = (Range<S>, T)>,
 2470        S: ToOffset,
 2471        T: Into<Arc<str>>,
 2472    {
 2473        if self.read_only(cx) {
 2474            return;
 2475        }
 2476
 2477        self.buffer.update(cx, |buffer, cx| {
 2478            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2479        });
 2480    }
 2481
 2482    pub fn edit_with_block_indent<I, S, T>(
 2483        &mut self,
 2484        edits: I,
 2485        original_indent_columns: Vec<u32>,
 2486        cx: &mut ViewContext<Self>,
 2487    ) where
 2488        I: IntoIterator<Item = (Range<S>, T)>,
 2489        S: ToOffset,
 2490        T: Into<Arc<str>>,
 2491    {
 2492        if self.read_only(cx) {
 2493            return;
 2494        }
 2495
 2496        self.buffer.update(cx, |buffer, cx| {
 2497            buffer.edit(
 2498                edits,
 2499                Some(AutoindentMode::Block {
 2500                    original_indent_columns,
 2501                }),
 2502                cx,
 2503            )
 2504        });
 2505    }
 2506
 2507    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2508        self.hide_context_menu(cx);
 2509
 2510        match phase {
 2511            SelectPhase::Begin {
 2512                position,
 2513                add,
 2514                click_count,
 2515            } => self.begin_selection(position, add, click_count, cx),
 2516            SelectPhase::BeginColumnar {
 2517                position,
 2518                goal_column,
 2519                reset,
 2520            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2521            SelectPhase::Extend {
 2522                position,
 2523                click_count,
 2524            } => self.extend_selection(position, click_count, cx),
 2525            SelectPhase::Update {
 2526                position,
 2527                goal_column,
 2528                scroll_delta,
 2529            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2530            SelectPhase::End => self.end_selection(cx),
 2531        }
 2532    }
 2533
 2534    fn extend_selection(
 2535        &mut self,
 2536        position: DisplayPoint,
 2537        click_count: usize,
 2538        cx: &mut ViewContext<Self>,
 2539    ) {
 2540        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2541        let tail = self.selections.newest::<usize>(cx).tail();
 2542        self.begin_selection(position, false, click_count, cx);
 2543
 2544        let position = position.to_offset(&display_map, Bias::Left);
 2545        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2546
 2547        let mut pending_selection = self
 2548            .selections
 2549            .pending_anchor()
 2550            .expect("extend_selection not called with pending selection");
 2551        if position >= tail {
 2552            pending_selection.start = tail_anchor;
 2553        } else {
 2554            pending_selection.end = tail_anchor;
 2555            pending_selection.reversed = true;
 2556        }
 2557
 2558        let mut pending_mode = self.selections.pending_mode().unwrap();
 2559        match &mut pending_mode {
 2560            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2561            _ => {}
 2562        }
 2563
 2564        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2565            s.set_pending(pending_selection, pending_mode)
 2566        });
 2567    }
 2568
 2569    fn begin_selection(
 2570        &mut self,
 2571        position: DisplayPoint,
 2572        add: bool,
 2573        click_count: usize,
 2574        cx: &mut ViewContext<Self>,
 2575    ) {
 2576        if !self.focus_handle.is_focused(cx) {
 2577            self.last_focused_descendant = None;
 2578            cx.focus(&self.focus_handle);
 2579        }
 2580
 2581        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2582        let buffer = &display_map.buffer_snapshot;
 2583        let newest_selection = self.selections.newest_anchor().clone();
 2584        let position = display_map.clip_point(position, Bias::Left);
 2585
 2586        let start;
 2587        let end;
 2588        let mode;
 2589        let auto_scroll;
 2590        match click_count {
 2591            1 => {
 2592                start = buffer.anchor_before(position.to_point(&display_map));
 2593                end = start;
 2594                mode = SelectMode::Character;
 2595                auto_scroll = true;
 2596            }
 2597            2 => {
 2598                let range = movement::surrounding_word(&display_map, position);
 2599                start = buffer.anchor_before(range.start.to_point(&display_map));
 2600                end = buffer.anchor_before(range.end.to_point(&display_map));
 2601                mode = SelectMode::Word(start..end);
 2602                auto_scroll = true;
 2603            }
 2604            3 => {
 2605                let position = display_map
 2606                    .clip_point(position, Bias::Left)
 2607                    .to_point(&display_map);
 2608                let line_start = display_map.prev_line_boundary(position).0;
 2609                let next_line_start = buffer.clip_point(
 2610                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2611                    Bias::Left,
 2612                );
 2613                start = buffer.anchor_before(line_start);
 2614                end = buffer.anchor_before(next_line_start);
 2615                mode = SelectMode::Line(start..end);
 2616                auto_scroll = true;
 2617            }
 2618            _ => {
 2619                start = buffer.anchor_before(0);
 2620                end = buffer.anchor_before(buffer.len());
 2621                mode = SelectMode::All;
 2622                auto_scroll = false;
 2623            }
 2624        }
 2625
 2626        let point_to_delete: Option<usize> = {
 2627            let selected_points: Vec<Selection<Point>> =
 2628                self.selections.disjoint_in_range(start..end, cx);
 2629
 2630            if !add || click_count > 1 {
 2631                None
 2632            } else if selected_points.len() > 0 {
 2633                Some(selected_points[0].id)
 2634            } else {
 2635                let clicked_point_already_selected =
 2636                    self.selections.disjoint.iter().find(|selection| {
 2637                        selection.start.to_point(buffer) == start.to_point(buffer)
 2638                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2639                    });
 2640
 2641                if let Some(selection) = clicked_point_already_selected {
 2642                    Some(selection.id)
 2643                } else {
 2644                    None
 2645                }
 2646            }
 2647        };
 2648
 2649        let selections_count = self.selections.count();
 2650
 2651        self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
 2652            if let Some(point_to_delete) = point_to_delete {
 2653                s.delete(point_to_delete);
 2654
 2655                if selections_count == 1 {
 2656                    s.set_pending_anchor_range(start..end, mode);
 2657                }
 2658            } else {
 2659                if !add {
 2660                    s.clear_disjoint();
 2661                } else if click_count > 1 {
 2662                    s.delete(newest_selection.id)
 2663                }
 2664
 2665                s.set_pending_anchor_range(start..end, mode);
 2666            }
 2667        });
 2668    }
 2669
 2670    fn begin_columnar_selection(
 2671        &mut self,
 2672        position: DisplayPoint,
 2673        goal_column: u32,
 2674        reset: bool,
 2675        cx: &mut ViewContext<Self>,
 2676    ) {
 2677        if !self.focus_handle.is_focused(cx) {
 2678            self.last_focused_descendant = None;
 2679            cx.focus(&self.focus_handle);
 2680        }
 2681
 2682        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2683
 2684        if reset {
 2685            let pointer_position = display_map
 2686                .buffer_snapshot
 2687                .anchor_before(position.to_point(&display_map));
 2688
 2689            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2690                s.clear_disjoint();
 2691                s.set_pending_anchor_range(
 2692                    pointer_position..pointer_position,
 2693                    SelectMode::Character,
 2694                );
 2695            });
 2696        }
 2697
 2698        let tail = self.selections.newest::<Point>(cx).tail();
 2699        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2700
 2701        if !reset {
 2702            self.select_columns(
 2703                tail.to_display_point(&display_map),
 2704                position,
 2705                goal_column,
 2706                &display_map,
 2707                cx,
 2708            );
 2709        }
 2710    }
 2711
 2712    fn update_selection(
 2713        &mut self,
 2714        position: DisplayPoint,
 2715        goal_column: u32,
 2716        scroll_delta: gpui::Point<f32>,
 2717        cx: &mut ViewContext<Self>,
 2718    ) {
 2719        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2720
 2721        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2722            let tail = tail.to_display_point(&display_map);
 2723            self.select_columns(tail, position, goal_column, &display_map, cx);
 2724        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2725            let buffer = self.buffer.read(cx).snapshot(cx);
 2726            let head;
 2727            let tail;
 2728            let mode = self.selections.pending_mode().unwrap();
 2729            match &mode {
 2730                SelectMode::Character => {
 2731                    head = position.to_point(&display_map);
 2732                    tail = pending.tail().to_point(&buffer);
 2733                }
 2734                SelectMode::Word(original_range) => {
 2735                    let original_display_range = original_range.start.to_display_point(&display_map)
 2736                        ..original_range.end.to_display_point(&display_map);
 2737                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2738                        ..original_display_range.end.to_point(&display_map);
 2739                    if movement::is_inside_word(&display_map, position)
 2740                        || original_display_range.contains(&position)
 2741                    {
 2742                        let word_range = movement::surrounding_word(&display_map, position);
 2743                        if word_range.start < original_display_range.start {
 2744                            head = word_range.start.to_point(&display_map);
 2745                        } else {
 2746                            head = word_range.end.to_point(&display_map);
 2747                        }
 2748                    } else {
 2749                        head = position.to_point(&display_map);
 2750                    }
 2751
 2752                    if head <= original_buffer_range.start {
 2753                        tail = original_buffer_range.end;
 2754                    } else {
 2755                        tail = original_buffer_range.start;
 2756                    }
 2757                }
 2758                SelectMode::Line(original_range) => {
 2759                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2760
 2761                    let position = display_map
 2762                        .clip_point(position, Bias::Left)
 2763                        .to_point(&display_map);
 2764                    let line_start = display_map.prev_line_boundary(position).0;
 2765                    let next_line_start = buffer.clip_point(
 2766                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2767                        Bias::Left,
 2768                    );
 2769
 2770                    if line_start < original_range.start {
 2771                        head = line_start
 2772                    } else {
 2773                        head = next_line_start
 2774                    }
 2775
 2776                    if head <= original_range.start {
 2777                        tail = original_range.end;
 2778                    } else {
 2779                        tail = original_range.start;
 2780                    }
 2781                }
 2782                SelectMode::All => {
 2783                    return;
 2784                }
 2785            };
 2786
 2787            if head < tail {
 2788                pending.start = buffer.anchor_before(head);
 2789                pending.end = buffer.anchor_before(tail);
 2790                pending.reversed = true;
 2791            } else {
 2792                pending.start = buffer.anchor_before(tail);
 2793                pending.end = buffer.anchor_before(head);
 2794                pending.reversed = false;
 2795            }
 2796
 2797            self.change_selections(None, cx, |s| {
 2798                s.set_pending(pending, mode);
 2799            });
 2800        } else {
 2801            log::error!("update_selection dispatched with no pending selection");
 2802            return;
 2803        }
 2804
 2805        self.apply_scroll_delta(scroll_delta, cx);
 2806        cx.notify();
 2807    }
 2808
 2809    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2810        self.columnar_selection_tail.take();
 2811        if self.selections.pending_anchor().is_some() {
 2812            let selections = self.selections.all::<usize>(cx);
 2813            self.change_selections(None, cx, |s| {
 2814                s.select(selections);
 2815                s.clear_pending();
 2816            });
 2817        }
 2818    }
 2819
 2820    fn select_columns(
 2821        &mut self,
 2822        tail: DisplayPoint,
 2823        head: DisplayPoint,
 2824        goal_column: u32,
 2825        display_map: &DisplaySnapshot,
 2826        cx: &mut ViewContext<Self>,
 2827    ) {
 2828        let start_row = cmp::min(tail.row(), head.row());
 2829        let end_row = cmp::max(tail.row(), head.row());
 2830        let start_column = cmp::min(tail.column(), goal_column);
 2831        let end_column = cmp::max(tail.column(), goal_column);
 2832        let reversed = start_column < tail.column();
 2833
 2834        let selection_ranges = (start_row.0..=end_row.0)
 2835            .map(DisplayRow)
 2836            .filter_map(|row| {
 2837                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2838                    let start = display_map
 2839                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2840                        .to_point(display_map);
 2841                    let end = display_map
 2842                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2843                        .to_point(display_map);
 2844                    if reversed {
 2845                        Some(end..start)
 2846                    } else {
 2847                        Some(start..end)
 2848                    }
 2849                } else {
 2850                    None
 2851                }
 2852            })
 2853            .collect::<Vec<_>>();
 2854
 2855        self.change_selections(None, cx, |s| {
 2856            s.select_ranges(selection_ranges);
 2857        });
 2858        cx.notify();
 2859    }
 2860
 2861    pub fn has_pending_nonempty_selection(&self) -> bool {
 2862        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2863            Some(Selection { start, end, .. }) => start != end,
 2864            None => false,
 2865        };
 2866
 2867        pending_nonempty_selection
 2868            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2869    }
 2870
 2871    pub fn has_pending_selection(&self) -> bool {
 2872        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2873    }
 2874
 2875    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2876        self.clear_expanded_diff_hunks(cx);
 2877        if self.dismiss_menus_and_popups(true, cx) {
 2878            return;
 2879        }
 2880
 2881        if self.mode == EditorMode::Full {
 2882            if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
 2883                return;
 2884            }
 2885        }
 2886
 2887        cx.propagate();
 2888    }
 2889
 2890    pub fn dismiss_menus_and_popups(
 2891        &mut self,
 2892        should_report_inline_completion_event: bool,
 2893        cx: &mut ViewContext<Self>,
 2894    ) -> bool {
 2895        if self.take_rename(false, cx).is_some() {
 2896            return true;
 2897        }
 2898
 2899        if hide_hover(self, cx) {
 2900            return true;
 2901        }
 2902
 2903        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2904            return true;
 2905        }
 2906
 2907        if self.hide_context_menu(cx).is_some() {
 2908            return true;
 2909        }
 2910
 2911        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2912            return true;
 2913        }
 2914
 2915        if self.snippet_stack.pop().is_some() {
 2916            return true;
 2917        }
 2918
 2919        if self.mode == EditorMode::Full {
 2920            if self.active_diagnostics.is_some() {
 2921                self.dismiss_diagnostics(cx);
 2922                return true;
 2923            }
 2924        }
 2925
 2926        false
 2927    }
 2928
 2929    fn linked_editing_ranges_for(
 2930        &self,
 2931        selection: Range<text::Anchor>,
 2932        cx: &AppContext,
 2933    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2934        if self.linked_edit_ranges.is_empty() {
 2935            return None;
 2936        }
 2937        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2938            selection.end.buffer_id.and_then(|end_buffer_id| {
 2939                if selection.start.buffer_id != Some(end_buffer_id) {
 2940                    return None;
 2941                }
 2942                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2943                let snapshot = buffer.read(cx).snapshot();
 2944                self.linked_edit_ranges
 2945                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2946                    .map(|ranges| (ranges, snapshot, buffer))
 2947            })?;
 2948        use text::ToOffset as TO;
 2949        // find offset from the start of current range to current cursor position
 2950        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2951
 2952        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2953        let start_difference = start_offset - start_byte_offset;
 2954        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2955        let end_difference = end_offset - start_byte_offset;
 2956        // Current range has associated linked ranges.
 2957        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2958        for range in linked_ranges.iter() {
 2959            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2960            let end_offset = start_offset + end_difference;
 2961            let start_offset = start_offset + start_difference;
 2962            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2963                continue;
 2964            }
 2965            let start = buffer_snapshot.anchor_after(start_offset);
 2966            let end = buffer_snapshot.anchor_after(end_offset);
 2967            linked_edits
 2968                .entry(buffer.clone())
 2969                .or_default()
 2970                .push(start..end);
 2971        }
 2972        Some(linked_edits)
 2973    }
 2974
 2975    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2976        let text: Arc<str> = text.into();
 2977
 2978        if self.read_only(cx) {
 2979            return;
 2980        }
 2981
 2982        let selections = self.selections.all_adjusted(cx);
 2983        let mut bracket_inserted = false;
 2984        let mut edits = Vec::new();
 2985        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2986        let mut new_selections = Vec::with_capacity(selections.len());
 2987        let mut new_autoclose_regions = Vec::new();
 2988        let snapshot = self.buffer.read(cx).read(cx);
 2989
 2990        for (selection, autoclose_region) in
 2991            self.selections_with_autoclose_regions(selections, &snapshot)
 2992        {
 2993            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2994                // Determine if the inserted text matches the opening or closing
 2995                // bracket of any of this language's bracket pairs.
 2996                let mut bracket_pair = None;
 2997                let mut is_bracket_pair_start = false;
 2998                let mut is_bracket_pair_end = false;
 2999                if !text.is_empty() {
 3000                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3001                    //  and they are removing the character that triggered IME popup.
 3002                    for (pair, enabled) in scope.brackets() {
 3003                        if !pair.close && !pair.surround {
 3004                            continue;
 3005                        }
 3006
 3007                        if enabled && pair.start.ends_with(text.as_ref()) {
 3008                            bracket_pair = Some(pair.clone());
 3009                            is_bracket_pair_start = true;
 3010                            break;
 3011                        }
 3012                        if pair.end.as_str() == text.as_ref() {
 3013                            bracket_pair = Some(pair.clone());
 3014                            is_bracket_pair_end = true;
 3015                            break;
 3016                        }
 3017                    }
 3018                }
 3019
 3020                if let Some(bracket_pair) = bracket_pair {
 3021                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3022                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3023                    let auto_surround =
 3024                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3025                    if selection.is_empty() {
 3026                        if is_bracket_pair_start {
 3027                            let prefix_len = bracket_pair.start.len() - text.len();
 3028
 3029                            // If the inserted text is a suffix of an opening bracket and the
 3030                            // selection is preceded by the rest of the opening bracket, then
 3031                            // insert the closing bracket.
 3032                            let following_text_allows_autoclose = snapshot
 3033                                .chars_at(selection.start)
 3034                                .next()
 3035                                .map_or(true, |c| scope.should_autoclose_before(c));
 3036                            let preceding_text_matches_prefix = prefix_len == 0
 3037                                || (selection.start.column >= (prefix_len as u32)
 3038                                    && snapshot.contains_str_at(
 3039                                        Point::new(
 3040                                            selection.start.row,
 3041                                            selection.start.column - (prefix_len as u32),
 3042                                        ),
 3043                                        &bracket_pair.start[..prefix_len],
 3044                                    ));
 3045
 3046                            if autoclose
 3047                                && bracket_pair.close
 3048                                && following_text_allows_autoclose
 3049                                && preceding_text_matches_prefix
 3050                            {
 3051                                let anchor = snapshot.anchor_before(selection.end);
 3052                                new_selections.push((selection.map(|_| anchor), text.len()));
 3053                                new_autoclose_regions.push((
 3054                                    anchor,
 3055                                    text.len(),
 3056                                    selection.id,
 3057                                    bracket_pair.clone(),
 3058                                ));
 3059                                edits.push((
 3060                                    selection.range(),
 3061                                    format!("{}{}", text, bracket_pair.end).into(),
 3062                                ));
 3063                                bracket_inserted = true;
 3064                                continue;
 3065                            }
 3066                        }
 3067
 3068                        if let Some(region) = autoclose_region {
 3069                            // If the selection is followed by an auto-inserted closing bracket,
 3070                            // then don't insert that closing bracket again; just move the selection
 3071                            // past the closing bracket.
 3072                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3073                                && text.as_ref() == region.pair.end.as_str();
 3074                            if should_skip {
 3075                                let anchor = snapshot.anchor_after(selection.end);
 3076                                new_selections
 3077                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3078                                continue;
 3079                            }
 3080                        }
 3081
 3082                        let always_treat_brackets_as_autoclosed = snapshot
 3083                            .settings_at(selection.start, cx)
 3084                            .always_treat_brackets_as_autoclosed;
 3085                        if always_treat_brackets_as_autoclosed
 3086                            && is_bracket_pair_end
 3087                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3088                        {
 3089                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3090                            // and the inserted text is a closing bracket and the selection is followed
 3091                            // by the closing bracket then move the selection past the closing bracket.
 3092                            let anchor = snapshot.anchor_after(selection.end);
 3093                            new_selections.push((selection.map(|_| anchor), text.len()));
 3094                            continue;
 3095                        }
 3096                    }
 3097                    // If an opening bracket is 1 character long and is typed while
 3098                    // text is selected, then surround that text with the bracket pair.
 3099                    else if auto_surround
 3100                        && bracket_pair.surround
 3101                        && is_bracket_pair_start
 3102                        && bracket_pair.start.chars().count() == 1
 3103                    {
 3104                        edits.push((selection.start..selection.start, text.clone()));
 3105                        edits.push((
 3106                            selection.end..selection.end,
 3107                            bracket_pair.end.as_str().into(),
 3108                        ));
 3109                        bracket_inserted = true;
 3110                        new_selections.push((
 3111                            Selection {
 3112                                id: selection.id,
 3113                                start: snapshot.anchor_after(selection.start),
 3114                                end: snapshot.anchor_before(selection.end),
 3115                                reversed: selection.reversed,
 3116                                goal: selection.goal,
 3117                            },
 3118                            0,
 3119                        ));
 3120                        continue;
 3121                    }
 3122                }
 3123            }
 3124
 3125            if self.auto_replace_emoji_shortcode
 3126                && selection.is_empty()
 3127                && text.as_ref().ends_with(':')
 3128            {
 3129                if let Some(possible_emoji_short_code) =
 3130                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3131                {
 3132                    if !possible_emoji_short_code.is_empty() {
 3133                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3134                            let emoji_shortcode_start = Point::new(
 3135                                selection.start.row,
 3136                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3137                            );
 3138
 3139                            // Remove shortcode from buffer
 3140                            edits.push((
 3141                                emoji_shortcode_start..selection.start,
 3142                                "".to_string().into(),
 3143                            ));
 3144                            new_selections.push((
 3145                                Selection {
 3146                                    id: selection.id,
 3147                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3148                                    end: snapshot.anchor_before(selection.start),
 3149                                    reversed: selection.reversed,
 3150                                    goal: selection.goal,
 3151                                },
 3152                                0,
 3153                            ));
 3154
 3155                            // Insert emoji
 3156                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3157                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3158                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3159
 3160                            continue;
 3161                        }
 3162                    }
 3163                }
 3164            }
 3165
 3166            // If not handling any auto-close operation, then just replace the selected
 3167            // text with the given input and move the selection to the end of the
 3168            // newly inserted text.
 3169            let anchor = snapshot.anchor_after(selection.end);
 3170            if !self.linked_edit_ranges.is_empty() {
 3171                let start_anchor = snapshot.anchor_before(selection.start);
 3172
 3173                let is_word_char = text.chars().next().map_or(true, |char| {
 3174                    let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
 3175                    let kind = char_kind(&scope, char);
 3176
 3177                    kind == CharKind::Word
 3178                });
 3179
 3180                if is_word_char {
 3181                    if let Some(ranges) = self
 3182                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3183                    {
 3184                        for (buffer, edits) in ranges {
 3185                            linked_edits
 3186                                .entry(buffer.clone())
 3187                                .or_default()
 3188                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3189                        }
 3190                    }
 3191                }
 3192            }
 3193
 3194            new_selections.push((selection.map(|_| anchor), 0));
 3195            edits.push((selection.start..selection.end, text.clone()));
 3196        }
 3197
 3198        drop(snapshot);
 3199
 3200        self.transact(cx, |this, cx| {
 3201            this.buffer.update(cx, |buffer, cx| {
 3202                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3203            });
 3204            for (buffer, edits) in linked_edits {
 3205                buffer.update(cx, |buffer, cx| {
 3206                    let snapshot = buffer.snapshot();
 3207                    let edits = edits
 3208                        .into_iter()
 3209                        .map(|(range, text)| {
 3210                            use text::ToPoint as TP;
 3211                            let end_point = TP::to_point(&range.end, &snapshot);
 3212                            let start_point = TP::to_point(&range.start, &snapshot);
 3213                            (start_point..end_point, text)
 3214                        })
 3215                        .sorted_by_key(|(range, _)| range.start)
 3216                        .collect::<Vec<_>>();
 3217                    buffer.edit(edits, None, cx);
 3218                })
 3219            }
 3220            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3221            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3222            let snapshot = this.buffer.read(cx).read(cx);
 3223            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3224                .zip(new_selection_deltas)
 3225                .map(|(selection, delta)| Selection {
 3226                    id: selection.id,
 3227                    start: selection.start + delta,
 3228                    end: selection.end + delta,
 3229                    reversed: selection.reversed,
 3230                    goal: SelectionGoal::None,
 3231                })
 3232                .collect::<Vec<_>>();
 3233
 3234            let mut i = 0;
 3235            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3236                let position = position.to_offset(&snapshot) + delta;
 3237                let start = snapshot.anchor_before(position);
 3238                let end = snapshot.anchor_after(position);
 3239                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3240                    match existing_state.range.start.cmp(&start, &snapshot) {
 3241                        Ordering::Less => i += 1,
 3242                        Ordering::Greater => break,
 3243                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3244                            Ordering::Less => i += 1,
 3245                            Ordering::Equal => break,
 3246                            Ordering::Greater => break,
 3247                        },
 3248                    }
 3249                }
 3250                this.autoclose_regions.insert(
 3251                    i,
 3252                    AutocloseRegion {
 3253                        selection_id,
 3254                        range: start..end,
 3255                        pair,
 3256                    },
 3257                );
 3258            }
 3259
 3260            drop(snapshot);
 3261            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3262            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3263                s.select(new_selections)
 3264            });
 3265
 3266            if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
 3267                if let Some(on_type_format_task) =
 3268                    this.trigger_on_type_formatting(text.to_string(), cx)
 3269                {
 3270                    on_type_format_task.detach_and_log_err(cx);
 3271                }
 3272            }
 3273
 3274            let editor_settings = EditorSettings::get_global(cx);
 3275            if bracket_inserted
 3276                && (editor_settings.auto_signature_help
 3277                    || editor_settings.show_signature_help_after_edits)
 3278            {
 3279                this.show_signature_help(&ShowSignatureHelp, cx);
 3280            }
 3281
 3282            let trigger_in_words = !had_active_inline_completion;
 3283            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3284            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3285            this.refresh_inline_completion(true, cx);
 3286        });
 3287    }
 3288
 3289    fn find_possible_emoji_shortcode_at_position(
 3290        snapshot: &MultiBufferSnapshot,
 3291        position: Point,
 3292    ) -> Option<String> {
 3293        let mut chars = Vec::new();
 3294        let mut found_colon = false;
 3295        for char in snapshot.reversed_chars_at(position).take(100) {
 3296            // Found a possible emoji shortcode in the middle of the buffer
 3297            if found_colon {
 3298                if char.is_whitespace() {
 3299                    chars.reverse();
 3300                    return Some(chars.iter().collect());
 3301                }
 3302                // If the previous character is not a whitespace, we are in the middle of a word
 3303                // and we only want to complete the shortcode if the word is made up of other emojis
 3304                let mut containing_word = String::new();
 3305                for ch in snapshot
 3306                    .reversed_chars_at(position)
 3307                    .skip(chars.len() + 1)
 3308                    .take(100)
 3309                {
 3310                    if ch.is_whitespace() {
 3311                        break;
 3312                    }
 3313                    containing_word.push(ch);
 3314                }
 3315                let containing_word = containing_word.chars().rev().collect::<String>();
 3316                if util::word_consists_of_emojis(containing_word.as_str()) {
 3317                    chars.reverse();
 3318                    return Some(chars.iter().collect());
 3319                }
 3320            }
 3321
 3322            if char.is_whitespace() || !char.is_ascii() {
 3323                return None;
 3324            }
 3325            if char == ':' {
 3326                found_colon = true;
 3327            } else {
 3328                chars.push(char);
 3329            }
 3330        }
 3331        // Found a possible emoji shortcode at the beginning of the buffer
 3332        chars.reverse();
 3333        Some(chars.iter().collect())
 3334    }
 3335
 3336    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3337        self.transact(cx, |this, cx| {
 3338            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3339                let selections = this.selections.all::<usize>(cx);
 3340                let multi_buffer = this.buffer.read(cx);
 3341                let buffer = multi_buffer.snapshot(cx);
 3342                selections
 3343                    .iter()
 3344                    .map(|selection| {
 3345                        let start_point = selection.start.to_point(&buffer);
 3346                        let mut indent =
 3347                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3348                        indent.len = cmp::min(indent.len, start_point.column);
 3349                        let start = selection.start;
 3350                        let end = selection.end;
 3351                        let selection_is_empty = start == end;
 3352                        let language_scope = buffer.language_scope_at(start);
 3353                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3354                            &language_scope
 3355                        {
 3356                            let leading_whitespace_len = buffer
 3357                                .reversed_chars_at(start)
 3358                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3359                                .map(|c| c.len_utf8())
 3360                                .sum::<usize>();
 3361
 3362                            let trailing_whitespace_len = buffer
 3363                                .chars_at(end)
 3364                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3365                                .map(|c| c.len_utf8())
 3366                                .sum::<usize>();
 3367
 3368                            let insert_extra_newline =
 3369                                language.brackets().any(|(pair, enabled)| {
 3370                                    let pair_start = pair.start.trim_end();
 3371                                    let pair_end = pair.end.trim_start();
 3372
 3373                                    enabled
 3374                                        && pair.newline
 3375                                        && buffer.contains_str_at(
 3376                                            end + trailing_whitespace_len,
 3377                                            pair_end,
 3378                                        )
 3379                                        && buffer.contains_str_at(
 3380                                            (start - leading_whitespace_len)
 3381                                                .saturating_sub(pair_start.len()),
 3382                                            pair_start,
 3383                                        )
 3384                                });
 3385
 3386                            // Comment extension on newline is allowed only for cursor selections
 3387                            let comment_delimiter = maybe!({
 3388                                if !selection_is_empty {
 3389                                    return None;
 3390                                }
 3391
 3392                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3393                                    return None;
 3394                                }
 3395
 3396                                let delimiters = language.line_comment_prefixes();
 3397                                let max_len_of_delimiter =
 3398                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3399                                let (snapshot, range) =
 3400                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3401
 3402                                let mut index_of_first_non_whitespace = 0;
 3403                                let comment_candidate = snapshot
 3404                                    .chars_for_range(range)
 3405                                    .skip_while(|c| {
 3406                                        let should_skip = c.is_whitespace();
 3407                                        if should_skip {
 3408                                            index_of_first_non_whitespace += 1;
 3409                                        }
 3410                                        should_skip
 3411                                    })
 3412                                    .take(max_len_of_delimiter)
 3413                                    .collect::<String>();
 3414                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3415                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3416                                })?;
 3417                                let cursor_is_placed_after_comment_marker =
 3418                                    index_of_first_non_whitespace + comment_prefix.len()
 3419                                        <= start_point.column as usize;
 3420                                if cursor_is_placed_after_comment_marker {
 3421                                    Some(comment_prefix.clone())
 3422                                } else {
 3423                                    None
 3424                                }
 3425                            });
 3426                            (comment_delimiter, insert_extra_newline)
 3427                        } else {
 3428                            (None, false)
 3429                        };
 3430
 3431                        let capacity_for_delimiter = comment_delimiter
 3432                            .as_deref()
 3433                            .map(str::len)
 3434                            .unwrap_or_default();
 3435                        let mut new_text =
 3436                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3437                        new_text.push_str("\n");
 3438                        new_text.extend(indent.chars());
 3439                        if let Some(delimiter) = &comment_delimiter {
 3440                            new_text.push_str(&delimiter);
 3441                        }
 3442                        if insert_extra_newline {
 3443                            new_text = new_text.repeat(2);
 3444                        }
 3445
 3446                        let anchor = buffer.anchor_after(end);
 3447                        let new_selection = selection.map(|_| anchor);
 3448                        (
 3449                            (start..end, new_text),
 3450                            (insert_extra_newline, new_selection),
 3451                        )
 3452                    })
 3453                    .unzip()
 3454            };
 3455
 3456            this.edit_with_autoindent(edits, cx);
 3457            let buffer = this.buffer.read(cx).snapshot(cx);
 3458            let new_selections = selection_fixup_info
 3459                .into_iter()
 3460                .map(|(extra_newline_inserted, new_selection)| {
 3461                    let mut cursor = new_selection.end.to_point(&buffer);
 3462                    if extra_newline_inserted {
 3463                        cursor.row -= 1;
 3464                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3465                    }
 3466                    new_selection.map(|_| cursor)
 3467                })
 3468                .collect();
 3469
 3470            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3471            this.refresh_inline_completion(true, cx);
 3472        });
 3473    }
 3474
 3475    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3476        let buffer = self.buffer.read(cx);
 3477        let snapshot = buffer.snapshot(cx);
 3478
 3479        let mut edits = Vec::new();
 3480        let mut rows = Vec::new();
 3481
 3482        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3483            let cursor = selection.head();
 3484            let row = cursor.row;
 3485
 3486            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3487
 3488            let newline = "\n".to_string();
 3489            edits.push((start_of_line..start_of_line, newline));
 3490
 3491            rows.push(row + rows_inserted as u32);
 3492        }
 3493
 3494        self.transact(cx, |editor, cx| {
 3495            editor.edit(edits, cx);
 3496
 3497            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3498                let mut index = 0;
 3499                s.move_cursors_with(|map, _, _| {
 3500                    let row = rows[index];
 3501                    index += 1;
 3502
 3503                    let point = Point::new(row, 0);
 3504                    let boundary = map.next_line_boundary(point).1;
 3505                    let clipped = map.clip_point(boundary, Bias::Left);
 3506
 3507                    (clipped, SelectionGoal::None)
 3508                });
 3509            });
 3510
 3511            let mut indent_edits = Vec::new();
 3512            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3513            for row in rows {
 3514                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3515                for (row, indent) in indents {
 3516                    if indent.len == 0 {
 3517                        continue;
 3518                    }
 3519
 3520                    let text = match indent.kind {
 3521                        IndentKind::Space => " ".repeat(indent.len as usize),
 3522                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3523                    };
 3524                    let point = Point::new(row.0, 0);
 3525                    indent_edits.push((point..point, text));
 3526                }
 3527            }
 3528            editor.edit(indent_edits, cx);
 3529        });
 3530    }
 3531
 3532    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3533        let buffer = self.buffer.read(cx);
 3534        let snapshot = buffer.snapshot(cx);
 3535
 3536        let mut edits = Vec::new();
 3537        let mut rows = Vec::new();
 3538        let mut rows_inserted = 0;
 3539
 3540        for selection in self.selections.all_adjusted(cx) {
 3541            let cursor = selection.head();
 3542            let row = cursor.row;
 3543
 3544            let point = Point::new(row + 1, 0);
 3545            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3546
 3547            let newline = "\n".to_string();
 3548            edits.push((start_of_line..start_of_line, newline));
 3549
 3550            rows_inserted += 1;
 3551            rows.push(row + rows_inserted);
 3552        }
 3553
 3554        self.transact(cx, |editor, cx| {
 3555            editor.edit(edits, cx);
 3556
 3557            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3558                let mut index = 0;
 3559                s.move_cursors_with(|map, _, _| {
 3560                    let row = rows[index];
 3561                    index += 1;
 3562
 3563                    let point = Point::new(row, 0);
 3564                    let boundary = map.next_line_boundary(point).1;
 3565                    let clipped = map.clip_point(boundary, Bias::Left);
 3566
 3567                    (clipped, SelectionGoal::None)
 3568                });
 3569            });
 3570
 3571            let mut indent_edits = Vec::new();
 3572            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3573            for row in rows {
 3574                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3575                for (row, indent) in indents {
 3576                    if indent.len == 0 {
 3577                        continue;
 3578                    }
 3579
 3580                    let text = match indent.kind {
 3581                        IndentKind::Space => " ".repeat(indent.len as usize),
 3582                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3583                    };
 3584                    let point = Point::new(row.0, 0);
 3585                    indent_edits.push((point..point, text));
 3586                }
 3587            }
 3588            editor.edit(indent_edits, cx);
 3589        });
 3590    }
 3591
 3592    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3593        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3594            original_indent_columns: Vec::new(),
 3595        });
 3596        self.insert_with_autoindent_mode(text, autoindent, cx);
 3597    }
 3598
 3599    fn insert_with_autoindent_mode(
 3600        &mut self,
 3601        text: &str,
 3602        autoindent_mode: Option<AutoindentMode>,
 3603        cx: &mut ViewContext<Self>,
 3604    ) {
 3605        if self.read_only(cx) {
 3606            return;
 3607        }
 3608
 3609        let text: Arc<str> = text.into();
 3610        self.transact(cx, |this, cx| {
 3611            let old_selections = this.selections.all_adjusted(cx);
 3612            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3613                let anchors = {
 3614                    let snapshot = buffer.read(cx);
 3615                    old_selections
 3616                        .iter()
 3617                        .map(|s| {
 3618                            let anchor = snapshot.anchor_after(s.head());
 3619                            s.map(|_| anchor)
 3620                        })
 3621                        .collect::<Vec<_>>()
 3622                };
 3623                buffer.edit(
 3624                    old_selections
 3625                        .iter()
 3626                        .map(|s| (s.start..s.end, text.clone())),
 3627                    autoindent_mode,
 3628                    cx,
 3629                );
 3630                anchors
 3631            });
 3632
 3633            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3634                s.select_anchors(selection_anchors);
 3635            })
 3636        });
 3637    }
 3638
 3639    fn trigger_completion_on_input(
 3640        &mut self,
 3641        text: &str,
 3642        trigger_in_words: bool,
 3643        cx: &mut ViewContext<Self>,
 3644    ) {
 3645        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3646            self.show_completions(
 3647                &ShowCompletions {
 3648                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3649                },
 3650                cx,
 3651            );
 3652        } else {
 3653            self.hide_context_menu(cx);
 3654        }
 3655    }
 3656
 3657    fn is_completion_trigger(
 3658        &self,
 3659        text: &str,
 3660        trigger_in_words: bool,
 3661        cx: &mut ViewContext<Self>,
 3662    ) -> bool {
 3663        let position = self.selections.newest_anchor().head();
 3664        let multibuffer = self.buffer.read(cx);
 3665        let Some(buffer) = position
 3666            .buffer_id
 3667            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3668        else {
 3669            return false;
 3670        };
 3671
 3672        if let Some(completion_provider) = &self.completion_provider {
 3673            completion_provider.is_completion_trigger(
 3674                &buffer,
 3675                position.text_anchor,
 3676                text,
 3677                trigger_in_words,
 3678                cx,
 3679            )
 3680        } else {
 3681            false
 3682        }
 3683    }
 3684
 3685    /// If any empty selections is touching the start of its innermost containing autoclose
 3686    /// region, expand it to select the brackets.
 3687    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3688        let selections = self.selections.all::<usize>(cx);
 3689        let buffer = self.buffer.read(cx).read(cx);
 3690        let new_selections = self
 3691            .selections_with_autoclose_regions(selections, &buffer)
 3692            .map(|(mut selection, region)| {
 3693                if !selection.is_empty() {
 3694                    return selection;
 3695                }
 3696
 3697                if let Some(region) = region {
 3698                    let mut range = region.range.to_offset(&buffer);
 3699                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3700                        range.start -= region.pair.start.len();
 3701                        if buffer.contains_str_at(range.start, &region.pair.start)
 3702                            && buffer.contains_str_at(range.end, &region.pair.end)
 3703                        {
 3704                            range.end += region.pair.end.len();
 3705                            selection.start = range.start;
 3706                            selection.end = range.end;
 3707
 3708                            return selection;
 3709                        }
 3710                    }
 3711                }
 3712
 3713                let always_treat_brackets_as_autoclosed = buffer
 3714                    .settings_at(selection.start, cx)
 3715                    .always_treat_brackets_as_autoclosed;
 3716
 3717                if !always_treat_brackets_as_autoclosed {
 3718                    return selection;
 3719                }
 3720
 3721                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3722                    for (pair, enabled) in scope.brackets() {
 3723                        if !enabled || !pair.close {
 3724                            continue;
 3725                        }
 3726
 3727                        if buffer.contains_str_at(selection.start, &pair.end) {
 3728                            let pair_start_len = pair.start.len();
 3729                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3730                            {
 3731                                selection.start -= pair_start_len;
 3732                                selection.end += pair.end.len();
 3733
 3734                                return selection;
 3735                            }
 3736                        }
 3737                    }
 3738                }
 3739
 3740                selection
 3741            })
 3742            .collect();
 3743
 3744        drop(buffer);
 3745        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3746    }
 3747
 3748    /// Iterate the given selections, and for each one, find the smallest surrounding
 3749    /// autoclose region. This uses the ordering of the selections and the autoclose
 3750    /// regions to avoid repeated comparisons.
 3751    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3752        &'a self,
 3753        selections: impl IntoIterator<Item = Selection<D>>,
 3754        buffer: &'a MultiBufferSnapshot,
 3755    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3756        let mut i = 0;
 3757        let mut regions = self.autoclose_regions.as_slice();
 3758        selections.into_iter().map(move |selection| {
 3759            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3760
 3761            let mut enclosing = None;
 3762            while let Some(pair_state) = regions.get(i) {
 3763                if pair_state.range.end.to_offset(buffer) < range.start {
 3764                    regions = &regions[i + 1..];
 3765                    i = 0;
 3766                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3767                    break;
 3768                } else {
 3769                    if pair_state.selection_id == selection.id {
 3770                        enclosing = Some(pair_state);
 3771                    }
 3772                    i += 1;
 3773                }
 3774            }
 3775
 3776            (selection.clone(), enclosing)
 3777        })
 3778    }
 3779
 3780    /// Remove any autoclose regions that no longer contain their selection.
 3781    fn invalidate_autoclose_regions(
 3782        &mut self,
 3783        mut selections: &[Selection<Anchor>],
 3784        buffer: &MultiBufferSnapshot,
 3785    ) {
 3786        self.autoclose_regions.retain(|state| {
 3787            let mut i = 0;
 3788            while let Some(selection) = selections.get(i) {
 3789                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3790                    selections = &selections[1..];
 3791                    continue;
 3792                }
 3793                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3794                    break;
 3795                }
 3796                if selection.id == state.selection_id {
 3797                    return true;
 3798                } else {
 3799                    i += 1;
 3800                }
 3801            }
 3802            false
 3803        });
 3804    }
 3805
 3806    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3807        let offset = position.to_offset(buffer);
 3808        let (word_range, kind) = buffer.surrounding_word(offset);
 3809        if offset > word_range.start && kind == Some(CharKind::Word) {
 3810            Some(
 3811                buffer
 3812                    .text_for_range(word_range.start..offset)
 3813                    .collect::<String>(),
 3814            )
 3815        } else {
 3816            None
 3817        }
 3818    }
 3819
 3820    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3821        self.refresh_inlay_hints(
 3822            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3823            cx,
 3824        );
 3825    }
 3826
 3827    pub fn inlay_hints_enabled(&self) -> bool {
 3828        self.inlay_hint_cache.enabled
 3829    }
 3830
 3831    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3832        if self.project.is_none() || self.mode != EditorMode::Full {
 3833            return;
 3834        }
 3835
 3836        let reason_description = reason.description();
 3837        let ignore_debounce = matches!(
 3838            reason,
 3839            InlayHintRefreshReason::SettingsChange(_)
 3840                | InlayHintRefreshReason::Toggle(_)
 3841                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3842        );
 3843        let (invalidate_cache, required_languages) = match reason {
 3844            InlayHintRefreshReason::Toggle(enabled) => {
 3845                self.inlay_hint_cache.enabled = enabled;
 3846                if enabled {
 3847                    (InvalidationStrategy::RefreshRequested, None)
 3848                } else {
 3849                    self.inlay_hint_cache.clear();
 3850                    self.splice_inlays(
 3851                        self.visible_inlay_hints(cx)
 3852                            .iter()
 3853                            .map(|inlay| inlay.id)
 3854                            .collect(),
 3855                        Vec::new(),
 3856                        cx,
 3857                    );
 3858                    return;
 3859                }
 3860            }
 3861            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3862                match self.inlay_hint_cache.update_settings(
 3863                    &self.buffer,
 3864                    new_settings,
 3865                    self.visible_inlay_hints(cx),
 3866                    cx,
 3867                ) {
 3868                    ControlFlow::Break(Some(InlaySplice {
 3869                        to_remove,
 3870                        to_insert,
 3871                    })) => {
 3872                        self.splice_inlays(to_remove, to_insert, cx);
 3873                        return;
 3874                    }
 3875                    ControlFlow::Break(None) => return,
 3876                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3877                }
 3878            }
 3879            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3880                if let Some(InlaySplice {
 3881                    to_remove,
 3882                    to_insert,
 3883                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3884                {
 3885                    self.splice_inlays(to_remove, to_insert, cx);
 3886                }
 3887                return;
 3888            }
 3889            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3890            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3891                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3892            }
 3893            InlayHintRefreshReason::RefreshRequested => {
 3894                (InvalidationStrategy::RefreshRequested, None)
 3895            }
 3896        };
 3897
 3898        if let Some(InlaySplice {
 3899            to_remove,
 3900            to_insert,
 3901        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3902            reason_description,
 3903            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3904            invalidate_cache,
 3905            ignore_debounce,
 3906            cx,
 3907        ) {
 3908            self.splice_inlays(to_remove, to_insert, cx);
 3909        }
 3910    }
 3911
 3912    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3913        self.display_map
 3914            .read(cx)
 3915            .current_inlays()
 3916            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3917            .cloned()
 3918            .collect()
 3919    }
 3920
 3921    pub fn excerpts_for_inlay_hints_query(
 3922        &self,
 3923        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3924        cx: &mut ViewContext<Editor>,
 3925    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3926        let Some(project) = self.project.as_ref() else {
 3927            return HashMap::default();
 3928        };
 3929        let project = project.read(cx);
 3930        let multi_buffer = self.buffer().read(cx);
 3931        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3932        let multi_buffer_visible_start = self
 3933            .scroll_manager
 3934            .anchor()
 3935            .anchor
 3936            .to_point(&multi_buffer_snapshot);
 3937        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3938            multi_buffer_visible_start
 3939                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3940            Bias::Left,
 3941        );
 3942        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3943        multi_buffer
 3944            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3945            .into_iter()
 3946            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3947            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3948                let buffer = buffer_handle.read(cx);
 3949                let buffer_file = project::File::from_dyn(buffer.file())?;
 3950                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3951                let worktree_entry = buffer_worktree
 3952                    .read(cx)
 3953                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3954                if worktree_entry.is_ignored {
 3955                    return None;
 3956                }
 3957
 3958                let language = buffer.language()?;
 3959                if let Some(restrict_to_languages) = restrict_to_languages {
 3960                    if !restrict_to_languages.contains(language) {
 3961                        return None;
 3962                    }
 3963                }
 3964                Some((
 3965                    excerpt_id,
 3966                    (
 3967                        buffer_handle,
 3968                        buffer.version().clone(),
 3969                        excerpt_visible_range,
 3970                    ),
 3971                ))
 3972            })
 3973            .collect()
 3974    }
 3975
 3976    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3977        TextLayoutDetails {
 3978            text_system: cx.text_system().clone(),
 3979            editor_style: self.style.clone().unwrap(),
 3980            rem_size: cx.rem_size(),
 3981            scroll_anchor: self.scroll_manager.anchor(),
 3982            visible_rows: self.visible_line_count(),
 3983            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3984        }
 3985    }
 3986
 3987    fn splice_inlays(
 3988        &self,
 3989        to_remove: Vec<InlayId>,
 3990        to_insert: Vec<Inlay>,
 3991        cx: &mut ViewContext<Self>,
 3992    ) {
 3993        self.display_map.update(cx, |display_map, cx| {
 3994            display_map.splice_inlays(to_remove, to_insert, cx);
 3995        });
 3996        cx.notify();
 3997    }
 3998
 3999    fn trigger_on_type_formatting(
 4000        &self,
 4001        input: String,
 4002        cx: &mut ViewContext<Self>,
 4003    ) -> Option<Task<Result<()>>> {
 4004        if input.len() != 1 {
 4005            return None;
 4006        }
 4007
 4008        let project = self.project.as_ref()?;
 4009        let position = self.selections.newest_anchor().head();
 4010        let (buffer, buffer_position) = self
 4011            .buffer
 4012            .read(cx)
 4013            .text_anchor_for_position(position, cx)?;
 4014
 4015        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4016        // hence we do LSP request & edit on host side only — add formats to host's history.
 4017        let push_to_lsp_host_history = true;
 4018        // If this is not the host, append its history with new edits.
 4019        let push_to_client_history = project.read(cx).is_remote();
 4020
 4021        let on_type_formatting = project.update(cx, |project, cx| {
 4022            project.on_type_format(
 4023                buffer.clone(),
 4024                buffer_position,
 4025                input,
 4026                push_to_lsp_host_history,
 4027                cx,
 4028            )
 4029        });
 4030        Some(cx.spawn(|editor, mut cx| async move {
 4031            if let Some(transaction) = on_type_formatting.await? {
 4032                if push_to_client_history {
 4033                    buffer
 4034                        .update(&mut cx, |buffer, _| {
 4035                            buffer.push_transaction(transaction, Instant::now());
 4036                        })
 4037                        .ok();
 4038                }
 4039                editor.update(&mut cx, |editor, cx| {
 4040                    editor.refresh_document_highlights(cx);
 4041                })?;
 4042            }
 4043            Ok(())
 4044        }))
 4045    }
 4046
 4047    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4048        if self.pending_rename.is_some() {
 4049            return;
 4050        }
 4051
 4052        let Some(provider) = self.completion_provider.as_ref() else {
 4053            return;
 4054        };
 4055
 4056        let position = self.selections.newest_anchor().head();
 4057        let (buffer, buffer_position) =
 4058            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4059                output
 4060            } else {
 4061                return;
 4062            };
 4063
 4064        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4065        let is_followup_invoke = {
 4066            let context_menu_state = self.context_menu.read();
 4067            matches!(
 4068                context_menu_state.deref(),
 4069                Some(ContextMenu::Completions(_))
 4070            )
 4071        };
 4072        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4073            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4074            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(&trigger) => {
 4075                CompletionTriggerKind::TRIGGER_CHARACTER
 4076            }
 4077
 4078            _ => CompletionTriggerKind::INVOKED,
 4079        };
 4080        let completion_context = CompletionContext {
 4081            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4082                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4083                    Some(String::from(trigger))
 4084                } else {
 4085                    None
 4086                }
 4087            }),
 4088            trigger_kind,
 4089        };
 4090        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4091
 4092        let id = post_inc(&mut self.next_completion_id);
 4093        let task = cx.spawn(|this, mut cx| {
 4094            async move {
 4095                this.update(&mut cx, |this, _| {
 4096                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4097                })?;
 4098                let completions = completions.await.log_err();
 4099                let menu = if let Some(completions) = completions {
 4100                    let mut menu = CompletionsMenu {
 4101                        id,
 4102                        initial_position: position,
 4103                        match_candidates: completions
 4104                            .iter()
 4105                            .enumerate()
 4106                            .map(|(id, completion)| {
 4107                                StringMatchCandidate::new(
 4108                                    id,
 4109                                    completion.label.text[completion.label.filter_range.clone()]
 4110                                        .into(),
 4111                                )
 4112                            })
 4113                            .collect(),
 4114                        buffer: buffer.clone(),
 4115                        completions: Arc::new(RwLock::new(completions.into())),
 4116                        matches: Vec::new().into(),
 4117                        selected_item: 0,
 4118                        scroll_handle: UniformListScrollHandle::new(),
 4119                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4120                            DebouncedDelay::new(),
 4121                        )),
 4122                    };
 4123                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4124                        .await;
 4125
 4126                    if menu.matches.is_empty() {
 4127                        None
 4128                    } else {
 4129                        this.update(&mut cx, |editor, cx| {
 4130                            let completions = menu.completions.clone();
 4131                            let matches = menu.matches.clone();
 4132
 4133                            let delay_ms = EditorSettings::get_global(cx)
 4134                                .completion_documentation_secondary_query_debounce;
 4135                            let delay = Duration::from_millis(delay_ms);
 4136                            editor
 4137                                .completion_documentation_pre_resolve_debounce
 4138                                .fire_new(delay, cx, |editor, cx| {
 4139                                    CompletionsMenu::pre_resolve_completion_documentation(
 4140                                        buffer,
 4141                                        completions,
 4142                                        matches,
 4143                                        editor,
 4144                                        cx,
 4145                                    )
 4146                                });
 4147                        })
 4148                        .ok();
 4149                        Some(menu)
 4150                    }
 4151                } else {
 4152                    None
 4153                };
 4154
 4155                this.update(&mut cx, |this, cx| {
 4156                    let mut context_menu = this.context_menu.write();
 4157                    match context_menu.as_ref() {
 4158                        None => {}
 4159
 4160                        Some(ContextMenu::Completions(prev_menu)) => {
 4161                            if prev_menu.id > id {
 4162                                return;
 4163                            }
 4164                        }
 4165
 4166                        _ => return,
 4167                    }
 4168
 4169                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4170                        let menu = menu.unwrap();
 4171                        *context_menu = Some(ContextMenu::Completions(menu));
 4172                        drop(context_menu);
 4173                        this.discard_inline_completion(false, cx);
 4174                        cx.notify();
 4175                    } else if this.completion_tasks.len() <= 1 {
 4176                        // If there are no more completion tasks and the last menu was
 4177                        // empty, we should hide it. If it was already hidden, we should
 4178                        // also show the copilot completion when available.
 4179                        drop(context_menu);
 4180                        if this.hide_context_menu(cx).is_none() {
 4181                            this.update_visible_inline_completion(cx);
 4182                        }
 4183                    }
 4184                })?;
 4185
 4186                Ok::<_, anyhow::Error>(())
 4187            }
 4188            .log_err()
 4189        });
 4190
 4191        self.completion_tasks.push((id, task));
 4192    }
 4193
 4194    pub fn confirm_completion(
 4195        &mut self,
 4196        action: &ConfirmCompletion,
 4197        cx: &mut ViewContext<Self>,
 4198    ) -> Option<Task<Result<()>>> {
 4199        use language::ToOffset as _;
 4200
 4201        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4202            menu
 4203        } else {
 4204            return None;
 4205        };
 4206
 4207        let mat = completions_menu
 4208            .matches
 4209            .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
 4210        let buffer_handle = completions_menu.buffer;
 4211        let completions = completions_menu.completions.read();
 4212        let completion = completions.get(mat.candidate_id)?;
 4213        cx.stop_propagation();
 4214
 4215        let snippet;
 4216        let text;
 4217
 4218        if completion.is_snippet() {
 4219            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4220            text = snippet.as_ref().unwrap().text.clone();
 4221        } else {
 4222            snippet = None;
 4223            text = completion.new_text.clone();
 4224        };
 4225        let selections = self.selections.all::<usize>(cx);
 4226        let buffer = buffer_handle.read(cx);
 4227        let old_range = completion.old_range.to_offset(buffer);
 4228        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4229
 4230        let newest_selection = self.selections.newest_anchor();
 4231        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4232            return None;
 4233        }
 4234
 4235        let lookbehind = newest_selection
 4236            .start
 4237            .text_anchor
 4238            .to_offset(buffer)
 4239            .saturating_sub(old_range.start);
 4240        let lookahead = old_range
 4241            .end
 4242            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4243        let mut common_prefix_len = old_text
 4244            .bytes()
 4245            .zip(text.bytes())
 4246            .take_while(|(a, b)| a == b)
 4247            .count();
 4248
 4249        let snapshot = self.buffer.read(cx).snapshot(cx);
 4250        let mut range_to_replace: Option<Range<isize>> = None;
 4251        let mut ranges = Vec::new();
 4252        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4253        for selection in &selections {
 4254            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4255                let start = selection.start.saturating_sub(lookbehind);
 4256                let end = selection.end + lookahead;
 4257                if selection.id == newest_selection.id {
 4258                    range_to_replace = Some(
 4259                        ((start + common_prefix_len) as isize - selection.start as isize)
 4260                            ..(end as isize - selection.start as isize),
 4261                    );
 4262                }
 4263                ranges.push(start + common_prefix_len..end);
 4264            } else {
 4265                common_prefix_len = 0;
 4266                ranges.clear();
 4267                ranges.extend(selections.iter().map(|s| {
 4268                    if s.id == newest_selection.id {
 4269                        range_to_replace = Some(
 4270                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4271                                - selection.start as isize
 4272                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4273                                    - selection.start as isize,
 4274                        );
 4275                        old_range.clone()
 4276                    } else {
 4277                        s.start..s.end
 4278                    }
 4279                }));
 4280                break;
 4281            }
 4282            if !self.linked_edit_ranges.is_empty() {
 4283                let start_anchor = snapshot.anchor_before(selection.head());
 4284                let end_anchor = snapshot.anchor_after(selection.tail());
 4285                if let Some(ranges) = self
 4286                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4287                {
 4288                    for (buffer, edits) in ranges {
 4289                        linked_edits.entry(buffer.clone()).or_default().extend(
 4290                            edits
 4291                                .into_iter()
 4292                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4293                        );
 4294                    }
 4295                }
 4296            }
 4297        }
 4298        let text = &text[common_prefix_len..];
 4299
 4300        cx.emit(EditorEvent::InputHandled {
 4301            utf16_range_to_replace: range_to_replace,
 4302            text: text.into(),
 4303        });
 4304
 4305        self.transact(cx, |this, cx| {
 4306            if let Some(mut snippet) = snippet {
 4307                snippet.text = text.to_string();
 4308                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4309                    tabstop.start -= common_prefix_len as isize;
 4310                    tabstop.end -= common_prefix_len as isize;
 4311                }
 4312
 4313                this.insert_snippet(&ranges, snippet, cx).log_err();
 4314            } else {
 4315                this.buffer.update(cx, |buffer, cx| {
 4316                    buffer.edit(
 4317                        ranges.iter().map(|range| (range.clone(), text)),
 4318                        this.autoindent_mode.clone(),
 4319                        cx,
 4320                    );
 4321                });
 4322            }
 4323            for (buffer, edits) in linked_edits {
 4324                buffer.update(cx, |buffer, cx| {
 4325                    let snapshot = buffer.snapshot();
 4326                    let edits = edits
 4327                        .into_iter()
 4328                        .map(|(range, text)| {
 4329                            use text::ToPoint as TP;
 4330                            let end_point = TP::to_point(&range.end, &snapshot);
 4331                            let start_point = TP::to_point(&range.start, &snapshot);
 4332                            (start_point..end_point, text)
 4333                        })
 4334                        .sorted_by_key(|(range, _)| range.start)
 4335                        .collect::<Vec<_>>();
 4336                    buffer.edit(edits, None, cx);
 4337                })
 4338            }
 4339
 4340            this.refresh_inline_completion(true, cx);
 4341        });
 4342
 4343        if let Some(confirm) = completion.confirm.as_ref() {
 4344            (confirm)(cx);
 4345        }
 4346
 4347        if completion.show_new_completions_on_confirm {
 4348            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4349        }
 4350
 4351        let provider = self.completion_provider.as_ref()?;
 4352        let apply_edits = provider.apply_additional_edits_for_completion(
 4353            buffer_handle,
 4354            completion.clone(),
 4355            true,
 4356            cx,
 4357        );
 4358
 4359        let editor_settings = EditorSettings::get_global(cx);
 4360        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4361            // After the code completion is finished, users often want to know what signatures are needed.
 4362            // so we should automatically call signature_help
 4363            self.show_signature_help(&ShowSignatureHelp, cx);
 4364        }
 4365
 4366        Some(cx.foreground_executor().spawn(async move {
 4367            apply_edits.await?;
 4368            Ok(())
 4369        }))
 4370    }
 4371
 4372    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4373        let mut context_menu = self.context_menu.write();
 4374        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4375            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4376                // Toggle if we're selecting the same one
 4377                *context_menu = None;
 4378                cx.notify();
 4379                return;
 4380            } else {
 4381                // Otherwise, clear it and start a new one
 4382                *context_menu = None;
 4383                cx.notify();
 4384            }
 4385        }
 4386        drop(context_menu);
 4387        let snapshot = self.snapshot(cx);
 4388        let deployed_from_indicator = action.deployed_from_indicator;
 4389        let mut task = self.code_actions_task.take();
 4390        let action = action.clone();
 4391        cx.spawn(|editor, mut cx| async move {
 4392            while let Some(prev_task) = task {
 4393                prev_task.await;
 4394                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4395            }
 4396
 4397            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4398                if editor.focus_handle.is_focused(cx) {
 4399                    let multibuffer_point = action
 4400                        .deployed_from_indicator
 4401                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4402                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4403                    let (buffer, buffer_row) = snapshot
 4404                        .buffer_snapshot
 4405                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4406                        .and_then(|(buffer_snapshot, range)| {
 4407                            editor
 4408                                .buffer
 4409                                .read(cx)
 4410                                .buffer(buffer_snapshot.remote_id())
 4411                                .map(|buffer| (buffer, range.start.row))
 4412                        })?;
 4413                    let (_, code_actions) = editor
 4414                        .available_code_actions
 4415                        .clone()
 4416                        .and_then(|(location, code_actions)| {
 4417                            let snapshot = location.buffer.read(cx).snapshot();
 4418                            let point_range = location.range.to_point(&snapshot);
 4419                            let point_range = point_range.start.row..=point_range.end.row;
 4420                            if point_range.contains(&buffer_row) {
 4421                                Some((location, code_actions))
 4422                            } else {
 4423                                None
 4424                            }
 4425                        })
 4426                        .unzip();
 4427                    let buffer_id = buffer.read(cx).remote_id();
 4428                    let tasks = editor
 4429                        .tasks
 4430                        .get(&(buffer_id, buffer_row))
 4431                        .map(|t| Arc::new(t.to_owned()));
 4432                    if tasks.is_none() && code_actions.is_none() {
 4433                        return None;
 4434                    }
 4435
 4436                    editor.completion_tasks.clear();
 4437                    editor.discard_inline_completion(false, cx);
 4438                    let task_context =
 4439                        tasks
 4440                            .as_ref()
 4441                            .zip(editor.project.clone())
 4442                            .map(|(tasks, project)| {
 4443                                let position = Point::new(buffer_row, tasks.column);
 4444                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4445                                let location = Location {
 4446                                    buffer: buffer.clone(),
 4447                                    range: range_start..range_start,
 4448                                };
 4449                                // Fill in the environmental variables from the tree-sitter captures
 4450                                let mut captured_task_variables = TaskVariables::default();
 4451                                for (capture_name, value) in tasks.extra_variables.clone() {
 4452                                    captured_task_variables.insert(
 4453                                        task::VariableName::Custom(capture_name.into()),
 4454                                        value.clone(),
 4455                                    );
 4456                                }
 4457                                project.update(cx, |project, cx| {
 4458                                    project.task_context_for_location(
 4459                                        captured_task_variables,
 4460                                        location,
 4461                                        cx,
 4462                                    )
 4463                                })
 4464                            });
 4465
 4466                    Some(cx.spawn(|editor, mut cx| async move {
 4467                        let task_context = match task_context {
 4468                            Some(task_context) => task_context.await,
 4469                            None => None,
 4470                        };
 4471                        let resolved_tasks =
 4472                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4473                                Arc::new(ResolvedTasks {
 4474                                    templates: tasks
 4475                                        .templates
 4476                                        .iter()
 4477                                        .filter_map(|(kind, template)| {
 4478                                            template
 4479                                                .resolve_task(&kind.to_id_base(), &task_context)
 4480                                                .map(|task| (kind.clone(), task))
 4481                                        })
 4482                                        .collect(),
 4483                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4484                                        multibuffer_point.row,
 4485                                        tasks.column,
 4486                                    )),
 4487                                })
 4488                            });
 4489                        let spawn_straight_away = resolved_tasks
 4490                            .as_ref()
 4491                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4492                            && code_actions
 4493                                .as_ref()
 4494                                .map_or(true, |actions| actions.is_empty());
 4495                        if let Some(task) = editor
 4496                            .update(&mut cx, |editor, cx| {
 4497                                *editor.context_menu.write() =
 4498                                    Some(ContextMenu::CodeActions(CodeActionsMenu {
 4499                                        buffer,
 4500                                        actions: CodeActionContents {
 4501                                            tasks: resolved_tasks,
 4502                                            actions: code_actions,
 4503                                        },
 4504                                        selected_item: Default::default(),
 4505                                        scroll_handle: UniformListScrollHandle::default(),
 4506                                        deployed_from_indicator,
 4507                                    }));
 4508                                if spawn_straight_away {
 4509                                    if let Some(task) = editor.confirm_code_action(
 4510                                        &ConfirmCodeAction { item_ix: Some(0) },
 4511                                        cx,
 4512                                    ) {
 4513                                        cx.notify();
 4514                                        return task;
 4515                                    }
 4516                                }
 4517                                cx.notify();
 4518                                Task::ready(Ok(()))
 4519                            })
 4520                            .ok()
 4521                        {
 4522                            task.await
 4523                        } else {
 4524                            Ok(())
 4525                        }
 4526                    }))
 4527                } else {
 4528                    Some(Task::ready(Ok(())))
 4529                }
 4530            })?;
 4531            if let Some(task) = spawned_test_task {
 4532                task.await?;
 4533            }
 4534
 4535            Ok::<_, anyhow::Error>(())
 4536        })
 4537        .detach_and_log_err(cx);
 4538    }
 4539
 4540    pub fn confirm_code_action(
 4541        &mut self,
 4542        action: &ConfirmCodeAction,
 4543        cx: &mut ViewContext<Self>,
 4544    ) -> Option<Task<Result<()>>> {
 4545        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4546            menu
 4547        } else {
 4548            return None;
 4549        };
 4550        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4551        let action = actions_menu.actions.get(action_ix)?;
 4552        let title = action.label();
 4553        let buffer = actions_menu.buffer;
 4554        let workspace = self.workspace()?;
 4555
 4556        match action {
 4557            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4558                workspace.update(cx, |workspace, cx| {
 4559                    workspace::tasks::schedule_resolved_task(
 4560                        workspace,
 4561                        task_source_kind,
 4562                        resolved_task,
 4563                        false,
 4564                        cx,
 4565                    );
 4566
 4567                    Some(Task::ready(Ok(())))
 4568                })
 4569            }
 4570            CodeActionsItem::CodeAction(action) => {
 4571                let apply_code_actions = workspace
 4572                    .read(cx)
 4573                    .project()
 4574                    .clone()
 4575                    .update(cx, |project, cx| {
 4576                        project.apply_code_action(buffer, action, true, cx)
 4577                    });
 4578                let workspace = workspace.downgrade();
 4579                Some(cx.spawn(|editor, cx| async move {
 4580                    let project_transaction = apply_code_actions.await?;
 4581                    Self::open_project_transaction(
 4582                        &editor,
 4583                        workspace,
 4584                        project_transaction,
 4585                        title,
 4586                        cx,
 4587                    )
 4588                    .await
 4589                }))
 4590            }
 4591        }
 4592    }
 4593
 4594    pub async fn open_project_transaction(
 4595        this: &WeakView<Editor>,
 4596        workspace: WeakView<Workspace>,
 4597        transaction: ProjectTransaction,
 4598        title: String,
 4599        mut cx: AsyncWindowContext,
 4600    ) -> Result<()> {
 4601        let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
 4602
 4603        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4604        cx.update(|cx| {
 4605            entries.sort_unstable_by_key(|(buffer, _)| {
 4606                buffer.read(cx).file().map(|f| f.path().clone())
 4607            });
 4608        })?;
 4609
 4610        // If the project transaction's edits are all contained within this editor, then
 4611        // avoid opening a new editor to display them.
 4612
 4613        if let Some((buffer, transaction)) = entries.first() {
 4614            if entries.len() == 1 {
 4615                let excerpt = this.update(&mut cx, |editor, cx| {
 4616                    editor
 4617                        .buffer()
 4618                        .read(cx)
 4619                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4620                })?;
 4621                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4622                    if excerpted_buffer == *buffer {
 4623                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4624                            let excerpt_range = excerpt_range.to_offset(buffer);
 4625                            buffer
 4626                                .edited_ranges_for_transaction::<usize>(transaction)
 4627                                .all(|range| {
 4628                                    excerpt_range.start <= range.start
 4629                                        && excerpt_range.end >= range.end
 4630                                })
 4631                        })?;
 4632
 4633                        if all_edits_within_excerpt {
 4634                            return Ok(());
 4635                        }
 4636                    }
 4637                }
 4638            }
 4639        } else {
 4640            return Ok(());
 4641        }
 4642
 4643        let mut ranges_to_highlight = Vec::new();
 4644        let excerpt_buffer = cx.new_model(|cx| {
 4645            let mut multibuffer =
 4646                MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
 4647            for (buffer_handle, transaction) in &entries {
 4648                let buffer = buffer_handle.read(cx);
 4649                ranges_to_highlight.extend(
 4650                    multibuffer.push_excerpts_with_context_lines(
 4651                        buffer_handle.clone(),
 4652                        buffer
 4653                            .edited_ranges_for_transaction::<usize>(transaction)
 4654                            .collect(),
 4655                        DEFAULT_MULTIBUFFER_CONTEXT,
 4656                        cx,
 4657                    ),
 4658                );
 4659            }
 4660            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4661            multibuffer
 4662        })?;
 4663
 4664        workspace.update(&mut cx, |workspace, cx| {
 4665            let project = workspace.project().clone();
 4666            let editor =
 4667                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4668            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4669            editor.update(cx, |editor, cx| {
 4670                editor.highlight_background::<Self>(
 4671                    &ranges_to_highlight,
 4672                    |theme| theme.editor_highlighted_line_background,
 4673                    cx,
 4674                );
 4675            });
 4676        })?;
 4677
 4678        Ok(())
 4679    }
 4680
 4681    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4682        let project = self.project.clone()?;
 4683        let buffer = self.buffer.read(cx);
 4684        let newest_selection = self.selections.newest_anchor().clone();
 4685        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4686        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4687        if start_buffer != end_buffer {
 4688            return None;
 4689        }
 4690
 4691        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4692            cx.background_executor()
 4693                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4694                .await;
 4695
 4696            let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
 4697                project.code_actions(&start_buffer, start..end, cx)
 4698            }) {
 4699                code_actions.await
 4700            } else {
 4701                Vec::new()
 4702            };
 4703
 4704            this.update(&mut cx, |this, cx| {
 4705                this.available_code_actions = if actions.is_empty() {
 4706                    None
 4707                } else {
 4708                    Some((
 4709                        Location {
 4710                            buffer: start_buffer,
 4711                            range: start..end,
 4712                        },
 4713                        actions.into(),
 4714                    ))
 4715                };
 4716                cx.notify();
 4717            })
 4718            .log_err();
 4719        }));
 4720        None
 4721    }
 4722
 4723    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4724        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4725            self.show_git_blame_inline = false;
 4726
 4727            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4728                cx.background_executor().timer(delay).await;
 4729
 4730                this.update(&mut cx, |this, cx| {
 4731                    this.show_git_blame_inline = true;
 4732                    cx.notify();
 4733                })
 4734                .log_err();
 4735            }));
 4736        }
 4737    }
 4738
 4739    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4740        if self.pending_rename.is_some() {
 4741            return None;
 4742        }
 4743
 4744        let project = self.project.clone()?;
 4745        let buffer = self.buffer.read(cx);
 4746        let newest_selection = self.selections.newest_anchor().clone();
 4747        let cursor_position = newest_selection.head();
 4748        let (cursor_buffer, cursor_buffer_position) =
 4749            buffer.text_anchor_for_position(cursor_position, cx)?;
 4750        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4751        if cursor_buffer != tail_buffer {
 4752            return None;
 4753        }
 4754
 4755        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4756            cx.background_executor()
 4757                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 4758                .await;
 4759
 4760            let highlights = if let Some(highlights) = project
 4761                .update(&mut cx, |project, cx| {
 4762                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4763                })
 4764                .log_err()
 4765            {
 4766                highlights.await.log_err()
 4767            } else {
 4768                None
 4769            };
 4770
 4771            if let Some(highlights) = highlights {
 4772                this.update(&mut cx, |this, cx| {
 4773                    if this.pending_rename.is_some() {
 4774                        return;
 4775                    }
 4776
 4777                    let buffer_id = cursor_position.buffer_id;
 4778                    let buffer = this.buffer.read(cx);
 4779                    if !buffer
 4780                        .text_anchor_for_position(cursor_position, cx)
 4781                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4782                    {
 4783                        return;
 4784                    }
 4785
 4786                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4787                    let mut write_ranges = Vec::new();
 4788                    let mut read_ranges = Vec::new();
 4789                    for highlight in highlights {
 4790                        for (excerpt_id, excerpt_range) in
 4791                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4792                        {
 4793                            let start = highlight
 4794                                .range
 4795                                .start
 4796                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4797                            let end = highlight
 4798                                .range
 4799                                .end
 4800                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4801                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4802                                continue;
 4803                            }
 4804
 4805                            let range = Anchor {
 4806                                buffer_id,
 4807                                excerpt_id: excerpt_id,
 4808                                text_anchor: start,
 4809                            }..Anchor {
 4810                                buffer_id,
 4811                                excerpt_id,
 4812                                text_anchor: end,
 4813                            };
 4814                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4815                                write_ranges.push(range);
 4816                            } else {
 4817                                read_ranges.push(range);
 4818                            }
 4819                        }
 4820                    }
 4821
 4822                    this.highlight_background::<DocumentHighlightRead>(
 4823                        &read_ranges,
 4824                        |theme| theme.editor_document_highlight_read_background,
 4825                        cx,
 4826                    );
 4827                    this.highlight_background::<DocumentHighlightWrite>(
 4828                        &write_ranges,
 4829                        |theme| theme.editor_document_highlight_write_background,
 4830                        cx,
 4831                    );
 4832                    cx.notify();
 4833                })
 4834                .log_err();
 4835            }
 4836        }));
 4837        None
 4838    }
 4839
 4840    fn refresh_inline_completion(
 4841        &mut self,
 4842        debounce: bool,
 4843        cx: &mut ViewContext<Self>,
 4844    ) -> Option<()> {
 4845        let provider = self.inline_completion_provider()?;
 4846        let cursor = self.selections.newest_anchor().head();
 4847        let (buffer, cursor_buffer_position) =
 4848            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4849        if !self.show_inline_completions
 4850            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4851        {
 4852            self.discard_inline_completion(false, cx);
 4853            return None;
 4854        }
 4855
 4856        self.update_visible_inline_completion(cx);
 4857        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4858        Some(())
 4859    }
 4860
 4861    fn cycle_inline_completion(
 4862        &mut self,
 4863        direction: Direction,
 4864        cx: &mut ViewContext<Self>,
 4865    ) -> Option<()> {
 4866        let provider = self.inline_completion_provider()?;
 4867        let cursor = self.selections.newest_anchor().head();
 4868        let (buffer, cursor_buffer_position) =
 4869            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4870        if !self.show_inline_completions
 4871            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4872        {
 4873            return None;
 4874        }
 4875
 4876        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4877        self.update_visible_inline_completion(cx);
 4878
 4879        Some(())
 4880    }
 4881
 4882    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4883        if !self.has_active_inline_completion(cx) {
 4884            self.refresh_inline_completion(false, cx);
 4885            return;
 4886        }
 4887
 4888        self.update_visible_inline_completion(cx);
 4889    }
 4890
 4891    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4892        self.show_cursor_names(cx);
 4893    }
 4894
 4895    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4896        self.show_cursor_names = true;
 4897        cx.notify();
 4898        cx.spawn(|this, mut cx| async move {
 4899            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4900            this.update(&mut cx, |this, cx| {
 4901                this.show_cursor_names = false;
 4902                cx.notify()
 4903            })
 4904            .ok()
 4905        })
 4906        .detach();
 4907    }
 4908
 4909    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4910        if self.has_active_inline_completion(cx) {
 4911            self.cycle_inline_completion(Direction::Next, cx);
 4912        } else {
 4913            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4914            if is_copilot_disabled {
 4915                cx.propagate();
 4916            }
 4917        }
 4918    }
 4919
 4920    pub fn previous_inline_completion(
 4921        &mut self,
 4922        _: &PreviousInlineCompletion,
 4923        cx: &mut ViewContext<Self>,
 4924    ) {
 4925        if self.has_active_inline_completion(cx) {
 4926            self.cycle_inline_completion(Direction::Prev, cx);
 4927        } else {
 4928            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4929            if is_copilot_disabled {
 4930                cx.propagate();
 4931            }
 4932        }
 4933    }
 4934
 4935    pub fn accept_inline_completion(
 4936        &mut self,
 4937        _: &AcceptInlineCompletion,
 4938        cx: &mut ViewContext<Self>,
 4939    ) {
 4940        let Some(completion) = self.take_active_inline_completion(cx) else {
 4941            return;
 4942        };
 4943        if let Some(provider) = self.inline_completion_provider() {
 4944            provider.accept(cx);
 4945        }
 4946
 4947        cx.emit(EditorEvent::InputHandled {
 4948            utf16_range_to_replace: None,
 4949            text: completion.text.to_string().into(),
 4950        });
 4951        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 4952        self.refresh_inline_completion(true, cx);
 4953        cx.notify();
 4954    }
 4955
 4956    pub fn accept_partial_inline_completion(
 4957        &mut self,
 4958        _: &AcceptPartialInlineCompletion,
 4959        cx: &mut ViewContext<Self>,
 4960    ) {
 4961        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 4962            if let Some(completion) = self.take_active_inline_completion(cx) {
 4963                let mut partial_completion = completion
 4964                    .text
 4965                    .chars()
 4966                    .by_ref()
 4967                    .take_while(|c| c.is_alphabetic())
 4968                    .collect::<String>();
 4969                if partial_completion.is_empty() {
 4970                    partial_completion = completion
 4971                        .text
 4972                        .chars()
 4973                        .by_ref()
 4974                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4975                        .collect::<String>();
 4976                }
 4977
 4978                cx.emit(EditorEvent::InputHandled {
 4979                    utf16_range_to_replace: None,
 4980                    text: partial_completion.clone().into(),
 4981                });
 4982                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4983                self.refresh_inline_completion(true, cx);
 4984                cx.notify();
 4985            }
 4986        }
 4987    }
 4988
 4989    fn discard_inline_completion(
 4990        &mut self,
 4991        should_report_inline_completion_event: bool,
 4992        cx: &mut ViewContext<Self>,
 4993    ) -> bool {
 4994        if let Some(provider) = self.inline_completion_provider() {
 4995            provider.discard(should_report_inline_completion_event, cx);
 4996        }
 4997
 4998        self.take_active_inline_completion(cx).is_some()
 4999    }
 5000
 5001    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5002        if let Some(completion) = self.active_inline_completion.as_ref() {
 5003            let buffer = self.buffer.read(cx).read(cx);
 5004            completion.position.is_valid(&buffer)
 5005        } else {
 5006            false
 5007        }
 5008    }
 5009
 5010    fn take_active_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
 5011        let completion = self.active_inline_completion.take()?;
 5012        self.display_map.update(cx, |map, cx| {
 5013            map.splice_inlays(vec![completion.id], Default::default(), cx);
 5014        });
 5015        let buffer = self.buffer.read(cx).read(cx);
 5016
 5017        if completion.position.is_valid(&buffer) {
 5018            Some(completion)
 5019        } else {
 5020            None
 5021        }
 5022    }
 5023
 5024    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5025        let selection = self.selections.newest_anchor();
 5026        let cursor = selection.head();
 5027
 5028        if self.context_menu.read().is_none()
 5029            && self.completion_tasks.is_empty()
 5030            && selection.start == selection.end
 5031        {
 5032            if let Some(provider) = self.inline_completion_provider() {
 5033                if let Some((buffer, cursor_buffer_position)) =
 5034                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5035                {
 5036                    if let Some(text) =
 5037                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5038                    {
 5039                        let text = Rope::from(text);
 5040                        let mut to_remove = Vec::new();
 5041                        if let Some(completion) = self.active_inline_completion.take() {
 5042                            to_remove.push(completion.id);
 5043                        }
 5044
 5045                        let completion_inlay =
 5046                            Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
 5047                        self.active_inline_completion = Some(completion_inlay.clone());
 5048                        self.display_map.update(cx, move |map, cx| {
 5049                            map.splice_inlays(to_remove, vec![completion_inlay], cx)
 5050                        });
 5051                        cx.notify();
 5052                        return;
 5053                    }
 5054                }
 5055            }
 5056        }
 5057
 5058        self.discard_inline_completion(false, cx);
 5059    }
 5060
 5061    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5062        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5063    }
 5064
 5065    fn render_code_actions_indicator(
 5066        &self,
 5067        _style: &EditorStyle,
 5068        row: DisplayRow,
 5069        is_active: bool,
 5070        cx: &mut ViewContext<Self>,
 5071    ) -> Option<IconButton> {
 5072        if self.available_code_actions.is_some() {
 5073            Some(
 5074                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5075                    .shape(ui::IconButtonShape::Square)
 5076                    .icon_size(IconSize::XSmall)
 5077                    .icon_color(Color::Muted)
 5078                    .selected(is_active)
 5079                    .on_click(cx.listener(move |editor, _e, cx| {
 5080                        editor.focus(cx);
 5081                        editor.toggle_code_actions(
 5082                            &ToggleCodeActions {
 5083                                deployed_from_indicator: Some(row),
 5084                            },
 5085                            cx,
 5086                        );
 5087                    })),
 5088            )
 5089        } else {
 5090            None
 5091        }
 5092    }
 5093
 5094    fn clear_tasks(&mut self) {
 5095        self.tasks.clear()
 5096    }
 5097
 5098    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5099        if let Some(_) = self.tasks.insert(key, value) {
 5100            // This case should hopefully be rare, but just in case...
 5101            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5102        }
 5103    }
 5104
 5105    fn render_run_indicator(
 5106        &self,
 5107        _style: &EditorStyle,
 5108        is_active: bool,
 5109        row: DisplayRow,
 5110        cx: &mut ViewContext<Self>,
 5111    ) -> IconButton {
 5112        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5113            .shape(ui::IconButtonShape::Square)
 5114            .icon_size(IconSize::XSmall)
 5115            .icon_color(Color::Muted)
 5116            .selected(is_active)
 5117            .on_click(cx.listener(move |editor, _e, cx| {
 5118                editor.focus(cx);
 5119                editor.toggle_code_actions(
 5120                    &ToggleCodeActions {
 5121                        deployed_from_indicator: Some(row),
 5122                    },
 5123                    cx,
 5124                );
 5125            }))
 5126    }
 5127
 5128    pub fn context_menu_visible(&self) -> bool {
 5129        self.context_menu
 5130            .read()
 5131            .as_ref()
 5132            .map_or(false, |menu| menu.visible())
 5133    }
 5134
 5135    fn render_context_menu(
 5136        &self,
 5137        cursor_position: DisplayPoint,
 5138        style: &EditorStyle,
 5139        max_height: Pixels,
 5140        cx: &mut ViewContext<Editor>,
 5141    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5142        self.context_menu.read().as_ref().map(|menu| {
 5143            menu.render(
 5144                cursor_position,
 5145                style,
 5146                max_height,
 5147                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5148                cx,
 5149            )
 5150        })
 5151    }
 5152
 5153    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5154        cx.notify();
 5155        self.completion_tasks.clear();
 5156        let context_menu = self.context_menu.write().take();
 5157        if context_menu.is_some() {
 5158            self.update_visible_inline_completion(cx);
 5159        }
 5160        context_menu
 5161    }
 5162
 5163    pub fn insert_snippet(
 5164        &mut self,
 5165        insertion_ranges: &[Range<usize>],
 5166        snippet: Snippet,
 5167        cx: &mut ViewContext<Self>,
 5168    ) -> Result<()> {
 5169        struct Tabstop<T> {
 5170            is_end_tabstop: bool,
 5171            ranges: Vec<Range<T>>,
 5172        }
 5173
 5174        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5175            let snippet_text: Arc<str> = snippet.text.clone().into();
 5176            buffer.edit(
 5177                insertion_ranges
 5178                    .iter()
 5179                    .cloned()
 5180                    .map(|range| (range, snippet_text.clone())),
 5181                Some(AutoindentMode::EachLine),
 5182                cx,
 5183            );
 5184
 5185            let snapshot = &*buffer.read(cx);
 5186            let snippet = &snippet;
 5187            snippet
 5188                .tabstops
 5189                .iter()
 5190                .map(|tabstop| {
 5191                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5192                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5193                    });
 5194                    let mut tabstop_ranges = tabstop
 5195                        .iter()
 5196                        .flat_map(|tabstop_range| {
 5197                            let mut delta = 0_isize;
 5198                            insertion_ranges.iter().map(move |insertion_range| {
 5199                                let insertion_start = insertion_range.start as isize + delta;
 5200                                delta +=
 5201                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5202
 5203                                let start = ((insertion_start + tabstop_range.start) as usize)
 5204                                    .min(snapshot.len());
 5205                                let end = ((insertion_start + tabstop_range.end) as usize)
 5206                                    .min(snapshot.len());
 5207                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5208                            })
 5209                        })
 5210                        .collect::<Vec<_>>();
 5211                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5212
 5213                    Tabstop {
 5214                        is_end_tabstop,
 5215                        ranges: tabstop_ranges,
 5216                    }
 5217                })
 5218                .collect::<Vec<_>>()
 5219        });
 5220        if let Some(tabstop) = tabstops.first() {
 5221            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5222                s.select_ranges(tabstop.ranges.iter().cloned());
 5223            });
 5224
 5225            // If we're already at the last tabstop and it's at the end of the snippet,
 5226            // we're done, we don't need to keep the state around.
 5227            if !tabstop.is_end_tabstop {
 5228                let ranges = tabstops
 5229                    .into_iter()
 5230                    .map(|tabstop| tabstop.ranges)
 5231                    .collect::<Vec<_>>();
 5232                self.snippet_stack.push(SnippetState {
 5233                    active_index: 0,
 5234                    ranges,
 5235                });
 5236            }
 5237
 5238            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5239            if self.autoclose_regions.is_empty() {
 5240                let snapshot = self.buffer.read(cx).snapshot(cx);
 5241                for selection in &mut self.selections.all::<Point>(cx) {
 5242                    let selection_head = selection.head();
 5243                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5244                        continue;
 5245                    };
 5246
 5247                    let mut bracket_pair = None;
 5248                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5249                    let prev_chars = snapshot
 5250                        .reversed_chars_at(selection_head)
 5251                        .collect::<String>();
 5252                    for (pair, enabled) in scope.brackets() {
 5253                        if enabled
 5254                            && pair.close
 5255                            && prev_chars.starts_with(pair.start.as_str())
 5256                            && next_chars.starts_with(pair.end.as_str())
 5257                        {
 5258                            bracket_pair = Some(pair.clone());
 5259                            break;
 5260                        }
 5261                    }
 5262                    if let Some(pair) = bracket_pair {
 5263                        let start = snapshot.anchor_after(selection_head);
 5264                        let end = snapshot.anchor_after(selection_head);
 5265                        self.autoclose_regions.push(AutocloseRegion {
 5266                            selection_id: selection.id,
 5267                            range: start..end,
 5268                            pair,
 5269                        });
 5270                    }
 5271                }
 5272            }
 5273        }
 5274        Ok(())
 5275    }
 5276
 5277    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5278        self.move_to_snippet_tabstop(Bias::Right, cx)
 5279    }
 5280
 5281    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5282        self.move_to_snippet_tabstop(Bias::Left, cx)
 5283    }
 5284
 5285    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5286        if let Some(mut snippet) = self.snippet_stack.pop() {
 5287            match bias {
 5288                Bias::Left => {
 5289                    if snippet.active_index > 0 {
 5290                        snippet.active_index -= 1;
 5291                    } else {
 5292                        self.snippet_stack.push(snippet);
 5293                        return false;
 5294                    }
 5295                }
 5296                Bias::Right => {
 5297                    if snippet.active_index + 1 < snippet.ranges.len() {
 5298                        snippet.active_index += 1;
 5299                    } else {
 5300                        self.snippet_stack.push(snippet);
 5301                        return false;
 5302                    }
 5303                }
 5304            }
 5305            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5306                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5307                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5308                });
 5309                // If snippet state is not at the last tabstop, push it back on the stack
 5310                if snippet.active_index + 1 < snippet.ranges.len() {
 5311                    self.snippet_stack.push(snippet);
 5312                }
 5313                return true;
 5314            }
 5315        }
 5316
 5317        false
 5318    }
 5319
 5320    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5321        self.transact(cx, |this, cx| {
 5322            this.select_all(&SelectAll, cx);
 5323            this.insert("", cx);
 5324        });
 5325    }
 5326
 5327    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5328        self.transact(cx, |this, cx| {
 5329            this.select_autoclose_pair(cx);
 5330            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5331            if !this.linked_edit_ranges.is_empty() {
 5332                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5333                let snapshot = this.buffer.read(cx).snapshot(cx);
 5334
 5335                for selection in selections.iter() {
 5336                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5337                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5338                    if selection_start.buffer_id != selection_end.buffer_id {
 5339                        continue;
 5340                    }
 5341                    if let Some(ranges) =
 5342                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5343                    {
 5344                        for (buffer, entries) in ranges {
 5345                            linked_ranges.entry(buffer).or_default().extend(entries);
 5346                        }
 5347                    }
 5348                }
 5349            }
 5350
 5351            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5352            if !this.selections.line_mode {
 5353                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5354                for selection in &mut selections {
 5355                    if selection.is_empty() {
 5356                        let old_head = selection.head();
 5357                        let mut new_head =
 5358                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5359                                .to_point(&display_map);
 5360                        if let Some((buffer, line_buffer_range)) = display_map
 5361                            .buffer_snapshot
 5362                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5363                        {
 5364                            let indent_size =
 5365                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5366                            let indent_len = match indent_size.kind {
 5367                                IndentKind::Space => {
 5368                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5369                                }
 5370                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5371                            };
 5372                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5373                                let indent_len = indent_len.get();
 5374                                new_head = cmp::min(
 5375                                    new_head,
 5376                                    MultiBufferPoint::new(
 5377                                        old_head.row,
 5378                                        ((old_head.column - 1) / indent_len) * indent_len,
 5379                                    ),
 5380                                );
 5381                            }
 5382                        }
 5383
 5384                        selection.set_head(new_head, SelectionGoal::None);
 5385                    }
 5386                }
 5387            }
 5388
 5389            this.signature_help_state.set_backspace_pressed(true);
 5390            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5391            this.insert("", cx);
 5392            let empty_str: Arc<str> = Arc::from("");
 5393            for (buffer, edits) in linked_ranges {
 5394                let snapshot = buffer.read(cx).snapshot();
 5395                use text::ToPoint as TP;
 5396
 5397                let edits = edits
 5398                    .into_iter()
 5399                    .map(|range| {
 5400                        let end_point = TP::to_point(&range.end, &snapshot);
 5401                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5402
 5403                        if end_point == start_point {
 5404                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5405                                .saturating_sub(1);
 5406                            start_point = TP::to_point(&offset, &snapshot);
 5407                        };
 5408
 5409                        (start_point..end_point, empty_str.clone())
 5410                    })
 5411                    .sorted_by_key(|(range, _)| range.start)
 5412                    .collect::<Vec<_>>();
 5413                buffer.update(cx, |this, cx| {
 5414                    this.edit(edits, None, cx);
 5415                })
 5416            }
 5417            this.refresh_inline_completion(true, cx);
 5418            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5419        });
 5420    }
 5421
 5422    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5423        self.transact(cx, |this, cx| {
 5424            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5425                let line_mode = s.line_mode;
 5426                s.move_with(|map, selection| {
 5427                    if selection.is_empty() && !line_mode {
 5428                        let cursor = movement::right(map, selection.head());
 5429                        selection.end = cursor;
 5430                        selection.reversed = true;
 5431                        selection.goal = SelectionGoal::None;
 5432                    }
 5433                })
 5434            });
 5435            this.insert("", cx);
 5436            this.refresh_inline_completion(true, cx);
 5437        });
 5438    }
 5439
 5440    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5441        if self.move_to_prev_snippet_tabstop(cx) {
 5442            return;
 5443        }
 5444
 5445        self.outdent(&Outdent, cx);
 5446    }
 5447
 5448    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5449        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5450            return;
 5451        }
 5452
 5453        let mut selections = self.selections.all_adjusted(cx);
 5454        let buffer = self.buffer.read(cx);
 5455        let snapshot = buffer.snapshot(cx);
 5456        let rows_iter = selections.iter().map(|s| s.head().row);
 5457        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5458
 5459        let mut edits = Vec::new();
 5460        let mut prev_edited_row = 0;
 5461        let mut row_delta = 0;
 5462        for selection in &mut selections {
 5463            if selection.start.row != prev_edited_row {
 5464                row_delta = 0;
 5465            }
 5466            prev_edited_row = selection.end.row;
 5467
 5468            // If the selection is non-empty, then increase the indentation of the selected lines.
 5469            if !selection.is_empty() {
 5470                row_delta =
 5471                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5472                continue;
 5473            }
 5474
 5475            // If the selection is empty and the cursor is in the leading whitespace before the
 5476            // suggested indentation, then auto-indent the line.
 5477            let cursor = selection.head();
 5478            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5479            if let Some(suggested_indent) =
 5480                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5481            {
 5482                if cursor.column < suggested_indent.len
 5483                    && cursor.column <= current_indent.len
 5484                    && current_indent.len <= suggested_indent.len
 5485                {
 5486                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5487                    selection.end = selection.start;
 5488                    if row_delta == 0 {
 5489                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5490                            cursor.row,
 5491                            current_indent,
 5492                            suggested_indent,
 5493                        ));
 5494                        row_delta = suggested_indent.len - current_indent.len;
 5495                    }
 5496                    continue;
 5497                }
 5498            }
 5499
 5500            // Otherwise, insert a hard or soft tab.
 5501            let settings = buffer.settings_at(cursor, cx);
 5502            let tab_size = if settings.hard_tabs {
 5503                IndentSize::tab()
 5504            } else {
 5505                let tab_size = settings.tab_size.get();
 5506                let char_column = snapshot
 5507                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5508                    .flat_map(str::chars)
 5509                    .count()
 5510                    + row_delta as usize;
 5511                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5512                IndentSize::spaces(chars_to_next_tab_stop)
 5513            };
 5514            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5515            selection.end = selection.start;
 5516            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5517            row_delta += tab_size.len;
 5518        }
 5519
 5520        self.transact(cx, |this, cx| {
 5521            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5522            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5523            this.refresh_inline_completion(true, cx);
 5524        });
 5525    }
 5526
 5527    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5528        if self.read_only(cx) {
 5529            return;
 5530        }
 5531        let mut selections = self.selections.all::<Point>(cx);
 5532        let mut prev_edited_row = 0;
 5533        let mut row_delta = 0;
 5534        let mut edits = Vec::new();
 5535        let buffer = self.buffer.read(cx);
 5536        let snapshot = buffer.snapshot(cx);
 5537        for selection in &mut selections {
 5538            if selection.start.row != prev_edited_row {
 5539                row_delta = 0;
 5540            }
 5541            prev_edited_row = selection.end.row;
 5542
 5543            row_delta =
 5544                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5545        }
 5546
 5547        self.transact(cx, |this, cx| {
 5548            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5549            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5550        });
 5551    }
 5552
 5553    fn indent_selection(
 5554        buffer: &MultiBuffer,
 5555        snapshot: &MultiBufferSnapshot,
 5556        selection: &mut Selection<Point>,
 5557        edits: &mut Vec<(Range<Point>, String)>,
 5558        delta_for_start_row: u32,
 5559        cx: &AppContext,
 5560    ) -> u32 {
 5561        let settings = buffer.settings_at(selection.start, cx);
 5562        let tab_size = settings.tab_size.get();
 5563        let indent_kind = if settings.hard_tabs {
 5564            IndentKind::Tab
 5565        } else {
 5566            IndentKind::Space
 5567        };
 5568        let mut start_row = selection.start.row;
 5569        let mut end_row = selection.end.row + 1;
 5570
 5571        // If a selection ends at the beginning of a line, don't indent
 5572        // that last line.
 5573        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5574            end_row -= 1;
 5575        }
 5576
 5577        // Avoid re-indenting a row that has already been indented by a
 5578        // previous selection, but still update this selection's column
 5579        // to reflect that indentation.
 5580        if delta_for_start_row > 0 {
 5581            start_row += 1;
 5582            selection.start.column += delta_for_start_row;
 5583            if selection.end.row == selection.start.row {
 5584                selection.end.column += delta_for_start_row;
 5585            }
 5586        }
 5587
 5588        let mut delta_for_end_row = 0;
 5589        let has_multiple_rows = start_row + 1 != end_row;
 5590        for row in start_row..end_row {
 5591            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5592            let indent_delta = match (current_indent.kind, indent_kind) {
 5593                (IndentKind::Space, IndentKind::Space) => {
 5594                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5595                    IndentSize::spaces(columns_to_next_tab_stop)
 5596                }
 5597                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5598                (_, IndentKind::Tab) => IndentSize::tab(),
 5599            };
 5600
 5601            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5602                0
 5603            } else {
 5604                selection.start.column
 5605            };
 5606            let row_start = Point::new(row, start);
 5607            edits.push((
 5608                row_start..row_start,
 5609                indent_delta.chars().collect::<String>(),
 5610            ));
 5611
 5612            // Update this selection's endpoints to reflect the indentation.
 5613            if row == selection.start.row {
 5614                selection.start.column += indent_delta.len;
 5615            }
 5616            if row == selection.end.row {
 5617                selection.end.column += indent_delta.len;
 5618                delta_for_end_row = indent_delta.len;
 5619            }
 5620        }
 5621
 5622        if selection.start.row == selection.end.row {
 5623            delta_for_start_row + delta_for_end_row
 5624        } else {
 5625            delta_for_end_row
 5626        }
 5627    }
 5628
 5629    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5630        if self.read_only(cx) {
 5631            return;
 5632        }
 5633        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5634        let selections = self.selections.all::<Point>(cx);
 5635        let mut deletion_ranges = Vec::new();
 5636        let mut last_outdent = None;
 5637        {
 5638            let buffer = self.buffer.read(cx);
 5639            let snapshot = buffer.snapshot(cx);
 5640            for selection in &selections {
 5641                let settings = buffer.settings_at(selection.start, cx);
 5642                let tab_size = settings.tab_size.get();
 5643                let mut rows = selection.spanned_rows(false, &display_map);
 5644
 5645                // Avoid re-outdenting a row that has already been outdented by a
 5646                // previous selection.
 5647                if let Some(last_row) = last_outdent {
 5648                    if last_row == rows.start {
 5649                        rows.start = rows.start.next_row();
 5650                    }
 5651                }
 5652                let has_multiple_rows = rows.len() > 1;
 5653                for row in rows.iter_rows() {
 5654                    let indent_size = snapshot.indent_size_for_line(row);
 5655                    if indent_size.len > 0 {
 5656                        let deletion_len = match indent_size.kind {
 5657                            IndentKind::Space => {
 5658                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5659                                if columns_to_prev_tab_stop == 0 {
 5660                                    tab_size
 5661                                } else {
 5662                                    columns_to_prev_tab_stop
 5663                                }
 5664                            }
 5665                            IndentKind::Tab => 1,
 5666                        };
 5667                        let start = if has_multiple_rows
 5668                            || deletion_len > selection.start.column
 5669                            || indent_size.len < selection.start.column
 5670                        {
 5671                            0
 5672                        } else {
 5673                            selection.start.column - deletion_len
 5674                        };
 5675                        deletion_ranges.push(
 5676                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5677                        );
 5678                        last_outdent = Some(row);
 5679                    }
 5680                }
 5681            }
 5682        }
 5683
 5684        self.transact(cx, |this, cx| {
 5685            this.buffer.update(cx, |buffer, cx| {
 5686                let empty_str: Arc<str> = "".into();
 5687                buffer.edit(
 5688                    deletion_ranges
 5689                        .into_iter()
 5690                        .map(|range| (range, empty_str.clone())),
 5691                    None,
 5692                    cx,
 5693                );
 5694            });
 5695            let selections = this.selections.all::<usize>(cx);
 5696            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5697        });
 5698    }
 5699
 5700    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5701        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5702        let selections = self.selections.all::<Point>(cx);
 5703
 5704        let mut new_cursors = Vec::new();
 5705        let mut edit_ranges = Vec::new();
 5706        let mut selections = selections.iter().peekable();
 5707        while let Some(selection) = selections.next() {
 5708            let mut rows = selection.spanned_rows(false, &display_map);
 5709            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5710
 5711            // Accumulate contiguous regions of rows that we want to delete.
 5712            while let Some(next_selection) = selections.peek() {
 5713                let next_rows = next_selection.spanned_rows(false, &display_map);
 5714                if next_rows.start <= rows.end {
 5715                    rows.end = next_rows.end;
 5716                    selections.next().unwrap();
 5717                } else {
 5718                    break;
 5719                }
 5720            }
 5721
 5722            let buffer = &display_map.buffer_snapshot;
 5723            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5724            let edit_end;
 5725            let cursor_buffer_row;
 5726            if buffer.max_point().row >= rows.end.0 {
 5727                // If there's a line after the range, delete the \n from the end of the row range
 5728                // and position the cursor on the next line.
 5729                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5730                cursor_buffer_row = rows.end;
 5731            } else {
 5732                // If there isn't a line after the range, delete the \n from the line before the
 5733                // start of the row range and position the cursor there.
 5734                edit_start = edit_start.saturating_sub(1);
 5735                edit_end = buffer.len();
 5736                cursor_buffer_row = rows.start.previous_row();
 5737            }
 5738
 5739            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5740            *cursor.column_mut() =
 5741                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5742
 5743            new_cursors.push((
 5744                selection.id,
 5745                buffer.anchor_after(cursor.to_point(&display_map)),
 5746            ));
 5747            edit_ranges.push(edit_start..edit_end);
 5748        }
 5749
 5750        self.transact(cx, |this, cx| {
 5751            let buffer = this.buffer.update(cx, |buffer, cx| {
 5752                let empty_str: Arc<str> = "".into();
 5753                buffer.edit(
 5754                    edit_ranges
 5755                        .into_iter()
 5756                        .map(|range| (range, empty_str.clone())),
 5757                    None,
 5758                    cx,
 5759                );
 5760                buffer.snapshot(cx)
 5761            });
 5762            let new_selections = new_cursors
 5763                .into_iter()
 5764                .map(|(id, cursor)| {
 5765                    let cursor = cursor.to_point(&buffer);
 5766                    Selection {
 5767                        id,
 5768                        start: cursor,
 5769                        end: cursor,
 5770                        reversed: false,
 5771                        goal: SelectionGoal::None,
 5772                    }
 5773                })
 5774                .collect();
 5775
 5776            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5777                s.select(new_selections);
 5778            });
 5779        });
 5780    }
 5781
 5782    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5783        if self.read_only(cx) {
 5784            return;
 5785        }
 5786        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5787        for selection in self.selections.all::<Point>(cx) {
 5788            let start = MultiBufferRow(selection.start.row);
 5789            let end = if selection.start.row == selection.end.row {
 5790                MultiBufferRow(selection.start.row + 1)
 5791            } else {
 5792                MultiBufferRow(selection.end.row)
 5793            };
 5794
 5795            if let Some(last_row_range) = row_ranges.last_mut() {
 5796                if start <= last_row_range.end {
 5797                    last_row_range.end = end;
 5798                    continue;
 5799                }
 5800            }
 5801            row_ranges.push(start..end);
 5802        }
 5803
 5804        let snapshot = self.buffer.read(cx).snapshot(cx);
 5805        let mut cursor_positions = Vec::new();
 5806        for row_range in &row_ranges {
 5807            let anchor = snapshot.anchor_before(Point::new(
 5808                row_range.end.previous_row().0,
 5809                snapshot.line_len(row_range.end.previous_row()),
 5810            ));
 5811            cursor_positions.push(anchor..anchor);
 5812        }
 5813
 5814        self.transact(cx, |this, cx| {
 5815            for row_range in row_ranges.into_iter().rev() {
 5816                for row in row_range.iter_rows().rev() {
 5817                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5818                    let next_line_row = row.next_row();
 5819                    let indent = snapshot.indent_size_for_line(next_line_row);
 5820                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5821
 5822                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5823                        " "
 5824                    } else {
 5825                        ""
 5826                    };
 5827
 5828                    this.buffer.update(cx, |buffer, cx| {
 5829                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5830                    });
 5831                }
 5832            }
 5833
 5834            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5835                s.select_anchor_ranges(cursor_positions)
 5836            });
 5837        });
 5838    }
 5839
 5840    pub fn sort_lines_case_sensitive(
 5841        &mut self,
 5842        _: &SortLinesCaseSensitive,
 5843        cx: &mut ViewContext<Self>,
 5844    ) {
 5845        self.manipulate_lines(cx, |lines| lines.sort())
 5846    }
 5847
 5848    pub fn sort_lines_case_insensitive(
 5849        &mut self,
 5850        _: &SortLinesCaseInsensitive,
 5851        cx: &mut ViewContext<Self>,
 5852    ) {
 5853        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5854    }
 5855
 5856    pub fn unique_lines_case_insensitive(
 5857        &mut self,
 5858        _: &UniqueLinesCaseInsensitive,
 5859        cx: &mut ViewContext<Self>,
 5860    ) {
 5861        self.manipulate_lines(cx, |lines| {
 5862            let mut seen = HashSet::default();
 5863            lines.retain(|line| seen.insert(line.to_lowercase()));
 5864        })
 5865    }
 5866
 5867    pub fn unique_lines_case_sensitive(
 5868        &mut self,
 5869        _: &UniqueLinesCaseSensitive,
 5870        cx: &mut ViewContext<Self>,
 5871    ) {
 5872        self.manipulate_lines(cx, |lines| {
 5873            let mut seen = HashSet::default();
 5874            lines.retain(|line| seen.insert(*line));
 5875        })
 5876    }
 5877
 5878    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5879        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 5880        if !revert_changes.is_empty() {
 5881            self.transact(cx, |editor, cx| {
 5882                editor.buffer().update(cx, |multi_buffer, cx| {
 5883                    for (buffer_id, changes) in revert_changes {
 5884                        if let Some(buffer) = multi_buffer.buffer(buffer_id) {
 5885                            buffer.update(cx, |buffer, cx| {
 5886                                buffer.edit(
 5887                                    changes.into_iter().map(|(range, text)| {
 5888                                        (range, text.to_string().map(Arc::<str>::from))
 5889                                    }),
 5890                                    None,
 5891                                    cx,
 5892                                );
 5893                            });
 5894                        }
 5895                    }
 5896                });
 5897                editor.change_selections(None, cx, |selections| selections.refresh());
 5898            });
 5899        }
 5900    }
 5901
 5902    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5903        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5904            let project_path = buffer.read(cx).project_path(cx)?;
 5905            let project = self.project.as_ref()?.read(cx);
 5906            let entry = project.entry_for_path(&project_path, cx)?;
 5907            let abs_path = project.absolute_path(&project_path, cx)?;
 5908            let parent = if entry.is_symlink {
 5909                abs_path.canonicalize().ok()?
 5910            } else {
 5911                abs_path
 5912            }
 5913            .parent()?
 5914            .to_path_buf();
 5915            Some(parent)
 5916        }) {
 5917            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5918        }
 5919    }
 5920
 5921    fn gather_revert_changes(
 5922        &mut self,
 5923        selections: &[Selection<Anchor>],
 5924        cx: &mut ViewContext<'_, Editor>,
 5925    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 5926        let mut revert_changes = HashMap::default();
 5927        self.buffer.update(cx, |multi_buffer, cx| {
 5928            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 5929            for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 5930                Self::prepare_revert_change(&mut revert_changes, &multi_buffer, &hunk, cx);
 5931            }
 5932        });
 5933        revert_changes
 5934    }
 5935
 5936    fn prepare_revert_change(
 5937        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 5938        multi_buffer: &MultiBuffer,
 5939        hunk: &DiffHunk<MultiBufferRow>,
 5940        cx: &mut AppContext,
 5941    ) -> Option<()> {
 5942        let buffer = multi_buffer.buffer(hunk.buffer_id)?;
 5943        let buffer = buffer.read(cx);
 5944        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 5945        let buffer_snapshot = buffer.snapshot();
 5946        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5947        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5948            probe
 5949                .0
 5950                .start
 5951                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5952                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5953        }) {
 5954            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 5955            Some(())
 5956        } else {
 5957            None
 5958        }
 5959    }
 5960
 5961    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5962        self.manipulate_lines(cx, |lines| lines.reverse())
 5963    }
 5964
 5965    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5966        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5967    }
 5968
 5969    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5970    where
 5971        Fn: FnMut(&mut Vec<&str>),
 5972    {
 5973        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5974        let buffer = self.buffer.read(cx).snapshot(cx);
 5975
 5976        let mut edits = Vec::new();
 5977
 5978        let selections = self.selections.all::<Point>(cx);
 5979        let mut selections = selections.iter().peekable();
 5980        let mut contiguous_row_selections = Vec::new();
 5981        let mut new_selections = Vec::new();
 5982        let mut added_lines = 0;
 5983        let mut removed_lines = 0;
 5984
 5985        while let Some(selection) = selections.next() {
 5986            let (start_row, end_row) = consume_contiguous_rows(
 5987                &mut contiguous_row_selections,
 5988                selection,
 5989                &display_map,
 5990                &mut selections,
 5991            );
 5992
 5993            let start_point = Point::new(start_row.0, 0);
 5994            let end_point = Point::new(
 5995                end_row.previous_row().0,
 5996                buffer.line_len(end_row.previous_row()),
 5997            );
 5998            let text = buffer
 5999                .text_for_range(start_point..end_point)
 6000                .collect::<String>();
 6001
 6002            let mut lines = text.split('\n').collect_vec();
 6003
 6004            let lines_before = lines.len();
 6005            callback(&mut lines);
 6006            let lines_after = lines.len();
 6007
 6008            edits.push((start_point..end_point, lines.join("\n")));
 6009
 6010            // Selections must change based on added and removed line count
 6011            let start_row =
 6012                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6013            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6014            new_selections.push(Selection {
 6015                id: selection.id,
 6016                start: start_row,
 6017                end: end_row,
 6018                goal: SelectionGoal::None,
 6019                reversed: selection.reversed,
 6020            });
 6021
 6022            if lines_after > lines_before {
 6023                added_lines += lines_after - lines_before;
 6024            } else if lines_before > lines_after {
 6025                removed_lines += lines_before - lines_after;
 6026            }
 6027        }
 6028
 6029        self.transact(cx, |this, cx| {
 6030            let buffer = this.buffer.update(cx, |buffer, cx| {
 6031                buffer.edit(edits, None, cx);
 6032                buffer.snapshot(cx)
 6033            });
 6034
 6035            // Recalculate offsets on newly edited buffer
 6036            let new_selections = new_selections
 6037                .iter()
 6038                .map(|s| {
 6039                    let start_point = Point::new(s.start.0, 0);
 6040                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6041                    Selection {
 6042                        id: s.id,
 6043                        start: buffer.point_to_offset(start_point),
 6044                        end: buffer.point_to_offset(end_point),
 6045                        goal: s.goal,
 6046                        reversed: s.reversed,
 6047                    }
 6048                })
 6049                .collect();
 6050
 6051            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6052                s.select(new_selections);
 6053            });
 6054
 6055            this.request_autoscroll(Autoscroll::fit(), cx);
 6056        });
 6057    }
 6058
 6059    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6060        self.manipulate_text(cx, |text| text.to_uppercase())
 6061    }
 6062
 6063    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6064        self.manipulate_text(cx, |text| text.to_lowercase())
 6065    }
 6066
 6067    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6068        self.manipulate_text(cx, |text| {
 6069            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6070            // https://github.com/rutrum/convert-case/issues/16
 6071            text.split('\n')
 6072                .map(|line| line.to_case(Case::Title))
 6073                .join("\n")
 6074        })
 6075    }
 6076
 6077    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6078        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6079    }
 6080
 6081    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6082        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6083    }
 6084
 6085    pub fn convert_to_upper_camel_case(
 6086        &mut self,
 6087        _: &ConvertToUpperCamelCase,
 6088        cx: &mut ViewContext<Self>,
 6089    ) {
 6090        self.manipulate_text(cx, |text| {
 6091            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6092            // https://github.com/rutrum/convert-case/issues/16
 6093            text.split('\n')
 6094                .map(|line| line.to_case(Case::UpperCamel))
 6095                .join("\n")
 6096        })
 6097    }
 6098
 6099    pub fn convert_to_lower_camel_case(
 6100        &mut self,
 6101        _: &ConvertToLowerCamelCase,
 6102        cx: &mut ViewContext<Self>,
 6103    ) {
 6104        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6105    }
 6106
 6107    pub fn convert_to_opposite_case(
 6108        &mut self,
 6109        _: &ConvertToOppositeCase,
 6110        cx: &mut ViewContext<Self>,
 6111    ) {
 6112        self.manipulate_text(cx, |text| {
 6113            text.chars()
 6114                .fold(String::with_capacity(text.len()), |mut t, c| {
 6115                    if c.is_uppercase() {
 6116                        t.extend(c.to_lowercase());
 6117                    } else {
 6118                        t.extend(c.to_uppercase());
 6119                    }
 6120                    t
 6121                })
 6122        })
 6123    }
 6124
 6125    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6126    where
 6127        Fn: FnMut(&str) -> String,
 6128    {
 6129        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6130        let buffer = self.buffer.read(cx).snapshot(cx);
 6131
 6132        let mut new_selections = Vec::new();
 6133        let mut edits = Vec::new();
 6134        let mut selection_adjustment = 0i32;
 6135
 6136        for selection in self.selections.all::<usize>(cx) {
 6137            let selection_is_empty = selection.is_empty();
 6138
 6139            let (start, end) = if selection_is_empty {
 6140                let word_range = movement::surrounding_word(
 6141                    &display_map,
 6142                    selection.start.to_display_point(&display_map),
 6143                );
 6144                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6145                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6146                (start, end)
 6147            } else {
 6148                (selection.start, selection.end)
 6149            };
 6150
 6151            let text = buffer.text_for_range(start..end).collect::<String>();
 6152            let old_length = text.len() as i32;
 6153            let text = callback(&text);
 6154
 6155            new_selections.push(Selection {
 6156                start: (start as i32 - selection_adjustment) as usize,
 6157                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6158                goal: SelectionGoal::None,
 6159                ..selection
 6160            });
 6161
 6162            selection_adjustment += old_length - text.len() as i32;
 6163
 6164            edits.push((start..end, text));
 6165        }
 6166
 6167        self.transact(cx, |this, cx| {
 6168            this.buffer.update(cx, |buffer, cx| {
 6169                buffer.edit(edits, None, cx);
 6170            });
 6171
 6172            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6173                s.select(new_selections);
 6174            });
 6175
 6176            this.request_autoscroll(Autoscroll::fit(), cx);
 6177        });
 6178    }
 6179
 6180    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6181        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6182        let buffer = &display_map.buffer_snapshot;
 6183        let selections = self.selections.all::<Point>(cx);
 6184
 6185        let mut edits = Vec::new();
 6186        let mut selections_iter = selections.iter().peekable();
 6187        while let Some(selection) = selections_iter.next() {
 6188            // Avoid duplicating the same lines twice.
 6189            let mut rows = selection.spanned_rows(false, &display_map);
 6190
 6191            while let Some(next_selection) = selections_iter.peek() {
 6192                let next_rows = next_selection.spanned_rows(false, &display_map);
 6193                if next_rows.start < rows.end {
 6194                    rows.end = next_rows.end;
 6195                    selections_iter.next().unwrap();
 6196                } else {
 6197                    break;
 6198                }
 6199            }
 6200
 6201            // Copy the text from the selected row region and splice it either at the start
 6202            // or end of the region.
 6203            let start = Point::new(rows.start.0, 0);
 6204            let end = Point::new(
 6205                rows.end.previous_row().0,
 6206                buffer.line_len(rows.end.previous_row()),
 6207            );
 6208            let text = buffer
 6209                .text_for_range(start..end)
 6210                .chain(Some("\n"))
 6211                .collect::<String>();
 6212            let insert_location = if upwards {
 6213                Point::new(rows.end.0, 0)
 6214            } else {
 6215                start
 6216            };
 6217            edits.push((insert_location..insert_location, text));
 6218        }
 6219
 6220        self.transact(cx, |this, cx| {
 6221            this.buffer.update(cx, |buffer, cx| {
 6222                buffer.edit(edits, None, cx);
 6223            });
 6224
 6225            this.request_autoscroll(Autoscroll::fit(), cx);
 6226        });
 6227    }
 6228
 6229    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6230        self.duplicate_line(true, cx);
 6231    }
 6232
 6233    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6234        self.duplicate_line(false, cx);
 6235    }
 6236
 6237    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6238        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6239        let buffer = self.buffer.read(cx).snapshot(cx);
 6240
 6241        let mut edits = Vec::new();
 6242        let mut unfold_ranges = Vec::new();
 6243        let mut refold_ranges = Vec::new();
 6244
 6245        let selections = self.selections.all::<Point>(cx);
 6246        let mut selections = selections.iter().peekable();
 6247        let mut contiguous_row_selections = Vec::new();
 6248        let mut new_selections = Vec::new();
 6249
 6250        while let Some(selection) = selections.next() {
 6251            // Find all the selections that span a contiguous row range
 6252            let (start_row, end_row) = consume_contiguous_rows(
 6253                &mut contiguous_row_selections,
 6254                selection,
 6255                &display_map,
 6256                &mut selections,
 6257            );
 6258
 6259            // Move the text spanned by the row range to be before the line preceding the row range
 6260            if start_row.0 > 0 {
 6261                let range_to_move = Point::new(
 6262                    start_row.previous_row().0,
 6263                    buffer.line_len(start_row.previous_row()),
 6264                )
 6265                    ..Point::new(
 6266                        end_row.previous_row().0,
 6267                        buffer.line_len(end_row.previous_row()),
 6268                    );
 6269                let insertion_point = display_map
 6270                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6271                    .0;
 6272
 6273                // Don't move lines across excerpts
 6274                if buffer
 6275                    .excerpt_boundaries_in_range((
 6276                        Bound::Excluded(insertion_point),
 6277                        Bound::Included(range_to_move.end),
 6278                    ))
 6279                    .next()
 6280                    .is_none()
 6281                {
 6282                    let text = buffer
 6283                        .text_for_range(range_to_move.clone())
 6284                        .flat_map(|s| s.chars())
 6285                        .skip(1)
 6286                        .chain(['\n'])
 6287                        .collect::<String>();
 6288
 6289                    edits.push((
 6290                        buffer.anchor_after(range_to_move.start)
 6291                            ..buffer.anchor_before(range_to_move.end),
 6292                        String::new(),
 6293                    ));
 6294                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6295                    edits.push((insertion_anchor..insertion_anchor, text));
 6296
 6297                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6298
 6299                    // Move selections up
 6300                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6301                        |mut selection| {
 6302                            selection.start.row -= row_delta;
 6303                            selection.end.row -= row_delta;
 6304                            selection
 6305                        },
 6306                    ));
 6307
 6308                    // Move folds up
 6309                    unfold_ranges.push(range_to_move.clone());
 6310                    for fold in display_map.folds_in_range(
 6311                        buffer.anchor_before(range_to_move.start)
 6312                            ..buffer.anchor_after(range_to_move.end),
 6313                    ) {
 6314                        let mut start = fold.range.start.to_point(&buffer);
 6315                        let mut end = fold.range.end.to_point(&buffer);
 6316                        start.row -= row_delta;
 6317                        end.row -= row_delta;
 6318                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6319                    }
 6320                }
 6321            }
 6322
 6323            // If we didn't move line(s), preserve the existing selections
 6324            new_selections.append(&mut contiguous_row_selections);
 6325        }
 6326
 6327        self.transact(cx, |this, cx| {
 6328            this.unfold_ranges(unfold_ranges, true, true, cx);
 6329            this.buffer.update(cx, |buffer, cx| {
 6330                for (range, text) in edits {
 6331                    buffer.edit([(range, text)], None, cx);
 6332                }
 6333            });
 6334            this.fold_ranges(refold_ranges, true, cx);
 6335            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6336                s.select(new_selections);
 6337            })
 6338        });
 6339    }
 6340
 6341    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6342        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6343        let buffer = self.buffer.read(cx).snapshot(cx);
 6344
 6345        let mut edits = Vec::new();
 6346        let mut unfold_ranges = Vec::new();
 6347        let mut refold_ranges = Vec::new();
 6348
 6349        let selections = self.selections.all::<Point>(cx);
 6350        let mut selections = selections.iter().peekable();
 6351        let mut contiguous_row_selections = Vec::new();
 6352        let mut new_selections = Vec::new();
 6353
 6354        while let Some(selection) = selections.next() {
 6355            // Find all the selections that span a contiguous row range
 6356            let (start_row, end_row) = consume_contiguous_rows(
 6357                &mut contiguous_row_selections,
 6358                selection,
 6359                &display_map,
 6360                &mut selections,
 6361            );
 6362
 6363            // Move the text spanned by the row range to be after the last line of the row range
 6364            if end_row.0 <= buffer.max_point().row {
 6365                let range_to_move =
 6366                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6367                let insertion_point = display_map
 6368                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6369                    .0;
 6370
 6371                // Don't move lines across excerpt boundaries
 6372                if buffer
 6373                    .excerpt_boundaries_in_range((
 6374                        Bound::Excluded(range_to_move.start),
 6375                        Bound::Included(insertion_point),
 6376                    ))
 6377                    .next()
 6378                    .is_none()
 6379                {
 6380                    let mut text = String::from("\n");
 6381                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6382                    text.pop(); // Drop trailing newline
 6383                    edits.push((
 6384                        buffer.anchor_after(range_to_move.start)
 6385                            ..buffer.anchor_before(range_to_move.end),
 6386                        String::new(),
 6387                    ));
 6388                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6389                    edits.push((insertion_anchor..insertion_anchor, text));
 6390
 6391                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6392
 6393                    // Move selections down
 6394                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6395                        |mut selection| {
 6396                            selection.start.row += row_delta;
 6397                            selection.end.row += row_delta;
 6398                            selection
 6399                        },
 6400                    ));
 6401
 6402                    // Move folds down
 6403                    unfold_ranges.push(range_to_move.clone());
 6404                    for fold in display_map.folds_in_range(
 6405                        buffer.anchor_before(range_to_move.start)
 6406                            ..buffer.anchor_after(range_to_move.end),
 6407                    ) {
 6408                        let mut start = fold.range.start.to_point(&buffer);
 6409                        let mut end = fold.range.end.to_point(&buffer);
 6410                        start.row += row_delta;
 6411                        end.row += row_delta;
 6412                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6413                    }
 6414                }
 6415            }
 6416
 6417            // If we didn't move line(s), preserve the existing selections
 6418            new_selections.append(&mut contiguous_row_selections);
 6419        }
 6420
 6421        self.transact(cx, |this, cx| {
 6422            this.unfold_ranges(unfold_ranges, true, true, cx);
 6423            this.buffer.update(cx, |buffer, cx| {
 6424                for (range, text) in edits {
 6425                    buffer.edit([(range, text)], None, cx);
 6426                }
 6427            });
 6428            this.fold_ranges(refold_ranges, true, cx);
 6429            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6430        });
 6431    }
 6432
 6433    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6434        let text_layout_details = &self.text_layout_details(cx);
 6435        self.transact(cx, |this, cx| {
 6436            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6437                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6438                let line_mode = s.line_mode;
 6439                s.move_with(|display_map, selection| {
 6440                    if !selection.is_empty() || line_mode {
 6441                        return;
 6442                    }
 6443
 6444                    let mut head = selection.head();
 6445                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6446                    if head.column() == display_map.line_len(head.row()) {
 6447                        transpose_offset = display_map
 6448                            .buffer_snapshot
 6449                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6450                    }
 6451
 6452                    if transpose_offset == 0 {
 6453                        return;
 6454                    }
 6455
 6456                    *head.column_mut() += 1;
 6457                    head = display_map.clip_point(head, Bias::Right);
 6458                    let goal = SelectionGoal::HorizontalPosition(
 6459                        display_map
 6460                            .x_for_display_point(head, &text_layout_details)
 6461                            .into(),
 6462                    );
 6463                    selection.collapse_to(head, goal);
 6464
 6465                    let transpose_start = display_map
 6466                        .buffer_snapshot
 6467                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6468                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6469                        let transpose_end = display_map
 6470                            .buffer_snapshot
 6471                            .clip_offset(transpose_offset + 1, Bias::Right);
 6472                        if let Some(ch) =
 6473                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6474                        {
 6475                            edits.push((transpose_start..transpose_offset, String::new()));
 6476                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6477                        }
 6478                    }
 6479                });
 6480                edits
 6481            });
 6482            this.buffer
 6483                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6484            let selections = this.selections.all::<usize>(cx);
 6485            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6486                s.select(selections);
 6487            });
 6488        });
 6489    }
 6490
 6491    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6492        let mut text = String::new();
 6493        let buffer = self.buffer.read(cx).snapshot(cx);
 6494        let mut selections = self.selections.all::<Point>(cx);
 6495        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6496        {
 6497            let max_point = buffer.max_point();
 6498            let mut is_first = true;
 6499            for selection in &mut selections {
 6500                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6501                if is_entire_line {
 6502                    selection.start = Point::new(selection.start.row, 0);
 6503                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6504                    selection.goal = SelectionGoal::None;
 6505                }
 6506                if is_first {
 6507                    is_first = false;
 6508                } else {
 6509                    text += "\n";
 6510                }
 6511                let mut len = 0;
 6512                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6513                    text.push_str(chunk);
 6514                    len += chunk.len();
 6515                }
 6516                clipboard_selections.push(ClipboardSelection {
 6517                    len,
 6518                    is_entire_line,
 6519                    first_line_indent: buffer
 6520                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6521                        .len,
 6522                });
 6523            }
 6524        }
 6525
 6526        self.transact(cx, |this, cx| {
 6527            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6528                s.select(selections);
 6529            });
 6530            this.insert("", cx);
 6531            cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6532        });
 6533    }
 6534
 6535    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6536        let selections = self.selections.all::<Point>(cx);
 6537        let buffer = self.buffer.read(cx).read(cx);
 6538        let mut text = String::new();
 6539
 6540        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6541        {
 6542            let max_point = buffer.max_point();
 6543            let mut is_first = true;
 6544            for selection in selections.iter() {
 6545                let mut start = selection.start;
 6546                let mut end = selection.end;
 6547                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6548                if is_entire_line {
 6549                    start = Point::new(start.row, 0);
 6550                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6551                }
 6552                if is_first {
 6553                    is_first = false;
 6554                } else {
 6555                    text += "\n";
 6556                }
 6557                let mut len = 0;
 6558                for chunk in buffer.text_for_range(start..end) {
 6559                    text.push_str(chunk);
 6560                    len += chunk.len();
 6561                }
 6562                clipboard_selections.push(ClipboardSelection {
 6563                    len,
 6564                    is_entire_line,
 6565                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6566                });
 6567            }
 6568        }
 6569
 6570        cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6571    }
 6572
 6573    pub fn do_paste(
 6574        &mut self,
 6575        text: &String,
 6576        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6577        handle_entire_lines: bool,
 6578        cx: &mut ViewContext<Self>,
 6579    ) {
 6580        if self.read_only(cx) {
 6581            return;
 6582        }
 6583
 6584        let clipboard_text = Cow::Borrowed(text);
 6585
 6586        self.transact(cx, |this, cx| {
 6587            if let Some(mut clipboard_selections) = clipboard_selections {
 6588                let old_selections = this.selections.all::<usize>(cx);
 6589                let all_selections_were_entire_line =
 6590                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6591                let first_selection_indent_column =
 6592                    clipboard_selections.first().map(|s| s.first_line_indent);
 6593                if clipboard_selections.len() != old_selections.len() {
 6594                    clipboard_selections.drain(..);
 6595                }
 6596
 6597                this.buffer.update(cx, |buffer, cx| {
 6598                    let snapshot = buffer.read(cx);
 6599                    let mut start_offset = 0;
 6600                    let mut edits = Vec::new();
 6601                    let mut original_indent_columns = Vec::new();
 6602                    for (ix, selection) in old_selections.iter().enumerate() {
 6603                        let to_insert;
 6604                        let entire_line;
 6605                        let original_indent_column;
 6606                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6607                            let end_offset = start_offset + clipboard_selection.len;
 6608                            to_insert = &clipboard_text[start_offset..end_offset];
 6609                            entire_line = clipboard_selection.is_entire_line;
 6610                            start_offset = end_offset + 1;
 6611                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6612                        } else {
 6613                            to_insert = clipboard_text.as_str();
 6614                            entire_line = all_selections_were_entire_line;
 6615                            original_indent_column = first_selection_indent_column
 6616                        }
 6617
 6618                        // If the corresponding selection was empty when this slice of the
 6619                        // clipboard text was written, then the entire line containing the
 6620                        // selection was copied. If this selection is also currently empty,
 6621                        // then paste the line before the current line of the buffer.
 6622                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6623                            let column = selection.start.to_point(&snapshot).column as usize;
 6624                            let line_start = selection.start - column;
 6625                            line_start..line_start
 6626                        } else {
 6627                            selection.range()
 6628                        };
 6629
 6630                        edits.push((range, to_insert));
 6631                        original_indent_columns.extend(original_indent_column);
 6632                    }
 6633                    drop(snapshot);
 6634
 6635                    buffer.edit(
 6636                        edits,
 6637                        Some(AutoindentMode::Block {
 6638                            original_indent_columns,
 6639                        }),
 6640                        cx,
 6641                    );
 6642                });
 6643
 6644                let selections = this.selections.all::<usize>(cx);
 6645                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6646            } else {
 6647                this.insert(&clipboard_text, cx);
 6648            }
 6649        });
 6650    }
 6651
 6652    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6653        if let Some(item) = cx.read_from_clipboard() {
 6654            self.do_paste(
 6655                item.text(),
 6656                item.metadata::<Vec<ClipboardSelection>>(),
 6657                true,
 6658                cx,
 6659            )
 6660        };
 6661    }
 6662
 6663    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6664        if self.read_only(cx) {
 6665            return;
 6666        }
 6667
 6668        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6669            if let Some((selections, _)) =
 6670                self.selection_history.transaction(transaction_id).cloned()
 6671            {
 6672                self.change_selections(None, cx, |s| {
 6673                    s.select_anchors(selections.to_vec());
 6674                });
 6675            }
 6676            self.request_autoscroll(Autoscroll::fit(), cx);
 6677            self.unmark_text(cx);
 6678            self.refresh_inline_completion(true, cx);
 6679            cx.emit(EditorEvent::Edited { transaction_id });
 6680            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 6681        }
 6682    }
 6683
 6684    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 6685        if self.read_only(cx) {
 6686            return;
 6687        }
 6688
 6689        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 6690            if let Some((_, Some(selections))) =
 6691                self.selection_history.transaction(transaction_id).cloned()
 6692            {
 6693                self.change_selections(None, cx, |s| {
 6694                    s.select_anchors(selections.to_vec());
 6695                });
 6696            }
 6697            self.request_autoscroll(Autoscroll::fit(), cx);
 6698            self.unmark_text(cx);
 6699            self.refresh_inline_completion(true, cx);
 6700            cx.emit(EditorEvent::Edited { transaction_id });
 6701        }
 6702    }
 6703
 6704    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 6705        self.buffer
 6706            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 6707    }
 6708
 6709    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 6710        self.buffer
 6711            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 6712    }
 6713
 6714    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 6715        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6716            let line_mode = s.line_mode;
 6717            s.move_with(|map, selection| {
 6718                let cursor = if selection.is_empty() && !line_mode {
 6719                    movement::left(map, selection.start)
 6720                } else {
 6721                    selection.start
 6722                };
 6723                selection.collapse_to(cursor, SelectionGoal::None);
 6724            });
 6725        })
 6726    }
 6727
 6728    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 6729        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6730            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 6731        })
 6732    }
 6733
 6734    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 6735        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6736            let line_mode = s.line_mode;
 6737            s.move_with(|map, selection| {
 6738                let cursor = if selection.is_empty() && !line_mode {
 6739                    movement::right(map, selection.end)
 6740                } else {
 6741                    selection.end
 6742                };
 6743                selection.collapse_to(cursor, SelectionGoal::None)
 6744            });
 6745        })
 6746    }
 6747
 6748    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 6749        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6750            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 6751        })
 6752    }
 6753
 6754    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 6755        if self.take_rename(true, cx).is_some() {
 6756            return;
 6757        }
 6758
 6759        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6760            cx.propagate();
 6761            return;
 6762        }
 6763
 6764        let text_layout_details = &self.text_layout_details(cx);
 6765        let selection_count = self.selections.count();
 6766        let first_selection = self.selections.first_anchor();
 6767
 6768        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6769            let line_mode = s.line_mode;
 6770            s.move_with(|map, selection| {
 6771                if !selection.is_empty() && !line_mode {
 6772                    selection.goal = SelectionGoal::None;
 6773                }
 6774                let (cursor, goal) = movement::up(
 6775                    map,
 6776                    selection.start,
 6777                    selection.goal,
 6778                    false,
 6779                    &text_layout_details,
 6780                );
 6781                selection.collapse_to(cursor, goal);
 6782            });
 6783        });
 6784
 6785        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6786        {
 6787            cx.propagate();
 6788        }
 6789    }
 6790
 6791    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 6792        if self.take_rename(true, cx).is_some() {
 6793            return;
 6794        }
 6795
 6796        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6797            cx.propagate();
 6798            return;
 6799        }
 6800
 6801        let text_layout_details = &self.text_layout_details(cx);
 6802
 6803        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6804            let line_mode = s.line_mode;
 6805            s.move_with(|map, selection| {
 6806                if !selection.is_empty() && !line_mode {
 6807                    selection.goal = SelectionGoal::None;
 6808                }
 6809                let (cursor, goal) = movement::up_by_rows(
 6810                    map,
 6811                    selection.start,
 6812                    action.lines,
 6813                    selection.goal,
 6814                    false,
 6815                    &text_layout_details,
 6816                );
 6817                selection.collapse_to(cursor, goal);
 6818            });
 6819        })
 6820    }
 6821
 6822    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 6823        if self.take_rename(true, cx).is_some() {
 6824            return;
 6825        }
 6826
 6827        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6828            cx.propagate();
 6829            return;
 6830        }
 6831
 6832        let text_layout_details = &self.text_layout_details(cx);
 6833
 6834        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6835            let line_mode = s.line_mode;
 6836            s.move_with(|map, selection| {
 6837                if !selection.is_empty() && !line_mode {
 6838                    selection.goal = SelectionGoal::None;
 6839                }
 6840                let (cursor, goal) = movement::down_by_rows(
 6841                    map,
 6842                    selection.start,
 6843                    action.lines,
 6844                    selection.goal,
 6845                    false,
 6846                    &text_layout_details,
 6847                );
 6848                selection.collapse_to(cursor, goal);
 6849            });
 6850        })
 6851    }
 6852
 6853    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 6854        let text_layout_details = &self.text_layout_details(cx);
 6855        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6856            s.move_heads_with(|map, head, goal| {
 6857                movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6858            })
 6859        })
 6860    }
 6861
 6862    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 6863        let text_layout_details = &self.text_layout_details(cx);
 6864        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6865            s.move_heads_with(|map, head, goal| {
 6866                movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6867            })
 6868        })
 6869    }
 6870
 6871    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 6872        let Some(row_count) = self.visible_row_count() else {
 6873            return;
 6874        };
 6875
 6876        let text_layout_details = &self.text_layout_details(cx);
 6877
 6878        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6879            s.move_heads_with(|map, head, goal| {
 6880                movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
 6881            })
 6882        })
 6883    }
 6884
 6885    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 6886        if self.take_rename(true, cx).is_some() {
 6887            return;
 6888        }
 6889
 6890        if self
 6891            .context_menu
 6892            .write()
 6893            .as_mut()
 6894            .map(|menu| menu.select_first(self.project.as_ref(), cx))
 6895            .unwrap_or(false)
 6896        {
 6897            return;
 6898        }
 6899
 6900        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6901            cx.propagate();
 6902            return;
 6903        }
 6904
 6905        let Some(row_count) = self.visible_row_count() else {
 6906            return;
 6907        };
 6908
 6909        let autoscroll = if action.center_cursor {
 6910            Autoscroll::center()
 6911        } else {
 6912            Autoscroll::fit()
 6913        };
 6914
 6915        let text_layout_details = &self.text_layout_details(cx);
 6916
 6917        self.change_selections(Some(autoscroll), cx, |s| {
 6918            let line_mode = s.line_mode;
 6919            s.move_with(|map, selection| {
 6920                if !selection.is_empty() && !line_mode {
 6921                    selection.goal = SelectionGoal::None;
 6922                }
 6923                let (cursor, goal) = movement::up_by_rows(
 6924                    map,
 6925                    selection.end,
 6926                    row_count,
 6927                    selection.goal,
 6928                    false,
 6929                    &text_layout_details,
 6930                );
 6931                selection.collapse_to(cursor, goal);
 6932            });
 6933        });
 6934    }
 6935
 6936    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 6937        let text_layout_details = &self.text_layout_details(cx);
 6938        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6939            s.move_heads_with(|map, head, goal| {
 6940                movement::up(map, head, goal, false, &text_layout_details)
 6941            })
 6942        })
 6943    }
 6944
 6945    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 6946        self.take_rename(true, cx);
 6947
 6948        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6949            cx.propagate();
 6950            return;
 6951        }
 6952
 6953        let text_layout_details = &self.text_layout_details(cx);
 6954        let selection_count = self.selections.count();
 6955        let first_selection = self.selections.first_anchor();
 6956
 6957        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6958            let line_mode = s.line_mode;
 6959            s.move_with(|map, selection| {
 6960                if !selection.is_empty() && !line_mode {
 6961                    selection.goal = SelectionGoal::None;
 6962                }
 6963                let (cursor, goal) = movement::down(
 6964                    map,
 6965                    selection.end,
 6966                    selection.goal,
 6967                    false,
 6968                    &text_layout_details,
 6969                );
 6970                selection.collapse_to(cursor, goal);
 6971            });
 6972        });
 6973
 6974        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6975        {
 6976            cx.propagate();
 6977        }
 6978    }
 6979
 6980    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 6981        let Some(row_count) = self.visible_row_count() else {
 6982            return;
 6983        };
 6984
 6985        let text_layout_details = &self.text_layout_details(cx);
 6986
 6987        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6988            s.move_heads_with(|map, head, goal| {
 6989                movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
 6990            })
 6991        })
 6992    }
 6993
 6994    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 6995        if self.take_rename(true, cx).is_some() {
 6996            return;
 6997        }
 6998
 6999        if self
 7000            .context_menu
 7001            .write()
 7002            .as_mut()
 7003            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 7004            .unwrap_or(false)
 7005        {
 7006            return;
 7007        }
 7008
 7009        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7010            cx.propagate();
 7011            return;
 7012        }
 7013
 7014        let Some(row_count) = self.visible_row_count() else {
 7015            return;
 7016        };
 7017
 7018        let autoscroll = if action.center_cursor {
 7019            Autoscroll::center()
 7020        } else {
 7021            Autoscroll::fit()
 7022        };
 7023
 7024        let text_layout_details = &self.text_layout_details(cx);
 7025        self.change_selections(Some(autoscroll), cx, |s| {
 7026            let line_mode = s.line_mode;
 7027            s.move_with(|map, selection| {
 7028                if !selection.is_empty() && !line_mode {
 7029                    selection.goal = SelectionGoal::None;
 7030                }
 7031                let (cursor, goal) = movement::down_by_rows(
 7032                    map,
 7033                    selection.end,
 7034                    row_count,
 7035                    selection.goal,
 7036                    false,
 7037                    &text_layout_details,
 7038                );
 7039                selection.collapse_to(cursor, goal);
 7040            });
 7041        });
 7042    }
 7043
 7044    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7045        let text_layout_details = &self.text_layout_details(cx);
 7046        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7047            s.move_heads_with(|map, head, goal| {
 7048                movement::down(map, head, goal, false, &text_layout_details)
 7049            })
 7050        });
 7051    }
 7052
 7053    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7054        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7055            context_menu.select_first(self.project.as_ref(), cx);
 7056        }
 7057    }
 7058
 7059    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7060        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7061            context_menu.select_prev(self.project.as_ref(), cx);
 7062        }
 7063    }
 7064
 7065    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7066        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7067            context_menu.select_next(self.project.as_ref(), cx);
 7068        }
 7069    }
 7070
 7071    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7072        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7073            context_menu.select_last(self.project.as_ref(), cx);
 7074        }
 7075    }
 7076
 7077    pub fn move_to_previous_word_start(
 7078        &mut self,
 7079        _: &MoveToPreviousWordStart,
 7080        cx: &mut ViewContext<Self>,
 7081    ) {
 7082        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7083            s.move_cursors_with(|map, head, _| {
 7084                (
 7085                    movement::previous_word_start(map, head),
 7086                    SelectionGoal::None,
 7087                )
 7088            });
 7089        })
 7090    }
 7091
 7092    pub fn move_to_previous_subword_start(
 7093        &mut self,
 7094        _: &MoveToPreviousSubwordStart,
 7095        cx: &mut ViewContext<Self>,
 7096    ) {
 7097        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7098            s.move_cursors_with(|map, head, _| {
 7099                (
 7100                    movement::previous_subword_start(map, head),
 7101                    SelectionGoal::None,
 7102                )
 7103            });
 7104        })
 7105    }
 7106
 7107    pub fn select_to_previous_word_start(
 7108        &mut self,
 7109        _: &SelectToPreviousWordStart,
 7110        cx: &mut ViewContext<Self>,
 7111    ) {
 7112        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7113            s.move_heads_with(|map, head, _| {
 7114                (
 7115                    movement::previous_word_start(map, head),
 7116                    SelectionGoal::None,
 7117                )
 7118            });
 7119        })
 7120    }
 7121
 7122    pub fn select_to_previous_subword_start(
 7123        &mut self,
 7124        _: &SelectToPreviousSubwordStart,
 7125        cx: &mut ViewContext<Self>,
 7126    ) {
 7127        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7128            s.move_heads_with(|map, head, _| {
 7129                (
 7130                    movement::previous_subword_start(map, head),
 7131                    SelectionGoal::None,
 7132                )
 7133            });
 7134        })
 7135    }
 7136
 7137    pub fn delete_to_previous_word_start(
 7138        &mut self,
 7139        _: &DeleteToPreviousWordStart,
 7140        cx: &mut ViewContext<Self>,
 7141    ) {
 7142        self.transact(cx, |this, cx| {
 7143            this.select_autoclose_pair(cx);
 7144            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7145                let line_mode = s.line_mode;
 7146                s.move_with(|map, selection| {
 7147                    if selection.is_empty() && !line_mode {
 7148                        let cursor = movement::previous_word_start(map, selection.head());
 7149                        selection.set_head(cursor, SelectionGoal::None);
 7150                    }
 7151                });
 7152            });
 7153            this.insert("", cx);
 7154        });
 7155    }
 7156
 7157    pub fn delete_to_previous_subword_start(
 7158        &mut self,
 7159        _: &DeleteToPreviousSubwordStart,
 7160        cx: &mut ViewContext<Self>,
 7161    ) {
 7162        self.transact(cx, |this, cx| {
 7163            this.select_autoclose_pair(cx);
 7164            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7165                let line_mode = s.line_mode;
 7166                s.move_with(|map, selection| {
 7167                    if selection.is_empty() && !line_mode {
 7168                        let cursor = movement::previous_subword_start(map, selection.head());
 7169                        selection.set_head(cursor, SelectionGoal::None);
 7170                    }
 7171                });
 7172            });
 7173            this.insert("", cx);
 7174        });
 7175    }
 7176
 7177    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7178        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7179            s.move_cursors_with(|map, head, _| {
 7180                (movement::next_word_end(map, head), SelectionGoal::None)
 7181            });
 7182        })
 7183    }
 7184
 7185    pub fn move_to_next_subword_end(
 7186        &mut self,
 7187        _: &MoveToNextSubwordEnd,
 7188        cx: &mut ViewContext<Self>,
 7189    ) {
 7190        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7191            s.move_cursors_with(|map, head, _| {
 7192                (movement::next_subword_end(map, head), SelectionGoal::None)
 7193            });
 7194        })
 7195    }
 7196
 7197    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7198        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7199            s.move_heads_with(|map, head, _| {
 7200                (movement::next_word_end(map, head), SelectionGoal::None)
 7201            });
 7202        })
 7203    }
 7204
 7205    pub fn select_to_next_subword_end(
 7206        &mut self,
 7207        _: &SelectToNextSubwordEnd,
 7208        cx: &mut ViewContext<Self>,
 7209    ) {
 7210        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7211            s.move_heads_with(|map, head, _| {
 7212                (movement::next_subword_end(map, head), SelectionGoal::None)
 7213            });
 7214        })
 7215    }
 7216
 7217    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
 7218        self.transact(cx, |this, cx| {
 7219            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7220                let line_mode = s.line_mode;
 7221                s.move_with(|map, selection| {
 7222                    if selection.is_empty() && !line_mode {
 7223                        let cursor = movement::next_word_end(map, selection.head());
 7224                        selection.set_head(cursor, SelectionGoal::None);
 7225                    }
 7226                });
 7227            });
 7228            this.insert("", cx);
 7229        });
 7230    }
 7231
 7232    pub fn delete_to_next_subword_end(
 7233        &mut self,
 7234        _: &DeleteToNextSubwordEnd,
 7235        cx: &mut ViewContext<Self>,
 7236    ) {
 7237        self.transact(cx, |this, cx| {
 7238            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7239                s.move_with(|map, selection| {
 7240                    if selection.is_empty() {
 7241                        let cursor = movement::next_subword_end(map, selection.head());
 7242                        selection.set_head(cursor, SelectionGoal::None);
 7243                    }
 7244                });
 7245            });
 7246            this.insert("", cx);
 7247        });
 7248    }
 7249
 7250    pub fn move_to_beginning_of_line(
 7251        &mut self,
 7252        action: &MoveToBeginningOfLine,
 7253        cx: &mut ViewContext<Self>,
 7254    ) {
 7255        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7256            s.move_cursors_with(|map, head, _| {
 7257                (
 7258                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7259                    SelectionGoal::None,
 7260                )
 7261            });
 7262        })
 7263    }
 7264
 7265    pub fn select_to_beginning_of_line(
 7266        &mut self,
 7267        action: &SelectToBeginningOfLine,
 7268        cx: &mut ViewContext<Self>,
 7269    ) {
 7270        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7271            s.move_heads_with(|map, head, _| {
 7272                (
 7273                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7274                    SelectionGoal::None,
 7275                )
 7276            });
 7277        });
 7278    }
 7279
 7280    pub fn delete_to_beginning_of_line(
 7281        &mut self,
 7282        _: &DeleteToBeginningOfLine,
 7283        cx: &mut ViewContext<Self>,
 7284    ) {
 7285        self.transact(cx, |this, cx| {
 7286            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7287                s.move_with(|_, selection| {
 7288                    selection.reversed = true;
 7289                });
 7290            });
 7291
 7292            this.select_to_beginning_of_line(
 7293                &SelectToBeginningOfLine {
 7294                    stop_at_soft_wraps: false,
 7295                },
 7296                cx,
 7297            );
 7298            this.backspace(&Backspace, cx);
 7299        });
 7300    }
 7301
 7302    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7303        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7304            s.move_cursors_with(|map, head, _| {
 7305                (
 7306                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7307                    SelectionGoal::None,
 7308                )
 7309            });
 7310        })
 7311    }
 7312
 7313    pub fn select_to_end_of_line(
 7314        &mut self,
 7315        action: &SelectToEndOfLine,
 7316        cx: &mut ViewContext<Self>,
 7317    ) {
 7318        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7319            s.move_heads_with(|map, head, _| {
 7320                (
 7321                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7322                    SelectionGoal::None,
 7323                )
 7324            });
 7325        })
 7326    }
 7327
 7328    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7329        self.transact(cx, |this, cx| {
 7330            this.select_to_end_of_line(
 7331                &SelectToEndOfLine {
 7332                    stop_at_soft_wraps: false,
 7333                },
 7334                cx,
 7335            );
 7336            this.delete(&Delete, cx);
 7337        });
 7338    }
 7339
 7340    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7341        self.transact(cx, |this, cx| {
 7342            this.select_to_end_of_line(
 7343                &SelectToEndOfLine {
 7344                    stop_at_soft_wraps: false,
 7345                },
 7346                cx,
 7347            );
 7348            this.cut(&Cut, cx);
 7349        });
 7350    }
 7351
 7352    pub fn move_to_start_of_paragraph(
 7353        &mut self,
 7354        _: &MoveToStartOfParagraph,
 7355        cx: &mut ViewContext<Self>,
 7356    ) {
 7357        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7358            cx.propagate();
 7359            return;
 7360        }
 7361
 7362        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7363            s.move_with(|map, selection| {
 7364                selection.collapse_to(
 7365                    movement::start_of_paragraph(map, selection.head(), 1),
 7366                    SelectionGoal::None,
 7367                )
 7368            });
 7369        })
 7370    }
 7371
 7372    pub fn move_to_end_of_paragraph(
 7373        &mut self,
 7374        _: &MoveToEndOfParagraph,
 7375        cx: &mut ViewContext<Self>,
 7376    ) {
 7377        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7378            cx.propagate();
 7379            return;
 7380        }
 7381
 7382        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7383            s.move_with(|map, selection| {
 7384                selection.collapse_to(
 7385                    movement::end_of_paragraph(map, selection.head(), 1),
 7386                    SelectionGoal::None,
 7387                )
 7388            });
 7389        })
 7390    }
 7391
 7392    pub fn select_to_start_of_paragraph(
 7393        &mut self,
 7394        _: &SelectToStartOfParagraph,
 7395        cx: &mut ViewContext<Self>,
 7396    ) {
 7397        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7398            cx.propagate();
 7399            return;
 7400        }
 7401
 7402        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7403            s.move_heads_with(|map, head, _| {
 7404                (
 7405                    movement::start_of_paragraph(map, head, 1),
 7406                    SelectionGoal::None,
 7407                )
 7408            });
 7409        })
 7410    }
 7411
 7412    pub fn select_to_end_of_paragraph(
 7413        &mut self,
 7414        _: &SelectToEndOfParagraph,
 7415        cx: &mut ViewContext<Self>,
 7416    ) {
 7417        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7418            cx.propagate();
 7419            return;
 7420        }
 7421
 7422        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7423            s.move_heads_with(|map, head, _| {
 7424                (
 7425                    movement::end_of_paragraph(map, head, 1),
 7426                    SelectionGoal::None,
 7427                )
 7428            });
 7429        })
 7430    }
 7431
 7432    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7433        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7434            cx.propagate();
 7435            return;
 7436        }
 7437
 7438        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7439            s.select_ranges(vec![0..0]);
 7440        });
 7441    }
 7442
 7443    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7444        let mut selection = self.selections.last::<Point>(cx);
 7445        selection.set_head(Point::zero(), SelectionGoal::None);
 7446
 7447        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7448            s.select(vec![selection]);
 7449        });
 7450    }
 7451
 7452    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7453        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7454            cx.propagate();
 7455            return;
 7456        }
 7457
 7458        let cursor = self.buffer.read(cx).read(cx).len();
 7459        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7460            s.select_ranges(vec![cursor..cursor])
 7461        });
 7462    }
 7463
 7464    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7465        self.nav_history = nav_history;
 7466    }
 7467
 7468    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7469        self.nav_history.as_ref()
 7470    }
 7471
 7472    fn push_to_nav_history(
 7473        &mut self,
 7474        cursor_anchor: Anchor,
 7475        new_position: Option<Point>,
 7476        cx: &mut ViewContext<Self>,
 7477    ) {
 7478        if let Some(nav_history) = self.nav_history.as_mut() {
 7479            let buffer = self.buffer.read(cx).read(cx);
 7480            let cursor_position = cursor_anchor.to_point(&buffer);
 7481            let scroll_state = self.scroll_manager.anchor();
 7482            let scroll_top_row = scroll_state.top_row(&buffer);
 7483            drop(buffer);
 7484
 7485            if let Some(new_position) = new_position {
 7486                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7487                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7488                    return;
 7489                }
 7490            }
 7491
 7492            nav_history.push(
 7493                Some(NavigationData {
 7494                    cursor_anchor,
 7495                    cursor_position,
 7496                    scroll_anchor: scroll_state,
 7497                    scroll_top_row,
 7498                }),
 7499                cx,
 7500            );
 7501        }
 7502    }
 7503
 7504    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7505        let buffer = self.buffer.read(cx).snapshot(cx);
 7506        let mut selection = self.selections.first::<usize>(cx);
 7507        selection.set_head(buffer.len(), SelectionGoal::None);
 7508        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7509            s.select(vec![selection]);
 7510        });
 7511    }
 7512
 7513    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7514        let end = self.buffer.read(cx).read(cx).len();
 7515        self.change_selections(None, cx, |s| {
 7516            s.select_ranges(vec![0..end]);
 7517        });
 7518    }
 7519
 7520    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7521        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7522        let mut selections = self.selections.all::<Point>(cx);
 7523        let max_point = display_map.buffer_snapshot.max_point();
 7524        for selection in &mut selections {
 7525            let rows = selection.spanned_rows(true, &display_map);
 7526            selection.start = Point::new(rows.start.0, 0);
 7527            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7528            selection.reversed = false;
 7529        }
 7530        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7531            s.select(selections);
 7532        });
 7533    }
 7534
 7535    pub fn split_selection_into_lines(
 7536        &mut self,
 7537        _: &SplitSelectionIntoLines,
 7538        cx: &mut ViewContext<Self>,
 7539    ) {
 7540        let mut to_unfold = Vec::new();
 7541        let mut new_selection_ranges = Vec::new();
 7542        {
 7543            let selections = self.selections.all::<Point>(cx);
 7544            let buffer = self.buffer.read(cx).read(cx);
 7545            for selection in selections {
 7546                for row in selection.start.row..selection.end.row {
 7547                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7548                    new_selection_ranges.push(cursor..cursor);
 7549                }
 7550                new_selection_ranges.push(selection.end..selection.end);
 7551                to_unfold.push(selection.start..selection.end);
 7552            }
 7553        }
 7554        self.unfold_ranges(to_unfold, true, true, cx);
 7555        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7556            s.select_ranges(new_selection_ranges);
 7557        });
 7558    }
 7559
 7560    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7561        self.add_selection(true, cx);
 7562    }
 7563
 7564    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7565        self.add_selection(false, cx);
 7566    }
 7567
 7568    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7569        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7570        let mut selections = self.selections.all::<Point>(cx);
 7571        let text_layout_details = self.text_layout_details(cx);
 7572        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7573            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7574            let range = oldest_selection.display_range(&display_map).sorted();
 7575
 7576            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7577            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7578            let positions = start_x.min(end_x)..start_x.max(end_x);
 7579
 7580            selections.clear();
 7581            let mut stack = Vec::new();
 7582            for row in range.start.row().0..=range.end.row().0 {
 7583                if let Some(selection) = self.selections.build_columnar_selection(
 7584                    &display_map,
 7585                    DisplayRow(row),
 7586                    &positions,
 7587                    oldest_selection.reversed,
 7588                    &text_layout_details,
 7589                ) {
 7590                    stack.push(selection.id);
 7591                    selections.push(selection);
 7592                }
 7593            }
 7594
 7595            if above {
 7596                stack.reverse();
 7597            }
 7598
 7599            AddSelectionsState { above, stack }
 7600        });
 7601
 7602        let last_added_selection = *state.stack.last().unwrap();
 7603        let mut new_selections = Vec::new();
 7604        if above == state.above {
 7605            let end_row = if above {
 7606                DisplayRow(0)
 7607            } else {
 7608                display_map.max_point().row()
 7609            };
 7610
 7611            'outer: for selection in selections {
 7612                if selection.id == last_added_selection {
 7613                    let range = selection.display_range(&display_map).sorted();
 7614                    debug_assert_eq!(range.start.row(), range.end.row());
 7615                    let mut row = range.start.row();
 7616                    let positions =
 7617                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7618                            px(start)..px(end)
 7619                        } else {
 7620                            let start_x =
 7621                                display_map.x_for_display_point(range.start, &text_layout_details);
 7622                            let end_x =
 7623                                display_map.x_for_display_point(range.end, &text_layout_details);
 7624                            start_x.min(end_x)..start_x.max(end_x)
 7625                        };
 7626
 7627                    while row != end_row {
 7628                        if above {
 7629                            row.0 -= 1;
 7630                        } else {
 7631                            row.0 += 1;
 7632                        }
 7633
 7634                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7635                            &display_map,
 7636                            row,
 7637                            &positions,
 7638                            selection.reversed,
 7639                            &text_layout_details,
 7640                        ) {
 7641                            state.stack.push(new_selection.id);
 7642                            if above {
 7643                                new_selections.push(new_selection);
 7644                                new_selections.push(selection);
 7645                            } else {
 7646                                new_selections.push(selection);
 7647                                new_selections.push(new_selection);
 7648                            }
 7649
 7650                            continue 'outer;
 7651                        }
 7652                    }
 7653                }
 7654
 7655                new_selections.push(selection);
 7656            }
 7657        } else {
 7658            new_selections = selections;
 7659            new_selections.retain(|s| s.id != last_added_selection);
 7660            state.stack.pop();
 7661        }
 7662
 7663        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7664            s.select(new_selections);
 7665        });
 7666        if state.stack.len() > 1 {
 7667            self.add_selections_state = Some(state);
 7668        }
 7669    }
 7670
 7671    pub fn select_next_match_internal(
 7672        &mut self,
 7673        display_map: &DisplaySnapshot,
 7674        replace_newest: bool,
 7675        autoscroll: Option<Autoscroll>,
 7676        cx: &mut ViewContext<Self>,
 7677    ) -> Result<()> {
 7678        fn select_next_match_ranges(
 7679            this: &mut Editor,
 7680            range: Range<usize>,
 7681            replace_newest: bool,
 7682            auto_scroll: Option<Autoscroll>,
 7683            cx: &mut ViewContext<Editor>,
 7684        ) {
 7685            this.unfold_ranges([range.clone()], false, true, cx);
 7686            this.change_selections(auto_scroll, cx, |s| {
 7687                if replace_newest {
 7688                    s.delete(s.newest_anchor().id);
 7689                }
 7690                s.insert_range(range.clone());
 7691            });
 7692        }
 7693
 7694        let buffer = &display_map.buffer_snapshot;
 7695        let mut selections = self.selections.all::<usize>(cx);
 7696        if let Some(mut select_next_state) = self.select_next_state.take() {
 7697            let query = &select_next_state.query;
 7698            if !select_next_state.done {
 7699                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7700                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7701                let mut next_selected_range = None;
 7702
 7703                let bytes_after_last_selection =
 7704                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7705                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7706                let query_matches = query
 7707                    .stream_find_iter(bytes_after_last_selection)
 7708                    .map(|result| (last_selection.end, result))
 7709                    .chain(
 7710                        query
 7711                            .stream_find_iter(bytes_before_first_selection)
 7712                            .map(|result| (0, result)),
 7713                    );
 7714
 7715                for (start_offset, query_match) in query_matches {
 7716                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7717                    let offset_range =
 7718                        start_offset + query_match.start()..start_offset + query_match.end();
 7719                    let display_range = offset_range.start.to_display_point(&display_map)
 7720                        ..offset_range.end.to_display_point(&display_map);
 7721
 7722                    if !select_next_state.wordwise
 7723                        || (!movement::is_inside_word(&display_map, display_range.start)
 7724                            && !movement::is_inside_word(&display_map, display_range.end))
 7725                    {
 7726                        // TODO: This is n^2, because we might check all the selections
 7727                        if !selections
 7728                            .iter()
 7729                            .any(|selection| selection.range().overlaps(&offset_range))
 7730                        {
 7731                            next_selected_range = Some(offset_range);
 7732                            break;
 7733                        }
 7734                    }
 7735                }
 7736
 7737                if let Some(next_selected_range) = next_selected_range {
 7738                    select_next_match_ranges(
 7739                        self,
 7740                        next_selected_range,
 7741                        replace_newest,
 7742                        autoscroll,
 7743                        cx,
 7744                    );
 7745                } else {
 7746                    select_next_state.done = true;
 7747                }
 7748            }
 7749
 7750            self.select_next_state = Some(select_next_state);
 7751        } else {
 7752            let mut only_carets = true;
 7753            let mut same_text_selected = true;
 7754            let mut selected_text = None;
 7755
 7756            let mut selections_iter = selections.iter().peekable();
 7757            while let Some(selection) = selections_iter.next() {
 7758                if selection.start != selection.end {
 7759                    only_carets = false;
 7760                }
 7761
 7762                if same_text_selected {
 7763                    if selected_text.is_none() {
 7764                        selected_text =
 7765                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7766                    }
 7767
 7768                    if let Some(next_selection) = selections_iter.peek() {
 7769                        if next_selection.range().len() == selection.range().len() {
 7770                            let next_selected_text = buffer
 7771                                .text_for_range(next_selection.range())
 7772                                .collect::<String>();
 7773                            if Some(next_selected_text) != selected_text {
 7774                                same_text_selected = false;
 7775                                selected_text = None;
 7776                            }
 7777                        } else {
 7778                            same_text_selected = false;
 7779                            selected_text = None;
 7780                        }
 7781                    }
 7782                }
 7783            }
 7784
 7785            if only_carets {
 7786                for selection in &mut selections {
 7787                    let word_range = movement::surrounding_word(
 7788                        &display_map,
 7789                        selection.start.to_display_point(&display_map),
 7790                    );
 7791                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7792                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7793                    selection.goal = SelectionGoal::None;
 7794                    selection.reversed = false;
 7795                    select_next_match_ranges(
 7796                        self,
 7797                        selection.start..selection.end,
 7798                        replace_newest,
 7799                        autoscroll,
 7800                        cx,
 7801                    );
 7802                }
 7803
 7804                if selections.len() == 1 {
 7805                    let selection = selections
 7806                        .last()
 7807                        .expect("ensured that there's only one selection");
 7808                    let query = buffer
 7809                        .text_for_range(selection.start..selection.end)
 7810                        .collect::<String>();
 7811                    let is_empty = query.is_empty();
 7812                    let select_state = SelectNextState {
 7813                        query: AhoCorasick::new(&[query])?,
 7814                        wordwise: true,
 7815                        done: is_empty,
 7816                    };
 7817                    self.select_next_state = Some(select_state);
 7818                } else {
 7819                    self.select_next_state = None;
 7820                }
 7821            } else if let Some(selected_text) = selected_text {
 7822                self.select_next_state = Some(SelectNextState {
 7823                    query: AhoCorasick::new(&[selected_text])?,
 7824                    wordwise: false,
 7825                    done: false,
 7826                });
 7827                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 7828            }
 7829        }
 7830        Ok(())
 7831    }
 7832
 7833    pub fn select_all_matches(
 7834        &mut self,
 7835        _action: &SelectAllMatches,
 7836        cx: &mut ViewContext<Self>,
 7837    ) -> Result<()> {
 7838        self.push_to_selection_history();
 7839        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7840
 7841        self.select_next_match_internal(&display_map, false, None, cx)?;
 7842        let Some(select_next_state) = self.select_next_state.as_mut() else {
 7843            return Ok(());
 7844        };
 7845        if select_next_state.done {
 7846            return Ok(());
 7847        }
 7848
 7849        let mut new_selections = self.selections.all::<usize>(cx);
 7850
 7851        let buffer = &display_map.buffer_snapshot;
 7852        let query_matches = select_next_state
 7853            .query
 7854            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 7855
 7856        for query_match in query_matches {
 7857            let query_match = query_match.unwrap(); // can only fail due to I/O
 7858            let offset_range = query_match.start()..query_match.end();
 7859            let display_range = offset_range.start.to_display_point(&display_map)
 7860                ..offset_range.end.to_display_point(&display_map);
 7861
 7862            if !select_next_state.wordwise
 7863                || (!movement::is_inside_word(&display_map, display_range.start)
 7864                    && !movement::is_inside_word(&display_map, display_range.end))
 7865            {
 7866                self.selections.change_with(cx, |selections| {
 7867                    new_selections.push(Selection {
 7868                        id: selections.new_selection_id(),
 7869                        start: offset_range.start,
 7870                        end: offset_range.end,
 7871                        reversed: false,
 7872                        goal: SelectionGoal::None,
 7873                    });
 7874                });
 7875            }
 7876        }
 7877
 7878        new_selections.sort_by_key(|selection| selection.start);
 7879        let mut ix = 0;
 7880        while ix + 1 < new_selections.len() {
 7881            let current_selection = &new_selections[ix];
 7882            let next_selection = &new_selections[ix + 1];
 7883            if current_selection.range().overlaps(&next_selection.range()) {
 7884                if current_selection.id < next_selection.id {
 7885                    new_selections.remove(ix + 1);
 7886                } else {
 7887                    new_selections.remove(ix);
 7888                }
 7889            } else {
 7890                ix += 1;
 7891            }
 7892        }
 7893
 7894        select_next_state.done = true;
 7895        self.unfold_ranges(
 7896            new_selections.iter().map(|selection| selection.range()),
 7897            false,
 7898            false,
 7899            cx,
 7900        );
 7901        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 7902            selections.select(new_selections)
 7903        });
 7904
 7905        Ok(())
 7906    }
 7907
 7908    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 7909        self.push_to_selection_history();
 7910        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7911        self.select_next_match_internal(
 7912            &display_map,
 7913            action.replace_newest,
 7914            Some(Autoscroll::newest()),
 7915            cx,
 7916        )?;
 7917        Ok(())
 7918    }
 7919
 7920    pub fn select_previous(
 7921        &mut self,
 7922        action: &SelectPrevious,
 7923        cx: &mut ViewContext<Self>,
 7924    ) -> Result<()> {
 7925        self.push_to_selection_history();
 7926        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7927        let buffer = &display_map.buffer_snapshot;
 7928        let mut selections = self.selections.all::<usize>(cx);
 7929        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 7930            let query = &select_prev_state.query;
 7931            if !select_prev_state.done {
 7932                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7933                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7934                let mut next_selected_range = None;
 7935                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 7936                let bytes_before_last_selection =
 7937                    buffer.reversed_bytes_in_range(0..last_selection.start);
 7938                let bytes_after_first_selection =
 7939                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 7940                let query_matches = query
 7941                    .stream_find_iter(bytes_before_last_selection)
 7942                    .map(|result| (last_selection.start, result))
 7943                    .chain(
 7944                        query
 7945                            .stream_find_iter(bytes_after_first_selection)
 7946                            .map(|result| (buffer.len(), result)),
 7947                    );
 7948                for (end_offset, query_match) in query_matches {
 7949                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7950                    let offset_range =
 7951                        end_offset - query_match.end()..end_offset - query_match.start();
 7952                    let display_range = offset_range.start.to_display_point(&display_map)
 7953                        ..offset_range.end.to_display_point(&display_map);
 7954
 7955                    if !select_prev_state.wordwise
 7956                        || (!movement::is_inside_word(&display_map, display_range.start)
 7957                            && !movement::is_inside_word(&display_map, display_range.end))
 7958                    {
 7959                        next_selected_range = Some(offset_range);
 7960                        break;
 7961                    }
 7962                }
 7963
 7964                if let Some(next_selected_range) = next_selected_range {
 7965                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 7966                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7967                        if action.replace_newest {
 7968                            s.delete(s.newest_anchor().id);
 7969                        }
 7970                        s.insert_range(next_selected_range);
 7971                    });
 7972                } else {
 7973                    select_prev_state.done = true;
 7974                }
 7975            }
 7976
 7977            self.select_prev_state = Some(select_prev_state);
 7978        } else {
 7979            let mut only_carets = true;
 7980            let mut same_text_selected = true;
 7981            let mut selected_text = None;
 7982
 7983            let mut selections_iter = selections.iter().peekable();
 7984            while let Some(selection) = selections_iter.next() {
 7985                if selection.start != selection.end {
 7986                    only_carets = false;
 7987                }
 7988
 7989                if same_text_selected {
 7990                    if selected_text.is_none() {
 7991                        selected_text =
 7992                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7993                    }
 7994
 7995                    if let Some(next_selection) = selections_iter.peek() {
 7996                        if next_selection.range().len() == selection.range().len() {
 7997                            let next_selected_text = buffer
 7998                                .text_for_range(next_selection.range())
 7999                                .collect::<String>();
 8000                            if Some(next_selected_text) != selected_text {
 8001                                same_text_selected = false;
 8002                                selected_text = None;
 8003                            }
 8004                        } else {
 8005                            same_text_selected = false;
 8006                            selected_text = None;
 8007                        }
 8008                    }
 8009                }
 8010            }
 8011
 8012            if only_carets {
 8013                for selection in &mut selections {
 8014                    let word_range = movement::surrounding_word(
 8015                        &display_map,
 8016                        selection.start.to_display_point(&display_map),
 8017                    );
 8018                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8019                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8020                    selection.goal = SelectionGoal::None;
 8021                    selection.reversed = false;
 8022                }
 8023                if selections.len() == 1 {
 8024                    let selection = selections
 8025                        .last()
 8026                        .expect("ensured that there's only one selection");
 8027                    let query = buffer
 8028                        .text_for_range(selection.start..selection.end)
 8029                        .collect::<String>();
 8030                    let is_empty = query.is_empty();
 8031                    let select_state = SelectNextState {
 8032                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8033                        wordwise: true,
 8034                        done: is_empty,
 8035                    };
 8036                    self.select_prev_state = Some(select_state);
 8037                } else {
 8038                    self.select_prev_state = None;
 8039                }
 8040
 8041                self.unfold_ranges(
 8042                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8043                    false,
 8044                    true,
 8045                    cx,
 8046                );
 8047                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8048                    s.select(selections);
 8049                });
 8050            } else if let Some(selected_text) = selected_text {
 8051                self.select_prev_state = Some(SelectNextState {
 8052                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8053                    wordwise: false,
 8054                    done: false,
 8055                });
 8056                self.select_previous(action, cx)?;
 8057            }
 8058        }
 8059        Ok(())
 8060    }
 8061
 8062    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8063        let text_layout_details = &self.text_layout_details(cx);
 8064        self.transact(cx, |this, cx| {
 8065            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8066            let mut edits = Vec::new();
 8067            let mut selection_edit_ranges = Vec::new();
 8068            let mut last_toggled_row = None;
 8069            let snapshot = this.buffer.read(cx).read(cx);
 8070            let empty_str: Arc<str> = "".into();
 8071            let mut suffixes_inserted = Vec::new();
 8072
 8073            fn comment_prefix_range(
 8074                snapshot: &MultiBufferSnapshot,
 8075                row: MultiBufferRow,
 8076                comment_prefix: &str,
 8077                comment_prefix_whitespace: &str,
 8078            ) -> Range<Point> {
 8079                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8080
 8081                let mut line_bytes = snapshot
 8082                    .bytes_in_range(start..snapshot.max_point())
 8083                    .flatten()
 8084                    .copied();
 8085
 8086                // If this line currently begins with the line comment prefix, then record
 8087                // the range containing the prefix.
 8088                if line_bytes
 8089                    .by_ref()
 8090                    .take(comment_prefix.len())
 8091                    .eq(comment_prefix.bytes())
 8092                {
 8093                    // Include any whitespace that matches the comment prefix.
 8094                    let matching_whitespace_len = line_bytes
 8095                        .zip(comment_prefix_whitespace.bytes())
 8096                        .take_while(|(a, b)| a == b)
 8097                        .count() as u32;
 8098                    let end = Point::new(
 8099                        start.row,
 8100                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8101                    );
 8102                    start..end
 8103                } else {
 8104                    start..start
 8105                }
 8106            }
 8107
 8108            fn comment_suffix_range(
 8109                snapshot: &MultiBufferSnapshot,
 8110                row: MultiBufferRow,
 8111                comment_suffix: &str,
 8112                comment_suffix_has_leading_space: bool,
 8113            ) -> Range<Point> {
 8114                let end = Point::new(row.0, snapshot.line_len(row));
 8115                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8116
 8117                let mut line_end_bytes = snapshot
 8118                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8119                    .flatten()
 8120                    .copied();
 8121
 8122                let leading_space_len = if suffix_start_column > 0
 8123                    && line_end_bytes.next() == Some(b' ')
 8124                    && comment_suffix_has_leading_space
 8125                {
 8126                    1
 8127                } else {
 8128                    0
 8129                };
 8130
 8131                // If this line currently begins with the line comment prefix, then record
 8132                // the range containing the prefix.
 8133                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8134                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8135                    start..end
 8136                } else {
 8137                    end..end
 8138                }
 8139            }
 8140
 8141            // TODO: Handle selections that cross excerpts
 8142            for selection in &mut selections {
 8143                let start_column = snapshot
 8144                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8145                    .len;
 8146                let language = if let Some(language) =
 8147                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8148                {
 8149                    language
 8150                } else {
 8151                    continue;
 8152                };
 8153
 8154                selection_edit_ranges.clear();
 8155
 8156                // If multiple selections contain a given row, avoid processing that
 8157                // row more than once.
 8158                let mut start_row = MultiBufferRow(selection.start.row);
 8159                if last_toggled_row == Some(start_row) {
 8160                    start_row = start_row.next_row();
 8161                }
 8162                let end_row =
 8163                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8164                        MultiBufferRow(selection.end.row - 1)
 8165                    } else {
 8166                        MultiBufferRow(selection.end.row)
 8167                    };
 8168                last_toggled_row = Some(end_row);
 8169
 8170                if start_row > end_row {
 8171                    continue;
 8172                }
 8173
 8174                // If the language has line comments, toggle those.
 8175                let full_comment_prefixes = language.line_comment_prefixes();
 8176                if !full_comment_prefixes.is_empty() {
 8177                    let first_prefix = full_comment_prefixes
 8178                        .first()
 8179                        .expect("prefixes is non-empty");
 8180                    let prefix_trimmed_lengths = full_comment_prefixes
 8181                        .iter()
 8182                        .map(|p| p.trim_end_matches(' ').len())
 8183                        .collect::<SmallVec<[usize; 4]>>();
 8184
 8185                    let mut all_selection_lines_are_comments = true;
 8186
 8187                    for row in start_row.0..=end_row.0 {
 8188                        let row = MultiBufferRow(row);
 8189                        if start_row < end_row && snapshot.is_line_blank(row) {
 8190                            continue;
 8191                        }
 8192
 8193                        let prefix_range = full_comment_prefixes
 8194                            .iter()
 8195                            .zip(prefix_trimmed_lengths.iter().copied())
 8196                            .map(|(prefix, trimmed_prefix_len)| {
 8197                                comment_prefix_range(
 8198                                    snapshot.deref(),
 8199                                    row,
 8200                                    &prefix[..trimmed_prefix_len],
 8201                                    &prefix[trimmed_prefix_len..],
 8202                                )
 8203                            })
 8204                            .max_by_key(|range| range.end.column - range.start.column)
 8205                            .expect("prefixes is non-empty");
 8206
 8207                        if prefix_range.is_empty() {
 8208                            all_selection_lines_are_comments = false;
 8209                        }
 8210
 8211                        selection_edit_ranges.push(prefix_range);
 8212                    }
 8213
 8214                    if all_selection_lines_are_comments {
 8215                        edits.extend(
 8216                            selection_edit_ranges
 8217                                .iter()
 8218                                .cloned()
 8219                                .map(|range| (range, empty_str.clone())),
 8220                        );
 8221                    } else {
 8222                        let min_column = selection_edit_ranges
 8223                            .iter()
 8224                            .map(|range| range.start.column)
 8225                            .min()
 8226                            .unwrap_or(0);
 8227                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8228                            let position = Point::new(range.start.row, min_column);
 8229                            (position..position, first_prefix.clone())
 8230                        }));
 8231                    }
 8232                } else if let Some((full_comment_prefix, comment_suffix)) =
 8233                    language.block_comment_delimiters()
 8234                {
 8235                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8236                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8237                    let prefix_range = comment_prefix_range(
 8238                        snapshot.deref(),
 8239                        start_row,
 8240                        comment_prefix,
 8241                        comment_prefix_whitespace,
 8242                    );
 8243                    let suffix_range = comment_suffix_range(
 8244                        snapshot.deref(),
 8245                        end_row,
 8246                        comment_suffix.trim_start_matches(' '),
 8247                        comment_suffix.starts_with(' '),
 8248                    );
 8249
 8250                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8251                        edits.push((
 8252                            prefix_range.start..prefix_range.start,
 8253                            full_comment_prefix.clone(),
 8254                        ));
 8255                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8256                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8257                    } else {
 8258                        edits.push((prefix_range, empty_str.clone()));
 8259                        edits.push((suffix_range, empty_str.clone()));
 8260                    }
 8261                } else {
 8262                    continue;
 8263                }
 8264            }
 8265
 8266            drop(snapshot);
 8267            this.buffer.update(cx, |buffer, cx| {
 8268                buffer.edit(edits, None, cx);
 8269            });
 8270
 8271            // Adjust selections so that they end before any comment suffixes that
 8272            // were inserted.
 8273            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8274            let mut selections = this.selections.all::<Point>(cx);
 8275            let snapshot = this.buffer.read(cx).read(cx);
 8276            for selection in &mut selections {
 8277                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8278                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8279                        Ordering::Less => {
 8280                            suffixes_inserted.next();
 8281                            continue;
 8282                        }
 8283                        Ordering::Greater => break,
 8284                        Ordering::Equal => {
 8285                            if selection.end.column == snapshot.line_len(row) {
 8286                                if selection.is_empty() {
 8287                                    selection.start.column -= suffix_len as u32;
 8288                                }
 8289                                selection.end.column -= suffix_len as u32;
 8290                            }
 8291                            break;
 8292                        }
 8293                    }
 8294                }
 8295            }
 8296
 8297            drop(snapshot);
 8298            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8299
 8300            let selections = this.selections.all::<Point>(cx);
 8301            let selections_on_single_row = selections.windows(2).all(|selections| {
 8302                selections[0].start.row == selections[1].start.row
 8303                    && selections[0].end.row == selections[1].end.row
 8304                    && selections[0].start.row == selections[0].end.row
 8305            });
 8306            let selections_selecting = selections
 8307                .iter()
 8308                .any(|selection| selection.start != selection.end);
 8309            let advance_downwards = action.advance_downwards
 8310                && selections_on_single_row
 8311                && !selections_selecting
 8312                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8313
 8314            if advance_downwards {
 8315                let snapshot = this.buffer.read(cx).snapshot(cx);
 8316
 8317                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8318                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8319                        let mut point = display_point.to_point(display_snapshot);
 8320                        point.row += 1;
 8321                        point = snapshot.clip_point(point, Bias::Left);
 8322                        let display_point = point.to_display_point(display_snapshot);
 8323                        let goal = SelectionGoal::HorizontalPosition(
 8324                            display_snapshot
 8325                                .x_for_display_point(display_point, &text_layout_details)
 8326                                .into(),
 8327                        );
 8328                        (display_point, goal)
 8329                    })
 8330                });
 8331            }
 8332        });
 8333    }
 8334
 8335    pub fn select_enclosing_symbol(
 8336        &mut self,
 8337        _: &SelectEnclosingSymbol,
 8338        cx: &mut ViewContext<Self>,
 8339    ) {
 8340        let buffer = self.buffer.read(cx).snapshot(cx);
 8341        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8342
 8343        fn update_selection(
 8344            selection: &Selection<usize>,
 8345            buffer_snap: &MultiBufferSnapshot,
 8346        ) -> Option<Selection<usize>> {
 8347            let cursor = selection.head();
 8348            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8349            for symbol in symbols.iter().rev() {
 8350                let start = symbol.range.start.to_offset(&buffer_snap);
 8351                let end = symbol.range.end.to_offset(&buffer_snap);
 8352                let new_range = start..end;
 8353                if start < selection.start || end > selection.end {
 8354                    return Some(Selection {
 8355                        id: selection.id,
 8356                        start: new_range.start,
 8357                        end: new_range.end,
 8358                        goal: SelectionGoal::None,
 8359                        reversed: selection.reversed,
 8360                    });
 8361                }
 8362            }
 8363            None
 8364        }
 8365
 8366        let mut selected_larger_symbol = false;
 8367        let new_selections = old_selections
 8368            .iter()
 8369            .map(|selection| match update_selection(selection, &buffer) {
 8370                Some(new_selection) => {
 8371                    if new_selection.range() != selection.range() {
 8372                        selected_larger_symbol = true;
 8373                    }
 8374                    new_selection
 8375                }
 8376                None => selection.clone(),
 8377            })
 8378            .collect::<Vec<_>>();
 8379
 8380        if selected_larger_symbol {
 8381            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8382                s.select(new_selections);
 8383            });
 8384        }
 8385    }
 8386
 8387    pub fn select_larger_syntax_node(
 8388        &mut self,
 8389        _: &SelectLargerSyntaxNode,
 8390        cx: &mut ViewContext<Self>,
 8391    ) {
 8392        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8393        let buffer = self.buffer.read(cx).snapshot(cx);
 8394        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8395
 8396        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8397        let mut selected_larger_node = false;
 8398        let new_selections = old_selections
 8399            .iter()
 8400            .map(|selection| {
 8401                let old_range = selection.start..selection.end;
 8402                let mut new_range = old_range.clone();
 8403                while let Some(containing_range) =
 8404                    buffer.range_for_syntax_ancestor(new_range.clone())
 8405                {
 8406                    new_range = containing_range;
 8407                    if !display_map.intersects_fold(new_range.start)
 8408                        && !display_map.intersects_fold(new_range.end)
 8409                    {
 8410                        break;
 8411                    }
 8412                }
 8413
 8414                selected_larger_node |= new_range != old_range;
 8415                Selection {
 8416                    id: selection.id,
 8417                    start: new_range.start,
 8418                    end: new_range.end,
 8419                    goal: SelectionGoal::None,
 8420                    reversed: selection.reversed,
 8421                }
 8422            })
 8423            .collect::<Vec<_>>();
 8424
 8425        if selected_larger_node {
 8426            stack.push(old_selections);
 8427            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8428                s.select(new_selections);
 8429            });
 8430        }
 8431        self.select_larger_syntax_node_stack = stack;
 8432    }
 8433
 8434    pub fn select_smaller_syntax_node(
 8435        &mut self,
 8436        _: &SelectSmallerSyntaxNode,
 8437        cx: &mut ViewContext<Self>,
 8438    ) {
 8439        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8440        if let Some(selections) = stack.pop() {
 8441            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8442                s.select(selections.to_vec());
 8443            });
 8444        }
 8445        self.select_larger_syntax_node_stack = stack;
 8446    }
 8447
 8448    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8449        if !EditorSettings::get_global(cx).gutter.runnables {
 8450            self.clear_tasks();
 8451            return Task::ready(());
 8452        }
 8453        let project = self.project.clone();
 8454        cx.spawn(|this, mut cx| async move {
 8455            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8456                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8457            }) else {
 8458                return;
 8459            };
 8460
 8461            let Some(project) = project else {
 8462                return;
 8463            };
 8464
 8465            let hide_runnables = project
 8466                .update(&mut cx, |project, cx| {
 8467                    // Do not display any test indicators in non-dev server remote projects.
 8468                    project.is_remote() && project.ssh_connection_string(cx).is_none()
 8469                })
 8470                .unwrap_or(true);
 8471            if hide_runnables {
 8472                return;
 8473            }
 8474            let new_rows =
 8475                cx.background_executor()
 8476                    .spawn({
 8477                        let snapshot = display_snapshot.clone();
 8478                        async move {
 8479                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8480                        }
 8481                    })
 8482                    .await;
 8483            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8484
 8485            this.update(&mut cx, |this, _| {
 8486                this.clear_tasks();
 8487                for (key, value) in rows {
 8488                    this.insert_tasks(key, value);
 8489                }
 8490            })
 8491            .ok();
 8492        })
 8493    }
 8494    fn fetch_runnable_ranges(
 8495        snapshot: &DisplaySnapshot,
 8496        range: Range<Anchor>,
 8497    ) -> Vec<language::RunnableRange> {
 8498        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8499    }
 8500
 8501    fn runnable_rows(
 8502        project: Model<Project>,
 8503        snapshot: DisplaySnapshot,
 8504        runnable_ranges: Vec<RunnableRange>,
 8505        mut cx: AsyncWindowContext,
 8506    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8507        runnable_ranges
 8508            .into_iter()
 8509            .filter_map(|mut runnable| {
 8510                let tasks = cx
 8511                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8512                    .ok()?;
 8513                if tasks.is_empty() {
 8514                    return None;
 8515                }
 8516
 8517                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8518
 8519                let row = snapshot
 8520                    .buffer_snapshot
 8521                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8522                    .1
 8523                    .start
 8524                    .row;
 8525
 8526                let context_range =
 8527                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8528                Some((
 8529                    (runnable.buffer_id, row),
 8530                    RunnableTasks {
 8531                        templates: tasks,
 8532                        offset: MultiBufferOffset(runnable.run_range.start),
 8533                        context_range,
 8534                        column: point.column,
 8535                        extra_variables: runnable.extra_captures,
 8536                    },
 8537                ))
 8538            })
 8539            .collect()
 8540    }
 8541
 8542    fn templates_with_tags(
 8543        project: &Model<Project>,
 8544        runnable: &mut Runnable,
 8545        cx: &WindowContext<'_>,
 8546    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8547        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8548            let (worktree_id, file) = project
 8549                .buffer_for_id(runnable.buffer, cx)
 8550                .and_then(|buffer| buffer.read(cx).file())
 8551                .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
 8552                .unzip();
 8553
 8554            (project.task_inventory().clone(), worktree_id, file)
 8555        });
 8556
 8557        let inventory = inventory.read(cx);
 8558        let tags = mem::take(&mut runnable.tags);
 8559        let mut tags: Vec<_> = tags
 8560            .into_iter()
 8561            .flat_map(|tag| {
 8562                let tag = tag.0.clone();
 8563                inventory
 8564                    .list_tasks(
 8565                        file.clone(),
 8566                        Some(runnable.language.clone()),
 8567                        worktree_id,
 8568                        cx,
 8569                    )
 8570                    .into_iter()
 8571                    .filter(move |(_, template)| {
 8572                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8573                    })
 8574            })
 8575            .sorted_by_key(|(kind, _)| kind.to_owned())
 8576            .collect();
 8577        if let Some((leading_tag_source, _)) = tags.first() {
 8578            // Strongest source wins; if we have worktree tag binding, prefer that to
 8579            // global and language bindings;
 8580            // if we have a global binding, prefer that to language binding.
 8581            let first_mismatch = tags
 8582                .iter()
 8583                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8584            if let Some(index) = first_mismatch {
 8585                tags.truncate(index);
 8586            }
 8587        }
 8588
 8589        tags
 8590    }
 8591
 8592    pub fn move_to_enclosing_bracket(
 8593        &mut self,
 8594        _: &MoveToEnclosingBracket,
 8595        cx: &mut ViewContext<Self>,
 8596    ) {
 8597        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8598            s.move_offsets_with(|snapshot, selection| {
 8599                let Some(enclosing_bracket_ranges) =
 8600                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8601                else {
 8602                    return;
 8603                };
 8604
 8605                let mut best_length = usize::MAX;
 8606                let mut best_inside = false;
 8607                let mut best_in_bracket_range = false;
 8608                let mut best_destination = None;
 8609                for (open, close) in enclosing_bracket_ranges {
 8610                    let close = close.to_inclusive();
 8611                    let length = close.end() - open.start;
 8612                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8613                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8614                        || close.contains(&selection.head());
 8615
 8616                    // If best is next to a bracket and current isn't, skip
 8617                    if !in_bracket_range && best_in_bracket_range {
 8618                        continue;
 8619                    }
 8620
 8621                    // Prefer smaller lengths unless best is inside and current isn't
 8622                    if length > best_length && (best_inside || !inside) {
 8623                        continue;
 8624                    }
 8625
 8626                    best_length = length;
 8627                    best_inside = inside;
 8628                    best_in_bracket_range = in_bracket_range;
 8629                    best_destination = Some(
 8630                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8631                            if inside {
 8632                                open.end
 8633                            } else {
 8634                                open.start
 8635                            }
 8636                        } else {
 8637                            if inside {
 8638                                *close.start()
 8639                            } else {
 8640                                *close.end()
 8641                            }
 8642                        },
 8643                    );
 8644                }
 8645
 8646                if let Some(destination) = best_destination {
 8647                    selection.collapse_to(destination, SelectionGoal::None);
 8648                }
 8649            })
 8650        });
 8651    }
 8652
 8653    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 8654        self.end_selection(cx);
 8655        self.selection_history.mode = SelectionHistoryMode::Undoing;
 8656        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 8657            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8658            self.select_next_state = entry.select_next_state;
 8659            self.select_prev_state = entry.select_prev_state;
 8660            self.add_selections_state = entry.add_selections_state;
 8661            self.request_autoscroll(Autoscroll::newest(), cx);
 8662        }
 8663        self.selection_history.mode = SelectionHistoryMode::Normal;
 8664    }
 8665
 8666    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 8667        self.end_selection(cx);
 8668        self.selection_history.mode = SelectionHistoryMode::Redoing;
 8669        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 8670            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8671            self.select_next_state = entry.select_next_state;
 8672            self.select_prev_state = entry.select_prev_state;
 8673            self.add_selections_state = entry.add_selections_state;
 8674            self.request_autoscroll(Autoscroll::newest(), cx);
 8675        }
 8676        self.selection_history.mode = SelectionHistoryMode::Normal;
 8677    }
 8678
 8679    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 8680        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 8681    }
 8682
 8683    pub fn expand_excerpts_down(
 8684        &mut self,
 8685        action: &ExpandExcerptsDown,
 8686        cx: &mut ViewContext<Self>,
 8687    ) {
 8688        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 8689    }
 8690
 8691    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 8692        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 8693    }
 8694
 8695    pub fn expand_excerpts_for_direction(
 8696        &mut self,
 8697        lines: u32,
 8698        direction: ExpandExcerptDirection,
 8699        cx: &mut ViewContext<Self>,
 8700    ) {
 8701        let selections = self.selections.disjoint_anchors();
 8702
 8703        let lines = if lines == 0 {
 8704            EditorSettings::get_global(cx).expand_excerpt_lines
 8705        } else {
 8706            lines
 8707        };
 8708
 8709        self.buffer.update(cx, |buffer, cx| {
 8710            buffer.expand_excerpts(
 8711                selections
 8712                    .into_iter()
 8713                    .map(|selection| selection.head().excerpt_id)
 8714                    .dedup(),
 8715                lines,
 8716                direction,
 8717                cx,
 8718            )
 8719        })
 8720    }
 8721
 8722    pub fn expand_excerpt(
 8723        &mut self,
 8724        excerpt: ExcerptId,
 8725        direction: ExpandExcerptDirection,
 8726        cx: &mut ViewContext<Self>,
 8727    ) {
 8728        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 8729        self.buffer.update(cx, |buffer, cx| {
 8730            buffer.expand_excerpts([excerpt], lines, direction, cx)
 8731        })
 8732    }
 8733
 8734    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8735        self.go_to_diagnostic_impl(Direction::Next, cx)
 8736    }
 8737
 8738    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8739        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8740    }
 8741
 8742    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8743        let buffer = self.buffer.read(cx).snapshot(cx);
 8744        let selection = self.selections.newest::<usize>(cx);
 8745
 8746        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8747        if direction == Direction::Next {
 8748            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8749                let (group_id, jump_to) = popover.activation_info();
 8750                if self.activate_diagnostics(group_id, cx) {
 8751                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8752                        let mut new_selection = s.newest_anchor().clone();
 8753                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 8754                        s.select_anchors(vec![new_selection.clone()]);
 8755                    });
 8756                }
 8757                return;
 8758            }
 8759        }
 8760
 8761        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 8762            active_diagnostics
 8763                .primary_range
 8764                .to_offset(&buffer)
 8765                .to_inclusive()
 8766        });
 8767        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 8768            if active_primary_range.contains(&selection.head()) {
 8769                *active_primary_range.start()
 8770            } else {
 8771                selection.head()
 8772            }
 8773        } else {
 8774            selection.head()
 8775        };
 8776        let snapshot = self.snapshot(cx);
 8777        loop {
 8778            let diagnostics = if direction == Direction::Prev {
 8779                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 8780            } else {
 8781                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 8782            }
 8783            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 8784            let group = diagnostics
 8785                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 8786                // be sorted in a stable way
 8787                // skip until we are at current active diagnostic, if it exists
 8788                .skip_while(|entry| {
 8789                    (match direction {
 8790                        Direction::Prev => entry.range.start >= search_start,
 8791                        Direction::Next => entry.range.start <= search_start,
 8792                    }) && self
 8793                        .active_diagnostics
 8794                        .as_ref()
 8795                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 8796                })
 8797                .find_map(|entry| {
 8798                    if entry.diagnostic.is_primary
 8799                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 8800                        && !entry.range.is_empty()
 8801                        // if we match with the active diagnostic, skip it
 8802                        && Some(entry.diagnostic.group_id)
 8803                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 8804                    {
 8805                        Some((entry.range, entry.diagnostic.group_id))
 8806                    } else {
 8807                        None
 8808                    }
 8809                });
 8810
 8811            if let Some((primary_range, group_id)) = group {
 8812                if self.activate_diagnostics(group_id, cx) {
 8813                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8814                        s.select(vec![Selection {
 8815                            id: selection.id,
 8816                            start: primary_range.start,
 8817                            end: primary_range.start,
 8818                            reversed: false,
 8819                            goal: SelectionGoal::None,
 8820                        }]);
 8821                    });
 8822                }
 8823                break;
 8824            } else {
 8825                // Cycle around to the start of the buffer, potentially moving back to the start of
 8826                // the currently active diagnostic.
 8827                active_primary_range.take();
 8828                if direction == Direction::Prev {
 8829                    if search_start == buffer.len() {
 8830                        break;
 8831                    } else {
 8832                        search_start = buffer.len();
 8833                    }
 8834                } else if search_start == 0 {
 8835                    break;
 8836                } else {
 8837                    search_start = 0;
 8838                }
 8839            }
 8840        }
 8841    }
 8842
 8843    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 8844        let snapshot = self
 8845            .display_map
 8846            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8847        let selection = self.selections.newest::<Point>(cx);
 8848
 8849        if !self.seek_in_direction(
 8850            &snapshot,
 8851            selection.head(),
 8852            false,
 8853            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8854                MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
 8855            ),
 8856            cx,
 8857        ) {
 8858            let wrapped_point = Point::zero();
 8859            self.seek_in_direction(
 8860                &snapshot,
 8861                wrapped_point,
 8862                true,
 8863                snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8864                    MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 8865                ),
 8866                cx,
 8867            );
 8868        }
 8869    }
 8870
 8871    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 8872        let snapshot = self
 8873            .display_map
 8874            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8875        let selection = self.selections.newest::<Point>(cx);
 8876
 8877        if !self.seek_in_direction(
 8878            &snapshot,
 8879            selection.head(),
 8880            false,
 8881            snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8882                MultiBufferRow(0)..MultiBufferRow(selection.head().row),
 8883            ),
 8884            cx,
 8885        ) {
 8886            let wrapped_point = snapshot.buffer_snapshot.max_point();
 8887            self.seek_in_direction(
 8888                &snapshot,
 8889                wrapped_point,
 8890                true,
 8891                snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8892                    MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
 8893                ),
 8894                cx,
 8895            );
 8896        }
 8897    }
 8898
 8899    fn seek_in_direction(
 8900        &mut self,
 8901        snapshot: &DisplaySnapshot,
 8902        initial_point: Point,
 8903        is_wrapped: bool,
 8904        hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
 8905        cx: &mut ViewContext<Editor>,
 8906    ) -> bool {
 8907        let display_point = initial_point.to_display_point(snapshot);
 8908        let mut hunks = hunks
 8909            .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
 8910            .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
 8911            .dedup();
 8912
 8913        if let Some(hunk) = hunks.next() {
 8914            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8915                let row = hunk.start_display_row();
 8916                let point = DisplayPoint::new(row, 0);
 8917                s.select_display_ranges([point..point]);
 8918            });
 8919
 8920            true
 8921        } else {
 8922            false
 8923        }
 8924    }
 8925
 8926    pub fn go_to_definition(
 8927        &mut self,
 8928        _: &GoToDefinition,
 8929        cx: &mut ViewContext<Self>,
 8930    ) -> Task<Result<bool>> {
 8931        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
 8932    }
 8933
 8934    pub fn go_to_implementation(
 8935        &mut self,
 8936        _: &GoToImplementation,
 8937        cx: &mut ViewContext<Self>,
 8938    ) -> Task<Result<bool>> {
 8939        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 8940    }
 8941
 8942    pub fn go_to_implementation_split(
 8943        &mut self,
 8944        _: &GoToImplementationSplit,
 8945        cx: &mut ViewContext<Self>,
 8946    ) -> Task<Result<bool>> {
 8947        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 8948    }
 8949
 8950    pub fn go_to_type_definition(
 8951        &mut self,
 8952        _: &GoToTypeDefinition,
 8953        cx: &mut ViewContext<Self>,
 8954    ) -> Task<Result<bool>> {
 8955        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 8956    }
 8957
 8958    pub fn go_to_definition_split(
 8959        &mut self,
 8960        _: &GoToDefinitionSplit,
 8961        cx: &mut ViewContext<Self>,
 8962    ) -> Task<Result<bool>> {
 8963        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 8964    }
 8965
 8966    pub fn go_to_type_definition_split(
 8967        &mut self,
 8968        _: &GoToTypeDefinitionSplit,
 8969        cx: &mut ViewContext<Self>,
 8970    ) -> Task<Result<bool>> {
 8971        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 8972    }
 8973
 8974    fn go_to_definition_of_kind(
 8975        &mut self,
 8976        kind: GotoDefinitionKind,
 8977        split: bool,
 8978        cx: &mut ViewContext<Self>,
 8979    ) -> Task<Result<bool>> {
 8980        let Some(workspace) = self.workspace() else {
 8981            return Task::ready(Ok(false));
 8982        };
 8983        let buffer = self.buffer.read(cx);
 8984        let head = self.selections.newest::<usize>(cx).head();
 8985        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 8986            text_anchor
 8987        } else {
 8988            return Task::ready(Ok(false));
 8989        };
 8990
 8991        let project = workspace.read(cx).project().clone();
 8992        let definitions = project.update(cx, |project, cx| match kind {
 8993            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 8994            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 8995            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 8996        });
 8997
 8998        cx.spawn(|editor, mut cx| async move {
 8999            let definitions = definitions.await?;
 9000            let navigated = editor
 9001                .update(&mut cx, |editor, cx| {
 9002                    editor.navigate_to_hover_links(
 9003                        Some(kind),
 9004                        definitions
 9005                            .into_iter()
 9006                            .filter(|location| {
 9007                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9008                            })
 9009                            .map(HoverLink::Text)
 9010                            .collect::<Vec<_>>(),
 9011                        split,
 9012                        cx,
 9013                    )
 9014                })?
 9015                .await?;
 9016            anyhow::Ok(navigated)
 9017        })
 9018    }
 9019
 9020    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9021        let position = self.selections.newest_anchor().head();
 9022        let Some((buffer, buffer_position)) =
 9023            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9024        else {
 9025            return;
 9026        };
 9027
 9028        cx.spawn(|editor, mut cx| async move {
 9029            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9030                editor.update(&mut cx, |_, cx| {
 9031                    cx.open_url(&url);
 9032                })
 9033            } else {
 9034                Ok(())
 9035            }
 9036        })
 9037        .detach();
 9038    }
 9039
 9040    pub(crate) fn navigate_to_hover_links(
 9041        &mut self,
 9042        kind: Option<GotoDefinitionKind>,
 9043        mut definitions: Vec<HoverLink>,
 9044        split: bool,
 9045        cx: &mut ViewContext<Editor>,
 9046    ) -> Task<Result<bool>> {
 9047        // If there is one definition, just open it directly
 9048        if definitions.len() == 1 {
 9049            let definition = definitions.pop().unwrap();
 9050            let target_task = match definition {
 9051                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9052                HoverLink::InlayHint(lsp_location, server_id) => {
 9053                    self.compute_target_location(lsp_location, server_id, cx)
 9054                }
 9055                HoverLink::Url(url) => {
 9056                    cx.open_url(&url);
 9057                    Task::ready(Ok(None))
 9058                }
 9059            };
 9060            cx.spawn(|editor, mut cx| async move {
 9061                let target = target_task.await.context("target resolution task")?;
 9062                if let Some(target) = target {
 9063                    editor.update(&mut cx, |editor, cx| {
 9064                        let Some(workspace) = editor.workspace() else {
 9065                            return false;
 9066                        };
 9067                        let pane = workspace.read(cx).active_pane().clone();
 9068
 9069                        let range = target.range.to_offset(target.buffer.read(cx));
 9070                        let range = editor.range_for_match(&range);
 9071
 9072                        /// If select range has more than one line, we
 9073                        /// just point the cursor to range.start.
 9074                        fn check_multiline_range(
 9075                            buffer: &Buffer,
 9076                            range: Range<usize>,
 9077                        ) -> Range<usize> {
 9078                            if buffer.offset_to_point(range.start).row
 9079                                == buffer.offset_to_point(range.end).row
 9080                            {
 9081                                range
 9082                            } else {
 9083                                range.start..range.start
 9084                            }
 9085                        }
 9086
 9087                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9088                            let buffer = target.buffer.read(cx);
 9089                            let range = check_multiline_range(buffer, range);
 9090                            editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 9091                                s.select_ranges([range]);
 9092                            });
 9093                        } else {
 9094                            cx.window_context().defer(move |cx| {
 9095                                let target_editor: View<Self> =
 9096                                    workspace.update(cx, |workspace, cx| {
 9097                                        let pane = if split {
 9098                                            workspace.adjacent_pane(cx)
 9099                                        } else {
 9100                                            workspace.active_pane().clone()
 9101                                        };
 9102
 9103                                        workspace.open_project_item(
 9104                                            pane,
 9105                                            target.buffer.clone(),
 9106                                            true,
 9107                                            true,
 9108                                            cx,
 9109                                        )
 9110                                    });
 9111                                target_editor.update(cx, |target_editor, cx| {
 9112                                    // When selecting a definition in a different buffer, disable the nav history
 9113                                    // to avoid creating a history entry at the previous cursor location.
 9114                                    pane.update(cx, |pane, _| pane.disable_history());
 9115                                    let buffer = target.buffer.read(cx);
 9116                                    let range = check_multiline_range(buffer, range);
 9117                                    target_editor.change_selections(
 9118                                        Some(Autoscroll::focused()),
 9119                                        cx,
 9120                                        |s| {
 9121                                            s.select_ranges([range]);
 9122                                        },
 9123                                    );
 9124                                    pane.update(cx, |pane, _| pane.enable_history());
 9125                                });
 9126                            });
 9127                        }
 9128                        true
 9129                    })
 9130                } else {
 9131                    Ok(false)
 9132                }
 9133            })
 9134        } else if !definitions.is_empty() {
 9135            let replica_id = self.replica_id(cx);
 9136            cx.spawn(|editor, mut cx| async move {
 9137                let (title, location_tasks, workspace) = editor
 9138                    .update(&mut cx, |editor, cx| {
 9139                        let tab_kind = match kind {
 9140                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9141                            _ => "Definitions",
 9142                        };
 9143                        let title = definitions
 9144                            .iter()
 9145                            .find_map(|definition| match definition {
 9146                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9147                                    let buffer = origin.buffer.read(cx);
 9148                                    format!(
 9149                                        "{} for {}",
 9150                                        tab_kind,
 9151                                        buffer
 9152                                            .text_for_range(origin.range.clone())
 9153                                            .collect::<String>()
 9154                                    )
 9155                                }),
 9156                                HoverLink::InlayHint(_, _) => None,
 9157                                HoverLink::Url(_) => None,
 9158                            })
 9159                            .unwrap_or(tab_kind.to_string());
 9160                        let location_tasks = definitions
 9161                            .into_iter()
 9162                            .map(|definition| match definition {
 9163                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9164                                HoverLink::InlayHint(lsp_location, server_id) => {
 9165                                    editor.compute_target_location(lsp_location, server_id, cx)
 9166                                }
 9167                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9168                            })
 9169                            .collect::<Vec<_>>();
 9170                        (title, location_tasks, editor.workspace().clone())
 9171                    })
 9172                    .context("location tasks preparation")?;
 9173
 9174                let locations = futures::future::join_all(location_tasks)
 9175                    .await
 9176                    .into_iter()
 9177                    .filter_map(|location| location.transpose())
 9178                    .collect::<Result<_>>()
 9179                    .context("location tasks")?;
 9180
 9181                let Some(workspace) = workspace else {
 9182                    return Ok(false);
 9183                };
 9184                let opened = workspace
 9185                    .update(&mut cx, |workspace, cx| {
 9186                        Self::open_locations_in_multibuffer(
 9187                            workspace, locations, replica_id, title, split, cx,
 9188                        )
 9189                    })
 9190                    .ok();
 9191
 9192                anyhow::Ok(opened.is_some())
 9193            })
 9194        } else {
 9195            Task::ready(Ok(false))
 9196        }
 9197    }
 9198
 9199    fn compute_target_location(
 9200        &self,
 9201        lsp_location: lsp::Location,
 9202        server_id: LanguageServerId,
 9203        cx: &mut ViewContext<Editor>,
 9204    ) -> Task<anyhow::Result<Option<Location>>> {
 9205        let Some(project) = self.project.clone() else {
 9206            return Task::Ready(Some(Ok(None)));
 9207        };
 9208
 9209        cx.spawn(move |editor, mut cx| async move {
 9210            let location_task = editor.update(&mut cx, |editor, cx| {
 9211                project.update(cx, |project, cx| {
 9212                    let language_server_name =
 9213                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 9214                            project
 9215                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 9216                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 9217                        });
 9218                    language_server_name.map(|language_server_name| {
 9219                        project.open_local_buffer_via_lsp(
 9220                            lsp_location.uri.clone(),
 9221                            server_id,
 9222                            language_server_name,
 9223                            cx,
 9224                        )
 9225                    })
 9226                })
 9227            })?;
 9228            let location = match location_task {
 9229                Some(task) => Some({
 9230                    let target_buffer_handle = task.await.context("open local buffer")?;
 9231                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9232                        let target_start = target_buffer
 9233                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9234                        let target_end = target_buffer
 9235                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9236                        target_buffer.anchor_after(target_start)
 9237                            ..target_buffer.anchor_before(target_end)
 9238                    })?;
 9239                    Location {
 9240                        buffer: target_buffer_handle,
 9241                        range,
 9242                    }
 9243                }),
 9244                None => None,
 9245            };
 9246            Ok(location)
 9247        })
 9248    }
 9249
 9250    pub fn find_all_references(
 9251        &mut self,
 9252        _: &FindAllReferences,
 9253        cx: &mut ViewContext<Self>,
 9254    ) -> Option<Task<Result<()>>> {
 9255        let multi_buffer = self.buffer.read(cx);
 9256        let selection = self.selections.newest::<usize>(cx);
 9257        let head = selection.head();
 9258
 9259        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9260        let head_anchor = multi_buffer_snapshot.anchor_at(
 9261            head,
 9262            if head < selection.tail() {
 9263                Bias::Right
 9264            } else {
 9265                Bias::Left
 9266            },
 9267        );
 9268
 9269        match self
 9270            .find_all_references_task_sources
 9271            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9272        {
 9273            Ok(_) => {
 9274                log::info!(
 9275                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9276                );
 9277                return None;
 9278            }
 9279            Err(i) => {
 9280                self.find_all_references_task_sources.insert(i, head_anchor);
 9281            }
 9282        }
 9283
 9284        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9285        let replica_id = self.replica_id(cx);
 9286        let workspace = self.workspace()?;
 9287        let project = workspace.read(cx).project().clone();
 9288        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9289        Some(cx.spawn(|editor, mut cx| async move {
 9290            let _cleanup = defer({
 9291                let mut cx = cx.clone();
 9292                move || {
 9293                    let _ = editor.update(&mut cx, |editor, _| {
 9294                        if let Ok(i) =
 9295                            editor
 9296                                .find_all_references_task_sources
 9297                                .binary_search_by(|anchor| {
 9298                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9299                                })
 9300                        {
 9301                            editor.find_all_references_task_sources.remove(i);
 9302                        }
 9303                    });
 9304                }
 9305            });
 9306
 9307            let locations = references.await?;
 9308            if locations.is_empty() {
 9309                return anyhow::Ok(());
 9310            }
 9311
 9312            workspace.update(&mut cx, |workspace, cx| {
 9313                let title = locations
 9314                    .first()
 9315                    .as_ref()
 9316                    .map(|location| {
 9317                        let buffer = location.buffer.read(cx);
 9318                        format!(
 9319                            "References to `{}`",
 9320                            buffer
 9321                                .text_for_range(location.range.clone())
 9322                                .collect::<String>()
 9323                        )
 9324                    })
 9325                    .unwrap();
 9326                Self::open_locations_in_multibuffer(
 9327                    workspace, locations, replica_id, title, false, cx,
 9328                );
 9329            })
 9330        }))
 9331    }
 9332
 9333    /// Opens a multibuffer with the given project locations in it
 9334    pub fn open_locations_in_multibuffer(
 9335        workspace: &mut Workspace,
 9336        mut locations: Vec<Location>,
 9337        replica_id: ReplicaId,
 9338        title: String,
 9339        split: bool,
 9340        cx: &mut ViewContext<Workspace>,
 9341    ) {
 9342        // If there are multiple definitions, open them in a multibuffer
 9343        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9344        let mut locations = locations.into_iter().peekable();
 9345        let mut ranges_to_highlight = Vec::new();
 9346        let capability = workspace.project().read(cx).capability();
 9347
 9348        let excerpt_buffer = cx.new_model(|cx| {
 9349            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 9350            while let Some(location) = locations.next() {
 9351                let buffer = location.buffer.read(cx);
 9352                let mut ranges_for_buffer = Vec::new();
 9353                let range = location.range.to_offset(buffer);
 9354                ranges_for_buffer.push(range.clone());
 9355
 9356                while let Some(next_location) = locations.peek() {
 9357                    if next_location.buffer == location.buffer {
 9358                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9359                        locations.next();
 9360                    } else {
 9361                        break;
 9362                    }
 9363                }
 9364
 9365                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9366                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9367                    location.buffer.clone(),
 9368                    ranges_for_buffer,
 9369                    DEFAULT_MULTIBUFFER_CONTEXT,
 9370                    cx,
 9371                ))
 9372            }
 9373
 9374            multibuffer.with_title(title)
 9375        });
 9376
 9377        let editor = cx.new_view(|cx| {
 9378            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9379        });
 9380        editor.update(cx, |editor, cx| {
 9381            if let Some(first_range) = ranges_to_highlight.first() {
 9382                editor.change_selections(None, cx, |selections| {
 9383                    selections.clear_disjoint();
 9384                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9385                });
 9386            }
 9387            editor.highlight_background::<Self>(
 9388                &ranges_to_highlight,
 9389                |theme| theme.editor_highlighted_line_background,
 9390                cx,
 9391            );
 9392        });
 9393
 9394        let item = Box::new(editor);
 9395        let item_id = item.item_id();
 9396
 9397        if split {
 9398            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9399        } else {
 9400            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9401                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9402                    pane.close_current_preview_item(cx)
 9403                } else {
 9404                    None
 9405                }
 9406            });
 9407            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9408        }
 9409        workspace.active_pane().update(cx, |pane, cx| {
 9410            pane.set_preview_item_id(Some(item_id), cx);
 9411        });
 9412    }
 9413
 9414    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9415        use language::ToOffset as _;
 9416
 9417        let project = self.project.clone()?;
 9418        let selection = self.selections.newest_anchor().clone();
 9419        let (cursor_buffer, cursor_buffer_position) = self
 9420            .buffer
 9421            .read(cx)
 9422            .text_anchor_for_position(selection.head(), cx)?;
 9423        let (tail_buffer, cursor_buffer_position_end) = self
 9424            .buffer
 9425            .read(cx)
 9426            .text_anchor_for_position(selection.tail(), cx)?;
 9427        if tail_buffer != cursor_buffer {
 9428            return None;
 9429        }
 9430
 9431        let snapshot = cursor_buffer.read(cx).snapshot();
 9432        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9433        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9434        let prepare_rename = project.update(cx, |project, cx| {
 9435            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 9436        });
 9437        drop(snapshot);
 9438
 9439        Some(cx.spawn(|this, mut cx| async move {
 9440            let rename_range = if let Some(range) = prepare_rename.await? {
 9441                Some(range)
 9442            } else {
 9443                this.update(&mut cx, |this, cx| {
 9444                    let buffer = this.buffer.read(cx).snapshot(cx);
 9445                    let mut buffer_highlights = this
 9446                        .document_highlights_for_position(selection.head(), &buffer)
 9447                        .filter(|highlight| {
 9448                            highlight.start.excerpt_id == selection.head().excerpt_id
 9449                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9450                        });
 9451                    buffer_highlights
 9452                        .next()
 9453                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9454                })?
 9455            };
 9456            if let Some(rename_range) = rename_range {
 9457                this.update(&mut cx, |this, cx| {
 9458                    let snapshot = cursor_buffer.read(cx).snapshot();
 9459                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9460                    let cursor_offset_in_rename_range =
 9461                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9462                    let cursor_offset_in_rename_range_end =
 9463                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9464
 9465                    this.take_rename(false, cx);
 9466                    let buffer = this.buffer.read(cx).read(cx);
 9467                    let cursor_offset = selection.head().to_offset(&buffer);
 9468                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9469                    let rename_end = rename_start + rename_buffer_range.len();
 9470                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9471                    let mut old_highlight_id = None;
 9472                    let old_name: Arc<str> = buffer
 9473                        .chunks(rename_start..rename_end, true)
 9474                        .map(|chunk| {
 9475                            if old_highlight_id.is_none() {
 9476                                old_highlight_id = chunk.syntax_highlight_id;
 9477                            }
 9478                            chunk.text
 9479                        })
 9480                        .collect::<String>()
 9481                        .into();
 9482
 9483                    drop(buffer);
 9484
 9485                    // Position the selection in the rename editor so that it matches the current selection.
 9486                    this.show_local_selections = false;
 9487                    let rename_editor = cx.new_view(|cx| {
 9488                        let mut editor = Editor::single_line(cx);
 9489                        editor.buffer.update(cx, |buffer, cx| {
 9490                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9491                        });
 9492                        let rename_selection_range = match cursor_offset_in_rename_range
 9493                            .cmp(&cursor_offset_in_rename_range_end)
 9494                        {
 9495                            Ordering::Equal => {
 9496                                editor.select_all(&SelectAll, cx);
 9497                                return editor;
 9498                            }
 9499                            Ordering::Less => {
 9500                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9501                            }
 9502                            Ordering::Greater => {
 9503                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9504                            }
 9505                        };
 9506                        if rename_selection_range.end > old_name.len() {
 9507                            editor.select_all(&SelectAll, cx);
 9508                        } else {
 9509                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9510                                s.select_ranges([rename_selection_range]);
 9511                            });
 9512                        }
 9513                        editor
 9514                    });
 9515                    cx.subscribe(&rename_editor, |_, _, e, cx| match e {
 9516                        EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
 9517                        _ => {}
 9518                    })
 9519                    .detach();
 9520
 9521                    let write_highlights =
 9522                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9523                    let read_highlights =
 9524                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9525                    let ranges = write_highlights
 9526                        .iter()
 9527                        .flat_map(|(_, ranges)| ranges.iter())
 9528                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9529                        .cloned()
 9530                        .collect();
 9531
 9532                    this.highlight_text::<Rename>(
 9533                        ranges,
 9534                        HighlightStyle {
 9535                            fade_out: Some(0.6),
 9536                            ..Default::default()
 9537                        },
 9538                        cx,
 9539                    );
 9540                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9541                    cx.focus(&rename_focus_handle);
 9542                    let block_id = this.insert_blocks(
 9543                        [BlockProperties {
 9544                            style: BlockStyle::Flex,
 9545                            position: range.start,
 9546                            height: 1,
 9547                            render: Box::new({
 9548                                let rename_editor = rename_editor.clone();
 9549                                move |cx: &mut BlockContext| {
 9550                                    let mut text_style = cx.editor_style.text.clone();
 9551                                    if let Some(highlight_style) = old_highlight_id
 9552                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 9553                                    {
 9554                                        text_style = text_style.highlight(highlight_style);
 9555                                    }
 9556                                    div()
 9557                                        .pl(cx.anchor_x)
 9558                                        .child(EditorElement::new(
 9559                                            &rename_editor,
 9560                                            EditorStyle {
 9561                                                background: cx.theme().system().transparent,
 9562                                                local_player: cx.editor_style.local_player,
 9563                                                text: text_style,
 9564                                                scrollbar_width: cx.editor_style.scrollbar_width,
 9565                                                syntax: cx.editor_style.syntax.clone(),
 9566                                                status: cx.editor_style.status.clone(),
 9567                                                inlay_hints_style: HighlightStyle {
 9568                                                    color: Some(cx.theme().status().hint),
 9569                                                    font_weight: Some(FontWeight::BOLD),
 9570                                                    ..HighlightStyle::default()
 9571                                                },
 9572                                                suggestions_style: HighlightStyle {
 9573                                                    color: Some(cx.theme().status().predictive),
 9574                                                    ..HighlightStyle::default()
 9575                                                },
 9576                                            },
 9577                                        ))
 9578                                        .into_any_element()
 9579                                }
 9580                            }),
 9581                            disposition: BlockDisposition::Below,
 9582                        }],
 9583                        Some(Autoscroll::fit()),
 9584                        cx,
 9585                    )[0];
 9586                    this.pending_rename = Some(RenameState {
 9587                        range,
 9588                        old_name,
 9589                        editor: rename_editor,
 9590                        block_id,
 9591                    });
 9592                })?;
 9593            }
 9594
 9595            Ok(())
 9596        }))
 9597    }
 9598
 9599    pub fn confirm_rename(
 9600        &mut self,
 9601        _: &ConfirmRename,
 9602        cx: &mut ViewContext<Self>,
 9603    ) -> Option<Task<Result<()>>> {
 9604        let rename = self.take_rename(false, cx)?;
 9605        let workspace = self.workspace()?;
 9606        let (start_buffer, start) = self
 9607            .buffer
 9608            .read(cx)
 9609            .text_anchor_for_position(rename.range.start, cx)?;
 9610        let (end_buffer, end) = self
 9611            .buffer
 9612            .read(cx)
 9613            .text_anchor_for_position(rename.range.end, cx)?;
 9614        if start_buffer != end_buffer {
 9615            return None;
 9616        }
 9617
 9618        let buffer = start_buffer;
 9619        let range = start..end;
 9620        let old_name = rename.old_name;
 9621        let new_name = rename.editor.read(cx).text(cx);
 9622
 9623        let rename = workspace
 9624            .read(cx)
 9625            .project()
 9626            .clone()
 9627            .update(cx, |project, cx| {
 9628                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 9629            });
 9630        let workspace = workspace.downgrade();
 9631
 9632        Some(cx.spawn(|editor, mut cx| async move {
 9633            let project_transaction = rename.await?;
 9634            Self::open_project_transaction(
 9635                &editor,
 9636                workspace,
 9637                project_transaction,
 9638                format!("Rename: {}{}", old_name, new_name),
 9639                cx.clone(),
 9640            )
 9641            .await?;
 9642
 9643            editor.update(&mut cx, |editor, cx| {
 9644                editor.refresh_document_highlights(cx);
 9645            })?;
 9646            Ok(())
 9647        }))
 9648    }
 9649
 9650    fn take_rename(
 9651        &mut self,
 9652        moving_cursor: bool,
 9653        cx: &mut ViewContext<Self>,
 9654    ) -> Option<RenameState> {
 9655        let rename = self.pending_rename.take()?;
 9656        if rename.editor.focus_handle(cx).is_focused(cx) {
 9657            cx.focus(&self.focus_handle);
 9658        }
 9659
 9660        self.remove_blocks(
 9661            [rename.block_id].into_iter().collect(),
 9662            Some(Autoscroll::fit()),
 9663            cx,
 9664        );
 9665        self.clear_highlights::<Rename>(cx);
 9666        self.show_local_selections = true;
 9667
 9668        if moving_cursor {
 9669            let rename_editor = rename.editor.read(cx);
 9670            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 9671
 9672            // Update the selection to match the position of the selection inside
 9673            // the rename editor.
 9674            let snapshot = self.buffer.read(cx).read(cx);
 9675            let rename_range = rename.range.to_offset(&snapshot);
 9676            let cursor_in_editor = snapshot
 9677                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 9678                .min(rename_range.end);
 9679            drop(snapshot);
 9680
 9681            self.change_selections(None, cx, |s| {
 9682                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 9683            });
 9684        } else {
 9685            self.refresh_document_highlights(cx);
 9686        }
 9687
 9688        Some(rename)
 9689    }
 9690
 9691    pub fn pending_rename(&self) -> Option<&RenameState> {
 9692        self.pending_rename.as_ref()
 9693    }
 9694
 9695    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9696        let project = match &self.project {
 9697            Some(project) => project.clone(),
 9698            None => return None,
 9699        };
 9700
 9701        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 9702    }
 9703
 9704    fn perform_format(
 9705        &mut self,
 9706        project: Model<Project>,
 9707        trigger: FormatTrigger,
 9708        cx: &mut ViewContext<Self>,
 9709    ) -> Task<Result<()>> {
 9710        let buffer = self.buffer().clone();
 9711        let mut buffers = buffer.read(cx).all_buffers();
 9712        if trigger == FormatTrigger::Save {
 9713            buffers.retain(|buffer| buffer.read(cx).is_dirty());
 9714        }
 9715
 9716        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 9717        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 9718
 9719        cx.spawn(|_, mut cx| async move {
 9720            let transaction = futures::select_biased! {
 9721                () = timeout => {
 9722                    log::warn!("timed out waiting for formatting");
 9723                    None
 9724                }
 9725                transaction = format.log_err().fuse() => transaction,
 9726            };
 9727
 9728            buffer
 9729                .update(&mut cx, |buffer, cx| {
 9730                    if let Some(transaction) = transaction {
 9731                        if !buffer.is_singleton() {
 9732                            buffer.push_transaction(&transaction.0, cx);
 9733                        }
 9734                    }
 9735
 9736                    cx.notify();
 9737                })
 9738                .ok();
 9739
 9740            Ok(())
 9741        })
 9742    }
 9743
 9744    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
 9745        if let Some(project) = self.project.clone() {
 9746            self.buffer.update(cx, |multi_buffer, cx| {
 9747                project.update(cx, |project, cx| {
 9748                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
 9749                });
 9750            })
 9751        }
 9752    }
 9753
 9754    fn cancel_language_server_work(
 9755        &mut self,
 9756        _: &CancelLanguageServerWork,
 9757        cx: &mut ViewContext<Self>,
 9758    ) {
 9759        if let Some(project) = self.project.clone() {
 9760            self.buffer.update(cx, |multi_buffer, cx| {
 9761                project.update(cx, |project, cx| {
 9762                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
 9763                });
 9764            })
 9765        }
 9766    }
 9767
 9768    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 9769        cx.show_character_palette();
 9770    }
 9771
 9772    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
 9773        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
 9774            let buffer = self.buffer.read(cx).snapshot(cx);
 9775            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
 9776            let is_valid = buffer
 9777                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
 9778                .any(|entry| {
 9779                    entry.diagnostic.is_primary
 9780                        && !entry.range.is_empty()
 9781                        && entry.range.start == primary_range_start
 9782                        && entry.diagnostic.message == active_diagnostics.primary_message
 9783                });
 9784
 9785            if is_valid != active_diagnostics.is_valid {
 9786                active_diagnostics.is_valid = is_valid;
 9787                let mut new_styles = HashMap::default();
 9788                for (block_id, diagnostic) in &active_diagnostics.blocks {
 9789                    new_styles.insert(
 9790                        *block_id,
 9791                        (
 9792                            None,
 9793                            diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
 9794                        ),
 9795                    );
 9796                }
 9797                self.display_map.update(cx, |display_map, cx| {
 9798                    display_map.replace_blocks(new_styles, cx)
 9799                });
 9800            }
 9801        }
 9802    }
 9803
 9804    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
 9805        self.dismiss_diagnostics(cx);
 9806        let snapshot = self.snapshot(cx);
 9807        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
 9808            let buffer = self.buffer.read(cx).snapshot(cx);
 9809
 9810            let mut primary_range = None;
 9811            let mut primary_message = None;
 9812            let mut group_end = Point::zero();
 9813            let diagnostic_group = buffer
 9814                .diagnostic_group::<MultiBufferPoint>(group_id)
 9815                .filter_map(|entry| {
 9816                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
 9817                        && (entry.range.start.row == entry.range.end.row
 9818                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
 9819                    {
 9820                        return None;
 9821                    }
 9822                    if entry.range.end > group_end {
 9823                        group_end = entry.range.end;
 9824                    }
 9825                    if entry.diagnostic.is_primary {
 9826                        primary_range = Some(entry.range.clone());
 9827                        primary_message = Some(entry.diagnostic.message.clone());
 9828                    }
 9829                    Some(entry)
 9830                })
 9831                .collect::<Vec<_>>();
 9832            let primary_range = primary_range?;
 9833            let primary_message = primary_message?;
 9834            let primary_range =
 9835                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
 9836
 9837            let blocks = display_map
 9838                .insert_blocks(
 9839                    diagnostic_group.iter().map(|entry| {
 9840                        let diagnostic = entry.diagnostic.clone();
 9841                        let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
 9842                        BlockProperties {
 9843                            style: BlockStyle::Fixed,
 9844                            position: buffer.anchor_after(entry.range.start),
 9845                            height: message_height,
 9846                            render: diagnostic_block_renderer(diagnostic, None, true, true),
 9847                            disposition: BlockDisposition::Below,
 9848                        }
 9849                    }),
 9850                    cx,
 9851                )
 9852                .into_iter()
 9853                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
 9854                .collect();
 9855
 9856            Some(ActiveDiagnosticGroup {
 9857                primary_range,
 9858                primary_message,
 9859                group_id,
 9860                blocks,
 9861                is_valid: true,
 9862            })
 9863        });
 9864        self.active_diagnostics.is_some()
 9865    }
 9866
 9867    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
 9868        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
 9869            self.display_map.update(cx, |display_map, cx| {
 9870                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
 9871            });
 9872            cx.notify();
 9873        }
 9874    }
 9875
 9876    pub fn set_selections_from_remote(
 9877        &mut self,
 9878        selections: Vec<Selection<Anchor>>,
 9879        pending_selection: Option<Selection<Anchor>>,
 9880        cx: &mut ViewContext<Self>,
 9881    ) {
 9882        let old_cursor_position = self.selections.newest_anchor().head();
 9883        self.selections.change_with(cx, |s| {
 9884            s.select_anchors(selections);
 9885            if let Some(pending_selection) = pending_selection {
 9886                s.set_pending(pending_selection, SelectMode::Character);
 9887            } else {
 9888                s.clear_pending();
 9889            }
 9890        });
 9891        self.selections_did_change(false, &old_cursor_position, true, cx);
 9892    }
 9893
 9894    fn push_to_selection_history(&mut self) {
 9895        self.selection_history.push(SelectionHistoryEntry {
 9896            selections: self.selections.disjoint_anchors(),
 9897            select_next_state: self.select_next_state.clone(),
 9898            select_prev_state: self.select_prev_state.clone(),
 9899            add_selections_state: self.add_selections_state.clone(),
 9900        });
 9901    }
 9902
 9903    pub fn transact(
 9904        &mut self,
 9905        cx: &mut ViewContext<Self>,
 9906        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
 9907    ) -> Option<TransactionId> {
 9908        self.start_transaction_at(Instant::now(), cx);
 9909        update(self, cx);
 9910        self.end_transaction_at(Instant::now(), cx)
 9911    }
 9912
 9913    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
 9914        self.end_selection(cx);
 9915        if let Some(tx_id) = self
 9916            .buffer
 9917            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
 9918        {
 9919            self.selection_history
 9920                .insert_transaction(tx_id, self.selections.disjoint_anchors());
 9921            cx.emit(EditorEvent::TransactionBegun {
 9922                transaction_id: tx_id,
 9923            })
 9924        }
 9925    }
 9926
 9927    fn end_transaction_at(
 9928        &mut self,
 9929        now: Instant,
 9930        cx: &mut ViewContext<Self>,
 9931    ) -> Option<TransactionId> {
 9932        if let Some(transaction_id) = self
 9933            .buffer
 9934            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 9935        {
 9936            if let Some((_, end_selections)) =
 9937                self.selection_history.transaction_mut(transaction_id)
 9938            {
 9939                *end_selections = Some(self.selections.disjoint_anchors());
 9940            } else {
 9941                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
 9942            }
 9943
 9944            cx.emit(EditorEvent::Edited { transaction_id });
 9945            Some(transaction_id)
 9946        } else {
 9947            None
 9948        }
 9949    }
 9950
 9951    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
 9952        let mut fold_ranges = Vec::new();
 9953
 9954        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9955
 9956        let selections = self.selections.all_adjusted(cx);
 9957        for selection in selections {
 9958            let range = selection.range().sorted();
 9959            let buffer_start_row = range.start.row;
 9960
 9961            for row in (0..=range.end.row).rev() {
 9962                if let Some((foldable_range, fold_text)) =
 9963                    display_map.foldable_range(MultiBufferRow(row))
 9964                {
 9965                    if foldable_range.end.row >= buffer_start_row {
 9966                        fold_ranges.push((foldable_range, fold_text));
 9967                        if row <= range.start.row {
 9968                            break;
 9969                        }
 9970                    }
 9971                }
 9972            }
 9973        }
 9974
 9975        self.fold_ranges(fold_ranges, true, cx);
 9976    }
 9977
 9978    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
 9979        let buffer_row = fold_at.buffer_row;
 9980        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9981
 9982        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
 9983            let autoscroll = self
 9984                .selections
 9985                .all::<Point>(cx)
 9986                .iter()
 9987                .any(|selection| fold_range.overlaps(&selection.range()));
 9988
 9989            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
 9990        }
 9991    }
 9992
 9993    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
 9994        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9995        let buffer = &display_map.buffer_snapshot;
 9996        let selections = self.selections.all::<Point>(cx);
 9997        let ranges = selections
 9998            .iter()
 9999            .map(|s| {
10000                let range = s.display_range(&display_map).sorted();
10001                let mut start = range.start.to_point(&display_map);
10002                let mut end = range.end.to_point(&display_map);
10003                start.column = 0;
10004                end.column = buffer.line_len(MultiBufferRow(end.row));
10005                start..end
10006            })
10007            .collect::<Vec<_>>();
10008
10009        self.unfold_ranges(ranges, true, true, cx);
10010    }
10011
10012    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10013        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10014
10015        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10016            ..Point::new(
10017                unfold_at.buffer_row.0,
10018                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10019            );
10020
10021        let autoscroll = self
10022            .selections
10023            .all::<Point>(cx)
10024            .iter()
10025            .any(|selection| selection.range().overlaps(&intersection_range));
10026
10027        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10028    }
10029
10030    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10031        let selections = self.selections.all::<Point>(cx);
10032        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10033        let line_mode = self.selections.line_mode;
10034        let ranges = selections.into_iter().map(|s| {
10035            if line_mode {
10036                let start = Point::new(s.start.row, 0);
10037                let end = Point::new(
10038                    s.end.row,
10039                    display_map
10040                        .buffer_snapshot
10041                        .line_len(MultiBufferRow(s.end.row)),
10042                );
10043                (start..end, display_map.fold_placeholder.clone())
10044            } else {
10045                (s.start..s.end, display_map.fold_placeholder.clone())
10046            }
10047        });
10048        self.fold_ranges(ranges, true, cx);
10049    }
10050
10051    pub fn fold_ranges<T: ToOffset + Clone>(
10052        &mut self,
10053        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10054        auto_scroll: bool,
10055        cx: &mut ViewContext<Self>,
10056    ) {
10057        let mut fold_ranges = Vec::new();
10058        let mut buffers_affected = HashMap::default();
10059        let multi_buffer = self.buffer().read(cx);
10060        for (fold_range, fold_text) in ranges {
10061            if let Some((_, buffer, _)) =
10062                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10063            {
10064                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10065            };
10066            fold_ranges.push((fold_range, fold_text));
10067        }
10068
10069        let mut ranges = fold_ranges.into_iter().peekable();
10070        if ranges.peek().is_some() {
10071            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10072
10073            if auto_scroll {
10074                self.request_autoscroll(Autoscroll::fit(), cx);
10075            }
10076
10077            for buffer in buffers_affected.into_values() {
10078                self.sync_expanded_diff_hunks(buffer, cx);
10079            }
10080
10081            cx.notify();
10082
10083            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10084                // Clear diagnostics block when folding a range that contains it.
10085                let snapshot = self.snapshot(cx);
10086                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10087                    drop(snapshot);
10088                    self.active_diagnostics = Some(active_diagnostics);
10089                    self.dismiss_diagnostics(cx);
10090                } else {
10091                    self.active_diagnostics = Some(active_diagnostics);
10092                }
10093            }
10094
10095            self.scrollbar_marker_state.dirty = true;
10096        }
10097    }
10098
10099    pub fn unfold_ranges<T: ToOffset + Clone>(
10100        &mut self,
10101        ranges: impl IntoIterator<Item = Range<T>>,
10102        inclusive: bool,
10103        auto_scroll: bool,
10104        cx: &mut ViewContext<Self>,
10105    ) {
10106        let mut unfold_ranges = Vec::new();
10107        let mut buffers_affected = HashMap::default();
10108        let multi_buffer = self.buffer().read(cx);
10109        for range in ranges {
10110            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10111                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10112            };
10113            unfold_ranges.push(range);
10114        }
10115
10116        let mut ranges = unfold_ranges.into_iter().peekable();
10117        if ranges.peek().is_some() {
10118            self.display_map
10119                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10120            if auto_scroll {
10121                self.request_autoscroll(Autoscroll::fit(), cx);
10122            }
10123
10124            for buffer in buffers_affected.into_values() {
10125                self.sync_expanded_diff_hunks(buffer, cx);
10126            }
10127
10128            cx.notify();
10129            self.scrollbar_marker_state.dirty = true;
10130            self.active_indent_guides_state.dirty = true;
10131        }
10132    }
10133
10134    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10135        if hovered != self.gutter_hovered {
10136            self.gutter_hovered = hovered;
10137            cx.notify();
10138        }
10139    }
10140
10141    pub fn insert_blocks(
10142        &mut self,
10143        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10144        autoscroll: Option<Autoscroll>,
10145        cx: &mut ViewContext<Self>,
10146    ) -> Vec<BlockId> {
10147        let blocks = self
10148            .display_map
10149            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10150        if let Some(autoscroll) = autoscroll {
10151            self.request_autoscroll(autoscroll, cx);
10152        }
10153        blocks
10154    }
10155
10156    pub fn replace_blocks(
10157        &mut self,
10158        blocks: HashMap<BlockId, (Option<u8>, RenderBlock)>,
10159        autoscroll: Option<Autoscroll>,
10160        cx: &mut ViewContext<Self>,
10161    ) {
10162        self.display_map
10163            .update(cx, |display_map, cx| display_map.replace_blocks(blocks, cx));
10164        if let Some(autoscroll) = autoscroll {
10165            self.request_autoscroll(autoscroll, cx);
10166        }
10167    }
10168
10169    pub fn remove_blocks(
10170        &mut self,
10171        block_ids: HashSet<BlockId>,
10172        autoscroll: Option<Autoscroll>,
10173        cx: &mut ViewContext<Self>,
10174    ) {
10175        self.display_map.update(cx, |display_map, cx| {
10176            display_map.remove_blocks(block_ids, cx)
10177        });
10178        if let Some(autoscroll) = autoscroll {
10179            self.request_autoscroll(autoscroll, cx);
10180        }
10181    }
10182
10183    pub fn row_for_block(
10184        &self,
10185        block_id: BlockId,
10186        cx: &mut ViewContext<Self>,
10187    ) -> Option<DisplayRow> {
10188        self.display_map
10189            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10190    }
10191
10192    pub fn insert_creases(
10193        &mut self,
10194        creases: impl IntoIterator<Item = Crease>,
10195        cx: &mut ViewContext<Self>,
10196    ) -> Vec<CreaseId> {
10197        self.display_map
10198            .update(cx, |map, cx| map.insert_creases(creases, cx))
10199    }
10200
10201    pub fn remove_creases(
10202        &mut self,
10203        ids: impl IntoIterator<Item = CreaseId>,
10204        cx: &mut ViewContext<Self>,
10205    ) {
10206        self.display_map
10207            .update(cx, |map, cx| map.remove_creases(ids, cx));
10208    }
10209
10210    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10211        self.display_map
10212            .update(cx, |map, cx| map.snapshot(cx))
10213            .longest_row()
10214    }
10215
10216    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10217        self.display_map
10218            .update(cx, |map, cx| map.snapshot(cx))
10219            .max_point()
10220    }
10221
10222    pub fn text(&self, cx: &AppContext) -> String {
10223        self.buffer.read(cx).read(cx).text()
10224    }
10225
10226    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10227        let text = self.text(cx);
10228        let text = text.trim();
10229
10230        if text.is_empty() {
10231            return None;
10232        }
10233
10234        Some(text.to_string())
10235    }
10236
10237    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10238        self.transact(cx, |this, cx| {
10239            this.buffer
10240                .read(cx)
10241                .as_singleton()
10242                .expect("you can only call set_text on editors for singleton buffers")
10243                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10244        });
10245    }
10246
10247    pub fn display_text(&self, cx: &mut AppContext) -> String {
10248        self.display_map
10249            .update(cx, |map, cx| map.snapshot(cx))
10250            .text()
10251    }
10252
10253    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10254        let mut wrap_guides = smallvec::smallvec![];
10255
10256        if self.show_wrap_guides == Some(false) {
10257            return wrap_guides;
10258        }
10259
10260        let settings = self.buffer.read(cx).settings_at(0, cx);
10261        if settings.show_wrap_guides {
10262            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10263                wrap_guides.push((soft_wrap as usize, true));
10264            }
10265            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10266        }
10267
10268        wrap_guides
10269    }
10270
10271    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10272        let settings = self.buffer.read(cx).settings_at(0, cx);
10273        let mode = self
10274            .soft_wrap_mode_override
10275            .unwrap_or_else(|| settings.soft_wrap);
10276        match mode {
10277            language_settings::SoftWrap::None => SoftWrap::None,
10278            language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10279            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10280            language_settings::SoftWrap::PreferredLineLength => {
10281                SoftWrap::Column(settings.preferred_line_length)
10282            }
10283        }
10284    }
10285
10286    pub fn set_soft_wrap_mode(
10287        &mut self,
10288        mode: language_settings::SoftWrap,
10289        cx: &mut ViewContext<Self>,
10290    ) {
10291        self.soft_wrap_mode_override = Some(mode);
10292        cx.notify();
10293    }
10294
10295    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10296        let rem_size = cx.rem_size();
10297        self.display_map.update(cx, |map, cx| {
10298            map.set_font(
10299                style.text.font(),
10300                style.text.font_size.to_pixels(rem_size),
10301                cx,
10302            )
10303        });
10304        self.style = Some(style);
10305    }
10306
10307    pub fn style(&self) -> Option<&EditorStyle> {
10308        self.style.as_ref()
10309    }
10310
10311    // Called by the element. This method is not designed to be called outside of the editor
10312    // element's layout code because it does not notify when rewrapping is computed synchronously.
10313    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10314        self.display_map
10315            .update(cx, |map, cx| map.set_wrap_width(width, cx))
10316    }
10317
10318    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10319        if self.soft_wrap_mode_override.is_some() {
10320            self.soft_wrap_mode_override.take();
10321        } else {
10322            let soft_wrap = match self.soft_wrap_mode(cx) {
10323                SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10324                SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10325                    language_settings::SoftWrap::PreferLine
10326                }
10327            };
10328            self.soft_wrap_mode_override = Some(soft_wrap);
10329        }
10330        cx.notify();
10331    }
10332
10333    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10334        let Some(workspace) = self.workspace() else {
10335            return;
10336        };
10337        let fs = workspace.read(cx).app_state().fs.clone();
10338        let current_show = TabBarSettings::get_global(cx).show;
10339        update_settings_file::<TabBarSettings>(fs, cx, move |setting| {
10340            setting.show = Some(!current_show);
10341        });
10342    }
10343
10344    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10345        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10346            self.buffer
10347                .read(cx)
10348                .settings_at(0, cx)
10349                .indent_guides
10350                .enabled
10351        });
10352        self.show_indent_guides = Some(!currently_enabled);
10353        cx.notify();
10354    }
10355
10356    fn should_show_indent_guides(&self) -> Option<bool> {
10357        self.show_indent_guides
10358    }
10359
10360    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10361        let mut editor_settings = EditorSettings::get_global(cx).clone();
10362        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10363        EditorSettings::override_global(editor_settings, cx);
10364    }
10365
10366    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10367        self.show_gutter = show_gutter;
10368        cx.notify();
10369    }
10370
10371    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10372        self.show_line_numbers = Some(show_line_numbers);
10373        cx.notify();
10374    }
10375
10376    pub fn set_show_git_diff_gutter(
10377        &mut self,
10378        show_git_diff_gutter: bool,
10379        cx: &mut ViewContext<Self>,
10380    ) {
10381        self.show_git_diff_gutter = Some(show_git_diff_gutter);
10382        cx.notify();
10383    }
10384
10385    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10386        self.show_code_actions = Some(show_code_actions);
10387        cx.notify();
10388    }
10389
10390    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10391        self.show_runnables = Some(show_runnables);
10392        cx.notify();
10393    }
10394
10395    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10396        self.show_wrap_guides = Some(show_wrap_guides);
10397        cx.notify();
10398    }
10399
10400    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10401        self.show_indent_guides = Some(show_indent_guides);
10402        cx.notify();
10403    }
10404
10405    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10406        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10407            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10408                if let Some(dir) = file.abs_path(cx).parent() {
10409                    return Some(dir.to_owned());
10410                }
10411            }
10412
10413            if let Some(project_path) = buffer.read(cx).project_path(cx) {
10414                return Some(project_path.path.to_path_buf());
10415            }
10416        }
10417
10418        None
10419    }
10420
10421    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10422        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10423            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10424                cx.reveal_path(&file.abs_path(cx));
10425            }
10426        }
10427    }
10428
10429    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10430        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10431            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10432                if let Some(path) = file.abs_path(cx).to_str() {
10433                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10434                }
10435            }
10436        }
10437    }
10438
10439    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10440        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10441            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10442                if let Some(path) = file.path().to_str() {
10443                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10444                }
10445            }
10446        }
10447    }
10448
10449    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10450        self.show_git_blame_gutter = !self.show_git_blame_gutter;
10451
10452        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10453            self.start_git_blame(true, cx);
10454        }
10455
10456        cx.notify();
10457    }
10458
10459    pub fn toggle_git_blame_inline(
10460        &mut self,
10461        _: &ToggleGitBlameInline,
10462        cx: &mut ViewContext<Self>,
10463    ) {
10464        self.toggle_git_blame_inline_internal(true, cx);
10465        cx.notify();
10466    }
10467
10468    pub fn git_blame_inline_enabled(&self) -> bool {
10469        self.git_blame_inline_enabled
10470    }
10471
10472    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10473        self.show_selection_menu = self
10474            .show_selection_menu
10475            .map(|show_selections_menu| !show_selections_menu)
10476            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10477
10478        cx.notify();
10479    }
10480
10481    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10482        self.show_selection_menu
10483            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10484    }
10485
10486    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10487        if let Some(project) = self.project.as_ref() {
10488            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10489                return;
10490            };
10491
10492            if buffer.read(cx).file().is_none() {
10493                return;
10494            }
10495
10496            let focused = self.focus_handle(cx).contains_focused(cx);
10497
10498            let project = project.clone();
10499            let blame =
10500                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10501            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10502            self.blame = Some(blame);
10503        }
10504    }
10505
10506    fn toggle_git_blame_inline_internal(
10507        &mut self,
10508        user_triggered: bool,
10509        cx: &mut ViewContext<Self>,
10510    ) {
10511        if self.git_blame_inline_enabled {
10512            self.git_blame_inline_enabled = false;
10513            self.show_git_blame_inline = false;
10514            self.show_git_blame_inline_delay_task.take();
10515        } else {
10516            self.git_blame_inline_enabled = true;
10517            self.start_git_blame_inline(user_triggered, cx);
10518        }
10519
10520        cx.notify();
10521    }
10522
10523    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10524        self.start_git_blame(user_triggered, cx);
10525
10526        if ProjectSettings::get_global(cx)
10527            .git
10528            .inline_blame_delay()
10529            .is_some()
10530        {
10531            self.start_inline_blame_timer(cx);
10532        } else {
10533            self.show_git_blame_inline = true
10534        }
10535    }
10536
10537    pub fn blame(&self) -> Option<&Model<GitBlame>> {
10538        self.blame.as_ref()
10539    }
10540
10541    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10542        self.show_git_blame_gutter && self.has_blame_entries(cx)
10543    }
10544
10545    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10546        self.show_git_blame_inline
10547            && self.focus_handle.is_focused(cx)
10548            && !self.newest_selection_head_on_empty_line(cx)
10549            && self.has_blame_entries(cx)
10550    }
10551
10552    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10553        self.blame()
10554            .map_or(false, |blame| blame.read(cx).has_generated_entries())
10555    }
10556
10557    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10558        let cursor_anchor = self.selections.newest_anchor().head();
10559
10560        let snapshot = self.buffer.read(cx).snapshot(cx);
10561        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10562
10563        snapshot.line_len(buffer_row) == 0
10564    }
10565
10566    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10567        let (path, selection, repo) = maybe!({
10568            let project_handle = self.project.as_ref()?.clone();
10569            let project = project_handle.read(cx);
10570
10571            let selection = self.selections.newest::<Point>(cx);
10572            let selection_range = selection.range();
10573
10574            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10575                (buffer, selection_range.start.row..selection_range.end.row)
10576            } else {
10577                let buffer_ranges = self
10578                    .buffer()
10579                    .read(cx)
10580                    .range_to_buffer_ranges(selection_range, cx);
10581
10582                let (buffer, range, _) = if selection.reversed {
10583                    buffer_ranges.first()
10584                } else {
10585                    buffer_ranges.last()
10586                }?;
10587
10588                let snapshot = buffer.read(cx).snapshot();
10589                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10590                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
10591                (buffer.clone(), selection)
10592            };
10593
10594            let path = buffer
10595                .read(cx)
10596                .file()?
10597                .as_local()?
10598                .path()
10599                .to_str()?
10600                .to_string();
10601            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10602            Some((path, selection, repo))
10603        })
10604        .ok_or_else(|| anyhow!("unable to open git repository"))?;
10605
10606        const REMOTE_NAME: &str = "origin";
10607        let origin_url = repo
10608            .remote_url(REMOTE_NAME)
10609            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10610        let sha = repo
10611            .head_sha()
10612            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10613
10614        let (provider, remote) =
10615            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10616                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10617
10618        Ok(provider.build_permalink(
10619            remote,
10620            BuildPermalinkParams {
10621                sha: &sha,
10622                path: &path,
10623                selection: Some(selection),
10624            },
10625        ))
10626    }
10627
10628    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10629        let permalink = self.get_permalink_to_line(cx);
10630
10631        match permalink {
10632            Ok(permalink) => {
10633                cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
10634            }
10635            Err(err) => {
10636                let message = format!("Failed to copy permalink: {err}");
10637
10638                Err::<(), anyhow::Error>(err).log_err();
10639
10640                if let Some(workspace) = self.workspace() {
10641                    workspace.update(cx, |workspace, cx| {
10642                        struct CopyPermalinkToLine;
10643
10644                        workspace.show_toast(
10645                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10646                            cx,
10647                        )
10648                    })
10649                }
10650            }
10651        }
10652    }
10653
10654    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10655        let permalink = self.get_permalink_to_line(cx);
10656
10657        match permalink {
10658            Ok(permalink) => {
10659                cx.open_url(permalink.as_ref());
10660            }
10661            Err(err) => {
10662                let message = format!("Failed to open permalink: {err}");
10663
10664                Err::<(), anyhow::Error>(err).log_err();
10665
10666                if let Some(workspace) = self.workspace() {
10667                    workspace.update(cx, |workspace, cx| {
10668                        struct OpenPermalinkToLine;
10669
10670                        workspace.show_toast(
10671                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10672                            cx,
10673                        )
10674                    })
10675                }
10676            }
10677        }
10678    }
10679
10680    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10681    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10682    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10683    pub fn highlight_rows<T: 'static>(
10684        &mut self,
10685        rows: RangeInclusive<Anchor>,
10686        color: Option<Hsla>,
10687        should_autoscroll: bool,
10688        cx: &mut ViewContext<Self>,
10689    ) {
10690        let snapshot = self.buffer().read(cx).snapshot(cx);
10691        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10692        let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10693            highlight
10694                .range
10695                .start()
10696                .cmp(&rows.start(), &snapshot)
10697                .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10698        });
10699        match (color, existing_highlight_index) {
10700            (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10701                ix,
10702                RowHighlight {
10703                    index: post_inc(&mut self.highlight_order),
10704                    range: rows,
10705                    should_autoscroll,
10706                    color,
10707                },
10708            ),
10709            (None, Ok(i)) => {
10710                row_highlights.remove(i);
10711            }
10712        }
10713    }
10714
10715    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10716    pub fn clear_row_highlights<T: 'static>(&mut self) {
10717        self.highlighted_rows.remove(&TypeId::of::<T>());
10718    }
10719
10720    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10721    pub fn highlighted_rows<T: 'static>(
10722        &self,
10723    ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10724        Some(
10725            self.highlighted_rows
10726                .get(&TypeId::of::<T>())?
10727                .iter()
10728                .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10729        )
10730    }
10731
10732    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10733    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10734    /// Allows to ignore certain kinds of highlights.
10735    pub fn highlighted_display_rows(
10736        &mut self,
10737        cx: &mut WindowContext,
10738    ) -> BTreeMap<DisplayRow, Hsla> {
10739        let snapshot = self.snapshot(cx);
10740        let mut used_highlight_orders = HashMap::default();
10741        self.highlighted_rows
10742            .iter()
10743            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10744            .fold(
10745                BTreeMap::<DisplayRow, Hsla>::new(),
10746                |mut unique_rows, highlight| {
10747                    let start_row = highlight.range.start().to_display_point(&snapshot).row();
10748                    let end_row = highlight.range.end().to_display_point(&snapshot).row();
10749                    for row in start_row.0..=end_row.0 {
10750                        let used_index =
10751                            used_highlight_orders.entry(row).or_insert(highlight.index);
10752                        if highlight.index >= *used_index {
10753                            *used_index = highlight.index;
10754                            match highlight.color {
10755                                Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10756                                None => unique_rows.remove(&DisplayRow(row)),
10757                            };
10758                        }
10759                    }
10760                    unique_rows
10761                },
10762            )
10763    }
10764
10765    pub fn highlighted_display_row_for_autoscroll(
10766        &self,
10767        snapshot: &DisplaySnapshot,
10768    ) -> Option<DisplayRow> {
10769        self.highlighted_rows
10770            .values()
10771            .flat_map(|highlighted_rows| highlighted_rows.iter())
10772            .filter_map(|highlight| {
10773                if highlight.color.is_none() || !highlight.should_autoscroll {
10774                    return None;
10775                }
10776                Some(highlight.range.start().to_display_point(&snapshot).row())
10777            })
10778            .min()
10779    }
10780
10781    pub fn set_search_within_ranges(
10782        &mut self,
10783        ranges: &[Range<Anchor>],
10784        cx: &mut ViewContext<Self>,
10785    ) {
10786        self.highlight_background::<SearchWithinRange>(
10787            ranges,
10788            |colors| colors.editor_document_highlight_read_background,
10789            cx,
10790        )
10791    }
10792
10793    pub fn set_breadcrumb_header(&mut self, new_header: String) {
10794        self.breadcrumb_header = Some(new_header);
10795    }
10796
10797    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10798        self.clear_background_highlights::<SearchWithinRange>(cx);
10799    }
10800
10801    pub fn highlight_background<T: 'static>(
10802        &mut self,
10803        ranges: &[Range<Anchor>],
10804        color_fetcher: fn(&ThemeColors) -> Hsla,
10805        cx: &mut ViewContext<Self>,
10806    ) {
10807        let snapshot = self.snapshot(cx);
10808        // this is to try and catch a panic sooner
10809        for range in ranges {
10810            snapshot
10811                .buffer_snapshot
10812                .summary_for_anchor::<usize>(&range.start);
10813            snapshot
10814                .buffer_snapshot
10815                .summary_for_anchor::<usize>(&range.end);
10816        }
10817
10818        self.background_highlights
10819            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10820        self.scrollbar_marker_state.dirty = true;
10821        cx.notify();
10822    }
10823
10824    pub fn clear_background_highlights<T: 'static>(
10825        &mut self,
10826        cx: &mut ViewContext<Self>,
10827    ) -> Option<BackgroundHighlight> {
10828        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10829        if !text_highlights.1.is_empty() {
10830            self.scrollbar_marker_state.dirty = true;
10831            cx.notify();
10832        }
10833        Some(text_highlights)
10834    }
10835
10836    pub fn highlight_gutter<T: 'static>(
10837        &mut self,
10838        ranges: &[Range<Anchor>],
10839        color_fetcher: fn(&AppContext) -> Hsla,
10840        cx: &mut ViewContext<Self>,
10841    ) {
10842        self.gutter_highlights
10843            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10844        cx.notify();
10845    }
10846
10847    pub fn clear_gutter_highlights<T: 'static>(
10848        &mut self,
10849        cx: &mut ViewContext<Self>,
10850    ) -> Option<GutterHighlight> {
10851        cx.notify();
10852        self.gutter_highlights.remove(&TypeId::of::<T>())
10853    }
10854
10855    #[cfg(feature = "test-support")]
10856    pub fn all_text_background_highlights(
10857        &mut self,
10858        cx: &mut ViewContext<Self>,
10859    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10860        let snapshot = self.snapshot(cx);
10861        let buffer = &snapshot.buffer_snapshot;
10862        let start = buffer.anchor_before(0);
10863        let end = buffer.anchor_after(buffer.len());
10864        let theme = cx.theme().colors();
10865        self.background_highlights_in_range(start..end, &snapshot, theme)
10866    }
10867
10868    #[cfg(feature = "test-support")]
10869    pub fn search_background_highlights(
10870        &mut self,
10871        cx: &mut ViewContext<Self>,
10872    ) -> Vec<Range<Point>> {
10873        let snapshot = self.buffer().read(cx).snapshot(cx);
10874
10875        let highlights = self
10876            .background_highlights
10877            .get(&TypeId::of::<items::BufferSearchHighlights>());
10878
10879        if let Some((_color, ranges)) = highlights {
10880            ranges
10881                .iter()
10882                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
10883                .collect_vec()
10884        } else {
10885            vec![]
10886        }
10887    }
10888
10889    fn document_highlights_for_position<'a>(
10890        &'a self,
10891        position: Anchor,
10892        buffer: &'a MultiBufferSnapshot,
10893    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
10894        let read_highlights = self
10895            .background_highlights
10896            .get(&TypeId::of::<DocumentHighlightRead>())
10897            .map(|h| &h.1);
10898        let write_highlights = self
10899            .background_highlights
10900            .get(&TypeId::of::<DocumentHighlightWrite>())
10901            .map(|h| &h.1);
10902        let left_position = position.bias_left(buffer);
10903        let right_position = position.bias_right(buffer);
10904        read_highlights
10905            .into_iter()
10906            .chain(write_highlights)
10907            .flat_map(move |ranges| {
10908                let start_ix = match ranges.binary_search_by(|probe| {
10909                    let cmp = probe.end.cmp(&left_position, buffer);
10910                    if cmp.is_ge() {
10911                        Ordering::Greater
10912                    } else {
10913                        Ordering::Less
10914                    }
10915                }) {
10916                    Ok(i) | Err(i) => i,
10917                };
10918
10919                ranges[start_ix..]
10920                    .iter()
10921                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
10922            })
10923    }
10924
10925    pub fn has_background_highlights<T: 'static>(&self) -> bool {
10926        self.background_highlights
10927            .get(&TypeId::of::<T>())
10928            .map_or(false, |(_, highlights)| !highlights.is_empty())
10929    }
10930
10931    pub fn background_highlights_in_range(
10932        &self,
10933        search_range: Range<Anchor>,
10934        display_snapshot: &DisplaySnapshot,
10935        theme: &ThemeColors,
10936    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10937        let mut results = Vec::new();
10938        for (color_fetcher, ranges) in self.background_highlights.values() {
10939            let color = color_fetcher(theme);
10940            let start_ix = match ranges.binary_search_by(|probe| {
10941                let cmp = probe
10942                    .end
10943                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10944                if cmp.is_gt() {
10945                    Ordering::Greater
10946                } else {
10947                    Ordering::Less
10948                }
10949            }) {
10950                Ok(i) | Err(i) => i,
10951            };
10952            for range in &ranges[start_ix..] {
10953                if range
10954                    .start
10955                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10956                    .is_ge()
10957                {
10958                    break;
10959                }
10960
10961                let start = range.start.to_display_point(&display_snapshot);
10962                let end = range.end.to_display_point(&display_snapshot);
10963                results.push((start..end, color))
10964            }
10965        }
10966        results
10967    }
10968
10969    pub fn background_highlight_row_ranges<T: 'static>(
10970        &self,
10971        search_range: Range<Anchor>,
10972        display_snapshot: &DisplaySnapshot,
10973        count: usize,
10974    ) -> Vec<RangeInclusive<DisplayPoint>> {
10975        let mut results = Vec::new();
10976        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
10977            return vec![];
10978        };
10979
10980        let start_ix = match ranges.binary_search_by(|probe| {
10981            let cmp = probe
10982                .end
10983                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10984            if cmp.is_gt() {
10985                Ordering::Greater
10986            } else {
10987                Ordering::Less
10988            }
10989        }) {
10990            Ok(i) | Err(i) => i,
10991        };
10992        let mut push_region = |start: Option<Point>, end: Option<Point>| {
10993            if let (Some(start_display), Some(end_display)) = (start, end) {
10994                results.push(
10995                    start_display.to_display_point(display_snapshot)
10996                        ..=end_display.to_display_point(display_snapshot),
10997                );
10998            }
10999        };
11000        let mut start_row: Option<Point> = None;
11001        let mut end_row: Option<Point> = None;
11002        if ranges.len() > count {
11003            return Vec::new();
11004        }
11005        for range in &ranges[start_ix..] {
11006            if range
11007                .start
11008                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11009                .is_ge()
11010            {
11011                break;
11012            }
11013            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11014            if let Some(current_row) = &end_row {
11015                if end.row == current_row.row {
11016                    continue;
11017                }
11018            }
11019            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11020            if start_row.is_none() {
11021                assert_eq!(end_row, None);
11022                start_row = Some(start);
11023                end_row = Some(end);
11024                continue;
11025            }
11026            if let Some(current_end) = end_row.as_mut() {
11027                if start.row > current_end.row + 1 {
11028                    push_region(start_row, end_row);
11029                    start_row = Some(start);
11030                    end_row = Some(end);
11031                } else {
11032                    // Merge two hunks.
11033                    *current_end = end;
11034                }
11035            } else {
11036                unreachable!();
11037            }
11038        }
11039        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11040        push_region(start_row, end_row);
11041        results
11042    }
11043
11044    pub fn gutter_highlights_in_range(
11045        &self,
11046        search_range: Range<Anchor>,
11047        display_snapshot: &DisplaySnapshot,
11048        cx: &AppContext,
11049    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11050        let mut results = Vec::new();
11051        for (color_fetcher, ranges) in self.gutter_highlights.values() {
11052            let color = color_fetcher(cx);
11053            let start_ix = match ranges.binary_search_by(|probe| {
11054                let cmp = probe
11055                    .end
11056                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11057                if cmp.is_gt() {
11058                    Ordering::Greater
11059                } else {
11060                    Ordering::Less
11061                }
11062            }) {
11063                Ok(i) | Err(i) => i,
11064            };
11065            for range in &ranges[start_ix..] {
11066                if range
11067                    .start
11068                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11069                    .is_ge()
11070                {
11071                    break;
11072                }
11073
11074                let start = range.start.to_display_point(&display_snapshot);
11075                let end = range.end.to_display_point(&display_snapshot);
11076                results.push((start..end, color))
11077            }
11078        }
11079        results
11080    }
11081
11082    /// Get the text ranges corresponding to the redaction query
11083    pub fn redacted_ranges(
11084        &self,
11085        search_range: Range<Anchor>,
11086        display_snapshot: &DisplaySnapshot,
11087        cx: &WindowContext,
11088    ) -> Vec<Range<DisplayPoint>> {
11089        display_snapshot
11090            .buffer_snapshot
11091            .redacted_ranges(search_range, |file| {
11092                if let Some(file) = file {
11093                    file.is_private()
11094                        && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11095                } else {
11096                    false
11097                }
11098            })
11099            .map(|range| {
11100                range.start.to_display_point(display_snapshot)
11101                    ..range.end.to_display_point(display_snapshot)
11102            })
11103            .collect()
11104    }
11105
11106    pub fn highlight_text<T: 'static>(
11107        &mut self,
11108        ranges: Vec<Range<Anchor>>,
11109        style: HighlightStyle,
11110        cx: &mut ViewContext<Self>,
11111    ) {
11112        self.display_map.update(cx, |map, _| {
11113            map.highlight_text(TypeId::of::<T>(), ranges, style)
11114        });
11115        cx.notify();
11116    }
11117
11118    pub(crate) fn highlight_inlays<T: 'static>(
11119        &mut self,
11120        highlights: Vec<InlayHighlight>,
11121        style: HighlightStyle,
11122        cx: &mut ViewContext<Self>,
11123    ) {
11124        self.display_map.update(cx, |map, _| {
11125            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11126        });
11127        cx.notify();
11128    }
11129
11130    pub fn text_highlights<'a, T: 'static>(
11131        &'a self,
11132        cx: &'a AppContext,
11133    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11134        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11135    }
11136
11137    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11138        let cleared = self
11139            .display_map
11140            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11141        if cleared {
11142            cx.notify();
11143        }
11144    }
11145
11146    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11147        (self.read_only(cx) || self.blink_manager.read(cx).visible())
11148            && self.focus_handle.is_focused(cx)
11149    }
11150
11151    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11152        self.show_cursor_when_unfocused = is_enabled;
11153        cx.notify();
11154    }
11155
11156    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11157        cx.notify();
11158    }
11159
11160    fn on_buffer_event(
11161        &mut self,
11162        multibuffer: Model<MultiBuffer>,
11163        event: &multi_buffer::Event,
11164        cx: &mut ViewContext<Self>,
11165    ) {
11166        match event {
11167            multi_buffer::Event::Edited {
11168                singleton_buffer_edited,
11169            } => {
11170                self.scrollbar_marker_state.dirty = true;
11171                self.active_indent_guides_state.dirty = true;
11172                self.refresh_active_diagnostics(cx);
11173                self.refresh_code_actions(cx);
11174                if self.has_active_inline_completion(cx) {
11175                    self.update_visible_inline_completion(cx);
11176                }
11177                cx.emit(EditorEvent::BufferEdited);
11178                cx.emit(SearchEvent::MatchesInvalidated);
11179                if *singleton_buffer_edited {
11180                    if let Some(project) = &self.project {
11181                        let project = project.read(cx);
11182                        #[allow(clippy::mutable_key_type)]
11183                        let languages_affected = multibuffer
11184                            .read(cx)
11185                            .all_buffers()
11186                            .into_iter()
11187                            .filter_map(|buffer| {
11188                                let buffer = buffer.read(cx);
11189                                let language = buffer.language()?;
11190                                if project.is_local()
11191                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
11192                                {
11193                                    None
11194                                } else {
11195                                    Some(language)
11196                                }
11197                            })
11198                            .cloned()
11199                            .collect::<HashSet<_>>();
11200                        if !languages_affected.is_empty() {
11201                            self.refresh_inlay_hints(
11202                                InlayHintRefreshReason::BufferEdited(languages_affected),
11203                                cx,
11204                            );
11205                        }
11206                    }
11207                }
11208
11209                let Some(project) = &self.project else { return };
11210                let telemetry = project.read(cx).client().telemetry().clone();
11211                refresh_linked_ranges(self, cx);
11212                telemetry.log_edit_event("editor");
11213            }
11214            multi_buffer::Event::ExcerptsAdded {
11215                buffer,
11216                predecessor,
11217                excerpts,
11218            } => {
11219                self.tasks_update_task = Some(self.refresh_runnables(cx));
11220                cx.emit(EditorEvent::ExcerptsAdded {
11221                    buffer: buffer.clone(),
11222                    predecessor: *predecessor,
11223                    excerpts: excerpts.clone(),
11224                });
11225                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11226            }
11227            multi_buffer::Event::ExcerptsRemoved { ids } => {
11228                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11229                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11230            }
11231            multi_buffer::Event::ExcerptsEdited { ids } => {
11232                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11233            }
11234            multi_buffer::Event::ExcerptsExpanded { ids } => {
11235                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11236            }
11237            multi_buffer::Event::Reparsed(buffer_id) => {
11238                self.tasks_update_task = Some(self.refresh_runnables(cx));
11239
11240                cx.emit(EditorEvent::Reparsed(*buffer_id));
11241            }
11242            multi_buffer::Event::LanguageChanged(buffer_id) => {
11243                linked_editing_ranges::refresh_linked_ranges(self, cx);
11244                cx.emit(EditorEvent::Reparsed(*buffer_id));
11245                cx.notify();
11246            }
11247            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11248            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11249            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11250                cx.emit(EditorEvent::TitleChanged)
11251            }
11252            multi_buffer::Event::DiffBaseChanged => {
11253                self.scrollbar_marker_state.dirty = true;
11254                cx.emit(EditorEvent::DiffBaseChanged);
11255                cx.notify();
11256            }
11257            multi_buffer::Event::DiffUpdated { buffer } => {
11258                self.sync_expanded_diff_hunks(buffer.clone(), cx);
11259                cx.notify();
11260            }
11261            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11262            multi_buffer::Event::DiagnosticsUpdated => {
11263                self.refresh_active_diagnostics(cx);
11264                self.scrollbar_marker_state.dirty = true;
11265                cx.notify();
11266            }
11267            _ => {}
11268        };
11269    }
11270
11271    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11272        cx.notify();
11273    }
11274
11275    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11276        self.tasks_update_task = Some(self.refresh_runnables(cx));
11277        self.refresh_inline_completion(true, cx);
11278        self.refresh_inlay_hints(
11279            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11280                self.selections.newest_anchor().head(),
11281                &self.buffer.read(cx).snapshot(cx),
11282                cx,
11283            )),
11284            cx,
11285        );
11286        let editor_settings = EditorSettings::get_global(cx);
11287        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11288        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11289
11290        let project_settings = ProjectSettings::get_global(cx);
11291        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11292
11293        if self.mode == EditorMode::Full {
11294            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11295            if self.git_blame_inline_enabled != inline_blame_enabled {
11296                self.toggle_git_blame_inline_internal(false, cx);
11297            }
11298        }
11299
11300        cx.notify();
11301    }
11302
11303    pub fn set_searchable(&mut self, searchable: bool) {
11304        self.searchable = searchable;
11305    }
11306
11307    pub fn searchable(&self) -> bool {
11308        self.searchable
11309    }
11310
11311    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11312        self.open_excerpts_common(true, cx)
11313    }
11314
11315    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11316        self.open_excerpts_common(false, cx)
11317    }
11318
11319    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11320        let buffer = self.buffer.read(cx);
11321        if buffer.is_singleton() {
11322            cx.propagate();
11323            return;
11324        }
11325
11326        let Some(workspace) = self.workspace() else {
11327            cx.propagate();
11328            return;
11329        };
11330
11331        let mut new_selections_by_buffer = HashMap::default();
11332        for selection in self.selections.all::<usize>(cx) {
11333            for (buffer, mut range, _) in
11334                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11335            {
11336                if selection.reversed {
11337                    mem::swap(&mut range.start, &mut range.end);
11338                }
11339                new_selections_by_buffer
11340                    .entry(buffer)
11341                    .or_insert(Vec::new())
11342                    .push(range)
11343            }
11344        }
11345
11346        // We defer the pane interaction because we ourselves are a workspace item
11347        // and activating a new item causes the pane to call a method on us reentrantly,
11348        // which panics if we're on the stack.
11349        cx.window_context().defer(move |cx| {
11350            workspace.update(cx, |workspace, cx| {
11351                let pane = if split {
11352                    workspace.adjacent_pane(cx)
11353                } else {
11354                    workspace.active_pane().clone()
11355                };
11356
11357                for (buffer, ranges) in new_selections_by_buffer {
11358                    let editor =
11359                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11360                    editor.update(cx, |editor, cx| {
11361                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11362                            s.select_ranges(ranges);
11363                        });
11364                    });
11365                }
11366            })
11367        });
11368    }
11369
11370    fn jump(
11371        &mut self,
11372        path: ProjectPath,
11373        position: Point,
11374        anchor: language::Anchor,
11375        offset_from_top: u32,
11376        cx: &mut ViewContext<Self>,
11377    ) {
11378        let workspace = self.workspace();
11379        cx.spawn(|_, mut cx| async move {
11380            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11381            let editor = workspace.update(&mut cx, |workspace, cx| {
11382                // Reset the preview item id before opening the new item
11383                workspace.active_pane().update(cx, |pane, cx| {
11384                    pane.set_preview_item_id(None, cx);
11385                });
11386                workspace.open_path_preview(path, None, true, true, cx)
11387            })?;
11388            let editor = editor
11389                .await?
11390                .downcast::<Editor>()
11391                .ok_or_else(|| anyhow!("opened item was not an editor"))?
11392                .downgrade();
11393            editor.update(&mut cx, |editor, cx| {
11394                let buffer = editor
11395                    .buffer()
11396                    .read(cx)
11397                    .as_singleton()
11398                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11399                let buffer = buffer.read(cx);
11400                let cursor = if buffer.can_resolve(&anchor) {
11401                    language::ToPoint::to_point(&anchor, buffer)
11402                } else {
11403                    buffer.clip_point(position, Bias::Left)
11404                };
11405
11406                let nav_history = editor.nav_history.take();
11407                editor.change_selections(
11408                    Some(Autoscroll::top_relative(offset_from_top as usize)),
11409                    cx,
11410                    |s| {
11411                        s.select_ranges([cursor..cursor]);
11412                    },
11413                );
11414                editor.nav_history = nav_history;
11415
11416                anyhow::Ok(())
11417            })??;
11418
11419            anyhow::Ok(())
11420        })
11421        .detach_and_log_err(cx);
11422    }
11423
11424    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11425        let snapshot = self.buffer.read(cx).read(cx);
11426        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11427        Some(
11428            ranges
11429                .iter()
11430                .map(move |range| {
11431                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11432                })
11433                .collect(),
11434        )
11435    }
11436
11437    fn selection_replacement_ranges(
11438        &self,
11439        range: Range<OffsetUtf16>,
11440        cx: &AppContext,
11441    ) -> Vec<Range<OffsetUtf16>> {
11442        let selections = self.selections.all::<OffsetUtf16>(cx);
11443        let newest_selection = selections
11444            .iter()
11445            .max_by_key(|selection| selection.id)
11446            .unwrap();
11447        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11448        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11449        let snapshot = self.buffer.read(cx).read(cx);
11450        selections
11451            .into_iter()
11452            .map(|mut selection| {
11453                selection.start.0 =
11454                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
11455                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11456                snapshot.clip_offset_utf16(selection.start, Bias::Left)
11457                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11458            })
11459            .collect()
11460    }
11461
11462    fn report_editor_event(
11463        &self,
11464        operation: &'static str,
11465        file_extension: Option<String>,
11466        cx: &AppContext,
11467    ) {
11468        if cfg!(any(test, feature = "test-support")) {
11469            return;
11470        }
11471
11472        let Some(project) = &self.project else { return };
11473
11474        // If None, we are in a file without an extension
11475        let file = self
11476            .buffer
11477            .read(cx)
11478            .as_singleton()
11479            .and_then(|b| b.read(cx).file());
11480        let file_extension = file_extension.or(file
11481            .as_ref()
11482            .and_then(|file| Path::new(file.file_name(cx)).extension())
11483            .and_then(|e| e.to_str())
11484            .map(|a| a.to_string()));
11485
11486        let vim_mode = cx
11487            .global::<SettingsStore>()
11488            .raw_user_settings()
11489            .get("vim_mode")
11490            == Some(&serde_json::Value::Bool(true));
11491
11492        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11493            == language::language_settings::InlineCompletionProvider::Copilot;
11494        let copilot_enabled_for_language = self
11495            .buffer
11496            .read(cx)
11497            .settings_at(0, cx)
11498            .show_inline_completions;
11499
11500        let telemetry = project.read(cx).client().telemetry().clone();
11501        telemetry.report_editor_event(
11502            file_extension,
11503            vim_mode,
11504            operation,
11505            copilot_enabled,
11506            copilot_enabled_for_language,
11507        )
11508    }
11509
11510    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11511    /// with each line being an array of {text, highlight} objects.
11512    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11513        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11514            return;
11515        };
11516
11517        #[derive(Serialize)]
11518        struct Chunk<'a> {
11519            text: String,
11520            highlight: Option<&'a str>,
11521        }
11522
11523        let snapshot = buffer.read(cx).snapshot();
11524        let range = self
11525            .selected_text_range(cx)
11526            .and_then(|selected_range| {
11527                if selected_range.is_empty() {
11528                    None
11529                } else {
11530                    Some(selected_range)
11531                }
11532            })
11533            .unwrap_or_else(|| 0..snapshot.len());
11534
11535        let chunks = snapshot.chunks(range, true);
11536        let mut lines = Vec::new();
11537        let mut line: VecDeque<Chunk> = VecDeque::new();
11538
11539        let Some(style) = self.style.as_ref() else {
11540            return;
11541        };
11542
11543        for chunk in chunks {
11544            let highlight = chunk
11545                .syntax_highlight_id
11546                .and_then(|id| id.name(&style.syntax));
11547            let mut chunk_lines = chunk.text.split('\n').peekable();
11548            while let Some(text) = chunk_lines.next() {
11549                let mut merged_with_last_token = false;
11550                if let Some(last_token) = line.back_mut() {
11551                    if last_token.highlight == highlight {
11552                        last_token.text.push_str(text);
11553                        merged_with_last_token = true;
11554                    }
11555                }
11556
11557                if !merged_with_last_token {
11558                    line.push_back(Chunk {
11559                        text: text.into(),
11560                        highlight,
11561                    });
11562                }
11563
11564                if chunk_lines.peek().is_some() {
11565                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
11566                        line.pop_front();
11567                    }
11568                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
11569                        line.pop_back();
11570                    }
11571
11572                    lines.push(mem::take(&mut line));
11573                }
11574            }
11575        }
11576
11577        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11578            return;
11579        };
11580        cx.write_to_clipboard(ClipboardItem::new(lines));
11581    }
11582
11583    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11584        &self.inlay_hint_cache
11585    }
11586
11587    pub fn replay_insert_event(
11588        &mut self,
11589        text: &str,
11590        relative_utf16_range: Option<Range<isize>>,
11591        cx: &mut ViewContext<Self>,
11592    ) {
11593        if !self.input_enabled {
11594            cx.emit(EditorEvent::InputIgnored { text: text.into() });
11595            return;
11596        }
11597        if let Some(relative_utf16_range) = relative_utf16_range {
11598            let selections = self.selections.all::<OffsetUtf16>(cx);
11599            self.change_selections(None, cx, |s| {
11600                let new_ranges = selections.into_iter().map(|range| {
11601                    let start = OffsetUtf16(
11602                        range
11603                            .head()
11604                            .0
11605                            .saturating_add_signed(relative_utf16_range.start),
11606                    );
11607                    let end = OffsetUtf16(
11608                        range
11609                            .head()
11610                            .0
11611                            .saturating_add_signed(relative_utf16_range.end),
11612                    );
11613                    start..end
11614                });
11615                s.select_ranges(new_ranges);
11616            });
11617        }
11618
11619        self.handle_input(text, cx);
11620    }
11621
11622    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11623        let Some(project) = self.project.as_ref() else {
11624            return false;
11625        };
11626        let project = project.read(cx);
11627
11628        let mut supports = false;
11629        self.buffer().read(cx).for_each_buffer(|buffer| {
11630            if !supports {
11631                supports = project
11632                    .language_servers_for_buffer(buffer.read(cx), cx)
11633                    .any(
11634                        |(_, server)| match server.capabilities().inlay_hint_provider {
11635                            Some(lsp::OneOf::Left(enabled)) => enabled,
11636                            Some(lsp::OneOf::Right(_)) => true,
11637                            None => false,
11638                        },
11639                    )
11640            }
11641        });
11642        supports
11643    }
11644
11645    pub fn focus(&self, cx: &mut WindowContext) {
11646        cx.focus(&self.focus_handle)
11647    }
11648
11649    pub fn is_focused(&self, cx: &WindowContext) -> bool {
11650        self.focus_handle.is_focused(cx)
11651    }
11652
11653    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11654        cx.emit(EditorEvent::Focused);
11655
11656        if let Some(descendant) = self
11657            .last_focused_descendant
11658            .take()
11659            .and_then(|descendant| descendant.upgrade())
11660        {
11661            cx.focus(&descendant);
11662        } else {
11663            if let Some(blame) = self.blame.as_ref() {
11664                blame.update(cx, GitBlame::focus)
11665            }
11666
11667            self.blink_manager.update(cx, BlinkManager::enable);
11668            self.show_cursor_names(cx);
11669            self.buffer.update(cx, |buffer, cx| {
11670                buffer.finalize_last_transaction(cx);
11671                if self.leader_peer_id.is_none() {
11672                    buffer.set_active_selections(
11673                        &self.selections.disjoint_anchors(),
11674                        self.selections.line_mode,
11675                        self.cursor_shape,
11676                        cx,
11677                    );
11678                }
11679            });
11680        }
11681    }
11682
11683    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
11684        cx.emit(EditorEvent::FocusedIn)
11685    }
11686
11687    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11688        if event.blurred != self.focus_handle {
11689            self.last_focused_descendant = Some(event.blurred);
11690        }
11691    }
11692
11693    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11694        self.blink_manager.update(cx, BlinkManager::disable);
11695        self.buffer
11696            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11697
11698        if let Some(blame) = self.blame.as_ref() {
11699            blame.update(cx, GitBlame::blur)
11700        }
11701        if !self.hover_state.focused(cx) {
11702            hide_hover(self, cx);
11703        }
11704
11705        self.hide_context_menu(cx);
11706        cx.emit(EditorEvent::Blurred);
11707        cx.notify();
11708    }
11709
11710    pub fn register_action<A: Action>(
11711        &mut self,
11712        listener: impl Fn(&A, &mut WindowContext) + 'static,
11713    ) -> Subscription {
11714        let id = self.next_editor_action_id.post_inc();
11715        let listener = Arc::new(listener);
11716        self.editor_actions.borrow_mut().insert(
11717            id,
11718            Box::new(move |cx| {
11719                let _view = cx.view().clone();
11720                let cx = cx.window_context();
11721                let listener = listener.clone();
11722                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11723                    let action = action.downcast_ref().unwrap();
11724                    if phase == DispatchPhase::Bubble {
11725                        listener(action, cx)
11726                    }
11727                })
11728            }),
11729        );
11730
11731        let editor_actions = self.editor_actions.clone();
11732        Subscription::new(move || {
11733            editor_actions.borrow_mut().remove(&id);
11734        })
11735    }
11736
11737    pub fn file_header_size(&self) -> u8 {
11738        self.file_header_size
11739    }
11740}
11741
11742fn hunks_for_selections(
11743    multi_buffer_snapshot: &MultiBufferSnapshot,
11744    selections: &[Selection<Anchor>],
11745) -> Vec<DiffHunk<MultiBufferRow>> {
11746    let mut hunks = Vec::with_capacity(selections.len());
11747    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11748        HashMap::default();
11749    let buffer_rows_for_selections = selections.iter().map(|selection| {
11750        let head = selection.head();
11751        let tail = selection.tail();
11752        let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11753        let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11754        if start > end {
11755            end..start
11756        } else {
11757            start..end
11758        }
11759    });
11760
11761    for selected_multi_buffer_rows in buffer_rows_for_selections {
11762        let query_rows =
11763            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11764        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11765            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11766            // when the caret is just above or just below the deleted hunk.
11767            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11768            let related_to_selection = if allow_adjacent {
11769                hunk.associated_range.overlaps(&query_rows)
11770                    || hunk.associated_range.start == query_rows.end
11771                    || hunk.associated_range.end == query_rows.start
11772            } else {
11773                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11774                // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11775                hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11776                    || selected_multi_buffer_rows.end == hunk.associated_range.start
11777            };
11778            if related_to_selection {
11779                if !processed_buffer_rows
11780                    .entry(hunk.buffer_id)
11781                    .or_default()
11782                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
11783                {
11784                    continue;
11785                }
11786                hunks.push(hunk);
11787            }
11788        }
11789    }
11790
11791    hunks
11792}
11793
11794pub trait CollaborationHub {
11795    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
11796    fn user_participant_indices<'a>(
11797        &self,
11798        cx: &'a AppContext,
11799    ) -> &'a HashMap<u64, ParticipantIndex>;
11800    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
11801}
11802
11803impl CollaborationHub for Model<Project> {
11804    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
11805        self.read(cx).collaborators()
11806    }
11807
11808    fn user_participant_indices<'a>(
11809        &self,
11810        cx: &'a AppContext,
11811    ) -> &'a HashMap<u64, ParticipantIndex> {
11812        self.read(cx).user_store().read(cx).participant_indices()
11813    }
11814
11815    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
11816        let this = self.read(cx);
11817        let user_ids = this.collaborators().values().map(|c| c.user_id);
11818        this.user_store().read_with(cx, |user_store, cx| {
11819            user_store.participant_names(user_ids, cx)
11820        })
11821    }
11822}
11823
11824pub trait CompletionProvider {
11825    fn completions(
11826        &self,
11827        buffer: &Model<Buffer>,
11828        buffer_position: text::Anchor,
11829        trigger: CompletionContext,
11830        cx: &mut ViewContext<Editor>,
11831    ) -> Task<Result<Vec<Completion>>>;
11832
11833    fn resolve_completions(
11834        &self,
11835        buffer: Model<Buffer>,
11836        completion_indices: Vec<usize>,
11837        completions: Arc<RwLock<Box<[Completion]>>>,
11838        cx: &mut ViewContext<Editor>,
11839    ) -> Task<Result<bool>>;
11840
11841    fn apply_additional_edits_for_completion(
11842        &self,
11843        buffer: Model<Buffer>,
11844        completion: Completion,
11845        push_to_history: bool,
11846        cx: &mut ViewContext<Editor>,
11847    ) -> Task<Result<Option<language::Transaction>>>;
11848
11849    fn is_completion_trigger(
11850        &self,
11851        buffer: &Model<Buffer>,
11852        position: language::Anchor,
11853        text: &str,
11854        trigger_in_words: bool,
11855        cx: &mut ViewContext<Editor>,
11856    ) -> bool;
11857}
11858
11859fn snippet_completions(
11860    project: &Project,
11861    buffer: &Model<Buffer>,
11862    buffer_position: text::Anchor,
11863    cx: &mut AppContext,
11864) -> Vec<Completion> {
11865    let language = buffer.read(cx).language_at(buffer_position);
11866    let language_name = language.as_ref().map(|language| language.lsp_id());
11867    let snippet_store = project.snippets().read(cx);
11868    let snippets = snippet_store.snippets_for(language_name, cx);
11869
11870    if snippets.is_empty() {
11871        return vec![];
11872    }
11873    let snapshot = buffer.read(cx).text_snapshot();
11874    let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
11875
11876    let mut lines = chunks.lines();
11877    let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
11878        return vec![];
11879    };
11880
11881    let scope = language.map(|language| language.default_scope());
11882    let mut last_word = line_at
11883        .chars()
11884        .rev()
11885        .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
11886        .collect::<String>();
11887    last_word = last_word.chars().rev().collect();
11888    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
11889    let to_lsp = |point: &text::Anchor| {
11890        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
11891        point_to_lsp(end)
11892    };
11893    let lsp_end = to_lsp(&buffer_position);
11894    snippets
11895        .into_iter()
11896        .filter_map(|snippet| {
11897            let matching_prefix = snippet
11898                .prefix
11899                .iter()
11900                .find(|prefix| prefix.starts_with(&last_word))?;
11901            let start = as_offset - last_word.len();
11902            let start = snapshot.anchor_before(start);
11903            let range = start..buffer_position;
11904            let lsp_start = to_lsp(&start);
11905            let lsp_range = lsp::Range {
11906                start: lsp_start,
11907                end: lsp_end,
11908            };
11909            Some(Completion {
11910                old_range: range,
11911                new_text: snippet.body.clone(),
11912                label: CodeLabel {
11913                    text: matching_prefix.clone(),
11914                    runs: vec![],
11915                    filter_range: 0..matching_prefix.len(),
11916                },
11917                server_id: LanguageServerId(usize::MAX),
11918                documentation: snippet
11919                    .description
11920                    .clone()
11921                    .map(|description| Documentation::SingleLine(description)),
11922                lsp_completion: lsp::CompletionItem {
11923                    label: snippet.prefix.first().unwrap().clone(),
11924                    kind: Some(CompletionItemKind::SNIPPET),
11925                    label_details: snippet.description.as_ref().map(|description| {
11926                        lsp::CompletionItemLabelDetails {
11927                            detail: Some(description.clone()),
11928                            description: None,
11929                        }
11930                    }),
11931                    insert_text_format: Some(InsertTextFormat::SNIPPET),
11932                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
11933                        lsp::InsertReplaceEdit {
11934                            new_text: snippet.body.clone(),
11935                            insert: lsp_range,
11936                            replace: lsp_range,
11937                        },
11938                    )),
11939                    filter_text: Some(snippet.body.clone()),
11940                    sort_text: Some(char::MAX.to_string()),
11941                    ..Default::default()
11942                },
11943                confirm: None,
11944                show_new_completions_on_confirm: false,
11945            })
11946        })
11947        .collect()
11948}
11949
11950impl CompletionProvider for Model<Project> {
11951    fn completions(
11952        &self,
11953        buffer: &Model<Buffer>,
11954        buffer_position: text::Anchor,
11955        options: CompletionContext,
11956        cx: &mut ViewContext<Editor>,
11957    ) -> Task<Result<Vec<Completion>>> {
11958        self.update(cx, |project, cx| {
11959            let snippets = snippet_completions(project, buffer, buffer_position, cx);
11960            let project_completions = project.completions(&buffer, buffer_position, options, cx);
11961            cx.background_executor().spawn(async move {
11962                let mut completions = project_completions.await?;
11963                //let snippets = snippets.into_iter().;
11964                completions.extend(snippets);
11965                Ok(completions)
11966            })
11967        })
11968    }
11969
11970    fn resolve_completions(
11971        &self,
11972        buffer: Model<Buffer>,
11973        completion_indices: Vec<usize>,
11974        completions: Arc<RwLock<Box<[Completion]>>>,
11975        cx: &mut ViewContext<Editor>,
11976    ) -> Task<Result<bool>> {
11977        self.update(cx, |project, cx| {
11978            project.resolve_completions(buffer, completion_indices, completions, cx)
11979        })
11980    }
11981
11982    fn apply_additional_edits_for_completion(
11983        &self,
11984        buffer: Model<Buffer>,
11985        completion: Completion,
11986        push_to_history: bool,
11987        cx: &mut ViewContext<Editor>,
11988    ) -> Task<Result<Option<language::Transaction>>> {
11989        self.update(cx, |project, cx| {
11990            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
11991        })
11992    }
11993
11994    fn is_completion_trigger(
11995        &self,
11996        buffer: &Model<Buffer>,
11997        position: language::Anchor,
11998        text: &str,
11999        trigger_in_words: bool,
12000        cx: &mut ViewContext<Editor>,
12001    ) -> bool {
12002        if !EditorSettings::get_global(cx).show_completions_on_input {
12003            return false;
12004        }
12005
12006        let mut chars = text.chars();
12007        let char = if let Some(char) = chars.next() {
12008            char
12009        } else {
12010            return false;
12011        };
12012        if chars.next().is_some() {
12013            return false;
12014        }
12015
12016        let buffer = buffer.read(cx);
12017        let scope = buffer.snapshot().language_scope_at(position);
12018        if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
12019            return true;
12020        }
12021
12022        buffer
12023            .completion_triggers()
12024            .iter()
12025            .any(|string| string == text)
12026    }
12027}
12028
12029fn inlay_hint_settings(
12030    location: Anchor,
12031    snapshot: &MultiBufferSnapshot,
12032    cx: &mut ViewContext<'_, Editor>,
12033) -> InlayHintSettings {
12034    let file = snapshot.file_at(location);
12035    let language = snapshot.language_at(location);
12036    let settings = all_language_settings(file, cx);
12037    settings
12038        .language(language.map(|l| l.name()).as_deref())
12039        .inlay_hints
12040}
12041
12042fn consume_contiguous_rows(
12043    contiguous_row_selections: &mut Vec<Selection<Point>>,
12044    selection: &Selection<Point>,
12045    display_map: &DisplaySnapshot,
12046    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12047) -> (MultiBufferRow, MultiBufferRow) {
12048    contiguous_row_selections.push(selection.clone());
12049    let start_row = MultiBufferRow(selection.start.row);
12050    let mut end_row = ending_row(selection, display_map);
12051
12052    while let Some(next_selection) = selections.peek() {
12053        if next_selection.start.row <= end_row.0 {
12054            end_row = ending_row(next_selection, display_map);
12055            contiguous_row_selections.push(selections.next().unwrap().clone());
12056        } else {
12057            break;
12058        }
12059    }
12060    (start_row, end_row)
12061}
12062
12063fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12064    if next_selection.end.column > 0 || next_selection.is_empty() {
12065        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12066    } else {
12067        MultiBufferRow(next_selection.end.row)
12068    }
12069}
12070
12071impl EditorSnapshot {
12072    pub fn remote_selections_in_range<'a>(
12073        &'a self,
12074        range: &'a Range<Anchor>,
12075        collaboration_hub: &dyn CollaborationHub,
12076        cx: &'a AppContext,
12077    ) -> impl 'a + Iterator<Item = RemoteSelection> {
12078        let participant_names = collaboration_hub.user_names(cx);
12079        let participant_indices = collaboration_hub.user_participant_indices(cx);
12080        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12081        let collaborators_by_replica_id = collaborators_by_peer_id
12082            .iter()
12083            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12084            .collect::<HashMap<_, _>>();
12085        self.buffer_snapshot
12086            .selections_in_range(range, false)
12087            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12088                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12089                let participant_index = participant_indices.get(&collaborator.user_id).copied();
12090                let user_name = participant_names.get(&collaborator.user_id).cloned();
12091                Some(RemoteSelection {
12092                    replica_id,
12093                    selection,
12094                    cursor_shape,
12095                    line_mode,
12096                    participant_index,
12097                    peer_id: collaborator.peer_id,
12098                    user_name,
12099                })
12100            })
12101    }
12102
12103    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12104        self.display_snapshot.buffer_snapshot.language_at(position)
12105    }
12106
12107    pub fn is_focused(&self) -> bool {
12108        self.is_focused
12109    }
12110
12111    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12112        self.placeholder_text.as_ref()
12113    }
12114
12115    pub fn scroll_position(&self) -> gpui::Point<f32> {
12116        self.scroll_anchor.scroll_position(&self.display_snapshot)
12117    }
12118
12119    pub fn gutter_dimensions(
12120        &self,
12121        font_id: FontId,
12122        font_size: Pixels,
12123        em_width: Pixels,
12124        max_line_number_width: Pixels,
12125        cx: &AppContext,
12126    ) -> GutterDimensions {
12127        if !self.show_gutter {
12128            return GutterDimensions::default();
12129        }
12130        let descent = cx.text_system().descent(font_id, font_size);
12131
12132        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12133            matches!(
12134                ProjectSettings::get_global(cx).git.git_gutter,
12135                Some(GitGutterSetting::TrackedFiles)
12136            )
12137        });
12138        let gutter_settings = EditorSettings::get_global(cx).gutter;
12139        let show_line_numbers = self
12140            .show_line_numbers
12141            .unwrap_or(gutter_settings.line_numbers);
12142        let line_gutter_width = if show_line_numbers {
12143            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12144            let min_width_for_number_on_gutter = em_width * 4.0;
12145            max_line_number_width.max(min_width_for_number_on_gutter)
12146        } else {
12147            0.0.into()
12148        };
12149
12150        let show_code_actions = self
12151            .show_code_actions
12152            .unwrap_or(gutter_settings.code_actions);
12153
12154        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12155
12156        let git_blame_entries_width = self
12157            .render_git_blame_gutter
12158            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12159
12160        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12161        left_padding += if show_code_actions || show_runnables {
12162            em_width * 3.0
12163        } else if show_git_gutter && show_line_numbers {
12164            em_width * 2.0
12165        } else if show_git_gutter || show_line_numbers {
12166            em_width
12167        } else {
12168            px(0.)
12169        };
12170
12171        let right_padding = if gutter_settings.folds && show_line_numbers {
12172            em_width * 4.0
12173        } else if gutter_settings.folds {
12174            em_width * 3.0
12175        } else if show_line_numbers {
12176            em_width
12177        } else {
12178            px(0.)
12179        };
12180
12181        GutterDimensions {
12182            left_padding,
12183            right_padding,
12184            width: line_gutter_width + left_padding + right_padding,
12185            margin: -descent,
12186            git_blame_entries_width,
12187        }
12188    }
12189
12190    pub fn render_fold_toggle(
12191        &self,
12192        buffer_row: MultiBufferRow,
12193        row_contains_cursor: bool,
12194        editor: View<Editor>,
12195        cx: &mut WindowContext,
12196    ) -> Option<AnyElement> {
12197        let folded = self.is_line_folded(buffer_row);
12198
12199        if let Some(crease) = self
12200            .crease_snapshot
12201            .query_row(buffer_row, &self.buffer_snapshot)
12202        {
12203            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12204                if folded {
12205                    editor.update(cx, |editor, cx| {
12206                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12207                    });
12208                } else {
12209                    editor.update(cx, |editor, cx| {
12210                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12211                    });
12212                }
12213            });
12214
12215            Some((crease.render_toggle)(
12216                buffer_row,
12217                folded,
12218                toggle_callback,
12219                cx,
12220            ))
12221        } else if folded
12222            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12223        {
12224            Some(
12225                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12226                    .selected(folded)
12227                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12228                        if folded {
12229                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
12230                        } else {
12231                            this.fold_at(&FoldAt { buffer_row }, cx);
12232                        }
12233                    }))
12234                    .into_any_element(),
12235            )
12236        } else {
12237            None
12238        }
12239    }
12240
12241    pub fn render_crease_trailer(
12242        &self,
12243        buffer_row: MultiBufferRow,
12244        cx: &mut WindowContext,
12245    ) -> Option<AnyElement> {
12246        let folded = self.is_line_folded(buffer_row);
12247        let crease = self
12248            .crease_snapshot
12249            .query_row(buffer_row, &self.buffer_snapshot)?;
12250        Some((crease.render_trailer)(buffer_row, folded, cx))
12251    }
12252}
12253
12254impl Deref for EditorSnapshot {
12255    type Target = DisplaySnapshot;
12256
12257    fn deref(&self) -> &Self::Target {
12258        &self.display_snapshot
12259    }
12260}
12261
12262#[derive(Clone, Debug, PartialEq, Eq)]
12263pub enum EditorEvent {
12264    InputIgnored {
12265        text: Arc<str>,
12266    },
12267    InputHandled {
12268        utf16_range_to_replace: Option<Range<isize>>,
12269        text: Arc<str>,
12270    },
12271    ExcerptsAdded {
12272        buffer: Model<Buffer>,
12273        predecessor: ExcerptId,
12274        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12275    },
12276    ExcerptsRemoved {
12277        ids: Vec<ExcerptId>,
12278    },
12279    ExcerptsEdited {
12280        ids: Vec<ExcerptId>,
12281    },
12282    ExcerptsExpanded {
12283        ids: Vec<ExcerptId>,
12284    },
12285    BufferEdited,
12286    Edited {
12287        transaction_id: clock::Lamport,
12288    },
12289    Reparsed(BufferId),
12290    Focused,
12291    FocusedIn,
12292    Blurred,
12293    DirtyChanged,
12294    Saved,
12295    TitleChanged,
12296    DiffBaseChanged,
12297    SelectionsChanged {
12298        local: bool,
12299    },
12300    ScrollPositionChanged {
12301        local: bool,
12302        autoscroll: bool,
12303    },
12304    Closed,
12305    TransactionUndone {
12306        transaction_id: clock::Lamport,
12307    },
12308    TransactionBegun {
12309        transaction_id: clock::Lamport,
12310    },
12311}
12312
12313impl EventEmitter<EditorEvent> for Editor {}
12314
12315impl FocusableView for Editor {
12316    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12317        self.focus_handle.clone()
12318    }
12319}
12320
12321impl Render for Editor {
12322    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12323        let settings = ThemeSettings::get_global(cx);
12324
12325        let text_style = match self.mode {
12326            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12327                color: cx.theme().colors().editor_foreground,
12328                font_family: settings.ui_font.family.clone(),
12329                font_features: settings.ui_font.features.clone(),
12330                font_size: rems(0.875).into(),
12331                font_weight: settings.ui_font.weight,
12332                font_style: FontStyle::Normal,
12333                line_height: relative(settings.buffer_line_height.value()),
12334                background_color: None,
12335                underline: None,
12336                strikethrough: None,
12337                white_space: WhiteSpace::Normal,
12338            },
12339            EditorMode::Full => TextStyle {
12340                color: cx.theme().colors().editor_foreground,
12341                font_family: settings.buffer_font.family.clone(),
12342                font_features: settings.buffer_font.features.clone(),
12343                font_size: settings.buffer_font_size(cx).into(),
12344                font_weight: settings.buffer_font.weight,
12345                font_style: FontStyle::Normal,
12346                line_height: relative(settings.buffer_line_height.value()),
12347                background_color: None,
12348                underline: None,
12349                strikethrough: None,
12350                white_space: WhiteSpace::Normal,
12351            },
12352        };
12353
12354        let background = match self.mode {
12355            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12356            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12357            EditorMode::Full => cx.theme().colors().editor_background,
12358        };
12359
12360        EditorElement::new(
12361            cx.view(),
12362            EditorStyle {
12363                background,
12364                local_player: cx.theme().players().local(),
12365                text: text_style,
12366                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12367                syntax: cx.theme().syntax().clone(),
12368                status: cx.theme().status().clone(),
12369                inlay_hints_style: HighlightStyle {
12370                    color: Some(cx.theme().status().hint),
12371                    ..HighlightStyle::default()
12372                },
12373                suggestions_style: HighlightStyle {
12374                    color: Some(cx.theme().status().predictive),
12375                    ..HighlightStyle::default()
12376                },
12377            },
12378        )
12379    }
12380}
12381
12382impl ViewInputHandler for Editor {
12383    fn text_for_range(
12384        &mut self,
12385        range_utf16: Range<usize>,
12386        cx: &mut ViewContext<Self>,
12387    ) -> Option<String> {
12388        Some(
12389            self.buffer
12390                .read(cx)
12391                .read(cx)
12392                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12393                .collect(),
12394        )
12395    }
12396
12397    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12398        // Prevent the IME menu from appearing when holding down an alphabetic key
12399        // while input is disabled.
12400        if !self.input_enabled {
12401            return None;
12402        }
12403
12404        let range = self.selections.newest::<OffsetUtf16>(cx).range();
12405        Some(range.start.0..range.end.0)
12406    }
12407
12408    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12409        let snapshot = self.buffer.read(cx).read(cx);
12410        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12411        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12412    }
12413
12414    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12415        self.clear_highlights::<InputComposition>(cx);
12416        self.ime_transaction.take();
12417    }
12418
12419    fn replace_text_in_range(
12420        &mut self,
12421        range_utf16: Option<Range<usize>>,
12422        text: &str,
12423        cx: &mut ViewContext<Self>,
12424    ) {
12425        if !self.input_enabled {
12426            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12427            return;
12428        }
12429
12430        self.transact(cx, |this, cx| {
12431            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12432                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12433                Some(this.selection_replacement_ranges(range_utf16, cx))
12434            } else {
12435                this.marked_text_ranges(cx)
12436            };
12437
12438            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12439                let newest_selection_id = this.selections.newest_anchor().id;
12440                this.selections
12441                    .all::<OffsetUtf16>(cx)
12442                    .iter()
12443                    .zip(ranges_to_replace.iter())
12444                    .find_map(|(selection, range)| {
12445                        if selection.id == newest_selection_id {
12446                            Some(
12447                                (range.start.0 as isize - selection.head().0 as isize)
12448                                    ..(range.end.0 as isize - selection.head().0 as isize),
12449                            )
12450                        } else {
12451                            None
12452                        }
12453                    })
12454            });
12455
12456            cx.emit(EditorEvent::InputHandled {
12457                utf16_range_to_replace: range_to_replace,
12458                text: text.into(),
12459            });
12460
12461            if let Some(new_selected_ranges) = new_selected_ranges {
12462                this.change_selections(None, cx, |selections| {
12463                    selections.select_ranges(new_selected_ranges)
12464                });
12465                this.backspace(&Default::default(), cx);
12466            }
12467
12468            this.handle_input(text, cx);
12469        });
12470
12471        if let Some(transaction) = self.ime_transaction {
12472            self.buffer.update(cx, |buffer, cx| {
12473                buffer.group_until_transaction(transaction, cx);
12474            });
12475        }
12476
12477        self.unmark_text(cx);
12478    }
12479
12480    fn replace_and_mark_text_in_range(
12481        &mut self,
12482        range_utf16: Option<Range<usize>>,
12483        text: &str,
12484        new_selected_range_utf16: Option<Range<usize>>,
12485        cx: &mut ViewContext<Self>,
12486    ) {
12487        if !self.input_enabled {
12488            return;
12489        }
12490
12491        let transaction = self.transact(cx, |this, cx| {
12492            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12493                let snapshot = this.buffer.read(cx).read(cx);
12494                if let Some(relative_range_utf16) = range_utf16.as_ref() {
12495                    for marked_range in &mut marked_ranges {
12496                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12497                        marked_range.start.0 += relative_range_utf16.start;
12498                        marked_range.start =
12499                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12500                        marked_range.end =
12501                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12502                    }
12503                }
12504                Some(marked_ranges)
12505            } else if let Some(range_utf16) = range_utf16 {
12506                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12507                Some(this.selection_replacement_ranges(range_utf16, cx))
12508            } else {
12509                None
12510            };
12511
12512            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12513                let newest_selection_id = this.selections.newest_anchor().id;
12514                this.selections
12515                    .all::<OffsetUtf16>(cx)
12516                    .iter()
12517                    .zip(ranges_to_replace.iter())
12518                    .find_map(|(selection, range)| {
12519                        if selection.id == newest_selection_id {
12520                            Some(
12521                                (range.start.0 as isize - selection.head().0 as isize)
12522                                    ..(range.end.0 as isize - selection.head().0 as isize),
12523                            )
12524                        } else {
12525                            None
12526                        }
12527                    })
12528            });
12529
12530            cx.emit(EditorEvent::InputHandled {
12531                utf16_range_to_replace: range_to_replace,
12532                text: text.into(),
12533            });
12534
12535            if let Some(ranges) = ranges_to_replace {
12536                this.change_selections(None, cx, |s| s.select_ranges(ranges));
12537            }
12538
12539            let marked_ranges = {
12540                let snapshot = this.buffer.read(cx).read(cx);
12541                this.selections
12542                    .disjoint_anchors()
12543                    .iter()
12544                    .map(|selection| {
12545                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12546                    })
12547                    .collect::<Vec<_>>()
12548            };
12549
12550            if text.is_empty() {
12551                this.unmark_text(cx);
12552            } else {
12553                this.highlight_text::<InputComposition>(
12554                    marked_ranges.clone(),
12555                    HighlightStyle {
12556                        underline: Some(UnderlineStyle {
12557                            thickness: px(1.),
12558                            color: None,
12559                            wavy: false,
12560                        }),
12561                        ..Default::default()
12562                    },
12563                    cx,
12564                );
12565            }
12566
12567            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12568            let use_autoclose = this.use_autoclose;
12569            let use_auto_surround = this.use_auto_surround;
12570            this.set_use_autoclose(false);
12571            this.set_use_auto_surround(false);
12572            this.handle_input(text, cx);
12573            this.set_use_autoclose(use_autoclose);
12574            this.set_use_auto_surround(use_auto_surround);
12575
12576            if let Some(new_selected_range) = new_selected_range_utf16 {
12577                let snapshot = this.buffer.read(cx).read(cx);
12578                let new_selected_ranges = marked_ranges
12579                    .into_iter()
12580                    .map(|marked_range| {
12581                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12582                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12583                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12584                        snapshot.clip_offset_utf16(new_start, Bias::Left)
12585                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12586                    })
12587                    .collect::<Vec<_>>();
12588
12589                drop(snapshot);
12590                this.change_selections(None, cx, |selections| {
12591                    selections.select_ranges(new_selected_ranges)
12592                });
12593            }
12594        });
12595
12596        self.ime_transaction = self.ime_transaction.or(transaction);
12597        if let Some(transaction) = self.ime_transaction {
12598            self.buffer.update(cx, |buffer, cx| {
12599                buffer.group_until_transaction(transaction, cx);
12600            });
12601        }
12602
12603        if self.text_highlights::<InputComposition>(cx).is_none() {
12604            self.ime_transaction.take();
12605        }
12606    }
12607
12608    fn bounds_for_range(
12609        &mut self,
12610        range_utf16: Range<usize>,
12611        element_bounds: gpui::Bounds<Pixels>,
12612        cx: &mut ViewContext<Self>,
12613    ) -> Option<gpui::Bounds<Pixels>> {
12614        let text_layout_details = self.text_layout_details(cx);
12615        let style = &text_layout_details.editor_style;
12616        let font_id = cx.text_system().resolve_font(&style.text.font());
12617        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12618        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12619
12620        let em_width = cx
12621            .text_system()
12622            .typographic_bounds(font_id, font_size, 'm')
12623            .unwrap()
12624            .size
12625            .width;
12626
12627        let snapshot = self.snapshot(cx);
12628        let scroll_position = snapshot.scroll_position();
12629        let scroll_left = scroll_position.x * em_width;
12630
12631        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12632        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12633            + self.gutter_dimensions.width;
12634        let y = line_height * (start.row().as_f32() - scroll_position.y);
12635
12636        Some(Bounds {
12637            origin: element_bounds.origin + point(x, y),
12638            size: size(em_width, line_height),
12639        })
12640    }
12641}
12642
12643trait SelectionExt {
12644    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12645    fn spanned_rows(
12646        &self,
12647        include_end_if_at_line_start: bool,
12648        map: &DisplaySnapshot,
12649    ) -> Range<MultiBufferRow>;
12650}
12651
12652impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12653    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12654        let start = self
12655            .start
12656            .to_point(&map.buffer_snapshot)
12657            .to_display_point(map);
12658        let end = self
12659            .end
12660            .to_point(&map.buffer_snapshot)
12661            .to_display_point(map);
12662        if self.reversed {
12663            end..start
12664        } else {
12665            start..end
12666        }
12667    }
12668
12669    fn spanned_rows(
12670        &self,
12671        include_end_if_at_line_start: bool,
12672        map: &DisplaySnapshot,
12673    ) -> Range<MultiBufferRow> {
12674        let start = self.start.to_point(&map.buffer_snapshot);
12675        let mut end = self.end.to_point(&map.buffer_snapshot);
12676        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12677            end.row -= 1;
12678        }
12679
12680        let buffer_start = map.prev_line_boundary(start).0;
12681        let buffer_end = map.next_line_boundary(end).0;
12682        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12683    }
12684}
12685
12686impl<T: InvalidationRegion> InvalidationStack<T> {
12687    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12688    where
12689        S: Clone + ToOffset,
12690    {
12691        while let Some(region) = self.last() {
12692            let all_selections_inside_invalidation_ranges =
12693                if selections.len() == region.ranges().len() {
12694                    selections
12695                        .iter()
12696                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12697                        .all(|(selection, invalidation_range)| {
12698                            let head = selection.head().to_offset(buffer);
12699                            invalidation_range.start <= head && invalidation_range.end >= head
12700                        })
12701                } else {
12702                    false
12703                };
12704
12705            if all_selections_inside_invalidation_ranges {
12706                break;
12707            } else {
12708                self.pop();
12709            }
12710        }
12711    }
12712}
12713
12714impl<T> Default for InvalidationStack<T> {
12715    fn default() -> Self {
12716        Self(Default::default())
12717    }
12718}
12719
12720impl<T> Deref for InvalidationStack<T> {
12721    type Target = Vec<T>;
12722
12723    fn deref(&self) -> &Self::Target {
12724        &self.0
12725    }
12726}
12727
12728impl<T> DerefMut for InvalidationStack<T> {
12729    fn deref_mut(&mut self) -> &mut Self::Target {
12730        &mut self.0
12731    }
12732}
12733
12734impl InvalidationRegion for SnippetState {
12735    fn ranges(&self) -> &[Range<Anchor>] {
12736        &self.ranges[self.active_index]
12737    }
12738}
12739
12740pub fn diagnostic_block_renderer(
12741    diagnostic: Diagnostic,
12742    max_message_rows: Option<u8>,
12743    allow_closing: bool,
12744    _is_valid: bool,
12745) -> RenderBlock {
12746    let (text_without_backticks, code_ranges) =
12747        highlight_diagnostic_message(&diagnostic, max_message_rows);
12748
12749    Box::new(move |cx: &mut BlockContext| {
12750        let group_id: SharedString = cx.transform_block_id.to_string().into();
12751
12752        let mut text_style = cx.text_style().clone();
12753        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
12754        let theme_settings = ThemeSettings::get_global(cx);
12755        text_style.font_family = theme_settings.buffer_font.family.clone();
12756        text_style.font_style = theme_settings.buffer_font.style;
12757        text_style.font_features = theme_settings.buffer_font.features.clone();
12758        text_style.font_weight = theme_settings.buffer_font.weight;
12759
12760        let multi_line_diagnostic = diagnostic.message.contains('\n');
12761
12762        let buttons = |diagnostic: &Diagnostic, block_id: TransformBlockId| {
12763            if multi_line_diagnostic {
12764                v_flex()
12765            } else {
12766                h_flex()
12767            }
12768            .when(allow_closing, |div| {
12769                div.children(diagnostic.is_primary.then(|| {
12770                    IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
12771                        .icon_color(Color::Muted)
12772                        .size(ButtonSize::Compact)
12773                        .style(ButtonStyle::Transparent)
12774                        .visible_on_hover(group_id.clone())
12775                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
12776                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
12777                }))
12778            })
12779            .child(
12780                IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
12781                    .icon_color(Color::Muted)
12782                    .size(ButtonSize::Compact)
12783                    .style(ButtonStyle::Transparent)
12784                    .visible_on_hover(group_id.clone())
12785                    .on_click({
12786                        let message = diagnostic.message.clone();
12787                        move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
12788                    })
12789                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
12790            )
12791        };
12792
12793        let icon_size = buttons(&diagnostic, cx.transform_block_id)
12794            .into_any_element()
12795            .layout_as_root(AvailableSpace::min_size(), cx);
12796
12797        h_flex()
12798            .id(cx.transform_block_id)
12799            .group(group_id.clone())
12800            .relative()
12801            .size_full()
12802            .pl(cx.gutter_dimensions.width)
12803            .w(cx.max_width + cx.gutter_dimensions.width)
12804            .child(
12805                div()
12806                    .flex()
12807                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
12808                    .flex_shrink(),
12809            )
12810            .child(buttons(&diagnostic, cx.transform_block_id))
12811            .child(div().flex().flex_shrink_0().child(
12812                StyledText::new(text_without_backticks.clone()).with_highlights(
12813                    &text_style,
12814                    code_ranges.iter().map(|range| {
12815                        (
12816                            range.clone(),
12817                            HighlightStyle {
12818                                font_weight: Some(FontWeight::BOLD),
12819                                ..Default::default()
12820                            },
12821                        )
12822                    }),
12823                ),
12824            ))
12825            .into_any_element()
12826    })
12827}
12828
12829pub fn highlight_diagnostic_message(
12830    diagnostic: &Diagnostic,
12831    mut max_message_rows: Option<u8>,
12832) -> (SharedString, Vec<Range<usize>>) {
12833    let mut text_without_backticks = String::new();
12834    let mut code_ranges = Vec::new();
12835
12836    if let Some(source) = &diagnostic.source {
12837        text_without_backticks.push_str(&source);
12838        code_ranges.push(0..source.len());
12839        text_without_backticks.push_str(": ");
12840    }
12841
12842    let mut prev_offset = 0;
12843    let mut in_code_block = false;
12844    let has_row_limit = max_message_rows.is_some();
12845    let mut newline_indices = diagnostic
12846        .message
12847        .match_indices('\n')
12848        .filter(|_| has_row_limit)
12849        .map(|(ix, _)| ix)
12850        .fuse()
12851        .peekable();
12852
12853    for (quote_ix, _) in diagnostic
12854        .message
12855        .match_indices('`')
12856        .chain([(diagnostic.message.len(), "")])
12857    {
12858        let mut first_newline_ix = None;
12859        let mut last_newline_ix = None;
12860        while let Some(newline_ix) = newline_indices.peek() {
12861            if *newline_ix < quote_ix {
12862                if first_newline_ix.is_none() {
12863                    first_newline_ix = Some(*newline_ix);
12864                }
12865                last_newline_ix = Some(*newline_ix);
12866
12867                if let Some(rows_left) = &mut max_message_rows {
12868                    if *rows_left == 0 {
12869                        break;
12870                    } else {
12871                        *rows_left -= 1;
12872                    }
12873                }
12874                let _ = newline_indices.next();
12875            } else {
12876                break;
12877            }
12878        }
12879        let prev_len = text_without_backticks.len();
12880        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
12881        text_without_backticks.push_str(new_text);
12882        if in_code_block {
12883            code_ranges.push(prev_len..text_without_backticks.len());
12884        }
12885        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
12886        in_code_block = !in_code_block;
12887        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
12888            text_without_backticks.push_str("...");
12889            break;
12890        }
12891    }
12892
12893    (text_without_backticks.into(), code_ranges)
12894}
12895
12896fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
12897    match severity {
12898        DiagnosticSeverity::ERROR => colors.error,
12899        DiagnosticSeverity::WARNING => colors.warning,
12900        DiagnosticSeverity::INFORMATION => colors.info,
12901        DiagnosticSeverity::HINT => colors.info,
12902        _ => colors.ignored,
12903    }
12904}
12905
12906pub fn styled_runs_for_code_label<'a>(
12907    label: &'a CodeLabel,
12908    syntax_theme: &'a theme::SyntaxTheme,
12909) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
12910    let fade_out = HighlightStyle {
12911        fade_out: Some(0.35),
12912        ..Default::default()
12913    };
12914
12915    let mut prev_end = label.filter_range.end;
12916    label
12917        .runs
12918        .iter()
12919        .enumerate()
12920        .flat_map(move |(ix, (range, highlight_id))| {
12921            let style = if let Some(style) = highlight_id.style(syntax_theme) {
12922                style
12923            } else {
12924                return Default::default();
12925            };
12926            let mut muted_style = style;
12927            muted_style.highlight(fade_out);
12928
12929            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
12930            if range.start >= label.filter_range.end {
12931                if range.start > prev_end {
12932                    runs.push((prev_end..range.start, fade_out));
12933                }
12934                runs.push((range.clone(), muted_style));
12935            } else if range.end <= label.filter_range.end {
12936                runs.push((range.clone(), style));
12937            } else {
12938                runs.push((range.start..label.filter_range.end, style));
12939                runs.push((label.filter_range.end..range.end, muted_style));
12940            }
12941            prev_end = cmp::max(prev_end, range.end);
12942
12943            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
12944                runs.push((prev_end..label.text.len(), fade_out));
12945            }
12946
12947            runs
12948        })
12949}
12950
12951pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
12952    let mut prev_index = 0;
12953    let mut prev_codepoint: Option<char> = None;
12954    text.char_indices()
12955        .chain([(text.len(), '\0')])
12956        .filter_map(move |(index, codepoint)| {
12957            let prev_codepoint = prev_codepoint.replace(codepoint)?;
12958            let is_boundary = index == text.len()
12959                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
12960                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
12961            if is_boundary {
12962                let chunk = &text[prev_index..index];
12963                prev_index = index;
12964                Some(chunk)
12965            } else {
12966                None
12967            }
12968        })
12969}
12970
12971pub trait RangeToAnchorExt {
12972    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
12973}
12974
12975impl<T: ToOffset> RangeToAnchorExt for Range<T> {
12976    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
12977        let start_offset = self.start.to_offset(snapshot);
12978        let end_offset = self.end.to_offset(snapshot);
12979        if start_offset == end_offset {
12980            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
12981        } else {
12982            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
12983        }
12984    }
12985}
12986
12987pub trait RowExt {
12988    fn as_f32(&self) -> f32;
12989
12990    fn next_row(&self) -> Self;
12991
12992    fn previous_row(&self) -> Self;
12993
12994    fn minus(&self, other: Self) -> u32;
12995}
12996
12997impl RowExt for DisplayRow {
12998    fn as_f32(&self) -> f32 {
12999        self.0 as f32
13000    }
13001
13002    fn next_row(&self) -> Self {
13003        Self(self.0 + 1)
13004    }
13005
13006    fn previous_row(&self) -> Self {
13007        Self(self.0.saturating_sub(1))
13008    }
13009
13010    fn minus(&self, other: Self) -> u32 {
13011        self.0 - other.0
13012    }
13013}
13014
13015impl RowExt for MultiBufferRow {
13016    fn as_f32(&self) -> f32 {
13017        self.0 as f32
13018    }
13019
13020    fn next_row(&self) -> Self {
13021        Self(self.0 + 1)
13022    }
13023
13024    fn previous_row(&self) -> Self {
13025        Self(self.0.saturating_sub(1))
13026    }
13027
13028    fn minus(&self, other: Self) -> u32 {
13029        self.0 - other.0
13030    }
13031}
13032
13033trait RowRangeExt {
13034    type Row;
13035
13036    fn len(&self) -> usize;
13037
13038    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13039}
13040
13041impl RowRangeExt for Range<MultiBufferRow> {
13042    type Row = MultiBufferRow;
13043
13044    fn len(&self) -> usize {
13045        (self.end.0 - self.start.0) as usize
13046    }
13047
13048    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13049        (self.start.0..self.end.0).map(MultiBufferRow)
13050    }
13051}
13052
13053impl RowRangeExt for Range<DisplayRow> {
13054    type Row = DisplayRow;
13055
13056    fn len(&self) -> usize {
13057        (self.end.0 - self.start.0) as usize
13058    }
13059
13060    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13061        (self.start.0..self.end.0).map(DisplayRow)
13062    }
13063}
13064
13065fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13066    if hunk.diff_base_byte_range.is_empty() {
13067        DiffHunkStatus::Added
13068    } else if hunk.associated_range.is_empty() {
13069        DiffHunkStatus::Removed
13070    } else {
13071        DiffHunkStatus::Modified
13072    }
13073}