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, EventEmitter, FocusHandle, FocusOutEvent, FocusableView,
   72    FontId, FontStyle, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext,
   73    ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString,
   74    Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle, UnderlineStyle,
   75    UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
   76    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,
  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::register_followable_item::<Editor>(cx);
  275    workspace::register_deserializable_item::<Editor>(cx);
  276    cx.observe_new_views(
  277        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  278            workspace.register_action(Editor::new_file);
  279            workspace.register_action(Editor::new_file_in_direction);
  280        },
  281    )
  282    .detach();
  283
  284    cx.on_action(move |_: &workspace::NewFile, cx| {
  285        let app_state = workspace::AppState::global(cx);
  286        if let Some(app_state) = app_state.upgrade() {
  287            workspace::open_new(app_state, cx, |workspace, cx| {
  288                Editor::new_file(workspace, &Default::default(), cx)
  289            })
  290            .detach();
  291        }
  292    });
  293    cx.on_action(move |_: &workspace::NewWindow, cx| {
  294        let app_state = workspace::AppState::global(cx);
  295        if let Some(app_state) = app_state.upgrade() {
  296            workspace::open_new(app_state, cx, |workspace, cx| {
  297                Editor::new_file(workspace, &Default::default(), cx)
  298            })
  299            .detach();
  300        }
  301    });
  302}
  303
  304pub struct SearchWithinRange;
  305
  306trait InvalidationRegion {
  307    fn ranges(&self) -> &[Range<Anchor>];
  308}
  309
  310#[derive(Clone, Debug, PartialEq)]
  311pub enum SelectPhase {
  312    Begin {
  313        position: DisplayPoint,
  314        add: bool,
  315        click_count: usize,
  316    },
  317    BeginColumnar {
  318        position: DisplayPoint,
  319        reset: bool,
  320        goal_column: u32,
  321    },
  322    Extend {
  323        position: DisplayPoint,
  324        click_count: usize,
  325    },
  326    Update {
  327        position: DisplayPoint,
  328        goal_column: u32,
  329        scroll_delta: gpui::Point<f32>,
  330    },
  331    End,
  332}
  333
  334#[derive(Clone, Debug)]
  335pub enum SelectMode {
  336    Character,
  337    Word(Range<Anchor>),
  338    Line(Range<Anchor>),
  339    All,
  340}
  341
  342#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  343pub enum EditorMode {
  344    SingleLine { auto_width: bool },
  345    AutoHeight { max_lines: usize },
  346    Full,
  347}
  348
  349#[derive(Clone, Debug)]
  350pub enum SoftWrap {
  351    None,
  352    PreferLine,
  353    EditorWidth,
  354    Column(u32),
  355}
  356
  357#[derive(Clone)]
  358pub struct EditorStyle {
  359    pub background: Hsla,
  360    pub local_player: PlayerColor,
  361    pub text: TextStyle,
  362    pub scrollbar_width: Pixels,
  363    pub syntax: Arc<SyntaxTheme>,
  364    pub status: StatusColors,
  365    pub inlay_hints_style: HighlightStyle,
  366    pub suggestions_style: HighlightStyle,
  367}
  368
  369impl Default for EditorStyle {
  370    fn default() -> Self {
  371        Self {
  372            background: Hsla::default(),
  373            local_player: PlayerColor::default(),
  374            text: TextStyle::default(),
  375            scrollbar_width: Pixels::default(),
  376            syntax: Default::default(),
  377            // HACK: Status colors don't have a real default.
  378            // We should look into removing the status colors from the editor
  379            // style and retrieve them directly from the theme.
  380            status: StatusColors::dark(),
  381            inlay_hints_style: HighlightStyle::default(),
  382            suggestions_style: HighlightStyle::default(),
  383        }
  384    }
  385}
  386
  387type CompletionId = usize;
  388
  389#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  390struct EditorActionId(usize);
  391
  392impl EditorActionId {
  393    pub fn post_inc(&mut self) -> Self {
  394        let answer = self.0;
  395
  396        *self = Self(answer + 1);
  397
  398        Self(answer)
  399    }
  400}
  401
  402// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  403// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  404
  405type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  406type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  407
  408struct ScrollbarMarkerState {
  409    scrollbar_size: Size<Pixels>,
  410    dirty: bool,
  411    markers: Arc<[PaintQuad]>,
  412    pending_refresh: Option<Task<Result<()>>>,
  413}
  414
  415impl ScrollbarMarkerState {
  416    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  417        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  418    }
  419}
  420
  421impl Default for ScrollbarMarkerState {
  422    fn default() -> Self {
  423        Self {
  424            scrollbar_size: Size::default(),
  425            dirty: false,
  426            markers: Arc::from([]),
  427            pending_refresh: None,
  428        }
  429    }
  430}
  431
  432#[derive(Clone, Debug)]
  433struct RunnableTasks {
  434    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  435    offset: MultiBufferOffset,
  436    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  437    column: u32,
  438    // Values of all named captures, including those starting with '_'
  439    extra_variables: HashMap<String, String>,
  440    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  441    context_range: Range<BufferOffset>,
  442}
  443
  444#[derive(Clone)]
  445struct ResolvedTasks {
  446    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  447    position: Anchor,
  448}
  449#[derive(Copy, Clone, Debug)]
  450struct MultiBufferOffset(usize);
  451#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  452struct BufferOffset(usize);
  453/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  454///
  455/// See the [module level documentation](self) for more information.
  456pub struct Editor {
  457    focus_handle: FocusHandle,
  458    last_focused_descendant: Option<WeakFocusHandle>,
  459    /// The text buffer being edited
  460    buffer: Model<MultiBuffer>,
  461    /// Map of how text in the buffer should be displayed.
  462    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  463    pub display_map: Model<DisplayMap>,
  464    pub selections: SelectionsCollection,
  465    pub scroll_manager: ScrollManager,
  466    /// When inline assist editors are linked, they all render cursors because
  467    /// typing enters text into each of them, even the ones that aren't focused.
  468    pub(crate) show_cursor_when_unfocused: bool,
  469    columnar_selection_tail: Option<Anchor>,
  470    add_selections_state: Option<AddSelectionsState>,
  471    select_next_state: Option<SelectNextState>,
  472    select_prev_state: Option<SelectNextState>,
  473    selection_history: SelectionHistory,
  474    autoclose_regions: Vec<AutocloseRegion>,
  475    snippet_stack: InvalidationStack<SnippetState>,
  476    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  477    ime_transaction: Option<TransactionId>,
  478    active_diagnostics: Option<ActiveDiagnosticGroup>,
  479    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  480    project: Option<Model<Project>>,
  481    completion_provider: Option<Box<dyn CompletionProvider>>,
  482    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  483    blink_manager: Model<BlinkManager>,
  484    show_cursor_names: bool,
  485    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  486    pub show_local_selections: bool,
  487    mode: EditorMode,
  488    show_breadcrumbs: bool,
  489    show_gutter: bool,
  490    show_line_numbers: Option<bool>,
  491    show_git_diff_gutter: Option<bool>,
  492    show_code_actions: Option<bool>,
  493    show_runnables: Option<bool>,
  494    show_wrap_guides: Option<bool>,
  495    show_indent_guides: Option<bool>,
  496    placeholder_text: Option<Arc<str>>,
  497    highlight_order: usize,
  498    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  499    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  500    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  501    scrollbar_marker_state: ScrollbarMarkerState,
  502    active_indent_guides_state: ActiveIndentGuidesState,
  503    nav_history: Option<ItemNavHistory>,
  504    context_menu: RwLock<Option<ContextMenu>>,
  505    mouse_context_menu: Option<MouseContextMenu>,
  506    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  507    signature_help_state: SignatureHelpState,
  508    auto_signature_help: Option<bool>,
  509    find_all_references_task_sources: Vec<Anchor>,
  510    next_completion_id: CompletionId,
  511    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  512    available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
  513    code_actions_task: Option<Task<()>>,
  514    document_highlights_task: Option<Task<()>>,
  515    linked_editing_range_task: Option<Task<Option<()>>>,
  516    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  517    pending_rename: Option<RenameState>,
  518    searchable: bool,
  519    cursor_shape: CursorShape,
  520    current_line_highlight: Option<CurrentLineHighlight>,
  521    collapse_matches: bool,
  522    autoindent_mode: Option<AutoindentMode>,
  523    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  524    keymap_context_layers: BTreeMap<TypeId, KeyContext>,
  525    input_enabled: bool,
  526    use_modal_editing: bool,
  527    read_only: bool,
  528    leader_peer_id: Option<PeerId>,
  529    remote_id: Option<ViewId>,
  530    hover_state: HoverState,
  531    gutter_hovered: bool,
  532    hovered_link_state: Option<HoveredLinkState>,
  533    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  534    active_inline_completion: Option<Inlay>,
  535    show_inline_completions: bool,
  536    inlay_hint_cache: InlayHintCache,
  537    expanded_hunks: ExpandedHunks,
  538    next_inlay_id: usize,
  539    _subscriptions: Vec<Subscription>,
  540    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  541    gutter_dimensions: GutterDimensions,
  542    pub vim_replace_map: HashMap<Range<usize>, String>,
  543    style: Option<EditorStyle>,
  544    next_editor_action_id: EditorActionId,
  545    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  546    use_autoclose: bool,
  547    use_auto_surround: bool,
  548    auto_replace_emoji_shortcode: bool,
  549    show_git_blame_gutter: bool,
  550    show_git_blame_inline: bool,
  551    show_git_blame_inline_delay_task: Option<Task<()>>,
  552    git_blame_inline_enabled: bool,
  553    show_selection_menu: Option<bool>,
  554    blame: Option<Model<GitBlame>>,
  555    blame_subscription: Option<Subscription>,
  556    custom_context_menu: Option<
  557        Box<
  558            dyn 'static
  559                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  560        >,
  561    >,
  562    last_bounds: Option<Bounds<Pixels>>,
  563    expect_bounds_change: Option<Bounds<Pixels>>,
  564    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  565    tasks_update_task: Option<Task<()>>,
  566    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  567    file_header_size: u8,
  568    breadcrumb_header: Option<String>,
  569}
  570
  571#[derive(Clone)]
  572pub struct EditorSnapshot {
  573    pub mode: EditorMode,
  574    show_gutter: bool,
  575    show_line_numbers: Option<bool>,
  576    show_git_diff_gutter: Option<bool>,
  577    show_code_actions: Option<bool>,
  578    show_runnables: Option<bool>,
  579    render_git_blame_gutter: bool,
  580    pub display_snapshot: DisplaySnapshot,
  581    pub placeholder_text: Option<Arc<str>>,
  582    is_focused: bool,
  583    scroll_anchor: ScrollAnchor,
  584    ongoing_scroll: OngoingScroll,
  585    current_line_highlight: CurrentLineHighlight,
  586    gutter_hovered: bool,
  587}
  588
  589const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
  590
  591#[derive(Debug, Clone, Copy)]
  592pub struct GutterDimensions {
  593    pub left_padding: Pixels,
  594    pub right_padding: Pixels,
  595    pub width: Pixels,
  596    pub margin: Pixels,
  597    pub git_blame_entries_width: Option<Pixels>,
  598}
  599
  600impl GutterDimensions {
  601    /// The full width of the space taken up by the gutter.
  602    pub fn full_width(&self) -> Pixels {
  603        self.margin + self.width
  604    }
  605
  606    /// The width of the space reserved for the fold indicators,
  607    /// use alongside 'justify_end' and `gutter_width` to
  608    /// right align content with the line numbers
  609    pub fn fold_area_width(&self) -> Pixels {
  610        self.margin + self.right_padding
  611    }
  612}
  613
  614impl Default for GutterDimensions {
  615    fn default() -> Self {
  616        Self {
  617            left_padding: Pixels::ZERO,
  618            right_padding: Pixels::ZERO,
  619            width: Pixels::ZERO,
  620            margin: Pixels::ZERO,
  621            git_blame_entries_width: None,
  622        }
  623    }
  624}
  625
  626#[derive(Debug)]
  627pub struct RemoteSelection {
  628    pub replica_id: ReplicaId,
  629    pub selection: Selection<Anchor>,
  630    pub cursor_shape: CursorShape,
  631    pub peer_id: PeerId,
  632    pub line_mode: bool,
  633    pub participant_index: Option<ParticipantIndex>,
  634    pub user_name: Option<SharedString>,
  635}
  636
  637#[derive(Clone, Debug)]
  638struct SelectionHistoryEntry {
  639    selections: Arc<[Selection<Anchor>]>,
  640    select_next_state: Option<SelectNextState>,
  641    select_prev_state: Option<SelectNextState>,
  642    add_selections_state: Option<AddSelectionsState>,
  643}
  644
  645enum SelectionHistoryMode {
  646    Normal,
  647    Undoing,
  648    Redoing,
  649}
  650
  651#[derive(Clone, PartialEq, Eq, Hash)]
  652struct HoveredCursor {
  653    replica_id: u16,
  654    selection_id: usize,
  655}
  656
  657impl Default for SelectionHistoryMode {
  658    fn default() -> Self {
  659        Self::Normal
  660    }
  661}
  662
  663#[derive(Default)]
  664struct SelectionHistory {
  665    #[allow(clippy::type_complexity)]
  666    selections_by_transaction:
  667        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  668    mode: SelectionHistoryMode,
  669    undo_stack: VecDeque<SelectionHistoryEntry>,
  670    redo_stack: VecDeque<SelectionHistoryEntry>,
  671}
  672
  673impl SelectionHistory {
  674    fn insert_transaction(
  675        &mut self,
  676        transaction_id: TransactionId,
  677        selections: Arc<[Selection<Anchor>]>,
  678    ) {
  679        self.selections_by_transaction
  680            .insert(transaction_id, (selections, None));
  681    }
  682
  683    #[allow(clippy::type_complexity)]
  684    fn transaction(
  685        &self,
  686        transaction_id: TransactionId,
  687    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  688        self.selections_by_transaction.get(&transaction_id)
  689    }
  690
  691    #[allow(clippy::type_complexity)]
  692    fn transaction_mut(
  693        &mut self,
  694        transaction_id: TransactionId,
  695    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  696        self.selections_by_transaction.get_mut(&transaction_id)
  697    }
  698
  699    fn push(&mut self, entry: SelectionHistoryEntry) {
  700        if !entry.selections.is_empty() {
  701            match self.mode {
  702                SelectionHistoryMode::Normal => {
  703                    self.push_undo(entry);
  704                    self.redo_stack.clear();
  705                }
  706                SelectionHistoryMode::Undoing => self.push_redo(entry),
  707                SelectionHistoryMode::Redoing => self.push_undo(entry),
  708            }
  709        }
  710    }
  711
  712    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  713        if self
  714            .undo_stack
  715            .back()
  716            .map_or(true, |e| e.selections != entry.selections)
  717        {
  718            self.undo_stack.push_back(entry);
  719            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  720                self.undo_stack.pop_front();
  721            }
  722        }
  723    }
  724
  725    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  726        if self
  727            .redo_stack
  728            .back()
  729            .map_or(true, |e| e.selections != entry.selections)
  730        {
  731            self.redo_stack.push_back(entry);
  732            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  733                self.redo_stack.pop_front();
  734            }
  735        }
  736    }
  737}
  738
  739struct RowHighlight {
  740    index: usize,
  741    range: RangeInclusive<Anchor>,
  742    color: Option<Hsla>,
  743    should_autoscroll: bool,
  744}
  745
  746#[derive(Clone, Debug)]
  747struct AddSelectionsState {
  748    above: bool,
  749    stack: Vec<usize>,
  750}
  751
  752#[derive(Clone)]
  753struct SelectNextState {
  754    query: AhoCorasick,
  755    wordwise: bool,
  756    done: bool,
  757}
  758
  759impl std::fmt::Debug for SelectNextState {
  760    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  761        f.debug_struct(std::any::type_name::<Self>())
  762            .field("wordwise", &self.wordwise)
  763            .field("done", &self.done)
  764            .finish()
  765    }
  766}
  767
  768#[derive(Debug)]
  769struct AutocloseRegion {
  770    selection_id: usize,
  771    range: Range<Anchor>,
  772    pair: BracketPair,
  773}
  774
  775#[derive(Debug)]
  776struct SnippetState {
  777    ranges: Vec<Vec<Range<Anchor>>>,
  778    active_index: usize,
  779}
  780
  781#[doc(hidden)]
  782pub struct RenameState {
  783    pub range: Range<Anchor>,
  784    pub old_name: Arc<str>,
  785    pub editor: View<Editor>,
  786    block_id: BlockId,
  787}
  788
  789struct InvalidationStack<T>(Vec<T>);
  790
  791struct RegisteredInlineCompletionProvider {
  792    provider: Arc<dyn InlineCompletionProviderHandle>,
  793    _subscription: Subscription,
  794}
  795
  796enum ContextMenu {
  797    Completions(CompletionsMenu),
  798    CodeActions(CodeActionsMenu),
  799}
  800
  801impl ContextMenu {
  802    fn select_first(
  803        &mut self,
  804        project: Option<&Model<Project>>,
  805        cx: &mut ViewContext<Editor>,
  806    ) -> bool {
  807        if self.visible() {
  808            match self {
  809                ContextMenu::Completions(menu) => menu.select_first(project, cx),
  810                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  811            }
  812            true
  813        } else {
  814            false
  815        }
  816    }
  817
  818    fn select_prev(
  819        &mut self,
  820        project: Option<&Model<Project>>,
  821        cx: &mut ViewContext<Editor>,
  822    ) -> bool {
  823        if self.visible() {
  824            match self {
  825                ContextMenu::Completions(menu) => menu.select_prev(project, cx),
  826                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  827            }
  828            true
  829        } else {
  830            false
  831        }
  832    }
  833
  834    fn select_next(
  835        &mut self,
  836        project: Option<&Model<Project>>,
  837        cx: &mut ViewContext<Editor>,
  838    ) -> bool {
  839        if self.visible() {
  840            match self {
  841                ContextMenu::Completions(menu) => menu.select_next(project, cx),
  842                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  843            }
  844            true
  845        } else {
  846            false
  847        }
  848    }
  849
  850    fn select_last(
  851        &mut self,
  852        project: Option<&Model<Project>>,
  853        cx: &mut ViewContext<Editor>,
  854    ) -> bool {
  855        if self.visible() {
  856            match self {
  857                ContextMenu::Completions(menu) => menu.select_last(project, cx),
  858                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  859            }
  860            true
  861        } else {
  862            false
  863        }
  864    }
  865
  866    fn visible(&self) -> bool {
  867        match self {
  868            ContextMenu::Completions(menu) => menu.visible(),
  869            ContextMenu::CodeActions(menu) => menu.visible(),
  870        }
  871    }
  872
  873    fn render(
  874        &self,
  875        cursor_position: DisplayPoint,
  876        style: &EditorStyle,
  877        max_height: Pixels,
  878        workspace: Option<WeakView<Workspace>>,
  879        cx: &mut ViewContext<Editor>,
  880    ) -> (ContextMenuOrigin, AnyElement) {
  881        match self {
  882            ContextMenu::Completions(menu) => (
  883                ContextMenuOrigin::EditorPoint(cursor_position),
  884                menu.render(style, max_height, workspace, cx),
  885            ),
  886            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  887        }
  888    }
  889}
  890
  891enum ContextMenuOrigin {
  892    EditorPoint(DisplayPoint),
  893    GutterIndicator(DisplayRow),
  894}
  895
  896#[derive(Clone)]
  897struct CompletionsMenu {
  898    id: CompletionId,
  899    initial_position: Anchor,
  900    buffer: Model<Buffer>,
  901    completions: Arc<RwLock<Box<[Completion]>>>,
  902    match_candidates: Arc<[StringMatchCandidate]>,
  903    matches: Arc<[StringMatch]>,
  904    selected_item: usize,
  905    scroll_handle: UniformListScrollHandle,
  906    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  907}
  908
  909impl CompletionsMenu {
  910    fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  911        self.selected_item = 0;
  912        self.scroll_handle.scroll_to_item(self.selected_item);
  913        self.attempt_resolve_selected_completion_documentation(project, cx);
  914        cx.notify();
  915    }
  916
  917    fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  918        if self.selected_item > 0 {
  919            self.selected_item -= 1;
  920        } else {
  921            self.selected_item = self.matches.len() - 1;
  922        }
  923        self.scroll_handle.scroll_to_item(self.selected_item);
  924        self.attempt_resolve_selected_completion_documentation(project, cx);
  925        cx.notify();
  926    }
  927
  928    fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  929        if self.selected_item + 1 < self.matches.len() {
  930            self.selected_item += 1;
  931        } else {
  932            self.selected_item = 0;
  933        }
  934        self.scroll_handle.scroll_to_item(self.selected_item);
  935        self.attempt_resolve_selected_completion_documentation(project, cx);
  936        cx.notify();
  937    }
  938
  939    fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  940        self.selected_item = self.matches.len() - 1;
  941        self.scroll_handle.scroll_to_item(self.selected_item);
  942        self.attempt_resolve_selected_completion_documentation(project, cx);
  943        cx.notify();
  944    }
  945
  946    fn pre_resolve_completion_documentation(
  947        buffer: Model<Buffer>,
  948        completions: Arc<RwLock<Box<[Completion]>>>,
  949        matches: Arc<[StringMatch]>,
  950        editor: &Editor,
  951        cx: &mut ViewContext<Editor>,
  952    ) -> Task<()> {
  953        let settings = EditorSettings::get_global(cx);
  954        if !settings.show_completion_documentation {
  955            return Task::ready(());
  956        }
  957
  958        let Some(provider) = editor.completion_provider.as_ref() else {
  959            return Task::ready(());
  960        };
  961
  962        let resolve_task = provider.resolve_completions(
  963            buffer,
  964            matches.iter().map(|m| m.candidate_id).collect(),
  965            completions.clone(),
  966            cx,
  967        );
  968
  969        return cx.spawn(move |this, mut cx| async move {
  970            if let Some(true) = resolve_task.await.log_err() {
  971                this.update(&mut cx, |_, cx| cx.notify()).ok();
  972            }
  973        });
  974    }
  975
  976    fn attempt_resolve_selected_completion_documentation(
  977        &mut self,
  978        project: Option<&Model<Project>>,
  979        cx: &mut ViewContext<Editor>,
  980    ) {
  981        let settings = EditorSettings::get_global(cx);
  982        if !settings.show_completion_documentation {
  983            return;
  984        }
  985
  986        let completion_index = self.matches[self.selected_item].candidate_id;
  987        let Some(project) = project else {
  988            return;
  989        };
  990
  991        let resolve_task = project.update(cx, |project, cx| {
  992            project.resolve_completions(
  993                self.buffer.clone(),
  994                vec![completion_index],
  995                self.completions.clone(),
  996                cx,
  997            )
  998        });
  999
 1000        let delay_ms =
 1001            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1002        let delay = Duration::from_millis(delay_ms);
 1003
 1004        self.selected_completion_documentation_resolve_debounce
 1005            .lock()
 1006            .fire_new(delay, cx, |_, cx| {
 1007                cx.spawn(move |this, mut cx| async move {
 1008                    if let Some(true) = resolve_task.await.log_err() {
 1009                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1010                    }
 1011                })
 1012            });
 1013    }
 1014
 1015    fn visible(&self) -> bool {
 1016        !self.matches.is_empty()
 1017    }
 1018
 1019    fn render(
 1020        &self,
 1021        style: &EditorStyle,
 1022        max_height: Pixels,
 1023        workspace: Option<WeakView<Workspace>>,
 1024        cx: &mut ViewContext<Editor>,
 1025    ) -> AnyElement {
 1026        let settings = EditorSettings::get_global(cx);
 1027        let show_completion_documentation = settings.show_completion_documentation;
 1028
 1029        let widest_completion_ix = self
 1030            .matches
 1031            .iter()
 1032            .enumerate()
 1033            .max_by_key(|(_, mat)| {
 1034                let completions = self.completions.read();
 1035                let completion = &completions[mat.candidate_id];
 1036                let documentation = &completion.documentation;
 1037
 1038                let mut len = completion.label.text.chars().count();
 1039                if let Some(Documentation::SingleLine(text)) = documentation {
 1040                    if show_completion_documentation {
 1041                        len += text.chars().count();
 1042                    }
 1043                }
 1044
 1045                len
 1046            })
 1047            .map(|(ix, _)| ix);
 1048
 1049        let completions = self.completions.clone();
 1050        let matches = self.matches.clone();
 1051        let selected_item = self.selected_item;
 1052        let style = style.clone();
 1053
 1054        let multiline_docs = if show_completion_documentation {
 1055            let mat = &self.matches[selected_item];
 1056            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1057                Some(Documentation::MultiLinePlainText(text)) => {
 1058                    Some(div().child(SharedString::from(text.clone())))
 1059                }
 1060                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1061                    Some(div().child(render_parsed_markdown(
 1062                        "completions_markdown",
 1063                        parsed,
 1064                        &style,
 1065                        workspace,
 1066                        cx,
 1067                    )))
 1068                }
 1069                _ => None,
 1070            };
 1071            multiline_docs.map(|div| {
 1072                div.id("multiline_docs")
 1073                    .max_h(max_height)
 1074                    .flex_1()
 1075                    .px_1p5()
 1076                    .py_1()
 1077                    .min_w(px(260.))
 1078                    .max_w(px(640.))
 1079                    .w(px(500.))
 1080                    .overflow_y_scroll()
 1081                    .occlude()
 1082            })
 1083        } else {
 1084            None
 1085        };
 1086
 1087        let list = uniform_list(
 1088            cx.view().clone(),
 1089            "completions",
 1090            matches.len(),
 1091            move |_editor, range, cx| {
 1092                let start_ix = range.start;
 1093                let completions_guard = completions.read();
 1094
 1095                matches[range]
 1096                    .iter()
 1097                    .enumerate()
 1098                    .map(|(ix, mat)| {
 1099                        let item_ix = start_ix + ix;
 1100                        let candidate_id = mat.candidate_id;
 1101                        let completion = &completions_guard[candidate_id];
 1102
 1103                        let documentation = if show_completion_documentation {
 1104                            &completion.documentation
 1105                        } else {
 1106                            &None
 1107                        };
 1108
 1109                        let highlights = gpui::combine_highlights(
 1110                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1111                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1112                                |(range, mut highlight)| {
 1113                                    // Ignore font weight for syntax highlighting, as we'll use it
 1114                                    // for fuzzy matches.
 1115                                    highlight.font_weight = None;
 1116
 1117                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1118                                        highlight.strikethrough = Some(StrikethroughStyle {
 1119                                            thickness: 1.0.into(),
 1120                                            ..Default::default()
 1121                                        });
 1122                                        highlight.color = Some(cx.theme().colors().text_muted);
 1123                                    }
 1124
 1125                                    (range, highlight)
 1126                                },
 1127                            ),
 1128                        );
 1129                        let completion_label = StyledText::new(completion.label.text.clone())
 1130                            .with_highlights(&style.text, highlights);
 1131                        let documentation_label =
 1132                            if let Some(Documentation::SingleLine(text)) = documentation {
 1133                                if text.trim().is_empty() {
 1134                                    None
 1135                                } else {
 1136                                    Some(
 1137                                        Label::new(text.clone())
 1138                                            .ml_4()
 1139                                            .size(LabelSize::Small)
 1140                                            .color(Color::Muted),
 1141                                    )
 1142                                }
 1143                            } else {
 1144                                None
 1145                            };
 1146
 1147                        div().min_w(px(220.)).max_w(px(540.)).child(
 1148                            ListItem::new(mat.candidate_id)
 1149                                .inset(true)
 1150                                .selected(item_ix == selected_item)
 1151                                .on_click(cx.listener(move |editor, _event, cx| {
 1152                                    cx.stop_propagation();
 1153                                    if let Some(task) = editor.confirm_completion(
 1154                                        &ConfirmCompletion {
 1155                                            item_ix: Some(item_ix),
 1156                                        },
 1157                                        cx,
 1158                                    ) {
 1159                                        task.detach_and_log_err(cx)
 1160                                    }
 1161                                }))
 1162                                .child(h_flex().overflow_hidden().child(completion_label))
 1163                                .end_slot::<Label>(documentation_label),
 1164                        )
 1165                    })
 1166                    .collect()
 1167            },
 1168        )
 1169        .occlude()
 1170        .max_h(max_height)
 1171        .track_scroll(self.scroll_handle.clone())
 1172        .with_width_from_item(widest_completion_ix)
 1173        .with_sizing_behavior(ListSizingBehavior::Infer);
 1174
 1175        Popover::new()
 1176            .child(list)
 1177            .when_some(multiline_docs, |popover, multiline_docs| {
 1178                popover.aside(multiline_docs)
 1179            })
 1180            .into_any_element()
 1181    }
 1182
 1183    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1184        let mut matches = if let Some(query) = query {
 1185            fuzzy::match_strings(
 1186                &self.match_candidates,
 1187                query,
 1188                query.chars().any(|c| c.is_uppercase()),
 1189                100,
 1190                &Default::default(),
 1191                executor,
 1192            )
 1193            .await
 1194        } else {
 1195            self.match_candidates
 1196                .iter()
 1197                .enumerate()
 1198                .map(|(candidate_id, candidate)| StringMatch {
 1199                    candidate_id,
 1200                    score: Default::default(),
 1201                    positions: Default::default(),
 1202                    string: candidate.string.clone(),
 1203                })
 1204                .collect()
 1205        };
 1206
 1207        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1208        if let Some(query) = query {
 1209            if let Some(query_start) = query.chars().next() {
 1210                matches.retain(|string_match| {
 1211                    split_words(&string_match.string).any(|word| {
 1212                        // Check that the first codepoint of the word as lowercase matches the first
 1213                        // codepoint of the query as lowercase
 1214                        word.chars()
 1215                            .flat_map(|codepoint| codepoint.to_lowercase())
 1216                            .zip(query_start.to_lowercase())
 1217                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1218                    })
 1219                });
 1220            }
 1221        }
 1222
 1223        let completions = self.completions.read();
 1224        matches.sort_unstable_by_key(|mat| {
 1225            // We do want to strike a balance here between what the language server tells us
 1226            // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1227            // `Creat` and there is a local variable called `CreateComponent`).
 1228            // So what we do is: we bucket all matches into two buckets
 1229            // - Strong matches
 1230            // - Weak matches
 1231            // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1232            // and the Weak matches are the rest.
 1233            //
 1234            // For the strong matches, we sort by the language-servers score first and for the weak
 1235            // matches, we prefer our fuzzy finder first.
 1236            //
 1237            // The thinking behind that: it's useless to take the sort_text the language-server gives
 1238            // us into account when it's obviously a bad match.
 1239
 1240            #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1241            enum MatchScore<'a> {
 1242                Strong {
 1243                    sort_text: Option<&'a str>,
 1244                    score: Reverse<OrderedFloat<f64>>,
 1245                    sort_key: (usize, &'a str),
 1246                },
 1247                Weak {
 1248                    score: Reverse<OrderedFloat<f64>>,
 1249                    sort_text: Option<&'a str>,
 1250                    sort_key: (usize, &'a str),
 1251                },
 1252            }
 1253
 1254            let completion = &completions[mat.candidate_id];
 1255            let sort_key = completion.sort_key();
 1256            let sort_text = completion.lsp_completion.sort_text.as_deref();
 1257            let score = Reverse(OrderedFloat(mat.score));
 1258
 1259            if mat.score >= 0.2 {
 1260                MatchScore::Strong {
 1261                    sort_text,
 1262                    score,
 1263                    sort_key,
 1264                }
 1265            } else {
 1266                MatchScore::Weak {
 1267                    score,
 1268                    sort_text,
 1269                    sort_key,
 1270                }
 1271            }
 1272        });
 1273
 1274        for mat in &mut matches {
 1275            let completion = &completions[mat.candidate_id];
 1276            mat.string.clone_from(&completion.label.text);
 1277            for position in &mut mat.positions {
 1278                *position += completion.label.filter_range.start;
 1279            }
 1280        }
 1281        drop(completions);
 1282
 1283        self.matches = matches.into();
 1284        self.selected_item = 0;
 1285    }
 1286}
 1287
 1288#[derive(Clone)]
 1289struct CodeActionContents {
 1290    tasks: Option<Arc<ResolvedTasks>>,
 1291    actions: Option<Arc<[CodeAction]>>,
 1292}
 1293
 1294impl CodeActionContents {
 1295    fn len(&self) -> usize {
 1296        match (&self.tasks, &self.actions) {
 1297            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1298            (Some(tasks), None) => tasks.templates.len(),
 1299            (None, Some(actions)) => actions.len(),
 1300            (None, None) => 0,
 1301        }
 1302    }
 1303
 1304    fn is_empty(&self) -> bool {
 1305        match (&self.tasks, &self.actions) {
 1306            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1307            (Some(tasks), None) => tasks.templates.is_empty(),
 1308            (None, Some(actions)) => actions.is_empty(),
 1309            (None, None) => true,
 1310        }
 1311    }
 1312
 1313    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1314        self.tasks
 1315            .iter()
 1316            .flat_map(|tasks| {
 1317                tasks
 1318                    .templates
 1319                    .iter()
 1320                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1321            })
 1322            .chain(self.actions.iter().flat_map(|actions| {
 1323                actions
 1324                    .iter()
 1325                    .map(|action| CodeActionsItem::CodeAction(action.clone()))
 1326            }))
 1327    }
 1328    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1329        match (&self.tasks, &self.actions) {
 1330            (Some(tasks), Some(actions)) => {
 1331                if index < tasks.templates.len() {
 1332                    tasks
 1333                        .templates
 1334                        .get(index)
 1335                        .cloned()
 1336                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1337                } else {
 1338                    actions
 1339                        .get(index - tasks.templates.len())
 1340                        .cloned()
 1341                        .map(CodeActionsItem::CodeAction)
 1342                }
 1343            }
 1344            (Some(tasks), None) => tasks
 1345                .templates
 1346                .get(index)
 1347                .cloned()
 1348                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1349            (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
 1350            (None, None) => None,
 1351        }
 1352    }
 1353}
 1354
 1355#[allow(clippy::large_enum_variant)]
 1356#[derive(Clone)]
 1357enum CodeActionsItem {
 1358    Task(TaskSourceKind, ResolvedTask),
 1359    CodeAction(CodeAction),
 1360}
 1361
 1362impl CodeActionsItem {
 1363    fn as_task(&self) -> Option<&ResolvedTask> {
 1364        let Self::Task(_, task) = self else {
 1365            return None;
 1366        };
 1367        Some(task)
 1368    }
 1369    fn as_code_action(&self) -> Option<&CodeAction> {
 1370        let Self::CodeAction(action) = self else {
 1371            return None;
 1372        };
 1373        Some(action)
 1374    }
 1375    fn label(&self) -> String {
 1376        match self {
 1377            Self::CodeAction(action) => action.lsp_action.title.clone(),
 1378            Self::Task(_, task) => task.resolved_label.clone(),
 1379        }
 1380    }
 1381}
 1382
 1383struct CodeActionsMenu {
 1384    actions: CodeActionContents,
 1385    buffer: Model<Buffer>,
 1386    selected_item: usize,
 1387    scroll_handle: UniformListScrollHandle,
 1388    deployed_from_indicator: Option<DisplayRow>,
 1389}
 1390
 1391impl CodeActionsMenu {
 1392    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1393        self.selected_item = 0;
 1394        self.scroll_handle.scroll_to_item(self.selected_item);
 1395        cx.notify()
 1396    }
 1397
 1398    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1399        if self.selected_item > 0 {
 1400            self.selected_item -= 1;
 1401        } else {
 1402            self.selected_item = self.actions.len() - 1;
 1403        }
 1404        self.scroll_handle.scroll_to_item(self.selected_item);
 1405        cx.notify();
 1406    }
 1407
 1408    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1409        if self.selected_item + 1 < self.actions.len() {
 1410            self.selected_item += 1;
 1411        } else {
 1412            self.selected_item = 0;
 1413        }
 1414        self.scroll_handle.scroll_to_item(self.selected_item);
 1415        cx.notify();
 1416    }
 1417
 1418    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1419        self.selected_item = self.actions.len() - 1;
 1420        self.scroll_handle.scroll_to_item(self.selected_item);
 1421        cx.notify()
 1422    }
 1423
 1424    fn visible(&self) -> bool {
 1425        !self.actions.is_empty()
 1426    }
 1427
 1428    fn render(
 1429        &self,
 1430        cursor_position: DisplayPoint,
 1431        _style: &EditorStyle,
 1432        max_height: Pixels,
 1433        cx: &mut ViewContext<Editor>,
 1434    ) -> (ContextMenuOrigin, AnyElement) {
 1435        let actions = self.actions.clone();
 1436        let selected_item = self.selected_item;
 1437        let element = uniform_list(
 1438            cx.view().clone(),
 1439            "code_actions_menu",
 1440            self.actions.len(),
 1441            move |_this, range, cx| {
 1442                actions
 1443                    .iter()
 1444                    .skip(range.start)
 1445                    .take(range.end - range.start)
 1446                    .enumerate()
 1447                    .map(|(ix, action)| {
 1448                        let item_ix = range.start + ix;
 1449                        let selected = selected_item == item_ix;
 1450                        let colors = cx.theme().colors();
 1451                        div()
 1452                            .px_2()
 1453                            .text_color(colors.text)
 1454                            .when(selected, |style| {
 1455                                style
 1456                                    .bg(colors.element_active)
 1457                                    .text_color(colors.text_accent)
 1458                            })
 1459                            .hover(|style| {
 1460                                style
 1461                                    .bg(colors.element_hover)
 1462                                    .text_color(colors.text_accent)
 1463                            })
 1464                            .whitespace_nowrap()
 1465                            .when_some(action.as_code_action(), |this, action| {
 1466                                this.on_mouse_down(
 1467                                    MouseButton::Left,
 1468                                    cx.listener(move |editor, _, cx| {
 1469                                        cx.stop_propagation();
 1470                                        if let Some(task) = editor.confirm_code_action(
 1471                                            &ConfirmCodeAction {
 1472                                                item_ix: Some(item_ix),
 1473                                            },
 1474                                            cx,
 1475                                        ) {
 1476                                            task.detach_and_log_err(cx)
 1477                                        }
 1478                                    }),
 1479                                )
 1480                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1481                                .child(SharedString::from(action.lsp_action.title.clone()))
 1482                            })
 1483                            .when_some(action.as_task(), |this, task| {
 1484                                this.on_mouse_down(
 1485                                    MouseButton::Left,
 1486                                    cx.listener(move |editor, _, cx| {
 1487                                        cx.stop_propagation();
 1488                                        if let Some(task) = editor.confirm_code_action(
 1489                                            &ConfirmCodeAction {
 1490                                                item_ix: Some(item_ix),
 1491                                            },
 1492                                            cx,
 1493                                        ) {
 1494                                            task.detach_and_log_err(cx)
 1495                                        }
 1496                                    }),
 1497                                )
 1498                                .child(SharedString::from(task.resolved_label.clone()))
 1499                            })
 1500                    })
 1501                    .collect()
 1502            },
 1503        )
 1504        .elevation_1(cx)
 1505        .px_2()
 1506        .py_1()
 1507        .max_h(max_height)
 1508        .occlude()
 1509        .track_scroll(self.scroll_handle.clone())
 1510        .with_width_from_item(
 1511            self.actions
 1512                .iter()
 1513                .enumerate()
 1514                .max_by_key(|(_, action)| match action {
 1515                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1516                    CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
 1517                })
 1518                .map(|(ix, _)| ix),
 1519        )
 1520        .with_sizing_behavior(ListSizingBehavior::Infer)
 1521        .into_any_element();
 1522
 1523        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1524            ContextMenuOrigin::GutterIndicator(row)
 1525        } else {
 1526            ContextMenuOrigin::EditorPoint(cursor_position)
 1527        };
 1528
 1529        (cursor_position, element)
 1530    }
 1531}
 1532
 1533#[derive(Debug)]
 1534struct ActiveDiagnosticGroup {
 1535    primary_range: Range<Anchor>,
 1536    primary_message: String,
 1537    group_id: usize,
 1538    blocks: HashMap<BlockId, Diagnostic>,
 1539    is_valid: bool,
 1540}
 1541
 1542#[derive(Serialize, Deserialize, Clone, Debug)]
 1543pub struct ClipboardSelection {
 1544    pub len: usize,
 1545    pub is_entire_line: bool,
 1546    pub first_line_indent: u32,
 1547}
 1548
 1549#[derive(Debug)]
 1550pub(crate) struct NavigationData {
 1551    cursor_anchor: Anchor,
 1552    cursor_position: Point,
 1553    scroll_anchor: ScrollAnchor,
 1554    scroll_top_row: u32,
 1555}
 1556
 1557enum GotoDefinitionKind {
 1558    Symbol,
 1559    Type,
 1560    Implementation,
 1561}
 1562
 1563#[derive(Debug, Clone)]
 1564enum InlayHintRefreshReason {
 1565    Toggle(bool),
 1566    SettingsChange(InlayHintSettings),
 1567    NewLinesShown,
 1568    BufferEdited(HashSet<Arc<Language>>),
 1569    RefreshRequested,
 1570    ExcerptsRemoved(Vec<ExcerptId>),
 1571}
 1572
 1573impl InlayHintRefreshReason {
 1574    fn description(&self) -> &'static str {
 1575        match self {
 1576            Self::Toggle(_) => "toggle",
 1577            Self::SettingsChange(_) => "settings change",
 1578            Self::NewLinesShown => "new lines shown",
 1579            Self::BufferEdited(_) => "buffer edited",
 1580            Self::RefreshRequested => "refresh requested",
 1581            Self::ExcerptsRemoved(_) => "excerpts removed",
 1582        }
 1583    }
 1584}
 1585
 1586impl Editor {
 1587    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1588        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1589        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1590        Self::new(
 1591            EditorMode::SingleLine { auto_width: false },
 1592            buffer,
 1593            None,
 1594            false,
 1595            cx,
 1596        )
 1597    }
 1598
 1599    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1600        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1601        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1602        Self::new(EditorMode::Full, buffer, None, false, cx)
 1603    }
 1604
 1605    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1606        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1607        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1608        Self::new(
 1609            EditorMode::SingleLine { auto_width: true },
 1610            buffer,
 1611            None,
 1612            false,
 1613            cx,
 1614        )
 1615    }
 1616
 1617    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1618        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1619        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1620        Self::new(
 1621            EditorMode::AutoHeight { max_lines },
 1622            buffer,
 1623            None,
 1624            false,
 1625            cx,
 1626        )
 1627    }
 1628
 1629    pub fn for_buffer(
 1630        buffer: Model<Buffer>,
 1631        project: Option<Model<Project>>,
 1632        cx: &mut ViewContext<Self>,
 1633    ) -> Self {
 1634        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1635        Self::new(EditorMode::Full, buffer, project, false, cx)
 1636    }
 1637
 1638    pub fn for_multibuffer(
 1639        buffer: Model<MultiBuffer>,
 1640        project: Option<Model<Project>>,
 1641        show_excerpt_controls: bool,
 1642        cx: &mut ViewContext<Self>,
 1643    ) -> Self {
 1644        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1645    }
 1646
 1647    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1648        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1649        let mut clone = Self::new(
 1650            self.mode,
 1651            self.buffer.clone(),
 1652            self.project.clone(),
 1653            show_excerpt_controls,
 1654            cx,
 1655        );
 1656        self.display_map.update(cx, |display_map, cx| {
 1657            let snapshot = display_map.snapshot(cx);
 1658            clone.display_map.update(cx, |display_map, cx| {
 1659                display_map.set_state(&snapshot, cx);
 1660            });
 1661        });
 1662        clone.selections.clone_state(&self.selections);
 1663        clone.scroll_manager.clone_state(&self.scroll_manager);
 1664        clone.searchable = self.searchable;
 1665        clone
 1666    }
 1667
 1668    pub fn new(
 1669        mode: EditorMode,
 1670        buffer: Model<MultiBuffer>,
 1671        project: Option<Model<Project>>,
 1672        show_excerpt_controls: bool,
 1673        cx: &mut ViewContext<Self>,
 1674    ) -> Self {
 1675        let style = cx.text_style();
 1676        let font_size = style.font_size.to_pixels(cx.rem_size());
 1677        let editor = cx.view().downgrade();
 1678        let fold_placeholder = FoldPlaceholder {
 1679            constrain_width: true,
 1680            render: Arc::new(move |fold_id, fold_range, cx| {
 1681                let editor = editor.clone();
 1682                div()
 1683                    .id(fold_id)
 1684                    .bg(cx.theme().colors().ghost_element_background)
 1685                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1686                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1687                    .rounded_sm()
 1688                    .size_full()
 1689                    .cursor_pointer()
 1690                    .child("")
 1691                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1692                    .on_click(move |_, cx| {
 1693                        editor
 1694                            .update(cx, |editor, cx| {
 1695                                editor.unfold_ranges(
 1696                                    [fold_range.start..fold_range.end],
 1697                                    true,
 1698                                    false,
 1699                                    cx,
 1700                                );
 1701                                cx.stop_propagation();
 1702                            })
 1703                            .ok();
 1704                    })
 1705                    .into_any()
 1706            }),
 1707            merge_adjacent: true,
 1708        };
 1709        let file_header_size = if show_excerpt_controls { 3 } else { 2 };
 1710        let display_map = cx.new_model(|cx| {
 1711            DisplayMap::new(
 1712                buffer.clone(),
 1713                style.font(),
 1714                font_size,
 1715                None,
 1716                show_excerpt_controls,
 1717                file_header_size,
 1718                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1719                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1720                fold_placeholder,
 1721                cx,
 1722            )
 1723        });
 1724
 1725        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1726
 1727        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1728
 1729        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1730            .then(|| language_settings::SoftWrap::PreferLine);
 1731
 1732        let mut project_subscriptions = Vec::new();
 1733        if mode == EditorMode::Full {
 1734            if let Some(project) = project.as_ref() {
 1735                if buffer.read(cx).is_singleton() {
 1736                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1737                        cx.emit(EditorEvent::TitleChanged);
 1738                    }));
 1739                }
 1740                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1741                    if let project::Event::RefreshInlayHints = event {
 1742                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1743                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1744                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1745                            let focus_handle = editor.focus_handle(cx);
 1746                            if focus_handle.is_focused(cx) {
 1747                                let snapshot = buffer.read(cx).snapshot();
 1748                                for (range, snippet) in snippet_edits {
 1749                                    let editor_range =
 1750                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1751                                    editor
 1752                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1753                                        .ok();
 1754                                }
 1755                            }
 1756                        }
 1757                    }
 1758                }));
 1759                let task_inventory = project.read(cx).task_inventory().clone();
 1760                project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1761                    editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1762                }));
 1763            }
 1764        }
 1765
 1766        let inlay_hint_settings = inlay_hint_settings(
 1767            selections.newest_anchor().head(),
 1768            &buffer.read(cx).snapshot(cx),
 1769            cx,
 1770        );
 1771        let focus_handle = cx.focus_handle();
 1772        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1773        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1774            .detach();
 1775        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1776
 1777        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1778            Some(false)
 1779        } else {
 1780            None
 1781        };
 1782
 1783        let mut this = Self {
 1784            focus_handle,
 1785            show_cursor_when_unfocused: false,
 1786            last_focused_descendant: None,
 1787            buffer: buffer.clone(),
 1788            display_map: display_map.clone(),
 1789            selections,
 1790            scroll_manager: ScrollManager::new(cx),
 1791            columnar_selection_tail: None,
 1792            add_selections_state: None,
 1793            select_next_state: None,
 1794            select_prev_state: None,
 1795            selection_history: Default::default(),
 1796            autoclose_regions: Default::default(),
 1797            snippet_stack: Default::default(),
 1798            select_larger_syntax_node_stack: Vec::new(),
 1799            ime_transaction: Default::default(),
 1800            active_diagnostics: None,
 1801            soft_wrap_mode_override,
 1802            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1803            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1804            project,
 1805            blink_manager: blink_manager.clone(),
 1806            show_local_selections: true,
 1807            mode,
 1808            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1809            show_gutter: mode == EditorMode::Full,
 1810            show_line_numbers: None,
 1811            show_git_diff_gutter: None,
 1812            show_code_actions: None,
 1813            show_runnables: None,
 1814            show_wrap_guides: None,
 1815            show_indent_guides,
 1816            placeholder_text: None,
 1817            highlight_order: 0,
 1818            highlighted_rows: HashMap::default(),
 1819            background_highlights: Default::default(),
 1820            gutter_highlights: TreeMap::default(),
 1821            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1822            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1823            nav_history: None,
 1824            context_menu: RwLock::new(None),
 1825            mouse_context_menu: None,
 1826            completion_tasks: Default::default(),
 1827            signature_help_state: SignatureHelpState::default(),
 1828            auto_signature_help: None,
 1829            find_all_references_task_sources: Vec::new(),
 1830            next_completion_id: 0,
 1831            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1832            next_inlay_id: 0,
 1833            available_code_actions: Default::default(),
 1834            code_actions_task: Default::default(),
 1835            document_highlights_task: Default::default(),
 1836            linked_editing_range_task: Default::default(),
 1837            pending_rename: Default::default(),
 1838            searchable: true,
 1839            cursor_shape: Default::default(),
 1840            current_line_highlight: None,
 1841            autoindent_mode: Some(AutoindentMode::EachLine),
 1842            collapse_matches: false,
 1843            workspace: None,
 1844            keymap_context_layers: Default::default(),
 1845            input_enabled: true,
 1846            use_modal_editing: mode == EditorMode::Full,
 1847            read_only: false,
 1848            use_autoclose: true,
 1849            use_auto_surround: true,
 1850            auto_replace_emoji_shortcode: false,
 1851            leader_peer_id: None,
 1852            remote_id: None,
 1853            hover_state: Default::default(),
 1854            hovered_link_state: Default::default(),
 1855            inline_completion_provider: None,
 1856            active_inline_completion: None,
 1857            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1858            expanded_hunks: ExpandedHunks::default(),
 1859            gutter_hovered: false,
 1860            pixel_position_of_newest_cursor: None,
 1861            last_bounds: None,
 1862            expect_bounds_change: None,
 1863            gutter_dimensions: GutterDimensions::default(),
 1864            style: None,
 1865            show_cursor_names: false,
 1866            hovered_cursors: Default::default(),
 1867            next_editor_action_id: EditorActionId::default(),
 1868            editor_actions: Rc::default(),
 1869            vim_replace_map: Default::default(),
 1870            show_inline_completions: mode == EditorMode::Full,
 1871            custom_context_menu: None,
 1872            show_git_blame_gutter: false,
 1873            show_git_blame_inline: false,
 1874            show_selection_menu: None,
 1875            show_git_blame_inline_delay_task: None,
 1876            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1877            blame: None,
 1878            blame_subscription: None,
 1879            file_header_size,
 1880            tasks: Default::default(),
 1881            _subscriptions: vec![
 1882                cx.observe(&buffer, Self::on_buffer_changed),
 1883                cx.subscribe(&buffer, Self::on_buffer_event),
 1884                cx.observe(&display_map, Self::on_display_map_changed),
 1885                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1886                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1887                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1888                cx.observe_window_activation(|editor, cx| {
 1889                    let active = cx.is_window_active();
 1890                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1891                        if active {
 1892                            blink_manager.enable(cx);
 1893                        } else {
 1894                            blink_manager.show_cursor(cx);
 1895                            blink_manager.disable(cx);
 1896                        }
 1897                    });
 1898                }),
 1899            ],
 1900            tasks_update_task: None,
 1901            linked_edit_ranges: Default::default(),
 1902            previous_search_ranges: None,
 1903            breadcrumb_header: None,
 1904        };
 1905        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1906        this._subscriptions.extend(project_subscriptions);
 1907
 1908        this.end_selection(cx);
 1909        this.scroll_manager.show_scrollbar(cx);
 1910
 1911        if mode == EditorMode::Full {
 1912            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1913            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1914
 1915            if this.git_blame_inline_enabled {
 1916                this.git_blame_inline_enabled = true;
 1917                this.start_git_blame_inline(false, cx);
 1918            }
 1919        }
 1920
 1921        this.report_editor_event("open", None, cx);
 1922        this
 1923    }
 1924
 1925    pub fn mouse_menu_is_focused(&self, cx: &mut WindowContext) -> bool {
 1926        self.mouse_context_menu
 1927            .as_ref()
 1928            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1929    }
 1930
 1931    fn key_context(&self, cx: &AppContext) -> KeyContext {
 1932        let mut key_context = KeyContext::new_with_defaults();
 1933        key_context.add("Editor");
 1934        let mode = match self.mode {
 1935            EditorMode::SingleLine { .. } => "single_line",
 1936            EditorMode::AutoHeight { .. } => "auto_height",
 1937            EditorMode::Full => "full",
 1938        };
 1939
 1940        if EditorSettings::get_global(cx).jupyter.enabled {
 1941            key_context.add("jupyter");
 1942        }
 1943
 1944        key_context.set("mode", mode);
 1945        if self.pending_rename.is_some() {
 1946            key_context.add("renaming");
 1947        }
 1948        if self.context_menu_visible() {
 1949            match self.context_menu.read().as_ref() {
 1950                Some(ContextMenu::Completions(_)) => {
 1951                    key_context.add("menu");
 1952                    key_context.add("showing_completions")
 1953                }
 1954                Some(ContextMenu::CodeActions(_)) => {
 1955                    key_context.add("menu");
 1956                    key_context.add("showing_code_actions")
 1957                }
 1958                None => {}
 1959            }
 1960        }
 1961
 1962        for layer in self.keymap_context_layers.values() {
 1963            key_context.extend(layer);
 1964        }
 1965
 1966        if let Some(extension) = self
 1967            .buffer
 1968            .read(cx)
 1969            .as_singleton()
 1970            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1971        {
 1972            key_context.set("extension", extension.to_string());
 1973        }
 1974
 1975        if self.has_active_inline_completion(cx) {
 1976            key_context.add("copilot_suggestion");
 1977            key_context.add("inline_completion");
 1978        }
 1979
 1980        key_context
 1981    }
 1982
 1983    pub fn new_file(
 1984        workspace: &mut Workspace,
 1985        _: &workspace::NewFile,
 1986        cx: &mut ViewContext<Workspace>,
 1987    ) {
 1988        let project = workspace.project().clone();
 1989        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1990
 1991        cx.spawn(|workspace, mut cx| async move {
 1992            let buffer = create.await?;
 1993            workspace.update(&mut cx, |workspace, cx| {
 1994                workspace.add_item_to_active_pane(
 1995                    Box::new(
 1996                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1997                    ),
 1998                    None,
 1999                    cx,
 2000                )
 2001            })
 2002        })
 2003        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2004            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2005                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2006                e.error_tag("required").unwrap_or("the latest version")
 2007            )),
 2008            _ => None,
 2009        });
 2010    }
 2011
 2012    pub fn new_file_in_direction(
 2013        workspace: &mut Workspace,
 2014        action: &workspace::NewFileInDirection,
 2015        cx: &mut ViewContext<Workspace>,
 2016    ) {
 2017        let project = workspace.project().clone();
 2018        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2019        let direction = action.0;
 2020
 2021        cx.spawn(|workspace, mut cx| async move {
 2022            let buffer = create.await?;
 2023            workspace.update(&mut cx, move |workspace, cx| {
 2024                workspace.split_item(
 2025                    direction,
 2026                    Box::new(
 2027                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2028                    ),
 2029                    cx,
 2030                )
 2031            })?;
 2032            anyhow::Ok(())
 2033        })
 2034        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2035            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2036                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2037                e.error_tag("required").unwrap_or("the latest version")
 2038            )),
 2039            _ => None,
 2040        });
 2041    }
 2042
 2043    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
 2044        self.buffer.read(cx).replica_id()
 2045    }
 2046
 2047    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2048        self.leader_peer_id
 2049    }
 2050
 2051    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2052        &self.buffer
 2053    }
 2054
 2055    pub fn workspace(&self) -> Option<View<Workspace>> {
 2056        self.workspace.as_ref()?.0.upgrade()
 2057    }
 2058
 2059    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2060        self.buffer().read(cx).title(cx)
 2061    }
 2062
 2063    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2064        EditorSnapshot {
 2065            mode: self.mode,
 2066            show_gutter: self.show_gutter,
 2067            show_line_numbers: self.show_line_numbers,
 2068            show_git_diff_gutter: self.show_git_diff_gutter,
 2069            show_code_actions: self.show_code_actions,
 2070            show_runnables: self.show_runnables,
 2071            render_git_blame_gutter: self.render_git_blame_gutter(cx),
 2072            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2073            scroll_anchor: self.scroll_manager.anchor(),
 2074            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2075            placeholder_text: self.placeholder_text.clone(),
 2076            is_focused: self.focus_handle.is_focused(cx),
 2077            current_line_highlight: self
 2078                .current_line_highlight
 2079                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2080            gutter_hovered: self.gutter_hovered,
 2081        }
 2082    }
 2083
 2084    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2085        self.buffer.read(cx).language_at(point, cx)
 2086    }
 2087
 2088    pub fn file_at<T: ToOffset>(
 2089        &self,
 2090        point: T,
 2091        cx: &AppContext,
 2092    ) -> Option<Arc<dyn language::File>> {
 2093        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2094    }
 2095
 2096    pub fn active_excerpt(
 2097        &self,
 2098        cx: &AppContext,
 2099    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2100        self.buffer
 2101            .read(cx)
 2102            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2103    }
 2104
 2105    pub fn mode(&self) -> EditorMode {
 2106        self.mode
 2107    }
 2108
 2109    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2110        self.collaboration_hub.as_deref()
 2111    }
 2112
 2113    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2114        self.collaboration_hub = Some(hub);
 2115    }
 2116
 2117    pub fn set_custom_context_menu(
 2118        &mut self,
 2119        f: impl 'static
 2120            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2121    ) {
 2122        self.custom_context_menu = Some(Box::new(f))
 2123    }
 2124
 2125    pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
 2126        self.completion_provider = Some(provider);
 2127    }
 2128
 2129    pub fn set_inline_completion_provider<T>(
 2130        &mut self,
 2131        provider: Option<Model<T>>,
 2132        cx: &mut ViewContext<Self>,
 2133    ) where
 2134        T: InlineCompletionProvider,
 2135    {
 2136        self.inline_completion_provider =
 2137            provider.map(|provider| RegisteredInlineCompletionProvider {
 2138                _subscription: cx.observe(&provider, |this, _, cx| {
 2139                    if this.focus_handle.is_focused(cx) {
 2140                        this.update_visible_inline_completion(cx);
 2141                    }
 2142                }),
 2143                provider: Arc::new(provider),
 2144            });
 2145        self.refresh_inline_completion(false, cx);
 2146    }
 2147
 2148    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2149        self.placeholder_text.as_deref()
 2150    }
 2151
 2152    pub fn set_placeholder_text(
 2153        &mut self,
 2154        placeholder_text: impl Into<Arc<str>>,
 2155        cx: &mut ViewContext<Self>,
 2156    ) {
 2157        let placeholder_text = Some(placeholder_text.into());
 2158        if self.placeholder_text != placeholder_text {
 2159            self.placeholder_text = placeholder_text;
 2160            cx.notify();
 2161        }
 2162    }
 2163
 2164    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2165        self.cursor_shape = cursor_shape;
 2166        cx.notify();
 2167    }
 2168
 2169    pub fn set_current_line_highlight(
 2170        &mut self,
 2171        current_line_highlight: Option<CurrentLineHighlight>,
 2172    ) {
 2173        self.current_line_highlight = current_line_highlight;
 2174    }
 2175
 2176    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2177        self.collapse_matches = collapse_matches;
 2178    }
 2179
 2180    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2181        if self.collapse_matches {
 2182            return range.start..range.start;
 2183        }
 2184        range.clone()
 2185    }
 2186
 2187    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2188        if self.display_map.read(cx).clip_at_line_ends != clip {
 2189            self.display_map
 2190                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2191        }
 2192    }
 2193
 2194    pub fn set_keymap_context_layer<Tag: 'static>(
 2195        &mut self,
 2196        context: KeyContext,
 2197        cx: &mut ViewContext<Self>,
 2198    ) {
 2199        self.keymap_context_layers
 2200            .insert(TypeId::of::<Tag>(), context);
 2201        cx.notify();
 2202    }
 2203
 2204    pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
 2205        self.keymap_context_layers.remove(&TypeId::of::<Tag>());
 2206        cx.notify();
 2207    }
 2208
 2209    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2210        self.input_enabled = input_enabled;
 2211    }
 2212
 2213    pub fn set_autoindent(&mut self, autoindent: bool) {
 2214        if autoindent {
 2215            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2216        } else {
 2217            self.autoindent_mode = None;
 2218        }
 2219    }
 2220
 2221    pub fn read_only(&self, cx: &AppContext) -> bool {
 2222        self.read_only || self.buffer.read(cx).read_only()
 2223    }
 2224
 2225    pub fn set_read_only(&mut self, read_only: bool) {
 2226        self.read_only = read_only;
 2227    }
 2228
 2229    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2230        self.use_autoclose = autoclose;
 2231    }
 2232
 2233    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2234        self.use_auto_surround = auto_surround;
 2235    }
 2236
 2237    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2238        self.auto_replace_emoji_shortcode = auto_replace;
 2239    }
 2240
 2241    pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
 2242        self.show_inline_completions = show_inline_completions;
 2243    }
 2244
 2245    pub fn set_use_modal_editing(&mut self, to: bool) {
 2246        self.use_modal_editing = to;
 2247    }
 2248
 2249    pub fn use_modal_editing(&self) -> bool {
 2250        self.use_modal_editing
 2251    }
 2252
 2253    fn selections_did_change(
 2254        &mut self,
 2255        local: bool,
 2256        old_cursor_position: &Anchor,
 2257        show_completions: bool,
 2258        cx: &mut ViewContext<Self>,
 2259    ) {
 2260        // Copy selections to primary selection buffer
 2261        #[cfg(target_os = "linux")]
 2262        if local {
 2263            let selections = self.selections.all::<usize>(cx);
 2264            let buffer_handle = self.buffer.read(cx).read(cx);
 2265
 2266            let mut text = String::new();
 2267            for (index, selection) in selections.iter().enumerate() {
 2268                let text_for_selection = buffer_handle
 2269                    .text_for_range(selection.start..selection.end)
 2270                    .collect::<String>();
 2271
 2272                text.push_str(&text_for_selection);
 2273                if index != selections.len() - 1 {
 2274                    text.push('\n');
 2275                }
 2276            }
 2277
 2278            if !text.is_empty() {
 2279                cx.write_to_primary(ClipboardItem::new(text));
 2280            }
 2281        }
 2282
 2283        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2284            self.buffer.update(cx, |buffer, cx| {
 2285                buffer.set_active_selections(
 2286                    &self.selections.disjoint_anchors(),
 2287                    self.selections.line_mode,
 2288                    self.cursor_shape,
 2289                    cx,
 2290                )
 2291            });
 2292        }
 2293        let display_map = self
 2294            .display_map
 2295            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2296        let buffer = &display_map.buffer_snapshot;
 2297        self.add_selections_state = None;
 2298        self.select_next_state = None;
 2299        self.select_prev_state = None;
 2300        self.select_larger_syntax_node_stack.clear();
 2301        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2302        self.snippet_stack
 2303            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2304        self.take_rename(false, cx);
 2305
 2306        let new_cursor_position = self.selections.newest_anchor().head();
 2307
 2308        self.push_to_nav_history(
 2309            *old_cursor_position,
 2310            Some(new_cursor_position.to_point(buffer)),
 2311            cx,
 2312        );
 2313
 2314        if local {
 2315            let new_cursor_position = self.selections.newest_anchor().head();
 2316            let mut context_menu = self.context_menu.write();
 2317            let completion_menu = match context_menu.as_ref() {
 2318                Some(ContextMenu::Completions(menu)) => Some(menu),
 2319
 2320                _ => {
 2321                    *context_menu = None;
 2322                    None
 2323                }
 2324            };
 2325
 2326            if let Some(completion_menu) = completion_menu {
 2327                let cursor_position = new_cursor_position.to_offset(buffer);
 2328                let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
 2329                if kind == Some(CharKind::Word)
 2330                    && word_range.to_inclusive().contains(&cursor_position)
 2331                {
 2332                    let mut completion_menu = completion_menu.clone();
 2333                    drop(context_menu);
 2334
 2335                    let query = Self::completion_query(buffer, cursor_position);
 2336                    cx.spawn(move |this, mut cx| async move {
 2337                        completion_menu
 2338                            .filter(query.as_deref(), cx.background_executor().clone())
 2339                            .await;
 2340
 2341                        this.update(&mut cx, |this, cx| {
 2342                            let mut context_menu = this.context_menu.write();
 2343                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2344                                return;
 2345                            };
 2346
 2347                            if menu.id > completion_menu.id {
 2348                                return;
 2349                            }
 2350
 2351                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2352                            drop(context_menu);
 2353                            cx.notify();
 2354                        })
 2355                    })
 2356                    .detach();
 2357
 2358                    if show_completions {
 2359                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2360                    }
 2361                } else {
 2362                    drop(context_menu);
 2363                    self.hide_context_menu(cx);
 2364                }
 2365            } else {
 2366                drop(context_menu);
 2367            }
 2368
 2369            hide_hover(self, cx);
 2370
 2371            if old_cursor_position.to_display_point(&display_map).row()
 2372                != new_cursor_position.to_display_point(&display_map).row()
 2373            {
 2374                self.available_code_actions.take();
 2375            }
 2376            self.refresh_code_actions(cx);
 2377            self.refresh_document_highlights(cx);
 2378            refresh_matching_bracket_highlights(self, cx);
 2379            self.discard_inline_completion(false, cx);
 2380            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2381            if self.git_blame_inline_enabled {
 2382                self.start_inline_blame_timer(cx);
 2383            }
 2384        }
 2385
 2386        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2387        cx.emit(EditorEvent::SelectionsChanged { local });
 2388
 2389        if self.selections.disjoint_anchors().len() == 1 {
 2390            cx.emit(SearchEvent::ActiveMatchChanged)
 2391        }
 2392        cx.notify();
 2393    }
 2394
 2395    pub fn change_selections<R>(
 2396        &mut self,
 2397        autoscroll: Option<Autoscroll>,
 2398        cx: &mut ViewContext<Self>,
 2399        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2400    ) -> R {
 2401        self.change_selections_inner(autoscroll, true, cx, change)
 2402    }
 2403
 2404    pub fn change_selections_inner<R>(
 2405        &mut self,
 2406        autoscroll: Option<Autoscroll>,
 2407        request_completions: bool,
 2408        cx: &mut ViewContext<Self>,
 2409        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2410    ) -> R {
 2411        let old_cursor_position = self.selections.newest_anchor().head();
 2412        self.push_to_selection_history();
 2413
 2414        let (changed, result) = self.selections.change_with(cx, change);
 2415
 2416        if changed {
 2417            if let Some(autoscroll) = autoscroll {
 2418                self.request_autoscroll(autoscroll, cx);
 2419            }
 2420            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2421
 2422            if self.should_open_signature_help_automatically(
 2423                &old_cursor_position,
 2424                self.signature_help_state.backspace_pressed(),
 2425                cx,
 2426            ) {
 2427                self.show_signature_help(&ShowSignatureHelp, cx);
 2428            }
 2429            self.signature_help_state.set_backspace_pressed(false);
 2430        }
 2431
 2432        result
 2433    }
 2434
 2435    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2436    where
 2437        I: IntoIterator<Item = (Range<S>, T)>,
 2438        S: ToOffset,
 2439        T: Into<Arc<str>>,
 2440    {
 2441        if self.read_only(cx) {
 2442            return;
 2443        }
 2444
 2445        self.buffer
 2446            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2447    }
 2448
 2449    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2450    where
 2451        I: IntoIterator<Item = (Range<S>, T)>,
 2452        S: ToOffset,
 2453        T: Into<Arc<str>>,
 2454    {
 2455        if self.read_only(cx) {
 2456            return;
 2457        }
 2458
 2459        self.buffer.update(cx, |buffer, cx| {
 2460            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2461        });
 2462    }
 2463
 2464    pub fn edit_with_block_indent<I, S, T>(
 2465        &mut self,
 2466        edits: I,
 2467        original_indent_columns: Vec<u32>,
 2468        cx: &mut ViewContext<Self>,
 2469    ) where
 2470        I: IntoIterator<Item = (Range<S>, T)>,
 2471        S: ToOffset,
 2472        T: Into<Arc<str>>,
 2473    {
 2474        if self.read_only(cx) {
 2475            return;
 2476        }
 2477
 2478        self.buffer.update(cx, |buffer, cx| {
 2479            buffer.edit(
 2480                edits,
 2481                Some(AutoindentMode::Block {
 2482                    original_indent_columns,
 2483                }),
 2484                cx,
 2485            )
 2486        });
 2487    }
 2488
 2489    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2490        self.hide_context_menu(cx);
 2491
 2492        match phase {
 2493            SelectPhase::Begin {
 2494                position,
 2495                add,
 2496                click_count,
 2497            } => self.begin_selection(position, add, click_count, cx),
 2498            SelectPhase::BeginColumnar {
 2499                position,
 2500                goal_column,
 2501                reset,
 2502            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2503            SelectPhase::Extend {
 2504                position,
 2505                click_count,
 2506            } => self.extend_selection(position, click_count, cx),
 2507            SelectPhase::Update {
 2508                position,
 2509                goal_column,
 2510                scroll_delta,
 2511            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2512            SelectPhase::End => self.end_selection(cx),
 2513        }
 2514    }
 2515
 2516    fn extend_selection(
 2517        &mut self,
 2518        position: DisplayPoint,
 2519        click_count: usize,
 2520        cx: &mut ViewContext<Self>,
 2521    ) {
 2522        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2523        let tail = self.selections.newest::<usize>(cx).tail();
 2524        self.begin_selection(position, false, click_count, cx);
 2525
 2526        let position = position.to_offset(&display_map, Bias::Left);
 2527        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2528
 2529        let mut pending_selection = self
 2530            .selections
 2531            .pending_anchor()
 2532            .expect("extend_selection not called with pending selection");
 2533        if position >= tail {
 2534            pending_selection.start = tail_anchor;
 2535        } else {
 2536            pending_selection.end = tail_anchor;
 2537            pending_selection.reversed = true;
 2538        }
 2539
 2540        let mut pending_mode = self.selections.pending_mode().unwrap();
 2541        match &mut pending_mode {
 2542            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2543            _ => {}
 2544        }
 2545
 2546        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2547            s.set_pending(pending_selection, pending_mode)
 2548        });
 2549    }
 2550
 2551    fn begin_selection(
 2552        &mut self,
 2553        position: DisplayPoint,
 2554        add: bool,
 2555        click_count: usize,
 2556        cx: &mut ViewContext<Self>,
 2557    ) {
 2558        if !self.focus_handle.is_focused(cx) {
 2559            self.last_focused_descendant = None;
 2560            cx.focus(&self.focus_handle);
 2561        }
 2562
 2563        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2564        let buffer = &display_map.buffer_snapshot;
 2565        let newest_selection = self.selections.newest_anchor().clone();
 2566        let position = display_map.clip_point(position, Bias::Left);
 2567
 2568        let start;
 2569        let end;
 2570        let mode;
 2571        let auto_scroll;
 2572        match click_count {
 2573            1 => {
 2574                start = buffer.anchor_before(position.to_point(&display_map));
 2575                end = start;
 2576                mode = SelectMode::Character;
 2577                auto_scroll = true;
 2578            }
 2579            2 => {
 2580                let range = movement::surrounding_word(&display_map, position);
 2581                start = buffer.anchor_before(range.start.to_point(&display_map));
 2582                end = buffer.anchor_before(range.end.to_point(&display_map));
 2583                mode = SelectMode::Word(start..end);
 2584                auto_scroll = true;
 2585            }
 2586            3 => {
 2587                let position = display_map
 2588                    .clip_point(position, Bias::Left)
 2589                    .to_point(&display_map);
 2590                let line_start = display_map.prev_line_boundary(position).0;
 2591                let next_line_start = buffer.clip_point(
 2592                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2593                    Bias::Left,
 2594                );
 2595                start = buffer.anchor_before(line_start);
 2596                end = buffer.anchor_before(next_line_start);
 2597                mode = SelectMode::Line(start..end);
 2598                auto_scroll = true;
 2599            }
 2600            _ => {
 2601                start = buffer.anchor_before(0);
 2602                end = buffer.anchor_before(buffer.len());
 2603                mode = SelectMode::All;
 2604                auto_scroll = false;
 2605            }
 2606        }
 2607
 2608        let point_to_delete: Option<usize> = {
 2609            let selected_points: Vec<Selection<Point>> =
 2610                self.selections.disjoint_in_range(start..end, cx);
 2611
 2612            if !add || click_count > 1 {
 2613                None
 2614            } else if selected_points.len() > 0 {
 2615                Some(selected_points[0].id)
 2616            } else {
 2617                let clicked_point_already_selected =
 2618                    self.selections.disjoint.iter().find(|selection| {
 2619                        selection.start.to_point(buffer) == start.to_point(buffer)
 2620                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2621                    });
 2622
 2623                if let Some(selection) = clicked_point_already_selected {
 2624                    Some(selection.id)
 2625                } else {
 2626                    None
 2627                }
 2628            }
 2629        };
 2630
 2631        let selections_count = self.selections.count();
 2632
 2633        self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
 2634            if let Some(point_to_delete) = point_to_delete {
 2635                s.delete(point_to_delete);
 2636
 2637                if selections_count == 1 {
 2638                    s.set_pending_anchor_range(start..end, mode);
 2639                }
 2640            } else {
 2641                if !add {
 2642                    s.clear_disjoint();
 2643                } else if click_count > 1 {
 2644                    s.delete(newest_selection.id)
 2645                }
 2646
 2647                s.set_pending_anchor_range(start..end, mode);
 2648            }
 2649        });
 2650    }
 2651
 2652    fn begin_columnar_selection(
 2653        &mut self,
 2654        position: DisplayPoint,
 2655        goal_column: u32,
 2656        reset: bool,
 2657        cx: &mut ViewContext<Self>,
 2658    ) {
 2659        if !self.focus_handle.is_focused(cx) {
 2660            self.last_focused_descendant = None;
 2661            cx.focus(&self.focus_handle);
 2662        }
 2663
 2664        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2665
 2666        if reset {
 2667            let pointer_position = display_map
 2668                .buffer_snapshot
 2669                .anchor_before(position.to_point(&display_map));
 2670
 2671            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2672                s.clear_disjoint();
 2673                s.set_pending_anchor_range(
 2674                    pointer_position..pointer_position,
 2675                    SelectMode::Character,
 2676                );
 2677            });
 2678        }
 2679
 2680        let tail = self.selections.newest::<Point>(cx).tail();
 2681        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2682
 2683        if !reset {
 2684            self.select_columns(
 2685                tail.to_display_point(&display_map),
 2686                position,
 2687                goal_column,
 2688                &display_map,
 2689                cx,
 2690            );
 2691        }
 2692    }
 2693
 2694    fn update_selection(
 2695        &mut self,
 2696        position: DisplayPoint,
 2697        goal_column: u32,
 2698        scroll_delta: gpui::Point<f32>,
 2699        cx: &mut ViewContext<Self>,
 2700    ) {
 2701        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2702
 2703        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2704            let tail = tail.to_display_point(&display_map);
 2705            self.select_columns(tail, position, goal_column, &display_map, cx);
 2706        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2707            let buffer = self.buffer.read(cx).snapshot(cx);
 2708            let head;
 2709            let tail;
 2710            let mode = self.selections.pending_mode().unwrap();
 2711            match &mode {
 2712                SelectMode::Character => {
 2713                    head = position.to_point(&display_map);
 2714                    tail = pending.tail().to_point(&buffer);
 2715                }
 2716                SelectMode::Word(original_range) => {
 2717                    let original_display_range = original_range.start.to_display_point(&display_map)
 2718                        ..original_range.end.to_display_point(&display_map);
 2719                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2720                        ..original_display_range.end.to_point(&display_map);
 2721                    if movement::is_inside_word(&display_map, position)
 2722                        || original_display_range.contains(&position)
 2723                    {
 2724                        let word_range = movement::surrounding_word(&display_map, position);
 2725                        if word_range.start < original_display_range.start {
 2726                            head = word_range.start.to_point(&display_map);
 2727                        } else {
 2728                            head = word_range.end.to_point(&display_map);
 2729                        }
 2730                    } else {
 2731                        head = position.to_point(&display_map);
 2732                    }
 2733
 2734                    if head <= original_buffer_range.start {
 2735                        tail = original_buffer_range.end;
 2736                    } else {
 2737                        tail = original_buffer_range.start;
 2738                    }
 2739                }
 2740                SelectMode::Line(original_range) => {
 2741                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2742
 2743                    let position = display_map
 2744                        .clip_point(position, Bias::Left)
 2745                        .to_point(&display_map);
 2746                    let line_start = display_map.prev_line_boundary(position).0;
 2747                    let next_line_start = buffer.clip_point(
 2748                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2749                        Bias::Left,
 2750                    );
 2751
 2752                    if line_start < original_range.start {
 2753                        head = line_start
 2754                    } else {
 2755                        head = next_line_start
 2756                    }
 2757
 2758                    if head <= original_range.start {
 2759                        tail = original_range.end;
 2760                    } else {
 2761                        tail = original_range.start;
 2762                    }
 2763                }
 2764                SelectMode::All => {
 2765                    return;
 2766                }
 2767            };
 2768
 2769            if head < tail {
 2770                pending.start = buffer.anchor_before(head);
 2771                pending.end = buffer.anchor_before(tail);
 2772                pending.reversed = true;
 2773            } else {
 2774                pending.start = buffer.anchor_before(tail);
 2775                pending.end = buffer.anchor_before(head);
 2776                pending.reversed = false;
 2777            }
 2778
 2779            self.change_selections(None, cx, |s| {
 2780                s.set_pending(pending, mode);
 2781            });
 2782        } else {
 2783            log::error!("update_selection dispatched with no pending selection");
 2784            return;
 2785        }
 2786
 2787        self.apply_scroll_delta(scroll_delta, cx);
 2788        cx.notify();
 2789    }
 2790
 2791    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2792        self.columnar_selection_tail.take();
 2793        if self.selections.pending_anchor().is_some() {
 2794            let selections = self.selections.all::<usize>(cx);
 2795            self.change_selections(None, cx, |s| {
 2796                s.select(selections);
 2797                s.clear_pending();
 2798            });
 2799        }
 2800    }
 2801
 2802    fn select_columns(
 2803        &mut self,
 2804        tail: DisplayPoint,
 2805        head: DisplayPoint,
 2806        goal_column: u32,
 2807        display_map: &DisplaySnapshot,
 2808        cx: &mut ViewContext<Self>,
 2809    ) {
 2810        let start_row = cmp::min(tail.row(), head.row());
 2811        let end_row = cmp::max(tail.row(), head.row());
 2812        let start_column = cmp::min(tail.column(), goal_column);
 2813        let end_column = cmp::max(tail.column(), goal_column);
 2814        let reversed = start_column < tail.column();
 2815
 2816        let selection_ranges = (start_row.0..=end_row.0)
 2817            .map(DisplayRow)
 2818            .filter_map(|row| {
 2819                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2820                    let start = display_map
 2821                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2822                        .to_point(display_map);
 2823                    let end = display_map
 2824                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2825                        .to_point(display_map);
 2826                    if reversed {
 2827                        Some(end..start)
 2828                    } else {
 2829                        Some(start..end)
 2830                    }
 2831                } else {
 2832                    None
 2833                }
 2834            })
 2835            .collect::<Vec<_>>();
 2836
 2837        self.change_selections(None, cx, |s| {
 2838            s.select_ranges(selection_ranges);
 2839        });
 2840        cx.notify();
 2841    }
 2842
 2843    pub fn has_pending_nonempty_selection(&self) -> bool {
 2844        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2845            Some(Selection { start, end, .. }) => start != end,
 2846            None => false,
 2847        };
 2848
 2849        pending_nonempty_selection
 2850            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2851    }
 2852
 2853    pub fn has_pending_selection(&self) -> bool {
 2854        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2855    }
 2856
 2857    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2858        self.clear_expanded_diff_hunks(cx);
 2859        if self.dismiss_menus_and_popups(true, cx) {
 2860            return;
 2861        }
 2862
 2863        if self.mode == EditorMode::Full {
 2864            if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
 2865                return;
 2866            }
 2867        }
 2868
 2869        cx.propagate();
 2870    }
 2871
 2872    pub fn dismiss_menus_and_popups(
 2873        &mut self,
 2874        should_report_inline_completion_event: bool,
 2875        cx: &mut ViewContext<Self>,
 2876    ) -> bool {
 2877        if self.take_rename(false, cx).is_some() {
 2878            return true;
 2879        }
 2880
 2881        if hide_hover(self, cx) {
 2882            return true;
 2883        }
 2884
 2885        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2886            return true;
 2887        }
 2888
 2889        if self.hide_context_menu(cx).is_some() {
 2890            return true;
 2891        }
 2892
 2893        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2894            return true;
 2895        }
 2896
 2897        if self.snippet_stack.pop().is_some() {
 2898            return true;
 2899        }
 2900
 2901        if self.mode == EditorMode::Full {
 2902            if self.active_diagnostics.is_some() {
 2903                self.dismiss_diagnostics(cx);
 2904                return true;
 2905            }
 2906        }
 2907
 2908        false
 2909    }
 2910
 2911    fn linked_editing_ranges_for(
 2912        &self,
 2913        selection: Range<text::Anchor>,
 2914        cx: &AppContext,
 2915    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2916        if self.linked_edit_ranges.is_empty() {
 2917            return None;
 2918        }
 2919        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2920            selection.end.buffer_id.and_then(|end_buffer_id| {
 2921                if selection.start.buffer_id != Some(end_buffer_id) {
 2922                    return None;
 2923                }
 2924                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2925                let snapshot = buffer.read(cx).snapshot();
 2926                self.linked_edit_ranges
 2927                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2928                    .map(|ranges| (ranges, snapshot, buffer))
 2929            })?;
 2930        use text::ToOffset as TO;
 2931        // find offset from the start of current range to current cursor position
 2932        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2933
 2934        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2935        let start_difference = start_offset - start_byte_offset;
 2936        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2937        let end_difference = end_offset - start_byte_offset;
 2938        // Current range has associated linked ranges.
 2939        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2940        for range in linked_ranges.iter() {
 2941            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2942            let end_offset = start_offset + end_difference;
 2943            let start_offset = start_offset + start_difference;
 2944            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2945                continue;
 2946            }
 2947            let start = buffer_snapshot.anchor_after(start_offset);
 2948            let end = buffer_snapshot.anchor_after(end_offset);
 2949            linked_edits
 2950                .entry(buffer.clone())
 2951                .or_default()
 2952                .push(start..end);
 2953        }
 2954        Some(linked_edits)
 2955    }
 2956
 2957    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2958        let text: Arc<str> = text.into();
 2959
 2960        if self.read_only(cx) {
 2961            return;
 2962        }
 2963
 2964        let selections = self.selections.all_adjusted(cx);
 2965        let mut bracket_inserted = false;
 2966        let mut edits = Vec::new();
 2967        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2968        let mut new_selections = Vec::with_capacity(selections.len());
 2969        let mut new_autoclose_regions = Vec::new();
 2970        let snapshot = self.buffer.read(cx).read(cx);
 2971
 2972        for (selection, autoclose_region) in
 2973            self.selections_with_autoclose_regions(selections, &snapshot)
 2974        {
 2975            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2976                // Determine if the inserted text matches the opening or closing
 2977                // bracket of any of this language's bracket pairs.
 2978                let mut bracket_pair = None;
 2979                let mut is_bracket_pair_start = false;
 2980                let mut is_bracket_pair_end = false;
 2981                if !text.is_empty() {
 2982                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2983                    //  and they are removing the character that triggered IME popup.
 2984                    for (pair, enabled) in scope.brackets() {
 2985                        if !pair.close && !pair.surround {
 2986                            continue;
 2987                        }
 2988
 2989                        if enabled && pair.start.ends_with(text.as_ref()) {
 2990                            bracket_pair = Some(pair.clone());
 2991                            is_bracket_pair_start = true;
 2992                            break;
 2993                        }
 2994                        if pair.end.as_str() == text.as_ref() {
 2995                            bracket_pair = Some(pair.clone());
 2996                            is_bracket_pair_end = true;
 2997                            break;
 2998                        }
 2999                    }
 3000                }
 3001
 3002                if let Some(bracket_pair) = bracket_pair {
 3003                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3004                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3005                    let auto_surround =
 3006                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3007                    if selection.is_empty() {
 3008                        if is_bracket_pair_start {
 3009                            let prefix_len = bracket_pair.start.len() - text.len();
 3010
 3011                            // If the inserted text is a suffix of an opening bracket and the
 3012                            // selection is preceded by the rest of the opening bracket, then
 3013                            // insert the closing bracket.
 3014                            let following_text_allows_autoclose = snapshot
 3015                                .chars_at(selection.start)
 3016                                .next()
 3017                                .map_or(true, |c| scope.should_autoclose_before(c));
 3018                            let preceding_text_matches_prefix = prefix_len == 0
 3019                                || (selection.start.column >= (prefix_len as u32)
 3020                                    && snapshot.contains_str_at(
 3021                                        Point::new(
 3022                                            selection.start.row,
 3023                                            selection.start.column - (prefix_len as u32),
 3024                                        ),
 3025                                        &bracket_pair.start[..prefix_len],
 3026                                    ));
 3027
 3028                            if autoclose
 3029                                && bracket_pair.close
 3030                                && following_text_allows_autoclose
 3031                                && preceding_text_matches_prefix
 3032                            {
 3033                                let anchor = snapshot.anchor_before(selection.end);
 3034                                new_selections.push((selection.map(|_| anchor), text.len()));
 3035                                new_autoclose_regions.push((
 3036                                    anchor,
 3037                                    text.len(),
 3038                                    selection.id,
 3039                                    bracket_pair.clone(),
 3040                                ));
 3041                                edits.push((
 3042                                    selection.range(),
 3043                                    format!("{}{}", text, bracket_pair.end).into(),
 3044                                ));
 3045                                bracket_inserted = true;
 3046                                continue;
 3047                            }
 3048                        }
 3049
 3050                        if let Some(region) = autoclose_region {
 3051                            // If the selection is followed by an auto-inserted closing bracket,
 3052                            // then don't insert that closing bracket again; just move the selection
 3053                            // past the closing bracket.
 3054                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3055                                && text.as_ref() == region.pair.end.as_str();
 3056                            if should_skip {
 3057                                let anchor = snapshot.anchor_after(selection.end);
 3058                                new_selections
 3059                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3060                                continue;
 3061                            }
 3062                        }
 3063
 3064                        let always_treat_brackets_as_autoclosed = snapshot
 3065                            .settings_at(selection.start, cx)
 3066                            .always_treat_brackets_as_autoclosed;
 3067                        if always_treat_brackets_as_autoclosed
 3068                            && is_bracket_pair_end
 3069                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3070                        {
 3071                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3072                            // and the inserted text is a closing bracket and the selection is followed
 3073                            // by the closing bracket then move the selection past the closing bracket.
 3074                            let anchor = snapshot.anchor_after(selection.end);
 3075                            new_selections.push((selection.map(|_| anchor), text.len()));
 3076                            continue;
 3077                        }
 3078                    }
 3079                    // If an opening bracket is 1 character long and is typed while
 3080                    // text is selected, then surround that text with the bracket pair.
 3081                    else if auto_surround
 3082                        && bracket_pair.surround
 3083                        && is_bracket_pair_start
 3084                        && bracket_pair.start.chars().count() == 1
 3085                    {
 3086                        edits.push((selection.start..selection.start, text.clone()));
 3087                        edits.push((
 3088                            selection.end..selection.end,
 3089                            bracket_pair.end.as_str().into(),
 3090                        ));
 3091                        bracket_inserted = true;
 3092                        new_selections.push((
 3093                            Selection {
 3094                                id: selection.id,
 3095                                start: snapshot.anchor_after(selection.start),
 3096                                end: snapshot.anchor_before(selection.end),
 3097                                reversed: selection.reversed,
 3098                                goal: selection.goal,
 3099                            },
 3100                            0,
 3101                        ));
 3102                        continue;
 3103                    }
 3104                }
 3105            }
 3106
 3107            if self.auto_replace_emoji_shortcode
 3108                && selection.is_empty()
 3109                && text.as_ref().ends_with(':')
 3110            {
 3111                if let Some(possible_emoji_short_code) =
 3112                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3113                {
 3114                    if !possible_emoji_short_code.is_empty() {
 3115                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3116                            let emoji_shortcode_start = Point::new(
 3117                                selection.start.row,
 3118                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3119                            );
 3120
 3121                            // Remove shortcode from buffer
 3122                            edits.push((
 3123                                emoji_shortcode_start..selection.start,
 3124                                "".to_string().into(),
 3125                            ));
 3126                            new_selections.push((
 3127                                Selection {
 3128                                    id: selection.id,
 3129                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3130                                    end: snapshot.anchor_before(selection.start),
 3131                                    reversed: selection.reversed,
 3132                                    goal: selection.goal,
 3133                                },
 3134                                0,
 3135                            ));
 3136
 3137                            // Insert emoji
 3138                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3139                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3140                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3141
 3142                            continue;
 3143                        }
 3144                    }
 3145                }
 3146            }
 3147
 3148            // If not handling any auto-close operation, then just replace the selected
 3149            // text with the given input and move the selection to the end of the
 3150            // newly inserted text.
 3151            let anchor = snapshot.anchor_after(selection.end);
 3152            if !self.linked_edit_ranges.is_empty() {
 3153                let start_anchor = snapshot.anchor_before(selection.start);
 3154
 3155                let is_word_char = text.chars().next().map_or(true, |char| {
 3156                    let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
 3157                    let kind = char_kind(&scope, char);
 3158
 3159                    kind == CharKind::Word
 3160                });
 3161
 3162                if is_word_char {
 3163                    if let Some(ranges) = self
 3164                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3165                    {
 3166                        for (buffer, edits) in ranges {
 3167                            linked_edits
 3168                                .entry(buffer.clone())
 3169                                .or_default()
 3170                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3171                        }
 3172                    }
 3173                }
 3174            }
 3175
 3176            new_selections.push((selection.map(|_| anchor), 0));
 3177            edits.push((selection.start..selection.end, text.clone()));
 3178        }
 3179
 3180        drop(snapshot);
 3181
 3182        self.transact(cx, |this, cx| {
 3183            this.buffer.update(cx, |buffer, cx| {
 3184                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3185            });
 3186            for (buffer, edits) in linked_edits {
 3187                buffer.update(cx, |buffer, cx| {
 3188                    let snapshot = buffer.snapshot();
 3189                    let edits = edits
 3190                        .into_iter()
 3191                        .map(|(range, text)| {
 3192                            use text::ToPoint as TP;
 3193                            let end_point = TP::to_point(&range.end, &snapshot);
 3194                            let start_point = TP::to_point(&range.start, &snapshot);
 3195                            (start_point..end_point, text)
 3196                        })
 3197                        .sorted_by_key(|(range, _)| range.start)
 3198                        .collect::<Vec<_>>();
 3199                    buffer.edit(edits, None, cx);
 3200                })
 3201            }
 3202            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3203            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3204            let snapshot = this.buffer.read(cx).read(cx);
 3205            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3206                .zip(new_selection_deltas)
 3207                .map(|(selection, delta)| Selection {
 3208                    id: selection.id,
 3209                    start: selection.start + delta,
 3210                    end: selection.end + delta,
 3211                    reversed: selection.reversed,
 3212                    goal: SelectionGoal::None,
 3213                })
 3214                .collect::<Vec<_>>();
 3215
 3216            let mut i = 0;
 3217            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3218                let position = position.to_offset(&snapshot) + delta;
 3219                let start = snapshot.anchor_before(position);
 3220                let end = snapshot.anchor_after(position);
 3221                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3222                    match existing_state.range.start.cmp(&start, &snapshot) {
 3223                        Ordering::Less => i += 1,
 3224                        Ordering::Greater => break,
 3225                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3226                            Ordering::Less => i += 1,
 3227                            Ordering::Equal => break,
 3228                            Ordering::Greater => break,
 3229                        },
 3230                    }
 3231                }
 3232                this.autoclose_regions.insert(
 3233                    i,
 3234                    AutocloseRegion {
 3235                        selection_id,
 3236                        range: start..end,
 3237                        pair,
 3238                    },
 3239                );
 3240            }
 3241
 3242            drop(snapshot);
 3243            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3244            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3245                s.select(new_selections)
 3246            });
 3247
 3248            if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
 3249                if let Some(on_type_format_task) =
 3250                    this.trigger_on_type_formatting(text.to_string(), cx)
 3251                {
 3252                    on_type_format_task.detach_and_log_err(cx);
 3253                }
 3254            }
 3255
 3256            let editor_settings = EditorSettings::get_global(cx);
 3257            if bracket_inserted
 3258                && (editor_settings.auto_signature_help
 3259                    || editor_settings.show_signature_help_after_edits)
 3260            {
 3261                this.show_signature_help(&ShowSignatureHelp, cx);
 3262            }
 3263
 3264            let trigger_in_words = !had_active_inline_completion;
 3265            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3266            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3267            this.refresh_inline_completion(true, cx);
 3268        });
 3269    }
 3270
 3271    fn find_possible_emoji_shortcode_at_position(
 3272        snapshot: &MultiBufferSnapshot,
 3273        position: Point,
 3274    ) -> Option<String> {
 3275        let mut chars = Vec::new();
 3276        let mut found_colon = false;
 3277        for char in snapshot.reversed_chars_at(position).take(100) {
 3278            // Found a possible emoji shortcode in the middle of the buffer
 3279            if found_colon {
 3280                if char.is_whitespace() {
 3281                    chars.reverse();
 3282                    return Some(chars.iter().collect());
 3283                }
 3284                // If the previous character is not a whitespace, we are in the middle of a word
 3285                // and we only want to complete the shortcode if the word is made up of other emojis
 3286                let mut containing_word = String::new();
 3287                for ch in snapshot
 3288                    .reversed_chars_at(position)
 3289                    .skip(chars.len() + 1)
 3290                    .take(100)
 3291                {
 3292                    if ch.is_whitespace() {
 3293                        break;
 3294                    }
 3295                    containing_word.push(ch);
 3296                }
 3297                let containing_word = containing_word.chars().rev().collect::<String>();
 3298                if util::word_consists_of_emojis(containing_word.as_str()) {
 3299                    chars.reverse();
 3300                    return Some(chars.iter().collect());
 3301                }
 3302            }
 3303
 3304            if char.is_whitespace() || !char.is_ascii() {
 3305                return None;
 3306            }
 3307            if char == ':' {
 3308                found_colon = true;
 3309            } else {
 3310                chars.push(char);
 3311            }
 3312        }
 3313        // Found a possible emoji shortcode at the beginning of the buffer
 3314        chars.reverse();
 3315        Some(chars.iter().collect())
 3316    }
 3317
 3318    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3319        self.transact(cx, |this, cx| {
 3320            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3321                let selections = this.selections.all::<usize>(cx);
 3322                let multi_buffer = this.buffer.read(cx);
 3323                let buffer = multi_buffer.snapshot(cx);
 3324                selections
 3325                    .iter()
 3326                    .map(|selection| {
 3327                        let start_point = selection.start.to_point(&buffer);
 3328                        let mut indent =
 3329                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3330                        indent.len = cmp::min(indent.len, start_point.column);
 3331                        let start = selection.start;
 3332                        let end = selection.end;
 3333                        let selection_is_empty = start == end;
 3334                        let language_scope = buffer.language_scope_at(start);
 3335                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3336                            &language_scope
 3337                        {
 3338                            let leading_whitespace_len = buffer
 3339                                .reversed_chars_at(start)
 3340                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3341                                .map(|c| c.len_utf8())
 3342                                .sum::<usize>();
 3343
 3344                            let trailing_whitespace_len = buffer
 3345                                .chars_at(end)
 3346                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3347                                .map(|c| c.len_utf8())
 3348                                .sum::<usize>();
 3349
 3350                            let insert_extra_newline =
 3351                                language.brackets().any(|(pair, enabled)| {
 3352                                    let pair_start = pair.start.trim_end();
 3353                                    let pair_end = pair.end.trim_start();
 3354
 3355                                    enabled
 3356                                        && pair.newline
 3357                                        && buffer.contains_str_at(
 3358                                            end + trailing_whitespace_len,
 3359                                            pair_end,
 3360                                        )
 3361                                        && buffer.contains_str_at(
 3362                                            (start - leading_whitespace_len)
 3363                                                .saturating_sub(pair_start.len()),
 3364                                            pair_start,
 3365                                        )
 3366                                });
 3367
 3368                            // Comment extension on newline is allowed only for cursor selections
 3369                            let comment_delimiter = maybe!({
 3370                                if !selection_is_empty {
 3371                                    return None;
 3372                                }
 3373
 3374                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3375                                    return None;
 3376                                }
 3377
 3378                                let delimiters = language.line_comment_prefixes();
 3379                                let max_len_of_delimiter =
 3380                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3381                                let (snapshot, range) =
 3382                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3383
 3384                                let mut index_of_first_non_whitespace = 0;
 3385                                let comment_candidate = snapshot
 3386                                    .chars_for_range(range)
 3387                                    .skip_while(|c| {
 3388                                        let should_skip = c.is_whitespace();
 3389                                        if should_skip {
 3390                                            index_of_first_non_whitespace += 1;
 3391                                        }
 3392                                        should_skip
 3393                                    })
 3394                                    .take(max_len_of_delimiter)
 3395                                    .collect::<String>();
 3396                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3397                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3398                                })?;
 3399                                let cursor_is_placed_after_comment_marker =
 3400                                    index_of_first_non_whitespace + comment_prefix.len()
 3401                                        <= start_point.column as usize;
 3402                                if cursor_is_placed_after_comment_marker {
 3403                                    Some(comment_prefix.clone())
 3404                                } else {
 3405                                    None
 3406                                }
 3407                            });
 3408                            (comment_delimiter, insert_extra_newline)
 3409                        } else {
 3410                            (None, false)
 3411                        };
 3412
 3413                        let capacity_for_delimiter = comment_delimiter
 3414                            .as_deref()
 3415                            .map(str::len)
 3416                            .unwrap_or_default();
 3417                        let mut new_text =
 3418                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3419                        new_text.push_str("\n");
 3420                        new_text.extend(indent.chars());
 3421                        if let Some(delimiter) = &comment_delimiter {
 3422                            new_text.push_str(&delimiter);
 3423                        }
 3424                        if insert_extra_newline {
 3425                            new_text = new_text.repeat(2);
 3426                        }
 3427
 3428                        let anchor = buffer.anchor_after(end);
 3429                        let new_selection = selection.map(|_| anchor);
 3430                        (
 3431                            (start..end, new_text),
 3432                            (insert_extra_newline, new_selection),
 3433                        )
 3434                    })
 3435                    .unzip()
 3436            };
 3437
 3438            this.edit_with_autoindent(edits, cx);
 3439            let buffer = this.buffer.read(cx).snapshot(cx);
 3440            let new_selections = selection_fixup_info
 3441                .into_iter()
 3442                .map(|(extra_newline_inserted, new_selection)| {
 3443                    let mut cursor = new_selection.end.to_point(&buffer);
 3444                    if extra_newline_inserted {
 3445                        cursor.row -= 1;
 3446                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3447                    }
 3448                    new_selection.map(|_| cursor)
 3449                })
 3450                .collect();
 3451
 3452            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3453            this.refresh_inline_completion(true, cx);
 3454        });
 3455    }
 3456
 3457    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3458        let buffer = self.buffer.read(cx);
 3459        let snapshot = buffer.snapshot(cx);
 3460
 3461        let mut edits = Vec::new();
 3462        let mut rows = Vec::new();
 3463
 3464        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3465            let cursor = selection.head();
 3466            let row = cursor.row;
 3467
 3468            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3469
 3470            let newline = "\n".to_string();
 3471            edits.push((start_of_line..start_of_line, newline));
 3472
 3473            rows.push(row + rows_inserted as u32);
 3474        }
 3475
 3476        self.transact(cx, |editor, cx| {
 3477            editor.edit(edits, cx);
 3478
 3479            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3480                let mut index = 0;
 3481                s.move_cursors_with(|map, _, _| {
 3482                    let row = rows[index];
 3483                    index += 1;
 3484
 3485                    let point = Point::new(row, 0);
 3486                    let boundary = map.next_line_boundary(point).1;
 3487                    let clipped = map.clip_point(boundary, Bias::Left);
 3488
 3489                    (clipped, SelectionGoal::None)
 3490                });
 3491            });
 3492
 3493            let mut indent_edits = Vec::new();
 3494            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3495            for row in rows {
 3496                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3497                for (row, indent) in indents {
 3498                    if indent.len == 0 {
 3499                        continue;
 3500                    }
 3501
 3502                    let text = match indent.kind {
 3503                        IndentKind::Space => " ".repeat(indent.len as usize),
 3504                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3505                    };
 3506                    let point = Point::new(row.0, 0);
 3507                    indent_edits.push((point..point, text));
 3508                }
 3509            }
 3510            editor.edit(indent_edits, cx);
 3511        });
 3512    }
 3513
 3514    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3515        let buffer = self.buffer.read(cx);
 3516        let snapshot = buffer.snapshot(cx);
 3517
 3518        let mut edits = Vec::new();
 3519        let mut rows = Vec::new();
 3520        let mut rows_inserted = 0;
 3521
 3522        for selection in self.selections.all_adjusted(cx) {
 3523            let cursor = selection.head();
 3524            let row = cursor.row;
 3525
 3526            let point = Point::new(row + 1, 0);
 3527            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3528
 3529            let newline = "\n".to_string();
 3530            edits.push((start_of_line..start_of_line, newline));
 3531
 3532            rows_inserted += 1;
 3533            rows.push(row + rows_inserted);
 3534        }
 3535
 3536        self.transact(cx, |editor, cx| {
 3537            editor.edit(edits, cx);
 3538
 3539            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3540                let mut index = 0;
 3541                s.move_cursors_with(|map, _, _| {
 3542                    let row = rows[index];
 3543                    index += 1;
 3544
 3545                    let point = Point::new(row, 0);
 3546                    let boundary = map.next_line_boundary(point).1;
 3547                    let clipped = map.clip_point(boundary, Bias::Left);
 3548
 3549                    (clipped, SelectionGoal::None)
 3550                });
 3551            });
 3552
 3553            let mut indent_edits = Vec::new();
 3554            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3555            for row in rows {
 3556                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3557                for (row, indent) in indents {
 3558                    if indent.len == 0 {
 3559                        continue;
 3560                    }
 3561
 3562                    let text = match indent.kind {
 3563                        IndentKind::Space => " ".repeat(indent.len as usize),
 3564                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3565                    };
 3566                    let point = Point::new(row.0, 0);
 3567                    indent_edits.push((point..point, text));
 3568                }
 3569            }
 3570            editor.edit(indent_edits, cx);
 3571        });
 3572    }
 3573
 3574    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3575        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3576            original_indent_columns: Vec::new(),
 3577        });
 3578        self.insert_with_autoindent_mode(text, autoindent, cx);
 3579    }
 3580
 3581    fn insert_with_autoindent_mode(
 3582        &mut self,
 3583        text: &str,
 3584        autoindent_mode: Option<AutoindentMode>,
 3585        cx: &mut ViewContext<Self>,
 3586    ) {
 3587        if self.read_only(cx) {
 3588            return;
 3589        }
 3590
 3591        let text: Arc<str> = text.into();
 3592        self.transact(cx, |this, cx| {
 3593            let old_selections = this.selections.all_adjusted(cx);
 3594            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3595                let anchors = {
 3596                    let snapshot = buffer.read(cx);
 3597                    old_selections
 3598                        .iter()
 3599                        .map(|s| {
 3600                            let anchor = snapshot.anchor_after(s.head());
 3601                            s.map(|_| anchor)
 3602                        })
 3603                        .collect::<Vec<_>>()
 3604                };
 3605                buffer.edit(
 3606                    old_selections
 3607                        .iter()
 3608                        .map(|s| (s.start..s.end, text.clone())),
 3609                    autoindent_mode,
 3610                    cx,
 3611                );
 3612                anchors
 3613            });
 3614
 3615            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3616                s.select_anchors(selection_anchors);
 3617            })
 3618        });
 3619    }
 3620
 3621    fn trigger_completion_on_input(
 3622        &mut self,
 3623        text: &str,
 3624        trigger_in_words: bool,
 3625        cx: &mut ViewContext<Self>,
 3626    ) {
 3627        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3628            self.show_completions(
 3629                &ShowCompletions {
 3630                    trigger: text.chars().last(),
 3631                },
 3632                cx,
 3633            );
 3634        } else {
 3635            self.hide_context_menu(cx);
 3636        }
 3637    }
 3638
 3639    fn is_completion_trigger(
 3640        &self,
 3641        text: &str,
 3642        trigger_in_words: bool,
 3643        cx: &mut ViewContext<Self>,
 3644    ) -> bool {
 3645        let position = self.selections.newest_anchor().head();
 3646        let multibuffer = self.buffer.read(cx);
 3647        let Some(buffer) = position
 3648            .buffer_id
 3649            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3650        else {
 3651            return false;
 3652        };
 3653
 3654        if let Some(completion_provider) = &self.completion_provider {
 3655            completion_provider.is_completion_trigger(
 3656                &buffer,
 3657                position.text_anchor,
 3658                text,
 3659                trigger_in_words,
 3660                cx,
 3661            )
 3662        } else {
 3663            false
 3664        }
 3665    }
 3666
 3667    /// If any empty selections is touching the start of its innermost containing autoclose
 3668    /// region, expand it to select the brackets.
 3669    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3670        let selections = self.selections.all::<usize>(cx);
 3671        let buffer = self.buffer.read(cx).read(cx);
 3672        let new_selections = self
 3673            .selections_with_autoclose_regions(selections, &buffer)
 3674            .map(|(mut selection, region)| {
 3675                if !selection.is_empty() {
 3676                    return selection;
 3677                }
 3678
 3679                if let Some(region) = region {
 3680                    let mut range = region.range.to_offset(&buffer);
 3681                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3682                        range.start -= region.pair.start.len();
 3683                        if buffer.contains_str_at(range.start, &region.pair.start)
 3684                            && buffer.contains_str_at(range.end, &region.pair.end)
 3685                        {
 3686                            range.end += region.pair.end.len();
 3687                            selection.start = range.start;
 3688                            selection.end = range.end;
 3689
 3690                            return selection;
 3691                        }
 3692                    }
 3693                }
 3694
 3695                let always_treat_brackets_as_autoclosed = buffer
 3696                    .settings_at(selection.start, cx)
 3697                    .always_treat_brackets_as_autoclosed;
 3698
 3699                if !always_treat_brackets_as_autoclosed {
 3700                    return selection;
 3701                }
 3702
 3703                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3704                    for (pair, enabled) in scope.brackets() {
 3705                        if !enabled || !pair.close {
 3706                            continue;
 3707                        }
 3708
 3709                        if buffer.contains_str_at(selection.start, &pair.end) {
 3710                            let pair_start_len = pair.start.len();
 3711                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3712                            {
 3713                                selection.start -= pair_start_len;
 3714                                selection.end += pair.end.len();
 3715
 3716                                return selection;
 3717                            }
 3718                        }
 3719                    }
 3720                }
 3721
 3722                selection
 3723            })
 3724            .collect();
 3725
 3726        drop(buffer);
 3727        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3728    }
 3729
 3730    /// Iterate the given selections, and for each one, find the smallest surrounding
 3731    /// autoclose region. This uses the ordering of the selections and the autoclose
 3732    /// regions to avoid repeated comparisons.
 3733    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3734        &'a self,
 3735        selections: impl IntoIterator<Item = Selection<D>>,
 3736        buffer: &'a MultiBufferSnapshot,
 3737    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3738        let mut i = 0;
 3739        let mut regions = self.autoclose_regions.as_slice();
 3740        selections.into_iter().map(move |selection| {
 3741            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3742
 3743            let mut enclosing = None;
 3744            while let Some(pair_state) = regions.get(i) {
 3745                if pair_state.range.end.to_offset(buffer) < range.start {
 3746                    regions = &regions[i + 1..];
 3747                    i = 0;
 3748                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3749                    break;
 3750                } else {
 3751                    if pair_state.selection_id == selection.id {
 3752                        enclosing = Some(pair_state);
 3753                    }
 3754                    i += 1;
 3755                }
 3756            }
 3757
 3758            (selection.clone(), enclosing)
 3759        })
 3760    }
 3761
 3762    /// Remove any autoclose regions that no longer contain their selection.
 3763    fn invalidate_autoclose_regions(
 3764        &mut self,
 3765        mut selections: &[Selection<Anchor>],
 3766        buffer: &MultiBufferSnapshot,
 3767    ) {
 3768        self.autoclose_regions.retain(|state| {
 3769            let mut i = 0;
 3770            while let Some(selection) = selections.get(i) {
 3771                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3772                    selections = &selections[1..];
 3773                    continue;
 3774                }
 3775                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3776                    break;
 3777                }
 3778                if selection.id == state.selection_id {
 3779                    return true;
 3780                } else {
 3781                    i += 1;
 3782                }
 3783            }
 3784            false
 3785        });
 3786    }
 3787
 3788    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3789        let offset = position.to_offset(buffer);
 3790        let (word_range, kind) = buffer.surrounding_word(offset);
 3791        if offset > word_range.start && kind == Some(CharKind::Word) {
 3792            Some(
 3793                buffer
 3794                    .text_for_range(word_range.start..offset)
 3795                    .collect::<String>(),
 3796            )
 3797        } else {
 3798            None
 3799        }
 3800    }
 3801
 3802    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3803        self.refresh_inlay_hints(
 3804            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3805            cx,
 3806        );
 3807    }
 3808
 3809    pub fn inlay_hints_enabled(&self) -> bool {
 3810        self.inlay_hint_cache.enabled
 3811    }
 3812
 3813    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3814        if self.project.is_none() || self.mode != EditorMode::Full {
 3815            return;
 3816        }
 3817
 3818        let reason_description = reason.description();
 3819        let ignore_debounce = matches!(
 3820            reason,
 3821            InlayHintRefreshReason::SettingsChange(_)
 3822                | InlayHintRefreshReason::Toggle(_)
 3823                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3824        );
 3825        let (invalidate_cache, required_languages) = match reason {
 3826            InlayHintRefreshReason::Toggle(enabled) => {
 3827                self.inlay_hint_cache.enabled = enabled;
 3828                if enabled {
 3829                    (InvalidationStrategy::RefreshRequested, None)
 3830                } else {
 3831                    self.inlay_hint_cache.clear();
 3832                    self.splice_inlays(
 3833                        self.visible_inlay_hints(cx)
 3834                            .iter()
 3835                            .map(|inlay| inlay.id)
 3836                            .collect(),
 3837                        Vec::new(),
 3838                        cx,
 3839                    );
 3840                    return;
 3841                }
 3842            }
 3843            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3844                match self.inlay_hint_cache.update_settings(
 3845                    &self.buffer,
 3846                    new_settings,
 3847                    self.visible_inlay_hints(cx),
 3848                    cx,
 3849                ) {
 3850                    ControlFlow::Break(Some(InlaySplice {
 3851                        to_remove,
 3852                        to_insert,
 3853                    })) => {
 3854                        self.splice_inlays(to_remove, to_insert, cx);
 3855                        return;
 3856                    }
 3857                    ControlFlow::Break(None) => return,
 3858                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3859                }
 3860            }
 3861            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3862                if let Some(InlaySplice {
 3863                    to_remove,
 3864                    to_insert,
 3865                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3866                {
 3867                    self.splice_inlays(to_remove, to_insert, cx);
 3868                }
 3869                return;
 3870            }
 3871            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3872            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3873                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3874            }
 3875            InlayHintRefreshReason::RefreshRequested => {
 3876                (InvalidationStrategy::RefreshRequested, None)
 3877            }
 3878        };
 3879
 3880        if let Some(InlaySplice {
 3881            to_remove,
 3882            to_insert,
 3883        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3884            reason_description,
 3885            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3886            invalidate_cache,
 3887            ignore_debounce,
 3888            cx,
 3889        ) {
 3890            self.splice_inlays(to_remove, to_insert, cx);
 3891        }
 3892    }
 3893
 3894    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3895        self.display_map
 3896            .read(cx)
 3897            .current_inlays()
 3898            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3899            .cloned()
 3900            .collect()
 3901    }
 3902
 3903    pub fn excerpts_for_inlay_hints_query(
 3904        &self,
 3905        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3906        cx: &mut ViewContext<Editor>,
 3907    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3908        let Some(project) = self.project.as_ref() else {
 3909            return HashMap::default();
 3910        };
 3911        let project = project.read(cx);
 3912        let multi_buffer = self.buffer().read(cx);
 3913        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3914        let multi_buffer_visible_start = self
 3915            .scroll_manager
 3916            .anchor()
 3917            .anchor
 3918            .to_point(&multi_buffer_snapshot);
 3919        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3920            multi_buffer_visible_start
 3921                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3922            Bias::Left,
 3923        );
 3924        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3925        multi_buffer
 3926            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3927            .into_iter()
 3928            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3929            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3930                let buffer = buffer_handle.read(cx);
 3931                let buffer_file = project::File::from_dyn(buffer.file())?;
 3932                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3933                let worktree_entry = buffer_worktree
 3934                    .read(cx)
 3935                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3936                if worktree_entry.is_ignored {
 3937                    return None;
 3938                }
 3939
 3940                let language = buffer.language()?;
 3941                if let Some(restrict_to_languages) = restrict_to_languages {
 3942                    if !restrict_to_languages.contains(language) {
 3943                        return None;
 3944                    }
 3945                }
 3946                Some((
 3947                    excerpt_id,
 3948                    (
 3949                        buffer_handle,
 3950                        buffer.version().clone(),
 3951                        excerpt_visible_range,
 3952                    ),
 3953                ))
 3954            })
 3955            .collect()
 3956    }
 3957
 3958    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3959        TextLayoutDetails {
 3960            text_system: cx.text_system().clone(),
 3961            editor_style: self.style.clone().unwrap(),
 3962            rem_size: cx.rem_size(),
 3963            scroll_anchor: self.scroll_manager.anchor(),
 3964            visible_rows: self.visible_line_count(),
 3965            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3966        }
 3967    }
 3968
 3969    fn splice_inlays(
 3970        &self,
 3971        to_remove: Vec<InlayId>,
 3972        to_insert: Vec<Inlay>,
 3973        cx: &mut ViewContext<Self>,
 3974    ) {
 3975        self.display_map.update(cx, |display_map, cx| {
 3976            display_map.splice_inlays(to_remove, to_insert, cx);
 3977        });
 3978        cx.notify();
 3979    }
 3980
 3981    fn trigger_on_type_formatting(
 3982        &self,
 3983        input: String,
 3984        cx: &mut ViewContext<Self>,
 3985    ) -> Option<Task<Result<()>>> {
 3986        if input.len() != 1 {
 3987            return None;
 3988        }
 3989
 3990        let project = self.project.as_ref()?;
 3991        let position = self.selections.newest_anchor().head();
 3992        let (buffer, buffer_position) = self
 3993            .buffer
 3994            .read(cx)
 3995            .text_anchor_for_position(position, cx)?;
 3996
 3997        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3998        // hence we do LSP request & edit on host side only — add formats to host's history.
 3999        let push_to_lsp_host_history = true;
 4000        // If this is not the host, append its history with new edits.
 4001        let push_to_client_history = project.read(cx).is_remote();
 4002
 4003        let on_type_formatting = project.update(cx, |project, cx| {
 4004            project.on_type_format(
 4005                buffer.clone(),
 4006                buffer_position,
 4007                input,
 4008                push_to_lsp_host_history,
 4009                cx,
 4010            )
 4011        });
 4012        Some(cx.spawn(|editor, mut cx| async move {
 4013            if let Some(transaction) = on_type_formatting.await? {
 4014                if push_to_client_history {
 4015                    buffer
 4016                        .update(&mut cx, |buffer, _| {
 4017                            buffer.push_transaction(transaction, Instant::now());
 4018                        })
 4019                        .ok();
 4020                }
 4021                editor.update(&mut cx, |editor, cx| {
 4022                    editor.refresh_document_highlights(cx);
 4023                })?;
 4024            }
 4025            Ok(())
 4026        }))
 4027    }
 4028
 4029    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4030        if self.pending_rename.is_some() {
 4031            return;
 4032        }
 4033
 4034        let Some(provider) = self.completion_provider.as_ref() else {
 4035            return;
 4036        };
 4037
 4038        let position = self.selections.newest_anchor().head();
 4039        let (buffer, buffer_position) =
 4040            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4041                output
 4042            } else {
 4043                return;
 4044            };
 4045
 4046        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4047        let is_followup_invoke = {
 4048            let context_menu_state = self.context_menu.read();
 4049            matches!(
 4050                context_menu_state.deref(),
 4051                Some(ContextMenu::Completions(_))
 4052            )
 4053        };
 4054        let trigger_kind = match (options.trigger, is_followup_invoke) {
 4055            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4056            (Some(_), _) => CompletionTriggerKind::TRIGGER_CHARACTER,
 4057            _ => CompletionTriggerKind::INVOKED,
 4058        };
 4059        let completion_context = CompletionContext {
 4060            trigger_character: options.trigger.and_then(|c| {
 4061                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4062                    Some(String::from(c))
 4063                } else {
 4064                    None
 4065                }
 4066            }),
 4067            trigger_kind,
 4068        };
 4069        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4070
 4071        let id = post_inc(&mut self.next_completion_id);
 4072        let task = cx.spawn(|this, mut cx| {
 4073            async move {
 4074                this.update(&mut cx, |this, _| {
 4075                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4076                })?;
 4077                let completions = completions.await.log_err();
 4078                let menu = if let Some(completions) = completions {
 4079                    let mut menu = CompletionsMenu {
 4080                        id,
 4081                        initial_position: position,
 4082                        match_candidates: completions
 4083                            .iter()
 4084                            .enumerate()
 4085                            .map(|(id, completion)| {
 4086                                StringMatchCandidate::new(
 4087                                    id,
 4088                                    completion.label.text[completion.label.filter_range.clone()]
 4089                                        .into(),
 4090                                )
 4091                            })
 4092                            .collect(),
 4093                        buffer: buffer.clone(),
 4094                        completions: Arc::new(RwLock::new(completions.into())),
 4095                        matches: Vec::new().into(),
 4096                        selected_item: 0,
 4097                        scroll_handle: UniformListScrollHandle::new(),
 4098                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4099                            DebouncedDelay::new(),
 4100                        )),
 4101                    };
 4102                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4103                        .await;
 4104
 4105                    if menu.matches.is_empty() {
 4106                        None
 4107                    } else {
 4108                        this.update(&mut cx, |editor, cx| {
 4109                            let completions = menu.completions.clone();
 4110                            let matches = menu.matches.clone();
 4111
 4112                            let delay_ms = EditorSettings::get_global(cx)
 4113                                .completion_documentation_secondary_query_debounce;
 4114                            let delay = Duration::from_millis(delay_ms);
 4115                            editor
 4116                                .completion_documentation_pre_resolve_debounce
 4117                                .fire_new(delay, cx, |editor, cx| {
 4118                                    CompletionsMenu::pre_resolve_completion_documentation(
 4119                                        buffer,
 4120                                        completions,
 4121                                        matches,
 4122                                        editor,
 4123                                        cx,
 4124                                    )
 4125                                });
 4126                        })
 4127                        .ok();
 4128                        Some(menu)
 4129                    }
 4130                } else {
 4131                    None
 4132                };
 4133
 4134                this.update(&mut cx, |this, cx| {
 4135                    let mut context_menu = this.context_menu.write();
 4136                    match context_menu.as_ref() {
 4137                        None => {}
 4138
 4139                        Some(ContextMenu::Completions(prev_menu)) => {
 4140                            if prev_menu.id > id {
 4141                                return;
 4142                            }
 4143                        }
 4144
 4145                        _ => return,
 4146                    }
 4147
 4148                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4149                        let menu = menu.unwrap();
 4150                        *context_menu = Some(ContextMenu::Completions(menu));
 4151                        drop(context_menu);
 4152                        this.discard_inline_completion(false, cx);
 4153                        cx.notify();
 4154                    } else if this.completion_tasks.len() <= 1 {
 4155                        // If there are no more completion tasks and the last menu was
 4156                        // empty, we should hide it. If it was already hidden, we should
 4157                        // also show the copilot completion when available.
 4158                        drop(context_menu);
 4159                        if this.hide_context_menu(cx).is_none() {
 4160                            this.update_visible_inline_completion(cx);
 4161                        }
 4162                    }
 4163                })?;
 4164
 4165                Ok::<_, anyhow::Error>(())
 4166            }
 4167            .log_err()
 4168        });
 4169
 4170        self.completion_tasks.push((id, task));
 4171    }
 4172
 4173    pub fn confirm_completion(
 4174        &mut self,
 4175        action: &ConfirmCompletion,
 4176        cx: &mut ViewContext<Self>,
 4177    ) -> Option<Task<Result<()>>> {
 4178        use language::ToOffset as _;
 4179
 4180        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4181            menu
 4182        } else {
 4183            return None;
 4184        };
 4185
 4186        let mat = completions_menu
 4187            .matches
 4188            .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
 4189        let buffer_handle = completions_menu.buffer;
 4190        let completions = completions_menu.completions.read();
 4191        let completion = completions.get(mat.candidate_id)?;
 4192        cx.stop_propagation();
 4193
 4194        let snippet;
 4195        let text;
 4196
 4197        if completion.is_snippet() {
 4198            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4199            text = snippet.as_ref().unwrap().text.clone();
 4200        } else {
 4201            snippet = None;
 4202            text = completion.new_text.clone();
 4203        };
 4204        let selections = self.selections.all::<usize>(cx);
 4205        let buffer = buffer_handle.read(cx);
 4206        let old_range = completion.old_range.to_offset(buffer);
 4207        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4208
 4209        let newest_selection = self.selections.newest_anchor();
 4210        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4211            return None;
 4212        }
 4213
 4214        let lookbehind = newest_selection
 4215            .start
 4216            .text_anchor
 4217            .to_offset(buffer)
 4218            .saturating_sub(old_range.start);
 4219        let lookahead = old_range
 4220            .end
 4221            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4222        let mut common_prefix_len = old_text
 4223            .bytes()
 4224            .zip(text.bytes())
 4225            .take_while(|(a, b)| a == b)
 4226            .count();
 4227
 4228        let snapshot = self.buffer.read(cx).snapshot(cx);
 4229        let mut range_to_replace: Option<Range<isize>> = None;
 4230        let mut ranges = Vec::new();
 4231        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4232        for selection in &selections {
 4233            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4234                let start = selection.start.saturating_sub(lookbehind);
 4235                let end = selection.end + lookahead;
 4236                if selection.id == newest_selection.id {
 4237                    range_to_replace = Some(
 4238                        ((start + common_prefix_len) as isize - selection.start as isize)
 4239                            ..(end as isize - selection.start as isize),
 4240                    );
 4241                }
 4242                ranges.push(start + common_prefix_len..end);
 4243            } else {
 4244                common_prefix_len = 0;
 4245                ranges.clear();
 4246                ranges.extend(selections.iter().map(|s| {
 4247                    if s.id == newest_selection.id {
 4248                        range_to_replace = Some(
 4249                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4250                                - selection.start as isize
 4251                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4252                                    - selection.start as isize,
 4253                        );
 4254                        old_range.clone()
 4255                    } else {
 4256                        s.start..s.end
 4257                    }
 4258                }));
 4259                break;
 4260            }
 4261            if !self.linked_edit_ranges.is_empty() {
 4262                let start_anchor = snapshot.anchor_before(selection.head());
 4263                let end_anchor = snapshot.anchor_after(selection.tail());
 4264                if let Some(ranges) = self
 4265                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4266                {
 4267                    for (buffer, edits) in ranges {
 4268                        linked_edits.entry(buffer.clone()).or_default().extend(
 4269                            edits
 4270                                .into_iter()
 4271                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4272                        );
 4273                    }
 4274                }
 4275            }
 4276        }
 4277        let text = &text[common_prefix_len..];
 4278
 4279        cx.emit(EditorEvent::InputHandled {
 4280            utf16_range_to_replace: range_to_replace,
 4281            text: text.into(),
 4282        });
 4283
 4284        self.transact(cx, |this, cx| {
 4285            if let Some(mut snippet) = snippet {
 4286                snippet.text = text.to_string();
 4287                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4288                    tabstop.start -= common_prefix_len as isize;
 4289                    tabstop.end -= common_prefix_len as isize;
 4290                }
 4291
 4292                this.insert_snippet(&ranges, snippet, cx).log_err();
 4293            } else {
 4294                this.buffer.update(cx, |buffer, cx| {
 4295                    buffer.edit(
 4296                        ranges.iter().map(|range| (range.clone(), text)),
 4297                        this.autoindent_mode.clone(),
 4298                        cx,
 4299                    );
 4300                });
 4301            }
 4302            for (buffer, edits) in linked_edits {
 4303                buffer.update(cx, |buffer, cx| {
 4304                    let snapshot = buffer.snapshot();
 4305                    let edits = edits
 4306                        .into_iter()
 4307                        .map(|(range, text)| {
 4308                            use text::ToPoint as TP;
 4309                            let end_point = TP::to_point(&range.end, &snapshot);
 4310                            let start_point = TP::to_point(&range.start, &snapshot);
 4311                            (start_point..end_point, text)
 4312                        })
 4313                        .sorted_by_key(|(range, _)| range.start)
 4314                        .collect::<Vec<_>>();
 4315                    buffer.edit(edits, None, cx);
 4316                })
 4317            }
 4318
 4319            this.refresh_inline_completion(true, cx);
 4320        });
 4321
 4322        if let Some(confirm) = completion.confirm.as_ref() {
 4323            (confirm)(cx);
 4324        }
 4325
 4326        if completion.show_new_completions_on_confirm {
 4327            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4328        }
 4329
 4330        let provider = self.completion_provider.as_ref()?;
 4331        let apply_edits = provider.apply_additional_edits_for_completion(
 4332            buffer_handle,
 4333            completion.clone(),
 4334            true,
 4335            cx,
 4336        );
 4337
 4338        let editor_settings = EditorSettings::get_global(cx);
 4339        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4340            // After the code completion is finished, users often want to know what signatures are needed.
 4341            // so we should automatically call signature_help
 4342            self.show_signature_help(&ShowSignatureHelp, cx);
 4343        }
 4344
 4345        Some(cx.foreground_executor().spawn(async move {
 4346            apply_edits.await?;
 4347            Ok(())
 4348        }))
 4349    }
 4350
 4351    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4352        let mut context_menu = self.context_menu.write();
 4353        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4354            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4355                // Toggle if we're selecting the same one
 4356                *context_menu = None;
 4357                cx.notify();
 4358                return;
 4359            } else {
 4360                // Otherwise, clear it and start a new one
 4361                *context_menu = None;
 4362                cx.notify();
 4363            }
 4364        }
 4365        drop(context_menu);
 4366        let snapshot = self.snapshot(cx);
 4367        let deployed_from_indicator = action.deployed_from_indicator;
 4368        let mut task = self.code_actions_task.take();
 4369        let action = action.clone();
 4370        cx.spawn(|editor, mut cx| async move {
 4371            while let Some(prev_task) = task {
 4372                prev_task.await;
 4373                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4374            }
 4375
 4376            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4377                if editor.focus_handle.is_focused(cx) {
 4378                    let multibuffer_point = action
 4379                        .deployed_from_indicator
 4380                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4381                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4382                    let (buffer, buffer_row) = snapshot
 4383                        .buffer_snapshot
 4384                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4385                        .and_then(|(buffer_snapshot, range)| {
 4386                            editor
 4387                                .buffer
 4388                                .read(cx)
 4389                                .buffer(buffer_snapshot.remote_id())
 4390                                .map(|buffer| (buffer, range.start.row))
 4391                        })?;
 4392                    let (_, code_actions) = editor
 4393                        .available_code_actions
 4394                        .clone()
 4395                        .and_then(|(location, code_actions)| {
 4396                            let snapshot = location.buffer.read(cx).snapshot();
 4397                            let point_range = location.range.to_point(&snapshot);
 4398                            let point_range = point_range.start.row..=point_range.end.row;
 4399                            if point_range.contains(&buffer_row) {
 4400                                Some((location, code_actions))
 4401                            } else {
 4402                                None
 4403                            }
 4404                        })
 4405                        .unzip();
 4406                    let buffer_id = buffer.read(cx).remote_id();
 4407                    let tasks = editor
 4408                        .tasks
 4409                        .get(&(buffer_id, buffer_row))
 4410                        .map(|t| Arc::new(t.to_owned()));
 4411                    if tasks.is_none() && code_actions.is_none() {
 4412                        return None;
 4413                    }
 4414
 4415                    editor.completion_tasks.clear();
 4416                    editor.discard_inline_completion(false, cx);
 4417                    let task_context =
 4418                        tasks
 4419                            .as_ref()
 4420                            .zip(editor.project.clone())
 4421                            .map(|(tasks, project)| {
 4422                                let position = Point::new(buffer_row, tasks.column);
 4423                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4424                                let location = Location {
 4425                                    buffer: buffer.clone(),
 4426                                    range: range_start..range_start,
 4427                                };
 4428                                // Fill in the environmental variables from the tree-sitter captures
 4429                                let mut captured_task_variables = TaskVariables::default();
 4430                                for (capture_name, value) in tasks.extra_variables.clone() {
 4431                                    captured_task_variables.insert(
 4432                                        task::VariableName::Custom(capture_name.into()),
 4433                                        value.clone(),
 4434                                    );
 4435                                }
 4436                                project.update(cx, |project, cx| {
 4437                                    project.task_context_for_location(
 4438                                        captured_task_variables,
 4439                                        location,
 4440                                        cx,
 4441                                    )
 4442                                })
 4443                            });
 4444
 4445                    Some(cx.spawn(|editor, mut cx| async move {
 4446                        let task_context = match task_context {
 4447                            Some(task_context) => task_context.await,
 4448                            None => None,
 4449                        };
 4450                        let resolved_tasks =
 4451                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4452                                Arc::new(ResolvedTasks {
 4453                                    templates: tasks
 4454                                        .templates
 4455                                        .iter()
 4456                                        .filter_map(|(kind, template)| {
 4457                                            template
 4458                                                .resolve_task(&kind.to_id_base(), &task_context)
 4459                                                .map(|task| (kind.clone(), task))
 4460                                        })
 4461                                        .collect(),
 4462                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4463                                        multibuffer_point.row,
 4464                                        tasks.column,
 4465                                    )),
 4466                                })
 4467                            });
 4468                        let spawn_straight_away = resolved_tasks
 4469                            .as_ref()
 4470                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4471                            && code_actions
 4472                                .as_ref()
 4473                                .map_or(true, |actions| actions.is_empty());
 4474                        if let Some(task) = editor
 4475                            .update(&mut cx, |editor, cx| {
 4476                                *editor.context_menu.write() =
 4477                                    Some(ContextMenu::CodeActions(CodeActionsMenu {
 4478                                        buffer,
 4479                                        actions: CodeActionContents {
 4480                                            tasks: resolved_tasks,
 4481                                            actions: code_actions,
 4482                                        },
 4483                                        selected_item: Default::default(),
 4484                                        scroll_handle: UniformListScrollHandle::default(),
 4485                                        deployed_from_indicator,
 4486                                    }));
 4487                                if spawn_straight_away {
 4488                                    if let Some(task) = editor.confirm_code_action(
 4489                                        &ConfirmCodeAction { item_ix: Some(0) },
 4490                                        cx,
 4491                                    ) {
 4492                                        cx.notify();
 4493                                        return task;
 4494                                    }
 4495                                }
 4496                                cx.notify();
 4497                                Task::ready(Ok(()))
 4498                            })
 4499                            .ok()
 4500                        {
 4501                            task.await
 4502                        } else {
 4503                            Ok(())
 4504                        }
 4505                    }))
 4506                } else {
 4507                    Some(Task::ready(Ok(())))
 4508                }
 4509            })?;
 4510            if let Some(task) = spawned_test_task {
 4511                task.await?;
 4512            }
 4513
 4514            Ok::<_, anyhow::Error>(())
 4515        })
 4516        .detach_and_log_err(cx);
 4517    }
 4518
 4519    pub fn confirm_code_action(
 4520        &mut self,
 4521        action: &ConfirmCodeAction,
 4522        cx: &mut ViewContext<Self>,
 4523    ) -> Option<Task<Result<()>>> {
 4524        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4525            menu
 4526        } else {
 4527            return None;
 4528        };
 4529        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4530        let action = actions_menu.actions.get(action_ix)?;
 4531        let title = action.label();
 4532        let buffer = actions_menu.buffer;
 4533        let workspace = self.workspace()?;
 4534
 4535        match action {
 4536            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4537                workspace.update(cx, |workspace, cx| {
 4538                    workspace::tasks::schedule_resolved_task(
 4539                        workspace,
 4540                        task_source_kind,
 4541                        resolved_task,
 4542                        false,
 4543                        cx,
 4544                    );
 4545
 4546                    Some(Task::ready(Ok(())))
 4547                })
 4548            }
 4549            CodeActionsItem::CodeAction(action) => {
 4550                let apply_code_actions = workspace
 4551                    .read(cx)
 4552                    .project()
 4553                    .clone()
 4554                    .update(cx, |project, cx| {
 4555                        project.apply_code_action(buffer, action, true, cx)
 4556                    });
 4557                let workspace = workspace.downgrade();
 4558                Some(cx.spawn(|editor, cx| async move {
 4559                    let project_transaction = apply_code_actions.await?;
 4560                    Self::open_project_transaction(
 4561                        &editor,
 4562                        workspace,
 4563                        project_transaction,
 4564                        title,
 4565                        cx,
 4566                    )
 4567                    .await
 4568                }))
 4569            }
 4570        }
 4571    }
 4572
 4573    pub async fn open_project_transaction(
 4574        this: &WeakView<Editor>,
 4575        workspace: WeakView<Workspace>,
 4576        transaction: ProjectTransaction,
 4577        title: String,
 4578        mut cx: AsyncWindowContext,
 4579    ) -> Result<()> {
 4580        let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
 4581
 4582        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4583        cx.update(|cx| {
 4584            entries.sort_unstable_by_key(|(buffer, _)| {
 4585                buffer.read(cx).file().map(|f| f.path().clone())
 4586            });
 4587        })?;
 4588
 4589        // If the project transaction's edits are all contained within this editor, then
 4590        // avoid opening a new editor to display them.
 4591
 4592        if let Some((buffer, transaction)) = entries.first() {
 4593            if entries.len() == 1 {
 4594                let excerpt = this.update(&mut cx, |editor, cx| {
 4595                    editor
 4596                        .buffer()
 4597                        .read(cx)
 4598                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4599                })?;
 4600                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4601                    if excerpted_buffer == *buffer {
 4602                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4603                            let excerpt_range = excerpt_range.to_offset(buffer);
 4604                            buffer
 4605                                .edited_ranges_for_transaction::<usize>(transaction)
 4606                                .all(|range| {
 4607                                    excerpt_range.start <= range.start
 4608                                        && excerpt_range.end >= range.end
 4609                                })
 4610                        })?;
 4611
 4612                        if all_edits_within_excerpt {
 4613                            return Ok(());
 4614                        }
 4615                    }
 4616                }
 4617            }
 4618        } else {
 4619            return Ok(());
 4620        }
 4621
 4622        let mut ranges_to_highlight = Vec::new();
 4623        let excerpt_buffer = cx.new_model(|cx| {
 4624            let mut multibuffer =
 4625                MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
 4626            for (buffer_handle, transaction) in &entries {
 4627                let buffer = buffer_handle.read(cx);
 4628                ranges_to_highlight.extend(
 4629                    multibuffer.push_excerpts_with_context_lines(
 4630                        buffer_handle.clone(),
 4631                        buffer
 4632                            .edited_ranges_for_transaction::<usize>(transaction)
 4633                            .collect(),
 4634                        DEFAULT_MULTIBUFFER_CONTEXT,
 4635                        cx,
 4636                    ),
 4637                );
 4638            }
 4639            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4640            multibuffer
 4641        })?;
 4642
 4643        workspace.update(&mut cx, |workspace, cx| {
 4644            let project = workspace.project().clone();
 4645            let editor =
 4646                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4647            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, cx);
 4648            editor.update(cx, |editor, cx| {
 4649                editor.highlight_background::<Self>(
 4650                    &ranges_to_highlight,
 4651                    |theme| theme.editor_highlighted_line_background,
 4652                    cx,
 4653                );
 4654            });
 4655        })?;
 4656
 4657        Ok(())
 4658    }
 4659
 4660    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4661        let project = self.project.clone()?;
 4662        let buffer = self.buffer.read(cx);
 4663        let newest_selection = self.selections.newest_anchor().clone();
 4664        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4665        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4666        if start_buffer != end_buffer {
 4667            return None;
 4668        }
 4669
 4670        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4671            cx.background_executor()
 4672                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4673                .await;
 4674
 4675            let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
 4676                project.code_actions(&start_buffer, start..end, cx)
 4677            }) {
 4678                code_actions.await
 4679            } else {
 4680                Vec::new()
 4681            };
 4682
 4683            this.update(&mut cx, |this, cx| {
 4684                this.available_code_actions = if actions.is_empty() {
 4685                    None
 4686                } else {
 4687                    Some((
 4688                        Location {
 4689                            buffer: start_buffer,
 4690                            range: start..end,
 4691                        },
 4692                        actions.into(),
 4693                    ))
 4694                };
 4695                cx.notify();
 4696            })
 4697            .log_err();
 4698        }));
 4699        None
 4700    }
 4701
 4702    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4703        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4704            self.show_git_blame_inline = false;
 4705
 4706            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4707                cx.background_executor().timer(delay).await;
 4708
 4709                this.update(&mut cx, |this, cx| {
 4710                    this.show_git_blame_inline = true;
 4711                    cx.notify();
 4712                })
 4713                .log_err();
 4714            }));
 4715        }
 4716    }
 4717
 4718    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4719        if self.pending_rename.is_some() {
 4720            return None;
 4721        }
 4722
 4723        let project = self.project.clone()?;
 4724        let buffer = self.buffer.read(cx);
 4725        let newest_selection = self.selections.newest_anchor().clone();
 4726        let cursor_position = newest_selection.head();
 4727        let (cursor_buffer, cursor_buffer_position) =
 4728            buffer.text_anchor_for_position(cursor_position, cx)?;
 4729        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4730        if cursor_buffer != tail_buffer {
 4731            return None;
 4732        }
 4733
 4734        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4735            cx.background_executor()
 4736                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 4737                .await;
 4738
 4739            let highlights = if let Some(highlights) = project
 4740                .update(&mut cx, |project, cx| {
 4741                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4742                })
 4743                .log_err()
 4744            {
 4745                highlights.await.log_err()
 4746            } else {
 4747                None
 4748            };
 4749
 4750            if let Some(highlights) = highlights {
 4751                this.update(&mut cx, |this, cx| {
 4752                    if this.pending_rename.is_some() {
 4753                        return;
 4754                    }
 4755
 4756                    let buffer_id = cursor_position.buffer_id;
 4757                    let buffer = this.buffer.read(cx);
 4758                    if !buffer
 4759                        .text_anchor_for_position(cursor_position, cx)
 4760                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4761                    {
 4762                        return;
 4763                    }
 4764
 4765                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4766                    let mut write_ranges = Vec::new();
 4767                    let mut read_ranges = Vec::new();
 4768                    for highlight in highlights {
 4769                        for (excerpt_id, excerpt_range) in
 4770                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4771                        {
 4772                            let start = highlight
 4773                                .range
 4774                                .start
 4775                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4776                            let end = highlight
 4777                                .range
 4778                                .end
 4779                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4780                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4781                                continue;
 4782                            }
 4783
 4784                            let range = Anchor {
 4785                                buffer_id,
 4786                                excerpt_id: excerpt_id,
 4787                                text_anchor: start,
 4788                            }..Anchor {
 4789                                buffer_id,
 4790                                excerpt_id,
 4791                                text_anchor: end,
 4792                            };
 4793                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4794                                write_ranges.push(range);
 4795                            } else {
 4796                                read_ranges.push(range);
 4797                            }
 4798                        }
 4799                    }
 4800
 4801                    this.highlight_background::<DocumentHighlightRead>(
 4802                        &read_ranges,
 4803                        |theme| theme.editor_document_highlight_read_background,
 4804                        cx,
 4805                    );
 4806                    this.highlight_background::<DocumentHighlightWrite>(
 4807                        &write_ranges,
 4808                        |theme| theme.editor_document_highlight_write_background,
 4809                        cx,
 4810                    );
 4811                    cx.notify();
 4812                })
 4813                .log_err();
 4814            }
 4815        }));
 4816        None
 4817    }
 4818
 4819    fn refresh_inline_completion(
 4820        &mut self,
 4821        debounce: bool,
 4822        cx: &mut ViewContext<Self>,
 4823    ) -> Option<()> {
 4824        let provider = self.inline_completion_provider()?;
 4825        let cursor = self.selections.newest_anchor().head();
 4826        let (buffer, cursor_buffer_position) =
 4827            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4828        if !self.show_inline_completions
 4829            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4830        {
 4831            self.discard_inline_completion(false, cx);
 4832            return None;
 4833        }
 4834
 4835        self.update_visible_inline_completion(cx);
 4836        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4837        Some(())
 4838    }
 4839
 4840    fn cycle_inline_completion(
 4841        &mut self,
 4842        direction: Direction,
 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            return None;
 4853        }
 4854
 4855        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4856        self.update_visible_inline_completion(cx);
 4857
 4858        Some(())
 4859    }
 4860
 4861    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4862        if !self.has_active_inline_completion(cx) {
 4863            self.refresh_inline_completion(false, cx);
 4864            return;
 4865        }
 4866
 4867        self.update_visible_inline_completion(cx);
 4868    }
 4869
 4870    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4871        self.show_cursor_names(cx);
 4872    }
 4873
 4874    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4875        self.show_cursor_names = true;
 4876        cx.notify();
 4877        cx.spawn(|this, mut cx| async move {
 4878            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4879            this.update(&mut cx, |this, cx| {
 4880                this.show_cursor_names = false;
 4881                cx.notify()
 4882            })
 4883            .ok()
 4884        })
 4885        .detach();
 4886    }
 4887
 4888    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4889        if self.has_active_inline_completion(cx) {
 4890            self.cycle_inline_completion(Direction::Next, cx);
 4891        } else {
 4892            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4893            if is_copilot_disabled {
 4894                cx.propagate();
 4895            }
 4896        }
 4897    }
 4898
 4899    pub fn previous_inline_completion(
 4900        &mut self,
 4901        _: &PreviousInlineCompletion,
 4902        cx: &mut ViewContext<Self>,
 4903    ) {
 4904        if self.has_active_inline_completion(cx) {
 4905            self.cycle_inline_completion(Direction::Prev, cx);
 4906        } else {
 4907            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4908            if is_copilot_disabled {
 4909                cx.propagate();
 4910            }
 4911        }
 4912    }
 4913
 4914    pub fn accept_inline_completion(
 4915        &mut self,
 4916        _: &AcceptInlineCompletion,
 4917        cx: &mut ViewContext<Self>,
 4918    ) {
 4919        let Some(completion) = self.take_active_inline_completion(cx) else {
 4920            return;
 4921        };
 4922        if let Some(provider) = self.inline_completion_provider() {
 4923            provider.accept(cx);
 4924        }
 4925
 4926        cx.emit(EditorEvent::InputHandled {
 4927            utf16_range_to_replace: None,
 4928            text: completion.text.to_string().into(),
 4929        });
 4930        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 4931        self.refresh_inline_completion(true, cx);
 4932        cx.notify();
 4933    }
 4934
 4935    pub fn accept_partial_inline_completion(
 4936        &mut self,
 4937        _: &AcceptPartialInlineCompletion,
 4938        cx: &mut ViewContext<Self>,
 4939    ) {
 4940        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 4941            if let Some(completion) = self.take_active_inline_completion(cx) {
 4942                let mut partial_completion = completion
 4943                    .text
 4944                    .chars()
 4945                    .by_ref()
 4946                    .take_while(|c| c.is_alphabetic())
 4947                    .collect::<String>();
 4948                if partial_completion.is_empty() {
 4949                    partial_completion = completion
 4950                        .text
 4951                        .chars()
 4952                        .by_ref()
 4953                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4954                        .collect::<String>();
 4955                }
 4956
 4957                cx.emit(EditorEvent::InputHandled {
 4958                    utf16_range_to_replace: None,
 4959                    text: partial_completion.clone().into(),
 4960                });
 4961                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4962                self.refresh_inline_completion(true, cx);
 4963                cx.notify();
 4964            }
 4965        }
 4966    }
 4967
 4968    fn discard_inline_completion(
 4969        &mut self,
 4970        should_report_inline_completion_event: bool,
 4971        cx: &mut ViewContext<Self>,
 4972    ) -> bool {
 4973        if let Some(provider) = self.inline_completion_provider() {
 4974            provider.discard(should_report_inline_completion_event, cx);
 4975        }
 4976
 4977        self.take_active_inline_completion(cx).is_some()
 4978    }
 4979
 4980    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 4981        if let Some(completion) = self.active_inline_completion.as_ref() {
 4982            let buffer = self.buffer.read(cx).read(cx);
 4983            completion.position.is_valid(&buffer)
 4984        } else {
 4985            false
 4986        }
 4987    }
 4988
 4989    fn take_active_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
 4990        let completion = self.active_inline_completion.take()?;
 4991        self.display_map.update(cx, |map, cx| {
 4992            map.splice_inlays(vec![completion.id], Default::default(), cx);
 4993        });
 4994        let buffer = self.buffer.read(cx).read(cx);
 4995
 4996        if completion.position.is_valid(&buffer) {
 4997            Some(completion)
 4998        } else {
 4999            None
 5000        }
 5001    }
 5002
 5003    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5004        let selection = self.selections.newest_anchor();
 5005        let cursor = selection.head();
 5006
 5007        if self.context_menu.read().is_none()
 5008            && self.completion_tasks.is_empty()
 5009            && selection.start == selection.end
 5010        {
 5011            if let Some(provider) = self.inline_completion_provider() {
 5012                if let Some((buffer, cursor_buffer_position)) =
 5013                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5014                {
 5015                    if let Some(text) =
 5016                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5017                    {
 5018                        let text = Rope::from(text);
 5019                        let mut to_remove = Vec::new();
 5020                        if let Some(completion) = self.active_inline_completion.take() {
 5021                            to_remove.push(completion.id);
 5022                        }
 5023
 5024                        let completion_inlay =
 5025                            Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
 5026                        self.active_inline_completion = Some(completion_inlay.clone());
 5027                        self.display_map.update(cx, move |map, cx| {
 5028                            map.splice_inlays(to_remove, vec![completion_inlay], cx)
 5029                        });
 5030                        cx.notify();
 5031                        return;
 5032                    }
 5033                }
 5034            }
 5035        }
 5036
 5037        self.discard_inline_completion(false, cx);
 5038    }
 5039
 5040    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5041        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5042    }
 5043
 5044    fn render_code_actions_indicator(
 5045        &self,
 5046        _style: &EditorStyle,
 5047        row: DisplayRow,
 5048        is_active: bool,
 5049        cx: &mut ViewContext<Self>,
 5050    ) -> Option<IconButton> {
 5051        if self.available_code_actions.is_some() {
 5052            Some(
 5053                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5054                    .shape(ui::IconButtonShape::Square)
 5055                    .icon_size(IconSize::XSmall)
 5056                    .icon_color(Color::Muted)
 5057                    .selected(is_active)
 5058                    .on_click(cx.listener(move |editor, _e, cx| {
 5059                        editor.focus(cx);
 5060                        editor.toggle_code_actions(
 5061                            &ToggleCodeActions {
 5062                                deployed_from_indicator: Some(row),
 5063                            },
 5064                            cx,
 5065                        );
 5066                    })),
 5067            )
 5068        } else {
 5069            None
 5070        }
 5071    }
 5072
 5073    fn clear_tasks(&mut self) {
 5074        self.tasks.clear()
 5075    }
 5076
 5077    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5078        if let Some(_) = self.tasks.insert(key, value) {
 5079            // This case should hopefully be rare, but just in case...
 5080            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5081        }
 5082    }
 5083
 5084    fn render_run_indicator(
 5085        &self,
 5086        _style: &EditorStyle,
 5087        is_active: bool,
 5088        row: DisplayRow,
 5089        cx: &mut ViewContext<Self>,
 5090    ) -> IconButton {
 5091        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5092            .shape(ui::IconButtonShape::Square)
 5093            .icon_size(IconSize::XSmall)
 5094            .icon_color(Color::Muted)
 5095            .selected(is_active)
 5096            .on_click(cx.listener(move |editor, _e, cx| {
 5097                editor.focus(cx);
 5098                editor.toggle_code_actions(
 5099                    &ToggleCodeActions {
 5100                        deployed_from_indicator: Some(row),
 5101                    },
 5102                    cx,
 5103                );
 5104            }))
 5105    }
 5106
 5107    pub fn context_menu_visible(&self) -> bool {
 5108        self.context_menu
 5109            .read()
 5110            .as_ref()
 5111            .map_or(false, |menu| menu.visible())
 5112    }
 5113
 5114    fn render_context_menu(
 5115        &self,
 5116        cursor_position: DisplayPoint,
 5117        style: &EditorStyle,
 5118        max_height: Pixels,
 5119        cx: &mut ViewContext<Editor>,
 5120    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5121        self.context_menu.read().as_ref().map(|menu| {
 5122            menu.render(
 5123                cursor_position,
 5124                style,
 5125                max_height,
 5126                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5127                cx,
 5128            )
 5129        })
 5130    }
 5131
 5132    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5133        cx.notify();
 5134        self.completion_tasks.clear();
 5135        let context_menu = self.context_menu.write().take();
 5136        if context_menu.is_some() {
 5137            self.update_visible_inline_completion(cx);
 5138        }
 5139        context_menu
 5140    }
 5141
 5142    pub fn insert_snippet(
 5143        &mut self,
 5144        insertion_ranges: &[Range<usize>],
 5145        snippet: Snippet,
 5146        cx: &mut ViewContext<Self>,
 5147    ) -> Result<()> {
 5148        struct Tabstop<T> {
 5149            is_end_tabstop: bool,
 5150            ranges: Vec<Range<T>>,
 5151        }
 5152
 5153        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5154            let snippet_text: Arc<str> = snippet.text.clone().into();
 5155            buffer.edit(
 5156                insertion_ranges
 5157                    .iter()
 5158                    .cloned()
 5159                    .map(|range| (range, snippet_text.clone())),
 5160                Some(AutoindentMode::EachLine),
 5161                cx,
 5162            );
 5163
 5164            let snapshot = &*buffer.read(cx);
 5165            let snippet = &snippet;
 5166            snippet
 5167                .tabstops
 5168                .iter()
 5169                .map(|tabstop| {
 5170                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5171                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5172                    });
 5173                    let mut tabstop_ranges = tabstop
 5174                        .iter()
 5175                        .flat_map(|tabstop_range| {
 5176                            let mut delta = 0_isize;
 5177                            insertion_ranges.iter().map(move |insertion_range| {
 5178                                let insertion_start = insertion_range.start as isize + delta;
 5179                                delta +=
 5180                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5181
 5182                                let start = ((insertion_start + tabstop_range.start) as usize)
 5183                                    .min(snapshot.len());
 5184                                let end = ((insertion_start + tabstop_range.end) as usize)
 5185                                    .min(snapshot.len());
 5186                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5187                            })
 5188                        })
 5189                        .collect::<Vec<_>>();
 5190                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5191
 5192                    Tabstop {
 5193                        is_end_tabstop,
 5194                        ranges: tabstop_ranges,
 5195                    }
 5196                })
 5197                .collect::<Vec<_>>()
 5198        });
 5199        if let Some(tabstop) = tabstops.first() {
 5200            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5201                s.select_ranges(tabstop.ranges.iter().cloned());
 5202            });
 5203
 5204            // If we're already at the last tabstop and it's at the end of the snippet,
 5205            // we're done, we don't need to keep the state around.
 5206            if !tabstop.is_end_tabstop {
 5207                let ranges = tabstops
 5208                    .into_iter()
 5209                    .map(|tabstop| tabstop.ranges)
 5210                    .collect::<Vec<_>>();
 5211                self.snippet_stack.push(SnippetState {
 5212                    active_index: 0,
 5213                    ranges,
 5214                });
 5215            }
 5216
 5217            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5218            if self.autoclose_regions.is_empty() {
 5219                let snapshot = self.buffer.read(cx).snapshot(cx);
 5220                for selection in &mut self.selections.all::<Point>(cx) {
 5221                    let selection_head = selection.head();
 5222                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5223                        continue;
 5224                    };
 5225
 5226                    let mut bracket_pair = None;
 5227                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5228                    let prev_chars = snapshot
 5229                        .reversed_chars_at(selection_head)
 5230                        .collect::<String>();
 5231                    for (pair, enabled) in scope.brackets() {
 5232                        if enabled
 5233                            && pair.close
 5234                            && prev_chars.starts_with(pair.start.as_str())
 5235                            && next_chars.starts_with(pair.end.as_str())
 5236                        {
 5237                            bracket_pair = Some(pair.clone());
 5238                            break;
 5239                        }
 5240                    }
 5241                    if let Some(pair) = bracket_pair {
 5242                        let start = snapshot.anchor_after(selection_head);
 5243                        let end = snapshot.anchor_after(selection_head);
 5244                        self.autoclose_regions.push(AutocloseRegion {
 5245                            selection_id: selection.id,
 5246                            range: start..end,
 5247                            pair,
 5248                        });
 5249                    }
 5250                }
 5251            }
 5252        }
 5253        Ok(())
 5254    }
 5255
 5256    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5257        self.move_to_snippet_tabstop(Bias::Right, cx)
 5258    }
 5259
 5260    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5261        self.move_to_snippet_tabstop(Bias::Left, cx)
 5262    }
 5263
 5264    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5265        if let Some(mut snippet) = self.snippet_stack.pop() {
 5266            match bias {
 5267                Bias::Left => {
 5268                    if snippet.active_index > 0 {
 5269                        snippet.active_index -= 1;
 5270                    } else {
 5271                        self.snippet_stack.push(snippet);
 5272                        return false;
 5273                    }
 5274                }
 5275                Bias::Right => {
 5276                    if snippet.active_index + 1 < snippet.ranges.len() {
 5277                        snippet.active_index += 1;
 5278                    } else {
 5279                        self.snippet_stack.push(snippet);
 5280                        return false;
 5281                    }
 5282                }
 5283            }
 5284            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5285                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5286                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5287                });
 5288                // If snippet state is not at the last tabstop, push it back on the stack
 5289                if snippet.active_index + 1 < snippet.ranges.len() {
 5290                    self.snippet_stack.push(snippet);
 5291                }
 5292                return true;
 5293            }
 5294        }
 5295
 5296        false
 5297    }
 5298
 5299    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5300        self.transact(cx, |this, cx| {
 5301            this.select_all(&SelectAll, cx);
 5302            this.insert("", cx);
 5303        });
 5304    }
 5305
 5306    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5307        self.transact(cx, |this, cx| {
 5308            this.select_autoclose_pair(cx);
 5309            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5310            if !this.linked_edit_ranges.is_empty() {
 5311                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5312                let snapshot = this.buffer.read(cx).snapshot(cx);
 5313
 5314                for selection in selections.iter() {
 5315                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5316                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5317                    if selection_start.buffer_id != selection_end.buffer_id {
 5318                        continue;
 5319                    }
 5320                    if let Some(ranges) =
 5321                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5322                    {
 5323                        for (buffer, entries) in ranges {
 5324                            linked_ranges.entry(buffer).or_default().extend(entries);
 5325                        }
 5326                    }
 5327                }
 5328            }
 5329
 5330            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5331            if !this.selections.line_mode {
 5332                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5333                for selection in &mut selections {
 5334                    if selection.is_empty() {
 5335                        let old_head = selection.head();
 5336                        let mut new_head =
 5337                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5338                                .to_point(&display_map);
 5339                        if let Some((buffer, line_buffer_range)) = display_map
 5340                            .buffer_snapshot
 5341                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5342                        {
 5343                            let indent_size =
 5344                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5345                            let indent_len = match indent_size.kind {
 5346                                IndentKind::Space => {
 5347                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5348                                }
 5349                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5350                            };
 5351                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5352                                let indent_len = indent_len.get();
 5353                                new_head = cmp::min(
 5354                                    new_head,
 5355                                    MultiBufferPoint::new(
 5356                                        old_head.row,
 5357                                        ((old_head.column - 1) / indent_len) * indent_len,
 5358                                    ),
 5359                                );
 5360                            }
 5361                        }
 5362
 5363                        selection.set_head(new_head, SelectionGoal::None);
 5364                    }
 5365                }
 5366            }
 5367
 5368            this.signature_help_state.set_backspace_pressed(true);
 5369            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5370            this.insert("", cx);
 5371            let empty_str: Arc<str> = Arc::from("");
 5372            for (buffer, edits) in linked_ranges {
 5373                let snapshot = buffer.read(cx).snapshot();
 5374                use text::ToPoint as TP;
 5375
 5376                let edits = edits
 5377                    .into_iter()
 5378                    .map(|range| {
 5379                        let end_point = TP::to_point(&range.end, &snapshot);
 5380                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5381
 5382                        if end_point == start_point {
 5383                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5384                                .saturating_sub(1);
 5385                            start_point = TP::to_point(&offset, &snapshot);
 5386                        };
 5387
 5388                        (start_point..end_point, empty_str.clone())
 5389                    })
 5390                    .sorted_by_key(|(range, _)| range.start)
 5391                    .collect::<Vec<_>>();
 5392                buffer.update(cx, |this, cx| {
 5393                    this.edit(edits, None, cx);
 5394                })
 5395            }
 5396            this.refresh_inline_completion(true, cx);
 5397            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5398        });
 5399    }
 5400
 5401    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5402        self.transact(cx, |this, cx| {
 5403            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5404                let line_mode = s.line_mode;
 5405                s.move_with(|map, selection| {
 5406                    if selection.is_empty() && !line_mode {
 5407                        let cursor = movement::right(map, selection.head());
 5408                        selection.end = cursor;
 5409                        selection.reversed = true;
 5410                        selection.goal = SelectionGoal::None;
 5411                    }
 5412                })
 5413            });
 5414            this.insert("", cx);
 5415            this.refresh_inline_completion(true, cx);
 5416        });
 5417    }
 5418
 5419    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5420        if self.move_to_prev_snippet_tabstop(cx) {
 5421            return;
 5422        }
 5423
 5424        self.outdent(&Outdent, cx);
 5425    }
 5426
 5427    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5428        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5429            return;
 5430        }
 5431
 5432        let mut selections = self.selections.all_adjusted(cx);
 5433        let buffer = self.buffer.read(cx);
 5434        let snapshot = buffer.snapshot(cx);
 5435        let rows_iter = selections.iter().map(|s| s.head().row);
 5436        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5437
 5438        let mut edits = Vec::new();
 5439        let mut prev_edited_row = 0;
 5440        let mut row_delta = 0;
 5441        for selection in &mut selections {
 5442            if selection.start.row != prev_edited_row {
 5443                row_delta = 0;
 5444            }
 5445            prev_edited_row = selection.end.row;
 5446
 5447            // If the selection is non-empty, then increase the indentation of the selected lines.
 5448            if !selection.is_empty() {
 5449                row_delta =
 5450                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5451                continue;
 5452            }
 5453
 5454            // If the selection is empty and the cursor is in the leading whitespace before the
 5455            // suggested indentation, then auto-indent the line.
 5456            let cursor = selection.head();
 5457            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5458            if let Some(suggested_indent) =
 5459                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5460            {
 5461                if cursor.column < suggested_indent.len
 5462                    && cursor.column <= current_indent.len
 5463                    && current_indent.len <= suggested_indent.len
 5464                {
 5465                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5466                    selection.end = selection.start;
 5467                    if row_delta == 0 {
 5468                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5469                            cursor.row,
 5470                            current_indent,
 5471                            suggested_indent,
 5472                        ));
 5473                        row_delta = suggested_indent.len - current_indent.len;
 5474                    }
 5475                    continue;
 5476                }
 5477            }
 5478
 5479            // Otherwise, insert a hard or soft tab.
 5480            let settings = buffer.settings_at(cursor, cx);
 5481            let tab_size = if settings.hard_tabs {
 5482                IndentSize::tab()
 5483            } else {
 5484                let tab_size = settings.tab_size.get();
 5485                let char_column = snapshot
 5486                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5487                    .flat_map(str::chars)
 5488                    .count()
 5489                    + row_delta as usize;
 5490                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5491                IndentSize::spaces(chars_to_next_tab_stop)
 5492            };
 5493            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5494            selection.end = selection.start;
 5495            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5496            row_delta += tab_size.len;
 5497        }
 5498
 5499        self.transact(cx, |this, cx| {
 5500            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5501            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5502            this.refresh_inline_completion(true, cx);
 5503        });
 5504    }
 5505
 5506    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5507        if self.read_only(cx) {
 5508            return;
 5509        }
 5510        let mut selections = self.selections.all::<Point>(cx);
 5511        let mut prev_edited_row = 0;
 5512        let mut row_delta = 0;
 5513        let mut edits = Vec::new();
 5514        let buffer = self.buffer.read(cx);
 5515        let snapshot = buffer.snapshot(cx);
 5516        for selection in &mut selections {
 5517            if selection.start.row != prev_edited_row {
 5518                row_delta = 0;
 5519            }
 5520            prev_edited_row = selection.end.row;
 5521
 5522            row_delta =
 5523                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5524        }
 5525
 5526        self.transact(cx, |this, cx| {
 5527            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5528            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5529        });
 5530    }
 5531
 5532    fn indent_selection(
 5533        buffer: &MultiBuffer,
 5534        snapshot: &MultiBufferSnapshot,
 5535        selection: &mut Selection<Point>,
 5536        edits: &mut Vec<(Range<Point>, String)>,
 5537        delta_for_start_row: u32,
 5538        cx: &AppContext,
 5539    ) -> u32 {
 5540        let settings = buffer.settings_at(selection.start, cx);
 5541        let tab_size = settings.tab_size.get();
 5542        let indent_kind = if settings.hard_tabs {
 5543            IndentKind::Tab
 5544        } else {
 5545            IndentKind::Space
 5546        };
 5547        let mut start_row = selection.start.row;
 5548        let mut end_row = selection.end.row + 1;
 5549
 5550        // If a selection ends at the beginning of a line, don't indent
 5551        // that last line.
 5552        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5553            end_row -= 1;
 5554        }
 5555
 5556        // Avoid re-indenting a row that has already been indented by a
 5557        // previous selection, but still update this selection's column
 5558        // to reflect that indentation.
 5559        if delta_for_start_row > 0 {
 5560            start_row += 1;
 5561            selection.start.column += delta_for_start_row;
 5562            if selection.end.row == selection.start.row {
 5563                selection.end.column += delta_for_start_row;
 5564            }
 5565        }
 5566
 5567        let mut delta_for_end_row = 0;
 5568        let has_multiple_rows = start_row + 1 != end_row;
 5569        for row in start_row..end_row {
 5570            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5571            let indent_delta = match (current_indent.kind, indent_kind) {
 5572                (IndentKind::Space, IndentKind::Space) => {
 5573                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5574                    IndentSize::spaces(columns_to_next_tab_stop)
 5575                }
 5576                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5577                (_, IndentKind::Tab) => IndentSize::tab(),
 5578            };
 5579
 5580            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5581                0
 5582            } else {
 5583                selection.start.column
 5584            };
 5585            let row_start = Point::new(row, start);
 5586            edits.push((
 5587                row_start..row_start,
 5588                indent_delta.chars().collect::<String>(),
 5589            ));
 5590
 5591            // Update this selection's endpoints to reflect the indentation.
 5592            if row == selection.start.row {
 5593                selection.start.column += indent_delta.len;
 5594            }
 5595            if row == selection.end.row {
 5596                selection.end.column += indent_delta.len;
 5597                delta_for_end_row = indent_delta.len;
 5598            }
 5599        }
 5600
 5601        if selection.start.row == selection.end.row {
 5602            delta_for_start_row + delta_for_end_row
 5603        } else {
 5604            delta_for_end_row
 5605        }
 5606    }
 5607
 5608    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5609        if self.read_only(cx) {
 5610            return;
 5611        }
 5612        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5613        let selections = self.selections.all::<Point>(cx);
 5614        let mut deletion_ranges = Vec::new();
 5615        let mut last_outdent = None;
 5616        {
 5617            let buffer = self.buffer.read(cx);
 5618            let snapshot = buffer.snapshot(cx);
 5619            for selection in &selections {
 5620                let settings = buffer.settings_at(selection.start, cx);
 5621                let tab_size = settings.tab_size.get();
 5622                let mut rows = selection.spanned_rows(false, &display_map);
 5623
 5624                // Avoid re-outdenting a row that has already been outdented by a
 5625                // previous selection.
 5626                if let Some(last_row) = last_outdent {
 5627                    if last_row == rows.start {
 5628                        rows.start = rows.start.next_row();
 5629                    }
 5630                }
 5631                let has_multiple_rows = rows.len() > 1;
 5632                for row in rows.iter_rows() {
 5633                    let indent_size = snapshot.indent_size_for_line(row);
 5634                    if indent_size.len > 0 {
 5635                        let deletion_len = match indent_size.kind {
 5636                            IndentKind::Space => {
 5637                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5638                                if columns_to_prev_tab_stop == 0 {
 5639                                    tab_size
 5640                                } else {
 5641                                    columns_to_prev_tab_stop
 5642                                }
 5643                            }
 5644                            IndentKind::Tab => 1,
 5645                        };
 5646                        let start = if has_multiple_rows
 5647                            || deletion_len > selection.start.column
 5648                            || indent_size.len < selection.start.column
 5649                        {
 5650                            0
 5651                        } else {
 5652                            selection.start.column - deletion_len
 5653                        };
 5654                        deletion_ranges.push(
 5655                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5656                        );
 5657                        last_outdent = Some(row);
 5658                    }
 5659                }
 5660            }
 5661        }
 5662
 5663        self.transact(cx, |this, cx| {
 5664            this.buffer.update(cx, |buffer, cx| {
 5665                let empty_str: Arc<str> = "".into();
 5666                buffer.edit(
 5667                    deletion_ranges
 5668                        .into_iter()
 5669                        .map(|range| (range, empty_str.clone())),
 5670                    None,
 5671                    cx,
 5672                );
 5673            });
 5674            let selections = this.selections.all::<usize>(cx);
 5675            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5676        });
 5677    }
 5678
 5679    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5680        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5681        let selections = self.selections.all::<Point>(cx);
 5682
 5683        let mut new_cursors = Vec::new();
 5684        let mut edit_ranges = Vec::new();
 5685        let mut selections = selections.iter().peekable();
 5686        while let Some(selection) = selections.next() {
 5687            let mut rows = selection.spanned_rows(false, &display_map);
 5688            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5689
 5690            // Accumulate contiguous regions of rows that we want to delete.
 5691            while let Some(next_selection) = selections.peek() {
 5692                let next_rows = next_selection.spanned_rows(false, &display_map);
 5693                if next_rows.start <= rows.end {
 5694                    rows.end = next_rows.end;
 5695                    selections.next().unwrap();
 5696                } else {
 5697                    break;
 5698                }
 5699            }
 5700
 5701            let buffer = &display_map.buffer_snapshot;
 5702            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5703            let edit_end;
 5704            let cursor_buffer_row;
 5705            if buffer.max_point().row >= rows.end.0 {
 5706                // If there's a line after the range, delete the \n from the end of the row range
 5707                // and position the cursor on the next line.
 5708                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5709                cursor_buffer_row = rows.end;
 5710            } else {
 5711                // If there isn't a line after the range, delete the \n from the line before the
 5712                // start of the row range and position the cursor there.
 5713                edit_start = edit_start.saturating_sub(1);
 5714                edit_end = buffer.len();
 5715                cursor_buffer_row = rows.start.previous_row();
 5716            }
 5717
 5718            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5719            *cursor.column_mut() =
 5720                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5721
 5722            new_cursors.push((
 5723                selection.id,
 5724                buffer.anchor_after(cursor.to_point(&display_map)),
 5725            ));
 5726            edit_ranges.push(edit_start..edit_end);
 5727        }
 5728
 5729        self.transact(cx, |this, cx| {
 5730            let buffer = this.buffer.update(cx, |buffer, cx| {
 5731                let empty_str: Arc<str> = "".into();
 5732                buffer.edit(
 5733                    edit_ranges
 5734                        .into_iter()
 5735                        .map(|range| (range, empty_str.clone())),
 5736                    None,
 5737                    cx,
 5738                );
 5739                buffer.snapshot(cx)
 5740            });
 5741            let new_selections = new_cursors
 5742                .into_iter()
 5743                .map(|(id, cursor)| {
 5744                    let cursor = cursor.to_point(&buffer);
 5745                    Selection {
 5746                        id,
 5747                        start: cursor,
 5748                        end: cursor,
 5749                        reversed: false,
 5750                        goal: SelectionGoal::None,
 5751                    }
 5752                })
 5753                .collect();
 5754
 5755            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5756                s.select(new_selections);
 5757            });
 5758        });
 5759    }
 5760
 5761    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5762        if self.read_only(cx) {
 5763            return;
 5764        }
 5765        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5766        for selection in self.selections.all::<Point>(cx) {
 5767            let start = MultiBufferRow(selection.start.row);
 5768            let end = if selection.start.row == selection.end.row {
 5769                MultiBufferRow(selection.start.row + 1)
 5770            } else {
 5771                MultiBufferRow(selection.end.row)
 5772            };
 5773
 5774            if let Some(last_row_range) = row_ranges.last_mut() {
 5775                if start <= last_row_range.end {
 5776                    last_row_range.end = end;
 5777                    continue;
 5778                }
 5779            }
 5780            row_ranges.push(start..end);
 5781        }
 5782
 5783        let snapshot = self.buffer.read(cx).snapshot(cx);
 5784        let mut cursor_positions = Vec::new();
 5785        for row_range in &row_ranges {
 5786            let anchor = snapshot.anchor_before(Point::new(
 5787                row_range.end.previous_row().0,
 5788                snapshot.line_len(row_range.end.previous_row()),
 5789            ));
 5790            cursor_positions.push(anchor..anchor);
 5791        }
 5792
 5793        self.transact(cx, |this, cx| {
 5794            for row_range in row_ranges.into_iter().rev() {
 5795                for row in row_range.iter_rows().rev() {
 5796                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5797                    let next_line_row = row.next_row();
 5798                    let indent = snapshot.indent_size_for_line(next_line_row);
 5799                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5800
 5801                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5802                        " "
 5803                    } else {
 5804                        ""
 5805                    };
 5806
 5807                    this.buffer.update(cx, |buffer, cx| {
 5808                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5809                    });
 5810                }
 5811            }
 5812
 5813            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5814                s.select_anchor_ranges(cursor_positions)
 5815            });
 5816        });
 5817    }
 5818
 5819    pub fn sort_lines_case_sensitive(
 5820        &mut self,
 5821        _: &SortLinesCaseSensitive,
 5822        cx: &mut ViewContext<Self>,
 5823    ) {
 5824        self.manipulate_lines(cx, |lines| lines.sort())
 5825    }
 5826
 5827    pub fn sort_lines_case_insensitive(
 5828        &mut self,
 5829        _: &SortLinesCaseInsensitive,
 5830        cx: &mut ViewContext<Self>,
 5831    ) {
 5832        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5833    }
 5834
 5835    pub fn unique_lines_case_insensitive(
 5836        &mut self,
 5837        _: &UniqueLinesCaseInsensitive,
 5838        cx: &mut ViewContext<Self>,
 5839    ) {
 5840        self.manipulate_lines(cx, |lines| {
 5841            let mut seen = HashSet::default();
 5842            lines.retain(|line| seen.insert(line.to_lowercase()));
 5843        })
 5844    }
 5845
 5846    pub fn unique_lines_case_sensitive(
 5847        &mut self,
 5848        _: &UniqueLinesCaseSensitive,
 5849        cx: &mut ViewContext<Self>,
 5850    ) {
 5851        self.manipulate_lines(cx, |lines| {
 5852            let mut seen = HashSet::default();
 5853            lines.retain(|line| seen.insert(*line));
 5854        })
 5855    }
 5856
 5857    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5858        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 5859        if !revert_changes.is_empty() {
 5860            self.transact(cx, |editor, cx| {
 5861                editor.buffer().update(cx, |multi_buffer, cx| {
 5862                    for (buffer_id, changes) in revert_changes {
 5863                        if let Some(buffer) = multi_buffer.buffer(buffer_id) {
 5864                            buffer.update(cx, |buffer, cx| {
 5865                                buffer.edit(
 5866                                    changes.into_iter().map(|(range, text)| {
 5867                                        (range, text.to_string().map(Arc::<str>::from))
 5868                                    }),
 5869                                    None,
 5870                                    cx,
 5871                                );
 5872                            });
 5873                        }
 5874                    }
 5875                });
 5876                editor.change_selections(None, cx, |selections| selections.refresh());
 5877            });
 5878        }
 5879    }
 5880
 5881    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5882        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5883            let project_path = buffer.read(cx).project_path(cx)?;
 5884            let project = self.project.as_ref()?.read(cx);
 5885            let entry = project.entry_for_path(&project_path, cx)?;
 5886            let abs_path = project.absolute_path(&project_path, cx)?;
 5887            let parent = if entry.is_symlink {
 5888                abs_path.canonicalize().ok()?
 5889            } else {
 5890                abs_path
 5891            }
 5892            .parent()?
 5893            .to_path_buf();
 5894            Some(parent)
 5895        }) {
 5896            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5897        }
 5898    }
 5899
 5900    fn gather_revert_changes(
 5901        &mut self,
 5902        selections: &[Selection<Anchor>],
 5903        cx: &mut ViewContext<'_, Editor>,
 5904    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 5905        let mut revert_changes = HashMap::default();
 5906        self.buffer.update(cx, |multi_buffer, cx| {
 5907            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 5908            for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 5909                Self::prepare_revert_change(&mut revert_changes, &multi_buffer, &hunk, cx);
 5910            }
 5911        });
 5912        revert_changes
 5913    }
 5914
 5915    fn prepare_revert_change(
 5916        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 5917        multi_buffer: &MultiBuffer,
 5918        hunk: &DiffHunk<MultiBufferRow>,
 5919        cx: &mut AppContext,
 5920    ) -> Option<()> {
 5921        let buffer = multi_buffer.buffer(hunk.buffer_id)?;
 5922        let buffer = buffer.read(cx);
 5923        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 5924        let buffer_snapshot = buffer.snapshot();
 5925        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5926        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5927            probe
 5928                .0
 5929                .start
 5930                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5931                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5932        }) {
 5933            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 5934            Some(())
 5935        } else {
 5936            None
 5937        }
 5938    }
 5939
 5940    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5941        self.manipulate_lines(cx, |lines| lines.reverse())
 5942    }
 5943
 5944    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5945        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5946    }
 5947
 5948    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5949    where
 5950        Fn: FnMut(&mut Vec<&str>),
 5951    {
 5952        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5953        let buffer = self.buffer.read(cx).snapshot(cx);
 5954
 5955        let mut edits = Vec::new();
 5956
 5957        let selections = self.selections.all::<Point>(cx);
 5958        let mut selections = selections.iter().peekable();
 5959        let mut contiguous_row_selections = Vec::new();
 5960        let mut new_selections = Vec::new();
 5961        let mut added_lines = 0;
 5962        let mut removed_lines = 0;
 5963
 5964        while let Some(selection) = selections.next() {
 5965            let (start_row, end_row) = consume_contiguous_rows(
 5966                &mut contiguous_row_selections,
 5967                selection,
 5968                &display_map,
 5969                &mut selections,
 5970            );
 5971
 5972            let start_point = Point::new(start_row.0, 0);
 5973            let end_point = Point::new(
 5974                end_row.previous_row().0,
 5975                buffer.line_len(end_row.previous_row()),
 5976            );
 5977            let text = buffer
 5978                .text_for_range(start_point..end_point)
 5979                .collect::<String>();
 5980
 5981            let mut lines = text.split('\n').collect_vec();
 5982
 5983            let lines_before = lines.len();
 5984            callback(&mut lines);
 5985            let lines_after = lines.len();
 5986
 5987            edits.push((start_point..end_point, lines.join("\n")));
 5988
 5989            // Selections must change based on added and removed line count
 5990            let start_row =
 5991                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 5992            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 5993            new_selections.push(Selection {
 5994                id: selection.id,
 5995                start: start_row,
 5996                end: end_row,
 5997                goal: SelectionGoal::None,
 5998                reversed: selection.reversed,
 5999            });
 6000
 6001            if lines_after > lines_before {
 6002                added_lines += lines_after - lines_before;
 6003            } else if lines_before > lines_after {
 6004                removed_lines += lines_before - lines_after;
 6005            }
 6006        }
 6007
 6008        self.transact(cx, |this, cx| {
 6009            let buffer = this.buffer.update(cx, |buffer, cx| {
 6010                buffer.edit(edits, None, cx);
 6011                buffer.snapshot(cx)
 6012            });
 6013
 6014            // Recalculate offsets on newly edited buffer
 6015            let new_selections = new_selections
 6016                .iter()
 6017                .map(|s| {
 6018                    let start_point = Point::new(s.start.0, 0);
 6019                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6020                    Selection {
 6021                        id: s.id,
 6022                        start: buffer.point_to_offset(start_point),
 6023                        end: buffer.point_to_offset(end_point),
 6024                        goal: s.goal,
 6025                        reversed: s.reversed,
 6026                    }
 6027                })
 6028                .collect();
 6029
 6030            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6031                s.select(new_selections);
 6032            });
 6033
 6034            this.request_autoscroll(Autoscroll::fit(), cx);
 6035        });
 6036    }
 6037
 6038    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6039        self.manipulate_text(cx, |text| text.to_uppercase())
 6040    }
 6041
 6042    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6043        self.manipulate_text(cx, |text| text.to_lowercase())
 6044    }
 6045
 6046    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6047        self.manipulate_text(cx, |text| {
 6048            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6049            // https://github.com/rutrum/convert-case/issues/16
 6050            text.split('\n')
 6051                .map(|line| line.to_case(Case::Title))
 6052                .join("\n")
 6053        })
 6054    }
 6055
 6056    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6057        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6058    }
 6059
 6060    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6061        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6062    }
 6063
 6064    pub fn convert_to_upper_camel_case(
 6065        &mut self,
 6066        _: &ConvertToUpperCamelCase,
 6067        cx: &mut ViewContext<Self>,
 6068    ) {
 6069        self.manipulate_text(cx, |text| {
 6070            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6071            // https://github.com/rutrum/convert-case/issues/16
 6072            text.split('\n')
 6073                .map(|line| line.to_case(Case::UpperCamel))
 6074                .join("\n")
 6075        })
 6076    }
 6077
 6078    pub fn convert_to_lower_camel_case(
 6079        &mut self,
 6080        _: &ConvertToLowerCamelCase,
 6081        cx: &mut ViewContext<Self>,
 6082    ) {
 6083        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6084    }
 6085
 6086    pub fn convert_to_opposite_case(
 6087        &mut self,
 6088        _: &ConvertToOppositeCase,
 6089        cx: &mut ViewContext<Self>,
 6090    ) {
 6091        self.manipulate_text(cx, |text| {
 6092            text.chars()
 6093                .fold(String::with_capacity(text.len()), |mut t, c| {
 6094                    if c.is_uppercase() {
 6095                        t.extend(c.to_lowercase());
 6096                    } else {
 6097                        t.extend(c.to_uppercase());
 6098                    }
 6099                    t
 6100                })
 6101        })
 6102    }
 6103
 6104    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6105    where
 6106        Fn: FnMut(&str) -> String,
 6107    {
 6108        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6109        let buffer = self.buffer.read(cx).snapshot(cx);
 6110
 6111        let mut new_selections = Vec::new();
 6112        let mut edits = Vec::new();
 6113        let mut selection_adjustment = 0i32;
 6114
 6115        for selection in self.selections.all::<usize>(cx) {
 6116            let selection_is_empty = selection.is_empty();
 6117
 6118            let (start, end) = if selection_is_empty {
 6119                let word_range = movement::surrounding_word(
 6120                    &display_map,
 6121                    selection.start.to_display_point(&display_map),
 6122                );
 6123                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6124                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6125                (start, end)
 6126            } else {
 6127                (selection.start, selection.end)
 6128            };
 6129
 6130            let text = buffer.text_for_range(start..end).collect::<String>();
 6131            let old_length = text.len() as i32;
 6132            let text = callback(&text);
 6133
 6134            new_selections.push(Selection {
 6135                start: (start as i32 - selection_adjustment) as usize,
 6136                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6137                goal: SelectionGoal::None,
 6138                ..selection
 6139            });
 6140
 6141            selection_adjustment += old_length - text.len() as i32;
 6142
 6143            edits.push((start..end, text));
 6144        }
 6145
 6146        self.transact(cx, |this, cx| {
 6147            this.buffer.update(cx, |buffer, cx| {
 6148                buffer.edit(edits, None, cx);
 6149            });
 6150
 6151            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6152                s.select(new_selections);
 6153            });
 6154
 6155            this.request_autoscroll(Autoscroll::fit(), cx);
 6156        });
 6157    }
 6158
 6159    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6160        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6161        let buffer = &display_map.buffer_snapshot;
 6162        let selections = self.selections.all::<Point>(cx);
 6163
 6164        let mut edits = Vec::new();
 6165        let mut selections_iter = selections.iter().peekable();
 6166        while let Some(selection) = selections_iter.next() {
 6167            // Avoid duplicating the same lines twice.
 6168            let mut rows = selection.spanned_rows(false, &display_map);
 6169
 6170            while let Some(next_selection) = selections_iter.peek() {
 6171                let next_rows = next_selection.spanned_rows(false, &display_map);
 6172                if next_rows.start < rows.end {
 6173                    rows.end = next_rows.end;
 6174                    selections_iter.next().unwrap();
 6175                } else {
 6176                    break;
 6177                }
 6178            }
 6179
 6180            // Copy the text from the selected row region and splice it either at the start
 6181            // or end of the region.
 6182            let start = Point::new(rows.start.0, 0);
 6183            let end = Point::new(
 6184                rows.end.previous_row().0,
 6185                buffer.line_len(rows.end.previous_row()),
 6186            );
 6187            let text = buffer
 6188                .text_for_range(start..end)
 6189                .chain(Some("\n"))
 6190                .collect::<String>();
 6191            let insert_location = if upwards {
 6192                Point::new(rows.end.0, 0)
 6193            } else {
 6194                start
 6195            };
 6196            edits.push((insert_location..insert_location, text));
 6197        }
 6198
 6199        self.transact(cx, |this, cx| {
 6200            this.buffer.update(cx, |buffer, cx| {
 6201                buffer.edit(edits, None, cx);
 6202            });
 6203
 6204            this.request_autoscroll(Autoscroll::fit(), cx);
 6205        });
 6206    }
 6207
 6208    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6209        self.duplicate_line(true, cx);
 6210    }
 6211
 6212    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6213        self.duplicate_line(false, cx);
 6214    }
 6215
 6216    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6217        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6218        let buffer = self.buffer.read(cx).snapshot(cx);
 6219
 6220        let mut edits = Vec::new();
 6221        let mut unfold_ranges = Vec::new();
 6222        let mut refold_ranges = Vec::new();
 6223
 6224        let selections = self.selections.all::<Point>(cx);
 6225        let mut selections = selections.iter().peekable();
 6226        let mut contiguous_row_selections = Vec::new();
 6227        let mut new_selections = Vec::new();
 6228
 6229        while let Some(selection) = selections.next() {
 6230            // Find all the selections that span a contiguous row range
 6231            let (start_row, end_row) = consume_contiguous_rows(
 6232                &mut contiguous_row_selections,
 6233                selection,
 6234                &display_map,
 6235                &mut selections,
 6236            );
 6237
 6238            // Move the text spanned by the row range to be before the line preceding the row range
 6239            if start_row.0 > 0 {
 6240                let range_to_move = Point::new(
 6241                    start_row.previous_row().0,
 6242                    buffer.line_len(start_row.previous_row()),
 6243                )
 6244                    ..Point::new(
 6245                        end_row.previous_row().0,
 6246                        buffer.line_len(end_row.previous_row()),
 6247                    );
 6248                let insertion_point = display_map
 6249                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6250                    .0;
 6251
 6252                // Don't move lines across excerpts
 6253                if buffer
 6254                    .excerpt_boundaries_in_range((
 6255                        Bound::Excluded(insertion_point),
 6256                        Bound::Included(range_to_move.end),
 6257                    ))
 6258                    .next()
 6259                    .is_none()
 6260                {
 6261                    let text = buffer
 6262                        .text_for_range(range_to_move.clone())
 6263                        .flat_map(|s| s.chars())
 6264                        .skip(1)
 6265                        .chain(['\n'])
 6266                        .collect::<String>();
 6267
 6268                    edits.push((
 6269                        buffer.anchor_after(range_to_move.start)
 6270                            ..buffer.anchor_before(range_to_move.end),
 6271                        String::new(),
 6272                    ));
 6273                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6274                    edits.push((insertion_anchor..insertion_anchor, text));
 6275
 6276                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6277
 6278                    // Move selections up
 6279                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6280                        |mut selection| {
 6281                            selection.start.row -= row_delta;
 6282                            selection.end.row -= row_delta;
 6283                            selection
 6284                        },
 6285                    ));
 6286
 6287                    // Move folds up
 6288                    unfold_ranges.push(range_to_move.clone());
 6289                    for fold in display_map.folds_in_range(
 6290                        buffer.anchor_before(range_to_move.start)
 6291                            ..buffer.anchor_after(range_to_move.end),
 6292                    ) {
 6293                        let mut start = fold.range.start.to_point(&buffer);
 6294                        let mut end = fold.range.end.to_point(&buffer);
 6295                        start.row -= row_delta;
 6296                        end.row -= row_delta;
 6297                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6298                    }
 6299                }
 6300            }
 6301
 6302            // If we didn't move line(s), preserve the existing selections
 6303            new_selections.append(&mut contiguous_row_selections);
 6304        }
 6305
 6306        self.transact(cx, |this, cx| {
 6307            this.unfold_ranges(unfold_ranges, true, true, cx);
 6308            this.buffer.update(cx, |buffer, cx| {
 6309                for (range, text) in edits {
 6310                    buffer.edit([(range, text)], None, cx);
 6311                }
 6312            });
 6313            this.fold_ranges(refold_ranges, true, cx);
 6314            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6315                s.select(new_selections);
 6316            })
 6317        });
 6318    }
 6319
 6320    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6321        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6322        let buffer = self.buffer.read(cx).snapshot(cx);
 6323
 6324        let mut edits = Vec::new();
 6325        let mut unfold_ranges = Vec::new();
 6326        let mut refold_ranges = Vec::new();
 6327
 6328        let selections = self.selections.all::<Point>(cx);
 6329        let mut selections = selections.iter().peekable();
 6330        let mut contiguous_row_selections = Vec::new();
 6331        let mut new_selections = Vec::new();
 6332
 6333        while let Some(selection) = selections.next() {
 6334            // Find all the selections that span a contiguous row range
 6335            let (start_row, end_row) = consume_contiguous_rows(
 6336                &mut contiguous_row_selections,
 6337                selection,
 6338                &display_map,
 6339                &mut selections,
 6340            );
 6341
 6342            // Move the text spanned by the row range to be after the last line of the row range
 6343            if end_row.0 <= buffer.max_point().row {
 6344                let range_to_move =
 6345                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6346                let insertion_point = display_map
 6347                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6348                    .0;
 6349
 6350                // Don't move lines across excerpt boundaries
 6351                if buffer
 6352                    .excerpt_boundaries_in_range((
 6353                        Bound::Excluded(range_to_move.start),
 6354                        Bound::Included(insertion_point),
 6355                    ))
 6356                    .next()
 6357                    .is_none()
 6358                {
 6359                    let mut text = String::from("\n");
 6360                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6361                    text.pop(); // Drop trailing newline
 6362                    edits.push((
 6363                        buffer.anchor_after(range_to_move.start)
 6364                            ..buffer.anchor_before(range_to_move.end),
 6365                        String::new(),
 6366                    ));
 6367                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6368                    edits.push((insertion_anchor..insertion_anchor, text));
 6369
 6370                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6371
 6372                    // Move selections down
 6373                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6374                        |mut selection| {
 6375                            selection.start.row += row_delta;
 6376                            selection.end.row += row_delta;
 6377                            selection
 6378                        },
 6379                    ));
 6380
 6381                    // Move folds down
 6382                    unfold_ranges.push(range_to_move.clone());
 6383                    for fold in display_map.folds_in_range(
 6384                        buffer.anchor_before(range_to_move.start)
 6385                            ..buffer.anchor_after(range_to_move.end),
 6386                    ) {
 6387                        let mut start = fold.range.start.to_point(&buffer);
 6388                        let mut end = fold.range.end.to_point(&buffer);
 6389                        start.row += row_delta;
 6390                        end.row += row_delta;
 6391                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6392                    }
 6393                }
 6394            }
 6395
 6396            // If we didn't move line(s), preserve the existing selections
 6397            new_selections.append(&mut contiguous_row_selections);
 6398        }
 6399
 6400        self.transact(cx, |this, cx| {
 6401            this.unfold_ranges(unfold_ranges, true, true, cx);
 6402            this.buffer.update(cx, |buffer, cx| {
 6403                for (range, text) in edits {
 6404                    buffer.edit([(range, text)], None, cx);
 6405                }
 6406            });
 6407            this.fold_ranges(refold_ranges, true, cx);
 6408            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6409        });
 6410    }
 6411
 6412    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6413        let text_layout_details = &self.text_layout_details(cx);
 6414        self.transact(cx, |this, cx| {
 6415            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6416                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6417                let line_mode = s.line_mode;
 6418                s.move_with(|display_map, selection| {
 6419                    if !selection.is_empty() || line_mode {
 6420                        return;
 6421                    }
 6422
 6423                    let mut head = selection.head();
 6424                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6425                    if head.column() == display_map.line_len(head.row()) {
 6426                        transpose_offset = display_map
 6427                            .buffer_snapshot
 6428                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6429                    }
 6430
 6431                    if transpose_offset == 0 {
 6432                        return;
 6433                    }
 6434
 6435                    *head.column_mut() += 1;
 6436                    head = display_map.clip_point(head, Bias::Right);
 6437                    let goal = SelectionGoal::HorizontalPosition(
 6438                        display_map
 6439                            .x_for_display_point(head, &text_layout_details)
 6440                            .into(),
 6441                    );
 6442                    selection.collapse_to(head, goal);
 6443
 6444                    let transpose_start = display_map
 6445                        .buffer_snapshot
 6446                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6447                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6448                        let transpose_end = display_map
 6449                            .buffer_snapshot
 6450                            .clip_offset(transpose_offset + 1, Bias::Right);
 6451                        if let Some(ch) =
 6452                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6453                        {
 6454                            edits.push((transpose_start..transpose_offset, String::new()));
 6455                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6456                        }
 6457                    }
 6458                });
 6459                edits
 6460            });
 6461            this.buffer
 6462                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6463            let selections = this.selections.all::<usize>(cx);
 6464            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6465                s.select(selections);
 6466            });
 6467        });
 6468    }
 6469
 6470    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6471        let mut text = String::new();
 6472        let buffer = self.buffer.read(cx).snapshot(cx);
 6473        let mut selections = self.selections.all::<Point>(cx);
 6474        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6475        {
 6476            let max_point = buffer.max_point();
 6477            let mut is_first = true;
 6478            for selection in &mut selections {
 6479                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6480                if is_entire_line {
 6481                    selection.start = Point::new(selection.start.row, 0);
 6482                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6483                    selection.goal = SelectionGoal::None;
 6484                }
 6485                if is_first {
 6486                    is_first = false;
 6487                } else {
 6488                    text += "\n";
 6489                }
 6490                let mut len = 0;
 6491                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6492                    text.push_str(chunk);
 6493                    len += chunk.len();
 6494                }
 6495                clipboard_selections.push(ClipboardSelection {
 6496                    len,
 6497                    is_entire_line,
 6498                    first_line_indent: buffer
 6499                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6500                        .len,
 6501                });
 6502            }
 6503        }
 6504
 6505        self.transact(cx, |this, cx| {
 6506            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6507                s.select(selections);
 6508            });
 6509            this.insert("", cx);
 6510            cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6511        });
 6512    }
 6513
 6514    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6515        let selections = self.selections.all::<Point>(cx);
 6516        let buffer = self.buffer.read(cx).read(cx);
 6517        let mut text = String::new();
 6518
 6519        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6520        {
 6521            let max_point = buffer.max_point();
 6522            let mut is_first = true;
 6523            for selection in selections.iter() {
 6524                let mut start = selection.start;
 6525                let mut end = selection.end;
 6526                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6527                if is_entire_line {
 6528                    start = Point::new(start.row, 0);
 6529                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6530                }
 6531                if is_first {
 6532                    is_first = false;
 6533                } else {
 6534                    text += "\n";
 6535                }
 6536                let mut len = 0;
 6537                for chunk in buffer.text_for_range(start..end) {
 6538                    text.push_str(chunk);
 6539                    len += chunk.len();
 6540                }
 6541                clipboard_selections.push(ClipboardSelection {
 6542                    len,
 6543                    is_entire_line,
 6544                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6545                });
 6546            }
 6547        }
 6548
 6549        cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6550    }
 6551
 6552    pub fn do_paste(
 6553        &mut self,
 6554        text: &String,
 6555        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6556        handle_entire_lines: bool,
 6557        cx: &mut ViewContext<Self>,
 6558    ) {
 6559        if self.read_only(cx) {
 6560            return;
 6561        }
 6562
 6563        let clipboard_text = Cow::Borrowed(text);
 6564
 6565        self.transact(cx, |this, cx| {
 6566            if let Some(mut clipboard_selections) = clipboard_selections {
 6567                let old_selections = this.selections.all::<usize>(cx);
 6568                let all_selections_were_entire_line =
 6569                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6570                let first_selection_indent_column =
 6571                    clipboard_selections.first().map(|s| s.first_line_indent);
 6572                if clipboard_selections.len() != old_selections.len() {
 6573                    clipboard_selections.drain(..);
 6574                }
 6575
 6576                this.buffer.update(cx, |buffer, cx| {
 6577                    let snapshot = buffer.read(cx);
 6578                    let mut start_offset = 0;
 6579                    let mut edits = Vec::new();
 6580                    let mut original_indent_columns = Vec::new();
 6581                    for (ix, selection) in old_selections.iter().enumerate() {
 6582                        let to_insert;
 6583                        let entire_line;
 6584                        let original_indent_column;
 6585                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6586                            let end_offset = start_offset + clipboard_selection.len;
 6587                            to_insert = &clipboard_text[start_offset..end_offset];
 6588                            entire_line = clipboard_selection.is_entire_line;
 6589                            start_offset = end_offset + 1;
 6590                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6591                        } else {
 6592                            to_insert = clipboard_text.as_str();
 6593                            entire_line = all_selections_were_entire_line;
 6594                            original_indent_column = first_selection_indent_column
 6595                        }
 6596
 6597                        // If the corresponding selection was empty when this slice of the
 6598                        // clipboard text was written, then the entire line containing the
 6599                        // selection was copied. If this selection is also currently empty,
 6600                        // then paste the line before the current line of the buffer.
 6601                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6602                            let column = selection.start.to_point(&snapshot).column as usize;
 6603                            let line_start = selection.start - column;
 6604                            line_start..line_start
 6605                        } else {
 6606                            selection.range()
 6607                        };
 6608
 6609                        edits.push((range, to_insert));
 6610                        original_indent_columns.extend(original_indent_column);
 6611                    }
 6612                    drop(snapshot);
 6613
 6614                    buffer.edit(
 6615                        edits,
 6616                        Some(AutoindentMode::Block {
 6617                            original_indent_columns,
 6618                        }),
 6619                        cx,
 6620                    );
 6621                });
 6622
 6623                let selections = this.selections.all::<usize>(cx);
 6624                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6625            } else {
 6626                this.insert(&clipboard_text, cx);
 6627            }
 6628        });
 6629    }
 6630
 6631    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6632        if let Some(item) = cx.read_from_clipboard() {
 6633            self.do_paste(
 6634                item.text(),
 6635                item.metadata::<Vec<ClipboardSelection>>(),
 6636                true,
 6637                cx,
 6638            )
 6639        };
 6640    }
 6641
 6642    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6643        if self.read_only(cx) {
 6644            return;
 6645        }
 6646
 6647        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6648            if let Some((selections, _)) =
 6649                self.selection_history.transaction(transaction_id).cloned()
 6650            {
 6651                self.change_selections(None, cx, |s| {
 6652                    s.select_anchors(selections.to_vec());
 6653                });
 6654            }
 6655            self.request_autoscroll(Autoscroll::fit(), cx);
 6656            self.unmark_text(cx);
 6657            self.refresh_inline_completion(true, cx);
 6658            cx.emit(EditorEvent::Edited { transaction_id });
 6659            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 6660        }
 6661    }
 6662
 6663    pub fn redo(&mut self, _: &Redo, 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.redo(cx)) {
 6669            if let Some((_, 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        }
 6681    }
 6682
 6683    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 6684        self.buffer
 6685            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 6686    }
 6687
 6688    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 6689        self.buffer
 6690            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 6691    }
 6692
 6693    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 6694        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6695            let line_mode = s.line_mode;
 6696            s.move_with(|map, selection| {
 6697                let cursor = if selection.is_empty() && !line_mode {
 6698                    movement::left(map, selection.start)
 6699                } else {
 6700                    selection.start
 6701                };
 6702                selection.collapse_to(cursor, SelectionGoal::None);
 6703            });
 6704        })
 6705    }
 6706
 6707    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 6708        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6709            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 6710        })
 6711    }
 6712
 6713    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 6714        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6715            let line_mode = s.line_mode;
 6716            s.move_with(|map, selection| {
 6717                let cursor = if selection.is_empty() && !line_mode {
 6718                    movement::right(map, selection.end)
 6719                } else {
 6720                    selection.end
 6721                };
 6722                selection.collapse_to(cursor, SelectionGoal::None)
 6723            });
 6724        })
 6725    }
 6726
 6727    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 6728        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6729            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 6730        })
 6731    }
 6732
 6733    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 6734        if self.take_rename(true, cx).is_some() {
 6735            return;
 6736        }
 6737
 6738        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6739            cx.propagate();
 6740            return;
 6741        }
 6742
 6743        let text_layout_details = &self.text_layout_details(cx);
 6744        let selection_count = self.selections.count();
 6745        let first_selection = self.selections.first_anchor();
 6746
 6747        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6748            let line_mode = s.line_mode;
 6749            s.move_with(|map, selection| {
 6750                if !selection.is_empty() && !line_mode {
 6751                    selection.goal = SelectionGoal::None;
 6752                }
 6753                let (cursor, goal) = movement::up(
 6754                    map,
 6755                    selection.start,
 6756                    selection.goal,
 6757                    false,
 6758                    &text_layout_details,
 6759                );
 6760                selection.collapse_to(cursor, goal);
 6761            });
 6762        });
 6763
 6764        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6765        {
 6766            cx.propagate();
 6767        }
 6768    }
 6769
 6770    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 6771        if self.take_rename(true, cx).is_some() {
 6772            return;
 6773        }
 6774
 6775        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6776            cx.propagate();
 6777            return;
 6778        }
 6779
 6780        let text_layout_details = &self.text_layout_details(cx);
 6781
 6782        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6783            let line_mode = s.line_mode;
 6784            s.move_with(|map, selection| {
 6785                if !selection.is_empty() && !line_mode {
 6786                    selection.goal = SelectionGoal::None;
 6787                }
 6788                let (cursor, goal) = movement::up_by_rows(
 6789                    map,
 6790                    selection.start,
 6791                    action.lines,
 6792                    selection.goal,
 6793                    false,
 6794                    &text_layout_details,
 6795                );
 6796                selection.collapse_to(cursor, goal);
 6797            });
 6798        })
 6799    }
 6800
 6801    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 6802        if self.take_rename(true, cx).is_some() {
 6803            return;
 6804        }
 6805
 6806        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6807            cx.propagate();
 6808            return;
 6809        }
 6810
 6811        let text_layout_details = &self.text_layout_details(cx);
 6812
 6813        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6814            let line_mode = s.line_mode;
 6815            s.move_with(|map, selection| {
 6816                if !selection.is_empty() && !line_mode {
 6817                    selection.goal = SelectionGoal::None;
 6818                }
 6819                let (cursor, goal) = movement::down_by_rows(
 6820                    map,
 6821                    selection.start,
 6822                    action.lines,
 6823                    selection.goal,
 6824                    false,
 6825                    &text_layout_details,
 6826                );
 6827                selection.collapse_to(cursor, goal);
 6828            });
 6829        })
 6830    }
 6831
 6832    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 6833        let text_layout_details = &self.text_layout_details(cx);
 6834        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6835            s.move_heads_with(|map, head, goal| {
 6836                movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6837            })
 6838        })
 6839    }
 6840
 6841    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 6842        let text_layout_details = &self.text_layout_details(cx);
 6843        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6844            s.move_heads_with(|map, head, goal| {
 6845                movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6846            })
 6847        })
 6848    }
 6849
 6850    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 6851        let Some(row_count) = self.visible_row_count() else {
 6852            return;
 6853        };
 6854
 6855        let text_layout_details = &self.text_layout_details(cx);
 6856
 6857        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6858            s.move_heads_with(|map, head, goal| {
 6859                movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
 6860            })
 6861        })
 6862    }
 6863
 6864    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 6865        if self.take_rename(true, cx).is_some() {
 6866            return;
 6867        }
 6868
 6869        if self
 6870            .context_menu
 6871            .write()
 6872            .as_mut()
 6873            .map(|menu| menu.select_first(self.project.as_ref(), cx))
 6874            .unwrap_or(false)
 6875        {
 6876            return;
 6877        }
 6878
 6879        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6880            cx.propagate();
 6881            return;
 6882        }
 6883
 6884        let Some(row_count) = self.visible_row_count() else {
 6885            return;
 6886        };
 6887
 6888        let autoscroll = if action.center_cursor {
 6889            Autoscroll::center()
 6890        } else {
 6891            Autoscroll::fit()
 6892        };
 6893
 6894        let text_layout_details = &self.text_layout_details(cx);
 6895
 6896        self.change_selections(Some(autoscroll), cx, |s| {
 6897            let line_mode = s.line_mode;
 6898            s.move_with(|map, selection| {
 6899                if !selection.is_empty() && !line_mode {
 6900                    selection.goal = SelectionGoal::None;
 6901                }
 6902                let (cursor, goal) = movement::up_by_rows(
 6903                    map,
 6904                    selection.end,
 6905                    row_count,
 6906                    selection.goal,
 6907                    false,
 6908                    &text_layout_details,
 6909                );
 6910                selection.collapse_to(cursor, goal);
 6911            });
 6912        });
 6913    }
 6914
 6915    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 6916        let text_layout_details = &self.text_layout_details(cx);
 6917        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6918            s.move_heads_with(|map, head, goal| {
 6919                movement::up(map, head, goal, false, &text_layout_details)
 6920            })
 6921        })
 6922    }
 6923
 6924    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 6925        self.take_rename(true, cx);
 6926
 6927        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6928            cx.propagate();
 6929            return;
 6930        }
 6931
 6932        let text_layout_details = &self.text_layout_details(cx);
 6933        let selection_count = self.selections.count();
 6934        let first_selection = self.selections.first_anchor();
 6935
 6936        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6937            let line_mode = s.line_mode;
 6938            s.move_with(|map, selection| {
 6939                if !selection.is_empty() && !line_mode {
 6940                    selection.goal = SelectionGoal::None;
 6941                }
 6942                let (cursor, goal) = movement::down(
 6943                    map,
 6944                    selection.end,
 6945                    selection.goal,
 6946                    false,
 6947                    &text_layout_details,
 6948                );
 6949                selection.collapse_to(cursor, goal);
 6950            });
 6951        });
 6952
 6953        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6954        {
 6955            cx.propagate();
 6956        }
 6957    }
 6958
 6959    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 6960        let Some(row_count) = self.visible_row_count() else {
 6961            return;
 6962        };
 6963
 6964        let text_layout_details = &self.text_layout_details(cx);
 6965
 6966        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6967            s.move_heads_with(|map, head, goal| {
 6968                movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
 6969            })
 6970        })
 6971    }
 6972
 6973    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 6974        if self.take_rename(true, cx).is_some() {
 6975            return;
 6976        }
 6977
 6978        if self
 6979            .context_menu
 6980            .write()
 6981            .as_mut()
 6982            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 6983            .unwrap_or(false)
 6984        {
 6985            return;
 6986        }
 6987
 6988        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6989            cx.propagate();
 6990            return;
 6991        }
 6992
 6993        let Some(row_count) = self.visible_row_count() else {
 6994            return;
 6995        };
 6996
 6997        let autoscroll = if action.center_cursor {
 6998            Autoscroll::center()
 6999        } else {
 7000            Autoscroll::fit()
 7001        };
 7002
 7003        let text_layout_details = &self.text_layout_details(cx);
 7004        self.change_selections(Some(autoscroll), cx, |s| {
 7005            let line_mode = s.line_mode;
 7006            s.move_with(|map, selection| {
 7007                if !selection.is_empty() && !line_mode {
 7008                    selection.goal = SelectionGoal::None;
 7009                }
 7010                let (cursor, goal) = movement::down_by_rows(
 7011                    map,
 7012                    selection.end,
 7013                    row_count,
 7014                    selection.goal,
 7015                    false,
 7016                    &text_layout_details,
 7017                );
 7018                selection.collapse_to(cursor, goal);
 7019            });
 7020        });
 7021    }
 7022
 7023    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7024        let text_layout_details = &self.text_layout_details(cx);
 7025        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7026            s.move_heads_with(|map, head, goal| {
 7027                movement::down(map, head, goal, false, &text_layout_details)
 7028            })
 7029        });
 7030    }
 7031
 7032    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7033        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7034            context_menu.select_first(self.project.as_ref(), cx);
 7035        }
 7036    }
 7037
 7038    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7039        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7040            context_menu.select_prev(self.project.as_ref(), cx);
 7041        }
 7042    }
 7043
 7044    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7045        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7046            context_menu.select_next(self.project.as_ref(), cx);
 7047        }
 7048    }
 7049
 7050    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7051        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7052            context_menu.select_last(self.project.as_ref(), cx);
 7053        }
 7054    }
 7055
 7056    pub fn move_to_previous_word_start(
 7057        &mut self,
 7058        _: &MoveToPreviousWordStart,
 7059        cx: &mut ViewContext<Self>,
 7060    ) {
 7061        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7062            s.move_cursors_with(|map, head, _| {
 7063                (
 7064                    movement::previous_word_start(map, head),
 7065                    SelectionGoal::None,
 7066                )
 7067            });
 7068        })
 7069    }
 7070
 7071    pub fn move_to_previous_subword_start(
 7072        &mut self,
 7073        _: &MoveToPreviousSubwordStart,
 7074        cx: &mut ViewContext<Self>,
 7075    ) {
 7076        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7077            s.move_cursors_with(|map, head, _| {
 7078                (
 7079                    movement::previous_subword_start(map, head),
 7080                    SelectionGoal::None,
 7081                )
 7082            });
 7083        })
 7084    }
 7085
 7086    pub fn select_to_previous_word_start(
 7087        &mut self,
 7088        _: &SelectToPreviousWordStart,
 7089        cx: &mut ViewContext<Self>,
 7090    ) {
 7091        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7092            s.move_heads_with(|map, head, _| {
 7093                (
 7094                    movement::previous_word_start(map, head),
 7095                    SelectionGoal::None,
 7096                )
 7097            });
 7098        })
 7099    }
 7100
 7101    pub fn select_to_previous_subword_start(
 7102        &mut self,
 7103        _: &SelectToPreviousSubwordStart,
 7104        cx: &mut ViewContext<Self>,
 7105    ) {
 7106        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7107            s.move_heads_with(|map, head, _| {
 7108                (
 7109                    movement::previous_subword_start(map, head),
 7110                    SelectionGoal::None,
 7111                )
 7112            });
 7113        })
 7114    }
 7115
 7116    pub fn delete_to_previous_word_start(
 7117        &mut self,
 7118        _: &DeleteToPreviousWordStart,
 7119        cx: &mut ViewContext<Self>,
 7120    ) {
 7121        self.transact(cx, |this, cx| {
 7122            this.select_autoclose_pair(cx);
 7123            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7124                let line_mode = s.line_mode;
 7125                s.move_with(|map, selection| {
 7126                    if selection.is_empty() && !line_mode {
 7127                        let cursor = movement::previous_word_start(map, selection.head());
 7128                        selection.set_head(cursor, SelectionGoal::None);
 7129                    }
 7130                });
 7131            });
 7132            this.insert("", cx);
 7133        });
 7134    }
 7135
 7136    pub fn delete_to_previous_subword_start(
 7137        &mut self,
 7138        _: &DeleteToPreviousSubwordStart,
 7139        cx: &mut ViewContext<Self>,
 7140    ) {
 7141        self.transact(cx, |this, cx| {
 7142            this.select_autoclose_pair(cx);
 7143            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7144                let line_mode = s.line_mode;
 7145                s.move_with(|map, selection| {
 7146                    if selection.is_empty() && !line_mode {
 7147                        let cursor = movement::previous_subword_start(map, selection.head());
 7148                        selection.set_head(cursor, SelectionGoal::None);
 7149                    }
 7150                });
 7151            });
 7152            this.insert("", cx);
 7153        });
 7154    }
 7155
 7156    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7157        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7158            s.move_cursors_with(|map, head, _| {
 7159                (movement::next_word_end(map, head), SelectionGoal::None)
 7160            });
 7161        })
 7162    }
 7163
 7164    pub fn move_to_next_subword_end(
 7165        &mut self,
 7166        _: &MoveToNextSubwordEnd,
 7167        cx: &mut ViewContext<Self>,
 7168    ) {
 7169        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7170            s.move_cursors_with(|map, head, _| {
 7171                (movement::next_subword_end(map, head), SelectionGoal::None)
 7172            });
 7173        })
 7174    }
 7175
 7176    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7177        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7178            s.move_heads_with(|map, head, _| {
 7179                (movement::next_word_end(map, head), SelectionGoal::None)
 7180            });
 7181        })
 7182    }
 7183
 7184    pub fn select_to_next_subword_end(
 7185        &mut self,
 7186        _: &SelectToNextSubwordEnd,
 7187        cx: &mut ViewContext<Self>,
 7188    ) {
 7189        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7190            s.move_heads_with(|map, head, _| {
 7191                (movement::next_subword_end(map, head), SelectionGoal::None)
 7192            });
 7193        })
 7194    }
 7195
 7196    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
 7197        self.transact(cx, |this, cx| {
 7198            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7199                let line_mode = s.line_mode;
 7200                s.move_with(|map, selection| {
 7201                    if selection.is_empty() && !line_mode {
 7202                        let cursor = movement::next_word_end(map, selection.head());
 7203                        selection.set_head(cursor, SelectionGoal::None);
 7204                    }
 7205                });
 7206            });
 7207            this.insert("", cx);
 7208        });
 7209    }
 7210
 7211    pub fn delete_to_next_subword_end(
 7212        &mut self,
 7213        _: &DeleteToNextSubwordEnd,
 7214        cx: &mut ViewContext<Self>,
 7215    ) {
 7216        self.transact(cx, |this, cx| {
 7217            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7218                s.move_with(|map, selection| {
 7219                    if selection.is_empty() {
 7220                        let cursor = movement::next_subword_end(map, selection.head());
 7221                        selection.set_head(cursor, SelectionGoal::None);
 7222                    }
 7223                });
 7224            });
 7225            this.insert("", cx);
 7226        });
 7227    }
 7228
 7229    pub fn move_to_beginning_of_line(
 7230        &mut self,
 7231        action: &MoveToBeginningOfLine,
 7232        cx: &mut ViewContext<Self>,
 7233    ) {
 7234        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7235            s.move_cursors_with(|map, head, _| {
 7236                (
 7237                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7238                    SelectionGoal::None,
 7239                )
 7240            });
 7241        })
 7242    }
 7243
 7244    pub fn select_to_beginning_of_line(
 7245        &mut self,
 7246        action: &SelectToBeginningOfLine,
 7247        cx: &mut ViewContext<Self>,
 7248    ) {
 7249        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7250            s.move_heads_with(|map, head, _| {
 7251                (
 7252                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7253                    SelectionGoal::None,
 7254                )
 7255            });
 7256        });
 7257    }
 7258
 7259    pub fn delete_to_beginning_of_line(
 7260        &mut self,
 7261        _: &DeleteToBeginningOfLine,
 7262        cx: &mut ViewContext<Self>,
 7263    ) {
 7264        self.transact(cx, |this, cx| {
 7265            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7266                s.move_with(|_, selection| {
 7267                    selection.reversed = true;
 7268                });
 7269            });
 7270
 7271            this.select_to_beginning_of_line(
 7272                &SelectToBeginningOfLine {
 7273                    stop_at_soft_wraps: false,
 7274                },
 7275                cx,
 7276            );
 7277            this.backspace(&Backspace, cx);
 7278        });
 7279    }
 7280
 7281    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7282        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7283            s.move_cursors_with(|map, head, _| {
 7284                (
 7285                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7286                    SelectionGoal::None,
 7287                )
 7288            });
 7289        })
 7290    }
 7291
 7292    pub fn select_to_end_of_line(
 7293        &mut self,
 7294        action: &SelectToEndOfLine,
 7295        cx: &mut ViewContext<Self>,
 7296    ) {
 7297        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7298            s.move_heads_with(|map, head, _| {
 7299                (
 7300                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7301                    SelectionGoal::None,
 7302                )
 7303            });
 7304        })
 7305    }
 7306
 7307    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7308        self.transact(cx, |this, cx| {
 7309            this.select_to_end_of_line(
 7310                &SelectToEndOfLine {
 7311                    stop_at_soft_wraps: false,
 7312                },
 7313                cx,
 7314            );
 7315            this.delete(&Delete, cx);
 7316        });
 7317    }
 7318
 7319    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7320        self.transact(cx, |this, cx| {
 7321            this.select_to_end_of_line(
 7322                &SelectToEndOfLine {
 7323                    stop_at_soft_wraps: false,
 7324                },
 7325                cx,
 7326            );
 7327            this.cut(&Cut, cx);
 7328        });
 7329    }
 7330
 7331    pub fn move_to_start_of_paragraph(
 7332        &mut self,
 7333        _: &MoveToStartOfParagraph,
 7334        cx: &mut ViewContext<Self>,
 7335    ) {
 7336        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7337            cx.propagate();
 7338            return;
 7339        }
 7340
 7341        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7342            s.move_with(|map, selection| {
 7343                selection.collapse_to(
 7344                    movement::start_of_paragraph(map, selection.head(), 1),
 7345                    SelectionGoal::None,
 7346                )
 7347            });
 7348        })
 7349    }
 7350
 7351    pub fn move_to_end_of_paragraph(
 7352        &mut self,
 7353        _: &MoveToEndOfParagraph,
 7354        cx: &mut ViewContext<Self>,
 7355    ) {
 7356        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7357            cx.propagate();
 7358            return;
 7359        }
 7360
 7361        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7362            s.move_with(|map, selection| {
 7363                selection.collapse_to(
 7364                    movement::end_of_paragraph(map, selection.head(), 1),
 7365                    SelectionGoal::None,
 7366                )
 7367            });
 7368        })
 7369    }
 7370
 7371    pub fn select_to_start_of_paragraph(
 7372        &mut self,
 7373        _: &SelectToStartOfParagraph,
 7374        cx: &mut ViewContext<Self>,
 7375    ) {
 7376        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7377            cx.propagate();
 7378            return;
 7379        }
 7380
 7381        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7382            s.move_heads_with(|map, head, _| {
 7383                (
 7384                    movement::start_of_paragraph(map, head, 1),
 7385                    SelectionGoal::None,
 7386                )
 7387            });
 7388        })
 7389    }
 7390
 7391    pub fn select_to_end_of_paragraph(
 7392        &mut self,
 7393        _: &SelectToEndOfParagraph,
 7394        cx: &mut ViewContext<Self>,
 7395    ) {
 7396        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7397            cx.propagate();
 7398            return;
 7399        }
 7400
 7401        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7402            s.move_heads_with(|map, head, _| {
 7403                (
 7404                    movement::end_of_paragraph(map, head, 1),
 7405                    SelectionGoal::None,
 7406                )
 7407            });
 7408        })
 7409    }
 7410
 7411    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7412        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7413            cx.propagate();
 7414            return;
 7415        }
 7416
 7417        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7418            s.select_ranges(vec![0..0]);
 7419        });
 7420    }
 7421
 7422    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7423        let mut selection = self.selections.last::<Point>(cx);
 7424        selection.set_head(Point::zero(), SelectionGoal::None);
 7425
 7426        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7427            s.select(vec![selection]);
 7428        });
 7429    }
 7430
 7431    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7432        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7433            cx.propagate();
 7434            return;
 7435        }
 7436
 7437        let cursor = self.buffer.read(cx).read(cx).len();
 7438        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7439            s.select_ranges(vec![cursor..cursor])
 7440        });
 7441    }
 7442
 7443    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7444        self.nav_history = nav_history;
 7445    }
 7446
 7447    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7448        self.nav_history.as_ref()
 7449    }
 7450
 7451    fn push_to_nav_history(
 7452        &mut self,
 7453        cursor_anchor: Anchor,
 7454        new_position: Option<Point>,
 7455        cx: &mut ViewContext<Self>,
 7456    ) {
 7457        if let Some(nav_history) = self.nav_history.as_mut() {
 7458            let buffer = self.buffer.read(cx).read(cx);
 7459            let cursor_position = cursor_anchor.to_point(&buffer);
 7460            let scroll_state = self.scroll_manager.anchor();
 7461            let scroll_top_row = scroll_state.top_row(&buffer);
 7462            drop(buffer);
 7463
 7464            if let Some(new_position) = new_position {
 7465                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7466                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7467                    return;
 7468                }
 7469            }
 7470
 7471            nav_history.push(
 7472                Some(NavigationData {
 7473                    cursor_anchor,
 7474                    cursor_position,
 7475                    scroll_anchor: scroll_state,
 7476                    scroll_top_row,
 7477                }),
 7478                cx,
 7479            );
 7480        }
 7481    }
 7482
 7483    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7484        let buffer = self.buffer.read(cx).snapshot(cx);
 7485        let mut selection = self.selections.first::<usize>(cx);
 7486        selection.set_head(buffer.len(), SelectionGoal::None);
 7487        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7488            s.select(vec![selection]);
 7489        });
 7490    }
 7491
 7492    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7493        let end = self.buffer.read(cx).read(cx).len();
 7494        self.change_selections(None, cx, |s| {
 7495            s.select_ranges(vec![0..end]);
 7496        });
 7497    }
 7498
 7499    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7500        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7501        let mut selections = self.selections.all::<Point>(cx);
 7502        let max_point = display_map.buffer_snapshot.max_point();
 7503        for selection in &mut selections {
 7504            let rows = selection.spanned_rows(true, &display_map);
 7505            selection.start = Point::new(rows.start.0, 0);
 7506            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7507            selection.reversed = false;
 7508        }
 7509        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7510            s.select(selections);
 7511        });
 7512    }
 7513
 7514    pub fn split_selection_into_lines(
 7515        &mut self,
 7516        _: &SplitSelectionIntoLines,
 7517        cx: &mut ViewContext<Self>,
 7518    ) {
 7519        let mut to_unfold = Vec::new();
 7520        let mut new_selection_ranges = Vec::new();
 7521        {
 7522            let selections = self.selections.all::<Point>(cx);
 7523            let buffer = self.buffer.read(cx).read(cx);
 7524            for selection in selections {
 7525                for row in selection.start.row..selection.end.row {
 7526                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7527                    new_selection_ranges.push(cursor..cursor);
 7528                }
 7529                new_selection_ranges.push(selection.end..selection.end);
 7530                to_unfold.push(selection.start..selection.end);
 7531            }
 7532        }
 7533        self.unfold_ranges(to_unfold, true, true, cx);
 7534        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7535            s.select_ranges(new_selection_ranges);
 7536        });
 7537    }
 7538
 7539    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7540        self.add_selection(true, cx);
 7541    }
 7542
 7543    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7544        self.add_selection(false, cx);
 7545    }
 7546
 7547    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7548        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7549        let mut selections = self.selections.all::<Point>(cx);
 7550        let text_layout_details = self.text_layout_details(cx);
 7551        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7552            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7553            let range = oldest_selection.display_range(&display_map).sorted();
 7554
 7555            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7556            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7557            let positions = start_x.min(end_x)..start_x.max(end_x);
 7558
 7559            selections.clear();
 7560            let mut stack = Vec::new();
 7561            for row in range.start.row().0..=range.end.row().0 {
 7562                if let Some(selection) = self.selections.build_columnar_selection(
 7563                    &display_map,
 7564                    DisplayRow(row),
 7565                    &positions,
 7566                    oldest_selection.reversed,
 7567                    &text_layout_details,
 7568                ) {
 7569                    stack.push(selection.id);
 7570                    selections.push(selection);
 7571                }
 7572            }
 7573
 7574            if above {
 7575                stack.reverse();
 7576            }
 7577
 7578            AddSelectionsState { above, stack }
 7579        });
 7580
 7581        let last_added_selection = *state.stack.last().unwrap();
 7582        let mut new_selections = Vec::new();
 7583        if above == state.above {
 7584            let end_row = if above {
 7585                DisplayRow(0)
 7586            } else {
 7587                display_map.max_point().row()
 7588            };
 7589
 7590            'outer: for selection in selections {
 7591                if selection.id == last_added_selection {
 7592                    let range = selection.display_range(&display_map).sorted();
 7593                    debug_assert_eq!(range.start.row(), range.end.row());
 7594                    let mut row = range.start.row();
 7595                    let positions =
 7596                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7597                            px(start)..px(end)
 7598                        } else {
 7599                            let start_x =
 7600                                display_map.x_for_display_point(range.start, &text_layout_details);
 7601                            let end_x =
 7602                                display_map.x_for_display_point(range.end, &text_layout_details);
 7603                            start_x.min(end_x)..start_x.max(end_x)
 7604                        };
 7605
 7606                    while row != end_row {
 7607                        if above {
 7608                            row.0 -= 1;
 7609                        } else {
 7610                            row.0 += 1;
 7611                        }
 7612
 7613                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7614                            &display_map,
 7615                            row,
 7616                            &positions,
 7617                            selection.reversed,
 7618                            &text_layout_details,
 7619                        ) {
 7620                            state.stack.push(new_selection.id);
 7621                            if above {
 7622                                new_selections.push(new_selection);
 7623                                new_selections.push(selection);
 7624                            } else {
 7625                                new_selections.push(selection);
 7626                                new_selections.push(new_selection);
 7627                            }
 7628
 7629                            continue 'outer;
 7630                        }
 7631                    }
 7632                }
 7633
 7634                new_selections.push(selection);
 7635            }
 7636        } else {
 7637            new_selections = selections;
 7638            new_selections.retain(|s| s.id != last_added_selection);
 7639            state.stack.pop();
 7640        }
 7641
 7642        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7643            s.select(new_selections);
 7644        });
 7645        if state.stack.len() > 1 {
 7646            self.add_selections_state = Some(state);
 7647        }
 7648    }
 7649
 7650    pub fn select_next_match_internal(
 7651        &mut self,
 7652        display_map: &DisplaySnapshot,
 7653        replace_newest: bool,
 7654        autoscroll: Option<Autoscroll>,
 7655        cx: &mut ViewContext<Self>,
 7656    ) -> Result<()> {
 7657        fn select_next_match_ranges(
 7658            this: &mut Editor,
 7659            range: Range<usize>,
 7660            replace_newest: bool,
 7661            auto_scroll: Option<Autoscroll>,
 7662            cx: &mut ViewContext<Editor>,
 7663        ) {
 7664            this.unfold_ranges([range.clone()], false, true, cx);
 7665            this.change_selections(auto_scroll, cx, |s| {
 7666                if replace_newest {
 7667                    s.delete(s.newest_anchor().id);
 7668                }
 7669                s.insert_range(range.clone());
 7670            });
 7671        }
 7672
 7673        let buffer = &display_map.buffer_snapshot;
 7674        let mut selections = self.selections.all::<usize>(cx);
 7675        if let Some(mut select_next_state) = self.select_next_state.take() {
 7676            let query = &select_next_state.query;
 7677            if !select_next_state.done {
 7678                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7679                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7680                let mut next_selected_range = None;
 7681
 7682                let bytes_after_last_selection =
 7683                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7684                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7685                let query_matches = query
 7686                    .stream_find_iter(bytes_after_last_selection)
 7687                    .map(|result| (last_selection.end, result))
 7688                    .chain(
 7689                        query
 7690                            .stream_find_iter(bytes_before_first_selection)
 7691                            .map(|result| (0, result)),
 7692                    );
 7693
 7694                for (start_offset, query_match) in query_matches {
 7695                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7696                    let offset_range =
 7697                        start_offset + query_match.start()..start_offset + query_match.end();
 7698                    let display_range = offset_range.start.to_display_point(&display_map)
 7699                        ..offset_range.end.to_display_point(&display_map);
 7700
 7701                    if !select_next_state.wordwise
 7702                        || (!movement::is_inside_word(&display_map, display_range.start)
 7703                            && !movement::is_inside_word(&display_map, display_range.end))
 7704                    {
 7705                        // TODO: This is n^2, because we might check all the selections
 7706                        if !selections
 7707                            .iter()
 7708                            .any(|selection| selection.range().overlaps(&offset_range))
 7709                        {
 7710                            next_selected_range = Some(offset_range);
 7711                            break;
 7712                        }
 7713                    }
 7714                }
 7715
 7716                if let Some(next_selected_range) = next_selected_range {
 7717                    select_next_match_ranges(
 7718                        self,
 7719                        next_selected_range,
 7720                        replace_newest,
 7721                        autoscroll,
 7722                        cx,
 7723                    );
 7724                } else {
 7725                    select_next_state.done = true;
 7726                }
 7727            }
 7728
 7729            self.select_next_state = Some(select_next_state);
 7730        } else {
 7731            let mut only_carets = true;
 7732            let mut same_text_selected = true;
 7733            let mut selected_text = None;
 7734
 7735            let mut selections_iter = selections.iter().peekable();
 7736            while let Some(selection) = selections_iter.next() {
 7737                if selection.start != selection.end {
 7738                    only_carets = false;
 7739                }
 7740
 7741                if same_text_selected {
 7742                    if selected_text.is_none() {
 7743                        selected_text =
 7744                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7745                    }
 7746
 7747                    if let Some(next_selection) = selections_iter.peek() {
 7748                        if next_selection.range().len() == selection.range().len() {
 7749                            let next_selected_text = buffer
 7750                                .text_for_range(next_selection.range())
 7751                                .collect::<String>();
 7752                            if Some(next_selected_text) != selected_text {
 7753                                same_text_selected = false;
 7754                                selected_text = None;
 7755                            }
 7756                        } else {
 7757                            same_text_selected = false;
 7758                            selected_text = None;
 7759                        }
 7760                    }
 7761                }
 7762            }
 7763
 7764            if only_carets {
 7765                for selection in &mut selections {
 7766                    let word_range = movement::surrounding_word(
 7767                        &display_map,
 7768                        selection.start.to_display_point(&display_map),
 7769                    );
 7770                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7771                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7772                    selection.goal = SelectionGoal::None;
 7773                    selection.reversed = false;
 7774                    select_next_match_ranges(
 7775                        self,
 7776                        selection.start..selection.end,
 7777                        replace_newest,
 7778                        autoscroll,
 7779                        cx,
 7780                    );
 7781                }
 7782
 7783                if selections.len() == 1 {
 7784                    let selection = selections
 7785                        .last()
 7786                        .expect("ensured that there's only one selection");
 7787                    let query = buffer
 7788                        .text_for_range(selection.start..selection.end)
 7789                        .collect::<String>();
 7790                    let is_empty = query.is_empty();
 7791                    let select_state = SelectNextState {
 7792                        query: AhoCorasick::new(&[query])?,
 7793                        wordwise: true,
 7794                        done: is_empty,
 7795                    };
 7796                    self.select_next_state = Some(select_state);
 7797                } else {
 7798                    self.select_next_state = None;
 7799                }
 7800            } else if let Some(selected_text) = selected_text {
 7801                self.select_next_state = Some(SelectNextState {
 7802                    query: AhoCorasick::new(&[selected_text])?,
 7803                    wordwise: false,
 7804                    done: false,
 7805                });
 7806                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 7807            }
 7808        }
 7809        Ok(())
 7810    }
 7811
 7812    pub fn select_all_matches(
 7813        &mut self,
 7814        _action: &SelectAllMatches,
 7815        cx: &mut ViewContext<Self>,
 7816    ) -> Result<()> {
 7817        self.push_to_selection_history();
 7818        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7819
 7820        self.select_next_match_internal(&display_map, false, None, cx)?;
 7821        let Some(select_next_state) = self.select_next_state.as_mut() else {
 7822            return Ok(());
 7823        };
 7824        if select_next_state.done {
 7825            return Ok(());
 7826        }
 7827
 7828        let mut new_selections = self.selections.all::<usize>(cx);
 7829
 7830        let buffer = &display_map.buffer_snapshot;
 7831        let query_matches = select_next_state
 7832            .query
 7833            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 7834
 7835        for query_match in query_matches {
 7836            let query_match = query_match.unwrap(); // can only fail due to I/O
 7837            let offset_range = query_match.start()..query_match.end();
 7838            let display_range = offset_range.start.to_display_point(&display_map)
 7839                ..offset_range.end.to_display_point(&display_map);
 7840
 7841            if !select_next_state.wordwise
 7842                || (!movement::is_inside_word(&display_map, display_range.start)
 7843                    && !movement::is_inside_word(&display_map, display_range.end))
 7844            {
 7845                self.selections.change_with(cx, |selections| {
 7846                    new_selections.push(Selection {
 7847                        id: selections.new_selection_id(),
 7848                        start: offset_range.start,
 7849                        end: offset_range.end,
 7850                        reversed: false,
 7851                        goal: SelectionGoal::None,
 7852                    });
 7853                });
 7854            }
 7855        }
 7856
 7857        new_selections.sort_by_key(|selection| selection.start);
 7858        let mut ix = 0;
 7859        while ix + 1 < new_selections.len() {
 7860            let current_selection = &new_selections[ix];
 7861            let next_selection = &new_selections[ix + 1];
 7862            if current_selection.range().overlaps(&next_selection.range()) {
 7863                if current_selection.id < next_selection.id {
 7864                    new_selections.remove(ix + 1);
 7865                } else {
 7866                    new_selections.remove(ix);
 7867                }
 7868            } else {
 7869                ix += 1;
 7870            }
 7871        }
 7872
 7873        select_next_state.done = true;
 7874        self.unfold_ranges(
 7875            new_selections.iter().map(|selection| selection.range()),
 7876            false,
 7877            false,
 7878            cx,
 7879        );
 7880        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 7881            selections.select(new_selections)
 7882        });
 7883
 7884        Ok(())
 7885    }
 7886
 7887    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 7888        self.push_to_selection_history();
 7889        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7890        self.select_next_match_internal(
 7891            &display_map,
 7892            action.replace_newest,
 7893            Some(Autoscroll::newest()),
 7894            cx,
 7895        )?;
 7896        Ok(())
 7897    }
 7898
 7899    pub fn select_previous(
 7900        &mut self,
 7901        action: &SelectPrevious,
 7902        cx: &mut ViewContext<Self>,
 7903    ) -> Result<()> {
 7904        self.push_to_selection_history();
 7905        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7906        let buffer = &display_map.buffer_snapshot;
 7907        let mut selections = self.selections.all::<usize>(cx);
 7908        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 7909            let query = &select_prev_state.query;
 7910            if !select_prev_state.done {
 7911                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7912                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7913                let mut next_selected_range = None;
 7914                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 7915                let bytes_before_last_selection =
 7916                    buffer.reversed_bytes_in_range(0..last_selection.start);
 7917                let bytes_after_first_selection =
 7918                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 7919                let query_matches = query
 7920                    .stream_find_iter(bytes_before_last_selection)
 7921                    .map(|result| (last_selection.start, result))
 7922                    .chain(
 7923                        query
 7924                            .stream_find_iter(bytes_after_first_selection)
 7925                            .map(|result| (buffer.len(), result)),
 7926                    );
 7927                for (end_offset, query_match) in query_matches {
 7928                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7929                    let offset_range =
 7930                        end_offset - query_match.end()..end_offset - query_match.start();
 7931                    let display_range = offset_range.start.to_display_point(&display_map)
 7932                        ..offset_range.end.to_display_point(&display_map);
 7933
 7934                    if !select_prev_state.wordwise
 7935                        || (!movement::is_inside_word(&display_map, display_range.start)
 7936                            && !movement::is_inside_word(&display_map, display_range.end))
 7937                    {
 7938                        next_selected_range = Some(offset_range);
 7939                        break;
 7940                    }
 7941                }
 7942
 7943                if let Some(next_selected_range) = next_selected_range {
 7944                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 7945                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7946                        if action.replace_newest {
 7947                            s.delete(s.newest_anchor().id);
 7948                        }
 7949                        s.insert_range(next_selected_range);
 7950                    });
 7951                } else {
 7952                    select_prev_state.done = true;
 7953                }
 7954            }
 7955
 7956            self.select_prev_state = Some(select_prev_state);
 7957        } else {
 7958            let mut only_carets = true;
 7959            let mut same_text_selected = true;
 7960            let mut selected_text = None;
 7961
 7962            let mut selections_iter = selections.iter().peekable();
 7963            while let Some(selection) = selections_iter.next() {
 7964                if selection.start != selection.end {
 7965                    only_carets = false;
 7966                }
 7967
 7968                if same_text_selected {
 7969                    if selected_text.is_none() {
 7970                        selected_text =
 7971                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7972                    }
 7973
 7974                    if let Some(next_selection) = selections_iter.peek() {
 7975                        if next_selection.range().len() == selection.range().len() {
 7976                            let next_selected_text = buffer
 7977                                .text_for_range(next_selection.range())
 7978                                .collect::<String>();
 7979                            if Some(next_selected_text) != selected_text {
 7980                                same_text_selected = false;
 7981                                selected_text = None;
 7982                            }
 7983                        } else {
 7984                            same_text_selected = false;
 7985                            selected_text = None;
 7986                        }
 7987                    }
 7988                }
 7989            }
 7990
 7991            if only_carets {
 7992                for selection in &mut selections {
 7993                    let word_range = movement::surrounding_word(
 7994                        &display_map,
 7995                        selection.start.to_display_point(&display_map),
 7996                    );
 7997                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7998                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7999                    selection.goal = SelectionGoal::None;
 8000                    selection.reversed = false;
 8001                }
 8002                if selections.len() == 1 {
 8003                    let selection = selections
 8004                        .last()
 8005                        .expect("ensured that there's only one selection");
 8006                    let query = buffer
 8007                        .text_for_range(selection.start..selection.end)
 8008                        .collect::<String>();
 8009                    let is_empty = query.is_empty();
 8010                    let select_state = SelectNextState {
 8011                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8012                        wordwise: true,
 8013                        done: is_empty,
 8014                    };
 8015                    self.select_prev_state = Some(select_state);
 8016                } else {
 8017                    self.select_prev_state = None;
 8018                }
 8019
 8020                self.unfold_ranges(
 8021                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8022                    false,
 8023                    true,
 8024                    cx,
 8025                );
 8026                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8027                    s.select(selections);
 8028                });
 8029            } else if let Some(selected_text) = selected_text {
 8030                self.select_prev_state = Some(SelectNextState {
 8031                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8032                    wordwise: false,
 8033                    done: false,
 8034                });
 8035                self.select_previous(action, cx)?;
 8036            }
 8037        }
 8038        Ok(())
 8039    }
 8040
 8041    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8042        let text_layout_details = &self.text_layout_details(cx);
 8043        self.transact(cx, |this, cx| {
 8044            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8045            let mut edits = Vec::new();
 8046            let mut selection_edit_ranges = Vec::new();
 8047            let mut last_toggled_row = None;
 8048            let snapshot = this.buffer.read(cx).read(cx);
 8049            let empty_str: Arc<str> = "".into();
 8050            let mut suffixes_inserted = Vec::new();
 8051
 8052            fn comment_prefix_range(
 8053                snapshot: &MultiBufferSnapshot,
 8054                row: MultiBufferRow,
 8055                comment_prefix: &str,
 8056                comment_prefix_whitespace: &str,
 8057            ) -> Range<Point> {
 8058                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8059
 8060                let mut line_bytes = snapshot
 8061                    .bytes_in_range(start..snapshot.max_point())
 8062                    .flatten()
 8063                    .copied();
 8064
 8065                // If this line currently begins with the line comment prefix, then record
 8066                // the range containing the prefix.
 8067                if line_bytes
 8068                    .by_ref()
 8069                    .take(comment_prefix.len())
 8070                    .eq(comment_prefix.bytes())
 8071                {
 8072                    // Include any whitespace that matches the comment prefix.
 8073                    let matching_whitespace_len = line_bytes
 8074                        .zip(comment_prefix_whitespace.bytes())
 8075                        .take_while(|(a, b)| a == b)
 8076                        .count() as u32;
 8077                    let end = Point::new(
 8078                        start.row,
 8079                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8080                    );
 8081                    start..end
 8082                } else {
 8083                    start..start
 8084                }
 8085            }
 8086
 8087            fn comment_suffix_range(
 8088                snapshot: &MultiBufferSnapshot,
 8089                row: MultiBufferRow,
 8090                comment_suffix: &str,
 8091                comment_suffix_has_leading_space: bool,
 8092            ) -> Range<Point> {
 8093                let end = Point::new(row.0, snapshot.line_len(row));
 8094                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8095
 8096                let mut line_end_bytes = snapshot
 8097                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8098                    .flatten()
 8099                    .copied();
 8100
 8101                let leading_space_len = if suffix_start_column > 0
 8102                    && line_end_bytes.next() == Some(b' ')
 8103                    && comment_suffix_has_leading_space
 8104                {
 8105                    1
 8106                } else {
 8107                    0
 8108                };
 8109
 8110                // If this line currently begins with the line comment prefix, then record
 8111                // the range containing the prefix.
 8112                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8113                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8114                    start..end
 8115                } else {
 8116                    end..end
 8117                }
 8118            }
 8119
 8120            // TODO: Handle selections that cross excerpts
 8121            for selection in &mut selections {
 8122                let start_column = snapshot
 8123                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8124                    .len;
 8125                let language = if let Some(language) =
 8126                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8127                {
 8128                    language
 8129                } else {
 8130                    continue;
 8131                };
 8132
 8133                selection_edit_ranges.clear();
 8134
 8135                // If multiple selections contain a given row, avoid processing that
 8136                // row more than once.
 8137                let mut start_row = MultiBufferRow(selection.start.row);
 8138                if last_toggled_row == Some(start_row) {
 8139                    start_row = start_row.next_row();
 8140                }
 8141                let end_row =
 8142                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8143                        MultiBufferRow(selection.end.row - 1)
 8144                    } else {
 8145                        MultiBufferRow(selection.end.row)
 8146                    };
 8147                last_toggled_row = Some(end_row);
 8148
 8149                if start_row > end_row {
 8150                    continue;
 8151                }
 8152
 8153                // If the language has line comments, toggle those.
 8154                let full_comment_prefixes = language.line_comment_prefixes();
 8155                if !full_comment_prefixes.is_empty() {
 8156                    let first_prefix = full_comment_prefixes
 8157                        .first()
 8158                        .expect("prefixes is non-empty");
 8159                    let prefix_trimmed_lengths = full_comment_prefixes
 8160                        .iter()
 8161                        .map(|p| p.trim_end_matches(' ').len())
 8162                        .collect::<SmallVec<[usize; 4]>>();
 8163
 8164                    let mut all_selection_lines_are_comments = true;
 8165
 8166                    for row in start_row.0..=end_row.0 {
 8167                        let row = MultiBufferRow(row);
 8168                        if start_row < end_row && snapshot.is_line_blank(row) {
 8169                            continue;
 8170                        }
 8171
 8172                        let prefix_range = full_comment_prefixes
 8173                            .iter()
 8174                            .zip(prefix_trimmed_lengths.iter().copied())
 8175                            .map(|(prefix, trimmed_prefix_len)| {
 8176                                comment_prefix_range(
 8177                                    snapshot.deref(),
 8178                                    row,
 8179                                    &prefix[..trimmed_prefix_len],
 8180                                    &prefix[trimmed_prefix_len..],
 8181                                )
 8182                            })
 8183                            .max_by_key(|range| range.end.column - range.start.column)
 8184                            .expect("prefixes is non-empty");
 8185
 8186                        if prefix_range.is_empty() {
 8187                            all_selection_lines_are_comments = false;
 8188                        }
 8189
 8190                        selection_edit_ranges.push(prefix_range);
 8191                    }
 8192
 8193                    if all_selection_lines_are_comments {
 8194                        edits.extend(
 8195                            selection_edit_ranges
 8196                                .iter()
 8197                                .cloned()
 8198                                .map(|range| (range, empty_str.clone())),
 8199                        );
 8200                    } else {
 8201                        let min_column = selection_edit_ranges
 8202                            .iter()
 8203                            .map(|range| range.start.column)
 8204                            .min()
 8205                            .unwrap_or(0);
 8206                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8207                            let position = Point::new(range.start.row, min_column);
 8208                            (position..position, first_prefix.clone())
 8209                        }));
 8210                    }
 8211                } else if let Some((full_comment_prefix, comment_suffix)) =
 8212                    language.block_comment_delimiters()
 8213                {
 8214                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8215                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8216                    let prefix_range = comment_prefix_range(
 8217                        snapshot.deref(),
 8218                        start_row,
 8219                        comment_prefix,
 8220                        comment_prefix_whitespace,
 8221                    );
 8222                    let suffix_range = comment_suffix_range(
 8223                        snapshot.deref(),
 8224                        end_row,
 8225                        comment_suffix.trim_start_matches(' '),
 8226                        comment_suffix.starts_with(' '),
 8227                    );
 8228
 8229                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8230                        edits.push((
 8231                            prefix_range.start..prefix_range.start,
 8232                            full_comment_prefix.clone(),
 8233                        ));
 8234                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8235                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8236                    } else {
 8237                        edits.push((prefix_range, empty_str.clone()));
 8238                        edits.push((suffix_range, empty_str.clone()));
 8239                    }
 8240                } else {
 8241                    continue;
 8242                }
 8243            }
 8244
 8245            drop(snapshot);
 8246            this.buffer.update(cx, |buffer, cx| {
 8247                buffer.edit(edits, None, cx);
 8248            });
 8249
 8250            // Adjust selections so that they end before any comment suffixes that
 8251            // were inserted.
 8252            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8253            let mut selections = this.selections.all::<Point>(cx);
 8254            let snapshot = this.buffer.read(cx).read(cx);
 8255            for selection in &mut selections {
 8256                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8257                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8258                        Ordering::Less => {
 8259                            suffixes_inserted.next();
 8260                            continue;
 8261                        }
 8262                        Ordering::Greater => break,
 8263                        Ordering::Equal => {
 8264                            if selection.end.column == snapshot.line_len(row) {
 8265                                if selection.is_empty() {
 8266                                    selection.start.column -= suffix_len as u32;
 8267                                }
 8268                                selection.end.column -= suffix_len as u32;
 8269                            }
 8270                            break;
 8271                        }
 8272                    }
 8273                }
 8274            }
 8275
 8276            drop(snapshot);
 8277            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8278
 8279            let selections = this.selections.all::<Point>(cx);
 8280            let selections_on_single_row = selections.windows(2).all(|selections| {
 8281                selections[0].start.row == selections[1].start.row
 8282                    && selections[0].end.row == selections[1].end.row
 8283                    && selections[0].start.row == selections[0].end.row
 8284            });
 8285            let selections_selecting = selections
 8286                .iter()
 8287                .any(|selection| selection.start != selection.end);
 8288            let advance_downwards = action.advance_downwards
 8289                && selections_on_single_row
 8290                && !selections_selecting
 8291                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8292
 8293            if advance_downwards {
 8294                let snapshot = this.buffer.read(cx).snapshot(cx);
 8295
 8296                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8297                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8298                        let mut point = display_point.to_point(display_snapshot);
 8299                        point.row += 1;
 8300                        point = snapshot.clip_point(point, Bias::Left);
 8301                        let display_point = point.to_display_point(display_snapshot);
 8302                        let goal = SelectionGoal::HorizontalPosition(
 8303                            display_snapshot
 8304                                .x_for_display_point(display_point, &text_layout_details)
 8305                                .into(),
 8306                        );
 8307                        (display_point, goal)
 8308                    })
 8309                });
 8310            }
 8311        });
 8312    }
 8313
 8314    pub fn select_enclosing_symbol(
 8315        &mut self,
 8316        _: &SelectEnclosingSymbol,
 8317        cx: &mut ViewContext<Self>,
 8318    ) {
 8319        let buffer = self.buffer.read(cx).snapshot(cx);
 8320        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8321
 8322        fn update_selection(
 8323            selection: &Selection<usize>,
 8324            buffer_snap: &MultiBufferSnapshot,
 8325        ) -> Option<Selection<usize>> {
 8326            let cursor = selection.head();
 8327            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8328            for symbol in symbols.iter().rev() {
 8329                let start = symbol.range.start.to_offset(&buffer_snap);
 8330                let end = symbol.range.end.to_offset(&buffer_snap);
 8331                let new_range = start..end;
 8332                if start < selection.start || end > selection.end {
 8333                    return Some(Selection {
 8334                        id: selection.id,
 8335                        start: new_range.start,
 8336                        end: new_range.end,
 8337                        goal: SelectionGoal::None,
 8338                        reversed: selection.reversed,
 8339                    });
 8340                }
 8341            }
 8342            None
 8343        }
 8344
 8345        let mut selected_larger_symbol = false;
 8346        let new_selections = old_selections
 8347            .iter()
 8348            .map(|selection| match update_selection(selection, &buffer) {
 8349                Some(new_selection) => {
 8350                    if new_selection.range() != selection.range() {
 8351                        selected_larger_symbol = true;
 8352                    }
 8353                    new_selection
 8354                }
 8355                None => selection.clone(),
 8356            })
 8357            .collect::<Vec<_>>();
 8358
 8359        if selected_larger_symbol {
 8360            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8361                s.select(new_selections);
 8362            });
 8363        }
 8364    }
 8365
 8366    pub fn select_larger_syntax_node(
 8367        &mut self,
 8368        _: &SelectLargerSyntaxNode,
 8369        cx: &mut ViewContext<Self>,
 8370    ) {
 8371        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8372        let buffer = self.buffer.read(cx).snapshot(cx);
 8373        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8374
 8375        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8376        let mut selected_larger_node = false;
 8377        let new_selections = old_selections
 8378            .iter()
 8379            .map(|selection| {
 8380                let old_range = selection.start..selection.end;
 8381                let mut new_range = old_range.clone();
 8382                while let Some(containing_range) =
 8383                    buffer.range_for_syntax_ancestor(new_range.clone())
 8384                {
 8385                    new_range = containing_range;
 8386                    if !display_map.intersects_fold(new_range.start)
 8387                        && !display_map.intersects_fold(new_range.end)
 8388                    {
 8389                        break;
 8390                    }
 8391                }
 8392
 8393                selected_larger_node |= new_range != old_range;
 8394                Selection {
 8395                    id: selection.id,
 8396                    start: new_range.start,
 8397                    end: new_range.end,
 8398                    goal: SelectionGoal::None,
 8399                    reversed: selection.reversed,
 8400                }
 8401            })
 8402            .collect::<Vec<_>>();
 8403
 8404        if selected_larger_node {
 8405            stack.push(old_selections);
 8406            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8407                s.select(new_selections);
 8408            });
 8409        }
 8410        self.select_larger_syntax_node_stack = stack;
 8411    }
 8412
 8413    pub fn select_smaller_syntax_node(
 8414        &mut self,
 8415        _: &SelectSmallerSyntaxNode,
 8416        cx: &mut ViewContext<Self>,
 8417    ) {
 8418        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8419        if let Some(selections) = stack.pop() {
 8420            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8421                s.select(selections.to_vec());
 8422            });
 8423        }
 8424        self.select_larger_syntax_node_stack = stack;
 8425    }
 8426
 8427    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8428        if !EditorSettings::get_global(cx).gutter.runnables {
 8429            self.clear_tasks();
 8430            return Task::ready(());
 8431        }
 8432        let project = self.project.clone();
 8433        cx.spawn(|this, mut cx| async move {
 8434            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8435                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8436            }) else {
 8437                return;
 8438            };
 8439
 8440            let Some(project) = project else {
 8441                return;
 8442            };
 8443
 8444            let hide_runnables = project
 8445                .update(&mut cx, |project, cx| {
 8446                    // Do not display any test indicators in non-dev server remote projects.
 8447                    project.is_remote() && project.ssh_connection_string(cx).is_none()
 8448                })
 8449                .unwrap_or(true);
 8450            if hide_runnables {
 8451                return;
 8452            }
 8453            let new_rows =
 8454                cx.background_executor()
 8455                    .spawn({
 8456                        let snapshot = display_snapshot.clone();
 8457                        async move {
 8458                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8459                        }
 8460                    })
 8461                    .await;
 8462            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8463
 8464            this.update(&mut cx, |this, _| {
 8465                this.clear_tasks();
 8466                for (key, value) in rows {
 8467                    this.insert_tasks(key, value);
 8468                }
 8469            })
 8470            .ok();
 8471        })
 8472    }
 8473    fn fetch_runnable_ranges(
 8474        snapshot: &DisplaySnapshot,
 8475        range: Range<Anchor>,
 8476    ) -> Vec<language::RunnableRange> {
 8477        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8478    }
 8479
 8480    fn runnable_rows(
 8481        project: Model<Project>,
 8482        snapshot: DisplaySnapshot,
 8483        runnable_ranges: Vec<RunnableRange>,
 8484        mut cx: AsyncWindowContext,
 8485    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8486        runnable_ranges
 8487            .into_iter()
 8488            .filter_map(|mut runnable| {
 8489                let tasks = cx
 8490                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8491                    .ok()?;
 8492                if tasks.is_empty() {
 8493                    return None;
 8494                }
 8495
 8496                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8497
 8498                let row = snapshot
 8499                    .buffer_snapshot
 8500                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8501                    .1
 8502                    .start
 8503                    .row;
 8504
 8505                let context_range =
 8506                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8507                Some((
 8508                    (runnable.buffer_id, row),
 8509                    RunnableTasks {
 8510                        templates: tasks,
 8511                        offset: MultiBufferOffset(runnable.run_range.start),
 8512                        context_range,
 8513                        column: point.column,
 8514                        extra_variables: runnable.extra_captures,
 8515                    },
 8516                ))
 8517            })
 8518            .collect()
 8519    }
 8520
 8521    fn templates_with_tags(
 8522        project: &Model<Project>,
 8523        runnable: &mut Runnable,
 8524        cx: &WindowContext<'_>,
 8525    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8526        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8527            let (worktree_id, file) = project
 8528                .buffer_for_id(runnable.buffer)
 8529                .and_then(|buffer| buffer.read(cx).file())
 8530                .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
 8531                .unzip();
 8532
 8533            (project.task_inventory().clone(), worktree_id, file)
 8534        });
 8535
 8536        let inventory = inventory.read(cx);
 8537        let tags = mem::take(&mut runnable.tags);
 8538        let mut tags: Vec<_> = tags
 8539            .into_iter()
 8540            .flat_map(|tag| {
 8541                let tag = tag.0.clone();
 8542                inventory
 8543                    .list_tasks(
 8544                        file.clone(),
 8545                        Some(runnable.language.clone()),
 8546                        worktree_id,
 8547                        cx,
 8548                    )
 8549                    .into_iter()
 8550                    .filter(move |(_, template)| {
 8551                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8552                    })
 8553            })
 8554            .sorted_by_key(|(kind, _)| kind.to_owned())
 8555            .collect();
 8556        if let Some((leading_tag_source, _)) = tags.first() {
 8557            // Strongest source wins; if we have worktree tag binding, prefer that to
 8558            // global and language bindings;
 8559            // if we have a global binding, prefer that to language binding.
 8560            let first_mismatch = tags
 8561                .iter()
 8562                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8563            if let Some(index) = first_mismatch {
 8564                tags.truncate(index);
 8565            }
 8566        }
 8567
 8568        tags
 8569    }
 8570
 8571    pub fn move_to_enclosing_bracket(
 8572        &mut self,
 8573        _: &MoveToEnclosingBracket,
 8574        cx: &mut ViewContext<Self>,
 8575    ) {
 8576        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8577            s.move_offsets_with(|snapshot, selection| {
 8578                let Some(enclosing_bracket_ranges) =
 8579                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8580                else {
 8581                    return;
 8582                };
 8583
 8584                let mut best_length = usize::MAX;
 8585                let mut best_inside = false;
 8586                let mut best_in_bracket_range = false;
 8587                let mut best_destination = None;
 8588                for (open, close) in enclosing_bracket_ranges {
 8589                    let close = close.to_inclusive();
 8590                    let length = close.end() - open.start;
 8591                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8592                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8593                        || close.contains(&selection.head());
 8594
 8595                    // If best is next to a bracket and current isn't, skip
 8596                    if !in_bracket_range && best_in_bracket_range {
 8597                        continue;
 8598                    }
 8599
 8600                    // Prefer smaller lengths unless best is inside and current isn't
 8601                    if length > best_length && (best_inside || !inside) {
 8602                        continue;
 8603                    }
 8604
 8605                    best_length = length;
 8606                    best_inside = inside;
 8607                    best_in_bracket_range = in_bracket_range;
 8608                    best_destination = Some(
 8609                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8610                            if inside {
 8611                                open.end
 8612                            } else {
 8613                                open.start
 8614                            }
 8615                        } else {
 8616                            if inside {
 8617                                *close.start()
 8618                            } else {
 8619                                *close.end()
 8620                            }
 8621                        },
 8622                    );
 8623                }
 8624
 8625                if let Some(destination) = best_destination {
 8626                    selection.collapse_to(destination, SelectionGoal::None);
 8627                }
 8628            })
 8629        });
 8630    }
 8631
 8632    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 8633        self.end_selection(cx);
 8634        self.selection_history.mode = SelectionHistoryMode::Undoing;
 8635        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 8636            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8637            self.select_next_state = entry.select_next_state;
 8638            self.select_prev_state = entry.select_prev_state;
 8639            self.add_selections_state = entry.add_selections_state;
 8640            self.request_autoscroll(Autoscroll::newest(), cx);
 8641        }
 8642        self.selection_history.mode = SelectionHistoryMode::Normal;
 8643    }
 8644
 8645    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 8646        self.end_selection(cx);
 8647        self.selection_history.mode = SelectionHistoryMode::Redoing;
 8648        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 8649            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8650            self.select_next_state = entry.select_next_state;
 8651            self.select_prev_state = entry.select_prev_state;
 8652            self.add_selections_state = entry.add_selections_state;
 8653            self.request_autoscroll(Autoscroll::newest(), cx);
 8654        }
 8655        self.selection_history.mode = SelectionHistoryMode::Normal;
 8656    }
 8657
 8658    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 8659        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 8660    }
 8661
 8662    pub fn expand_excerpts_down(
 8663        &mut self,
 8664        action: &ExpandExcerptsDown,
 8665        cx: &mut ViewContext<Self>,
 8666    ) {
 8667        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 8668    }
 8669
 8670    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 8671        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 8672    }
 8673
 8674    pub fn expand_excerpts_for_direction(
 8675        &mut self,
 8676        lines: u32,
 8677        direction: ExpandExcerptDirection,
 8678        cx: &mut ViewContext<Self>,
 8679    ) {
 8680        let selections = self.selections.disjoint_anchors();
 8681
 8682        let lines = if lines == 0 {
 8683            EditorSettings::get_global(cx).expand_excerpt_lines
 8684        } else {
 8685            lines
 8686        };
 8687
 8688        self.buffer.update(cx, |buffer, cx| {
 8689            buffer.expand_excerpts(
 8690                selections
 8691                    .into_iter()
 8692                    .map(|selection| selection.head().excerpt_id)
 8693                    .dedup(),
 8694                lines,
 8695                direction,
 8696                cx,
 8697            )
 8698        })
 8699    }
 8700
 8701    pub fn expand_excerpt(
 8702        &mut self,
 8703        excerpt: ExcerptId,
 8704        direction: ExpandExcerptDirection,
 8705        cx: &mut ViewContext<Self>,
 8706    ) {
 8707        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 8708        self.buffer.update(cx, |buffer, cx| {
 8709            buffer.expand_excerpts([excerpt], lines, direction, cx)
 8710        })
 8711    }
 8712
 8713    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8714        self.go_to_diagnostic_impl(Direction::Next, cx)
 8715    }
 8716
 8717    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8718        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8719    }
 8720
 8721    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8722        let buffer = self.buffer.read(cx).snapshot(cx);
 8723        let selection = self.selections.newest::<usize>(cx);
 8724
 8725        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8726        if direction == Direction::Next {
 8727            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8728                let (group_id, jump_to) = popover.activation_info();
 8729                if self.activate_diagnostics(group_id, cx) {
 8730                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8731                        let mut new_selection = s.newest_anchor().clone();
 8732                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 8733                        s.select_anchors(vec![new_selection.clone()]);
 8734                    });
 8735                }
 8736                return;
 8737            }
 8738        }
 8739
 8740        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 8741            active_diagnostics
 8742                .primary_range
 8743                .to_offset(&buffer)
 8744                .to_inclusive()
 8745        });
 8746        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 8747            if active_primary_range.contains(&selection.head()) {
 8748                *active_primary_range.start()
 8749            } else {
 8750                selection.head()
 8751            }
 8752        } else {
 8753            selection.head()
 8754        };
 8755        let snapshot = self.snapshot(cx);
 8756        loop {
 8757            let diagnostics = if direction == Direction::Prev {
 8758                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 8759            } else {
 8760                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 8761            }
 8762            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 8763            let group = diagnostics
 8764                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 8765                // be sorted in a stable way
 8766                // skip until we are at current active diagnostic, if it exists
 8767                .skip_while(|entry| {
 8768                    (match direction {
 8769                        Direction::Prev => entry.range.start >= search_start,
 8770                        Direction::Next => entry.range.start <= search_start,
 8771                    }) && self
 8772                        .active_diagnostics
 8773                        .as_ref()
 8774                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 8775                })
 8776                .find_map(|entry| {
 8777                    if entry.diagnostic.is_primary
 8778                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 8779                        && !entry.range.is_empty()
 8780                        // if we match with the active diagnostic, skip it
 8781                        && Some(entry.diagnostic.group_id)
 8782                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 8783                    {
 8784                        Some((entry.range, entry.diagnostic.group_id))
 8785                    } else {
 8786                        None
 8787                    }
 8788                });
 8789
 8790            if let Some((primary_range, group_id)) = group {
 8791                if self.activate_diagnostics(group_id, cx) {
 8792                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8793                        s.select(vec![Selection {
 8794                            id: selection.id,
 8795                            start: primary_range.start,
 8796                            end: primary_range.start,
 8797                            reversed: false,
 8798                            goal: SelectionGoal::None,
 8799                        }]);
 8800                    });
 8801                }
 8802                break;
 8803            } else {
 8804                // Cycle around to the start of the buffer, potentially moving back to the start of
 8805                // the currently active diagnostic.
 8806                active_primary_range.take();
 8807                if direction == Direction::Prev {
 8808                    if search_start == buffer.len() {
 8809                        break;
 8810                    } else {
 8811                        search_start = buffer.len();
 8812                    }
 8813                } else if search_start == 0 {
 8814                    break;
 8815                } else {
 8816                    search_start = 0;
 8817                }
 8818            }
 8819        }
 8820    }
 8821
 8822    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 8823        let snapshot = self
 8824            .display_map
 8825            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8826        let selection = self.selections.newest::<Point>(cx);
 8827
 8828        if !self.seek_in_direction(
 8829            &snapshot,
 8830            selection.head(),
 8831            false,
 8832            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8833                MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
 8834            ),
 8835            cx,
 8836        ) {
 8837            let wrapped_point = Point::zero();
 8838            self.seek_in_direction(
 8839                &snapshot,
 8840                wrapped_point,
 8841                true,
 8842                snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8843                    MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 8844                ),
 8845                cx,
 8846            );
 8847        }
 8848    }
 8849
 8850    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 8851        let snapshot = self
 8852            .display_map
 8853            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8854        let selection = self.selections.newest::<Point>(cx);
 8855
 8856        if !self.seek_in_direction(
 8857            &snapshot,
 8858            selection.head(),
 8859            false,
 8860            snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8861                MultiBufferRow(0)..MultiBufferRow(selection.head().row),
 8862            ),
 8863            cx,
 8864        ) {
 8865            let wrapped_point = snapshot.buffer_snapshot.max_point();
 8866            self.seek_in_direction(
 8867                &snapshot,
 8868                wrapped_point,
 8869                true,
 8870                snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8871                    MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
 8872                ),
 8873                cx,
 8874            );
 8875        }
 8876    }
 8877
 8878    fn seek_in_direction(
 8879        &mut self,
 8880        snapshot: &DisplaySnapshot,
 8881        initial_point: Point,
 8882        is_wrapped: bool,
 8883        hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
 8884        cx: &mut ViewContext<Editor>,
 8885    ) -> bool {
 8886        let display_point = initial_point.to_display_point(snapshot);
 8887        let mut hunks = hunks
 8888            .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
 8889            .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
 8890            .dedup();
 8891
 8892        if let Some(hunk) = hunks.next() {
 8893            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8894                let row = hunk.start_display_row();
 8895                let point = DisplayPoint::new(row, 0);
 8896                s.select_display_ranges([point..point]);
 8897            });
 8898
 8899            true
 8900        } else {
 8901            false
 8902        }
 8903    }
 8904
 8905    pub fn go_to_definition(
 8906        &mut self,
 8907        _: &GoToDefinition,
 8908        cx: &mut ViewContext<Self>,
 8909    ) -> Task<Result<bool>> {
 8910        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
 8911    }
 8912
 8913    pub fn go_to_implementation(
 8914        &mut self,
 8915        _: &GoToImplementation,
 8916        cx: &mut ViewContext<Self>,
 8917    ) -> Task<Result<bool>> {
 8918        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 8919    }
 8920
 8921    pub fn go_to_implementation_split(
 8922        &mut self,
 8923        _: &GoToImplementationSplit,
 8924        cx: &mut ViewContext<Self>,
 8925    ) -> Task<Result<bool>> {
 8926        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 8927    }
 8928
 8929    pub fn go_to_type_definition(
 8930        &mut self,
 8931        _: &GoToTypeDefinition,
 8932        cx: &mut ViewContext<Self>,
 8933    ) -> Task<Result<bool>> {
 8934        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 8935    }
 8936
 8937    pub fn go_to_definition_split(
 8938        &mut self,
 8939        _: &GoToDefinitionSplit,
 8940        cx: &mut ViewContext<Self>,
 8941    ) -> Task<Result<bool>> {
 8942        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 8943    }
 8944
 8945    pub fn go_to_type_definition_split(
 8946        &mut self,
 8947        _: &GoToTypeDefinitionSplit,
 8948        cx: &mut ViewContext<Self>,
 8949    ) -> Task<Result<bool>> {
 8950        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 8951    }
 8952
 8953    fn go_to_definition_of_kind(
 8954        &mut self,
 8955        kind: GotoDefinitionKind,
 8956        split: bool,
 8957        cx: &mut ViewContext<Self>,
 8958    ) -> Task<Result<bool>> {
 8959        let Some(workspace) = self.workspace() else {
 8960            return Task::ready(Ok(false));
 8961        };
 8962        let buffer = self.buffer.read(cx);
 8963        let head = self.selections.newest::<usize>(cx).head();
 8964        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 8965            text_anchor
 8966        } else {
 8967            return Task::ready(Ok(false));
 8968        };
 8969
 8970        let project = workspace.read(cx).project().clone();
 8971        let definitions = project.update(cx, |project, cx| match kind {
 8972            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 8973            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 8974            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 8975        });
 8976
 8977        cx.spawn(|editor, mut cx| async move {
 8978            let definitions = definitions.await?;
 8979            let navigated = editor
 8980                .update(&mut cx, |editor, cx| {
 8981                    editor.navigate_to_hover_links(
 8982                        Some(kind),
 8983                        definitions
 8984                            .into_iter()
 8985                            .filter(|location| {
 8986                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 8987                            })
 8988                            .map(HoverLink::Text)
 8989                            .collect::<Vec<_>>(),
 8990                        split,
 8991                        cx,
 8992                    )
 8993                })?
 8994                .await?;
 8995            anyhow::Ok(navigated)
 8996        })
 8997    }
 8998
 8999    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9000        let position = self.selections.newest_anchor().head();
 9001        let Some((buffer, buffer_position)) =
 9002            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9003        else {
 9004            return;
 9005        };
 9006
 9007        cx.spawn(|editor, mut cx| async move {
 9008            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9009                editor.update(&mut cx, |_, cx| {
 9010                    cx.open_url(&url);
 9011                })
 9012            } else {
 9013                Ok(())
 9014            }
 9015        })
 9016        .detach();
 9017    }
 9018
 9019    pub(crate) fn navigate_to_hover_links(
 9020        &mut self,
 9021        kind: Option<GotoDefinitionKind>,
 9022        mut definitions: Vec<HoverLink>,
 9023        split: bool,
 9024        cx: &mut ViewContext<Editor>,
 9025    ) -> Task<Result<bool>> {
 9026        // If there is one definition, just open it directly
 9027        if definitions.len() == 1 {
 9028            let definition = definitions.pop().unwrap();
 9029            let target_task = match definition {
 9030                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9031                HoverLink::InlayHint(lsp_location, server_id) => {
 9032                    self.compute_target_location(lsp_location, server_id, cx)
 9033                }
 9034                HoverLink::Url(url) => {
 9035                    cx.open_url(&url);
 9036                    Task::ready(Ok(None))
 9037                }
 9038            };
 9039            cx.spawn(|editor, mut cx| async move {
 9040                let target = target_task.await.context("target resolution task")?;
 9041                if let Some(target) = target {
 9042                    editor.update(&mut cx, |editor, cx| {
 9043                        let Some(workspace) = editor.workspace() else {
 9044                            return false;
 9045                        };
 9046                        let pane = workspace.read(cx).active_pane().clone();
 9047
 9048                        let range = target.range.to_offset(target.buffer.read(cx));
 9049                        let range = editor.range_for_match(&range);
 9050
 9051                        /// If select range has more than one line, we
 9052                        /// just point the cursor to range.start.
 9053                        fn check_multiline_range(
 9054                            buffer: &Buffer,
 9055                            range: Range<usize>,
 9056                        ) -> Range<usize> {
 9057                            if buffer.offset_to_point(range.start).row
 9058                                == buffer.offset_to_point(range.end).row
 9059                            {
 9060                                range
 9061                            } else {
 9062                                range.start..range.start
 9063                            }
 9064                        }
 9065
 9066                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9067                            let buffer = target.buffer.read(cx);
 9068                            let range = check_multiline_range(buffer, range);
 9069                            editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 9070                                s.select_ranges([range]);
 9071                            });
 9072                        } else {
 9073                            cx.window_context().defer(move |cx| {
 9074                                let target_editor: View<Self> =
 9075                                    workspace.update(cx, |workspace, cx| {
 9076                                        let pane = if split {
 9077                                            workspace.adjacent_pane(cx)
 9078                                        } else {
 9079                                            workspace.active_pane().clone()
 9080                                        };
 9081
 9082                                        workspace.open_project_item(pane, target.buffer.clone(), cx)
 9083                                    });
 9084                                target_editor.update(cx, |target_editor, cx| {
 9085                                    // When selecting a definition in a different buffer, disable the nav history
 9086                                    // to avoid creating a history entry at the previous cursor location.
 9087                                    pane.update(cx, |pane, _| pane.disable_history());
 9088                                    let buffer = target.buffer.read(cx);
 9089                                    let range = check_multiline_range(buffer, range);
 9090                                    target_editor.change_selections(
 9091                                        Some(Autoscroll::focused()),
 9092                                        cx,
 9093                                        |s| {
 9094                                            s.select_ranges([range]);
 9095                                        },
 9096                                    );
 9097                                    pane.update(cx, |pane, _| pane.enable_history());
 9098                                });
 9099                            });
 9100                        }
 9101                        true
 9102                    })
 9103                } else {
 9104                    Ok(false)
 9105                }
 9106            })
 9107        } else if !definitions.is_empty() {
 9108            let replica_id = self.replica_id(cx);
 9109            cx.spawn(|editor, mut cx| async move {
 9110                let (title, location_tasks, workspace) = editor
 9111                    .update(&mut cx, |editor, cx| {
 9112                        let tab_kind = match kind {
 9113                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9114                            _ => "Definitions",
 9115                        };
 9116                        let title = definitions
 9117                            .iter()
 9118                            .find_map(|definition| match definition {
 9119                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9120                                    let buffer = origin.buffer.read(cx);
 9121                                    format!(
 9122                                        "{} for {}",
 9123                                        tab_kind,
 9124                                        buffer
 9125                                            .text_for_range(origin.range.clone())
 9126                                            .collect::<String>()
 9127                                    )
 9128                                }),
 9129                                HoverLink::InlayHint(_, _) => None,
 9130                                HoverLink::Url(_) => None,
 9131                            })
 9132                            .unwrap_or(tab_kind.to_string());
 9133                        let location_tasks = definitions
 9134                            .into_iter()
 9135                            .map(|definition| match definition {
 9136                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9137                                HoverLink::InlayHint(lsp_location, server_id) => {
 9138                                    editor.compute_target_location(lsp_location, server_id, cx)
 9139                                }
 9140                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9141                            })
 9142                            .collect::<Vec<_>>();
 9143                        (title, location_tasks, editor.workspace().clone())
 9144                    })
 9145                    .context("location tasks preparation")?;
 9146
 9147                let locations = futures::future::join_all(location_tasks)
 9148                    .await
 9149                    .into_iter()
 9150                    .filter_map(|location| location.transpose())
 9151                    .collect::<Result<_>>()
 9152                    .context("location tasks")?;
 9153
 9154                let Some(workspace) = workspace else {
 9155                    return Ok(false);
 9156                };
 9157                let opened = workspace
 9158                    .update(&mut cx, |workspace, cx| {
 9159                        Self::open_locations_in_multibuffer(
 9160                            workspace, locations, replica_id, title, split, cx,
 9161                        )
 9162                    })
 9163                    .ok();
 9164
 9165                anyhow::Ok(opened.is_some())
 9166            })
 9167        } else {
 9168            Task::ready(Ok(false))
 9169        }
 9170    }
 9171
 9172    fn compute_target_location(
 9173        &self,
 9174        lsp_location: lsp::Location,
 9175        server_id: LanguageServerId,
 9176        cx: &mut ViewContext<Editor>,
 9177    ) -> Task<anyhow::Result<Option<Location>>> {
 9178        let Some(project) = self.project.clone() else {
 9179            return Task::Ready(Some(Ok(None)));
 9180        };
 9181
 9182        cx.spawn(move |editor, mut cx| async move {
 9183            let location_task = editor.update(&mut cx, |editor, cx| {
 9184                project.update(cx, |project, cx| {
 9185                    let language_server_name =
 9186                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 9187                            project
 9188                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 9189                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 9190                        });
 9191                    language_server_name.map(|language_server_name| {
 9192                        project.open_local_buffer_via_lsp(
 9193                            lsp_location.uri.clone(),
 9194                            server_id,
 9195                            language_server_name,
 9196                            cx,
 9197                        )
 9198                    })
 9199                })
 9200            })?;
 9201            let location = match location_task {
 9202                Some(task) => Some({
 9203                    let target_buffer_handle = task.await.context("open local buffer")?;
 9204                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9205                        let target_start = target_buffer
 9206                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9207                        let target_end = target_buffer
 9208                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9209                        target_buffer.anchor_after(target_start)
 9210                            ..target_buffer.anchor_before(target_end)
 9211                    })?;
 9212                    Location {
 9213                        buffer: target_buffer_handle,
 9214                        range,
 9215                    }
 9216                }),
 9217                None => None,
 9218            };
 9219            Ok(location)
 9220        })
 9221    }
 9222
 9223    pub fn find_all_references(
 9224        &mut self,
 9225        _: &FindAllReferences,
 9226        cx: &mut ViewContext<Self>,
 9227    ) -> Option<Task<Result<()>>> {
 9228        let multi_buffer = self.buffer.read(cx);
 9229        let selection = self.selections.newest::<usize>(cx);
 9230        let head = selection.head();
 9231
 9232        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9233        let head_anchor = multi_buffer_snapshot.anchor_at(
 9234            head,
 9235            if head < selection.tail() {
 9236                Bias::Right
 9237            } else {
 9238                Bias::Left
 9239            },
 9240        );
 9241
 9242        match self
 9243            .find_all_references_task_sources
 9244            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9245        {
 9246            Ok(_) => {
 9247                log::info!(
 9248                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9249                );
 9250                return None;
 9251            }
 9252            Err(i) => {
 9253                self.find_all_references_task_sources.insert(i, head_anchor);
 9254            }
 9255        }
 9256
 9257        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9258        let replica_id = self.replica_id(cx);
 9259        let workspace = self.workspace()?;
 9260        let project = workspace.read(cx).project().clone();
 9261        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9262        Some(cx.spawn(|editor, mut cx| async move {
 9263            let _cleanup = defer({
 9264                let mut cx = cx.clone();
 9265                move || {
 9266                    let _ = editor.update(&mut cx, |editor, _| {
 9267                        if let Ok(i) =
 9268                            editor
 9269                                .find_all_references_task_sources
 9270                                .binary_search_by(|anchor| {
 9271                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9272                                })
 9273                        {
 9274                            editor.find_all_references_task_sources.remove(i);
 9275                        }
 9276                    });
 9277                }
 9278            });
 9279
 9280            let locations = references.await?;
 9281            if locations.is_empty() {
 9282                return anyhow::Ok(());
 9283            }
 9284
 9285            workspace.update(&mut cx, |workspace, cx| {
 9286                let title = locations
 9287                    .first()
 9288                    .as_ref()
 9289                    .map(|location| {
 9290                        let buffer = location.buffer.read(cx);
 9291                        format!(
 9292                            "References to `{}`",
 9293                            buffer
 9294                                .text_for_range(location.range.clone())
 9295                                .collect::<String>()
 9296                        )
 9297                    })
 9298                    .unwrap();
 9299                Self::open_locations_in_multibuffer(
 9300                    workspace, locations, replica_id, title, false, cx,
 9301                );
 9302            })
 9303        }))
 9304    }
 9305
 9306    /// Opens a multibuffer with the given project locations in it
 9307    pub fn open_locations_in_multibuffer(
 9308        workspace: &mut Workspace,
 9309        mut locations: Vec<Location>,
 9310        replica_id: ReplicaId,
 9311        title: String,
 9312        split: bool,
 9313        cx: &mut ViewContext<Workspace>,
 9314    ) {
 9315        // If there are multiple definitions, open them in a multibuffer
 9316        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9317        let mut locations = locations.into_iter().peekable();
 9318        let mut ranges_to_highlight = Vec::new();
 9319        let capability = workspace.project().read(cx).capability();
 9320
 9321        let excerpt_buffer = cx.new_model(|cx| {
 9322            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 9323            while let Some(location) = locations.next() {
 9324                let buffer = location.buffer.read(cx);
 9325                let mut ranges_for_buffer = Vec::new();
 9326                let range = location.range.to_offset(buffer);
 9327                ranges_for_buffer.push(range.clone());
 9328
 9329                while let Some(next_location) = locations.peek() {
 9330                    if next_location.buffer == location.buffer {
 9331                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9332                        locations.next();
 9333                    } else {
 9334                        break;
 9335                    }
 9336                }
 9337
 9338                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9339                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9340                    location.buffer.clone(),
 9341                    ranges_for_buffer,
 9342                    DEFAULT_MULTIBUFFER_CONTEXT,
 9343                    cx,
 9344                ))
 9345            }
 9346
 9347            multibuffer.with_title(title)
 9348        });
 9349
 9350        let editor = cx.new_view(|cx| {
 9351            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9352        });
 9353        editor.update(cx, |editor, cx| {
 9354            if let Some(first_range) = ranges_to_highlight.first() {
 9355                editor.change_selections(None, cx, |selections| {
 9356                    selections.clear_disjoint();
 9357                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9358                });
 9359            }
 9360            editor.highlight_background::<Self>(
 9361                &ranges_to_highlight,
 9362                |theme| theme.editor_highlighted_line_background,
 9363                cx,
 9364            );
 9365        });
 9366
 9367        let item = Box::new(editor);
 9368        let item_id = item.item_id();
 9369
 9370        if split {
 9371            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9372        } else {
 9373            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9374                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9375                    pane.close_current_preview_item(cx)
 9376                } else {
 9377                    None
 9378                }
 9379            });
 9380            workspace.add_item_to_active_pane(item.clone(), destination_index, cx);
 9381        }
 9382        workspace.active_pane().update(cx, |pane, cx| {
 9383            pane.set_preview_item_id(Some(item_id), cx);
 9384        });
 9385    }
 9386
 9387    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9388        use language::ToOffset as _;
 9389
 9390        let project = self.project.clone()?;
 9391        let selection = self.selections.newest_anchor().clone();
 9392        let (cursor_buffer, cursor_buffer_position) = self
 9393            .buffer
 9394            .read(cx)
 9395            .text_anchor_for_position(selection.head(), cx)?;
 9396        let (tail_buffer, cursor_buffer_position_end) = self
 9397            .buffer
 9398            .read(cx)
 9399            .text_anchor_for_position(selection.tail(), cx)?;
 9400        if tail_buffer != cursor_buffer {
 9401            return None;
 9402        }
 9403
 9404        let snapshot = cursor_buffer.read(cx).snapshot();
 9405        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9406        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9407        let prepare_rename = project.update(cx, |project, cx| {
 9408            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 9409        });
 9410        drop(snapshot);
 9411
 9412        Some(cx.spawn(|this, mut cx| async move {
 9413            let rename_range = if let Some(range) = prepare_rename.await? {
 9414                Some(range)
 9415            } else {
 9416                this.update(&mut cx, |this, cx| {
 9417                    let buffer = this.buffer.read(cx).snapshot(cx);
 9418                    let mut buffer_highlights = this
 9419                        .document_highlights_for_position(selection.head(), &buffer)
 9420                        .filter(|highlight| {
 9421                            highlight.start.excerpt_id == selection.head().excerpt_id
 9422                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9423                        });
 9424                    buffer_highlights
 9425                        .next()
 9426                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9427                })?
 9428            };
 9429            if let Some(rename_range) = rename_range {
 9430                this.update(&mut cx, |this, cx| {
 9431                    let snapshot = cursor_buffer.read(cx).snapshot();
 9432                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9433                    let cursor_offset_in_rename_range =
 9434                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9435                    let cursor_offset_in_rename_range_end =
 9436                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9437
 9438                    this.take_rename(false, cx);
 9439                    let buffer = this.buffer.read(cx).read(cx);
 9440                    let cursor_offset = selection.head().to_offset(&buffer);
 9441                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9442                    let rename_end = rename_start + rename_buffer_range.len();
 9443                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9444                    let mut old_highlight_id = None;
 9445                    let old_name: Arc<str> = buffer
 9446                        .chunks(rename_start..rename_end, true)
 9447                        .map(|chunk| {
 9448                            if old_highlight_id.is_none() {
 9449                                old_highlight_id = chunk.syntax_highlight_id;
 9450                            }
 9451                            chunk.text
 9452                        })
 9453                        .collect::<String>()
 9454                        .into();
 9455
 9456                    drop(buffer);
 9457
 9458                    // Position the selection in the rename editor so that it matches the current selection.
 9459                    this.show_local_selections = false;
 9460                    let rename_editor = cx.new_view(|cx| {
 9461                        let mut editor = Editor::single_line(cx);
 9462                        editor.buffer.update(cx, |buffer, cx| {
 9463                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9464                        });
 9465                        let rename_selection_range = match cursor_offset_in_rename_range
 9466                            .cmp(&cursor_offset_in_rename_range_end)
 9467                        {
 9468                            Ordering::Equal => {
 9469                                editor.select_all(&SelectAll, cx);
 9470                                return editor;
 9471                            }
 9472                            Ordering::Less => {
 9473                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9474                            }
 9475                            Ordering::Greater => {
 9476                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9477                            }
 9478                        };
 9479                        if rename_selection_range.end > old_name.len() {
 9480                            editor.select_all(&SelectAll, cx);
 9481                        } else {
 9482                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9483                                s.select_ranges([rename_selection_range]);
 9484                            });
 9485                        }
 9486                        editor
 9487                    });
 9488
 9489                    let write_highlights =
 9490                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9491                    let read_highlights =
 9492                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9493                    let ranges = write_highlights
 9494                        .iter()
 9495                        .flat_map(|(_, ranges)| ranges.iter())
 9496                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9497                        .cloned()
 9498                        .collect();
 9499
 9500                    this.highlight_text::<Rename>(
 9501                        ranges,
 9502                        HighlightStyle {
 9503                            fade_out: Some(0.6),
 9504                            ..Default::default()
 9505                        },
 9506                        cx,
 9507                    );
 9508                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9509                    cx.focus(&rename_focus_handle);
 9510                    let block_id = this.insert_blocks(
 9511                        [BlockProperties {
 9512                            style: BlockStyle::Flex,
 9513                            position: range.start,
 9514                            height: 1,
 9515                            render: Box::new({
 9516                                let rename_editor = rename_editor.clone();
 9517                                move |cx: &mut BlockContext| {
 9518                                    let mut text_style = cx.editor_style.text.clone();
 9519                                    if let Some(highlight_style) = old_highlight_id
 9520                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 9521                                    {
 9522                                        text_style = text_style.highlight(highlight_style);
 9523                                    }
 9524                                    div()
 9525                                        .pl(cx.anchor_x)
 9526                                        .child(EditorElement::new(
 9527                                            &rename_editor,
 9528                                            EditorStyle {
 9529                                                background: cx.theme().system().transparent,
 9530                                                local_player: cx.editor_style.local_player,
 9531                                                text: text_style,
 9532                                                scrollbar_width: cx.editor_style.scrollbar_width,
 9533                                                syntax: cx.editor_style.syntax.clone(),
 9534                                                status: cx.editor_style.status.clone(),
 9535                                                inlay_hints_style: HighlightStyle {
 9536                                                    color: Some(cx.theme().status().hint),
 9537                                                    font_weight: Some(FontWeight::BOLD),
 9538                                                    ..HighlightStyle::default()
 9539                                                },
 9540                                                suggestions_style: HighlightStyle {
 9541                                                    color: Some(cx.theme().status().predictive),
 9542                                                    ..HighlightStyle::default()
 9543                                                },
 9544                                            },
 9545                                        ))
 9546                                        .into_any_element()
 9547                                }
 9548                            }),
 9549                            disposition: BlockDisposition::Below,
 9550                        }],
 9551                        Some(Autoscroll::fit()),
 9552                        cx,
 9553                    )[0];
 9554                    this.pending_rename = Some(RenameState {
 9555                        range,
 9556                        old_name,
 9557                        editor: rename_editor,
 9558                        block_id,
 9559                    });
 9560                })?;
 9561            }
 9562
 9563            Ok(())
 9564        }))
 9565    }
 9566
 9567    pub fn confirm_rename(
 9568        &mut self,
 9569        _: &ConfirmRename,
 9570        cx: &mut ViewContext<Self>,
 9571    ) -> Option<Task<Result<()>>> {
 9572        let rename = self.take_rename(false, cx)?;
 9573        let workspace = self.workspace()?;
 9574        let (start_buffer, start) = self
 9575            .buffer
 9576            .read(cx)
 9577            .text_anchor_for_position(rename.range.start, cx)?;
 9578        let (end_buffer, end) = self
 9579            .buffer
 9580            .read(cx)
 9581            .text_anchor_for_position(rename.range.end, cx)?;
 9582        if start_buffer != end_buffer {
 9583            return None;
 9584        }
 9585
 9586        let buffer = start_buffer;
 9587        let range = start..end;
 9588        let old_name = rename.old_name;
 9589        let new_name = rename.editor.read(cx).text(cx);
 9590
 9591        let rename = workspace
 9592            .read(cx)
 9593            .project()
 9594            .clone()
 9595            .update(cx, |project, cx| {
 9596                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 9597            });
 9598        let workspace = workspace.downgrade();
 9599
 9600        Some(cx.spawn(|editor, mut cx| async move {
 9601            let project_transaction = rename.await?;
 9602            Self::open_project_transaction(
 9603                &editor,
 9604                workspace,
 9605                project_transaction,
 9606                format!("Rename: {}{}", old_name, new_name),
 9607                cx.clone(),
 9608            )
 9609            .await?;
 9610
 9611            editor.update(&mut cx, |editor, cx| {
 9612                editor.refresh_document_highlights(cx);
 9613            })?;
 9614            Ok(())
 9615        }))
 9616    }
 9617
 9618    fn take_rename(
 9619        &mut self,
 9620        moving_cursor: bool,
 9621        cx: &mut ViewContext<Self>,
 9622    ) -> Option<RenameState> {
 9623        let rename = self.pending_rename.take()?;
 9624        if rename.editor.focus_handle(cx).is_focused(cx) {
 9625            cx.focus(&self.focus_handle);
 9626        }
 9627
 9628        self.remove_blocks(
 9629            [rename.block_id].into_iter().collect(),
 9630            Some(Autoscroll::fit()),
 9631            cx,
 9632        );
 9633        self.clear_highlights::<Rename>(cx);
 9634        self.show_local_selections = true;
 9635
 9636        if moving_cursor {
 9637            let rename_editor = rename.editor.read(cx);
 9638            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 9639
 9640            // Update the selection to match the position of the selection inside
 9641            // the rename editor.
 9642            let snapshot = self.buffer.read(cx).read(cx);
 9643            let rename_range = rename.range.to_offset(&snapshot);
 9644            let cursor_in_editor = snapshot
 9645                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 9646                .min(rename_range.end);
 9647            drop(snapshot);
 9648
 9649            self.change_selections(None, cx, |s| {
 9650                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 9651            });
 9652        } else {
 9653            self.refresh_document_highlights(cx);
 9654        }
 9655
 9656        Some(rename)
 9657    }
 9658
 9659    pub fn pending_rename(&self) -> Option<&RenameState> {
 9660        self.pending_rename.as_ref()
 9661    }
 9662
 9663    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9664        let project = match &self.project {
 9665            Some(project) => project.clone(),
 9666            None => return None,
 9667        };
 9668
 9669        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 9670    }
 9671
 9672    fn perform_format(
 9673        &mut self,
 9674        project: Model<Project>,
 9675        trigger: FormatTrigger,
 9676        cx: &mut ViewContext<Self>,
 9677    ) -> Task<Result<()>> {
 9678        let buffer = self.buffer().clone();
 9679        let mut buffers = buffer.read(cx).all_buffers();
 9680        if trigger == FormatTrigger::Save {
 9681            buffers.retain(|buffer| buffer.read(cx).is_dirty());
 9682        }
 9683
 9684        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 9685        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 9686
 9687        cx.spawn(|_, mut cx| async move {
 9688            let transaction = futures::select_biased! {
 9689                () = timeout => {
 9690                    log::warn!("timed out waiting for formatting");
 9691                    None
 9692                }
 9693                transaction = format.log_err().fuse() => transaction,
 9694            };
 9695
 9696            buffer
 9697                .update(&mut cx, |buffer, cx| {
 9698                    if let Some(transaction) = transaction {
 9699                        if !buffer.is_singleton() {
 9700                            buffer.push_transaction(&transaction.0, cx);
 9701                        }
 9702                    }
 9703
 9704                    cx.notify();
 9705                })
 9706                .ok();
 9707
 9708            Ok(())
 9709        })
 9710    }
 9711
 9712    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
 9713        if let Some(project) = self.project.clone() {
 9714            self.buffer.update(cx, |multi_buffer, cx| {
 9715                project.update(cx, |project, cx| {
 9716                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
 9717                });
 9718            })
 9719        }
 9720    }
 9721
 9722    fn cancel_language_server_work(
 9723        &mut self,
 9724        _: &CancelLanguageServerWork,
 9725        cx: &mut ViewContext<Self>,
 9726    ) {
 9727        if let Some(project) = self.project.clone() {
 9728            self.buffer.update(cx, |multi_buffer, cx| {
 9729                project.update(cx, |project, cx| {
 9730                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
 9731                });
 9732            })
 9733        }
 9734    }
 9735
 9736    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 9737        cx.show_character_palette();
 9738    }
 9739
 9740    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
 9741        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
 9742            let buffer = self.buffer.read(cx).snapshot(cx);
 9743            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
 9744            let is_valid = buffer
 9745                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
 9746                .any(|entry| {
 9747                    entry.diagnostic.is_primary
 9748                        && !entry.range.is_empty()
 9749                        && entry.range.start == primary_range_start
 9750                        && entry.diagnostic.message == active_diagnostics.primary_message
 9751                });
 9752
 9753            if is_valid != active_diagnostics.is_valid {
 9754                active_diagnostics.is_valid = is_valid;
 9755                let mut new_styles = HashMap::default();
 9756                for (block_id, diagnostic) in &active_diagnostics.blocks {
 9757                    new_styles.insert(
 9758                        *block_id,
 9759                        (
 9760                            None,
 9761                            diagnostic_block_renderer(diagnostic.clone(), is_valid),
 9762                        ),
 9763                    );
 9764                }
 9765                self.display_map.update(cx, |display_map, cx| {
 9766                    display_map.replace_blocks(new_styles, cx)
 9767                });
 9768            }
 9769        }
 9770    }
 9771
 9772    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
 9773        self.dismiss_diagnostics(cx);
 9774        let snapshot = self.snapshot(cx);
 9775        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
 9776            let buffer = self.buffer.read(cx).snapshot(cx);
 9777
 9778            let mut primary_range = None;
 9779            let mut primary_message = None;
 9780            let mut group_end = Point::zero();
 9781            let diagnostic_group = buffer
 9782                .diagnostic_group::<MultiBufferPoint>(group_id)
 9783                .filter_map(|entry| {
 9784                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
 9785                        && (entry.range.start.row == entry.range.end.row
 9786                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
 9787                    {
 9788                        return None;
 9789                    }
 9790                    if entry.range.end > group_end {
 9791                        group_end = entry.range.end;
 9792                    }
 9793                    if entry.diagnostic.is_primary {
 9794                        primary_range = Some(entry.range.clone());
 9795                        primary_message = Some(entry.diagnostic.message.clone());
 9796                    }
 9797                    Some(entry)
 9798                })
 9799                .collect::<Vec<_>>();
 9800            let primary_range = primary_range?;
 9801            let primary_message = primary_message?;
 9802            let primary_range =
 9803                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
 9804
 9805            let blocks = display_map
 9806                .insert_blocks(
 9807                    diagnostic_group.iter().map(|entry| {
 9808                        let diagnostic = entry.diagnostic.clone();
 9809                        let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
 9810                        BlockProperties {
 9811                            style: BlockStyle::Fixed,
 9812                            position: buffer.anchor_after(entry.range.start),
 9813                            height: message_height,
 9814                            render: diagnostic_block_renderer(diagnostic, true),
 9815                            disposition: BlockDisposition::Below,
 9816                        }
 9817                    }),
 9818                    cx,
 9819                )
 9820                .into_iter()
 9821                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
 9822                .collect();
 9823
 9824            Some(ActiveDiagnosticGroup {
 9825                primary_range,
 9826                primary_message,
 9827                group_id,
 9828                blocks,
 9829                is_valid: true,
 9830            })
 9831        });
 9832        self.active_diagnostics.is_some()
 9833    }
 9834
 9835    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
 9836        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
 9837            self.display_map.update(cx, |display_map, cx| {
 9838                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
 9839            });
 9840            cx.notify();
 9841        }
 9842    }
 9843
 9844    pub fn set_selections_from_remote(
 9845        &mut self,
 9846        selections: Vec<Selection<Anchor>>,
 9847        pending_selection: Option<Selection<Anchor>>,
 9848        cx: &mut ViewContext<Self>,
 9849    ) {
 9850        let old_cursor_position = self.selections.newest_anchor().head();
 9851        self.selections.change_with(cx, |s| {
 9852            s.select_anchors(selections);
 9853            if let Some(pending_selection) = pending_selection {
 9854                s.set_pending(pending_selection, SelectMode::Character);
 9855            } else {
 9856                s.clear_pending();
 9857            }
 9858        });
 9859        self.selections_did_change(false, &old_cursor_position, true, cx);
 9860    }
 9861
 9862    fn push_to_selection_history(&mut self) {
 9863        self.selection_history.push(SelectionHistoryEntry {
 9864            selections: self.selections.disjoint_anchors(),
 9865            select_next_state: self.select_next_state.clone(),
 9866            select_prev_state: self.select_prev_state.clone(),
 9867            add_selections_state: self.add_selections_state.clone(),
 9868        });
 9869    }
 9870
 9871    pub fn transact(
 9872        &mut self,
 9873        cx: &mut ViewContext<Self>,
 9874        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
 9875    ) -> Option<TransactionId> {
 9876        self.start_transaction_at(Instant::now(), cx);
 9877        update(self, cx);
 9878        self.end_transaction_at(Instant::now(), cx)
 9879    }
 9880
 9881    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
 9882        self.end_selection(cx);
 9883        if let Some(tx_id) = self
 9884            .buffer
 9885            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
 9886        {
 9887            self.selection_history
 9888                .insert_transaction(tx_id, self.selections.disjoint_anchors());
 9889            cx.emit(EditorEvent::TransactionBegun {
 9890                transaction_id: tx_id,
 9891            })
 9892        }
 9893    }
 9894
 9895    fn end_transaction_at(
 9896        &mut self,
 9897        now: Instant,
 9898        cx: &mut ViewContext<Self>,
 9899    ) -> Option<TransactionId> {
 9900        if let Some(transaction_id) = self
 9901            .buffer
 9902            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 9903        {
 9904            if let Some((_, end_selections)) =
 9905                self.selection_history.transaction_mut(transaction_id)
 9906            {
 9907                *end_selections = Some(self.selections.disjoint_anchors());
 9908            } else {
 9909                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
 9910            }
 9911
 9912            cx.emit(EditorEvent::Edited { transaction_id });
 9913            Some(transaction_id)
 9914        } else {
 9915            None
 9916        }
 9917    }
 9918
 9919    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
 9920        let mut fold_ranges = Vec::new();
 9921
 9922        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9923
 9924        let selections = self.selections.all_adjusted(cx);
 9925        for selection in selections {
 9926            let range = selection.range().sorted();
 9927            let buffer_start_row = range.start.row;
 9928
 9929            for row in (0..=range.end.row).rev() {
 9930                if let Some((foldable_range, fold_text)) =
 9931                    display_map.foldable_range(MultiBufferRow(row))
 9932                {
 9933                    if foldable_range.end.row >= buffer_start_row {
 9934                        fold_ranges.push((foldable_range, fold_text));
 9935                        if row <= range.start.row {
 9936                            break;
 9937                        }
 9938                    }
 9939                }
 9940            }
 9941        }
 9942
 9943        self.fold_ranges(fold_ranges, true, cx);
 9944    }
 9945
 9946    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
 9947        let buffer_row = fold_at.buffer_row;
 9948        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9949
 9950        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
 9951            let autoscroll = self
 9952                .selections
 9953                .all::<Point>(cx)
 9954                .iter()
 9955                .any(|selection| fold_range.overlaps(&selection.range()));
 9956
 9957            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
 9958        }
 9959    }
 9960
 9961    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
 9962        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9963        let buffer = &display_map.buffer_snapshot;
 9964        let selections = self.selections.all::<Point>(cx);
 9965        let ranges = selections
 9966            .iter()
 9967            .map(|s| {
 9968                let range = s.display_range(&display_map).sorted();
 9969                let mut start = range.start.to_point(&display_map);
 9970                let mut end = range.end.to_point(&display_map);
 9971                start.column = 0;
 9972                end.column = buffer.line_len(MultiBufferRow(end.row));
 9973                start..end
 9974            })
 9975            .collect::<Vec<_>>();
 9976
 9977        self.unfold_ranges(ranges, true, true, cx);
 9978    }
 9979
 9980    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
 9981        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9982
 9983        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
 9984            ..Point::new(
 9985                unfold_at.buffer_row.0,
 9986                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
 9987            );
 9988
 9989        let autoscroll = self
 9990            .selections
 9991            .all::<Point>(cx)
 9992            .iter()
 9993            .any(|selection| selection.range().overlaps(&intersection_range));
 9994
 9995        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
 9996    }
 9997
 9998    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
 9999        let selections = self.selections.all::<Point>(cx);
10000        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10001        let line_mode = self.selections.line_mode;
10002        let ranges = selections.into_iter().map(|s| {
10003            if line_mode {
10004                let start = Point::new(s.start.row, 0);
10005                let end = Point::new(
10006                    s.end.row,
10007                    display_map
10008                        .buffer_snapshot
10009                        .line_len(MultiBufferRow(s.end.row)),
10010                );
10011                (start..end, display_map.fold_placeholder.clone())
10012            } else {
10013                (s.start..s.end, display_map.fold_placeholder.clone())
10014            }
10015        });
10016        self.fold_ranges(ranges, true, cx);
10017    }
10018
10019    pub fn fold_ranges<T: ToOffset + Clone>(
10020        &mut self,
10021        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10022        auto_scroll: bool,
10023        cx: &mut ViewContext<Self>,
10024    ) {
10025        let mut fold_ranges = Vec::new();
10026        let mut buffers_affected = HashMap::default();
10027        let multi_buffer = self.buffer().read(cx);
10028        for (fold_range, fold_text) in ranges {
10029            if let Some((_, buffer, _)) =
10030                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10031            {
10032                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10033            };
10034            fold_ranges.push((fold_range, fold_text));
10035        }
10036
10037        let mut ranges = fold_ranges.into_iter().peekable();
10038        if ranges.peek().is_some() {
10039            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10040
10041            if auto_scroll {
10042                self.request_autoscroll(Autoscroll::fit(), cx);
10043            }
10044
10045            for buffer in buffers_affected.into_values() {
10046                self.sync_expanded_diff_hunks(buffer, cx);
10047            }
10048
10049            cx.notify();
10050
10051            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10052                // Clear diagnostics block when folding a range that contains it.
10053                let snapshot = self.snapshot(cx);
10054                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10055                    drop(snapshot);
10056                    self.active_diagnostics = Some(active_diagnostics);
10057                    self.dismiss_diagnostics(cx);
10058                } else {
10059                    self.active_diagnostics = Some(active_diagnostics);
10060                }
10061            }
10062
10063            self.scrollbar_marker_state.dirty = true;
10064        }
10065    }
10066
10067    pub fn unfold_ranges<T: ToOffset + Clone>(
10068        &mut self,
10069        ranges: impl IntoIterator<Item = Range<T>>,
10070        inclusive: bool,
10071        auto_scroll: bool,
10072        cx: &mut ViewContext<Self>,
10073    ) {
10074        let mut unfold_ranges = Vec::new();
10075        let mut buffers_affected = HashMap::default();
10076        let multi_buffer = self.buffer().read(cx);
10077        for range in ranges {
10078            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10079                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10080            };
10081            unfold_ranges.push(range);
10082        }
10083
10084        let mut ranges = unfold_ranges.into_iter().peekable();
10085        if ranges.peek().is_some() {
10086            self.display_map
10087                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10088            if auto_scroll {
10089                self.request_autoscroll(Autoscroll::fit(), cx);
10090            }
10091
10092            for buffer in buffers_affected.into_values() {
10093                self.sync_expanded_diff_hunks(buffer, cx);
10094            }
10095
10096            cx.notify();
10097            self.scrollbar_marker_state.dirty = true;
10098            self.active_indent_guides_state.dirty = true;
10099        }
10100    }
10101
10102    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10103        if hovered != self.gutter_hovered {
10104            self.gutter_hovered = hovered;
10105            cx.notify();
10106        }
10107    }
10108
10109    pub fn insert_blocks(
10110        &mut self,
10111        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10112        autoscroll: Option<Autoscroll>,
10113        cx: &mut ViewContext<Self>,
10114    ) -> Vec<BlockId> {
10115        let blocks = self
10116            .display_map
10117            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10118        if let Some(autoscroll) = autoscroll {
10119            self.request_autoscroll(autoscroll, cx);
10120        }
10121        blocks
10122    }
10123
10124    pub fn replace_blocks(
10125        &mut self,
10126        blocks: HashMap<BlockId, (Option<u8>, RenderBlock)>,
10127        autoscroll: Option<Autoscroll>,
10128        cx: &mut ViewContext<Self>,
10129    ) {
10130        self.display_map
10131            .update(cx, |display_map, cx| display_map.replace_blocks(blocks, cx));
10132        if let Some(autoscroll) = autoscroll {
10133            self.request_autoscroll(autoscroll, cx);
10134        }
10135    }
10136
10137    pub fn remove_blocks(
10138        &mut self,
10139        block_ids: HashSet<BlockId>,
10140        autoscroll: Option<Autoscroll>,
10141        cx: &mut ViewContext<Self>,
10142    ) {
10143        self.display_map.update(cx, |display_map, cx| {
10144            display_map.remove_blocks(block_ids, cx)
10145        });
10146        if let Some(autoscroll) = autoscroll {
10147            self.request_autoscroll(autoscroll, cx);
10148        }
10149    }
10150
10151    pub fn row_for_block(
10152        &self,
10153        block_id: BlockId,
10154        cx: &mut ViewContext<Self>,
10155    ) -> Option<DisplayRow> {
10156        self.display_map
10157            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10158    }
10159
10160    pub fn insert_creases(
10161        &mut self,
10162        creases: impl IntoIterator<Item = Crease>,
10163        cx: &mut ViewContext<Self>,
10164    ) -> Vec<CreaseId> {
10165        self.display_map
10166            .update(cx, |map, cx| map.insert_creases(creases, cx))
10167    }
10168
10169    pub fn remove_creases(
10170        &mut self,
10171        ids: impl IntoIterator<Item = CreaseId>,
10172        cx: &mut ViewContext<Self>,
10173    ) {
10174        self.display_map
10175            .update(cx, |map, cx| map.remove_creases(ids, cx));
10176    }
10177
10178    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10179        self.display_map
10180            .update(cx, |map, cx| map.snapshot(cx))
10181            .longest_row()
10182    }
10183
10184    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10185        self.display_map
10186            .update(cx, |map, cx| map.snapshot(cx))
10187            .max_point()
10188    }
10189
10190    pub fn text(&self, cx: &AppContext) -> String {
10191        self.buffer.read(cx).read(cx).text()
10192    }
10193
10194    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10195        let text = self.text(cx);
10196        let text = text.trim();
10197
10198        if text.is_empty() {
10199            return None;
10200        }
10201
10202        Some(text.to_string())
10203    }
10204
10205    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10206        self.transact(cx, |this, cx| {
10207            this.buffer
10208                .read(cx)
10209                .as_singleton()
10210                .expect("you can only call set_text on editors for singleton buffers")
10211                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10212        });
10213    }
10214
10215    pub fn display_text(&self, cx: &mut AppContext) -> String {
10216        self.display_map
10217            .update(cx, |map, cx| map.snapshot(cx))
10218            .text()
10219    }
10220
10221    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10222        let mut wrap_guides = smallvec::smallvec![];
10223
10224        if self.show_wrap_guides == Some(false) {
10225            return wrap_guides;
10226        }
10227
10228        let settings = self.buffer.read(cx).settings_at(0, cx);
10229        if settings.show_wrap_guides {
10230            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10231                wrap_guides.push((soft_wrap as usize, true));
10232            }
10233            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10234        }
10235
10236        wrap_guides
10237    }
10238
10239    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10240        let settings = self.buffer.read(cx).settings_at(0, cx);
10241        let mode = self
10242            .soft_wrap_mode_override
10243            .unwrap_or_else(|| settings.soft_wrap);
10244        match mode {
10245            language_settings::SoftWrap::None => SoftWrap::None,
10246            language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10247            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10248            language_settings::SoftWrap::PreferredLineLength => {
10249                SoftWrap::Column(settings.preferred_line_length)
10250            }
10251        }
10252    }
10253
10254    pub fn set_soft_wrap_mode(
10255        &mut self,
10256        mode: language_settings::SoftWrap,
10257        cx: &mut ViewContext<Self>,
10258    ) {
10259        self.soft_wrap_mode_override = Some(mode);
10260        cx.notify();
10261    }
10262
10263    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10264        let rem_size = cx.rem_size();
10265        self.display_map.update(cx, |map, cx| {
10266            map.set_font(
10267                style.text.font(),
10268                style.text.font_size.to_pixels(rem_size),
10269                cx,
10270            )
10271        });
10272        self.style = Some(style);
10273    }
10274
10275    pub fn style(&self) -> Option<&EditorStyle> {
10276        self.style.as_ref()
10277    }
10278
10279    // Called by the element. This method is not designed to be called outside of the editor
10280    // element's layout code because it does not notify when rewrapping is computed synchronously.
10281    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10282        self.display_map
10283            .update(cx, |map, cx| map.set_wrap_width(width, cx))
10284    }
10285
10286    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10287        if self.soft_wrap_mode_override.is_some() {
10288            self.soft_wrap_mode_override.take();
10289        } else {
10290            let soft_wrap = match self.soft_wrap_mode(cx) {
10291                SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10292                SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10293                    language_settings::SoftWrap::PreferLine
10294                }
10295            };
10296            self.soft_wrap_mode_override = Some(soft_wrap);
10297        }
10298        cx.notify();
10299    }
10300
10301    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10302        let Some(workspace) = self.workspace() else {
10303            return;
10304        };
10305        let fs = workspace.read(cx).app_state().fs.clone();
10306        let current_show = TabBarSettings::get_global(cx).show;
10307        update_settings_file::<TabBarSettings>(fs, cx, move |setting| {
10308            setting.show = Some(!current_show);
10309        });
10310    }
10311
10312    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10313        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10314            self.buffer
10315                .read(cx)
10316                .settings_at(0, cx)
10317                .indent_guides
10318                .enabled
10319        });
10320        self.show_indent_guides = Some(!currently_enabled);
10321        cx.notify();
10322    }
10323
10324    fn should_show_indent_guides(&self) -> Option<bool> {
10325        self.show_indent_guides
10326    }
10327
10328    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10329        let mut editor_settings = EditorSettings::get_global(cx).clone();
10330        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10331        EditorSettings::override_global(editor_settings, cx);
10332    }
10333
10334    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10335        self.show_gutter = show_gutter;
10336        cx.notify();
10337    }
10338
10339    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10340        self.show_line_numbers = Some(show_line_numbers);
10341        cx.notify();
10342    }
10343
10344    pub fn set_show_git_diff_gutter(
10345        &mut self,
10346        show_git_diff_gutter: bool,
10347        cx: &mut ViewContext<Self>,
10348    ) {
10349        self.show_git_diff_gutter = Some(show_git_diff_gutter);
10350        cx.notify();
10351    }
10352
10353    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10354        self.show_code_actions = Some(show_code_actions);
10355        cx.notify();
10356    }
10357
10358    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10359        self.show_runnables = Some(show_runnables);
10360        cx.notify();
10361    }
10362
10363    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10364        self.show_wrap_guides = Some(show_wrap_guides);
10365        cx.notify();
10366    }
10367
10368    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10369        self.show_indent_guides = Some(show_indent_guides);
10370        cx.notify();
10371    }
10372
10373    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10374        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10375            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10376                cx.reveal_path(&file.abs_path(cx));
10377            }
10378        }
10379    }
10380
10381    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10382        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10383            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10384                if let Some(path) = file.abs_path(cx).to_str() {
10385                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10386                }
10387            }
10388        }
10389    }
10390
10391    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10392        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10393            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10394                if let Some(path) = file.path().to_str() {
10395                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10396                }
10397            }
10398        }
10399    }
10400
10401    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10402        self.show_git_blame_gutter = !self.show_git_blame_gutter;
10403
10404        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10405            self.start_git_blame(true, cx);
10406        }
10407
10408        cx.notify();
10409    }
10410
10411    pub fn toggle_git_blame_inline(
10412        &mut self,
10413        _: &ToggleGitBlameInline,
10414        cx: &mut ViewContext<Self>,
10415    ) {
10416        self.toggle_git_blame_inline_internal(true, cx);
10417        cx.notify();
10418    }
10419
10420    pub fn git_blame_inline_enabled(&self) -> bool {
10421        self.git_blame_inline_enabled
10422    }
10423
10424    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10425        self.show_selection_menu = self
10426            .show_selection_menu
10427            .map(|show_selections_menu| !show_selections_menu)
10428            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10429
10430        cx.notify();
10431    }
10432
10433    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10434        self.show_selection_menu
10435            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10436    }
10437
10438    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10439        if let Some(project) = self.project.as_ref() {
10440            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10441                return;
10442            };
10443
10444            if buffer.read(cx).file().is_none() {
10445                return;
10446            }
10447
10448            let focused = self.focus_handle(cx).contains_focused(cx);
10449
10450            let project = project.clone();
10451            let blame =
10452                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10453            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10454            self.blame = Some(blame);
10455        }
10456    }
10457
10458    fn toggle_git_blame_inline_internal(
10459        &mut self,
10460        user_triggered: bool,
10461        cx: &mut ViewContext<Self>,
10462    ) {
10463        if self.git_blame_inline_enabled {
10464            self.git_blame_inline_enabled = false;
10465            self.show_git_blame_inline = false;
10466            self.show_git_blame_inline_delay_task.take();
10467        } else {
10468            self.git_blame_inline_enabled = true;
10469            self.start_git_blame_inline(user_triggered, cx);
10470        }
10471
10472        cx.notify();
10473    }
10474
10475    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10476        self.start_git_blame(user_triggered, cx);
10477
10478        if ProjectSettings::get_global(cx)
10479            .git
10480            .inline_blame_delay()
10481            .is_some()
10482        {
10483            self.start_inline_blame_timer(cx);
10484        } else {
10485            self.show_git_blame_inline = true
10486        }
10487    }
10488
10489    pub fn blame(&self) -> Option<&Model<GitBlame>> {
10490        self.blame.as_ref()
10491    }
10492
10493    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10494        self.show_git_blame_gutter && self.has_blame_entries(cx)
10495    }
10496
10497    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10498        self.show_git_blame_inline
10499            && self.focus_handle.is_focused(cx)
10500            && !self.newest_selection_head_on_empty_line(cx)
10501            && self.has_blame_entries(cx)
10502    }
10503
10504    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10505        self.blame()
10506            .map_or(false, |blame| blame.read(cx).has_generated_entries())
10507    }
10508
10509    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10510        let cursor_anchor = self.selections.newest_anchor().head();
10511
10512        let snapshot = self.buffer.read(cx).snapshot(cx);
10513        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10514
10515        snapshot.line_len(buffer_row) == 0
10516    }
10517
10518    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10519        let (path, selection, repo) = maybe!({
10520            let project_handle = self.project.as_ref()?.clone();
10521            let project = project_handle.read(cx);
10522
10523            let selection = self.selections.newest::<Point>(cx);
10524            let selection_range = selection.range();
10525
10526            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10527                (buffer, selection_range.start.row..selection_range.end.row)
10528            } else {
10529                let buffer_ranges = self
10530                    .buffer()
10531                    .read(cx)
10532                    .range_to_buffer_ranges(selection_range, cx);
10533
10534                let (buffer, range, _) = if selection.reversed {
10535                    buffer_ranges.first()
10536                } else {
10537                    buffer_ranges.last()
10538                }?;
10539
10540                let snapshot = buffer.read(cx).snapshot();
10541                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10542                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
10543                (buffer.clone(), selection)
10544            };
10545
10546            let path = buffer
10547                .read(cx)
10548                .file()?
10549                .as_local()?
10550                .path()
10551                .to_str()?
10552                .to_string();
10553            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10554            Some((path, selection, repo))
10555        })
10556        .ok_or_else(|| anyhow!("unable to open git repository"))?;
10557
10558        const REMOTE_NAME: &str = "origin";
10559        let origin_url = repo
10560            .remote_url(REMOTE_NAME)
10561            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10562        let sha = repo
10563            .head_sha()
10564            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10565
10566        let (provider, remote) =
10567            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10568                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10569
10570        Ok(provider.build_permalink(
10571            remote,
10572            BuildPermalinkParams {
10573                sha: &sha,
10574                path: &path,
10575                selection: Some(selection),
10576            },
10577        ))
10578    }
10579
10580    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10581        let permalink = self.get_permalink_to_line(cx);
10582
10583        match permalink {
10584            Ok(permalink) => {
10585                cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
10586            }
10587            Err(err) => {
10588                let message = format!("Failed to copy permalink: {err}");
10589
10590                Err::<(), anyhow::Error>(err).log_err();
10591
10592                if let Some(workspace) = self.workspace() {
10593                    workspace.update(cx, |workspace, cx| {
10594                        struct CopyPermalinkToLine;
10595
10596                        workspace.show_toast(
10597                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10598                            cx,
10599                        )
10600                    })
10601                }
10602            }
10603        }
10604    }
10605
10606    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10607        let permalink = self.get_permalink_to_line(cx);
10608
10609        match permalink {
10610            Ok(permalink) => {
10611                cx.open_url(permalink.as_ref());
10612            }
10613            Err(err) => {
10614                let message = format!("Failed to open permalink: {err}");
10615
10616                Err::<(), anyhow::Error>(err).log_err();
10617
10618                if let Some(workspace) = self.workspace() {
10619                    workspace.update(cx, |workspace, cx| {
10620                        struct OpenPermalinkToLine;
10621
10622                        workspace.show_toast(
10623                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10624                            cx,
10625                        )
10626                    })
10627                }
10628            }
10629        }
10630    }
10631
10632    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10633    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10634    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10635    pub fn highlight_rows<T: 'static>(
10636        &mut self,
10637        rows: RangeInclusive<Anchor>,
10638        color: Option<Hsla>,
10639        should_autoscroll: bool,
10640        cx: &mut ViewContext<Self>,
10641    ) {
10642        let snapshot = self.buffer().read(cx).snapshot(cx);
10643        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10644        let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10645            highlight
10646                .range
10647                .start()
10648                .cmp(&rows.start(), &snapshot)
10649                .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10650        });
10651        match (color, existing_highlight_index) {
10652            (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10653                ix,
10654                RowHighlight {
10655                    index: post_inc(&mut self.highlight_order),
10656                    range: rows,
10657                    should_autoscroll,
10658                    color,
10659                },
10660            ),
10661            (None, Ok(i)) => {
10662                row_highlights.remove(i);
10663            }
10664        }
10665    }
10666
10667    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10668    pub fn clear_row_highlights<T: 'static>(&mut self) {
10669        self.highlighted_rows.remove(&TypeId::of::<T>());
10670    }
10671
10672    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10673    pub fn highlighted_rows<T: 'static>(
10674        &self,
10675    ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10676        Some(
10677            self.highlighted_rows
10678                .get(&TypeId::of::<T>())?
10679                .iter()
10680                .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10681        )
10682    }
10683
10684    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10685    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10686    /// Allows to ignore certain kinds of highlights.
10687    pub fn highlighted_display_rows(
10688        &mut self,
10689        cx: &mut WindowContext,
10690    ) -> BTreeMap<DisplayRow, Hsla> {
10691        let snapshot = self.snapshot(cx);
10692        let mut used_highlight_orders = HashMap::default();
10693        self.highlighted_rows
10694            .iter()
10695            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10696            .fold(
10697                BTreeMap::<DisplayRow, Hsla>::new(),
10698                |mut unique_rows, highlight| {
10699                    let start_row = highlight.range.start().to_display_point(&snapshot).row();
10700                    let end_row = highlight.range.end().to_display_point(&snapshot).row();
10701                    for row in start_row.0..=end_row.0 {
10702                        let used_index =
10703                            used_highlight_orders.entry(row).or_insert(highlight.index);
10704                        if highlight.index >= *used_index {
10705                            *used_index = highlight.index;
10706                            match highlight.color {
10707                                Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10708                                None => unique_rows.remove(&DisplayRow(row)),
10709                            };
10710                        }
10711                    }
10712                    unique_rows
10713                },
10714            )
10715    }
10716
10717    pub fn highlighted_display_row_for_autoscroll(
10718        &self,
10719        snapshot: &DisplaySnapshot,
10720    ) -> Option<DisplayRow> {
10721        self.highlighted_rows
10722            .values()
10723            .flat_map(|highlighted_rows| highlighted_rows.iter())
10724            .filter_map(|highlight| {
10725                if highlight.color.is_none() || !highlight.should_autoscroll {
10726                    return None;
10727                }
10728                Some(highlight.range.start().to_display_point(&snapshot).row())
10729            })
10730            .min()
10731    }
10732
10733    pub fn set_search_within_ranges(
10734        &mut self,
10735        ranges: &[Range<Anchor>],
10736        cx: &mut ViewContext<Self>,
10737    ) {
10738        self.highlight_background::<SearchWithinRange>(
10739            ranges,
10740            |colors| colors.editor_document_highlight_read_background,
10741            cx,
10742        )
10743    }
10744
10745    pub fn set_breadcrumb_header(&mut self, new_header: String) {
10746        self.breadcrumb_header = Some(new_header);
10747    }
10748
10749    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10750        self.clear_background_highlights::<SearchWithinRange>(cx);
10751    }
10752
10753    pub fn highlight_background<T: 'static>(
10754        &mut self,
10755        ranges: &[Range<Anchor>],
10756        color_fetcher: fn(&ThemeColors) -> Hsla,
10757        cx: &mut ViewContext<Self>,
10758    ) {
10759        let snapshot = self.snapshot(cx);
10760        // this is to try and catch a panic sooner
10761        for range in ranges {
10762            snapshot
10763                .buffer_snapshot
10764                .summary_for_anchor::<usize>(&range.start);
10765            snapshot
10766                .buffer_snapshot
10767                .summary_for_anchor::<usize>(&range.end);
10768        }
10769
10770        self.background_highlights
10771            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10772        self.scrollbar_marker_state.dirty = true;
10773        cx.notify();
10774    }
10775
10776    pub fn clear_background_highlights<T: 'static>(
10777        &mut self,
10778        cx: &mut ViewContext<Self>,
10779    ) -> Option<BackgroundHighlight> {
10780        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10781        if !text_highlights.1.is_empty() {
10782            self.scrollbar_marker_state.dirty = true;
10783            cx.notify();
10784        }
10785        Some(text_highlights)
10786    }
10787
10788    pub fn highlight_gutter<T: 'static>(
10789        &mut self,
10790        ranges: &[Range<Anchor>],
10791        color_fetcher: fn(&AppContext) -> Hsla,
10792        cx: &mut ViewContext<Self>,
10793    ) {
10794        self.gutter_highlights
10795            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10796        cx.notify();
10797    }
10798
10799    pub fn clear_gutter_highlights<T: 'static>(
10800        &mut self,
10801        cx: &mut ViewContext<Self>,
10802    ) -> Option<GutterHighlight> {
10803        cx.notify();
10804        self.gutter_highlights.remove(&TypeId::of::<T>())
10805    }
10806
10807    #[cfg(feature = "test-support")]
10808    pub fn all_text_background_highlights(
10809        &mut self,
10810        cx: &mut ViewContext<Self>,
10811    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10812        let snapshot = self.snapshot(cx);
10813        let buffer = &snapshot.buffer_snapshot;
10814        let start = buffer.anchor_before(0);
10815        let end = buffer.anchor_after(buffer.len());
10816        let theme = cx.theme().colors();
10817        self.background_highlights_in_range(start..end, &snapshot, theme)
10818    }
10819
10820    #[cfg(feature = "test-support")]
10821    pub fn search_background_highlights(
10822        &mut self,
10823        cx: &mut ViewContext<Self>,
10824    ) -> Vec<Range<Point>> {
10825        let snapshot = self.buffer().read(cx).snapshot(cx);
10826
10827        let highlights = self
10828            .background_highlights
10829            .get(&TypeId::of::<items::BufferSearchHighlights>());
10830
10831        if let Some((_color, ranges)) = highlights {
10832            ranges
10833                .iter()
10834                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
10835                .collect_vec()
10836        } else {
10837            vec![]
10838        }
10839    }
10840
10841    fn document_highlights_for_position<'a>(
10842        &'a self,
10843        position: Anchor,
10844        buffer: &'a MultiBufferSnapshot,
10845    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
10846        let read_highlights = self
10847            .background_highlights
10848            .get(&TypeId::of::<DocumentHighlightRead>())
10849            .map(|h| &h.1);
10850        let write_highlights = self
10851            .background_highlights
10852            .get(&TypeId::of::<DocumentHighlightWrite>())
10853            .map(|h| &h.1);
10854        let left_position = position.bias_left(buffer);
10855        let right_position = position.bias_right(buffer);
10856        read_highlights
10857            .into_iter()
10858            .chain(write_highlights)
10859            .flat_map(move |ranges| {
10860                let start_ix = match ranges.binary_search_by(|probe| {
10861                    let cmp = probe.end.cmp(&left_position, buffer);
10862                    if cmp.is_ge() {
10863                        Ordering::Greater
10864                    } else {
10865                        Ordering::Less
10866                    }
10867                }) {
10868                    Ok(i) | Err(i) => i,
10869                };
10870
10871                ranges[start_ix..]
10872                    .iter()
10873                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
10874            })
10875    }
10876
10877    pub fn has_background_highlights<T: 'static>(&self) -> bool {
10878        self.background_highlights
10879            .get(&TypeId::of::<T>())
10880            .map_or(false, |(_, highlights)| !highlights.is_empty())
10881    }
10882
10883    pub fn background_highlights_in_range(
10884        &self,
10885        search_range: Range<Anchor>,
10886        display_snapshot: &DisplaySnapshot,
10887        theme: &ThemeColors,
10888    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10889        let mut results = Vec::new();
10890        for (color_fetcher, ranges) in self.background_highlights.values() {
10891            let color = color_fetcher(theme);
10892            let start_ix = match ranges.binary_search_by(|probe| {
10893                let cmp = probe
10894                    .end
10895                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10896                if cmp.is_gt() {
10897                    Ordering::Greater
10898                } else {
10899                    Ordering::Less
10900                }
10901            }) {
10902                Ok(i) | Err(i) => i,
10903            };
10904            for range in &ranges[start_ix..] {
10905                if range
10906                    .start
10907                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10908                    .is_ge()
10909                {
10910                    break;
10911                }
10912
10913                let start = range.start.to_display_point(&display_snapshot);
10914                let end = range.end.to_display_point(&display_snapshot);
10915                results.push((start..end, color))
10916            }
10917        }
10918        results
10919    }
10920
10921    pub fn background_highlight_row_ranges<T: 'static>(
10922        &self,
10923        search_range: Range<Anchor>,
10924        display_snapshot: &DisplaySnapshot,
10925        count: usize,
10926    ) -> Vec<RangeInclusive<DisplayPoint>> {
10927        let mut results = Vec::new();
10928        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
10929            return vec![];
10930        };
10931
10932        let start_ix = match ranges.binary_search_by(|probe| {
10933            let cmp = probe
10934                .end
10935                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10936            if cmp.is_gt() {
10937                Ordering::Greater
10938            } else {
10939                Ordering::Less
10940            }
10941        }) {
10942            Ok(i) | Err(i) => i,
10943        };
10944        let mut push_region = |start: Option<Point>, end: Option<Point>| {
10945            if let (Some(start_display), Some(end_display)) = (start, end) {
10946                results.push(
10947                    start_display.to_display_point(display_snapshot)
10948                        ..=end_display.to_display_point(display_snapshot),
10949                );
10950            }
10951        };
10952        let mut start_row: Option<Point> = None;
10953        let mut end_row: Option<Point> = None;
10954        if ranges.len() > count {
10955            return Vec::new();
10956        }
10957        for range in &ranges[start_ix..] {
10958            if range
10959                .start
10960                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10961                .is_ge()
10962            {
10963                break;
10964            }
10965            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
10966            if let Some(current_row) = &end_row {
10967                if end.row == current_row.row {
10968                    continue;
10969                }
10970            }
10971            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
10972            if start_row.is_none() {
10973                assert_eq!(end_row, None);
10974                start_row = Some(start);
10975                end_row = Some(end);
10976                continue;
10977            }
10978            if let Some(current_end) = end_row.as_mut() {
10979                if start.row > current_end.row + 1 {
10980                    push_region(start_row, end_row);
10981                    start_row = Some(start);
10982                    end_row = Some(end);
10983                } else {
10984                    // Merge two hunks.
10985                    *current_end = end;
10986                }
10987            } else {
10988                unreachable!();
10989            }
10990        }
10991        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
10992        push_region(start_row, end_row);
10993        results
10994    }
10995
10996    pub fn gutter_highlights_in_range(
10997        &self,
10998        search_range: Range<Anchor>,
10999        display_snapshot: &DisplaySnapshot,
11000        cx: &AppContext,
11001    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11002        let mut results = Vec::new();
11003        for (color_fetcher, ranges) in self.gutter_highlights.values() {
11004            let color = color_fetcher(cx);
11005            let start_ix = match ranges.binary_search_by(|probe| {
11006                let cmp = probe
11007                    .end
11008                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11009                if cmp.is_gt() {
11010                    Ordering::Greater
11011                } else {
11012                    Ordering::Less
11013                }
11014            }) {
11015                Ok(i) | Err(i) => i,
11016            };
11017            for range in &ranges[start_ix..] {
11018                if range
11019                    .start
11020                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11021                    .is_ge()
11022                {
11023                    break;
11024                }
11025
11026                let start = range.start.to_display_point(&display_snapshot);
11027                let end = range.end.to_display_point(&display_snapshot);
11028                results.push((start..end, color))
11029            }
11030        }
11031        results
11032    }
11033
11034    /// Get the text ranges corresponding to the redaction query
11035    pub fn redacted_ranges(
11036        &self,
11037        search_range: Range<Anchor>,
11038        display_snapshot: &DisplaySnapshot,
11039        cx: &WindowContext,
11040    ) -> Vec<Range<DisplayPoint>> {
11041        display_snapshot
11042            .buffer_snapshot
11043            .redacted_ranges(search_range, |file| {
11044                if let Some(file) = file {
11045                    file.is_private()
11046                        && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11047                } else {
11048                    false
11049                }
11050            })
11051            .map(|range| {
11052                range.start.to_display_point(display_snapshot)
11053                    ..range.end.to_display_point(display_snapshot)
11054            })
11055            .collect()
11056    }
11057
11058    pub fn highlight_text<T: 'static>(
11059        &mut self,
11060        ranges: Vec<Range<Anchor>>,
11061        style: HighlightStyle,
11062        cx: &mut ViewContext<Self>,
11063    ) {
11064        self.display_map.update(cx, |map, _| {
11065            map.highlight_text(TypeId::of::<T>(), ranges, style)
11066        });
11067        cx.notify();
11068    }
11069
11070    pub(crate) fn highlight_inlays<T: 'static>(
11071        &mut self,
11072        highlights: Vec<InlayHighlight>,
11073        style: HighlightStyle,
11074        cx: &mut ViewContext<Self>,
11075    ) {
11076        self.display_map.update(cx, |map, _| {
11077            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11078        });
11079        cx.notify();
11080    }
11081
11082    pub fn text_highlights<'a, T: 'static>(
11083        &'a self,
11084        cx: &'a AppContext,
11085    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11086        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11087    }
11088
11089    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11090        let cleared = self
11091            .display_map
11092            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11093        if cleared {
11094            cx.notify();
11095        }
11096    }
11097
11098    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11099        (self.read_only(cx) || self.blink_manager.read(cx).visible())
11100            && self.focus_handle.is_focused(cx)
11101    }
11102
11103    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11104        self.show_cursor_when_unfocused = is_enabled;
11105        cx.notify();
11106    }
11107
11108    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11109        cx.notify();
11110    }
11111
11112    fn on_buffer_event(
11113        &mut self,
11114        multibuffer: Model<MultiBuffer>,
11115        event: &multi_buffer::Event,
11116        cx: &mut ViewContext<Self>,
11117    ) {
11118        match event {
11119            multi_buffer::Event::Edited {
11120                singleton_buffer_edited,
11121            } => {
11122                self.scrollbar_marker_state.dirty = true;
11123                self.active_indent_guides_state.dirty = true;
11124                self.refresh_active_diagnostics(cx);
11125                self.refresh_code_actions(cx);
11126                if self.has_active_inline_completion(cx) {
11127                    self.update_visible_inline_completion(cx);
11128                }
11129                cx.emit(EditorEvent::BufferEdited);
11130                cx.emit(SearchEvent::MatchesInvalidated);
11131                if *singleton_buffer_edited {
11132                    if let Some(project) = &self.project {
11133                        let project = project.read(cx);
11134                        #[allow(clippy::mutable_key_type)]
11135                        let languages_affected = multibuffer
11136                            .read(cx)
11137                            .all_buffers()
11138                            .into_iter()
11139                            .filter_map(|buffer| {
11140                                let buffer = buffer.read(cx);
11141                                let language = buffer.language()?;
11142                                if project.is_local()
11143                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
11144                                {
11145                                    None
11146                                } else {
11147                                    Some(language)
11148                                }
11149                            })
11150                            .cloned()
11151                            .collect::<HashSet<_>>();
11152                        if !languages_affected.is_empty() {
11153                            self.refresh_inlay_hints(
11154                                InlayHintRefreshReason::BufferEdited(languages_affected),
11155                                cx,
11156                            );
11157                        }
11158                    }
11159                }
11160
11161                let Some(project) = &self.project else { return };
11162                let telemetry = project.read(cx).client().telemetry().clone();
11163                refresh_linked_ranges(self, cx);
11164                telemetry.log_edit_event("editor");
11165            }
11166            multi_buffer::Event::ExcerptsAdded {
11167                buffer,
11168                predecessor,
11169                excerpts,
11170            } => {
11171                self.tasks_update_task = Some(self.refresh_runnables(cx));
11172                cx.emit(EditorEvent::ExcerptsAdded {
11173                    buffer: buffer.clone(),
11174                    predecessor: *predecessor,
11175                    excerpts: excerpts.clone(),
11176                });
11177                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11178            }
11179            multi_buffer::Event::ExcerptsRemoved { ids } => {
11180                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11181                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11182            }
11183            multi_buffer::Event::ExcerptsEdited { ids } => {
11184                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11185            }
11186            multi_buffer::Event::ExcerptsExpanded { ids } => {
11187                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11188            }
11189            multi_buffer::Event::Reparsed(buffer_id) => {
11190                self.tasks_update_task = Some(self.refresh_runnables(cx));
11191
11192                cx.emit(EditorEvent::Reparsed(*buffer_id));
11193            }
11194            multi_buffer::Event::LanguageChanged(buffer_id) => {
11195                linked_editing_ranges::refresh_linked_ranges(self, cx);
11196                cx.emit(EditorEvent::Reparsed(*buffer_id));
11197                cx.notify();
11198            }
11199            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11200            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11201            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11202                cx.emit(EditorEvent::TitleChanged)
11203            }
11204            multi_buffer::Event::DiffBaseChanged => {
11205                self.scrollbar_marker_state.dirty = true;
11206                cx.emit(EditorEvent::DiffBaseChanged);
11207                cx.notify();
11208            }
11209            multi_buffer::Event::DiffUpdated { buffer } => {
11210                self.sync_expanded_diff_hunks(buffer.clone(), cx);
11211                cx.notify();
11212            }
11213            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11214            multi_buffer::Event::DiagnosticsUpdated => {
11215                self.refresh_active_diagnostics(cx);
11216                self.scrollbar_marker_state.dirty = true;
11217                cx.notify();
11218            }
11219            _ => {}
11220        };
11221    }
11222
11223    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11224        cx.notify();
11225    }
11226
11227    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11228        self.tasks_update_task = Some(self.refresh_runnables(cx));
11229        self.refresh_inline_completion(true, cx);
11230        self.refresh_inlay_hints(
11231            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11232                self.selections.newest_anchor().head(),
11233                &self.buffer.read(cx).snapshot(cx),
11234                cx,
11235            )),
11236            cx,
11237        );
11238        let editor_settings = EditorSettings::get_global(cx);
11239        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11240        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11241
11242        if self.mode == EditorMode::Full {
11243            let inline_blame_enabled = ProjectSettings::get_global(cx).git.inline_blame_enabled();
11244            if self.git_blame_inline_enabled != inline_blame_enabled {
11245                self.toggle_git_blame_inline_internal(false, cx);
11246            }
11247        }
11248
11249        cx.notify();
11250    }
11251
11252    pub fn set_searchable(&mut self, searchable: bool) {
11253        self.searchable = searchable;
11254    }
11255
11256    pub fn searchable(&self) -> bool {
11257        self.searchable
11258    }
11259
11260    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11261        self.open_excerpts_common(true, cx)
11262    }
11263
11264    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11265        self.open_excerpts_common(false, cx)
11266    }
11267
11268    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11269        let buffer = self.buffer.read(cx);
11270        if buffer.is_singleton() {
11271            cx.propagate();
11272            return;
11273        }
11274
11275        let Some(workspace) = self.workspace() else {
11276            cx.propagate();
11277            return;
11278        };
11279
11280        let mut new_selections_by_buffer = HashMap::default();
11281        for selection in self.selections.all::<usize>(cx) {
11282            for (buffer, mut range, _) in
11283                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11284            {
11285                if selection.reversed {
11286                    mem::swap(&mut range.start, &mut range.end);
11287                }
11288                new_selections_by_buffer
11289                    .entry(buffer)
11290                    .or_insert(Vec::new())
11291                    .push(range)
11292            }
11293        }
11294
11295        // We defer the pane interaction because we ourselves are a workspace item
11296        // and activating a new item causes the pane to call a method on us reentrantly,
11297        // which panics if we're on the stack.
11298        cx.window_context().defer(move |cx| {
11299            workspace.update(cx, |workspace, cx| {
11300                let pane = if split {
11301                    workspace.adjacent_pane(cx)
11302                } else {
11303                    workspace.active_pane().clone()
11304                };
11305
11306                for (buffer, ranges) in new_selections_by_buffer {
11307                    let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
11308                    editor.update(cx, |editor, cx| {
11309                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11310                            s.select_ranges(ranges);
11311                        });
11312                    });
11313                }
11314            })
11315        });
11316    }
11317
11318    fn jump(
11319        &mut self,
11320        path: ProjectPath,
11321        position: Point,
11322        anchor: language::Anchor,
11323        offset_from_top: u32,
11324        cx: &mut ViewContext<Self>,
11325    ) {
11326        let workspace = self.workspace();
11327        cx.spawn(|_, mut cx| async move {
11328            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11329            let editor = workspace.update(&mut cx, |workspace, cx| {
11330                // Reset the preview item id before opening the new item
11331                workspace.active_pane().update(cx, |pane, cx| {
11332                    pane.set_preview_item_id(None, cx);
11333                });
11334                workspace.open_path_preview(path, None, true, true, cx)
11335            })?;
11336            let editor = editor
11337                .await?
11338                .downcast::<Editor>()
11339                .ok_or_else(|| anyhow!("opened item was not an editor"))?
11340                .downgrade();
11341            editor.update(&mut cx, |editor, cx| {
11342                let buffer = editor
11343                    .buffer()
11344                    .read(cx)
11345                    .as_singleton()
11346                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11347                let buffer = buffer.read(cx);
11348                let cursor = if buffer.can_resolve(&anchor) {
11349                    language::ToPoint::to_point(&anchor, buffer)
11350                } else {
11351                    buffer.clip_point(position, Bias::Left)
11352                };
11353
11354                let nav_history = editor.nav_history.take();
11355                editor.change_selections(
11356                    Some(Autoscroll::top_relative(offset_from_top as usize)),
11357                    cx,
11358                    |s| {
11359                        s.select_ranges([cursor..cursor]);
11360                    },
11361                );
11362                editor.nav_history = nav_history;
11363
11364                anyhow::Ok(())
11365            })??;
11366
11367            anyhow::Ok(())
11368        })
11369        .detach_and_log_err(cx);
11370    }
11371
11372    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11373        let snapshot = self.buffer.read(cx).read(cx);
11374        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11375        Some(
11376            ranges
11377                .iter()
11378                .map(move |range| {
11379                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11380                })
11381                .collect(),
11382        )
11383    }
11384
11385    fn selection_replacement_ranges(
11386        &self,
11387        range: Range<OffsetUtf16>,
11388        cx: &AppContext,
11389    ) -> Vec<Range<OffsetUtf16>> {
11390        let selections = self.selections.all::<OffsetUtf16>(cx);
11391        let newest_selection = selections
11392            .iter()
11393            .max_by_key(|selection| selection.id)
11394            .unwrap();
11395        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11396        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11397        let snapshot = self.buffer.read(cx).read(cx);
11398        selections
11399            .into_iter()
11400            .map(|mut selection| {
11401                selection.start.0 =
11402                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
11403                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11404                snapshot.clip_offset_utf16(selection.start, Bias::Left)
11405                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11406            })
11407            .collect()
11408    }
11409
11410    fn report_editor_event(
11411        &self,
11412        operation: &'static str,
11413        file_extension: Option<String>,
11414        cx: &AppContext,
11415    ) {
11416        if cfg!(any(test, feature = "test-support")) {
11417            return;
11418        }
11419
11420        let Some(project) = &self.project else { return };
11421
11422        // If None, we are in a file without an extension
11423        let file = self
11424            .buffer
11425            .read(cx)
11426            .as_singleton()
11427            .and_then(|b| b.read(cx).file());
11428        let file_extension = file_extension.or(file
11429            .as_ref()
11430            .and_then(|file| Path::new(file.file_name(cx)).extension())
11431            .and_then(|e| e.to_str())
11432            .map(|a| a.to_string()));
11433
11434        let vim_mode = cx
11435            .global::<SettingsStore>()
11436            .raw_user_settings()
11437            .get("vim_mode")
11438            == Some(&serde_json::Value::Bool(true));
11439
11440        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11441            == language::language_settings::InlineCompletionProvider::Copilot;
11442        let copilot_enabled_for_language = self
11443            .buffer
11444            .read(cx)
11445            .settings_at(0, cx)
11446            .show_inline_completions;
11447
11448        let telemetry = project.read(cx).client().telemetry().clone();
11449        telemetry.report_editor_event(
11450            file_extension,
11451            vim_mode,
11452            operation,
11453            copilot_enabled,
11454            copilot_enabled_for_language,
11455        )
11456    }
11457
11458    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11459    /// with each line being an array of {text, highlight} objects.
11460    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11461        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11462            return;
11463        };
11464
11465        #[derive(Serialize)]
11466        struct Chunk<'a> {
11467            text: String,
11468            highlight: Option<&'a str>,
11469        }
11470
11471        let snapshot = buffer.read(cx).snapshot();
11472        let range = self
11473            .selected_text_range(cx)
11474            .and_then(|selected_range| {
11475                if selected_range.is_empty() {
11476                    None
11477                } else {
11478                    Some(selected_range)
11479                }
11480            })
11481            .unwrap_or_else(|| 0..snapshot.len());
11482
11483        let chunks = snapshot.chunks(range, true);
11484        let mut lines = Vec::new();
11485        let mut line: VecDeque<Chunk> = VecDeque::new();
11486
11487        let Some(style) = self.style.as_ref() else {
11488            return;
11489        };
11490
11491        for chunk in chunks {
11492            let highlight = chunk
11493                .syntax_highlight_id
11494                .and_then(|id| id.name(&style.syntax));
11495            let mut chunk_lines = chunk.text.split('\n').peekable();
11496            while let Some(text) = chunk_lines.next() {
11497                let mut merged_with_last_token = false;
11498                if let Some(last_token) = line.back_mut() {
11499                    if last_token.highlight == highlight {
11500                        last_token.text.push_str(text);
11501                        merged_with_last_token = true;
11502                    }
11503                }
11504
11505                if !merged_with_last_token {
11506                    line.push_back(Chunk {
11507                        text: text.into(),
11508                        highlight,
11509                    });
11510                }
11511
11512                if chunk_lines.peek().is_some() {
11513                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
11514                        line.pop_front();
11515                    }
11516                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
11517                        line.pop_back();
11518                    }
11519
11520                    lines.push(mem::take(&mut line));
11521                }
11522            }
11523        }
11524
11525        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11526            return;
11527        };
11528        cx.write_to_clipboard(ClipboardItem::new(lines));
11529    }
11530
11531    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11532        &self.inlay_hint_cache
11533    }
11534
11535    pub fn replay_insert_event(
11536        &mut self,
11537        text: &str,
11538        relative_utf16_range: Option<Range<isize>>,
11539        cx: &mut ViewContext<Self>,
11540    ) {
11541        if !self.input_enabled {
11542            cx.emit(EditorEvent::InputIgnored { text: text.into() });
11543            return;
11544        }
11545        if let Some(relative_utf16_range) = relative_utf16_range {
11546            let selections = self.selections.all::<OffsetUtf16>(cx);
11547            self.change_selections(None, cx, |s| {
11548                let new_ranges = selections.into_iter().map(|range| {
11549                    let start = OffsetUtf16(
11550                        range
11551                            .head()
11552                            .0
11553                            .saturating_add_signed(relative_utf16_range.start),
11554                    );
11555                    let end = OffsetUtf16(
11556                        range
11557                            .head()
11558                            .0
11559                            .saturating_add_signed(relative_utf16_range.end),
11560                    );
11561                    start..end
11562                });
11563                s.select_ranges(new_ranges);
11564            });
11565        }
11566
11567        self.handle_input(text, cx);
11568    }
11569
11570    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11571        let Some(project) = self.project.as_ref() else {
11572            return false;
11573        };
11574        let project = project.read(cx);
11575
11576        let mut supports = false;
11577        self.buffer().read(cx).for_each_buffer(|buffer| {
11578            if !supports {
11579                supports = project
11580                    .language_servers_for_buffer(buffer.read(cx), cx)
11581                    .any(
11582                        |(_, server)| match server.capabilities().inlay_hint_provider {
11583                            Some(lsp::OneOf::Left(enabled)) => enabled,
11584                            Some(lsp::OneOf::Right(_)) => true,
11585                            None => false,
11586                        },
11587                    )
11588            }
11589        });
11590        supports
11591    }
11592
11593    pub fn focus(&self, cx: &mut WindowContext) {
11594        cx.focus(&self.focus_handle)
11595    }
11596
11597    pub fn is_focused(&self, cx: &WindowContext) -> bool {
11598        self.focus_handle.is_focused(cx)
11599    }
11600
11601    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11602        cx.emit(EditorEvent::Focused);
11603
11604        if let Some(descendant) = self
11605            .last_focused_descendant
11606            .take()
11607            .and_then(|descendant| descendant.upgrade())
11608        {
11609            cx.focus(&descendant);
11610        } else {
11611            if let Some(blame) = self.blame.as_ref() {
11612                blame.update(cx, GitBlame::focus)
11613            }
11614
11615            self.blink_manager.update(cx, BlinkManager::enable);
11616            self.show_cursor_names(cx);
11617            self.buffer.update(cx, |buffer, cx| {
11618                buffer.finalize_last_transaction(cx);
11619                if self.leader_peer_id.is_none() {
11620                    buffer.set_active_selections(
11621                        &self.selections.disjoint_anchors(),
11622                        self.selections.line_mode,
11623                        self.cursor_shape,
11624                        cx,
11625                    );
11626                }
11627            });
11628        }
11629    }
11630
11631    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11632        if event.blurred != self.focus_handle {
11633            self.last_focused_descendant = Some(event.blurred);
11634        }
11635    }
11636
11637    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11638        self.blink_manager.update(cx, BlinkManager::disable);
11639        self.buffer
11640            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11641
11642        if let Some(blame) = self.blame.as_ref() {
11643            blame.update(cx, GitBlame::blur)
11644        }
11645        if !self.hover_state.focused(cx) {
11646            hide_hover(self, cx);
11647        }
11648
11649        self.hide_context_menu(cx);
11650        cx.emit(EditorEvent::Blurred);
11651        cx.notify();
11652    }
11653
11654    pub fn register_action<A: Action>(
11655        &mut self,
11656        listener: impl Fn(&A, &mut WindowContext) + 'static,
11657    ) -> Subscription {
11658        let id = self.next_editor_action_id.post_inc();
11659        let listener = Arc::new(listener);
11660        self.editor_actions.borrow_mut().insert(
11661            id,
11662            Box::new(move |cx| {
11663                let _view = cx.view().clone();
11664                let cx = cx.window_context();
11665                let listener = listener.clone();
11666                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11667                    let action = action.downcast_ref().unwrap();
11668                    if phase == DispatchPhase::Bubble {
11669                        listener(action, cx)
11670                    }
11671                })
11672            }),
11673        );
11674
11675        let editor_actions = self.editor_actions.clone();
11676        Subscription::new(move || {
11677            editor_actions.borrow_mut().remove(&id);
11678        })
11679    }
11680
11681    pub fn file_header_size(&self) -> u8 {
11682        self.file_header_size
11683    }
11684}
11685
11686fn hunks_for_selections(
11687    multi_buffer_snapshot: &MultiBufferSnapshot,
11688    selections: &[Selection<Anchor>],
11689) -> Vec<DiffHunk<MultiBufferRow>> {
11690    let mut hunks = Vec::with_capacity(selections.len());
11691    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11692        HashMap::default();
11693    let buffer_rows_for_selections = selections.iter().map(|selection| {
11694        let head = selection.head();
11695        let tail = selection.tail();
11696        let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11697        let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11698        if start > end {
11699            end..start
11700        } else {
11701            start..end
11702        }
11703    });
11704
11705    for selected_multi_buffer_rows in buffer_rows_for_selections {
11706        let query_rows =
11707            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11708        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11709            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11710            // when the caret is just above or just below the deleted hunk.
11711            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11712            let related_to_selection = if allow_adjacent {
11713                hunk.associated_range.overlaps(&query_rows)
11714                    || hunk.associated_range.start == query_rows.end
11715                    || hunk.associated_range.end == query_rows.start
11716            } else {
11717                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11718                // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11719                hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11720                    || selected_multi_buffer_rows.end == hunk.associated_range.start
11721            };
11722            if related_to_selection {
11723                if !processed_buffer_rows
11724                    .entry(hunk.buffer_id)
11725                    .or_default()
11726                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
11727                {
11728                    continue;
11729                }
11730                hunks.push(hunk);
11731            }
11732        }
11733    }
11734
11735    hunks
11736}
11737
11738pub trait CollaborationHub {
11739    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
11740    fn user_participant_indices<'a>(
11741        &self,
11742        cx: &'a AppContext,
11743    ) -> &'a HashMap<u64, ParticipantIndex>;
11744    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
11745}
11746
11747impl CollaborationHub for Model<Project> {
11748    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
11749        self.read(cx).collaborators()
11750    }
11751
11752    fn user_participant_indices<'a>(
11753        &self,
11754        cx: &'a AppContext,
11755    ) -> &'a HashMap<u64, ParticipantIndex> {
11756        self.read(cx).user_store().read(cx).participant_indices()
11757    }
11758
11759    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
11760        let this = self.read(cx);
11761        let user_ids = this.collaborators().values().map(|c| c.user_id);
11762        this.user_store().read_with(cx, |user_store, cx| {
11763            user_store.participant_names(user_ids, cx)
11764        })
11765    }
11766}
11767
11768pub trait CompletionProvider {
11769    fn completions(
11770        &self,
11771        buffer: &Model<Buffer>,
11772        buffer_position: text::Anchor,
11773        trigger: CompletionContext,
11774        cx: &mut ViewContext<Editor>,
11775    ) -> Task<Result<Vec<Completion>>>;
11776
11777    fn resolve_completions(
11778        &self,
11779        buffer: Model<Buffer>,
11780        completion_indices: Vec<usize>,
11781        completions: Arc<RwLock<Box<[Completion]>>>,
11782        cx: &mut ViewContext<Editor>,
11783    ) -> Task<Result<bool>>;
11784
11785    fn apply_additional_edits_for_completion(
11786        &self,
11787        buffer: Model<Buffer>,
11788        completion: Completion,
11789        push_to_history: bool,
11790        cx: &mut ViewContext<Editor>,
11791    ) -> Task<Result<Option<language::Transaction>>>;
11792
11793    fn is_completion_trigger(
11794        &self,
11795        buffer: &Model<Buffer>,
11796        position: language::Anchor,
11797        text: &str,
11798        trigger_in_words: bool,
11799        cx: &mut ViewContext<Editor>,
11800    ) -> bool;
11801}
11802
11803fn snippet_completions(
11804    project: &Project,
11805    buffer: &Model<Buffer>,
11806    buffer_position: text::Anchor,
11807    cx: &mut AppContext,
11808) -> Vec<Completion> {
11809    let language = buffer.read(cx).language_at(buffer_position);
11810    let language_name = language.as_ref().map(|language| language.lsp_id());
11811    let snippet_store = project.snippets().read(cx);
11812    let snippets = snippet_store.snippets_for(language_name, cx);
11813
11814    if snippets.is_empty() {
11815        return vec![];
11816    }
11817    let snapshot = buffer.read(cx).text_snapshot();
11818    let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
11819
11820    let mut lines = chunks.lines();
11821    let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
11822        return vec![];
11823    };
11824
11825    let scope = language.map(|language| language.default_scope());
11826    let mut last_word = line_at
11827        .chars()
11828        .rev()
11829        .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
11830        .collect::<String>();
11831    last_word = last_word.chars().rev().collect();
11832    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
11833    let to_lsp = |point: &text::Anchor| {
11834        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
11835        point_to_lsp(end)
11836    };
11837    let lsp_end = to_lsp(&buffer_position);
11838    snippets
11839        .into_iter()
11840        .filter_map(|snippet| {
11841            let matching_prefix = snippet
11842                .prefix
11843                .iter()
11844                .find(|prefix| prefix.starts_with(&last_word))?;
11845            let start = as_offset - last_word.len();
11846            let start = snapshot.anchor_before(start);
11847            let range = start..buffer_position;
11848            let lsp_start = to_lsp(&start);
11849            let lsp_range = lsp::Range {
11850                start: lsp_start,
11851                end: lsp_end,
11852            };
11853            Some(Completion {
11854                old_range: range,
11855                new_text: snippet.body.clone(),
11856                label: CodeLabel {
11857                    text: matching_prefix.clone(),
11858                    runs: vec![],
11859                    filter_range: 0..matching_prefix.len(),
11860                },
11861                server_id: LanguageServerId(usize::MAX),
11862                documentation: snippet
11863                    .description
11864                    .clone()
11865                    .map(|description| Documentation::SingleLine(description)),
11866                lsp_completion: lsp::CompletionItem {
11867                    label: snippet.prefix.first().unwrap().clone(),
11868                    kind: Some(CompletionItemKind::SNIPPET),
11869                    label_details: snippet.description.as_ref().map(|description| {
11870                        lsp::CompletionItemLabelDetails {
11871                            detail: Some(description.clone()),
11872                            description: None,
11873                        }
11874                    }),
11875                    insert_text_format: Some(InsertTextFormat::SNIPPET),
11876                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
11877                        lsp::InsertReplaceEdit {
11878                            new_text: snippet.body.clone(),
11879                            insert: lsp_range,
11880                            replace: lsp_range,
11881                        },
11882                    )),
11883                    filter_text: Some(snippet.body.clone()),
11884                    sort_text: Some(char::MAX.to_string()),
11885                    ..Default::default()
11886                },
11887                confirm: None,
11888                show_new_completions_on_confirm: false,
11889            })
11890        })
11891        .collect()
11892}
11893
11894impl CompletionProvider for Model<Project> {
11895    fn completions(
11896        &self,
11897        buffer: &Model<Buffer>,
11898        buffer_position: text::Anchor,
11899        options: CompletionContext,
11900        cx: &mut ViewContext<Editor>,
11901    ) -> Task<Result<Vec<Completion>>> {
11902        self.update(cx, |project, cx| {
11903            let snippets = snippet_completions(project, buffer, buffer_position, cx);
11904            let project_completions = project.completions(&buffer, buffer_position, options, cx);
11905            cx.background_executor().spawn(async move {
11906                let mut completions = project_completions.await?;
11907                //let snippets = snippets.into_iter().;
11908                completions.extend(snippets);
11909                Ok(completions)
11910            })
11911        })
11912    }
11913
11914    fn resolve_completions(
11915        &self,
11916        buffer: Model<Buffer>,
11917        completion_indices: Vec<usize>,
11918        completions: Arc<RwLock<Box<[Completion]>>>,
11919        cx: &mut ViewContext<Editor>,
11920    ) -> Task<Result<bool>> {
11921        self.update(cx, |project, cx| {
11922            project.resolve_completions(buffer, completion_indices, completions, cx)
11923        })
11924    }
11925
11926    fn apply_additional_edits_for_completion(
11927        &self,
11928        buffer: Model<Buffer>,
11929        completion: Completion,
11930        push_to_history: bool,
11931        cx: &mut ViewContext<Editor>,
11932    ) -> Task<Result<Option<language::Transaction>>> {
11933        self.update(cx, |project, cx| {
11934            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
11935        })
11936    }
11937
11938    fn is_completion_trigger(
11939        &self,
11940        buffer: &Model<Buffer>,
11941        position: language::Anchor,
11942        text: &str,
11943        trigger_in_words: bool,
11944        cx: &mut ViewContext<Editor>,
11945    ) -> bool {
11946        if !EditorSettings::get_global(cx).show_completions_on_input {
11947            return false;
11948        }
11949
11950        let mut chars = text.chars();
11951        let char = if let Some(char) = chars.next() {
11952            char
11953        } else {
11954            return false;
11955        };
11956        if chars.next().is_some() {
11957            return false;
11958        }
11959
11960        let buffer = buffer.read(cx);
11961        let scope = buffer.snapshot().language_scope_at(position);
11962        if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
11963            return true;
11964        }
11965
11966        buffer
11967            .completion_triggers()
11968            .iter()
11969            .any(|string| string == text)
11970    }
11971}
11972
11973fn inlay_hint_settings(
11974    location: Anchor,
11975    snapshot: &MultiBufferSnapshot,
11976    cx: &mut ViewContext<'_, Editor>,
11977) -> InlayHintSettings {
11978    let file = snapshot.file_at(location);
11979    let language = snapshot.language_at(location);
11980    let settings = all_language_settings(file, cx);
11981    settings
11982        .language(language.map(|l| l.name()).as_deref())
11983        .inlay_hints
11984}
11985
11986fn consume_contiguous_rows(
11987    contiguous_row_selections: &mut Vec<Selection<Point>>,
11988    selection: &Selection<Point>,
11989    display_map: &DisplaySnapshot,
11990    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
11991) -> (MultiBufferRow, MultiBufferRow) {
11992    contiguous_row_selections.push(selection.clone());
11993    let start_row = MultiBufferRow(selection.start.row);
11994    let mut end_row = ending_row(selection, display_map);
11995
11996    while let Some(next_selection) = selections.peek() {
11997        if next_selection.start.row <= end_row.0 {
11998            end_row = ending_row(next_selection, display_map);
11999            contiguous_row_selections.push(selections.next().unwrap().clone());
12000        } else {
12001            break;
12002        }
12003    }
12004    (start_row, end_row)
12005}
12006
12007fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12008    if next_selection.end.column > 0 || next_selection.is_empty() {
12009        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12010    } else {
12011        MultiBufferRow(next_selection.end.row)
12012    }
12013}
12014
12015impl EditorSnapshot {
12016    pub fn remote_selections_in_range<'a>(
12017        &'a self,
12018        range: &'a Range<Anchor>,
12019        collaboration_hub: &dyn CollaborationHub,
12020        cx: &'a AppContext,
12021    ) -> impl 'a + Iterator<Item = RemoteSelection> {
12022        let participant_names = collaboration_hub.user_names(cx);
12023        let participant_indices = collaboration_hub.user_participant_indices(cx);
12024        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12025        let collaborators_by_replica_id = collaborators_by_peer_id
12026            .iter()
12027            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12028            .collect::<HashMap<_, _>>();
12029        self.buffer_snapshot
12030            .selections_in_range(range, false)
12031            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12032                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12033                let participant_index = participant_indices.get(&collaborator.user_id).copied();
12034                let user_name = participant_names.get(&collaborator.user_id).cloned();
12035                Some(RemoteSelection {
12036                    replica_id,
12037                    selection,
12038                    cursor_shape,
12039                    line_mode,
12040                    participant_index,
12041                    peer_id: collaborator.peer_id,
12042                    user_name,
12043                })
12044            })
12045    }
12046
12047    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12048        self.display_snapshot.buffer_snapshot.language_at(position)
12049    }
12050
12051    pub fn is_focused(&self) -> bool {
12052        self.is_focused
12053    }
12054
12055    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12056        self.placeholder_text.as_ref()
12057    }
12058
12059    pub fn scroll_position(&self) -> gpui::Point<f32> {
12060        self.scroll_anchor.scroll_position(&self.display_snapshot)
12061    }
12062
12063    pub fn gutter_dimensions(
12064        &self,
12065        font_id: FontId,
12066        font_size: Pixels,
12067        em_width: Pixels,
12068        max_line_number_width: Pixels,
12069        cx: &AppContext,
12070    ) -> GutterDimensions {
12071        if !self.show_gutter {
12072            return GutterDimensions::default();
12073        }
12074        let descent = cx.text_system().descent(font_id, font_size);
12075
12076        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12077            matches!(
12078                ProjectSettings::get_global(cx).git.git_gutter,
12079                Some(GitGutterSetting::TrackedFiles)
12080            )
12081        });
12082        let gutter_settings = EditorSettings::get_global(cx).gutter;
12083        let show_line_numbers = self
12084            .show_line_numbers
12085            .unwrap_or(gutter_settings.line_numbers);
12086        let line_gutter_width = if show_line_numbers {
12087            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12088            let min_width_for_number_on_gutter = em_width * 4.0;
12089            max_line_number_width.max(min_width_for_number_on_gutter)
12090        } else {
12091            0.0.into()
12092        };
12093
12094        let show_code_actions = self
12095            .show_code_actions
12096            .unwrap_or(gutter_settings.code_actions);
12097
12098        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12099
12100        let git_blame_entries_width = self
12101            .render_git_blame_gutter
12102            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12103
12104        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12105        left_padding += if show_code_actions || show_runnables {
12106            em_width * 3.0
12107        } else if show_git_gutter && show_line_numbers {
12108            em_width * 2.0
12109        } else if show_git_gutter || show_line_numbers {
12110            em_width
12111        } else {
12112            px(0.)
12113        };
12114
12115        let right_padding = if gutter_settings.folds && show_line_numbers {
12116            em_width * 4.0
12117        } else if gutter_settings.folds {
12118            em_width * 3.0
12119        } else if show_line_numbers {
12120            em_width
12121        } else {
12122            px(0.)
12123        };
12124
12125        GutterDimensions {
12126            left_padding,
12127            right_padding,
12128            width: line_gutter_width + left_padding + right_padding,
12129            margin: -descent,
12130            git_blame_entries_width,
12131        }
12132    }
12133
12134    pub fn render_fold_toggle(
12135        &self,
12136        buffer_row: MultiBufferRow,
12137        row_contains_cursor: bool,
12138        editor: View<Editor>,
12139        cx: &mut WindowContext,
12140    ) -> Option<AnyElement> {
12141        let folded = self.is_line_folded(buffer_row);
12142
12143        if let Some(crease) = self
12144            .crease_snapshot
12145            .query_row(buffer_row, &self.buffer_snapshot)
12146        {
12147            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12148                if folded {
12149                    editor.update(cx, |editor, cx| {
12150                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12151                    });
12152                } else {
12153                    editor.update(cx, |editor, cx| {
12154                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12155                    });
12156                }
12157            });
12158
12159            Some((crease.render_toggle)(
12160                buffer_row,
12161                folded,
12162                toggle_callback,
12163                cx,
12164            ))
12165        } else if folded
12166            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12167        {
12168            Some(
12169                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12170                    .selected(folded)
12171                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12172                        if folded {
12173                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
12174                        } else {
12175                            this.fold_at(&FoldAt { buffer_row }, cx);
12176                        }
12177                    }))
12178                    .into_any_element(),
12179            )
12180        } else {
12181            None
12182        }
12183    }
12184
12185    pub fn render_crease_trailer(
12186        &self,
12187        buffer_row: MultiBufferRow,
12188        cx: &mut WindowContext,
12189    ) -> Option<AnyElement> {
12190        let folded = self.is_line_folded(buffer_row);
12191        let crease = self
12192            .crease_snapshot
12193            .query_row(buffer_row, &self.buffer_snapshot)?;
12194        Some((crease.render_trailer)(buffer_row, folded, cx))
12195    }
12196}
12197
12198impl Deref for EditorSnapshot {
12199    type Target = DisplaySnapshot;
12200
12201    fn deref(&self) -> &Self::Target {
12202        &self.display_snapshot
12203    }
12204}
12205
12206#[derive(Clone, Debug, PartialEq, Eq)]
12207pub enum EditorEvent {
12208    InputIgnored {
12209        text: Arc<str>,
12210    },
12211    InputHandled {
12212        utf16_range_to_replace: Option<Range<isize>>,
12213        text: Arc<str>,
12214    },
12215    ExcerptsAdded {
12216        buffer: Model<Buffer>,
12217        predecessor: ExcerptId,
12218        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12219    },
12220    ExcerptsRemoved {
12221        ids: Vec<ExcerptId>,
12222    },
12223    ExcerptsEdited {
12224        ids: Vec<ExcerptId>,
12225    },
12226    ExcerptsExpanded {
12227        ids: Vec<ExcerptId>,
12228    },
12229    BufferEdited,
12230    Edited {
12231        transaction_id: clock::Lamport,
12232    },
12233    Reparsed(BufferId),
12234    Focused,
12235    Blurred,
12236    DirtyChanged,
12237    Saved,
12238    TitleChanged,
12239    DiffBaseChanged,
12240    SelectionsChanged {
12241        local: bool,
12242    },
12243    ScrollPositionChanged {
12244        local: bool,
12245        autoscroll: bool,
12246    },
12247    Closed,
12248    TransactionUndone {
12249        transaction_id: clock::Lamport,
12250    },
12251    TransactionBegun {
12252        transaction_id: clock::Lamport,
12253    },
12254}
12255
12256impl EventEmitter<EditorEvent> for Editor {}
12257
12258impl FocusableView for Editor {
12259    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12260        self.focus_handle.clone()
12261    }
12262}
12263
12264impl Render for Editor {
12265    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12266        let settings = ThemeSettings::get_global(cx);
12267
12268        let text_style = match self.mode {
12269            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12270                color: cx.theme().colors().editor_foreground,
12271                font_family: settings.ui_font.family.clone(),
12272                font_features: settings.ui_font.features.clone(),
12273                font_size: rems(0.875).into(),
12274                font_weight: settings.ui_font.weight,
12275                font_style: FontStyle::Normal,
12276                line_height: relative(settings.buffer_line_height.value()),
12277                background_color: None,
12278                underline: None,
12279                strikethrough: None,
12280                white_space: WhiteSpace::Normal,
12281            },
12282            EditorMode::Full => TextStyle {
12283                color: cx.theme().colors().editor_foreground,
12284                font_family: settings.buffer_font.family.clone(),
12285                font_features: settings.buffer_font.features.clone(),
12286                font_size: settings.buffer_font_size(cx).into(),
12287                font_weight: settings.buffer_font.weight,
12288                font_style: FontStyle::Normal,
12289                line_height: relative(settings.buffer_line_height.value()),
12290                background_color: None,
12291                underline: None,
12292                strikethrough: None,
12293                white_space: WhiteSpace::Normal,
12294            },
12295        };
12296
12297        let background = match self.mode {
12298            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12299            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12300            EditorMode::Full => cx.theme().colors().editor_background,
12301        };
12302
12303        EditorElement::new(
12304            cx.view(),
12305            EditorStyle {
12306                background,
12307                local_player: cx.theme().players().local(),
12308                text: text_style,
12309                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12310                syntax: cx.theme().syntax().clone(),
12311                status: cx.theme().status().clone(),
12312                inlay_hints_style: HighlightStyle {
12313                    color: Some(cx.theme().status().hint),
12314                    ..HighlightStyle::default()
12315                },
12316                suggestions_style: HighlightStyle {
12317                    color: Some(cx.theme().status().predictive),
12318                    ..HighlightStyle::default()
12319                },
12320            },
12321        )
12322    }
12323}
12324
12325impl ViewInputHandler for Editor {
12326    fn text_for_range(
12327        &mut self,
12328        range_utf16: Range<usize>,
12329        cx: &mut ViewContext<Self>,
12330    ) -> Option<String> {
12331        Some(
12332            self.buffer
12333                .read(cx)
12334                .read(cx)
12335                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12336                .collect(),
12337        )
12338    }
12339
12340    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12341        // Prevent the IME menu from appearing when holding down an alphabetic key
12342        // while input is disabled.
12343        if !self.input_enabled {
12344            return None;
12345        }
12346
12347        let range = self.selections.newest::<OffsetUtf16>(cx).range();
12348        Some(range.start.0..range.end.0)
12349    }
12350
12351    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12352        let snapshot = self.buffer.read(cx).read(cx);
12353        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12354        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12355    }
12356
12357    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12358        self.clear_highlights::<InputComposition>(cx);
12359        self.ime_transaction.take();
12360    }
12361
12362    fn replace_text_in_range(
12363        &mut self,
12364        range_utf16: Option<Range<usize>>,
12365        text: &str,
12366        cx: &mut ViewContext<Self>,
12367    ) {
12368        if !self.input_enabled {
12369            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12370            return;
12371        }
12372
12373        self.transact(cx, |this, cx| {
12374            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12375                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12376                Some(this.selection_replacement_ranges(range_utf16, cx))
12377            } else {
12378                this.marked_text_ranges(cx)
12379            };
12380
12381            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12382                let newest_selection_id = this.selections.newest_anchor().id;
12383                this.selections
12384                    .all::<OffsetUtf16>(cx)
12385                    .iter()
12386                    .zip(ranges_to_replace.iter())
12387                    .find_map(|(selection, range)| {
12388                        if selection.id == newest_selection_id {
12389                            Some(
12390                                (range.start.0 as isize - selection.head().0 as isize)
12391                                    ..(range.end.0 as isize - selection.head().0 as isize),
12392                            )
12393                        } else {
12394                            None
12395                        }
12396                    })
12397            });
12398
12399            cx.emit(EditorEvent::InputHandled {
12400                utf16_range_to_replace: range_to_replace,
12401                text: text.into(),
12402            });
12403
12404            if let Some(new_selected_ranges) = new_selected_ranges {
12405                this.change_selections(None, cx, |selections| {
12406                    selections.select_ranges(new_selected_ranges)
12407                });
12408                this.backspace(&Default::default(), cx);
12409            }
12410
12411            this.handle_input(text, cx);
12412        });
12413
12414        if let Some(transaction) = self.ime_transaction {
12415            self.buffer.update(cx, |buffer, cx| {
12416                buffer.group_until_transaction(transaction, cx);
12417            });
12418        }
12419
12420        self.unmark_text(cx);
12421    }
12422
12423    fn replace_and_mark_text_in_range(
12424        &mut self,
12425        range_utf16: Option<Range<usize>>,
12426        text: &str,
12427        new_selected_range_utf16: Option<Range<usize>>,
12428        cx: &mut ViewContext<Self>,
12429    ) {
12430        if !self.input_enabled {
12431            return;
12432        }
12433
12434        let transaction = self.transact(cx, |this, cx| {
12435            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12436                let snapshot = this.buffer.read(cx).read(cx);
12437                if let Some(relative_range_utf16) = range_utf16.as_ref() {
12438                    for marked_range in &mut marked_ranges {
12439                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12440                        marked_range.start.0 += relative_range_utf16.start;
12441                        marked_range.start =
12442                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12443                        marked_range.end =
12444                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12445                    }
12446                }
12447                Some(marked_ranges)
12448            } else if let Some(range_utf16) = range_utf16 {
12449                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12450                Some(this.selection_replacement_ranges(range_utf16, cx))
12451            } else {
12452                None
12453            };
12454
12455            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12456                let newest_selection_id = this.selections.newest_anchor().id;
12457                this.selections
12458                    .all::<OffsetUtf16>(cx)
12459                    .iter()
12460                    .zip(ranges_to_replace.iter())
12461                    .find_map(|(selection, range)| {
12462                        if selection.id == newest_selection_id {
12463                            Some(
12464                                (range.start.0 as isize - selection.head().0 as isize)
12465                                    ..(range.end.0 as isize - selection.head().0 as isize),
12466                            )
12467                        } else {
12468                            None
12469                        }
12470                    })
12471            });
12472
12473            cx.emit(EditorEvent::InputHandled {
12474                utf16_range_to_replace: range_to_replace,
12475                text: text.into(),
12476            });
12477
12478            if let Some(ranges) = ranges_to_replace {
12479                this.change_selections(None, cx, |s| s.select_ranges(ranges));
12480            }
12481
12482            let marked_ranges = {
12483                let snapshot = this.buffer.read(cx).read(cx);
12484                this.selections
12485                    .disjoint_anchors()
12486                    .iter()
12487                    .map(|selection| {
12488                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12489                    })
12490                    .collect::<Vec<_>>()
12491            };
12492
12493            if text.is_empty() {
12494                this.unmark_text(cx);
12495            } else {
12496                this.highlight_text::<InputComposition>(
12497                    marked_ranges.clone(),
12498                    HighlightStyle {
12499                        underline: Some(UnderlineStyle {
12500                            thickness: px(1.),
12501                            color: None,
12502                            wavy: false,
12503                        }),
12504                        ..Default::default()
12505                    },
12506                    cx,
12507                );
12508            }
12509
12510            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12511            let use_autoclose = this.use_autoclose;
12512            let use_auto_surround = this.use_auto_surround;
12513            this.set_use_autoclose(false);
12514            this.set_use_auto_surround(false);
12515            this.handle_input(text, cx);
12516            this.set_use_autoclose(use_autoclose);
12517            this.set_use_auto_surround(use_auto_surround);
12518
12519            if let Some(new_selected_range) = new_selected_range_utf16 {
12520                let snapshot = this.buffer.read(cx).read(cx);
12521                let new_selected_ranges = marked_ranges
12522                    .into_iter()
12523                    .map(|marked_range| {
12524                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12525                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12526                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12527                        snapshot.clip_offset_utf16(new_start, Bias::Left)
12528                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12529                    })
12530                    .collect::<Vec<_>>();
12531
12532                drop(snapshot);
12533                this.change_selections(None, cx, |selections| {
12534                    selections.select_ranges(new_selected_ranges)
12535                });
12536            }
12537        });
12538
12539        self.ime_transaction = self.ime_transaction.or(transaction);
12540        if let Some(transaction) = self.ime_transaction {
12541            self.buffer.update(cx, |buffer, cx| {
12542                buffer.group_until_transaction(transaction, cx);
12543            });
12544        }
12545
12546        if self.text_highlights::<InputComposition>(cx).is_none() {
12547            self.ime_transaction.take();
12548        }
12549    }
12550
12551    fn bounds_for_range(
12552        &mut self,
12553        range_utf16: Range<usize>,
12554        element_bounds: gpui::Bounds<Pixels>,
12555        cx: &mut ViewContext<Self>,
12556    ) -> Option<gpui::Bounds<Pixels>> {
12557        let text_layout_details = self.text_layout_details(cx);
12558        let style = &text_layout_details.editor_style;
12559        let font_id = cx.text_system().resolve_font(&style.text.font());
12560        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12561        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12562
12563        let em_width = cx
12564            .text_system()
12565            .typographic_bounds(font_id, font_size, 'm')
12566            .unwrap()
12567            .size
12568            .width;
12569
12570        let snapshot = self.snapshot(cx);
12571        let scroll_position = snapshot.scroll_position();
12572        let scroll_left = scroll_position.x * em_width;
12573
12574        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12575        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12576            + self.gutter_dimensions.width;
12577        let y = line_height * (start.row().as_f32() - scroll_position.y);
12578
12579        Some(Bounds {
12580            origin: element_bounds.origin + point(x, y),
12581            size: size(em_width, line_height),
12582        })
12583    }
12584}
12585
12586trait SelectionExt {
12587    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12588    fn spanned_rows(
12589        &self,
12590        include_end_if_at_line_start: bool,
12591        map: &DisplaySnapshot,
12592    ) -> Range<MultiBufferRow>;
12593}
12594
12595impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12596    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12597        let start = self
12598            .start
12599            .to_point(&map.buffer_snapshot)
12600            .to_display_point(map);
12601        let end = self
12602            .end
12603            .to_point(&map.buffer_snapshot)
12604            .to_display_point(map);
12605        if self.reversed {
12606            end..start
12607        } else {
12608            start..end
12609        }
12610    }
12611
12612    fn spanned_rows(
12613        &self,
12614        include_end_if_at_line_start: bool,
12615        map: &DisplaySnapshot,
12616    ) -> Range<MultiBufferRow> {
12617        let start = self.start.to_point(&map.buffer_snapshot);
12618        let mut end = self.end.to_point(&map.buffer_snapshot);
12619        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12620            end.row -= 1;
12621        }
12622
12623        let buffer_start = map.prev_line_boundary(start).0;
12624        let buffer_end = map.next_line_boundary(end).0;
12625        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12626    }
12627}
12628
12629impl<T: InvalidationRegion> InvalidationStack<T> {
12630    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12631    where
12632        S: Clone + ToOffset,
12633    {
12634        while let Some(region) = self.last() {
12635            let all_selections_inside_invalidation_ranges =
12636                if selections.len() == region.ranges().len() {
12637                    selections
12638                        .iter()
12639                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12640                        .all(|(selection, invalidation_range)| {
12641                            let head = selection.head().to_offset(buffer);
12642                            invalidation_range.start <= head && invalidation_range.end >= head
12643                        })
12644                } else {
12645                    false
12646                };
12647
12648            if all_selections_inside_invalidation_ranges {
12649                break;
12650            } else {
12651                self.pop();
12652            }
12653        }
12654    }
12655}
12656
12657impl<T> Default for InvalidationStack<T> {
12658    fn default() -> Self {
12659        Self(Default::default())
12660    }
12661}
12662
12663impl<T> Deref for InvalidationStack<T> {
12664    type Target = Vec<T>;
12665
12666    fn deref(&self) -> &Self::Target {
12667        &self.0
12668    }
12669}
12670
12671impl<T> DerefMut for InvalidationStack<T> {
12672    fn deref_mut(&mut self) -> &mut Self::Target {
12673        &mut self.0
12674    }
12675}
12676
12677impl InvalidationRegion for SnippetState {
12678    fn ranges(&self) -> &[Range<Anchor>] {
12679        &self.ranges[self.active_index]
12680    }
12681}
12682
12683pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
12684    let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
12685
12686    Box::new(move |cx: &mut BlockContext| {
12687        let group_id: SharedString = cx.block_id.to_string().into();
12688
12689        let mut text_style = cx.text_style().clone();
12690        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
12691        let theme_settings = ThemeSettings::get_global(cx);
12692        text_style.font_family = theme_settings.buffer_font.family.clone();
12693        text_style.font_style = theme_settings.buffer_font.style;
12694        text_style.font_features = theme_settings.buffer_font.features.clone();
12695        text_style.font_weight = theme_settings.buffer_font.weight;
12696
12697        let multi_line_diagnostic = diagnostic.message.contains('\n');
12698
12699        let buttons = |diagnostic: &Diagnostic, block_id: usize| {
12700            if multi_line_diagnostic {
12701                v_flex()
12702            } else {
12703                h_flex()
12704            }
12705            .children(diagnostic.is_primary.then(|| {
12706                IconButton::new(("close-block", block_id), IconName::XCircle)
12707                    .icon_color(Color::Muted)
12708                    .size(ButtonSize::Compact)
12709                    .style(ButtonStyle::Transparent)
12710                    .visible_on_hover(group_id.clone())
12711                    .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
12712                    .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
12713            }))
12714            .child(
12715                IconButton::new(("copy-block", block_id), IconName::Copy)
12716                    .icon_color(Color::Muted)
12717                    .size(ButtonSize::Compact)
12718                    .style(ButtonStyle::Transparent)
12719                    .visible_on_hover(group_id.clone())
12720                    .on_click({
12721                        let message = diagnostic.message.clone();
12722                        move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
12723                    })
12724                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
12725            )
12726        };
12727
12728        let icon_size = buttons(&diagnostic, cx.block_id)
12729            .into_any_element()
12730            .layout_as_root(AvailableSpace::min_size(), cx);
12731
12732        h_flex()
12733            .id(cx.block_id)
12734            .group(group_id.clone())
12735            .relative()
12736            .size_full()
12737            .pl(cx.gutter_dimensions.width)
12738            .w(cx.max_width + cx.gutter_dimensions.width)
12739            .child(
12740                div()
12741                    .flex()
12742                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
12743                    .flex_shrink(),
12744            )
12745            .child(buttons(&diagnostic, cx.block_id))
12746            .child(div().flex().flex_shrink_0().child(
12747                StyledText::new(text_without_backticks.clone()).with_highlights(
12748                    &text_style,
12749                    code_ranges.iter().map(|range| {
12750                        (
12751                            range.clone(),
12752                            HighlightStyle {
12753                                font_weight: Some(FontWeight::BOLD),
12754                                ..Default::default()
12755                            },
12756                        )
12757                    }),
12758                ),
12759            ))
12760            .into_any_element()
12761    })
12762}
12763
12764pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
12765    let mut text_without_backticks = String::new();
12766    let mut code_ranges = Vec::new();
12767
12768    if let Some(source) = &diagnostic.source {
12769        text_without_backticks.push_str(&source);
12770        code_ranges.push(0..source.len());
12771        text_without_backticks.push_str(": ");
12772    }
12773
12774    let mut prev_offset = 0;
12775    let mut in_code_block = false;
12776    for (ix, _) in diagnostic
12777        .message
12778        .match_indices('`')
12779        .chain([(diagnostic.message.len(), "")])
12780    {
12781        let prev_len = text_without_backticks.len();
12782        text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
12783        prev_offset = ix + 1;
12784        if in_code_block {
12785            code_ranges.push(prev_len..text_without_backticks.len());
12786        }
12787        in_code_block = !in_code_block;
12788    }
12789
12790    (text_without_backticks.into(), code_ranges)
12791}
12792
12793fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
12794    match severity {
12795        DiagnosticSeverity::ERROR => colors.error,
12796        DiagnosticSeverity::WARNING => colors.warning,
12797        DiagnosticSeverity::INFORMATION => colors.info,
12798        DiagnosticSeverity::HINT => colors.info,
12799        _ => colors.ignored,
12800    }
12801}
12802
12803pub fn styled_runs_for_code_label<'a>(
12804    label: &'a CodeLabel,
12805    syntax_theme: &'a theme::SyntaxTheme,
12806) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
12807    let fade_out = HighlightStyle {
12808        fade_out: Some(0.35),
12809        ..Default::default()
12810    };
12811
12812    let mut prev_end = label.filter_range.end;
12813    label
12814        .runs
12815        .iter()
12816        .enumerate()
12817        .flat_map(move |(ix, (range, highlight_id))| {
12818            let style = if let Some(style) = highlight_id.style(syntax_theme) {
12819                style
12820            } else {
12821                return Default::default();
12822            };
12823            let mut muted_style = style;
12824            muted_style.highlight(fade_out);
12825
12826            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
12827            if range.start >= label.filter_range.end {
12828                if range.start > prev_end {
12829                    runs.push((prev_end..range.start, fade_out));
12830                }
12831                runs.push((range.clone(), muted_style));
12832            } else if range.end <= label.filter_range.end {
12833                runs.push((range.clone(), style));
12834            } else {
12835                runs.push((range.start..label.filter_range.end, style));
12836                runs.push((label.filter_range.end..range.end, muted_style));
12837            }
12838            prev_end = cmp::max(prev_end, range.end);
12839
12840            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
12841                runs.push((prev_end..label.text.len(), fade_out));
12842            }
12843
12844            runs
12845        })
12846}
12847
12848pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
12849    let mut prev_index = 0;
12850    let mut prev_codepoint: Option<char> = None;
12851    text.char_indices()
12852        .chain([(text.len(), '\0')])
12853        .filter_map(move |(index, codepoint)| {
12854            let prev_codepoint = prev_codepoint.replace(codepoint)?;
12855            let is_boundary = index == text.len()
12856                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
12857                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
12858            if is_boundary {
12859                let chunk = &text[prev_index..index];
12860                prev_index = index;
12861                Some(chunk)
12862            } else {
12863                None
12864            }
12865        })
12866}
12867
12868pub trait RangeToAnchorExt {
12869    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
12870}
12871
12872impl<T: ToOffset> RangeToAnchorExt for Range<T> {
12873    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
12874        let start_offset = self.start.to_offset(snapshot);
12875        let end_offset = self.end.to_offset(snapshot);
12876        if start_offset == end_offset {
12877            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
12878        } else {
12879            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
12880        }
12881    }
12882}
12883
12884pub trait RowExt {
12885    fn as_f32(&self) -> f32;
12886
12887    fn next_row(&self) -> Self;
12888
12889    fn previous_row(&self) -> Self;
12890
12891    fn minus(&self, other: Self) -> u32;
12892}
12893
12894impl RowExt for DisplayRow {
12895    fn as_f32(&self) -> f32 {
12896        self.0 as f32
12897    }
12898
12899    fn next_row(&self) -> Self {
12900        Self(self.0 + 1)
12901    }
12902
12903    fn previous_row(&self) -> Self {
12904        Self(self.0.saturating_sub(1))
12905    }
12906
12907    fn minus(&self, other: Self) -> u32 {
12908        self.0 - other.0
12909    }
12910}
12911
12912impl RowExt for MultiBufferRow {
12913    fn as_f32(&self) -> f32 {
12914        self.0 as f32
12915    }
12916
12917    fn next_row(&self) -> Self {
12918        Self(self.0 + 1)
12919    }
12920
12921    fn previous_row(&self) -> Self {
12922        Self(self.0.saturating_sub(1))
12923    }
12924
12925    fn minus(&self, other: Self) -> u32 {
12926        self.0 - other.0
12927    }
12928}
12929
12930trait RowRangeExt {
12931    type Row;
12932
12933    fn len(&self) -> usize;
12934
12935    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
12936}
12937
12938impl RowRangeExt for Range<MultiBufferRow> {
12939    type Row = MultiBufferRow;
12940
12941    fn len(&self) -> usize {
12942        (self.end.0 - self.start.0) as usize
12943    }
12944
12945    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
12946        (self.start.0..self.end.0).map(MultiBufferRow)
12947    }
12948}
12949
12950impl RowRangeExt for Range<DisplayRow> {
12951    type Row = DisplayRow;
12952
12953    fn len(&self) -> usize {
12954        (self.end.0 - self.start.0) as usize
12955    }
12956
12957    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
12958        (self.start.0..self.end.0).map(DisplayRow)
12959    }
12960}
12961
12962fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
12963    if hunk.diff_base_byte_range.is_empty() {
12964        DiffHunkStatus::Added
12965    } else if hunk.associated_range.is_empty() {
12966        DiffHunkStatus::Removed
12967    } else {
12968        DiffHunkStatus::Modified
12969    }
12970}