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 behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod debounced_delay;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31mod inline_completion_provider;
   32pub mod items;
   33mod linked_editing_ranges;
   34mod lsp_ext;
   35mod mouse_context_menu;
   36pub mod movement;
   37mod persistence;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45mod signature_help;
   46#[cfg(any(test, feature = "test-support"))]
   47pub mod test;
   48
   49use ::git::diff::{DiffHunk, DiffHunkStatus};
   50use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
   51pub(crate) use actions::*;
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use client::{Collaborator, ParticipantIndex};
   56use clock::ReplicaId;
   57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   58use convert_case::{Case, Casing};
   59use debounced_delay::DebouncedDelay;
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings,
   64};
   65pub use editor_settings_controls::*;
   66use element::LineWithInvisibles;
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::FutureExt;
   71use fuzzy::{StringMatch, StringMatchCandidate};
   72use git::blame::GitBlame;
   73use git::diff_hunk_to_display;
   74use gpui::{
   75    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   76    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
   77    ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
   78    FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
   79    KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
   80    SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
   81    UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
   82    VisualContext, WeakFocusHandle, WeakView, WindowContext,
   83};
   84use highlight_matching_bracket::refresh_matching_bracket_highlights;
   85use hover_popover::{hide_hover, HoverState};
   86use hunk_diff::ExpandedHunks;
   87pub(crate) use hunk_diff::HoveredHunk;
   88use indent_guides::ActiveIndentGuidesState;
   89use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   90pub use inline_completion_provider::*;
   91pub use items::MAX_TAB_TITLE_LEN;
   92use itertools::Itertools;
   93use language::{
   94    language_settings::{self, all_language_settings, InlayHintSettings},
   95    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   96    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   97    Point, Selection, SelectionGoal, TransactionId,
   98};
   99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  100use linked_editing_ranges::refresh_linked_ranges;
  101use similar::{ChangeTag, TextDiff};
  102use task::{ResolvedTask, TaskTemplate, TaskVariables};
  103
  104use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  105pub use lsp::CompletionContext;
  106use lsp::{
  107    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  108    LanguageServerId,
  109};
  110use mouse_context_menu::MouseContextMenu;
  111use movement::TextLayoutDetails;
  112pub use multi_buffer::{
  113    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  114    ToPoint,
  115};
  116use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
  117use ordered_float::OrderedFloat;
  118use parking_lot::{Mutex, RwLock};
  119use project::project_settings::{GitGutterSetting, ProjectSettings};
  120use project::{
  121    CodeAction, Completion, CompletionIntent, FormatTrigger, Item, Location, Project, ProjectPath,
  122    ProjectTransaction, TaskSourceKind,
  123};
  124use rand::prelude::*;
  125use rpc::{proto::*, ErrorExt};
  126use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  127use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  128use serde::{Deserialize, Serialize};
  129use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  130use smallvec::SmallVec;
  131use snippet::Snippet;
  132use std::{
  133    any::TypeId,
  134    borrow::Cow,
  135    cell::RefCell,
  136    cmp::{self, Ordering, Reverse},
  137    mem,
  138    num::NonZeroU32,
  139    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  140    path::{Path, PathBuf},
  141    rc::Rc,
  142    sync::Arc,
  143    time::{Duration, Instant},
  144};
  145pub use sum_tree::Bias;
  146use sum_tree::TreeMap;
  147use text::{BufferId, OffsetUtf16, Rope};
  148use theme::{
  149    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  150    ThemeColors, ThemeSettings,
  151};
  152use ui::{
  153    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  154    ListItem, Popover, Tooltip,
  155};
  156use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  157use workspace::item::{ItemHandle, PreviewTabsSettings};
  158use workspace::notifications::{DetachAndPromptErr, NotificationId};
  159use workspace::{
  160    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  161};
  162use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  163
  164use crate::hover_links::find_url;
  165use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  166
  167pub const FILE_HEADER_HEIGHT: u32 = 1;
  168pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  169pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  170pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  171const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  172const MAX_LINE_LEN: usize = 1024;
  173const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  174const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  175pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  176#[doc(hidden)]
  177pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  178#[doc(hidden)]
  179pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  180
  181pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  182pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  183
  184pub fn render_parsed_markdown(
  185    element_id: impl Into<ElementId>,
  186    parsed: &language::ParsedMarkdown,
  187    editor_style: &EditorStyle,
  188    workspace: Option<WeakView<Workspace>>,
  189    cx: &mut WindowContext,
  190) -> InteractiveText {
  191    let code_span_background_color = cx
  192        .theme()
  193        .colors()
  194        .editor_document_highlight_read_background;
  195
  196    let highlights = gpui::combine_highlights(
  197        parsed.highlights.iter().filter_map(|(range, highlight)| {
  198            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  199            Some((range.clone(), highlight))
  200        }),
  201        parsed
  202            .regions
  203            .iter()
  204            .zip(&parsed.region_ranges)
  205            .filter_map(|(region, range)| {
  206                if region.code {
  207                    Some((
  208                        range.clone(),
  209                        HighlightStyle {
  210                            background_color: Some(code_span_background_color),
  211                            ..Default::default()
  212                        },
  213                    ))
  214                } else {
  215                    None
  216                }
  217            }),
  218    );
  219
  220    let mut links = Vec::new();
  221    let mut link_ranges = Vec::new();
  222    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  223        if let Some(link) = region.link.clone() {
  224            links.push(link);
  225            link_ranges.push(range.clone());
  226        }
  227    }
  228
  229    InteractiveText::new(
  230        element_id,
  231        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  232    )
  233    .on_click(link_ranges, move |clicked_range_ix, cx| {
  234        match &links[clicked_range_ix] {
  235            markdown::Link::Web { url } => cx.open_url(url),
  236            markdown::Link::Path { path } => {
  237                if let Some(workspace) = &workspace {
  238                    _ = workspace.update(cx, |workspace, cx| {
  239                        workspace.open_abs_path(path.clone(), false, cx).detach();
  240                    });
  241                }
  242            }
  243        }
  244    })
  245}
  246
  247#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  248pub(crate) enum InlayId {
  249    Suggestion(usize),
  250    Hint(usize),
  251}
  252
  253impl InlayId {
  254    fn id(&self) -> usize {
  255        match self {
  256            Self::Suggestion(id) => *id,
  257            Self::Hint(id) => *id,
  258        }
  259    }
  260}
  261
  262enum DiffRowHighlight {}
  263enum DocumentHighlightRead {}
  264enum DocumentHighlightWrite {}
  265enum InputComposition {}
  266
  267#[derive(Copy, Clone, PartialEq, Eq)]
  268pub enum Direction {
  269    Prev,
  270    Next,
  271}
  272
  273#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  274pub enum Navigated {
  275    Yes,
  276    No,
  277}
  278
  279impl Navigated {
  280    pub fn from_bool(yes: bool) -> Navigated {
  281        if yes {
  282            Navigated::Yes
  283        } else {
  284            Navigated::No
  285        }
  286    }
  287}
  288
  289pub fn init_settings(cx: &mut AppContext) {
  290    EditorSettings::register(cx);
  291}
  292
  293pub fn init(cx: &mut AppContext) {
  294    init_settings(cx);
  295
  296    workspace::register_project_item::<Editor>(cx);
  297    workspace::FollowableViewRegistry::register::<Editor>(cx);
  298    workspace::register_serializable_item::<Editor>(cx);
  299
  300    cx.observe_new_views(
  301        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  302            workspace.register_action(Editor::new_file);
  303            workspace.register_action(Editor::new_file_vertical);
  304            workspace.register_action(Editor::new_file_horizontal);
  305        },
  306    )
  307    .detach();
  308
  309    cx.on_action(move |_: &workspace::NewFile, cx| {
  310        let app_state = workspace::AppState::global(cx);
  311        if let Some(app_state) = app_state.upgrade() {
  312            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  313                Editor::new_file(workspace, &Default::default(), cx)
  314            })
  315            .detach();
  316        }
  317    });
  318    cx.on_action(move |_: &workspace::NewWindow, cx| {
  319        let app_state = workspace::AppState::global(cx);
  320        if let Some(app_state) = app_state.upgrade() {
  321            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  322                Editor::new_file(workspace, &Default::default(), cx)
  323            })
  324            .detach();
  325        }
  326    });
  327}
  328
  329pub struct SearchWithinRange;
  330
  331trait InvalidationRegion {
  332    fn ranges(&self) -> &[Range<Anchor>];
  333}
  334
  335#[derive(Clone, Debug, PartialEq)]
  336pub enum SelectPhase {
  337    Begin {
  338        position: DisplayPoint,
  339        add: bool,
  340        click_count: usize,
  341    },
  342    BeginColumnar {
  343        position: DisplayPoint,
  344        reset: bool,
  345        goal_column: u32,
  346    },
  347    Extend {
  348        position: DisplayPoint,
  349        click_count: usize,
  350    },
  351    Update {
  352        position: DisplayPoint,
  353        goal_column: u32,
  354        scroll_delta: gpui::Point<f32>,
  355    },
  356    End,
  357}
  358
  359#[derive(Clone, Debug)]
  360pub enum SelectMode {
  361    Character,
  362    Word(Range<Anchor>),
  363    Line(Range<Anchor>),
  364    All,
  365}
  366
  367#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  368pub enum EditorMode {
  369    SingleLine { auto_width: bool },
  370    AutoHeight { max_lines: usize },
  371    Full,
  372}
  373
  374#[derive(Clone, Debug)]
  375pub enum SoftWrap {
  376    None,
  377    PreferLine,
  378    EditorWidth,
  379    Column(u32),
  380    Bounded(u32),
  381}
  382
  383#[derive(Clone)]
  384pub struct EditorStyle {
  385    pub background: Hsla,
  386    pub local_player: PlayerColor,
  387    pub text: TextStyle,
  388    pub scrollbar_width: Pixels,
  389    pub syntax: Arc<SyntaxTheme>,
  390    pub status: StatusColors,
  391    pub inlay_hints_style: HighlightStyle,
  392    pub suggestions_style: HighlightStyle,
  393    pub unnecessary_code_fade: f32,
  394}
  395
  396impl Default for EditorStyle {
  397    fn default() -> Self {
  398        Self {
  399            background: Hsla::default(),
  400            local_player: PlayerColor::default(),
  401            text: TextStyle::default(),
  402            scrollbar_width: Pixels::default(),
  403            syntax: Default::default(),
  404            // HACK: Status colors don't have a real default.
  405            // We should look into removing the status colors from the editor
  406            // style and retrieve them directly from the theme.
  407            status: StatusColors::dark(),
  408            inlay_hints_style: HighlightStyle::default(),
  409            suggestions_style: HighlightStyle::default(),
  410            unnecessary_code_fade: Default::default(),
  411        }
  412    }
  413}
  414
  415type CompletionId = usize;
  416
  417#[derive(Clone, Debug)]
  418struct CompletionState {
  419    // render_inlay_ids represents the inlay hints that are inserted
  420    // for rendering the inline completions. They may be discontinuous
  421    // in the event that the completion provider returns some intersection
  422    // with the existing content.
  423    render_inlay_ids: Vec<InlayId>,
  424    // text is the resulting rope that is inserted when the user accepts a completion.
  425    text: Rope,
  426    // position is the position of the cursor when the completion was triggered.
  427    position: multi_buffer::Anchor,
  428    // delete_range is the range of text that this completion state covers.
  429    // if the completion is accepted, this range should be deleted.
  430    delete_range: Option<Range<multi_buffer::Anchor>>,
  431}
  432
  433#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  434struct EditorActionId(usize);
  435
  436impl EditorActionId {
  437    pub fn post_inc(&mut self) -> Self {
  438        let answer = self.0;
  439
  440        *self = Self(answer + 1);
  441
  442        Self(answer)
  443    }
  444}
  445
  446// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  447// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  448
  449type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  450type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  451
  452#[derive(Default)]
  453struct ScrollbarMarkerState {
  454    scrollbar_size: Size<Pixels>,
  455    dirty: bool,
  456    markers: Arc<[PaintQuad]>,
  457    pending_refresh: Option<Task<Result<()>>>,
  458}
  459
  460impl ScrollbarMarkerState {
  461    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  462        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  463    }
  464}
  465
  466#[derive(Clone, Debug)]
  467struct RunnableTasks {
  468    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  469    offset: MultiBufferOffset,
  470    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  471    column: u32,
  472    // Values of all named captures, including those starting with '_'
  473    extra_variables: HashMap<String, String>,
  474    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  475    context_range: Range<BufferOffset>,
  476}
  477
  478#[derive(Clone)]
  479struct ResolvedTasks {
  480    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  481    position: Anchor,
  482}
  483#[derive(Copy, Clone, Debug)]
  484struct MultiBufferOffset(usize);
  485#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  486struct BufferOffset(usize);
  487
  488// Addons allow storing per-editor state in other crates (e.g. Vim)
  489pub trait Addon: 'static {
  490    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  491
  492    fn to_any(&self) -> &dyn std::any::Any;
  493}
  494
  495/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  496///
  497/// See the [module level documentation](self) for more information.
  498pub struct Editor {
  499    focus_handle: FocusHandle,
  500    last_focused_descendant: Option<WeakFocusHandle>,
  501    /// The text buffer being edited
  502    buffer: Model<MultiBuffer>,
  503    /// Map of how text in the buffer should be displayed.
  504    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  505    pub display_map: Model<DisplayMap>,
  506    pub selections: SelectionsCollection,
  507    pub scroll_manager: ScrollManager,
  508    /// When inline assist editors are linked, they all render cursors because
  509    /// typing enters text into each of them, even the ones that aren't focused.
  510    pub(crate) show_cursor_when_unfocused: bool,
  511    columnar_selection_tail: Option<Anchor>,
  512    add_selections_state: Option<AddSelectionsState>,
  513    select_next_state: Option<SelectNextState>,
  514    select_prev_state: Option<SelectNextState>,
  515    selection_history: SelectionHistory,
  516    autoclose_regions: Vec<AutocloseRegion>,
  517    snippet_stack: InvalidationStack<SnippetState>,
  518    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  519    ime_transaction: Option<TransactionId>,
  520    active_diagnostics: Option<ActiveDiagnosticGroup>,
  521    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  522    project: Option<Model<Project>>,
  523    completion_provider: Option<Box<dyn CompletionProvider>>,
  524    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  525    blink_manager: Model<BlinkManager>,
  526    show_cursor_names: bool,
  527    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  528    pub show_local_selections: bool,
  529    mode: EditorMode,
  530    show_breadcrumbs: bool,
  531    show_gutter: bool,
  532    show_line_numbers: Option<bool>,
  533    use_relative_line_numbers: Option<bool>,
  534    show_git_diff_gutter: Option<bool>,
  535    show_code_actions: Option<bool>,
  536    show_runnables: Option<bool>,
  537    show_wrap_guides: Option<bool>,
  538    show_indent_guides: Option<bool>,
  539    placeholder_text: Option<Arc<str>>,
  540    highlight_order: usize,
  541    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  542    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  543    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  544    scrollbar_marker_state: ScrollbarMarkerState,
  545    active_indent_guides_state: ActiveIndentGuidesState,
  546    nav_history: Option<ItemNavHistory>,
  547    context_menu: RwLock<Option<ContextMenu>>,
  548    mouse_context_menu: Option<MouseContextMenu>,
  549    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  550    signature_help_state: SignatureHelpState,
  551    auto_signature_help: Option<bool>,
  552    find_all_references_task_sources: Vec<Anchor>,
  553    next_completion_id: CompletionId,
  554    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  555    available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
  556    code_actions_task: Option<Task<()>>,
  557    document_highlights_task: Option<Task<()>>,
  558    linked_editing_range_task: Option<Task<Option<()>>>,
  559    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  560    pending_rename: Option<RenameState>,
  561    searchable: bool,
  562    cursor_shape: CursorShape,
  563    current_line_highlight: Option<CurrentLineHighlight>,
  564    collapse_matches: bool,
  565    autoindent_mode: Option<AutoindentMode>,
  566    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  567    input_enabled: bool,
  568    use_modal_editing: bool,
  569    read_only: bool,
  570    leader_peer_id: Option<PeerId>,
  571    remote_id: Option<ViewId>,
  572    hover_state: HoverState,
  573    gutter_hovered: bool,
  574    hovered_link_state: Option<HoveredLinkState>,
  575    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  576    active_inline_completion: Option<CompletionState>,
  577    // enable_inline_completions is a switch that Vim can use to disable
  578    // inline completions based on its mode.
  579    enable_inline_completions: bool,
  580    show_inline_completions_override: Option<bool>,
  581    inlay_hint_cache: InlayHintCache,
  582    expanded_hunks: ExpandedHunks,
  583    next_inlay_id: usize,
  584    _subscriptions: Vec<Subscription>,
  585    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  586    gutter_dimensions: GutterDimensions,
  587    style: Option<EditorStyle>,
  588    next_editor_action_id: EditorActionId,
  589    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  590    use_autoclose: bool,
  591    use_auto_surround: bool,
  592    auto_replace_emoji_shortcode: bool,
  593    show_git_blame_gutter: bool,
  594    show_git_blame_inline: bool,
  595    show_git_blame_inline_delay_task: Option<Task<()>>,
  596    git_blame_inline_enabled: bool,
  597    serialize_dirty_buffers: bool,
  598    show_selection_menu: Option<bool>,
  599    blame: Option<Model<GitBlame>>,
  600    blame_subscription: Option<Subscription>,
  601    custom_context_menu: Option<
  602        Box<
  603            dyn 'static
  604                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  605        >,
  606    >,
  607    last_bounds: Option<Bounds<Pixels>>,
  608    expect_bounds_change: Option<Bounds<Pixels>>,
  609    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  610    tasks_update_task: Option<Task<()>>,
  611    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  612    file_header_size: u32,
  613    breadcrumb_header: Option<String>,
  614    focused_block: Option<FocusedBlock>,
  615    next_scroll_position: NextScrollCursorCenterTopBottom,
  616    addons: HashMap<TypeId, Box<dyn Addon>>,
  617    _scroll_cursor_center_top_bottom_task: Task<()>,
  618}
  619
  620#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  621enum NextScrollCursorCenterTopBottom {
  622    #[default]
  623    Center,
  624    Top,
  625    Bottom,
  626}
  627
  628impl NextScrollCursorCenterTopBottom {
  629    fn next(&self) -> Self {
  630        match self {
  631            Self::Center => Self::Top,
  632            Self::Top => Self::Bottom,
  633            Self::Bottom => Self::Center,
  634        }
  635    }
  636}
  637
  638#[derive(Clone)]
  639pub struct EditorSnapshot {
  640    pub mode: EditorMode,
  641    show_gutter: bool,
  642    show_line_numbers: Option<bool>,
  643    show_git_diff_gutter: Option<bool>,
  644    show_code_actions: Option<bool>,
  645    show_runnables: Option<bool>,
  646    render_git_blame_gutter: bool,
  647    pub display_snapshot: DisplaySnapshot,
  648    pub placeholder_text: Option<Arc<str>>,
  649    is_focused: bool,
  650    scroll_anchor: ScrollAnchor,
  651    ongoing_scroll: OngoingScroll,
  652    current_line_highlight: CurrentLineHighlight,
  653    gutter_hovered: bool,
  654}
  655
  656const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
  657
  658#[derive(Default, Debug, Clone, Copy)]
  659pub struct GutterDimensions {
  660    pub left_padding: Pixels,
  661    pub right_padding: Pixels,
  662    pub width: Pixels,
  663    pub margin: Pixels,
  664    pub git_blame_entries_width: Option<Pixels>,
  665}
  666
  667impl GutterDimensions {
  668    /// The full width of the space taken up by the gutter.
  669    pub fn full_width(&self) -> Pixels {
  670        self.margin + self.width
  671    }
  672
  673    /// The width of the space reserved for the fold indicators,
  674    /// use alongside 'justify_end' and `gutter_width` to
  675    /// right align content with the line numbers
  676    pub fn fold_area_width(&self) -> Pixels {
  677        self.margin + self.right_padding
  678    }
  679}
  680
  681#[derive(Debug)]
  682pub struct RemoteSelection {
  683    pub replica_id: ReplicaId,
  684    pub selection: Selection<Anchor>,
  685    pub cursor_shape: CursorShape,
  686    pub peer_id: PeerId,
  687    pub line_mode: bool,
  688    pub participant_index: Option<ParticipantIndex>,
  689    pub user_name: Option<SharedString>,
  690}
  691
  692#[derive(Clone, Debug)]
  693struct SelectionHistoryEntry {
  694    selections: Arc<[Selection<Anchor>]>,
  695    select_next_state: Option<SelectNextState>,
  696    select_prev_state: Option<SelectNextState>,
  697    add_selections_state: Option<AddSelectionsState>,
  698}
  699
  700enum SelectionHistoryMode {
  701    Normal,
  702    Undoing,
  703    Redoing,
  704}
  705
  706#[derive(Clone, PartialEq, Eq, Hash)]
  707struct HoveredCursor {
  708    replica_id: u16,
  709    selection_id: usize,
  710}
  711
  712impl Default for SelectionHistoryMode {
  713    fn default() -> Self {
  714        Self::Normal
  715    }
  716}
  717
  718#[derive(Default)]
  719struct SelectionHistory {
  720    #[allow(clippy::type_complexity)]
  721    selections_by_transaction:
  722        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  723    mode: SelectionHistoryMode,
  724    undo_stack: VecDeque<SelectionHistoryEntry>,
  725    redo_stack: VecDeque<SelectionHistoryEntry>,
  726}
  727
  728impl SelectionHistory {
  729    fn insert_transaction(
  730        &mut self,
  731        transaction_id: TransactionId,
  732        selections: Arc<[Selection<Anchor>]>,
  733    ) {
  734        self.selections_by_transaction
  735            .insert(transaction_id, (selections, None));
  736    }
  737
  738    #[allow(clippy::type_complexity)]
  739    fn transaction(
  740        &self,
  741        transaction_id: TransactionId,
  742    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  743        self.selections_by_transaction.get(&transaction_id)
  744    }
  745
  746    #[allow(clippy::type_complexity)]
  747    fn transaction_mut(
  748        &mut self,
  749        transaction_id: TransactionId,
  750    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  751        self.selections_by_transaction.get_mut(&transaction_id)
  752    }
  753
  754    fn push(&mut self, entry: SelectionHistoryEntry) {
  755        if !entry.selections.is_empty() {
  756            match self.mode {
  757                SelectionHistoryMode::Normal => {
  758                    self.push_undo(entry);
  759                    self.redo_stack.clear();
  760                }
  761                SelectionHistoryMode::Undoing => self.push_redo(entry),
  762                SelectionHistoryMode::Redoing => self.push_undo(entry),
  763            }
  764        }
  765    }
  766
  767    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  768        if self
  769            .undo_stack
  770            .back()
  771            .map_or(true, |e| e.selections != entry.selections)
  772        {
  773            self.undo_stack.push_back(entry);
  774            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  775                self.undo_stack.pop_front();
  776            }
  777        }
  778    }
  779
  780    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  781        if self
  782            .redo_stack
  783            .back()
  784            .map_or(true, |e| e.selections != entry.selections)
  785        {
  786            self.redo_stack.push_back(entry);
  787            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  788                self.redo_stack.pop_front();
  789            }
  790        }
  791    }
  792}
  793
  794struct RowHighlight {
  795    index: usize,
  796    range: RangeInclusive<Anchor>,
  797    color: Option<Hsla>,
  798    should_autoscroll: bool,
  799}
  800
  801#[derive(Clone, Debug)]
  802struct AddSelectionsState {
  803    above: bool,
  804    stack: Vec<usize>,
  805}
  806
  807#[derive(Clone)]
  808struct SelectNextState {
  809    query: AhoCorasick,
  810    wordwise: bool,
  811    done: bool,
  812}
  813
  814impl std::fmt::Debug for SelectNextState {
  815    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  816        f.debug_struct(std::any::type_name::<Self>())
  817            .field("wordwise", &self.wordwise)
  818            .field("done", &self.done)
  819            .finish()
  820    }
  821}
  822
  823#[derive(Debug)]
  824struct AutocloseRegion {
  825    selection_id: usize,
  826    range: Range<Anchor>,
  827    pair: BracketPair,
  828}
  829
  830#[derive(Debug)]
  831struct SnippetState {
  832    ranges: Vec<Vec<Range<Anchor>>>,
  833    active_index: usize,
  834}
  835
  836#[doc(hidden)]
  837pub struct RenameState {
  838    pub range: Range<Anchor>,
  839    pub old_name: Arc<str>,
  840    pub editor: View<Editor>,
  841    block_id: CustomBlockId,
  842}
  843
  844struct InvalidationStack<T>(Vec<T>);
  845
  846struct RegisteredInlineCompletionProvider {
  847    provider: Arc<dyn InlineCompletionProviderHandle>,
  848    _subscription: Subscription,
  849}
  850
  851enum ContextMenu {
  852    Completions(CompletionsMenu),
  853    CodeActions(CodeActionsMenu),
  854}
  855
  856impl ContextMenu {
  857    fn select_first(
  858        &mut self,
  859        project: Option<&Model<Project>>,
  860        cx: &mut ViewContext<Editor>,
  861    ) -> bool {
  862        if self.visible() {
  863            match self {
  864                ContextMenu::Completions(menu) => menu.select_first(project, cx),
  865                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  866            }
  867            true
  868        } else {
  869            false
  870        }
  871    }
  872
  873    fn select_prev(
  874        &mut self,
  875        project: Option<&Model<Project>>,
  876        cx: &mut ViewContext<Editor>,
  877    ) -> bool {
  878        if self.visible() {
  879            match self {
  880                ContextMenu::Completions(menu) => menu.select_prev(project, cx),
  881                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  882            }
  883            true
  884        } else {
  885            false
  886        }
  887    }
  888
  889    fn select_next(
  890        &mut self,
  891        project: Option<&Model<Project>>,
  892        cx: &mut ViewContext<Editor>,
  893    ) -> bool {
  894        if self.visible() {
  895            match self {
  896                ContextMenu::Completions(menu) => menu.select_next(project, cx),
  897                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  898            }
  899            true
  900        } else {
  901            false
  902        }
  903    }
  904
  905    fn select_last(
  906        &mut self,
  907        project: Option<&Model<Project>>,
  908        cx: &mut ViewContext<Editor>,
  909    ) -> bool {
  910        if self.visible() {
  911            match self {
  912                ContextMenu::Completions(menu) => menu.select_last(project, cx),
  913                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  914            }
  915            true
  916        } else {
  917            false
  918        }
  919    }
  920
  921    fn visible(&self) -> bool {
  922        match self {
  923            ContextMenu::Completions(menu) => menu.visible(),
  924            ContextMenu::CodeActions(menu) => menu.visible(),
  925        }
  926    }
  927
  928    fn render(
  929        &self,
  930        cursor_position: DisplayPoint,
  931        style: &EditorStyle,
  932        max_height: Pixels,
  933        workspace: Option<WeakView<Workspace>>,
  934        cx: &mut ViewContext<Editor>,
  935    ) -> (ContextMenuOrigin, AnyElement) {
  936        match self {
  937            ContextMenu::Completions(menu) => (
  938                ContextMenuOrigin::EditorPoint(cursor_position),
  939                menu.render(style, max_height, workspace, cx),
  940            ),
  941            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  942        }
  943    }
  944}
  945
  946enum ContextMenuOrigin {
  947    EditorPoint(DisplayPoint),
  948    GutterIndicator(DisplayRow),
  949}
  950
  951#[derive(Clone)]
  952struct CompletionsMenu {
  953    id: CompletionId,
  954    sort_completions: bool,
  955    initial_position: Anchor,
  956    buffer: Model<Buffer>,
  957    completions: Arc<RwLock<Box<[Completion]>>>,
  958    match_candidates: Arc<[StringMatchCandidate]>,
  959    matches: Arc<[StringMatch]>,
  960    selected_item: usize,
  961    scroll_handle: UniformListScrollHandle,
  962    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  963}
  964
  965impl CompletionsMenu {
  966    fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  967        self.selected_item = 0;
  968        self.scroll_handle.scroll_to_item(self.selected_item);
  969        self.attempt_resolve_selected_completion_documentation(project, cx);
  970        cx.notify();
  971    }
  972
  973    fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  974        if self.selected_item > 0 {
  975            self.selected_item -= 1;
  976        } else {
  977            self.selected_item = self.matches.len() - 1;
  978        }
  979        self.scroll_handle.scroll_to_item(self.selected_item);
  980        self.attempt_resolve_selected_completion_documentation(project, cx);
  981        cx.notify();
  982    }
  983
  984    fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  985        if self.selected_item + 1 < self.matches.len() {
  986            self.selected_item += 1;
  987        } else {
  988            self.selected_item = 0;
  989        }
  990        self.scroll_handle.scroll_to_item(self.selected_item);
  991        self.attempt_resolve_selected_completion_documentation(project, cx);
  992        cx.notify();
  993    }
  994
  995    fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  996        self.selected_item = self.matches.len() - 1;
  997        self.scroll_handle.scroll_to_item(self.selected_item);
  998        self.attempt_resolve_selected_completion_documentation(project, cx);
  999        cx.notify();
 1000    }
 1001
 1002    fn pre_resolve_completion_documentation(
 1003        buffer: Model<Buffer>,
 1004        completions: Arc<RwLock<Box<[Completion]>>>,
 1005        matches: Arc<[StringMatch]>,
 1006        editor: &Editor,
 1007        cx: &mut ViewContext<Editor>,
 1008    ) -> Task<()> {
 1009        let settings = EditorSettings::get_global(cx);
 1010        if !settings.show_completion_documentation {
 1011            return Task::ready(());
 1012        }
 1013
 1014        let Some(provider) = editor.completion_provider.as_ref() else {
 1015            return Task::ready(());
 1016        };
 1017
 1018        let resolve_task = provider.resolve_completions(
 1019            buffer,
 1020            matches.iter().map(|m| m.candidate_id).collect(),
 1021            completions.clone(),
 1022            cx,
 1023        );
 1024
 1025        cx.spawn(move |this, mut cx| async move {
 1026            if let Some(true) = resolve_task.await.log_err() {
 1027                this.update(&mut cx, |_, cx| cx.notify()).ok();
 1028            }
 1029        })
 1030    }
 1031
 1032    fn attempt_resolve_selected_completion_documentation(
 1033        &mut self,
 1034        project: Option<&Model<Project>>,
 1035        cx: &mut ViewContext<Editor>,
 1036    ) {
 1037        let settings = EditorSettings::get_global(cx);
 1038        if !settings.show_completion_documentation {
 1039            return;
 1040        }
 1041
 1042        let completion_index = self.matches[self.selected_item].candidate_id;
 1043        let Some(project) = project else {
 1044            return;
 1045        };
 1046
 1047        let resolve_task = project.update(cx, |project, cx| {
 1048            project.resolve_completions(
 1049                self.buffer.clone(),
 1050                vec![completion_index],
 1051                self.completions.clone(),
 1052                cx,
 1053            )
 1054        });
 1055
 1056        let delay_ms =
 1057            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1058        let delay = Duration::from_millis(delay_ms);
 1059
 1060        self.selected_completion_documentation_resolve_debounce
 1061            .lock()
 1062            .fire_new(delay, cx, |_, cx| {
 1063                cx.spawn(move |this, mut cx| async move {
 1064                    if let Some(true) = resolve_task.await.log_err() {
 1065                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1066                    }
 1067                })
 1068            });
 1069    }
 1070
 1071    fn visible(&self) -> bool {
 1072        !self.matches.is_empty()
 1073    }
 1074
 1075    fn render(
 1076        &self,
 1077        style: &EditorStyle,
 1078        max_height: Pixels,
 1079        workspace: Option<WeakView<Workspace>>,
 1080        cx: &mut ViewContext<Editor>,
 1081    ) -> AnyElement {
 1082        let settings = EditorSettings::get_global(cx);
 1083        let show_completion_documentation = settings.show_completion_documentation;
 1084
 1085        let widest_completion_ix = self
 1086            .matches
 1087            .iter()
 1088            .enumerate()
 1089            .max_by_key(|(_, mat)| {
 1090                let completions = self.completions.read();
 1091                let completion = &completions[mat.candidate_id];
 1092                let documentation = &completion.documentation;
 1093
 1094                let mut len = completion.label.text.chars().count();
 1095                if let Some(Documentation::SingleLine(text)) = documentation {
 1096                    if show_completion_documentation {
 1097                        len += text.chars().count();
 1098                    }
 1099                }
 1100
 1101                len
 1102            })
 1103            .map(|(ix, _)| ix);
 1104
 1105        let completions = self.completions.clone();
 1106        let matches = self.matches.clone();
 1107        let selected_item = self.selected_item;
 1108        let style = style.clone();
 1109
 1110        let multiline_docs = if show_completion_documentation {
 1111            let mat = &self.matches[selected_item];
 1112            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1113                Some(Documentation::MultiLinePlainText(text)) => {
 1114                    Some(div().child(SharedString::from(text.clone())))
 1115                }
 1116                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1117                    Some(div().child(render_parsed_markdown(
 1118                        "completions_markdown",
 1119                        parsed,
 1120                        &style,
 1121                        workspace,
 1122                        cx,
 1123                    )))
 1124                }
 1125                _ => None,
 1126            };
 1127            multiline_docs.map(|div| {
 1128                div.id("multiline_docs")
 1129                    .max_h(max_height)
 1130                    .flex_1()
 1131                    .px_1p5()
 1132                    .py_1()
 1133                    .min_w(px(260.))
 1134                    .max_w(px(640.))
 1135                    .w(px(500.))
 1136                    .overflow_y_scroll()
 1137                    .occlude()
 1138            })
 1139        } else {
 1140            None
 1141        };
 1142
 1143        let list = uniform_list(
 1144            cx.view().clone(),
 1145            "completions",
 1146            matches.len(),
 1147            move |_editor, range, cx| {
 1148                let start_ix = range.start;
 1149                let completions_guard = completions.read();
 1150
 1151                matches[range]
 1152                    .iter()
 1153                    .enumerate()
 1154                    .map(|(ix, mat)| {
 1155                        let item_ix = start_ix + ix;
 1156                        let candidate_id = mat.candidate_id;
 1157                        let completion = &completions_guard[candidate_id];
 1158
 1159                        let documentation = if show_completion_documentation {
 1160                            &completion.documentation
 1161                        } else {
 1162                            &None
 1163                        };
 1164
 1165                        let highlights = gpui::combine_highlights(
 1166                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1167                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1168                                |(range, mut highlight)| {
 1169                                    // Ignore font weight for syntax highlighting, as we'll use it
 1170                                    // for fuzzy matches.
 1171                                    highlight.font_weight = None;
 1172
 1173                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1174                                        highlight.strikethrough = Some(StrikethroughStyle {
 1175                                            thickness: 1.0.into(),
 1176                                            ..Default::default()
 1177                                        });
 1178                                        highlight.color = Some(cx.theme().colors().text_muted);
 1179                                    }
 1180
 1181                                    (range, highlight)
 1182                                },
 1183                            ),
 1184                        );
 1185                        let completion_label = StyledText::new(completion.label.text.clone())
 1186                            .with_highlights(&style.text, highlights);
 1187                        let documentation_label =
 1188                            if let Some(Documentation::SingleLine(text)) = documentation {
 1189                                if text.trim().is_empty() {
 1190                                    None
 1191                                } else {
 1192                                    Some(
 1193                                        Label::new(text.clone())
 1194                                            .ml_4()
 1195                                            .size(LabelSize::Small)
 1196                                            .color(Color::Muted),
 1197                                    )
 1198                                }
 1199                            } else {
 1200                                None
 1201                            };
 1202
 1203                        div().min_w(px(220.)).max_w(px(540.)).child(
 1204                            ListItem::new(mat.candidate_id)
 1205                                .inset(true)
 1206                                .selected(item_ix == selected_item)
 1207                                .on_click(cx.listener(move |editor, _event, cx| {
 1208                                    cx.stop_propagation();
 1209                                    if let Some(task) = editor.confirm_completion(
 1210                                        &ConfirmCompletion {
 1211                                            item_ix: Some(item_ix),
 1212                                        },
 1213                                        cx,
 1214                                    ) {
 1215                                        task.detach_and_log_err(cx)
 1216                                    }
 1217                                }))
 1218                                .child(h_flex().overflow_hidden().child(completion_label))
 1219                                .end_slot::<Label>(documentation_label),
 1220                        )
 1221                    })
 1222                    .collect()
 1223            },
 1224        )
 1225        .occlude()
 1226        .max_h(max_height)
 1227        .track_scroll(self.scroll_handle.clone())
 1228        .with_width_from_item(widest_completion_ix)
 1229        .with_sizing_behavior(ListSizingBehavior::Infer);
 1230
 1231        Popover::new()
 1232            .child(list)
 1233            .when_some(multiline_docs, |popover, multiline_docs| {
 1234                popover.aside(multiline_docs)
 1235            })
 1236            .into_any_element()
 1237    }
 1238
 1239    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1240        let mut matches = if let Some(query) = query {
 1241            fuzzy::match_strings(
 1242                &self.match_candidates,
 1243                query,
 1244                query.chars().any(|c| c.is_uppercase()),
 1245                100,
 1246                &Default::default(),
 1247                executor,
 1248            )
 1249            .await
 1250        } else {
 1251            self.match_candidates
 1252                .iter()
 1253                .enumerate()
 1254                .map(|(candidate_id, candidate)| StringMatch {
 1255                    candidate_id,
 1256                    score: Default::default(),
 1257                    positions: Default::default(),
 1258                    string: candidate.string.clone(),
 1259                })
 1260                .collect()
 1261        };
 1262
 1263        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1264        if let Some(query) = query {
 1265            if let Some(query_start) = query.chars().next() {
 1266                matches.retain(|string_match| {
 1267                    split_words(&string_match.string).any(|word| {
 1268                        // Check that the first codepoint of the word as lowercase matches the first
 1269                        // codepoint of the query as lowercase
 1270                        word.chars()
 1271                            .flat_map(|codepoint| codepoint.to_lowercase())
 1272                            .zip(query_start.to_lowercase())
 1273                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1274                    })
 1275                });
 1276            }
 1277        }
 1278
 1279        let completions = self.completions.read();
 1280        if self.sort_completions {
 1281            matches.sort_unstable_by_key(|mat| {
 1282                // We do want to strike a balance here between what the language server tells us
 1283                // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1284                // `Creat` and there is a local variable called `CreateComponent`).
 1285                // So what we do is: we bucket all matches into two buckets
 1286                // - Strong matches
 1287                // - Weak matches
 1288                // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1289                // and the Weak matches are the rest.
 1290                //
 1291                // For the strong matches, we sort by the language-servers score first and for the weak
 1292                // matches, we prefer our fuzzy finder first.
 1293                //
 1294                // The thinking behind that: it's useless to take the sort_text the language-server gives
 1295                // us into account when it's obviously a bad match.
 1296
 1297                #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1298                enum MatchScore<'a> {
 1299                    Strong {
 1300                        sort_text: Option<&'a str>,
 1301                        score: Reverse<OrderedFloat<f64>>,
 1302                        sort_key: (usize, &'a str),
 1303                    },
 1304                    Weak {
 1305                        score: Reverse<OrderedFloat<f64>>,
 1306                        sort_text: Option<&'a str>,
 1307                        sort_key: (usize, &'a str),
 1308                    },
 1309                }
 1310
 1311                let completion = &completions[mat.candidate_id];
 1312                let sort_key = completion.sort_key();
 1313                let sort_text = completion.lsp_completion.sort_text.as_deref();
 1314                let score = Reverse(OrderedFloat(mat.score));
 1315
 1316                if mat.score >= 0.2 {
 1317                    MatchScore::Strong {
 1318                        sort_text,
 1319                        score,
 1320                        sort_key,
 1321                    }
 1322                } else {
 1323                    MatchScore::Weak {
 1324                        score,
 1325                        sort_text,
 1326                        sort_key,
 1327                    }
 1328                }
 1329            });
 1330        }
 1331
 1332        for mat in &mut matches {
 1333            let completion = &completions[mat.candidate_id];
 1334            mat.string.clone_from(&completion.label.text);
 1335            for position in &mut mat.positions {
 1336                *position += completion.label.filter_range.start;
 1337            }
 1338        }
 1339        drop(completions);
 1340
 1341        self.matches = matches.into();
 1342        self.selected_item = 0;
 1343    }
 1344}
 1345
 1346#[derive(Clone)]
 1347struct CodeActionContents {
 1348    tasks: Option<Arc<ResolvedTasks>>,
 1349    actions: Option<Arc<[CodeAction]>>,
 1350}
 1351
 1352impl CodeActionContents {
 1353    fn len(&self) -> usize {
 1354        match (&self.tasks, &self.actions) {
 1355            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1356            (Some(tasks), None) => tasks.templates.len(),
 1357            (None, Some(actions)) => actions.len(),
 1358            (None, None) => 0,
 1359        }
 1360    }
 1361
 1362    fn is_empty(&self) -> bool {
 1363        match (&self.tasks, &self.actions) {
 1364            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1365            (Some(tasks), None) => tasks.templates.is_empty(),
 1366            (None, Some(actions)) => actions.is_empty(),
 1367            (None, None) => true,
 1368        }
 1369    }
 1370
 1371    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1372        self.tasks
 1373            .iter()
 1374            .flat_map(|tasks| {
 1375                tasks
 1376                    .templates
 1377                    .iter()
 1378                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1379            })
 1380            .chain(self.actions.iter().flat_map(|actions| {
 1381                actions
 1382                    .iter()
 1383                    .map(|action| CodeActionsItem::CodeAction(action.clone()))
 1384            }))
 1385    }
 1386    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1387        match (&self.tasks, &self.actions) {
 1388            (Some(tasks), Some(actions)) => {
 1389                if index < tasks.templates.len() {
 1390                    tasks
 1391                        .templates
 1392                        .get(index)
 1393                        .cloned()
 1394                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1395                } else {
 1396                    actions
 1397                        .get(index - tasks.templates.len())
 1398                        .cloned()
 1399                        .map(CodeActionsItem::CodeAction)
 1400                }
 1401            }
 1402            (Some(tasks), None) => tasks
 1403                .templates
 1404                .get(index)
 1405                .cloned()
 1406                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1407            (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
 1408            (None, None) => None,
 1409        }
 1410    }
 1411}
 1412
 1413#[allow(clippy::large_enum_variant)]
 1414#[derive(Clone)]
 1415enum CodeActionsItem {
 1416    Task(TaskSourceKind, ResolvedTask),
 1417    CodeAction(CodeAction),
 1418}
 1419
 1420impl CodeActionsItem {
 1421    fn as_task(&self) -> Option<&ResolvedTask> {
 1422        let Self::Task(_, task) = self else {
 1423            return None;
 1424        };
 1425        Some(task)
 1426    }
 1427    fn as_code_action(&self) -> Option<&CodeAction> {
 1428        let Self::CodeAction(action) = self else {
 1429            return None;
 1430        };
 1431        Some(action)
 1432    }
 1433    fn label(&self) -> String {
 1434        match self {
 1435            Self::CodeAction(action) => action.lsp_action.title.clone(),
 1436            Self::Task(_, task) => task.resolved_label.clone(),
 1437        }
 1438    }
 1439}
 1440
 1441struct CodeActionsMenu {
 1442    actions: CodeActionContents,
 1443    buffer: Model<Buffer>,
 1444    selected_item: usize,
 1445    scroll_handle: UniformListScrollHandle,
 1446    deployed_from_indicator: Option<DisplayRow>,
 1447}
 1448
 1449impl CodeActionsMenu {
 1450    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1451        self.selected_item = 0;
 1452        self.scroll_handle.scroll_to_item(self.selected_item);
 1453        cx.notify()
 1454    }
 1455
 1456    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1457        if self.selected_item > 0 {
 1458            self.selected_item -= 1;
 1459        } else {
 1460            self.selected_item = self.actions.len() - 1;
 1461        }
 1462        self.scroll_handle.scroll_to_item(self.selected_item);
 1463        cx.notify();
 1464    }
 1465
 1466    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1467        if self.selected_item + 1 < self.actions.len() {
 1468            self.selected_item += 1;
 1469        } else {
 1470            self.selected_item = 0;
 1471        }
 1472        self.scroll_handle.scroll_to_item(self.selected_item);
 1473        cx.notify();
 1474    }
 1475
 1476    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1477        self.selected_item = self.actions.len() - 1;
 1478        self.scroll_handle.scroll_to_item(self.selected_item);
 1479        cx.notify()
 1480    }
 1481
 1482    fn visible(&self) -> bool {
 1483        !self.actions.is_empty()
 1484    }
 1485
 1486    fn render(
 1487        &self,
 1488        cursor_position: DisplayPoint,
 1489        _style: &EditorStyle,
 1490        max_height: Pixels,
 1491        cx: &mut ViewContext<Editor>,
 1492    ) -> (ContextMenuOrigin, AnyElement) {
 1493        let actions = self.actions.clone();
 1494        let selected_item = self.selected_item;
 1495        let element = uniform_list(
 1496            cx.view().clone(),
 1497            "code_actions_menu",
 1498            self.actions.len(),
 1499            move |_this, range, cx| {
 1500                actions
 1501                    .iter()
 1502                    .skip(range.start)
 1503                    .take(range.end - range.start)
 1504                    .enumerate()
 1505                    .map(|(ix, action)| {
 1506                        let item_ix = range.start + ix;
 1507                        let selected = selected_item == item_ix;
 1508                        let colors = cx.theme().colors();
 1509                        div()
 1510                            .px_1()
 1511                            .rounded_md()
 1512                            .text_color(colors.text)
 1513                            .when(selected, |style| {
 1514                                style
 1515                                    .bg(colors.element_active)
 1516                                    .text_color(colors.text_accent)
 1517                            })
 1518                            .hover(|style| {
 1519                                style
 1520                                    .bg(colors.element_hover)
 1521                                    .text_color(colors.text_accent)
 1522                            })
 1523                            .whitespace_nowrap()
 1524                            .when_some(action.as_code_action(), |this, action| {
 1525                                this.on_mouse_down(
 1526                                    MouseButton::Left,
 1527                                    cx.listener(move |editor, _, cx| {
 1528                                        cx.stop_propagation();
 1529                                        if let Some(task) = editor.confirm_code_action(
 1530                                            &ConfirmCodeAction {
 1531                                                item_ix: Some(item_ix),
 1532                                            },
 1533                                            cx,
 1534                                        ) {
 1535                                            task.detach_and_log_err(cx)
 1536                                        }
 1537                                    }),
 1538                                )
 1539                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1540                                .child(SharedString::from(action.lsp_action.title.clone()))
 1541                            })
 1542                            .when_some(action.as_task(), |this, task| {
 1543                                this.on_mouse_down(
 1544                                    MouseButton::Left,
 1545                                    cx.listener(move |editor, _, cx| {
 1546                                        cx.stop_propagation();
 1547                                        if let Some(task) = editor.confirm_code_action(
 1548                                            &ConfirmCodeAction {
 1549                                                item_ix: Some(item_ix),
 1550                                            },
 1551                                            cx,
 1552                                        ) {
 1553                                            task.detach_and_log_err(cx)
 1554                                        }
 1555                                    }),
 1556                                )
 1557                                .child(SharedString::from(task.resolved_label.clone()))
 1558                            })
 1559                    })
 1560                    .collect()
 1561            },
 1562        )
 1563        .elevation_1(cx)
 1564        .p_1()
 1565        .max_h(max_height)
 1566        .occlude()
 1567        .track_scroll(self.scroll_handle.clone())
 1568        .with_width_from_item(
 1569            self.actions
 1570                .iter()
 1571                .enumerate()
 1572                .max_by_key(|(_, action)| match action {
 1573                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1574                    CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
 1575                })
 1576                .map(|(ix, _)| ix),
 1577        )
 1578        .with_sizing_behavior(ListSizingBehavior::Infer)
 1579        .into_any_element();
 1580
 1581        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1582            ContextMenuOrigin::GutterIndicator(row)
 1583        } else {
 1584            ContextMenuOrigin::EditorPoint(cursor_position)
 1585        };
 1586
 1587        (cursor_position, element)
 1588    }
 1589}
 1590
 1591#[derive(Debug)]
 1592struct ActiveDiagnosticGroup {
 1593    primary_range: Range<Anchor>,
 1594    primary_message: String,
 1595    group_id: usize,
 1596    blocks: HashMap<CustomBlockId, Diagnostic>,
 1597    is_valid: bool,
 1598}
 1599
 1600#[derive(Serialize, Deserialize, Clone, Debug)]
 1601pub struct ClipboardSelection {
 1602    pub len: usize,
 1603    pub is_entire_line: bool,
 1604    pub first_line_indent: u32,
 1605}
 1606
 1607#[derive(Debug)]
 1608pub(crate) struct NavigationData {
 1609    cursor_anchor: Anchor,
 1610    cursor_position: Point,
 1611    scroll_anchor: ScrollAnchor,
 1612    scroll_top_row: u32,
 1613}
 1614
 1615#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1616enum GotoDefinitionKind {
 1617    Symbol,
 1618    Declaration,
 1619    Type,
 1620    Implementation,
 1621}
 1622
 1623#[derive(Debug, Clone)]
 1624enum InlayHintRefreshReason {
 1625    Toggle(bool),
 1626    SettingsChange(InlayHintSettings),
 1627    NewLinesShown,
 1628    BufferEdited(HashSet<Arc<Language>>),
 1629    RefreshRequested,
 1630    ExcerptsRemoved(Vec<ExcerptId>),
 1631}
 1632
 1633impl InlayHintRefreshReason {
 1634    fn description(&self) -> &'static str {
 1635        match self {
 1636            Self::Toggle(_) => "toggle",
 1637            Self::SettingsChange(_) => "settings change",
 1638            Self::NewLinesShown => "new lines shown",
 1639            Self::BufferEdited(_) => "buffer edited",
 1640            Self::RefreshRequested => "refresh requested",
 1641            Self::ExcerptsRemoved(_) => "excerpts removed",
 1642        }
 1643    }
 1644}
 1645
 1646pub(crate) struct FocusedBlock {
 1647    id: BlockId,
 1648    focus_handle: WeakFocusHandle,
 1649}
 1650
 1651impl Editor {
 1652    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1653        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1654        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1655        Self::new(
 1656            EditorMode::SingleLine { auto_width: false },
 1657            buffer,
 1658            None,
 1659            false,
 1660            cx,
 1661        )
 1662    }
 1663
 1664    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1665        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1666        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1667        Self::new(EditorMode::Full, buffer, None, false, cx)
 1668    }
 1669
 1670    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1671        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1672        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1673        Self::new(
 1674            EditorMode::SingleLine { auto_width: true },
 1675            buffer,
 1676            None,
 1677            false,
 1678            cx,
 1679        )
 1680    }
 1681
 1682    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1683        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1684        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1685        Self::new(
 1686            EditorMode::AutoHeight { max_lines },
 1687            buffer,
 1688            None,
 1689            false,
 1690            cx,
 1691        )
 1692    }
 1693
 1694    pub fn for_buffer(
 1695        buffer: Model<Buffer>,
 1696        project: Option<Model<Project>>,
 1697        cx: &mut ViewContext<Self>,
 1698    ) -> Self {
 1699        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1700        Self::new(EditorMode::Full, buffer, project, false, cx)
 1701    }
 1702
 1703    pub fn for_multibuffer(
 1704        buffer: Model<MultiBuffer>,
 1705        project: Option<Model<Project>>,
 1706        show_excerpt_controls: bool,
 1707        cx: &mut ViewContext<Self>,
 1708    ) -> Self {
 1709        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1710    }
 1711
 1712    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1713        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1714        let mut clone = Self::new(
 1715            self.mode,
 1716            self.buffer.clone(),
 1717            self.project.clone(),
 1718            show_excerpt_controls,
 1719            cx,
 1720        );
 1721        self.display_map.update(cx, |display_map, cx| {
 1722            let snapshot = display_map.snapshot(cx);
 1723            clone.display_map.update(cx, |display_map, cx| {
 1724                display_map.set_state(&snapshot, cx);
 1725            });
 1726        });
 1727        clone.selections.clone_state(&self.selections);
 1728        clone.scroll_manager.clone_state(&self.scroll_manager);
 1729        clone.searchable = self.searchable;
 1730        clone
 1731    }
 1732
 1733    pub fn new(
 1734        mode: EditorMode,
 1735        buffer: Model<MultiBuffer>,
 1736        project: Option<Model<Project>>,
 1737        show_excerpt_controls: bool,
 1738        cx: &mut ViewContext<Self>,
 1739    ) -> Self {
 1740        let style = cx.text_style();
 1741        let font_size = style.font_size.to_pixels(cx.rem_size());
 1742        let editor = cx.view().downgrade();
 1743        let fold_placeholder = FoldPlaceholder {
 1744            constrain_width: true,
 1745            render: Arc::new(move |fold_id, fold_range, cx| {
 1746                let editor = editor.clone();
 1747                div()
 1748                    .id(fold_id)
 1749                    .bg(cx.theme().colors().ghost_element_background)
 1750                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1751                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1752                    .rounded_sm()
 1753                    .size_full()
 1754                    .cursor_pointer()
 1755                    .child("")
 1756                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1757                    .on_click(move |_, cx| {
 1758                        editor
 1759                            .update(cx, |editor, cx| {
 1760                                editor.unfold_ranges(
 1761                                    [fold_range.start..fold_range.end],
 1762                                    true,
 1763                                    false,
 1764                                    cx,
 1765                                );
 1766                                cx.stop_propagation();
 1767                            })
 1768                            .ok();
 1769                    })
 1770                    .into_any()
 1771            }),
 1772            merge_adjacent: true,
 1773        };
 1774        let file_header_size = if show_excerpt_controls { 3 } else { 2 };
 1775        let display_map = cx.new_model(|cx| {
 1776            DisplayMap::new(
 1777                buffer.clone(),
 1778                style.font(),
 1779                font_size,
 1780                None,
 1781                show_excerpt_controls,
 1782                file_header_size,
 1783                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1784                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1785                fold_placeholder,
 1786                cx,
 1787            )
 1788        });
 1789
 1790        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1791
 1792        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1793
 1794        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1795            .then(|| language_settings::SoftWrap::PreferLine);
 1796
 1797        let mut project_subscriptions = Vec::new();
 1798        if mode == EditorMode::Full {
 1799            if let Some(project) = project.as_ref() {
 1800                if buffer.read(cx).is_singleton() {
 1801                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1802                        cx.emit(EditorEvent::TitleChanged);
 1803                    }));
 1804                }
 1805                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1806                    if let project::Event::RefreshInlayHints = event {
 1807                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1808                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1809                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1810                            let focus_handle = editor.focus_handle(cx);
 1811                            if focus_handle.is_focused(cx) {
 1812                                let snapshot = buffer.read(cx).snapshot();
 1813                                for (range, snippet) in snippet_edits {
 1814                                    let editor_range =
 1815                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1816                                    editor
 1817                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1818                                        .ok();
 1819                                }
 1820                            }
 1821                        }
 1822                    }
 1823                }));
 1824                let task_inventory = project.read(cx).task_inventory().clone();
 1825                project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1826                    editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1827                }));
 1828            }
 1829        }
 1830
 1831        let inlay_hint_settings = inlay_hint_settings(
 1832            selections.newest_anchor().head(),
 1833            &buffer.read(cx).snapshot(cx),
 1834            cx,
 1835        );
 1836        let focus_handle = cx.focus_handle();
 1837        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1838        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1839            .detach();
 1840        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1841            .detach();
 1842        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1843
 1844        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1845            Some(false)
 1846        } else {
 1847            None
 1848        };
 1849
 1850        let mut this = Self {
 1851            focus_handle,
 1852            show_cursor_when_unfocused: false,
 1853            last_focused_descendant: None,
 1854            buffer: buffer.clone(),
 1855            display_map: display_map.clone(),
 1856            selections,
 1857            scroll_manager: ScrollManager::new(cx),
 1858            columnar_selection_tail: None,
 1859            add_selections_state: None,
 1860            select_next_state: None,
 1861            select_prev_state: None,
 1862            selection_history: Default::default(),
 1863            autoclose_regions: Default::default(),
 1864            snippet_stack: Default::default(),
 1865            select_larger_syntax_node_stack: Vec::new(),
 1866            ime_transaction: Default::default(),
 1867            active_diagnostics: None,
 1868            soft_wrap_mode_override,
 1869            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1870            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1871            project,
 1872            blink_manager: blink_manager.clone(),
 1873            show_local_selections: true,
 1874            mode,
 1875            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1876            show_gutter: mode == EditorMode::Full,
 1877            show_line_numbers: None,
 1878            use_relative_line_numbers: None,
 1879            show_git_diff_gutter: None,
 1880            show_code_actions: None,
 1881            show_runnables: None,
 1882            show_wrap_guides: None,
 1883            show_indent_guides,
 1884            placeholder_text: None,
 1885            highlight_order: 0,
 1886            highlighted_rows: HashMap::default(),
 1887            background_highlights: Default::default(),
 1888            gutter_highlights: TreeMap::default(),
 1889            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1890            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1891            nav_history: None,
 1892            context_menu: RwLock::new(None),
 1893            mouse_context_menu: None,
 1894            completion_tasks: Default::default(),
 1895            signature_help_state: SignatureHelpState::default(),
 1896            auto_signature_help: None,
 1897            find_all_references_task_sources: Vec::new(),
 1898            next_completion_id: 0,
 1899            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1900            next_inlay_id: 0,
 1901            available_code_actions: Default::default(),
 1902            code_actions_task: Default::default(),
 1903            document_highlights_task: Default::default(),
 1904            linked_editing_range_task: Default::default(),
 1905            pending_rename: Default::default(),
 1906            searchable: true,
 1907            cursor_shape: EditorSettings::get_global(cx).cursor_shape,
 1908            current_line_highlight: None,
 1909            autoindent_mode: Some(AutoindentMode::EachLine),
 1910            collapse_matches: false,
 1911            workspace: None,
 1912            input_enabled: true,
 1913            use_modal_editing: mode == EditorMode::Full,
 1914            read_only: false,
 1915            use_autoclose: true,
 1916            use_auto_surround: true,
 1917            auto_replace_emoji_shortcode: false,
 1918            leader_peer_id: None,
 1919            remote_id: None,
 1920            hover_state: Default::default(),
 1921            hovered_link_state: Default::default(),
 1922            inline_completion_provider: None,
 1923            active_inline_completion: None,
 1924            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1925            expanded_hunks: ExpandedHunks::default(),
 1926            gutter_hovered: false,
 1927            pixel_position_of_newest_cursor: None,
 1928            last_bounds: None,
 1929            expect_bounds_change: None,
 1930            gutter_dimensions: GutterDimensions::default(),
 1931            style: None,
 1932            show_cursor_names: false,
 1933            hovered_cursors: Default::default(),
 1934            next_editor_action_id: EditorActionId::default(),
 1935            editor_actions: Rc::default(),
 1936            show_inline_completions_override: None,
 1937            enable_inline_completions: true,
 1938            custom_context_menu: None,
 1939            show_git_blame_gutter: false,
 1940            show_git_blame_inline: false,
 1941            show_selection_menu: None,
 1942            show_git_blame_inline_delay_task: None,
 1943            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1944            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1945                .session
 1946                .restore_unsaved_buffers,
 1947            blame: None,
 1948            blame_subscription: None,
 1949            file_header_size,
 1950            tasks: Default::default(),
 1951            _subscriptions: vec![
 1952                cx.observe(&buffer, Self::on_buffer_changed),
 1953                cx.subscribe(&buffer, Self::on_buffer_event),
 1954                cx.observe(&display_map, Self::on_display_map_changed),
 1955                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1956                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1957                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1958                cx.observe_window_activation(|editor, cx| {
 1959                    let active = cx.is_window_active();
 1960                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1961                        if active {
 1962                            blink_manager.enable(cx);
 1963                        } else {
 1964                            blink_manager.disable(cx);
 1965                        }
 1966                    });
 1967                }),
 1968            ],
 1969            tasks_update_task: None,
 1970            linked_edit_ranges: Default::default(),
 1971            previous_search_ranges: None,
 1972            breadcrumb_header: None,
 1973            focused_block: None,
 1974            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1975            addons: HashMap::default(),
 1976            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1977        };
 1978        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1979        this._subscriptions.extend(project_subscriptions);
 1980
 1981        this.end_selection(cx);
 1982        this.scroll_manager.show_scrollbar(cx);
 1983
 1984        if mode == EditorMode::Full {
 1985            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1986            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1987
 1988            if this.git_blame_inline_enabled {
 1989                this.git_blame_inline_enabled = true;
 1990                this.start_git_blame_inline(false, cx);
 1991            }
 1992        }
 1993
 1994        this.report_editor_event("open", None, cx);
 1995        this
 1996    }
 1997
 1998    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1999        self.mouse_context_menu
 2000            .as_ref()
 2001            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 2002    }
 2003
 2004    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 2005        let mut key_context = KeyContext::new_with_defaults();
 2006        key_context.add("Editor");
 2007        let mode = match self.mode {
 2008            EditorMode::SingleLine { .. } => "single_line",
 2009            EditorMode::AutoHeight { .. } => "auto_height",
 2010            EditorMode::Full => "full",
 2011        };
 2012
 2013        if EditorSettings::jupyter_enabled(cx) {
 2014            key_context.add("jupyter");
 2015        }
 2016
 2017        key_context.set("mode", mode);
 2018        if self.pending_rename.is_some() {
 2019            key_context.add("renaming");
 2020        }
 2021        if self.context_menu_visible() {
 2022            match self.context_menu.read().as_ref() {
 2023                Some(ContextMenu::Completions(_)) => {
 2024                    key_context.add("menu");
 2025                    key_context.add("showing_completions")
 2026                }
 2027                Some(ContextMenu::CodeActions(_)) => {
 2028                    key_context.add("menu");
 2029                    key_context.add("showing_code_actions")
 2030                }
 2031                None => {}
 2032            }
 2033        }
 2034
 2035        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 2036        if !self.focus_handle(cx).contains_focused(cx)
 2037            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 2038        {
 2039            for addon in self.addons.values() {
 2040                addon.extend_key_context(&mut key_context, cx)
 2041            }
 2042        }
 2043
 2044        if let Some(extension) = self
 2045            .buffer
 2046            .read(cx)
 2047            .as_singleton()
 2048            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 2049        {
 2050            key_context.set("extension", extension.to_string());
 2051        }
 2052
 2053        if self.has_active_inline_completion(cx) {
 2054            key_context.add("copilot_suggestion");
 2055            key_context.add("inline_completion");
 2056        }
 2057
 2058        key_context
 2059    }
 2060
 2061    pub fn new_file(
 2062        workspace: &mut Workspace,
 2063        _: &workspace::NewFile,
 2064        cx: &mut ViewContext<Workspace>,
 2065    ) {
 2066        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 2067            "Failed to create buffer",
 2068            cx,
 2069            |e, _| match e.error_code() {
 2070                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2071                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2072                e.error_tag("required").unwrap_or("the latest version")
 2073            )),
 2074                _ => None,
 2075            },
 2076        );
 2077    }
 2078
 2079    pub fn new_in_workspace(
 2080        workspace: &mut Workspace,
 2081        cx: &mut ViewContext<Workspace>,
 2082    ) -> Task<Result<View<Editor>>> {
 2083        let project = workspace.project().clone();
 2084        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2085
 2086        cx.spawn(|workspace, mut cx| async move {
 2087            let buffer = create.await?;
 2088            workspace.update(&mut cx, |workspace, cx| {
 2089                let editor =
 2090                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2091                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2092                editor
 2093            })
 2094        })
 2095    }
 2096
 2097    fn new_file_vertical(
 2098        workspace: &mut Workspace,
 2099        _: &workspace::NewFileSplitVertical,
 2100        cx: &mut ViewContext<Workspace>,
 2101    ) {
 2102        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 2103    }
 2104
 2105    fn new_file_horizontal(
 2106        workspace: &mut Workspace,
 2107        _: &workspace::NewFileSplitHorizontal,
 2108        cx: &mut ViewContext<Workspace>,
 2109    ) {
 2110        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 2111    }
 2112
 2113    fn new_file_in_direction(
 2114        workspace: &mut Workspace,
 2115        direction: SplitDirection,
 2116        cx: &mut ViewContext<Workspace>,
 2117    ) {
 2118        let project = workspace.project().clone();
 2119        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2120
 2121        cx.spawn(|workspace, mut cx| async move {
 2122            let buffer = create.await?;
 2123            workspace.update(&mut cx, move |workspace, cx| {
 2124                workspace.split_item(
 2125                    direction,
 2126                    Box::new(
 2127                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2128                    ),
 2129                    cx,
 2130                )
 2131            })?;
 2132            anyhow::Ok(())
 2133        })
 2134        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2135            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2136                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2137                e.error_tag("required").unwrap_or("the latest version")
 2138            )),
 2139            _ => None,
 2140        });
 2141    }
 2142
 2143    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
 2144        self.buffer.read(cx).replica_id()
 2145    }
 2146
 2147    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2148        self.leader_peer_id
 2149    }
 2150
 2151    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2152        &self.buffer
 2153    }
 2154
 2155    pub fn workspace(&self) -> Option<View<Workspace>> {
 2156        self.workspace.as_ref()?.0.upgrade()
 2157    }
 2158
 2159    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2160        self.buffer().read(cx).title(cx)
 2161    }
 2162
 2163    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2164        EditorSnapshot {
 2165            mode: self.mode,
 2166            show_gutter: self.show_gutter,
 2167            show_line_numbers: self.show_line_numbers,
 2168            show_git_diff_gutter: self.show_git_diff_gutter,
 2169            show_code_actions: self.show_code_actions,
 2170            show_runnables: self.show_runnables,
 2171            render_git_blame_gutter: self.render_git_blame_gutter(cx),
 2172            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2173            scroll_anchor: self.scroll_manager.anchor(),
 2174            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2175            placeholder_text: self.placeholder_text.clone(),
 2176            is_focused: self.focus_handle.is_focused(cx),
 2177            current_line_highlight: self
 2178                .current_line_highlight
 2179                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2180            gutter_hovered: self.gutter_hovered,
 2181        }
 2182    }
 2183
 2184    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2185        self.buffer.read(cx).language_at(point, cx)
 2186    }
 2187
 2188    pub fn file_at<T: ToOffset>(
 2189        &self,
 2190        point: T,
 2191        cx: &AppContext,
 2192    ) -> Option<Arc<dyn language::File>> {
 2193        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2194    }
 2195
 2196    pub fn active_excerpt(
 2197        &self,
 2198        cx: &AppContext,
 2199    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2200        self.buffer
 2201            .read(cx)
 2202            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2203    }
 2204
 2205    pub fn mode(&self) -> EditorMode {
 2206        self.mode
 2207    }
 2208
 2209    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2210        self.collaboration_hub.as_deref()
 2211    }
 2212
 2213    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2214        self.collaboration_hub = Some(hub);
 2215    }
 2216
 2217    pub fn set_custom_context_menu(
 2218        &mut self,
 2219        f: impl 'static
 2220            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2221    ) {
 2222        self.custom_context_menu = Some(Box::new(f))
 2223    }
 2224
 2225    pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
 2226        self.completion_provider = Some(provider);
 2227    }
 2228
 2229    pub fn set_inline_completion_provider<T>(
 2230        &mut self,
 2231        provider: Option<Model<T>>,
 2232        cx: &mut ViewContext<Self>,
 2233    ) where
 2234        T: InlineCompletionProvider,
 2235    {
 2236        self.inline_completion_provider =
 2237            provider.map(|provider| RegisteredInlineCompletionProvider {
 2238                _subscription: cx.observe(&provider, |this, _, cx| {
 2239                    if this.focus_handle.is_focused(cx) {
 2240                        this.update_visible_inline_completion(cx);
 2241                    }
 2242                }),
 2243                provider: Arc::new(provider),
 2244            });
 2245        self.refresh_inline_completion(false, false, cx);
 2246    }
 2247
 2248    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2249        self.placeholder_text.as_deref()
 2250    }
 2251
 2252    pub fn set_placeholder_text(
 2253        &mut self,
 2254        placeholder_text: impl Into<Arc<str>>,
 2255        cx: &mut ViewContext<Self>,
 2256    ) {
 2257        let placeholder_text = Some(placeholder_text.into());
 2258        if self.placeholder_text != placeholder_text {
 2259            self.placeholder_text = placeholder_text;
 2260            cx.notify();
 2261        }
 2262    }
 2263
 2264    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2265        self.cursor_shape = cursor_shape;
 2266
 2267        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2268        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2269
 2270        cx.notify();
 2271    }
 2272
 2273    pub fn set_current_line_highlight(
 2274        &mut self,
 2275        current_line_highlight: Option<CurrentLineHighlight>,
 2276    ) {
 2277        self.current_line_highlight = current_line_highlight;
 2278    }
 2279
 2280    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2281        self.collapse_matches = collapse_matches;
 2282    }
 2283
 2284    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2285        if self.collapse_matches {
 2286            return range.start..range.start;
 2287        }
 2288        range.clone()
 2289    }
 2290
 2291    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2292        if self.display_map.read(cx).clip_at_line_ends != clip {
 2293            self.display_map
 2294                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2295        }
 2296    }
 2297
 2298    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2299        self.input_enabled = input_enabled;
 2300    }
 2301
 2302    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 2303        self.enable_inline_completions = enabled;
 2304    }
 2305
 2306    pub fn set_autoindent(&mut self, autoindent: bool) {
 2307        if autoindent {
 2308            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2309        } else {
 2310            self.autoindent_mode = None;
 2311        }
 2312    }
 2313
 2314    pub fn read_only(&self, cx: &AppContext) -> bool {
 2315        self.read_only || self.buffer.read(cx).read_only()
 2316    }
 2317
 2318    pub fn set_read_only(&mut self, read_only: bool) {
 2319        self.read_only = read_only;
 2320    }
 2321
 2322    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2323        self.use_autoclose = autoclose;
 2324    }
 2325
 2326    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2327        self.use_auto_surround = auto_surround;
 2328    }
 2329
 2330    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2331        self.auto_replace_emoji_shortcode = auto_replace;
 2332    }
 2333
 2334    pub fn toggle_inline_completions(
 2335        &mut self,
 2336        _: &ToggleInlineCompletions,
 2337        cx: &mut ViewContext<Self>,
 2338    ) {
 2339        if self.show_inline_completions_override.is_some() {
 2340            self.set_show_inline_completions(None, cx);
 2341        } else {
 2342            let cursor = self.selections.newest_anchor().head();
 2343            if let Some((buffer, cursor_buffer_position)) =
 2344                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 2345            {
 2346                let show_inline_completions =
 2347                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 2348                self.set_show_inline_completions(Some(show_inline_completions), cx);
 2349            }
 2350        }
 2351    }
 2352
 2353    pub fn set_show_inline_completions(
 2354        &mut self,
 2355        show_inline_completions: Option<bool>,
 2356        cx: &mut ViewContext<Self>,
 2357    ) {
 2358        self.show_inline_completions_override = show_inline_completions;
 2359        self.refresh_inline_completion(false, true, cx);
 2360    }
 2361
 2362    fn should_show_inline_completions(
 2363        &self,
 2364        buffer: &Model<Buffer>,
 2365        buffer_position: language::Anchor,
 2366        cx: &AppContext,
 2367    ) -> bool {
 2368        if let Some(provider) = self.inline_completion_provider() {
 2369            if let Some(show_inline_completions) = self.show_inline_completions_override {
 2370                show_inline_completions
 2371            } else {
 2372                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 2373            }
 2374        } else {
 2375            false
 2376        }
 2377    }
 2378
 2379    pub fn set_use_modal_editing(&mut self, to: bool) {
 2380        self.use_modal_editing = to;
 2381    }
 2382
 2383    pub fn use_modal_editing(&self) -> bool {
 2384        self.use_modal_editing
 2385    }
 2386
 2387    fn selections_did_change(
 2388        &mut self,
 2389        local: bool,
 2390        old_cursor_position: &Anchor,
 2391        show_completions: bool,
 2392        cx: &mut ViewContext<Self>,
 2393    ) {
 2394        cx.invalidate_character_coordinates();
 2395
 2396        // Copy selections to primary selection buffer
 2397        #[cfg(target_os = "linux")]
 2398        if local {
 2399            let selections = self.selections.all::<usize>(cx);
 2400            let buffer_handle = self.buffer.read(cx).read(cx);
 2401
 2402            let mut text = String::new();
 2403            for (index, selection) in selections.iter().enumerate() {
 2404                let text_for_selection = buffer_handle
 2405                    .text_for_range(selection.start..selection.end)
 2406                    .collect::<String>();
 2407
 2408                text.push_str(&text_for_selection);
 2409                if index != selections.len() - 1 {
 2410                    text.push('\n');
 2411                }
 2412            }
 2413
 2414            if !text.is_empty() {
 2415                cx.write_to_primary(ClipboardItem::new_string(text));
 2416            }
 2417        }
 2418
 2419        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2420            self.buffer.update(cx, |buffer, cx| {
 2421                buffer.set_active_selections(
 2422                    &self.selections.disjoint_anchors(),
 2423                    self.selections.line_mode,
 2424                    self.cursor_shape,
 2425                    cx,
 2426                )
 2427            });
 2428        }
 2429        let display_map = self
 2430            .display_map
 2431            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2432        let buffer = &display_map.buffer_snapshot;
 2433        self.add_selections_state = None;
 2434        self.select_next_state = None;
 2435        self.select_prev_state = None;
 2436        self.select_larger_syntax_node_stack.clear();
 2437        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2438        self.snippet_stack
 2439            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2440        self.take_rename(false, cx);
 2441
 2442        let new_cursor_position = self.selections.newest_anchor().head();
 2443
 2444        self.push_to_nav_history(
 2445            *old_cursor_position,
 2446            Some(new_cursor_position.to_point(buffer)),
 2447            cx,
 2448        );
 2449
 2450        if local {
 2451            let new_cursor_position = self.selections.newest_anchor().head();
 2452            let mut context_menu = self.context_menu.write();
 2453            let completion_menu = match context_menu.as_ref() {
 2454                Some(ContextMenu::Completions(menu)) => Some(menu),
 2455
 2456                _ => {
 2457                    *context_menu = None;
 2458                    None
 2459                }
 2460            };
 2461
 2462            if let Some(completion_menu) = completion_menu {
 2463                let cursor_position = new_cursor_position.to_offset(buffer);
 2464                let (word_range, kind) =
 2465                    buffer.surrounding_word(completion_menu.initial_position, true);
 2466                if kind == Some(CharKind::Word)
 2467                    && word_range.to_inclusive().contains(&cursor_position)
 2468                {
 2469                    let mut completion_menu = completion_menu.clone();
 2470                    drop(context_menu);
 2471
 2472                    let query = Self::completion_query(buffer, cursor_position);
 2473                    cx.spawn(move |this, mut cx| async move {
 2474                        completion_menu
 2475                            .filter(query.as_deref(), cx.background_executor().clone())
 2476                            .await;
 2477
 2478                        this.update(&mut cx, |this, cx| {
 2479                            let mut context_menu = this.context_menu.write();
 2480                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2481                                return;
 2482                            };
 2483
 2484                            if menu.id > completion_menu.id {
 2485                                return;
 2486                            }
 2487
 2488                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2489                            drop(context_menu);
 2490                            cx.notify();
 2491                        })
 2492                    })
 2493                    .detach();
 2494
 2495                    if show_completions {
 2496                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2497                    }
 2498                } else {
 2499                    drop(context_menu);
 2500                    self.hide_context_menu(cx);
 2501                }
 2502            } else {
 2503                drop(context_menu);
 2504            }
 2505
 2506            hide_hover(self, cx);
 2507
 2508            if old_cursor_position.to_display_point(&display_map).row()
 2509                != new_cursor_position.to_display_point(&display_map).row()
 2510            {
 2511                self.available_code_actions.take();
 2512            }
 2513            self.refresh_code_actions(cx);
 2514            self.refresh_document_highlights(cx);
 2515            refresh_matching_bracket_highlights(self, cx);
 2516            self.discard_inline_completion(false, cx);
 2517            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2518            if self.git_blame_inline_enabled {
 2519                self.start_inline_blame_timer(cx);
 2520            }
 2521        }
 2522
 2523        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2524        cx.emit(EditorEvent::SelectionsChanged { local });
 2525
 2526        if self.selections.disjoint_anchors().len() == 1 {
 2527            cx.emit(SearchEvent::ActiveMatchChanged)
 2528        }
 2529        cx.notify();
 2530    }
 2531
 2532    pub fn change_selections<R>(
 2533        &mut self,
 2534        autoscroll: Option<Autoscroll>,
 2535        cx: &mut ViewContext<Self>,
 2536        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2537    ) -> R {
 2538        self.change_selections_inner(autoscroll, true, cx, change)
 2539    }
 2540
 2541    pub fn change_selections_inner<R>(
 2542        &mut self,
 2543        autoscroll: Option<Autoscroll>,
 2544        request_completions: bool,
 2545        cx: &mut ViewContext<Self>,
 2546        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2547    ) -> R {
 2548        let old_cursor_position = self.selections.newest_anchor().head();
 2549        self.push_to_selection_history();
 2550
 2551        let (changed, result) = self.selections.change_with(cx, change);
 2552
 2553        if changed {
 2554            if let Some(autoscroll) = autoscroll {
 2555                self.request_autoscroll(autoscroll, cx);
 2556            }
 2557            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2558
 2559            if self.should_open_signature_help_automatically(
 2560                &old_cursor_position,
 2561                self.signature_help_state.backspace_pressed(),
 2562                cx,
 2563            ) {
 2564                self.show_signature_help(&ShowSignatureHelp, cx);
 2565            }
 2566            self.signature_help_state.set_backspace_pressed(false);
 2567        }
 2568
 2569        result
 2570    }
 2571
 2572    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2573    where
 2574        I: IntoIterator<Item = (Range<S>, T)>,
 2575        S: ToOffset,
 2576        T: Into<Arc<str>>,
 2577    {
 2578        if self.read_only(cx) {
 2579            return;
 2580        }
 2581
 2582        self.buffer
 2583            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2584    }
 2585
 2586    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2587    where
 2588        I: IntoIterator<Item = (Range<S>, T)>,
 2589        S: ToOffset,
 2590        T: Into<Arc<str>>,
 2591    {
 2592        if self.read_only(cx) {
 2593            return;
 2594        }
 2595
 2596        self.buffer.update(cx, |buffer, cx| {
 2597            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2598        });
 2599    }
 2600
 2601    pub fn edit_with_block_indent<I, S, T>(
 2602        &mut self,
 2603        edits: I,
 2604        original_indent_columns: Vec<u32>,
 2605        cx: &mut ViewContext<Self>,
 2606    ) where
 2607        I: IntoIterator<Item = (Range<S>, T)>,
 2608        S: ToOffset,
 2609        T: Into<Arc<str>>,
 2610    {
 2611        if self.read_only(cx) {
 2612            return;
 2613        }
 2614
 2615        self.buffer.update(cx, |buffer, cx| {
 2616            buffer.edit(
 2617                edits,
 2618                Some(AutoindentMode::Block {
 2619                    original_indent_columns,
 2620                }),
 2621                cx,
 2622            )
 2623        });
 2624    }
 2625
 2626    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2627        self.hide_context_menu(cx);
 2628
 2629        match phase {
 2630            SelectPhase::Begin {
 2631                position,
 2632                add,
 2633                click_count,
 2634            } => self.begin_selection(position, add, click_count, cx),
 2635            SelectPhase::BeginColumnar {
 2636                position,
 2637                goal_column,
 2638                reset,
 2639            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2640            SelectPhase::Extend {
 2641                position,
 2642                click_count,
 2643            } => self.extend_selection(position, click_count, cx),
 2644            SelectPhase::Update {
 2645                position,
 2646                goal_column,
 2647                scroll_delta,
 2648            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2649            SelectPhase::End => self.end_selection(cx),
 2650        }
 2651    }
 2652
 2653    fn extend_selection(
 2654        &mut self,
 2655        position: DisplayPoint,
 2656        click_count: usize,
 2657        cx: &mut ViewContext<Self>,
 2658    ) {
 2659        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2660        let tail = self.selections.newest::<usize>(cx).tail();
 2661        self.begin_selection(position, false, click_count, cx);
 2662
 2663        let position = position.to_offset(&display_map, Bias::Left);
 2664        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2665
 2666        let mut pending_selection = self
 2667            .selections
 2668            .pending_anchor()
 2669            .expect("extend_selection not called with pending selection");
 2670        if position >= tail {
 2671            pending_selection.start = tail_anchor;
 2672        } else {
 2673            pending_selection.end = tail_anchor;
 2674            pending_selection.reversed = true;
 2675        }
 2676
 2677        let mut pending_mode = self.selections.pending_mode().unwrap();
 2678        match &mut pending_mode {
 2679            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2680            _ => {}
 2681        }
 2682
 2683        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2684            s.set_pending(pending_selection, pending_mode)
 2685        });
 2686    }
 2687
 2688    fn begin_selection(
 2689        &mut self,
 2690        position: DisplayPoint,
 2691        add: bool,
 2692        click_count: usize,
 2693        cx: &mut ViewContext<Self>,
 2694    ) {
 2695        if !self.focus_handle.is_focused(cx) {
 2696            self.last_focused_descendant = None;
 2697            cx.focus(&self.focus_handle);
 2698        }
 2699
 2700        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2701        let buffer = &display_map.buffer_snapshot;
 2702        let newest_selection = self.selections.newest_anchor().clone();
 2703        let position = display_map.clip_point(position, Bias::Left);
 2704
 2705        let start;
 2706        let end;
 2707        let mode;
 2708        let auto_scroll;
 2709        match click_count {
 2710            1 => {
 2711                start = buffer.anchor_before(position.to_point(&display_map));
 2712                end = start;
 2713                mode = SelectMode::Character;
 2714                auto_scroll = true;
 2715            }
 2716            2 => {
 2717                let range = movement::surrounding_word(&display_map, position);
 2718                start = buffer.anchor_before(range.start.to_point(&display_map));
 2719                end = buffer.anchor_before(range.end.to_point(&display_map));
 2720                mode = SelectMode::Word(start..end);
 2721                auto_scroll = true;
 2722            }
 2723            3 => {
 2724                let position = display_map
 2725                    .clip_point(position, Bias::Left)
 2726                    .to_point(&display_map);
 2727                let line_start = display_map.prev_line_boundary(position).0;
 2728                let next_line_start = buffer.clip_point(
 2729                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2730                    Bias::Left,
 2731                );
 2732                start = buffer.anchor_before(line_start);
 2733                end = buffer.anchor_before(next_line_start);
 2734                mode = SelectMode::Line(start..end);
 2735                auto_scroll = true;
 2736            }
 2737            _ => {
 2738                start = buffer.anchor_before(0);
 2739                end = buffer.anchor_before(buffer.len());
 2740                mode = SelectMode::All;
 2741                auto_scroll = false;
 2742            }
 2743        }
 2744
 2745        let point_to_delete: Option<usize> = {
 2746            let selected_points: Vec<Selection<Point>> =
 2747                self.selections.disjoint_in_range(start..end, cx);
 2748
 2749            if !add || click_count > 1 {
 2750                None
 2751            } else if !selected_points.is_empty() {
 2752                Some(selected_points[0].id)
 2753            } else {
 2754                let clicked_point_already_selected =
 2755                    self.selections.disjoint.iter().find(|selection| {
 2756                        selection.start.to_point(buffer) == start.to_point(buffer)
 2757                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2758                    });
 2759
 2760                clicked_point_already_selected.map(|selection| selection.id)
 2761            }
 2762        };
 2763
 2764        let selections_count = self.selections.count();
 2765
 2766        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2767            if let Some(point_to_delete) = point_to_delete {
 2768                s.delete(point_to_delete);
 2769
 2770                if selections_count == 1 {
 2771                    s.set_pending_anchor_range(start..end, mode);
 2772                }
 2773            } else {
 2774                if !add {
 2775                    s.clear_disjoint();
 2776                } else if click_count > 1 {
 2777                    s.delete(newest_selection.id)
 2778                }
 2779
 2780                s.set_pending_anchor_range(start..end, mode);
 2781            }
 2782        });
 2783    }
 2784
 2785    fn begin_columnar_selection(
 2786        &mut self,
 2787        position: DisplayPoint,
 2788        goal_column: u32,
 2789        reset: bool,
 2790        cx: &mut ViewContext<Self>,
 2791    ) {
 2792        if !self.focus_handle.is_focused(cx) {
 2793            self.last_focused_descendant = None;
 2794            cx.focus(&self.focus_handle);
 2795        }
 2796
 2797        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2798
 2799        if reset {
 2800            let pointer_position = display_map
 2801                .buffer_snapshot
 2802                .anchor_before(position.to_point(&display_map));
 2803
 2804            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2805                s.clear_disjoint();
 2806                s.set_pending_anchor_range(
 2807                    pointer_position..pointer_position,
 2808                    SelectMode::Character,
 2809                );
 2810            });
 2811        }
 2812
 2813        let tail = self.selections.newest::<Point>(cx).tail();
 2814        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2815
 2816        if !reset {
 2817            self.select_columns(
 2818                tail.to_display_point(&display_map),
 2819                position,
 2820                goal_column,
 2821                &display_map,
 2822                cx,
 2823            );
 2824        }
 2825    }
 2826
 2827    fn update_selection(
 2828        &mut self,
 2829        position: DisplayPoint,
 2830        goal_column: u32,
 2831        scroll_delta: gpui::Point<f32>,
 2832        cx: &mut ViewContext<Self>,
 2833    ) {
 2834        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2835
 2836        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2837            let tail = tail.to_display_point(&display_map);
 2838            self.select_columns(tail, position, goal_column, &display_map, cx);
 2839        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2840            let buffer = self.buffer.read(cx).snapshot(cx);
 2841            let head;
 2842            let tail;
 2843            let mode = self.selections.pending_mode().unwrap();
 2844            match &mode {
 2845                SelectMode::Character => {
 2846                    head = position.to_point(&display_map);
 2847                    tail = pending.tail().to_point(&buffer);
 2848                }
 2849                SelectMode::Word(original_range) => {
 2850                    let original_display_range = original_range.start.to_display_point(&display_map)
 2851                        ..original_range.end.to_display_point(&display_map);
 2852                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2853                        ..original_display_range.end.to_point(&display_map);
 2854                    if movement::is_inside_word(&display_map, position)
 2855                        || original_display_range.contains(&position)
 2856                    {
 2857                        let word_range = movement::surrounding_word(&display_map, position);
 2858                        if word_range.start < original_display_range.start {
 2859                            head = word_range.start.to_point(&display_map);
 2860                        } else {
 2861                            head = word_range.end.to_point(&display_map);
 2862                        }
 2863                    } else {
 2864                        head = position.to_point(&display_map);
 2865                    }
 2866
 2867                    if head <= original_buffer_range.start {
 2868                        tail = original_buffer_range.end;
 2869                    } else {
 2870                        tail = original_buffer_range.start;
 2871                    }
 2872                }
 2873                SelectMode::Line(original_range) => {
 2874                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2875
 2876                    let position = display_map
 2877                        .clip_point(position, Bias::Left)
 2878                        .to_point(&display_map);
 2879                    let line_start = display_map.prev_line_boundary(position).0;
 2880                    let next_line_start = buffer.clip_point(
 2881                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2882                        Bias::Left,
 2883                    );
 2884
 2885                    if line_start < original_range.start {
 2886                        head = line_start
 2887                    } else {
 2888                        head = next_line_start
 2889                    }
 2890
 2891                    if head <= original_range.start {
 2892                        tail = original_range.end;
 2893                    } else {
 2894                        tail = original_range.start;
 2895                    }
 2896                }
 2897                SelectMode::All => {
 2898                    return;
 2899                }
 2900            };
 2901
 2902            if head < tail {
 2903                pending.start = buffer.anchor_before(head);
 2904                pending.end = buffer.anchor_before(tail);
 2905                pending.reversed = true;
 2906            } else {
 2907                pending.start = buffer.anchor_before(tail);
 2908                pending.end = buffer.anchor_before(head);
 2909                pending.reversed = false;
 2910            }
 2911
 2912            self.change_selections(None, cx, |s| {
 2913                s.set_pending(pending, mode);
 2914            });
 2915        } else {
 2916            log::error!("update_selection dispatched with no pending selection");
 2917            return;
 2918        }
 2919
 2920        self.apply_scroll_delta(scroll_delta, cx);
 2921        cx.notify();
 2922    }
 2923
 2924    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2925        self.columnar_selection_tail.take();
 2926        if self.selections.pending_anchor().is_some() {
 2927            let selections = self.selections.all::<usize>(cx);
 2928            self.change_selections(None, cx, |s| {
 2929                s.select(selections);
 2930                s.clear_pending();
 2931            });
 2932        }
 2933    }
 2934
 2935    fn select_columns(
 2936        &mut self,
 2937        tail: DisplayPoint,
 2938        head: DisplayPoint,
 2939        goal_column: u32,
 2940        display_map: &DisplaySnapshot,
 2941        cx: &mut ViewContext<Self>,
 2942    ) {
 2943        let start_row = cmp::min(tail.row(), head.row());
 2944        let end_row = cmp::max(tail.row(), head.row());
 2945        let start_column = cmp::min(tail.column(), goal_column);
 2946        let end_column = cmp::max(tail.column(), goal_column);
 2947        let reversed = start_column < tail.column();
 2948
 2949        let selection_ranges = (start_row.0..=end_row.0)
 2950            .map(DisplayRow)
 2951            .filter_map(|row| {
 2952                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2953                    let start = display_map
 2954                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2955                        .to_point(display_map);
 2956                    let end = display_map
 2957                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2958                        .to_point(display_map);
 2959                    if reversed {
 2960                        Some(end..start)
 2961                    } else {
 2962                        Some(start..end)
 2963                    }
 2964                } else {
 2965                    None
 2966                }
 2967            })
 2968            .collect::<Vec<_>>();
 2969
 2970        self.change_selections(None, cx, |s| {
 2971            s.select_ranges(selection_ranges);
 2972        });
 2973        cx.notify();
 2974    }
 2975
 2976    pub fn has_pending_nonempty_selection(&self) -> bool {
 2977        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2978            Some(Selection { start, end, .. }) => start != end,
 2979            None => false,
 2980        };
 2981
 2982        pending_nonempty_selection
 2983            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2984    }
 2985
 2986    pub fn has_pending_selection(&self) -> bool {
 2987        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2988    }
 2989
 2990    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2991        if self.clear_clicked_diff_hunks(cx) {
 2992            cx.notify();
 2993            return;
 2994        }
 2995        if self.dismiss_menus_and_popups(true, cx) {
 2996            return;
 2997        }
 2998
 2999        if self.mode == EditorMode::Full
 3000            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 3001        {
 3002            return;
 3003        }
 3004
 3005        cx.propagate();
 3006    }
 3007
 3008    pub fn dismiss_menus_and_popups(
 3009        &mut self,
 3010        should_report_inline_completion_event: bool,
 3011        cx: &mut ViewContext<Self>,
 3012    ) -> bool {
 3013        if self.take_rename(false, cx).is_some() {
 3014            return true;
 3015        }
 3016
 3017        if hide_hover(self, cx) {
 3018            return true;
 3019        }
 3020
 3021        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 3022            return true;
 3023        }
 3024
 3025        if self.hide_context_menu(cx).is_some() {
 3026            return true;
 3027        }
 3028
 3029        if self.mouse_context_menu.take().is_some() {
 3030            return true;
 3031        }
 3032
 3033        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 3034            return true;
 3035        }
 3036
 3037        if self.snippet_stack.pop().is_some() {
 3038            return true;
 3039        }
 3040
 3041        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 3042            self.dismiss_diagnostics(cx);
 3043            return true;
 3044        }
 3045
 3046        false
 3047    }
 3048
 3049    fn linked_editing_ranges_for(
 3050        &self,
 3051        selection: Range<text::Anchor>,
 3052        cx: &AppContext,
 3053    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 3054        if self.linked_edit_ranges.is_empty() {
 3055            return None;
 3056        }
 3057        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 3058            selection.end.buffer_id.and_then(|end_buffer_id| {
 3059                if selection.start.buffer_id != Some(end_buffer_id) {
 3060                    return None;
 3061                }
 3062                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 3063                let snapshot = buffer.read(cx).snapshot();
 3064                self.linked_edit_ranges
 3065                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 3066                    .map(|ranges| (ranges, snapshot, buffer))
 3067            })?;
 3068        use text::ToOffset as TO;
 3069        // find offset from the start of current range to current cursor position
 3070        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 3071
 3072        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 3073        let start_difference = start_offset - start_byte_offset;
 3074        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 3075        let end_difference = end_offset - start_byte_offset;
 3076        // Current range has associated linked ranges.
 3077        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3078        for range in linked_ranges.iter() {
 3079            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 3080            let end_offset = start_offset + end_difference;
 3081            let start_offset = start_offset + start_difference;
 3082            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 3083                continue;
 3084            }
 3085            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 3086                if s.start.buffer_id != selection.start.buffer_id
 3087                    || s.end.buffer_id != selection.end.buffer_id
 3088                {
 3089                    return false;
 3090                }
 3091                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 3092                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 3093            }) {
 3094                continue;
 3095            }
 3096            let start = buffer_snapshot.anchor_after(start_offset);
 3097            let end = buffer_snapshot.anchor_after(end_offset);
 3098            linked_edits
 3099                .entry(buffer.clone())
 3100                .or_default()
 3101                .push(start..end);
 3102        }
 3103        Some(linked_edits)
 3104    }
 3105
 3106    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3107        let text: Arc<str> = text.into();
 3108
 3109        if self.read_only(cx) {
 3110            return;
 3111        }
 3112
 3113        let selections = self.selections.all_adjusted(cx);
 3114        let mut bracket_inserted = false;
 3115        let mut edits = Vec::new();
 3116        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3117        let mut new_selections = Vec::with_capacity(selections.len());
 3118        let mut new_autoclose_regions = Vec::new();
 3119        let snapshot = self.buffer.read(cx).read(cx);
 3120
 3121        for (selection, autoclose_region) in
 3122            self.selections_with_autoclose_regions(selections, &snapshot)
 3123        {
 3124            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3125                // Determine if the inserted text matches the opening or closing
 3126                // bracket of any of this language's bracket pairs.
 3127                let mut bracket_pair = None;
 3128                let mut is_bracket_pair_start = false;
 3129                let mut is_bracket_pair_end = false;
 3130                if !text.is_empty() {
 3131                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3132                    //  and they are removing the character that triggered IME popup.
 3133                    for (pair, enabled) in scope.brackets() {
 3134                        if !pair.close && !pair.surround {
 3135                            continue;
 3136                        }
 3137
 3138                        if enabled && pair.start.ends_with(text.as_ref()) {
 3139                            bracket_pair = Some(pair.clone());
 3140                            is_bracket_pair_start = true;
 3141                            break;
 3142                        }
 3143                        if pair.end.as_str() == text.as_ref() {
 3144                            bracket_pair = Some(pair.clone());
 3145                            is_bracket_pair_end = true;
 3146                            break;
 3147                        }
 3148                    }
 3149                }
 3150
 3151                if let Some(bracket_pair) = bracket_pair {
 3152                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3153                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3154                    let auto_surround =
 3155                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3156                    if selection.is_empty() {
 3157                        if is_bracket_pair_start {
 3158                            let prefix_len = bracket_pair.start.len() - text.len();
 3159
 3160                            // If the inserted text is a suffix of an opening bracket and the
 3161                            // selection is preceded by the rest of the opening bracket, then
 3162                            // insert the closing bracket.
 3163                            let following_text_allows_autoclose = snapshot
 3164                                .chars_at(selection.start)
 3165                                .next()
 3166                                .map_or(true, |c| scope.should_autoclose_before(c));
 3167                            let preceding_text_matches_prefix = prefix_len == 0
 3168                                || (selection.start.column >= (prefix_len as u32)
 3169                                    && snapshot.contains_str_at(
 3170                                        Point::new(
 3171                                            selection.start.row,
 3172                                            selection.start.column - (prefix_len as u32),
 3173                                        ),
 3174                                        &bracket_pair.start[..prefix_len],
 3175                                    ));
 3176
 3177                            if autoclose
 3178                                && bracket_pair.close
 3179                                && following_text_allows_autoclose
 3180                                && preceding_text_matches_prefix
 3181                            {
 3182                                let anchor = snapshot.anchor_before(selection.end);
 3183                                new_selections.push((selection.map(|_| anchor), text.len()));
 3184                                new_autoclose_regions.push((
 3185                                    anchor,
 3186                                    text.len(),
 3187                                    selection.id,
 3188                                    bracket_pair.clone(),
 3189                                ));
 3190                                edits.push((
 3191                                    selection.range(),
 3192                                    format!("{}{}", text, bracket_pair.end).into(),
 3193                                ));
 3194                                bracket_inserted = true;
 3195                                continue;
 3196                            }
 3197                        }
 3198
 3199                        if let Some(region) = autoclose_region {
 3200                            // If the selection is followed by an auto-inserted closing bracket,
 3201                            // then don't insert that closing bracket again; just move the selection
 3202                            // past the closing bracket.
 3203                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3204                                && text.as_ref() == region.pair.end.as_str();
 3205                            if should_skip {
 3206                                let anchor = snapshot.anchor_after(selection.end);
 3207                                new_selections
 3208                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3209                                continue;
 3210                            }
 3211                        }
 3212
 3213                        let always_treat_brackets_as_autoclosed = snapshot
 3214                            .settings_at(selection.start, cx)
 3215                            .always_treat_brackets_as_autoclosed;
 3216                        if always_treat_brackets_as_autoclosed
 3217                            && is_bracket_pair_end
 3218                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3219                        {
 3220                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3221                            // and the inserted text is a closing bracket and the selection is followed
 3222                            // by the closing bracket then move the selection past the closing bracket.
 3223                            let anchor = snapshot.anchor_after(selection.end);
 3224                            new_selections.push((selection.map(|_| anchor), text.len()));
 3225                            continue;
 3226                        }
 3227                    }
 3228                    // If an opening bracket is 1 character long and is typed while
 3229                    // text is selected, then surround that text with the bracket pair.
 3230                    else if auto_surround
 3231                        && bracket_pair.surround
 3232                        && is_bracket_pair_start
 3233                        && bracket_pair.start.chars().count() == 1
 3234                    {
 3235                        edits.push((selection.start..selection.start, text.clone()));
 3236                        edits.push((
 3237                            selection.end..selection.end,
 3238                            bracket_pair.end.as_str().into(),
 3239                        ));
 3240                        bracket_inserted = true;
 3241                        new_selections.push((
 3242                            Selection {
 3243                                id: selection.id,
 3244                                start: snapshot.anchor_after(selection.start),
 3245                                end: snapshot.anchor_before(selection.end),
 3246                                reversed: selection.reversed,
 3247                                goal: selection.goal,
 3248                            },
 3249                            0,
 3250                        ));
 3251                        continue;
 3252                    }
 3253                }
 3254            }
 3255
 3256            if self.auto_replace_emoji_shortcode
 3257                && selection.is_empty()
 3258                && text.as_ref().ends_with(':')
 3259            {
 3260                if let Some(possible_emoji_short_code) =
 3261                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3262                {
 3263                    if !possible_emoji_short_code.is_empty() {
 3264                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3265                            let emoji_shortcode_start = Point::new(
 3266                                selection.start.row,
 3267                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3268                            );
 3269
 3270                            // Remove shortcode from buffer
 3271                            edits.push((
 3272                                emoji_shortcode_start..selection.start,
 3273                                "".to_string().into(),
 3274                            ));
 3275                            new_selections.push((
 3276                                Selection {
 3277                                    id: selection.id,
 3278                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3279                                    end: snapshot.anchor_before(selection.start),
 3280                                    reversed: selection.reversed,
 3281                                    goal: selection.goal,
 3282                                },
 3283                                0,
 3284                            ));
 3285
 3286                            // Insert emoji
 3287                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3288                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3289                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3290
 3291                            continue;
 3292                        }
 3293                    }
 3294                }
 3295            }
 3296
 3297            // If not handling any auto-close operation, then just replace the selected
 3298            // text with the given input and move the selection to the end of the
 3299            // newly inserted text.
 3300            let anchor = snapshot.anchor_after(selection.end);
 3301            if !self.linked_edit_ranges.is_empty() {
 3302                let start_anchor = snapshot.anchor_before(selection.start);
 3303
 3304                let is_word_char = text.chars().next().map_or(true, |char| {
 3305                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3306                    classifier.is_word(char)
 3307                });
 3308
 3309                if is_word_char {
 3310                    if let Some(ranges) = self
 3311                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3312                    {
 3313                        for (buffer, edits) in ranges {
 3314                            linked_edits
 3315                                .entry(buffer.clone())
 3316                                .or_default()
 3317                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3318                        }
 3319                    }
 3320                }
 3321            }
 3322
 3323            new_selections.push((selection.map(|_| anchor), 0));
 3324            edits.push((selection.start..selection.end, text.clone()));
 3325        }
 3326
 3327        drop(snapshot);
 3328
 3329        self.transact(cx, |this, cx| {
 3330            this.buffer.update(cx, |buffer, cx| {
 3331                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3332            });
 3333            for (buffer, edits) in linked_edits {
 3334                buffer.update(cx, |buffer, cx| {
 3335                    let snapshot = buffer.snapshot();
 3336                    let edits = edits
 3337                        .into_iter()
 3338                        .map(|(range, text)| {
 3339                            use text::ToPoint as TP;
 3340                            let end_point = TP::to_point(&range.end, &snapshot);
 3341                            let start_point = TP::to_point(&range.start, &snapshot);
 3342                            (start_point..end_point, text)
 3343                        })
 3344                        .sorted_by_key(|(range, _)| range.start)
 3345                        .collect::<Vec<_>>();
 3346                    buffer.edit(edits, None, cx);
 3347                })
 3348            }
 3349            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3350            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3351            let snapshot = this.buffer.read(cx).read(cx);
 3352            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3353                .zip(new_selection_deltas)
 3354                .map(|(selection, delta)| Selection {
 3355                    id: selection.id,
 3356                    start: selection.start + delta,
 3357                    end: selection.end + delta,
 3358                    reversed: selection.reversed,
 3359                    goal: SelectionGoal::None,
 3360                })
 3361                .collect::<Vec<_>>();
 3362
 3363            let mut i = 0;
 3364            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3365                let position = position.to_offset(&snapshot) + delta;
 3366                let start = snapshot.anchor_before(position);
 3367                let end = snapshot.anchor_after(position);
 3368                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3369                    match existing_state.range.start.cmp(&start, &snapshot) {
 3370                        Ordering::Less => i += 1,
 3371                        Ordering::Greater => break,
 3372                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3373                            Ordering::Less => i += 1,
 3374                            Ordering::Equal => break,
 3375                            Ordering::Greater => break,
 3376                        },
 3377                    }
 3378                }
 3379                this.autoclose_regions.insert(
 3380                    i,
 3381                    AutocloseRegion {
 3382                        selection_id,
 3383                        range: start..end,
 3384                        pair,
 3385                    },
 3386                );
 3387            }
 3388
 3389            drop(snapshot);
 3390            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3391            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3392                s.select(new_selections)
 3393            });
 3394
 3395            if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
 3396                if let Some(on_type_format_task) =
 3397                    this.trigger_on_type_formatting(text.to_string(), cx)
 3398                {
 3399                    on_type_format_task.detach_and_log_err(cx);
 3400                }
 3401            }
 3402
 3403            let editor_settings = EditorSettings::get_global(cx);
 3404            if bracket_inserted
 3405                && (editor_settings.auto_signature_help
 3406                    || editor_settings.show_signature_help_after_edits)
 3407            {
 3408                this.show_signature_help(&ShowSignatureHelp, cx);
 3409            }
 3410
 3411            let trigger_in_words = !had_active_inline_completion;
 3412            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3413            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3414            this.refresh_inline_completion(true, false, cx);
 3415        });
 3416    }
 3417
 3418    fn find_possible_emoji_shortcode_at_position(
 3419        snapshot: &MultiBufferSnapshot,
 3420        position: Point,
 3421    ) -> Option<String> {
 3422        let mut chars = Vec::new();
 3423        let mut found_colon = false;
 3424        for char in snapshot.reversed_chars_at(position).take(100) {
 3425            // Found a possible emoji shortcode in the middle of the buffer
 3426            if found_colon {
 3427                if char.is_whitespace() {
 3428                    chars.reverse();
 3429                    return Some(chars.iter().collect());
 3430                }
 3431                // If the previous character is not a whitespace, we are in the middle of a word
 3432                // and we only want to complete the shortcode if the word is made up of other emojis
 3433                let mut containing_word = String::new();
 3434                for ch in snapshot
 3435                    .reversed_chars_at(position)
 3436                    .skip(chars.len() + 1)
 3437                    .take(100)
 3438                {
 3439                    if ch.is_whitespace() {
 3440                        break;
 3441                    }
 3442                    containing_word.push(ch);
 3443                }
 3444                let containing_word = containing_word.chars().rev().collect::<String>();
 3445                if util::word_consists_of_emojis(containing_word.as_str()) {
 3446                    chars.reverse();
 3447                    return Some(chars.iter().collect());
 3448                }
 3449            }
 3450
 3451            if char.is_whitespace() || !char.is_ascii() {
 3452                return None;
 3453            }
 3454            if char == ':' {
 3455                found_colon = true;
 3456            } else {
 3457                chars.push(char);
 3458            }
 3459        }
 3460        // Found a possible emoji shortcode at the beginning of the buffer
 3461        chars.reverse();
 3462        Some(chars.iter().collect())
 3463    }
 3464
 3465    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3466        self.transact(cx, |this, cx| {
 3467            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3468                let selections = this.selections.all::<usize>(cx);
 3469                let multi_buffer = this.buffer.read(cx);
 3470                let buffer = multi_buffer.snapshot(cx);
 3471                selections
 3472                    .iter()
 3473                    .map(|selection| {
 3474                        let start_point = selection.start.to_point(&buffer);
 3475                        let mut indent =
 3476                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3477                        indent.len = cmp::min(indent.len, start_point.column);
 3478                        let start = selection.start;
 3479                        let end = selection.end;
 3480                        let selection_is_empty = start == end;
 3481                        let language_scope = buffer.language_scope_at(start);
 3482                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3483                            &language_scope
 3484                        {
 3485                            let leading_whitespace_len = buffer
 3486                                .reversed_chars_at(start)
 3487                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3488                                .map(|c| c.len_utf8())
 3489                                .sum::<usize>();
 3490
 3491                            let trailing_whitespace_len = buffer
 3492                                .chars_at(end)
 3493                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3494                                .map(|c| c.len_utf8())
 3495                                .sum::<usize>();
 3496
 3497                            let insert_extra_newline =
 3498                                language.brackets().any(|(pair, enabled)| {
 3499                                    let pair_start = pair.start.trim_end();
 3500                                    let pair_end = pair.end.trim_start();
 3501
 3502                                    enabled
 3503                                        && pair.newline
 3504                                        && buffer.contains_str_at(
 3505                                            end + trailing_whitespace_len,
 3506                                            pair_end,
 3507                                        )
 3508                                        && buffer.contains_str_at(
 3509                                            (start - leading_whitespace_len)
 3510                                                .saturating_sub(pair_start.len()),
 3511                                            pair_start,
 3512                                        )
 3513                                });
 3514
 3515                            // Comment extension on newline is allowed only for cursor selections
 3516                            let comment_delimiter = maybe!({
 3517                                if !selection_is_empty {
 3518                                    return None;
 3519                                }
 3520
 3521                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3522                                    return None;
 3523                                }
 3524
 3525                                let delimiters = language.line_comment_prefixes();
 3526                                let max_len_of_delimiter =
 3527                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3528                                let (snapshot, range) =
 3529                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3530
 3531                                let mut index_of_first_non_whitespace = 0;
 3532                                let comment_candidate = snapshot
 3533                                    .chars_for_range(range)
 3534                                    .skip_while(|c| {
 3535                                        let should_skip = c.is_whitespace();
 3536                                        if should_skip {
 3537                                            index_of_first_non_whitespace += 1;
 3538                                        }
 3539                                        should_skip
 3540                                    })
 3541                                    .take(max_len_of_delimiter)
 3542                                    .collect::<String>();
 3543                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3544                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3545                                })?;
 3546                                let cursor_is_placed_after_comment_marker =
 3547                                    index_of_first_non_whitespace + comment_prefix.len()
 3548                                        <= start_point.column as usize;
 3549                                if cursor_is_placed_after_comment_marker {
 3550                                    Some(comment_prefix.clone())
 3551                                } else {
 3552                                    None
 3553                                }
 3554                            });
 3555                            (comment_delimiter, insert_extra_newline)
 3556                        } else {
 3557                            (None, false)
 3558                        };
 3559
 3560                        let capacity_for_delimiter = comment_delimiter
 3561                            .as_deref()
 3562                            .map(str::len)
 3563                            .unwrap_or_default();
 3564                        let mut new_text =
 3565                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3566                        new_text.push('\n');
 3567                        new_text.extend(indent.chars());
 3568                        if let Some(delimiter) = &comment_delimiter {
 3569                            new_text.push_str(delimiter);
 3570                        }
 3571                        if insert_extra_newline {
 3572                            new_text = new_text.repeat(2);
 3573                        }
 3574
 3575                        let anchor = buffer.anchor_after(end);
 3576                        let new_selection = selection.map(|_| anchor);
 3577                        (
 3578                            (start..end, new_text),
 3579                            (insert_extra_newline, new_selection),
 3580                        )
 3581                    })
 3582                    .unzip()
 3583            };
 3584
 3585            this.edit_with_autoindent(edits, cx);
 3586            let buffer = this.buffer.read(cx).snapshot(cx);
 3587            let new_selections = selection_fixup_info
 3588                .into_iter()
 3589                .map(|(extra_newline_inserted, new_selection)| {
 3590                    let mut cursor = new_selection.end.to_point(&buffer);
 3591                    if extra_newline_inserted {
 3592                        cursor.row -= 1;
 3593                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3594                    }
 3595                    new_selection.map(|_| cursor)
 3596                })
 3597                .collect();
 3598
 3599            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3600            this.refresh_inline_completion(true, false, cx);
 3601        });
 3602    }
 3603
 3604    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3605        let buffer = self.buffer.read(cx);
 3606        let snapshot = buffer.snapshot(cx);
 3607
 3608        let mut edits = Vec::new();
 3609        let mut rows = Vec::new();
 3610
 3611        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3612            let cursor = selection.head();
 3613            let row = cursor.row;
 3614
 3615            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3616
 3617            let newline = "\n".to_string();
 3618            edits.push((start_of_line..start_of_line, newline));
 3619
 3620            rows.push(row + rows_inserted as u32);
 3621        }
 3622
 3623        self.transact(cx, |editor, cx| {
 3624            editor.edit(edits, cx);
 3625
 3626            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3627                let mut index = 0;
 3628                s.move_cursors_with(|map, _, _| {
 3629                    let row = rows[index];
 3630                    index += 1;
 3631
 3632                    let point = Point::new(row, 0);
 3633                    let boundary = map.next_line_boundary(point).1;
 3634                    let clipped = map.clip_point(boundary, Bias::Left);
 3635
 3636                    (clipped, SelectionGoal::None)
 3637                });
 3638            });
 3639
 3640            let mut indent_edits = Vec::new();
 3641            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3642            for row in rows {
 3643                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3644                for (row, indent) in indents {
 3645                    if indent.len == 0 {
 3646                        continue;
 3647                    }
 3648
 3649                    let text = match indent.kind {
 3650                        IndentKind::Space => " ".repeat(indent.len as usize),
 3651                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3652                    };
 3653                    let point = Point::new(row.0, 0);
 3654                    indent_edits.push((point..point, text));
 3655                }
 3656            }
 3657            editor.edit(indent_edits, cx);
 3658        });
 3659    }
 3660
 3661    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3662        let buffer = self.buffer.read(cx);
 3663        let snapshot = buffer.snapshot(cx);
 3664
 3665        let mut edits = Vec::new();
 3666        let mut rows = Vec::new();
 3667        let mut rows_inserted = 0;
 3668
 3669        for selection in self.selections.all_adjusted(cx) {
 3670            let cursor = selection.head();
 3671            let row = cursor.row;
 3672
 3673            let point = Point::new(row + 1, 0);
 3674            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3675
 3676            let newline = "\n".to_string();
 3677            edits.push((start_of_line..start_of_line, newline));
 3678
 3679            rows_inserted += 1;
 3680            rows.push(row + rows_inserted);
 3681        }
 3682
 3683        self.transact(cx, |editor, cx| {
 3684            editor.edit(edits, cx);
 3685
 3686            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3687                let mut index = 0;
 3688                s.move_cursors_with(|map, _, _| {
 3689                    let row = rows[index];
 3690                    index += 1;
 3691
 3692                    let point = Point::new(row, 0);
 3693                    let boundary = map.next_line_boundary(point).1;
 3694                    let clipped = map.clip_point(boundary, Bias::Left);
 3695
 3696                    (clipped, SelectionGoal::None)
 3697                });
 3698            });
 3699
 3700            let mut indent_edits = Vec::new();
 3701            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3702            for row in rows {
 3703                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3704                for (row, indent) in indents {
 3705                    if indent.len == 0 {
 3706                        continue;
 3707                    }
 3708
 3709                    let text = match indent.kind {
 3710                        IndentKind::Space => " ".repeat(indent.len as usize),
 3711                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3712                    };
 3713                    let point = Point::new(row.0, 0);
 3714                    indent_edits.push((point..point, text));
 3715                }
 3716            }
 3717            editor.edit(indent_edits, cx);
 3718        });
 3719    }
 3720
 3721    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3722        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3723            original_indent_columns: Vec::new(),
 3724        });
 3725        self.insert_with_autoindent_mode(text, autoindent, cx);
 3726    }
 3727
 3728    fn insert_with_autoindent_mode(
 3729        &mut self,
 3730        text: &str,
 3731        autoindent_mode: Option<AutoindentMode>,
 3732        cx: &mut ViewContext<Self>,
 3733    ) {
 3734        if self.read_only(cx) {
 3735            return;
 3736        }
 3737
 3738        let text: Arc<str> = text.into();
 3739        self.transact(cx, |this, cx| {
 3740            let old_selections = this.selections.all_adjusted(cx);
 3741            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3742                let anchors = {
 3743                    let snapshot = buffer.read(cx);
 3744                    old_selections
 3745                        .iter()
 3746                        .map(|s| {
 3747                            let anchor = snapshot.anchor_after(s.head());
 3748                            s.map(|_| anchor)
 3749                        })
 3750                        .collect::<Vec<_>>()
 3751                };
 3752                buffer.edit(
 3753                    old_selections
 3754                        .iter()
 3755                        .map(|s| (s.start..s.end, text.clone())),
 3756                    autoindent_mode,
 3757                    cx,
 3758                );
 3759                anchors
 3760            });
 3761
 3762            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3763                s.select_anchors(selection_anchors);
 3764            })
 3765        });
 3766    }
 3767
 3768    fn trigger_completion_on_input(
 3769        &mut self,
 3770        text: &str,
 3771        trigger_in_words: bool,
 3772        cx: &mut ViewContext<Self>,
 3773    ) {
 3774        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3775            self.show_completions(
 3776                &ShowCompletions {
 3777                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3778                },
 3779                cx,
 3780            );
 3781        } else {
 3782            self.hide_context_menu(cx);
 3783        }
 3784    }
 3785
 3786    fn is_completion_trigger(
 3787        &self,
 3788        text: &str,
 3789        trigger_in_words: bool,
 3790        cx: &mut ViewContext<Self>,
 3791    ) -> bool {
 3792        let position = self.selections.newest_anchor().head();
 3793        let multibuffer = self.buffer.read(cx);
 3794        let Some(buffer) = position
 3795            .buffer_id
 3796            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3797        else {
 3798            return false;
 3799        };
 3800
 3801        if let Some(completion_provider) = &self.completion_provider {
 3802            completion_provider.is_completion_trigger(
 3803                &buffer,
 3804                position.text_anchor,
 3805                text,
 3806                trigger_in_words,
 3807                cx,
 3808            )
 3809        } else {
 3810            false
 3811        }
 3812    }
 3813
 3814    /// If any empty selections is touching the start of its innermost containing autoclose
 3815    /// region, expand it to select the brackets.
 3816    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3817        let selections = self.selections.all::<usize>(cx);
 3818        let buffer = self.buffer.read(cx).read(cx);
 3819        let new_selections = self
 3820            .selections_with_autoclose_regions(selections, &buffer)
 3821            .map(|(mut selection, region)| {
 3822                if !selection.is_empty() {
 3823                    return selection;
 3824                }
 3825
 3826                if let Some(region) = region {
 3827                    let mut range = region.range.to_offset(&buffer);
 3828                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3829                        range.start -= region.pair.start.len();
 3830                        if buffer.contains_str_at(range.start, &region.pair.start)
 3831                            && buffer.contains_str_at(range.end, &region.pair.end)
 3832                        {
 3833                            range.end += region.pair.end.len();
 3834                            selection.start = range.start;
 3835                            selection.end = range.end;
 3836
 3837                            return selection;
 3838                        }
 3839                    }
 3840                }
 3841
 3842                let always_treat_brackets_as_autoclosed = buffer
 3843                    .settings_at(selection.start, cx)
 3844                    .always_treat_brackets_as_autoclosed;
 3845
 3846                if !always_treat_brackets_as_autoclosed {
 3847                    return selection;
 3848                }
 3849
 3850                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3851                    for (pair, enabled) in scope.brackets() {
 3852                        if !enabled || !pair.close {
 3853                            continue;
 3854                        }
 3855
 3856                        if buffer.contains_str_at(selection.start, &pair.end) {
 3857                            let pair_start_len = pair.start.len();
 3858                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3859                            {
 3860                                selection.start -= pair_start_len;
 3861                                selection.end += pair.end.len();
 3862
 3863                                return selection;
 3864                            }
 3865                        }
 3866                    }
 3867                }
 3868
 3869                selection
 3870            })
 3871            .collect();
 3872
 3873        drop(buffer);
 3874        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3875    }
 3876
 3877    /// Iterate the given selections, and for each one, find the smallest surrounding
 3878    /// autoclose region. This uses the ordering of the selections and the autoclose
 3879    /// regions to avoid repeated comparisons.
 3880    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3881        &'a self,
 3882        selections: impl IntoIterator<Item = Selection<D>>,
 3883        buffer: &'a MultiBufferSnapshot,
 3884    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3885        let mut i = 0;
 3886        let mut regions = self.autoclose_regions.as_slice();
 3887        selections.into_iter().map(move |selection| {
 3888            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3889
 3890            let mut enclosing = None;
 3891            while let Some(pair_state) = regions.get(i) {
 3892                if pair_state.range.end.to_offset(buffer) < range.start {
 3893                    regions = &regions[i + 1..];
 3894                    i = 0;
 3895                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3896                    break;
 3897                } else {
 3898                    if pair_state.selection_id == selection.id {
 3899                        enclosing = Some(pair_state);
 3900                    }
 3901                    i += 1;
 3902                }
 3903            }
 3904
 3905            (selection.clone(), enclosing)
 3906        })
 3907    }
 3908
 3909    /// Remove any autoclose regions that no longer contain their selection.
 3910    fn invalidate_autoclose_regions(
 3911        &mut self,
 3912        mut selections: &[Selection<Anchor>],
 3913        buffer: &MultiBufferSnapshot,
 3914    ) {
 3915        self.autoclose_regions.retain(|state| {
 3916            let mut i = 0;
 3917            while let Some(selection) = selections.get(i) {
 3918                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3919                    selections = &selections[1..];
 3920                    continue;
 3921                }
 3922                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3923                    break;
 3924                }
 3925                if selection.id == state.selection_id {
 3926                    return true;
 3927                } else {
 3928                    i += 1;
 3929                }
 3930            }
 3931            false
 3932        });
 3933    }
 3934
 3935    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3936        let offset = position.to_offset(buffer);
 3937        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3938        if offset > word_range.start && kind == Some(CharKind::Word) {
 3939            Some(
 3940                buffer
 3941                    .text_for_range(word_range.start..offset)
 3942                    .collect::<String>(),
 3943            )
 3944        } else {
 3945            None
 3946        }
 3947    }
 3948
 3949    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3950        self.refresh_inlay_hints(
 3951            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3952            cx,
 3953        );
 3954    }
 3955
 3956    pub fn inlay_hints_enabled(&self) -> bool {
 3957        self.inlay_hint_cache.enabled
 3958    }
 3959
 3960    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3961        if self.project.is_none() || self.mode != EditorMode::Full {
 3962            return;
 3963        }
 3964
 3965        let reason_description = reason.description();
 3966        let ignore_debounce = matches!(
 3967            reason,
 3968            InlayHintRefreshReason::SettingsChange(_)
 3969                | InlayHintRefreshReason::Toggle(_)
 3970                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3971        );
 3972        let (invalidate_cache, required_languages) = match reason {
 3973            InlayHintRefreshReason::Toggle(enabled) => {
 3974                self.inlay_hint_cache.enabled = enabled;
 3975                if enabled {
 3976                    (InvalidationStrategy::RefreshRequested, None)
 3977                } else {
 3978                    self.inlay_hint_cache.clear();
 3979                    self.splice_inlays(
 3980                        self.visible_inlay_hints(cx)
 3981                            .iter()
 3982                            .map(|inlay| inlay.id)
 3983                            .collect(),
 3984                        Vec::new(),
 3985                        cx,
 3986                    );
 3987                    return;
 3988                }
 3989            }
 3990            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3991                match self.inlay_hint_cache.update_settings(
 3992                    &self.buffer,
 3993                    new_settings,
 3994                    self.visible_inlay_hints(cx),
 3995                    cx,
 3996                ) {
 3997                    ControlFlow::Break(Some(InlaySplice {
 3998                        to_remove,
 3999                        to_insert,
 4000                    })) => {
 4001                        self.splice_inlays(to_remove, to_insert, cx);
 4002                        return;
 4003                    }
 4004                    ControlFlow::Break(None) => return,
 4005                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 4006                }
 4007            }
 4008            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 4009                if let Some(InlaySplice {
 4010                    to_remove,
 4011                    to_insert,
 4012                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 4013                {
 4014                    self.splice_inlays(to_remove, to_insert, cx);
 4015                }
 4016                return;
 4017            }
 4018            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 4019            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 4020                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 4021            }
 4022            InlayHintRefreshReason::RefreshRequested => {
 4023                (InvalidationStrategy::RefreshRequested, None)
 4024            }
 4025        };
 4026
 4027        if let Some(InlaySplice {
 4028            to_remove,
 4029            to_insert,
 4030        }) = self.inlay_hint_cache.spawn_hint_refresh(
 4031            reason_description,
 4032            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 4033            invalidate_cache,
 4034            ignore_debounce,
 4035            cx,
 4036        ) {
 4037            self.splice_inlays(to_remove, to_insert, cx);
 4038        }
 4039    }
 4040
 4041    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 4042        self.display_map
 4043            .read(cx)
 4044            .current_inlays()
 4045            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 4046            .cloned()
 4047            .collect()
 4048    }
 4049
 4050    pub fn excerpts_for_inlay_hints_query(
 4051        &self,
 4052        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 4053        cx: &mut ViewContext<Editor>,
 4054    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 4055        let Some(project) = self.project.as_ref() else {
 4056            return HashMap::default();
 4057        };
 4058        let project = project.read(cx);
 4059        let multi_buffer = self.buffer().read(cx);
 4060        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 4061        let multi_buffer_visible_start = self
 4062            .scroll_manager
 4063            .anchor()
 4064            .anchor
 4065            .to_point(&multi_buffer_snapshot);
 4066        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 4067            multi_buffer_visible_start
 4068                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 4069            Bias::Left,
 4070        );
 4071        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 4072        multi_buffer
 4073            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 4074            .into_iter()
 4075            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 4076            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 4077                let buffer = buffer_handle.read(cx);
 4078                let buffer_file = project::File::from_dyn(buffer.file())?;
 4079                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 4080                let worktree_entry = buffer_worktree
 4081                    .read(cx)
 4082                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 4083                if worktree_entry.is_ignored {
 4084                    return None;
 4085                }
 4086
 4087                let language = buffer.language()?;
 4088                if let Some(restrict_to_languages) = restrict_to_languages {
 4089                    if !restrict_to_languages.contains(language) {
 4090                        return None;
 4091                    }
 4092                }
 4093                Some((
 4094                    excerpt_id,
 4095                    (
 4096                        buffer_handle,
 4097                        buffer.version().clone(),
 4098                        excerpt_visible_range,
 4099                    ),
 4100                ))
 4101            })
 4102            .collect()
 4103    }
 4104
 4105    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 4106        TextLayoutDetails {
 4107            text_system: cx.text_system().clone(),
 4108            editor_style: self.style.clone().unwrap(),
 4109            rem_size: cx.rem_size(),
 4110            scroll_anchor: self.scroll_manager.anchor(),
 4111            visible_rows: self.visible_line_count(),
 4112            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 4113        }
 4114    }
 4115
 4116    fn splice_inlays(
 4117        &self,
 4118        to_remove: Vec<InlayId>,
 4119        to_insert: Vec<Inlay>,
 4120        cx: &mut ViewContext<Self>,
 4121    ) {
 4122        self.display_map.update(cx, |display_map, cx| {
 4123            display_map.splice_inlays(to_remove, to_insert, cx);
 4124        });
 4125        cx.notify();
 4126    }
 4127
 4128    fn trigger_on_type_formatting(
 4129        &self,
 4130        input: String,
 4131        cx: &mut ViewContext<Self>,
 4132    ) -> Option<Task<Result<()>>> {
 4133        if input.len() != 1 {
 4134            return None;
 4135        }
 4136
 4137        let project = self.project.as_ref()?;
 4138        let position = self.selections.newest_anchor().head();
 4139        let (buffer, buffer_position) = self
 4140            .buffer
 4141            .read(cx)
 4142            .text_anchor_for_position(position, cx)?;
 4143
 4144        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4145        // hence we do LSP request & edit on host side only — add formats to host's history.
 4146        let push_to_lsp_host_history = true;
 4147        // If this is not the host, append its history with new edits.
 4148        let push_to_client_history = project.read(cx).is_via_collab();
 4149
 4150        let on_type_formatting = project.update(cx, |project, cx| {
 4151            project.on_type_format(
 4152                buffer.clone(),
 4153                buffer_position,
 4154                input,
 4155                push_to_lsp_host_history,
 4156                cx,
 4157            )
 4158        });
 4159        Some(cx.spawn(|editor, mut cx| async move {
 4160            if let Some(transaction) = on_type_formatting.await? {
 4161                if push_to_client_history {
 4162                    buffer
 4163                        .update(&mut cx, |buffer, _| {
 4164                            buffer.push_transaction(transaction, Instant::now());
 4165                        })
 4166                        .ok();
 4167                }
 4168                editor.update(&mut cx, |editor, cx| {
 4169                    editor.refresh_document_highlights(cx);
 4170                })?;
 4171            }
 4172            Ok(())
 4173        }))
 4174    }
 4175
 4176    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4177        if self.pending_rename.is_some() {
 4178            return;
 4179        }
 4180
 4181        let Some(provider) = self.completion_provider.as_ref() else {
 4182            return;
 4183        };
 4184
 4185        let position = self.selections.newest_anchor().head();
 4186        let (buffer, buffer_position) =
 4187            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4188                output
 4189            } else {
 4190                return;
 4191            };
 4192
 4193        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4194        let is_followup_invoke = {
 4195            let context_menu_state = self.context_menu.read();
 4196            matches!(
 4197                context_menu_state.deref(),
 4198                Some(ContextMenu::Completions(_))
 4199            )
 4200        };
 4201        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4202            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4203            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
 4204                CompletionTriggerKind::TRIGGER_CHARACTER
 4205            }
 4206
 4207            _ => CompletionTriggerKind::INVOKED,
 4208        };
 4209        let completion_context = CompletionContext {
 4210            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4211                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4212                    Some(String::from(trigger))
 4213                } else {
 4214                    None
 4215                }
 4216            }),
 4217            trigger_kind,
 4218        };
 4219        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4220        let sort_completions = provider.sort_completions();
 4221
 4222        let id = post_inc(&mut self.next_completion_id);
 4223        let task = cx.spawn(|this, mut cx| {
 4224            async move {
 4225                this.update(&mut cx, |this, _| {
 4226                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4227                })?;
 4228                let completions = completions.await.log_err();
 4229                let menu = if let Some(completions) = completions {
 4230                    let mut menu = CompletionsMenu {
 4231                        id,
 4232                        sort_completions,
 4233                        initial_position: position,
 4234                        match_candidates: completions
 4235                            .iter()
 4236                            .enumerate()
 4237                            .map(|(id, completion)| {
 4238                                StringMatchCandidate::new(
 4239                                    id,
 4240                                    completion.label.text[completion.label.filter_range.clone()]
 4241                                        .into(),
 4242                                )
 4243                            })
 4244                            .collect(),
 4245                        buffer: buffer.clone(),
 4246                        completions: Arc::new(RwLock::new(completions.into())),
 4247                        matches: Vec::new().into(),
 4248                        selected_item: 0,
 4249                        scroll_handle: UniformListScrollHandle::new(),
 4250                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4251                            DebouncedDelay::new(),
 4252                        )),
 4253                    };
 4254                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4255                        .await;
 4256
 4257                    if menu.matches.is_empty() {
 4258                        None
 4259                    } else {
 4260                        this.update(&mut cx, |editor, cx| {
 4261                            let completions = menu.completions.clone();
 4262                            let matches = menu.matches.clone();
 4263
 4264                            let delay_ms = EditorSettings::get_global(cx)
 4265                                .completion_documentation_secondary_query_debounce;
 4266                            let delay = Duration::from_millis(delay_ms);
 4267                            editor
 4268                                .completion_documentation_pre_resolve_debounce
 4269                                .fire_new(delay, cx, |editor, cx| {
 4270                                    CompletionsMenu::pre_resolve_completion_documentation(
 4271                                        buffer,
 4272                                        completions,
 4273                                        matches,
 4274                                        editor,
 4275                                        cx,
 4276                                    )
 4277                                });
 4278                        })
 4279                        .ok();
 4280                        Some(menu)
 4281                    }
 4282                } else {
 4283                    None
 4284                };
 4285
 4286                this.update(&mut cx, |this, cx| {
 4287                    let mut context_menu = this.context_menu.write();
 4288                    match context_menu.as_ref() {
 4289                        None => {}
 4290
 4291                        Some(ContextMenu::Completions(prev_menu)) => {
 4292                            if prev_menu.id > id {
 4293                                return;
 4294                            }
 4295                        }
 4296
 4297                        _ => return,
 4298                    }
 4299
 4300                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4301                        let menu = menu.unwrap();
 4302                        *context_menu = Some(ContextMenu::Completions(menu));
 4303                        drop(context_menu);
 4304                        this.discard_inline_completion(false, cx);
 4305                        cx.notify();
 4306                    } else if this.completion_tasks.len() <= 1 {
 4307                        // If there are no more completion tasks and the last menu was
 4308                        // empty, we should hide it. If it was already hidden, we should
 4309                        // also show the copilot completion when available.
 4310                        drop(context_menu);
 4311                        if this.hide_context_menu(cx).is_none() {
 4312                            this.update_visible_inline_completion(cx);
 4313                        }
 4314                    }
 4315                })?;
 4316
 4317                Ok::<_, anyhow::Error>(())
 4318            }
 4319            .log_err()
 4320        });
 4321
 4322        self.completion_tasks.push((id, task));
 4323    }
 4324
 4325    pub fn confirm_completion(
 4326        &mut self,
 4327        action: &ConfirmCompletion,
 4328        cx: &mut ViewContext<Self>,
 4329    ) -> Option<Task<Result<()>>> {
 4330        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 4331    }
 4332
 4333    pub fn compose_completion(
 4334        &mut self,
 4335        action: &ComposeCompletion,
 4336        cx: &mut ViewContext<Self>,
 4337    ) -> Option<Task<Result<()>>> {
 4338        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 4339    }
 4340
 4341    fn do_completion(
 4342        &mut self,
 4343        item_ix: Option<usize>,
 4344        intent: CompletionIntent,
 4345        cx: &mut ViewContext<Editor>,
 4346    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4347        use language::ToOffset as _;
 4348
 4349        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4350            menu
 4351        } else {
 4352            return None;
 4353        };
 4354
 4355        let mat = completions_menu
 4356            .matches
 4357            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4358        let buffer_handle = completions_menu.buffer;
 4359        let completions = completions_menu.completions.read();
 4360        let completion = completions.get(mat.candidate_id)?;
 4361        cx.stop_propagation();
 4362
 4363        let snippet;
 4364        let text;
 4365
 4366        if completion.is_snippet() {
 4367            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4368            text = snippet.as_ref().unwrap().text.clone();
 4369        } else {
 4370            snippet = None;
 4371            text = completion.new_text.clone();
 4372        };
 4373        let selections = self.selections.all::<usize>(cx);
 4374        let buffer = buffer_handle.read(cx);
 4375        let old_range = completion.old_range.to_offset(buffer);
 4376        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4377
 4378        let newest_selection = self.selections.newest_anchor();
 4379        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4380            return None;
 4381        }
 4382
 4383        let lookbehind = newest_selection
 4384            .start
 4385            .text_anchor
 4386            .to_offset(buffer)
 4387            .saturating_sub(old_range.start);
 4388        let lookahead = old_range
 4389            .end
 4390            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4391        let mut common_prefix_len = old_text
 4392            .bytes()
 4393            .zip(text.bytes())
 4394            .take_while(|(a, b)| a == b)
 4395            .count();
 4396
 4397        let snapshot = self.buffer.read(cx).snapshot(cx);
 4398        let mut range_to_replace: Option<Range<isize>> = None;
 4399        let mut ranges = Vec::new();
 4400        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4401        for selection in &selections {
 4402            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4403                let start = selection.start.saturating_sub(lookbehind);
 4404                let end = selection.end + lookahead;
 4405                if selection.id == newest_selection.id {
 4406                    range_to_replace = Some(
 4407                        ((start + common_prefix_len) as isize - selection.start as isize)
 4408                            ..(end as isize - selection.start as isize),
 4409                    );
 4410                }
 4411                ranges.push(start + common_prefix_len..end);
 4412            } else {
 4413                common_prefix_len = 0;
 4414                ranges.clear();
 4415                ranges.extend(selections.iter().map(|s| {
 4416                    if s.id == newest_selection.id {
 4417                        range_to_replace = Some(
 4418                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4419                                - selection.start as isize
 4420                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4421                                    - selection.start as isize,
 4422                        );
 4423                        old_range.clone()
 4424                    } else {
 4425                        s.start..s.end
 4426                    }
 4427                }));
 4428                break;
 4429            }
 4430            if !self.linked_edit_ranges.is_empty() {
 4431                let start_anchor = snapshot.anchor_before(selection.head());
 4432                let end_anchor = snapshot.anchor_after(selection.tail());
 4433                if let Some(ranges) = self
 4434                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4435                {
 4436                    for (buffer, edits) in ranges {
 4437                        linked_edits.entry(buffer.clone()).or_default().extend(
 4438                            edits
 4439                                .into_iter()
 4440                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4441                        );
 4442                    }
 4443                }
 4444            }
 4445        }
 4446        let text = &text[common_prefix_len..];
 4447
 4448        cx.emit(EditorEvent::InputHandled {
 4449            utf16_range_to_replace: range_to_replace,
 4450            text: text.into(),
 4451        });
 4452
 4453        self.transact(cx, |this, cx| {
 4454            if let Some(mut snippet) = snippet {
 4455                snippet.text = text.to_string();
 4456                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4457                    tabstop.start -= common_prefix_len as isize;
 4458                    tabstop.end -= common_prefix_len as isize;
 4459                }
 4460
 4461                this.insert_snippet(&ranges, snippet, cx).log_err();
 4462            } else {
 4463                this.buffer.update(cx, |buffer, cx| {
 4464                    buffer.edit(
 4465                        ranges.iter().map(|range| (range.clone(), text)),
 4466                        this.autoindent_mode.clone(),
 4467                        cx,
 4468                    );
 4469                });
 4470            }
 4471            for (buffer, edits) in linked_edits {
 4472                buffer.update(cx, |buffer, cx| {
 4473                    let snapshot = buffer.snapshot();
 4474                    let edits = edits
 4475                        .into_iter()
 4476                        .map(|(range, text)| {
 4477                            use text::ToPoint as TP;
 4478                            let end_point = TP::to_point(&range.end, &snapshot);
 4479                            let start_point = TP::to_point(&range.start, &snapshot);
 4480                            (start_point..end_point, text)
 4481                        })
 4482                        .sorted_by_key(|(range, _)| range.start)
 4483                        .collect::<Vec<_>>();
 4484                    buffer.edit(edits, None, cx);
 4485                })
 4486            }
 4487
 4488            this.refresh_inline_completion(true, false, cx);
 4489        });
 4490
 4491        let show_new_completions_on_confirm = completion
 4492            .confirm
 4493            .as_ref()
 4494            .map_or(false, |confirm| confirm(intent, cx));
 4495        if show_new_completions_on_confirm {
 4496            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4497        }
 4498
 4499        let provider = self.completion_provider.as_ref()?;
 4500        let apply_edits = provider.apply_additional_edits_for_completion(
 4501            buffer_handle,
 4502            completion.clone(),
 4503            true,
 4504            cx,
 4505        );
 4506
 4507        let editor_settings = EditorSettings::get_global(cx);
 4508        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4509            // After the code completion is finished, users often want to know what signatures are needed.
 4510            // so we should automatically call signature_help
 4511            self.show_signature_help(&ShowSignatureHelp, cx);
 4512        }
 4513
 4514        Some(cx.foreground_executor().spawn(async move {
 4515            apply_edits.await?;
 4516            Ok(())
 4517        }))
 4518    }
 4519
 4520    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4521        let mut context_menu = self.context_menu.write();
 4522        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4523            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4524                // Toggle if we're selecting the same one
 4525                *context_menu = None;
 4526                cx.notify();
 4527                return;
 4528            } else {
 4529                // Otherwise, clear it and start a new one
 4530                *context_menu = None;
 4531                cx.notify();
 4532            }
 4533        }
 4534        drop(context_menu);
 4535        let snapshot = self.snapshot(cx);
 4536        let deployed_from_indicator = action.deployed_from_indicator;
 4537        let mut task = self.code_actions_task.take();
 4538        let action = action.clone();
 4539        cx.spawn(|editor, mut cx| async move {
 4540            while let Some(prev_task) = task {
 4541                prev_task.await;
 4542                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4543            }
 4544
 4545            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4546                if editor.focus_handle.is_focused(cx) {
 4547                    let multibuffer_point = action
 4548                        .deployed_from_indicator
 4549                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4550                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4551                    let (buffer, buffer_row) = snapshot
 4552                        .buffer_snapshot
 4553                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4554                        .and_then(|(buffer_snapshot, range)| {
 4555                            editor
 4556                                .buffer
 4557                                .read(cx)
 4558                                .buffer(buffer_snapshot.remote_id())
 4559                                .map(|buffer| (buffer, range.start.row))
 4560                        })?;
 4561                    let (_, code_actions) = editor
 4562                        .available_code_actions
 4563                        .clone()
 4564                        .and_then(|(location, code_actions)| {
 4565                            let snapshot = location.buffer.read(cx).snapshot();
 4566                            let point_range = location.range.to_point(&snapshot);
 4567                            let point_range = point_range.start.row..=point_range.end.row;
 4568                            if point_range.contains(&buffer_row) {
 4569                                Some((location, code_actions))
 4570                            } else {
 4571                                None
 4572                            }
 4573                        })
 4574                        .unzip();
 4575                    let buffer_id = buffer.read(cx).remote_id();
 4576                    let tasks = editor
 4577                        .tasks
 4578                        .get(&(buffer_id, buffer_row))
 4579                        .map(|t| Arc::new(t.to_owned()));
 4580                    if tasks.is_none() && code_actions.is_none() {
 4581                        return None;
 4582                    }
 4583
 4584                    editor.completion_tasks.clear();
 4585                    editor.discard_inline_completion(false, cx);
 4586                    let task_context =
 4587                        tasks
 4588                            .as_ref()
 4589                            .zip(editor.project.clone())
 4590                            .map(|(tasks, project)| {
 4591                                let position = Point::new(buffer_row, tasks.column);
 4592                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4593                                let location = Location {
 4594                                    buffer: buffer.clone(),
 4595                                    range: range_start..range_start,
 4596                                };
 4597                                // Fill in the environmental variables from the tree-sitter captures
 4598                                let mut captured_task_variables = TaskVariables::default();
 4599                                for (capture_name, value) in tasks.extra_variables.clone() {
 4600                                    captured_task_variables.insert(
 4601                                        task::VariableName::Custom(capture_name.into()),
 4602                                        value.clone(),
 4603                                    );
 4604                                }
 4605                                project.update(cx, |project, cx| {
 4606                                    project.task_context_for_location(
 4607                                        captured_task_variables,
 4608                                        location,
 4609                                        cx,
 4610                                    )
 4611                                })
 4612                            });
 4613
 4614                    Some(cx.spawn(|editor, mut cx| async move {
 4615                        let task_context = match task_context {
 4616                            Some(task_context) => task_context.await,
 4617                            None => None,
 4618                        };
 4619                        let resolved_tasks =
 4620                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4621                                Arc::new(ResolvedTasks {
 4622                                    templates: tasks
 4623                                        .templates
 4624                                        .iter()
 4625                                        .filter_map(|(kind, template)| {
 4626                                            template
 4627                                                .resolve_task(&kind.to_id_base(), &task_context)
 4628                                                .map(|task| (kind.clone(), task))
 4629                                        })
 4630                                        .collect(),
 4631                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4632                                        multibuffer_point.row,
 4633                                        tasks.column,
 4634                                    )),
 4635                                })
 4636                            });
 4637                        let spawn_straight_away = resolved_tasks
 4638                            .as_ref()
 4639                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4640                            && code_actions
 4641                                .as_ref()
 4642                                .map_or(true, |actions| actions.is_empty());
 4643                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4644                            *editor.context_menu.write() =
 4645                                Some(ContextMenu::CodeActions(CodeActionsMenu {
 4646                                    buffer,
 4647                                    actions: CodeActionContents {
 4648                                        tasks: resolved_tasks,
 4649                                        actions: code_actions,
 4650                                    },
 4651                                    selected_item: Default::default(),
 4652                                    scroll_handle: UniformListScrollHandle::default(),
 4653                                    deployed_from_indicator,
 4654                                }));
 4655                            if spawn_straight_away {
 4656                                if let Some(task) = editor.confirm_code_action(
 4657                                    &ConfirmCodeAction { item_ix: Some(0) },
 4658                                    cx,
 4659                                ) {
 4660                                    cx.notify();
 4661                                    return task;
 4662                                }
 4663                            }
 4664                            cx.notify();
 4665                            Task::ready(Ok(()))
 4666                        }) {
 4667                            task.await
 4668                        } else {
 4669                            Ok(())
 4670                        }
 4671                    }))
 4672                } else {
 4673                    Some(Task::ready(Ok(())))
 4674                }
 4675            })?;
 4676            if let Some(task) = spawned_test_task {
 4677                task.await?;
 4678            }
 4679
 4680            Ok::<_, anyhow::Error>(())
 4681        })
 4682        .detach_and_log_err(cx);
 4683    }
 4684
 4685    pub fn confirm_code_action(
 4686        &mut self,
 4687        action: &ConfirmCodeAction,
 4688        cx: &mut ViewContext<Self>,
 4689    ) -> Option<Task<Result<()>>> {
 4690        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4691            menu
 4692        } else {
 4693            return None;
 4694        };
 4695        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4696        let action = actions_menu.actions.get(action_ix)?;
 4697        let title = action.label();
 4698        let buffer = actions_menu.buffer;
 4699        let workspace = self.workspace()?;
 4700
 4701        match action {
 4702            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4703                workspace.update(cx, |workspace, cx| {
 4704                    workspace::tasks::schedule_resolved_task(
 4705                        workspace,
 4706                        task_source_kind,
 4707                        resolved_task,
 4708                        false,
 4709                        cx,
 4710                    );
 4711
 4712                    Some(Task::ready(Ok(())))
 4713                })
 4714            }
 4715            CodeActionsItem::CodeAction(action) => {
 4716                let apply_code_actions = workspace
 4717                    .read(cx)
 4718                    .project()
 4719                    .clone()
 4720                    .update(cx, |project, cx| {
 4721                        project.apply_code_action(buffer, action, true, cx)
 4722                    });
 4723                let workspace = workspace.downgrade();
 4724                Some(cx.spawn(|editor, cx| async move {
 4725                    let project_transaction = apply_code_actions.await?;
 4726                    Self::open_project_transaction(
 4727                        &editor,
 4728                        workspace,
 4729                        project_transaction,
 4730                        title,
 4731                        cx,
 4732                    )
 4733                    .await
 4734                }))
 4735            }
 4736        }
 4737    }
 4738
 4739    pub async fn open_project_transaction(
 4740        this: &WeakView<Editor>,
 4741        workspace: WeakView<Workspace>,
 4742        transaction: ProjectTransaction,
 4743        title: String,
 4744        mut cx: AsyncWindowContext,
 4745    ) -> Result<()> {
 4746        let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
 4747
 4748        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4749        cx.update(|cx| {
 4750            entries.sort_unstable_by_key(|(buffer, _)| {
 4751                buffer.read(cx).file().map(|f| f.path().clone())
 4752            });
 4753        })?;
 4754
 4755        // If the project transaction's edits are all contained within this editor, then
 4756        // avoid opening a new editor to display them.
 4757
 4758        if let Some((buffer, transaction)) = entries.first() {
 4759            if entries.len() == 1 {
 4760                let excerpt = this.update(&mut cx, |editor, cx| {
 4761                    editor
 4762                        .buffer()
 4763                        .read(cx)
 4764                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4765                })?;
 4766                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4767                    if excerpted_buffer == *buffer {
 4768                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4769                            let excerpt_range = excerpt_range.to_offset(buffer);
 4770                            buffer
 4771                                .edited_ranges_for_transaction::<usize>(transaction)
 4772                                .all(|range| {
 4773                                    excerpt_range.start <= range.start
 4774                                        && excerpt_range.end >= range.end
 4775                                })
 4776                        })?;
 4777
 4778                        if all_edits_within_excerpt {
 4779                            return Ok(());
 4780                        }
 4781                    }
 4782                }
 4783            }
 4784        } else {
 4785            return Ok(());
 4786        }
 4787
 4788        let mut ranges_to_highlight = Vec::new();
 4789        let excerpt_buffer = cx.new_model(|cx| {
 4790            let mut multibuffer =
 4791                MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
 4792            for (buffer_handle, transaction) in &entries {
 4793                let buffer = buffer_handle.read(cx);
 4794                ranges_to_highlight.extend(
 4795                    multibuffer.push_excerpts_with_context_lines(
 4796                        buffer_handle.clone(),
 4797                        buffer
 4798                            .edited_ranges_for_transaction::<usize>(transaction)
 4799                            .collect(),
 4800                        DEFAULT_MULTIBUFFER_CONTEXT,
 4801                        cx,
 4802                    ),
 4803                );
 4804            }
 4805            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4806            multibuffer
 4807        })?;
 4808
 4809        workspace.update(&mut cx, |workspace, cx| {
 4810            let project = workspace.project().clone();
 4811            let editor =
 4812                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4813            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4814            editor.update(cx, |editor, cx| {
 4815                editor.highlight_background::<Self>(
 4816                    &ranges_to_highlight,
 4817                    |theme| theme.editor_highlighted_line_background,
 4818                    cx,
 4819                );
 4820            });
 4821        })?;
 4822
 4823        Ok(())
 4824    }
 4825
 4826    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4827        let project = self.project.clone()?;
 4828        let buffer = self.buffer.read(cx);
 4829        let newest_selection = self.selections.newest_anchor().clone();
 4830        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4831        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4832        if start_buffer != end_buffer {
 4833            return None;
 4834        }
 4835
 4836        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4837            cx.background_executor()
 4838                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4839                .await;
 4840
 4841            let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
 4842                project.code_actions(&start_buffer, start..end, cx)
 4843            }) {
 4844                code_actions.await
 4845            } else {
 4846                Vec::new()
 4847            };
 4848
 4849            this.update(&mut cx, |this, cx| {
 4850                this.available_code_actions = if actions.is_empty() {
 4851                    None
 4852                } else {
 4853                    Some((
 4854                        Location {
 4855                            buffer: start_buffer,
 4856                            range: start..end,
 4857                        },
 4858                        actions.into(),
 4859                    ))
 4860                };
 4861                cx.notify();
 4862            })
 4863            .log_err();
 4864        }));
 4865        None
 4866    }
 4867
 4868    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4869        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4870            self.show_git_blame_inline = false;
 4871
 4872            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4873                cx.background_executor().timer(delay).await;
 4874
 4875                this.update(&mut cx, |this, cx| {
 4876                    this.show_git_blame_inline = true;
 4877                    cx.notify();
 4878                })
 4879                .log_err();
 4880            }));
 4881        }
 4882    }
 4883
 4884    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4885        if self.pending_rename.is_some() {
 4886            return None;
 4887        }
 4888
 4889        let project = self.project.clone()?;
 4890        let buffer = self.buffer.read(cx);
 4891        let newest_selection = self.selections.newest_anchor().clone();
 4892        let cursor_position = newest_selection.head();
 4893        let (cursor_buffer, cursor_buffer_position) =
 4894            buffer.text_anchor_for_position(cursor_position, cx)?;
 4895        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4896        if cursor_buffer != tail_buffer {
 4897            return None;
 4898        }
 4899
 4900        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4901            cx.background_executor()
 4902                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 4903                .await;
 4904
 4905            let highlights = if let Some(highlights) = project
 4906                .update(&mut cx, |project, cx| {
 4907                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4908                })
 4909                .log_err()
 4910            {
 4911                highlights.await.log_err()
 4912            } else {
 4913                None
 4914            };
 4915
 4916            if let Some(highlights) = highlights {
 4917                this.update(&mut cx, |this, cx| {
 4918                    if this.pending_rename.is_some() {
 4919                        return;
 4920                    }
 4921
 4922                    let buffer_id = cursor_position.buffer_id;
 4923                    let buffer = this.buffer.read(cx);
 4924                    if !buffer
 4925                        .text_anchor_for_position(cursor_position, cx)
 4926                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4927                    {
 4928                        return;
 4929                    }
 4930
 4931                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4932                    let mut write_ranges = Vec::new();
 4933                    let mut read_ranges = Vec::new();
 4934                    for highlight in highlights {
 4935                        for (excerpt_id, excerpt_range) in
 4936                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4937                        {
 4938                            let start = highlight
 4939                                .range
 4940                                .start
 4941                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4942                            let end = highlight
 4943                                .range
 4944                                .end
 4945                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4946                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4947                                continue;
 4948                            }
 4949
 4950                            let range = Anchor {
 4951                                buffer_id,
 4952                                excerpt_id,
 4953                                text_anchor: start,
 4954                            }..Anchor {
 4955                                buffer_id,
 4956                                excerpt_id,
 4957                                text_anchor: end,
 4958                            };
 4959                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4960                                write_ranges.push(range);
 4961                            } else {
 4962                                read_ranges.push(range);
 4963                            }
 4964                        }
 4965                    }
 4966
 4967                    this.highlight_background::<DocumentHighlightRead>(
 4968                        &read_ranges,
 4969                        |theme| theme.editor_document_highlight_read_background,
 4970                        cx,
 4971                    );
 4972                    this.highlight_background::<DocumentHighlightWrite>(
 4973                        &write_ranges,
 4974                        |theme| theme.editor_document_highlight_write_background,
 4975                        cx,
 4976                    );
 4977                    cx.notify();
 4978                })
 4979                .log_err();
 4980            }
 4981        }));
 4982        None
 4983    }
 4984
 4985    pub fn refresh_inline_completion(
 4986        &mut self,
 4987        debounce: bool,
 4988        user_requested: bool,
 4989        cx: &mut ViewContext<Self>,
 4990    ) -> Option<()> {
 4991        let provider = self.inline_completion_provider()?;
 4992        let cursor = self.selections.newest_anchor().head();
 4993        let (buffer, cursor_buffer_position) =
 4994            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4995
 4996        if !user_requested
 4997            && (!self.enable_inline_completions
 4998                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
 4999        {
 5000            self.discard_inline_completion(false, cx);
 5001            return None;
 5002        }
 5003
 5004        self.update_visible_inline_completion(cx);
 5005        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 5006        Some(())
 5007    }
 5008
 5009    fn cycle_inline_completion(
 5010        &mut self,
 5011        direction: Direction,
 5012        cx: &mut ViewContext<Self>,
 5013    ) -> Option<()> {
 5014        let provider = self.inline_completion_provider()?;
 5015        let cursor = self.selections.newest_anchor().head();
 5016        let (buffer, cursor_buffer_position) =
 5017            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5018        if !self.enable_inline_completions
 5019            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 5020        {
 5021            return None;
 5022        }
 5023
 5024        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5025        self.update_visible_inline_completion(cx);
 5026
 5027        Some(())
 5028    }
 5029
 5030    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 5031        if !self.has_active_inline_completion(cx) {
 5032            self.refresh_inline_completion(false, true, cx);
 5033            return;
 5034        }
 5035
 5036        self.update_visible_inline_completion(cx);
 5037    }
 5038
 5039    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 5040        self.show_cursor_names(cx);
 5041    }
 5042
 5043    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 5044        self.show_cursor_names = true;
 5045        cx.notify();
 5046        cx.spawn(|this, mut cx| async move {
 5047            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5048            this.update(&mut cx, |this, cx| {
 5049                this.show_cursor_names = false;
 5050                cx.notify()
 5051            })
 5052            .ok()
 5053        })
 5054        .detach();
 5055    }
 5056
 5057    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 5058        if self.has_active_inline_completion(cx) {
 5059            self.cycle_inline_completion(Direction::Next, cx);
 5060        } else {
 5061            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5062            if is_copilot_disabled {
 5063                cx.propagate();
 5064            }
 5065        }
 5066    }
 5067
 5068    pub fn previous_inline_completion(
 5069        &mut self,
 5070        _: &PreviousInlineCompletion,
 5071        cx: &mut ViewContext<Self>,
 5072    ) {
 5073        if self.has_active_inline_completion(cx) {
 5074            self.cycle_inline_completion(Direction::Prev, cx);
 5075        } else {
 5076            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 5077            if is_copilot_disabled {
 5078                cx.propagate();
 5079            }
 5080        }
 5081    }
 5082
 5083    pub fn accept_inline_completion(
 5084        &mut self,
 5085        _: &AcceptInlineCompletion,
 5086        cx: &mut ViewContext<Self>,
 5087    ) {
 5088        let Some(completion) = self.take_active_inline_completion(cx) else {
 5089            return;
 5090        };
 5091        if let Some(provider) = self.inline_completion_provider() {
 5092            provider.accept(cx);
 5093        }
 5094
 5095        cx.emit(EditorEvent::InputHandled {
 5096            utf16_range_to_replace: None,
 5097            text: completion.text.to_string().into(),
 5098        });
 5099
 5100        if let Some(range) = completion.delete_range {
 5101            self.change_selections(None, cx, |s| s.select_ranges([range]))
 5102        }
 5103        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 5104        self.refresh_inline_completion(true, true, cx);
 5105        cx.notify();
 5106    }
 5107
 5108    pub fn accept_partial_inline_completion(
 5109        &mut self,
 5110        _: &AcceptPartialInlineCompletion,
 5111        cx: &mut ViewContext<Self>,
 5112    ) {
 5113        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 5114            if let Some(completion) = self.take_active_inline_completion(cx) {
 5115                let mut partial_completion = completion
 5116                    .text
 5117                    .chars()
 5118                    .by_ref()
 5119                    .take_while(|c| c.is_alphabetic())
 5120                    .collect::<String>();
 5121                if partial_completion.is_empty() {
 5122                    partial_completion = completion
 5123                        .text
 5124                        .chars()
 5125                        .by_ref()
 5126                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5127                        .collect::<String>();
 5128                }
 5129
 5130                cx.emit(EditorEvent::InputHandled {
 5131                    utf16_range_to_replace: None,
 5132                    text: partial_completion.clone().into(),
 5133                });
 5134
 5135                if let Some(range) = completion.delete_range {
 5136                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 5137                }
 5138                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 5139
 5140                self.refresh_inline_completion(true, true, cx);
 5141                cx.notify();
 5142            }
 5143        }
 5144    }
 5145
 5146    fn discard_inline_completion(
 5147        &mut self,
 5148        should_report_inline_completion_event: bool,
 5149        cx: &mut ViewContext<Self>,
 5150    ) -> bool {
 5151        if let Some(provider) = self.inline_completion_provider() {
 5152            provider.discard(should_report_inline_completion_event, cx);
 5153        }
 5154
 5155        self.take_active_inline_completion(cx).is_some()
 5156    }
 5157
 5158    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5159        if let Some(completion) = self.active_inline_completion.as_ref() {
 5160            let buffer = self.buffer.read(cx).read(cx);
 5161            completion.position.is_valid(&buffer)
 5162        } else {
 5163            false
 5164        }
 5165    }
 5166
 5167    fn take_active_inline_completion(
 5168        &mut self,
 5169        cx: &mut ViewContext<Self>,
 5170    ) -> Option<CompletionState> {
 5171        let completion = self.active_inline_completion.take()?;
 5172        let render_inlay_ids = completion.render_inlay_ids.clone();
 5173        self.display_map.update(cx, |map, cx| {
 5174            map.splice_inlays(render_inlay_ids, Default::default(), cx);
 5175        });
 5176        let buffer = self.buffer.read(cx).read(cx);
 5177
 5178        if completion.position.is_valid(&buffer) {
 5179            Some(completion)
 5180        } else {
 5181            None
 5182        }
 5183    }
 5184
 5185    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5186        let selection = self.selections.newest_anchor();
 5187        let cursor = selection.head();
 5188
 5189        let excerpt_id = cursor.excerpt_id;
 5190
 5191        if self.context_menu.read().is_none()
 5192            && self.completion_tasks.is_empty()
 5193            && selection.start == selection.end
 5194        {
 5195            if let Some(provider) = self.inline_completion_provider() {
 5196                if let Some((buffer, cursor_buffer_position)) =
 5197                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5198                {
 5199                    if let Some(proposal) =
 5200                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5201                    {
 5202                        let mut to_remove = Vec::new();
 5203                        if let Some(completion) = self.active_inline_completion.take() {
 5204                            to_remove.extend(completion.render_inlay_ids.iter());
 5205                        }
 5206
 5207                        let to_add = proposal
 5208                            .inlays
 5209                            .iter()
 5210                            .filter_map(|inlay| {
 5211                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5212                                let id = post_inc(&mut self.next_inlay_id);
 5213                                match inlay {
 5214                                    InlayProposal::Hint(position, hint) => {
 5215                                        let position =
 5216                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5217                                        Some(Inlay::hint(id, position, hint))
 5218                                    }
 5219                                    InlayProposal::Suggestion(position, text) => {
 5220                                        let position =
 5221                                            snapshot.anchor_in_excerpt(excerpt_id, *position)?;
 5222                                        Some(Inlay::suggestion(id, position, text.clone()))
 5223                                    }
 5224                                }
 5225                            })
 5226                            .collect_vec();
 5227
 5228                        self.active_inline_completion = Some(CompletionState {
 5229                            position: cursor,
 5230                            text: proposal.text,
 5231                            delete_range: proposal.delete_range.and_then(|range| {
 5232                                let snapshot = self.buffer.read(cx).snapshot(cx);
 5233                                let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
 5234                                let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
 5235                                Some(start?..end?)
 5236                            }),
 5237                            render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
 5238                        });
 5239
 5240                        self.display_map
 5241                            .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
 5242
 5243                        cx.notify();
 5244                        return;
 5245                    }
 5246                }
 5247            }
 5248        }
 5249
 5250        self.discard_inline_completion(false, cx);
 5251    }
 5252
 5253    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5254        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5255    }
 5256
 5257    fn render_code_actions_indicator(
 5258        &self,
 5259        _style: &EditorStyle,
 5260        row: DisplayRow,
 5261        is_active: bool,
 5262        cx: &mut ViewContext<Self>,
 5263    ) -> Option<IconButton> {
 5264        if self.available_code_actions.is_some() {
 5265            Some(
 5266                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5267                    .shape(ui::IconButtonShape::Square)
 5268                    .icon_size(IconSize::XSmall)
 5269                    .icon_color(Color::Muted)
 5270                    .selected(is_active)
 5271                    .on_click(cx.listener(move |editor, _e, cx| {
 5272                        editor.focus(cx);
 5273                        editor.toggle_code_actions(
 5274                            &ToggleCodeActions {
 5275                                deployed_from_indicator: Some(row),
 5276                            },
 5277                            cx,
 5278                        );
 5279                    })),
 5280            )
 5281        } else {
 5282            None
 5283        }
 5284    }
 5285
 5286    fn clear_tasks(&mut self) {
 5287        self.tasks.clear()
 5288    }
 5289
 5290    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5291        if self.tasks.insert(key, value).is_some() {
 5292            // This case should hopefully be rare, but just in case...
 5293            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5294        }
 5295    }
 5296
 5297    fn render_run_indicator(
 5298        &self,
 5299        _style: &EditorStyle,
 5300        is_active: bool,
 5301        row: DisplayRow,
 5302        cx: &mut ViewContext<Self>,
 5303    ) -> IconButton {
 5304        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5305            .shape(ui::IconButtonShape::Square)
 5306            .icon_size(IconSize::XSmall)
 5307            .icon_color(Color::Muted)
 5308            .selected(is_active)
 5309            .on_click(cx.listener(move |editor, _e, cx| {
 5310                editor.focus(cx);
 5311                editor.toggle_code_actions(
 5312                    &ToggleCodeActions {
 5313                        deployed_from_indicator: Some(row),
 5314                    },
 5315                    cx,
 5316                );
 5317            }))
 5318    }
 5319
 5320    fn close_hunk_diff_button(
 5321        &self,
 5322        hunk: HoveredHunk,
 5323        row: DisplayRow,
 5324        cx: &mut ViewContext<Self>,
 5325    ) -> IconButton {
 5326        IconButton::new(
 5327            ("close_hunk_diff_indicator", row.0 as usize),
 5328            ui::IconName::Close,
 5329        )
 5330        .shape(ui::IconButtonShape::Square)
 5331        .icon_size(IconSize::XSmall)
 5332        .icon_color(Color::Muted)
 5333        .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
 5334        .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
 5335    }
 5336
 5337    pub fn context_menu_visible(&self) -> bool {
 5338        self.context_menu
 5339            .read()
 5340            .as_ref()
 5341            .map_or(false, |menu| menu.visible())
 5342    }
 5343
 5344    fn render_context_menu(
 5345        &self,
 5346        cursor_position: DisplayPoint,
 5347        style: &EditorStyle,
 5348        max_height: Pixels,
 5349        cx: &mut ViewContext<Editor>,
 5350    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5351        self.context_menu.read().as_ref().map(|menu| {
 5352            menu.render(
 5353                cursor_position,
 5354                style,
 5355                max_height,
 5356                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5357                cx,
 5358            )
 5359        })
 5360    }
 5361
 5362    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5363        cx.notify();
 5364        self.completion_tasks.clear();
 5365        let context_menu = self.context_menu.write().take();
 5366        if context_menu.is_some() {
 5367            self.update_visible_inline_completion(cx);
 5368        }
 5369        context_menu
 5370    }
 5371
 5372    pub fn insert_snippet(
 5373        &mut self,
 5374        insertion_ranges: &[Range<usize>],
 5375        snippet: Snippet,
 5376        cx: &mut ViewContext<Self>,
 5377    ) -> Result<()> {
 5378        struct Tabstop<T> {
 5379            is_end_tabstop: bool,
 5380            ranges: Vec<Range<T>>,
 5381        }
 5382
 5383        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5384            let snippet_text: Arc<str> = snippet.text.clone().into();
 5385            buffer.edit(
 5386                insertion_ranges
 5387                    .iter()
 5388                    .cloned()
 5389                    .map(|range| (range, snippet_text.clone())),
 5390                Some(AutoindentMode::EachLine),
 5391                cx,
 5392            );
 5393
 5394            let snapshot = &*buffer.read(cx);
 5395            let snippet = &snippet;
 5396            snippet
 5397                .tabstops
 5398                .iter()
 5399                .map(|tabstop| {
 5400                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5401                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5402                    });
 5403                    let mut tabstop_ranges = tabstop
 5404                        .iter()
 5405                        .flat_map(|tabstop_range| {
 5406                            let mut delta = 0_isize;
 5407                            insertion_ranges.iter().map(move |insertion_range| {
 5408                                let insertion_start = insertion_range.start as isize + delta;
 5409                                delta +=
 5410                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5411
 5412                                let start = ((insertion_start + tabstop_range.start) as usize)
 5413                                    .min(snapshot.len());
 5414                                let end = ((insertion_start + tabstop_range.end) as usize)
 5415                                    .min(snapshot.len());
 5416                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5417                            })
 5418                        })
 5419                        .collect::<Vec<_>>();
 5420                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5421
 5422                    Tabstop {
 5423                        is_end_tabstop,
 5424                        ranges: tabstop_ranges,
 5425                    }
 5426                })
 5427                .collect::<Vec<_>>()
 5428        });
 5429        if let Some(tabstop) = tabstops.first() {
 5430            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5431                s.select_ranges(tabstop.ranges.iter().cloned());
 5432            });
 5433
 5434            // If we're already at the last tabstop and it's at the end of the snippet,
 5435            // we're done, we don't need to keep the state around.
 5436            if !tabstop.is_end_tabstop {
 5437                let ranges = tabstops
 5438                    .into_iter()
 5439                    .map(|tabstop| tabstop.ranges)
 5440                    .collect::<Vec<_>>();
 5441                self.snippet_stack.push(SnippetState {
 5442                    active_index: 0,
 5443                    ranges,
 5444                });
 5445            }
 5446
 5447            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5448            if self.autoclose_regions.is_empty() {
 5449                let snapshot = self.buffer.read(cx).snapshot(cx);
 5450                for selection in &mut self.selections.all::<Point>(cx) {
 5451                    let selection_head = selection.head();
 5452                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5453                        continue;
 5454                    };
 5455
 5456                    let mut bracket_pair = None;
 5457                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5458                    let prev_chars = snapshot
 5459                        .reversed_chars_at(selection_head)
 5460                        .collect::<String>();
 5461                    for (pair, enabled) in scope.brackets() {
 5462                        if enabled
 5463                            && pair.close
 5464                            && prev_chars.starts_with(pair.start.as_str())
 5465                            && next_chars.starts_with(pair.end.as_str())
 5466                        {
 5467                            bracket_pair = Some(pair.clone());
 5468                            break;
 5469                        }
 5470                    }
 5471                    if let Some(pair) = bracket_pair {
 5472                        let start = snapshot.anchor_after(selection_head);
 5473                        let end = snapshot.anchor_after(selection_head);
 5474                        self.autoclose_regions.push(AutocloseRegion {
 5475                            selection_id: selection.id,
 5476                            range: start..end,
 5477                            pair,
 5478                        });
 5479                    }
 5480                }
 5481            }
 5482        }
 5483        Ok(())
 5484    }
 5485
 5486    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5487        self.move_to_snippet_tabstop(Bias::Right, cx)
 5488    }
 5489
 5490    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5491        self.move_to_snippet_tabstop(Bias::Left, cx)
 5492    }
 5493
 5494    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5495        if let Some(mut snippet) = self.snippet_stack.pop() {
 5496            match bias {
 5497                Bias::Left => {
 5498                    if snippet.active_index > 0 {
 5499                        snippet.active_index -= 1;
 5500                    } else {
 5501                        self.snippet_stack.push(snippet);
 5502                        return false;
 5503                    }
 5504                }
 5505                Bias::Right => {
 5506                    if snippet.active_index + 1 < snippet.ranges.len() {
 5507                        snippet.active_index += 1;
 5508                    } else {
 5509                        self.snippet_stack.push(snippet);
 5510                        return false;
 5511                    }
 5512                }
 5513            }
 5514            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5515                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5516                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5517                });
 5518                // If snippet state is not at the last tabstop, push it back on the stack
 5519                if snippet.active_index + 1 < snippet.ranges.len() {
 5520                    self.snippet_stack.push(snippet);
 5521                }
 5522                return true;
 5523            }
 5524        }
 5525
 5526        false
 5527    }
 5528
 5529    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5530        self.transact(cx, |this, cx| {
 5531            this.select_all(&SelectAll, cx);
 5532            this.insert("", cx);
 5533        });
 5534    }
 5535
 5536    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5537        self.transact(cx, |this, cx| {
 5538            this.select_autoclose_pair(cx);
 5539            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5540            if !this.linked_edit_ranges.is_empty() {
 5541                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5542                let snapshot = this.buffer.read(cx).snapshot(cx);
 5543
 5544                for selection in selections.iter() {
 5545                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5546                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5547                    if selection_start.buffer_id != selection_end.buffer_id {
 5548                        continue;
 5549                    }
 5550                    if let Some(ranges) =
 5551                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5552                    {
 5553                        for (buffer, entries) in ranges {
 5554                            linked_ranges.entry(buffer).or_default().extend(entries);
 5555                        }
 5556                    }
 5557                }
 5558            }
 5559
 5560            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5561            if !this.selections.line_mode {
 5562                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5563                for selection in &mut selections {
 5564                    if selection.is_empty() {
 5565                        let old_head = selection.head();
 5566                        let mut new_head =
 5567                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5568                                .to_point(&display_map);
 5569                        if let Some((buffer, line_buffer_range)) = display_map
 5570                            .buffer_snapshot
 5571                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5572                        {
 5573                            let indent_size =
 5574                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5575                            let indent_len = match indent_size.kind {
 5576                                IndentKind::Space => {
 5577                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5578                                }
 5579                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5580                            };
 5581                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5582                                let indent_len = indent_len.get();
 5583                                new_head = cmp::min(
 5584                                    new_head,
 5585                                    MultiBufferPoint::new(
 5586                                        old_head.row,
 5587                                        ((old_head.column - 1) / indent_len) * indent_len,
 5588                                    ),
 5589                                );
 5590                            }
 5591                        }
 5592
 5593                        selection.set_head(new_head, SelectionGoal::None);
 5594                    }
 5595                }
 5596            }
 5597
 5598            this.signature_help_state.set_backspace_pressed(true);
 5599            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5600            this.insert("", cx);
 5601            let empty_str: Arc<str> = Arc::from("");
 5602            for (buffer, edits) in linked_ranges {
 5603                let snapshot = buffer.read(cx).snapshot();
 5604                use text::ToPoint as TP;
 5605
 5606                let edits = edits
 5607                    .into_iter()
 5608                    .map(|range| {
 5609                        let end_point = TP::to_point(&range.end, &snapshot);
 5610                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5611
 5612                        if end_point == start_point {
 5613                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5614                                .saturating_sub(1);
 5615                            start_point = TP::to_point(&offset, &snapshot);
 5616                        };
 5617
 5618                        (start_point..end_point, empty_str.clone())
 5619                    })
 5620                    .sorted_by_key(|(range, _)| range.start)
 5621                    .collect::<Vec<_>>();
 5622                buffer.update(cx, |this, cx| {
 5623                    this.edit(edits, None, cx);
 5624                })
 5625            }
 5626            this.refresh_inline_completion(true, false, cx);
 5627            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5628        });
 5629    }
 5630
 5631    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5632        self.transact(cx, |this, cx| {
 5633            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5634                let line_mode = s.line_mode;
 5635                s.move_with(|map, selection| {
 5636                    if selection.is_empty() && !line_mode {
 5637                        let cursor = movement::right(map, selection.head());
 5638                        selection.end = cursor;
 5639                        selection.reversed = true;
 5640                        selection.goal = SelectionGoal::None;
 5641                    }
 5642                })
 5643            });
 5644            this.insert("", cx);
 5645            this.refresh_inline_completion(true, false, cx);
 5646        });
 5647    }
 5648
 5649    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5650        if self.move_to_prev_snippet_tabstop(cx) {
 5651            return;
 5652        }
 5653
 5654        self.outdent(&Outdent, cx);
 5655    }
 5656
 5657    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5658        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5659            return;
 5660        }
 5661
 5662        let mut selections = self.selections.all_adjusted(cx);
 5663        let buffer = self.buffer.read(cx);
 5664        let snapshot = buffer.snapshot(cx);
 5665        let rows_iter = selections.iter().map(|s| s.head().row);
 5666        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5667
 5668        let mut edits = Vec::new();
 5669        let mut prev_edited_row = 0;
 5670        let mut row_delta = 0;
 5671        for selection in &mut selections {
 5672            if selection.start.row != prev_edited_row {
 5673                row_delta = 0;
 5674            }
 5675            prev_edited_row = selection.end.row;
 5676
 5677            // If the selection is non-empty, then increase the indentation of the selected lines.
 5678            if !selection.is_empty() {
 5679                row_delta =
 5680                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5681                continue;
 5682            }
 5683
 5684            // If the selection is empty and the cursor is in the leading whitespace before the
 5685            // suggested indentation, then auto-indent the line.
 5686            let cursor = selection.head();
 5687            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5688            if let Some(suggested_indent) =
 5689                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5690            {
 5691                if cursor.column < suggested_indent.len
 5692                    && cursor.column <= current_indent.len
 5693                    && current_indent.len <= suggested_indent.len
 5694                {
 5695                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5696                    selection.end = selection.start;
 5697                    if row_delta == 0 {
 5698                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5699                            cursor.row,
 5700                            current_indent,
 5701                            suggested_indent,
 5702                        ));
 5703                        row_delta = suggested_indent.len - current_indent.len;
 5704                    }
 5705                    continue;
 5706                }
 5707            }
 5708
 5709            // Otherwise, insert a hard or soft tab.
 5710            let settings = buffer.settings_at(cursor, cx);
 5711            let tab_size = if settings.hard_tabs {
 5712                IndentSize::tab()
 5713            } else {
 5714                let tab_size = settings.tab_size.get();
 5715                let char_column = snapshot
 5716                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5717                    .flat_map(str::chars)
 5718                    .count()
 5719                    + row_delta as usize;
 5720                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5721                IndentSize::spaces(chars_to_next_tab_stop)
 5722            };
 5723            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5724            selection.end = selection.start;
 5725            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5726            row_delta += tab_size.len;
 5727        }
 5728
 5729        self.transact(cx, |this, cx| {
 5730            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5731            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5732            this.refresh_inline_completion(true, false, cx);
 5733        });
 5734    }
 5735
 5736    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5737        if self.read_only(cx) {
 5738            return;
 5739        }
 5740        let mut selections = self.selections.all::<Point>(cx);
 5741        let mut prev_edited_row = 0;
 5742        let mut row_delta = 0;
 5743        let mut edits = Vec::new();
 5744        let buffer = self.buffer.read(cx);
 5745        let snapshot = buffer.snapshot(cx);
 5746        for selection in &mut selections {
 5747            if selection.start.row != prev_edited_row {
 5748                row_delta = 0;
 5749            }
 5750            prev_edited_row = selection.end.row;
 5751
 5752            row_delta =
 5753                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5754        }
 5755
 5756        self.transact(cx, |this, cx| {
 5757            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5758            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5759        });
 5760    }
 5761
 5762    fn indent_selection(
 5763        buffer: &MultiBuffer,
 5764        snapshot: &MultiBufferSnapshot,
 5765        selection: &mut Selection<Point>,
 5766        edits: &mut Vec<(Range<Point>, String)>,
 5767        delta_for_start_row: u32,
 5768        cx: &AppContext,
 5769    ) -> u32 {
 5770        let settings = buffer.settings_at(selection.start, cx);
 5771        let tab_size = settings.tab_size.get();
 5772        let indent_kind = if settings.hard_tabs {
 5773            IndentKind::Tab
 5774        } else {
 5775            IndentKind::Space
 5776        };
 5777        let mut start_row = selection.start.row;
 5778        let mut end_row = selection.end.row + 1;
 5779
 5780        // If a selection ends at the beginning of a line, don't indent
 5781        // that last line.
 5782        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5783            end_row -= 1;
 5784        }
 5785
 5786        // Avoid re-indenting a row that has already been indented by a
 5787        // previous selection, but still update this selection's column
 5788        // to reflect that indentation.
 5789        if delta_for_start_row > 0 {
 5790            start_row += 1;
 5791            selection.start.column += delta_for_start_row;
 5792            if selection.end.row == selection.start.row {
 5793                selection.end.column += delta_for_start_row;
 5794            }
 5795        }
 5796
 5797        let mut delta_for_end_row = 0;
 5798        let has_multiple_rows = start_row + 1 != end_row;
 5799        for row in start_row..end_row {
 5800            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5801            let indent_delta = match (current_indent.kind, indent_kind) {
 5802                (IndentKind::Space, IndentKind::Space) => {
 5803                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5804                    IndentSize::spaces(columns_to_next_tab_stop)
 5805                }
 5806                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5807                (_, IndentKind::Tab) => IndentSize::tab(),
 5808            };
 5809
 5810            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5811                0
 5812            } else {
 5813                selection.start.column
 5814            };
 5815            let row_start = Point::new(row, start);
 5816            edits.push((
 5817                row_start..row_start,
 5818                indent_delta.chars().collect::<String>(),
 5819            ));
 5820
 5821            // Update this selection's endpoints to reflect the indentation.
 5822            if row == selection.start.row {
 5823                selection.start.column += indent_delta.len;
 5824            }
 5825            if row == selection.end.row {
 5826                selection.end.column += indent_delta.len;
 5827                delta_for_end_row = indent_delta.len;
 5828            }
 5829        }
 5830
 5831        if selection.start.row == selection.end.row {
 5832            delta_for_start_row + delta_for_end_row
 5833        } else {
 5834            delta_for_end_row
 5835        }
 5836    }
 5837
 5838    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5839        if self.read_only(cx) {
 5840            return;
 5841        }
 5842        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5843        let selections = self.selections.all::<Point>(cx);
 5844        let mut deletion_ranges = Vec::new();
 5845        let mut last_outdent = None;
 5846        {
 5847            let buffer = self.buffer.read(cx);
 5848            let snapshot = buffer.snapshot(cx);
 5849            for selection in &selections {
 5850                let settings = buffer.settings_at(selection.start, cx);
 5851                let tab_size = settings.tab_size.get();
 5852                let mut rows = selection.spanned_rows(false, &display_map);
 5853
 5854                // Avoid re-outdenting a row that has already been outdented by a
 5855                // previous selection.
 5856                if let Some(last_row) = last_outdent {
 5857                    if last_row == rows.start {
 5858                        rows.start = rows.start.next_row();
 5859                    }
 5860                }
 5861                let has_multiple_rows = rows.len() > 1;
 5862                for row in rows.iter_rows() {
 5863                    let indent_size = snapshot.indent_size_for_line(row);
 5864                    if indent_size.len > 0 {
 5865                        let deletion_len = match indent_size.kind {
 5866                            IndentKind::Space => {
 5867                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5868                                if columns_to_prev_tab_stop == 0 {
 5869                                    tab_size
 5870                                } else {
 5871                                    columns_to_prev_tab_stop
 5872                                }
 5873                            }
 5874                            IndentKind::Tab => 1,
 5875                        };
 5876                        let start = if has_multiple_rows
 5877                            || deletion_len > selection.start.column
 5878                            || indent_size.len < selection.start.column
 5879                        {
 5880                            0
 5881                        } else {
 5882                            selection.start.column - deletion_len
 5883                        };
 5884                        deletion_ranges.push(
 5885                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5886                        );
 5887                        last_outdent = Some(row);
 5888                    }
 5889                }
 5890            }
 5891        }
 5892
 5893        self.transact(cx, |this, cx| {
 5894            this.buffer.update(cx, |buffer, cx| {
 5895                let empty_str: Arc<str> = Arc::default();
 5896                buffer.edit(
 5897                    deletion_ranges
 5898                        .into_iter()
 5899                        .map(|range| (range, empty_str.clone())),
 5900                    None,
 5901                    cx,
 5902                );
 5903            });
 5904            let selections = this.selections.all::<usize>(cx);
 5905            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5906        });
 5907    }
 5908
 5909    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5910        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5911        let selections = self.selections.all::<Point>(cx);
 5912
 5913        let mut new_cursors = Vec::new();
 5914        let mut edit_ranges = Vec::new();
 5915        let mut selections = selections.iter().peekable();
 5916        while let Some(selection) = selections.next() {
 5917            let mut rows = selection.spanned_rows(false, &display_map);
 5918            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5919
 5920            // Accumulate contiguous regions of rows that we want to delete.
 5921            while let Some(next_selection) = selections.peek() {
 5922                let next_rows = next_selection.spanned_rows(false, &display_map);
 5923                if next_rows.start <= rows.end {
 5924                    rows.end = next_rows.end;
 5925                    selections.next().unwrap();
 5926                } else {
 5927                    break;
 5928                }
 5929            }
 5930
 5931            let buffer = &display_map.buffer_snapshot;
 5932            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5933            let edit_end;
 5934            let cursor_buffer_row;
 5935            if buffer.max_point().row >= rows.end.0 {
 5936                // If there's a line after the range, delete the \n from the end of the row range
 5937                // and position the cursor on the next line.
 5938                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5939                cursor_buffer_row = rows.end;
 5940            } else {
 5941                // If there isn't a line after the range, delete the \n from the line before the
 5942                // start of the row range and position the cursor there.
 5943                edit_start = edit_start.saturating_sub(1);
 5944                edit_end = buffer.len();
 5945                cursor_buffer_row = rows.start.previous_row();
 5946            }
 5947
 5948            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5949            *cursor.column_mut() =
 5950                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5951
 5952            new_cursors.push((
 5953                selection.id,
 5954                buffer.anchor_after(cursor.to_point(&display_map)),
 5955            ));
 5956            edit_ranges.push(edit_start..edit_end);
 5957        }
 5958
 5959        self.transact(cx, |this, cx| {
 5960            let buffer = this.buffer.update(cx, |buffer, cx| {
 5961                let empty_str: Arc<str> = Arc::default();
 5962                buffer.edit(
 5963                    edit_ranges
 5964                        .into_iter()
 5965                        .map(|range| (range, empty_str.clone())),
 5966                    None,
 5967                    cx,
 5968                );
 5969                buffer.snapshot(cx)
 5970            });
 5971            let new_selections = new_cursors
 5972                .into_iter()
 5973                .map(|(id, cursor)| {
 5974                    let cursor = cursor.to_point(&buffer);
 5975                    Selection {
 5976                        id,
 5977                        start: cursor,
 5978                        end: cursor,
 5979                        reversed: false,
 5980                        goal: SelectionGoal::None,
 5981                    }
 5982                })
 5983                .collect();
 5984
 5985            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5986                s.select(new_selections);
 5987            });
 5988        });
 5989    }
 5990
 5991    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5992        if self.read_only(cx) {
 5993            return;
 5994        }
 5995        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5996        for selection in self.selections.all::<Point>(cx) {
 5997            let start = MultiBufferRow(selection.start.row);
 5998            let end = if selection.start.row == selection.end.row {
 5999                MultiBufferRow(selection.start.row + 1)
 6000            } else {
 6001                MultiBufferRow(selection.end.row)
 6002            };
 6003
 6004            if let Some(last_row_range) = row_ranges.last_mut() {
 6005                if start <= last_row_range.end {
 6006                    last_row_range.end = end;
 6007                    continue;
 6008                }
 6009            }
 6010            row_ranges.push(start..end);
 6011        }
 6012
 6013        let snapshot = self.buffer.read(cx).snapshot(cx);
 6014        let mut cursor_positions = Vec::new();
 6015        for row_range in &row_ranges {
 6016            let anchor = snapshot.anchor_before(Point::new(
 6017                row_range.end.previous_row().0,
 6018                snapshot.line_len(row_range.end.previous_row()),
 6019            ));
 6020            cursor_positions.push(anchor..anchor);
 6021        }
 6022
 6023        self.transact(cx, |this, cx| {
 6024            for row_range in row_ranges.into_iter().rev() {
 6025                for row in row_range.iter_rows().rev() {
 6026                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6027                    let next_line_row = row.next_row();
 6028                    let indent = snapshot.indent_size_for_line(next_line_row);
 6029                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6030
 6031                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 6032                        " "
 6033                    } else {
 6034                        ""
 6035                    };
 6036
 6037                    this.buffer.update(cx, |buffer, cx| {
 6038                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6039                    });
 6040                }
 6041            }
 6042
 6043            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6044                s.select_anchor_ranges(cursor_positions)
 6045            });
 6046        });
 6047    }
 6048
 6049    pub fn sort_lines_case_sensitive(
 6050        &mut self,
 6051        _: &SortLinesCaseSensitive,
 6052        cx: &mut ViewContext<Self>,
 6053    ) {
 6054        self.manipulate_lines(cx, |lines| lines.sort())
 6055    }
 6056
 6057    pub fn sort_lines_case_insensitive(
 6058        &mut self,
 6059        _: &SortLinesCaseInsensitive,
 6060        cx: &mut ViewContext<Self>,
 6061    ) {
 6062        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 6063    }
 6064
 6065    pub fn unique_lines_case_insensitive(
 6066        &mut self,
 6067        _: &UniqueLinesCaseInsensitive,
 6068        cx: &mut ViewContext<Self>,
 6069    ) {
 6070        self.manipulate_lines(cx, |lines| {
 6071            let mut seen = HashSet::default();
 6072            lines.retain(|line| seen.insert(line.to_lowercase()));
 6073        })
 6074    }
 6075
 6076    pub fn unique_lines_case_sensitive(
 6077        &mut self,
 6078        _: &UniqueLinesCaseSensitive,
 6079        cx: &mut ViewContext<Self>,
 6080    ) {
 6081        self.manipulate_lines(cx, |lines| {
 6082            let mut seen = HashSet::default();
 6083            lines.retain(|line| seen.insert(*line));
 6084        })
 6085    }
 6086
 6087    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 6088        let mut revert_changes = HashMap::default();
 6089        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6090        for hunk in hunks_for_rows(
 6091            Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
 6092            &multi_buffer_snapshot,
 6093        ) {
 6094            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6095        }
 6096        if !revert_changes.is_empty() {
 6097            self.transact(cx, |editor, cx| {
 6098                editor.revert(revert_changes, cx);
 6099            });
 6100        }
 6101    }
 6102
 6103    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 6104        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 6105        if !revert_changes.is_empty() {
 6106            self.transact(cx, |editor, cx| {
 6107                editor.revert(revert_changes, cx);
 6108            });
 6109        }
 6110    }
 6111
 6112    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 6113        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6114            let project_path = buffer.read(cx).project_path(cx)?;
 6115            let project = self.project.as_ref()?.read(cx);
 6116            let entry = project.entry_for_path(&project_path, cx)?;
 6117            let abs_path = project.absolute_path(&project_path, cx)?;
 6118            let parent = if entry.is_symlink {
 6119                abs_path.canonicalize().ok()?
 6120            } else {
 6121                abs_path
 6122            }
 6123            .parent()?
 6124            .to_path_buf();
 6125            Some(parent)
 6126        }) {
 6127            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 6128        }
 6129    }
 6130
 6131    fn gather_revert_changes(
 6132        &mut self,
 6133        selections: &[Selection<Anchor>],
 6134        cx: &mut ViewContext<'_, Editor>,
 6135    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 6136        let mut revert_changes = HashMap::default();
 6137        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 6138        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 6139            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 6140        }
 6141        revert_changes
 6142    }
 6143
 6144    pub fn prepare_revert_change(
 6145        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6146        multi_buffer: &Model<MultiBuffer>,
 6147        hunk: &DiffHunk<MultiBufferRow>,
 6148        cx: &AppContext,
 6149    ) -> Option<()> {
 6150        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 6151        let buffer = buffer.read(cx);
 6152        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 6153        let buffer_snapshot = buffer.snapshot();
 6154        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6155        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6156            probe
 6157                .0
 6158                .start
 6159                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6160                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6161        }) {
 6162            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6163            Some(())
 6164        } else {
 6165            None
 6166        }
 6167    }
 6168
 6169    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6170        self.manipulate_lines(cx, |lines| lines.reverse())
 6171    }
 6172
 6173    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6174        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6175    }
 6176
 6177    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6178    where
 6179        Fn: FnMut(&mut Vec<&str>),
 6180    {
 6181        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6182        let buffer = self.buffer.read(cx).snapshot(cx);
 6183
 6184        let mut edits = Vec::new();
 6185
 6186        let selections = self.selections.all::<Point>(cx);
 6187        let mut selections = selections.iter().peekable();
 6188        let mut contiguous_row_selections = Vec::new();
 6189        let mut new_selections = Vec::new();
 6190        let mut added_lines = 0;
 6191        let mut removed_lines = 0;
 6192
 6193        while let Some(selection) = selections.next() {
 6194            let (start_row, end_row) = consume_contiguous_rows(
 6195                &mut contiguous_row_selections,
 6196                selection,
 6197                &display_map,
 6198                &mut selections,
 6199            );
 6200
 6201            let start_point = Point::new(start_row.0, 0);
 6202            let end_point = Point::new(
 6203                end_row.previous_row().0,
 6204                buffer.line_len(end_row.previous_row()),
 6205            );
 6206            let text = buffer
 6207                .text_for_range(start_point..end_point)
 6208                .collect::<String>();
 6209
 6210            let mut lines = text.split('\n').collect_vec();
 6211
 6212            let lines_before = lines.len();
 6213            callback(&mut lines);
 6214            let lines_after = lines.len();
 6215
 6216            edits.push((start_point..end_point, lines.join("\n")));
 6217
 6218            // Selections must change based on added and removed line count
 6219            let start_row =
 6220                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6221            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6222            new_selections.push(Selection {
 6223                id: selection.id,
 6224                start: start_row,
 6225                end: end_row,
 6226                goal: SelectionGoal::None,
 6227                reversed: selection.reversed,
 6228            });
 6229
 6230            if lines_after > lines_before {
 6231                added_lines += lines_after - lines_before;
 6232            } else if lines_before > lines_after {
 6233                removed_lines += lines_before - lines_after;
 6234            }
 6235        }
 6236
 6237        self.transact(cx, |this, cx| {
 6238            let buffer = this.buffer.update(cx, |buffer, cx| {
 6239                buffer.edit(edits, None, cx);
 6240                buffer.snapshot(cx)
 6241            });
 6242
 6243            // Recalculate offsets on newly edited buffer
 6244            let new_selections = new_selections
 6245                .iter()
 6246                .map(|s| {
 6247                    let start_point = Point::new(s.start.0, 0);
 6248                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6249                    Selection {
 6250                        id: s.id,
 6251                        start: buffer.point_to_offset(start_point),
 6252                        end: buffer.point_to_offset(end_point),
 6253                        goal: s.goal,
 6254                        reversed: s.reversed,
 6255                    }
 6256                })
 6257                .collect();
 6258
 6259            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6260                s.select(new_selections);
 6261            });
 6262
 6263            this.request_autoscroll(Autoscroll::fit(), cx);
 6264        });
 6265    }
 6266
 6267    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6268        self.manipulate_text(cx, |text| text.to_uppercase())
 6269    }
 6270
 6271    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6272        self.manipulate_text(cx, |text| text.to_lowercase())
 6273    }
 6274
 6275    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6276        self.manipulate_text(cx, |text| {
 6277            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6278            // https://github.com/rutrum/convert-case/issues/16
 6279            text.split('\n')
 6280                .map(|line| line.to_case(Case::Title))
 6281                .join("\n")
 6282        })
 6283    }
 6284
 6285    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6286        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6287    }
 6288
 6289    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6290        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6291    }
 6292
 6293    pub fn convert_to_upper_camel_case(
 6294        &mut self,
 6295        _: &ConvertToUpperCamelCase,
 6296        cx: &mut ViewContext<Self>,
 6297    ) {
 6298        self.manipulate_text(cx, |text| {
 6299            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6300            // https://github.com/rutrum/convert-case/issues/16
 6301            text.split('\n')
 6302                .map(|line| line.to_case(Case::UpperCamel))
 6303                .join("\n")
 6304        })
 6305    }
 6306
 6307    pub fn convert_to_lower_camel_case(
 6308        &mut self,
 6309        _: &ConvertToLowerCamelCase,
 6310        cx: &mut ViewContext<Self>,
 6311    ) {
 6312        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6313    }
 6314
 6315    pub fn convert_to_opposite_case(
 6316        &mut self,
 6317        _: &ConvertToOppositeCase,
 6318        cx: &mut ViewContext<Self>,
 6319    ) {
 6320        self.manipulate_text(cx, |text| {
 6321            text.chars()
 6322                .fold(String::with_capacity(text.len()), |mut t, c| {
 6323                    if c.is_uppercase() {
 6324                        t.extend(c.to_lowercase());
 6325                    } else {
 6326                        t.extend(c.to_uppercase());
 6327                    }
 6328                    t
 6329                })
 6330        })
 6331    }
 6332
 6333    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6334    where
 6335        Fn: FnMut(&str) -> String,
 6336    {
 6337        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6338        let buffer = self.buffer.read(cx).snapshot(cx);
 6339
 6340        let mut new_selections = Vec::new();
 6341        let mut edits = Vec::new();
 6342        let mut selection_adjustment = 0i32;
 6343
 6344        for selection in self.selections.all::<usize>(cx) {
 6345            let selection_is_empty = selection.is_empty();
 6346
 6347            let (start, end) = if selection_is_empty {
 6348                let word_range = movement::surrounding_word(
 6349                    &display_map,
 6350                    selection.start.to_display_point(&display_map),
 6351                );
 6352                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6353                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6354                (start, end)
 6355            } else {
 6356                (selection.start, selection.end)
 6357            };
 6358
 6359            let text = buffer.text_for_range(start..end).collect::<String>();
 6360            let old_length = text.len() as i32;
 6361            let text = callback(&text);
 6362
 6363            new_selections.push(Selection {
 6364                start: (start as i32 - selection_adjustment) as usize,
 6365                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6366                goal: SelectionGoal::None,
 6367                ..selection
 6368            });
 6369
 6370            selection_adjustment += old_length - text.len() as i32;
 6371
 6372            edits.push((start..end, text));
 6373        }
 6374
 6375        self.transact(cx, |this, cx| {
 6376            this.buffer.update(cx, |buffer, cx| {
 6377                buffer.edit(edits, None, cx);
 6378            });
 6379
 6380            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6381                s.select(new_selections);
 6382            });
 6383
 6384            this.request_autoscroll(Autoscroll::fit(), cx);
 6385        });
 6386    }
 6387
 6388    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6389        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6390        let buffer = &display_map.buffer_snapshot;
 6391        let selections = self.selections.all::<Point>(cx);
 6392
 6393        let mut edits = Vec::new();
 6394        let mut selections_iter = selections.iter().peekable();
 6395        while let Some(selection) = selections_iter.next() {
 6396            // Avoid duplicating the same lines twice.
 6397            let mut rows = selection.spanned_rows(false, &display_map);
 6398
 6399            while let Some(next_selection) = selections_iter.peek() {
 6400                let next_rows = next_selection.spanned_rows(false, &display_map);
 6401                if next_rows.start < rows.end {
 6402                    rows.end = next_rows.end;
 6403                    selections_iter.next().unwrap();
 6404                } else {
 6405                    break;
 6406                }
 6407            }
 6408
 6409            // Copy the text from the selected row region and splice it either at the start
 6410            // or end of the region.
 6411            let start = Point::new(rows.start.0, 0);
 6412            let end = Point::new(
 6413                rows.end.previous_row().0,
 6414                buffer.line_len(rows.end.previous_row()),
 6415            );
 6416            let text = buffer
 6417                .text_for_range(start..end)
 6418                .chain(Some("\n"))
 6419                .collect::<String>();
 6420            let insert_location = if upwards {
 6421                Point::new(rows.end.0, 0)
 6422            } else {
 6423                start
 6424            };
 6425            edits.push((insert_location..insert_location, text));
 6426        }
 6427
 6428        self.transact(cx, |this, cx| {
 6429            this.buffer.update(cx, |buffer, cx| {
 6430                buffer.edit(edits, None, cx);
 6431            });
 6432
 6433            this.request_autoscroll(Autoscroll::fit(), cx);
 6434        });
 6435    }
 6436
 6437    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6438        self.duplicate_line(true, cx);
 6439    }
 6440
 6441    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6442        self.duplicate_line(false, cx);
 6443    }
 6444
 6445    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6446        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6447        let buffer = self.buffer.read(cx).snapshot(cx);
 6448
 6449        let mut edits = Vec::new();
 6450        let mut unfold_ranges = Vec::new();
 6451        let mut refold_ranges = Vec::new();
 6452
 6453        let selections = self.selections.all::<Point>(cx);
 6454        let mut selections = selections.iter().peekable();
 6455        let mut contiguous_row_selections = Vec::new();
 6456        let mut new_selections = Vec::new();
 6457
 6458        while let Some(selection) = selections.next() {
 6459            // Find all the selections that span a contiguous row range
 6460            let (start_row, end_row) = consume_contiguous_rows(
 6461                &mut contiguous_row_selections,
 6462                selection,
 6463                &display_map,
 6464                &mut selections,
 6465            );
 6466
 6467            // Move the text spanned by the row range to be before the line preceding the row range
 6468            if start_row.0 > 0 {
 6469                let range_to_move = Point::new(
 6470                    start_row.previous_row().0,
 6471                    buffer.line_len(start_row.previous_row()),
 6472                )
 6473                    ..Point::new(
 6474                        end_row.previous_row().0,
 6475                        buffer.line_len(end_row.previous_row()),
 6476                    );
 6477                let insertion_point = display_map
 6478                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6479                    .0;
 6480
 6481                // Don't move lines across excerpts
 6482                if buffer
 6483                    .excerpt_boundaries_in_range((
 6484                        Bound::Excluded(insertion_point),
 6485                        Bound::Included(range_to_move.end),
 6486                    ))
 6487                    .next()
 6488                    .is_none()
 6489                {
 6490                    let text = buffer
 6491                        .text_for_range(range_to_move.clone())
 6492                        .flat_map(|s| s.chars())
 6493                        .skip(1)
 6494                        .chain(['\n'])
 6495                        .collect::<String>();
 6496
 6497                    edits.push((
 6498                        buffer.anchor_after(range_to_move.start)
 6499                            ..buffer.anchor_before(range_to_move.end),
 6500                        String::new(),
 6501                    ));
 6502                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6503                    edits.push((insertion_anchor..insertion_anchor, text));
 6504
 6505                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6506
 6507                    // Move selections up
 6508                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6509                        |mut selection| {
 6510                            selection.start.row -= row_delta;
 6511                            selection.end.row -= row_delta;
 6512                            selection
 6513                        },
 6514                    ));
 6515
 6516                    // Move folds up
 6517                    unfold_ranges.push(range_to_move.clone());
 6518                    for fold in display_map.folds_in_range(
 6519                        buffer.anchor_before(range_to_move.start)
 6520                            ..buffer.anchor_after(range_to_move.end),
 6521                    ) {
 6522                        let mut start = fold.range.start.to_point(&buffer);
 6523                        let mut end = fold.range.end.to_point(&buffer);
 6524                        start.row -= row_delta;
 6525                        end.row -= row_delta;
 6526                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6527                    }
 6528                }
 6529            }
 6530
 6531            // If we didn't move line(s), preserve the existing selections
 6532            new_selections.append(&mut contiguous_row_selections);
 6533        }
 6534
 6535        self.transact(cx, |this, cx| {
 6536            this.unfold_ranges(unfold_ranges, true, true, cx);
 6537            this.buffer.update(cx, |buffer, cx| {
 6538                for (range, text) in edits {
 6539                    buffer.edit([(range, text)], None, cx);
 6540                }
 6541            });
 6542            this.fold_ranges(refold_ranges, true, cx);
 6543            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6544                s.select(new_selections);
 6545            })
 6546        });
 6547    }
 6548
 6549    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6550        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6551        let buffer = self.buffer.read(cx).snapshot(cx);
 6552
 6553        let mut edits = Vec::new();
 6554        let mut unfold_ranges = Vec::new();
 6555        let mut refold_ranges = Vec::new();
 6556
 6557        let selections = self.selections.all::<Point>(cx);
 6558        let mut selections = selections.iter().peekable();
 6559        let mut contiguous_row_selections = Vec::new();
 6560        let mut new_selections = Vec::new();
 6561
 6562        while let Some(selection) = selections.next() {
 6563            // Find all the selections that span a contiguous row range
 6564            let (start_row, end_row) = consume_contiguous_rows(
 6565                &mut contiguous_row_selections,
 6566                selection,
 6567                &display_map,
 6568                &mut selections,
 6569            );
 6570
 6571            // Move the text spanned by the row range to be after the last line of the row range
 6572            if end_row.0 <= buffer.max_point().row {
 6573                let range_to_move =
 6574                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6575                let insertion_point = display_map
 6576                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6577                    .0;
 6578
 6579                // Don't move lines across excerpt boundaries
 6580                if buffer
 6581                    .excerpt_boundaries_in_range((
 6582                        Bound::Excluded(range_to_move.start),
 6583                        Bound::Included(insertion_point),
 6584                    ))
 6585                    .next()
 6586                    .is_none()
 6587                {
 6588                    let mut text = String::from("\n");
 6589                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6590                    text.pop(); // Drop trailing newline
 6591                    edits.push((
 6592                        buffer.anchor_after(range_to_move.start)
 6593                            ..buffer.anchor_before(range_to_move.end),
 6594                        String::new(),
 6595                    ));
 6596                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6597                    edits.push((insertion_anchor..insertion_anchor, text));
 6598
 6599                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6600
 6601                    // Move selections down
 6602                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6603                        |mut selection| {
 6604                            selection.start.row += row_delta;
 6605                            selection.end.row += row_delta;
 6606                            selection
 6607                        },
 6608                    ));
 6609
 6610                    // Move folds down
 6611                    unfold_ranges.push(range_to_move.clone());
 6612                    for fold in display_map.folds_in_range(
 6613                        buffer.anchor_before(range_to_move.start)
 6614                            ..buffer.anchor_after(range_to_move.end),
 6615                    ) {
 6616                        let mut start = fold.range.start.to_point(&buffer);
 6617                        let mut end = fold.range.end.to_point(&buffer);
 6618                        start.row += row_delta;
 6619                        end.row += row_delta;
 6620                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6621                    }
 6622                }
 6623            }
 6624
 6625            // If we didn't move line(s), preserve the existing selections
 6626            new_selections.append(&mut contiguous_row_selections);
 6627        }
 6628
 6629        self.transact(cx, |this, cx| {
 6630            this.unfold_ranges(unfold_ranges, true, true, cx);
 6631            this.buffer.update(cx, |buffer, cx| {
 6632                for (range, text) in edits {
 6633                    buffer.edit([(range, text)], None, cx);
 6634                }
 6635            });
 6636            this.fold_ranges(refold_ranges, true, cx);
 6637            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6638        });
 6639    }
 6640
 6641    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6642        let text_layout_details = &self.text_layout_details(cx);
 6643        self.transact(cx, |this, cx| {
 6644            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6645                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6646                let line_mode = s.line_mode;
 6647                s.move_with(|display_map, selection| {
 6648                    if !selection.is_empty() || line_mode {
 6649                        return;
 6650                    }
 6651
 6652                    let mut head = selection.head();
 6653                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6654                    if head.column() == display_map.line_len(head.row()) {
 6655                        transpose_offset = display_map
 6656                            .buffer_snapshot
 6657                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6658                    }
 6659
 6660                    if transpose_offset == 0 {
 6661                        return;
 6662                    }
 6663
 6664                    *head.column_mut() += 1;
 6665                    head = display_map.clip_point(head, Bias::Right);
 6666                    let goal = SelectionGoal::HorizontalPosition(
 6667                        display_map
 6668                            .x_for_display_point(head, text_layout_details)
 6669                            .into(),
 6670                    );
 6671                    selection.collapse_to(head, goal);
 6672
 6673                    let transpose_start = display_map
 6674                        .buffer_snapshot
 6675                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6676                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6677                        let transpose_end = display_map
 6678                            .buffer_snapshot
 6679                            .clip_offset(transpose_offset + 1, Bias::Right);
 6680                        if let Some(ch) =
 6681                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6682                        {
 6683                            edits.push((transpose_start..transpose_offset, String::new()));
 6684                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6685                        }
 6686                    }
 6687                });
 6688                edits
 6689            });
 6690            this.buffer
 6691                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6692            let selections = this.selections.all::<usize>(cx);
 6693            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6694                s.select(selections);
 6695            });
 6696        });
 6697    }
 6698
 6699    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6700        let buffer = self.buffer.read(cx).snapshot(cx);
 6701        let selections = self.selections.all::<Point>(cx);
 6702        let mut selections = selections.iter().peekable();
 6703
 6704        let mut edits = Vec::new();
 6705        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6706
 6707        while let Some(selection) = selections.next() {
 6708            let mut start_row = selection.start.row;
 6709            let mut end_row = selection.end.row;
 6710
 6711            // Skip selections that overlap with a range that has already been rewrapped.
 6712            let selection_range = start_row..end_row;
 6713            if rewrapped_row_ranges
 6714                .iter()
 6715                .any(|range| range.overlaps(&selection_range))
 6716            {
 6717                continue;
 6718            }
 6719
 6720            let mut should_rewrap = false;
 6721
 6722            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6723                match language_scope.language_name().0.as_ref() {
 6724                    "Markdown" | "Plain Text" => {
 6725                        should_rewrap = true;
 6726                    }
 6727                    _ => {}
 6728                }
 6729            }
 6730
 6731            let row = selection.head().row;
 6732            let indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
 6733            let indent_end = Point::new(row, indent_size.len);
 6734
 6735            let mut line_prefix = indent_size.chars().collect::<String>();
 6736
 6737            if selection.is_empty() {
 6738                if let Some(comment_prefix) =
 6739                    buffer
 6740                        .language_scope_at(selection.head())
 6741                        .and_then(|language| {
 6742                            language
 6743                                .line_comment_prefixes()
 6744                                .iter()
 6745                                .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6746                                .cloned()
 6747                        })
 6748                {
 6749                    line_prefix.push_str(&comment_prefix);
 6750                    should_rewrap = true;
 6751                }
 6752
 6753                'expand_upwards: while start_row > 0 {
 6754                    let prev_row = start_row - 1;
 6755                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6756                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6757                    {
 6758                        start_row = prev_row;
 6759                    } else {
 6760                        break 'expand_upwards;
 6761                    }
 6762                }
 6763
 6764                'expand_downwards: while end_row < buffer.max_point().row {
 6765                    let next_row = end_row + 1;
 6766                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6767                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6768                    {
 6769                        end_row = next_row;
 6770                    } else {
 6771                        break 'expand_downwards;
 6772                    }
 6773                }
 6774            }
 6775
 6776            if !should_rewrap {
 6777                continue;
 6778            }
 6779
 6780            let start = Point::new(start_row, 0);
 6781            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6782            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6783            let unwrapped_text = selection_text
 6784                .lines()
 6785                .map(|line| line.strip_prefix(&line_prefix).unwrap())
 6786                .join(" ");
 6787            let wrap_column = buffer
 6788                .settings_at(Point::new(start_row, 0), cx)
 6789                .preferred_line_length as usize;
 6790            let mut wrapped_text = String::new();
 6791            let mut current_line = line_prefix.clone();
 6792            for word in unwrapped_text.split_whitespace() {
 6793                if current_line.len() + word.len() >= wrap_column {
 6794                    wrapped_text.push_str(&current_line);
 6795                    wrapped_text.push('\n');
 6796                    current_line.truncate(line_prefix.len());
 6797                }
 6798
 6799                if current_line.len() > line_prefix.len() {
 6800                    current_line.push(' ');
 6801                }
 6802
 6803                current_line.push_str(word);
 6804            }
 6805
 6806            if !current_line.is_empty() {
 6807                wrapped_text.push_str(&current_line);
 6808            }
 6809
 6810            let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
 6811            let mut offset = start.to_offset(&buffer);
 6812            let mut moved_since_edit = true;
 6813
 6814            for change in diff.iter_all_changes() {
 6815                let value = change.value();
 6816                match change.tag() {
 6817                    ChangeTag::Equal => {
 6818                        offset += value.len();
 6819                        moved_since_edit = true;
 6820                    }
 6821                    ChangeTag::Delete => {
 6822                        let start = buffer.anchor_after(offset);
 6823                        let end = buffer.anchor_before(offset + value.len());
 6824
 6825                        if moved_since_edit {
 6826                            edits.push((start..end, String::new()));
 6827                        } else {
 6828                            edits.last_mut().unwrap().0.end = end;
 6829                        }
 6830
 6831                        offset += value.len();
 6832                        moved_since_edit = false;
 6833                    }
 6834                    ChangeTag::Insert => {
 6835                        if moved_since_edit {
 6836                            let anchor = buffer.anchor_after(offset);
 6837                            edits.push((anchor..anchor, value.to_string()));
 6838                        } else {
 6839                            edits.last_mut().unwrap().1.push_str(value);
 6840                        }
 6841
 6842                        moved_since_edit = false;
 6843                    }
 6844                }
 6845            }
 6846
 6847            rewrapped_row_ranges.push(start_row..=end_row);
 6848        }
 6849
 6850        self.buffer
 6851            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6852    }
 6853
 6854    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6855        let mut text = String::new();
 6856        let buffer = self.buffer.read(cx).snapshot(cx);
 6857        let mut selections = self.selections.all::<Point>(cx);
 6858        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6859        {
 6860            let max_point = buffer.max_point();
 6861            let mut is_first = true;
 6862            for selection in &mut selections {
 6863                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6864                if is_entire_line {
 6865                    selection.start = Point::new(selection.start.row, 0);
 6866                    if !selection.is_empty() && selection.end.column == 0 {
 6867                        selection.end = cmp::min(max_point, selection.end);
 6868                    } else {
 6869                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6870                    }
 6871                    selection.goal = SelectionGoal::None;
 6872                }
 6873                if is_first {
 6874                    is_first = false;
 6875                } else {
 6876                    text += "\n";
 6877                }
 6878                let mut len = 0;
 6879                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6880                    text.push_str(chunk);
 6881                    len += chunk.len();
 6882                }
 6883                clipboard_selections.push(ClipboardSelection {
 6884                    len,
 6885                    is_entire_line,
 6886                    first_line_indent: buffer
 6887                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6888                        .len,
 6889                });
 6890            }
 6891        }
 6892
 6893        self.transact(cx, |this, cx| {
 6894            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6895                s.select(selections);
 6896            });
 6897            this.insert("", cx);
 6898            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6899                text,
 6900                clipboard_selections,
 6901            ));
 6902        });
 6903    }
 6904
 6905    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6906        let selections = self.selections.all::<Point>(cx);
 6907        let buffer = self.buffer.read(cx).read(cx);
 6908        let mut text = String::new();
 6909
 6910        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6911        {
 6912            let max_point = buffer.max_point();
 6913            let mut is_first = true;
 6914            for selection in selections.iter() {
 6915                let mut start = selection.start;
 6916                let mut end = selection.end;
 6917                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6918                if is_entire_line {
 6919                    start = Point::new(start.row, 0);
 6920                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6921                }
 6922                if is_first {
 6923                    is_first = false;
 6924                } else {
 6925                    text += "\n";
 6926                }
 6927                let mut len = 0;
 6928                for chunk in buffer.text_for_range(start..end) {
 6929                    text.push_str(chunk);
 6930                    len += chunk.len();
 6931                }
 6932                clipboard_selections.push(ClipboardSelection {
 6933                    len,
 6934                    is_entire_line,
 6935                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6936                });
 6937            }
 6938        }
 6939
 6940        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6941            text,
 6942            clipboard_selections,
 6943        ));
 6944    }
 6945
 6946    pub fn do_paste(
 6947        &mut self,
 6948        text: &String,
 6949        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6950        handle_entire_lines: bool,
 6951        cx: &mut ViewContext<Self>,
 6952    ) {
 6953        if self.read_only(cx) {
 6954            return;
 6955        }
 6956
 6957        let clipboard_text = Cow::Borrowed(text);
 6958
 6959        self.transact(cx, |this, cx| {
 6960            if let Some(mut clipboard_selections) = clipboard_selections {
 6961                let old_selections = this.selections.all::<usize>(cx);
 6962                let all_selections_were_entire_line =
 6963                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6964                let first_selection_indent_column =
 6965                    clipboard_selections.first().map(|s| s.first_line_indent);
 6966                if clipboard_selections.len() != old_selections.len() {
 6967                    clipboard_selections.drain(..);
 6968                }
 6969
 6970                this.buffer.update(cx, |buffer, cx| {
 6971                    let snapshot = buffer.read(cx);
 6972                    let mut start_offset = 0;
 6973                    let mut edits = Vec::new();
 6974                    let mut original_indent_columns = Vec::new();
 6975                    for (ix, selection) in old_selections.iter().enumerate() {
 6976                        let to_insert;
 6977                        let entire_line;
 6978                        let original_indent_column;
 6979                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6980                            let end_offset = start_offset + clipboard_selection.len;
 6981                            to_insert = &clipboard_text[start_offset..end_offset];
 6982                            entire_line = clipboard_selection.is_entire_line;
 6983                            start_offset = end_offset + 1;
 6984                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6985                        } else {
 6986                            to_insert = clipboard_text.as_str();
 6987                            entire_line = all_selections_were_entire_line;
 6988                            original_indent_column = first_selection_indent_column
 6989                        }
 6990
 6991                        // If the corresponding selection was empty when this slice of the
 6992                        // clipboard text was written, then the entire line containing the
 6993                        // selection was copied. If this selection is also currently empty,
 6994                        // then paste the line before the current line of the buffer.
 6995                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6996                            let column = selection.start.to_point(&snapshot).column as usize;
 6997                            let line_start = selection.start - column;
 6998                            line_start..line_start
 6999                        } else {
 7000                            selection.range()
 7001                        };
 7002
 7003                        edits.push((range, to_insert));
 7004                        original_indent_columns.extend(original_indent_column);
 7005                    }
 7006                    drop(snapshot);
 7007
 7008                    buffer.edit(
 7009                        edits,
 7010                        Some(AutoindentMode::Block {
 7011                            original_indent_columns,
 7012                        }),
 7013                        cx,
 7014                    );
 7015                });
 7016
 7017                let selections = this.selections.all::<usize>(cx);
 7018                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 7019            } else {
 7020                this.insert(&clipboard_text, cx);
 7021            }
 7022        });
 7023    }
 7024
 7025    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 7026        if let Some(item) = cx.read_from_clipboard() {
 7027            let entries = item.entries();
 7028
 7029            match entries.first() {
 7030                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7031                // of all the pasted entries.
 7032                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7033                    .do_paste(
 7034                        clipboard_string.text(),
 7035                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7036                        true,
 7037                        cx,
 7038                    ),
 7039                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 7040            }
 7041        }
 7042    }
 7043
 7044    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 7045        if self.read_only(cx) {
 7046            return;
 7047        }
 7048
 7049        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7050            if let Some((selections, _)) =
 7051                self.selection_history.transaction(transaction_id).cloned()
 7052            {
 7053                self.change_selections(None, cx, |s| {
 7054                    s.select_anchors(selections.to_vec());
 7055                });
 7056            }
 7057            self.request_autoscroll(Autoscroll::fit(), cx);
 7058            self.unmark_text(cx);
 7059            self.refresh_inline_completion(true, false, cx);
 7060            cx.emit(EditorEvent::Edited { transaction_id });
 7061            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7062        }
 7063    }
 7064
 7065    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7066        if self.read_only(cx) {
 7067            return;
 7068        }
 7069
 7070        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7071            if let Some((_, Some(selections))) =
 7072                self.selection_history.transaction(transaction_id).cloned()
 7073            {
 7074                self.change_selections(None, cx, |s| {
 7075                    s.select_anchors(selections.to_vec());
 7076                });
 7077            }
 7078            self.request_autoscroll(Autoscroll::fit(), cx);
 7079            self.unmark_text(cx);
 7080            self.refresh_inline_completion(true, false, cx);
 7081            cx.emit(EditorEvent::Edited { transaction_id });
 7082        }
 7083    }
 7084
 7085    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7086        self.buffer
 7087            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7088    }
 7089
 7090    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7091        self.buffer
 7092            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7093    }
 7094
 7095    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7096        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7097            let line_mode = s.line_mode;
 7098            s.move_with(|map, selection| {
 7099                let cursor = if selection.is_empty() && !line_mode {
 7100                    movement::left(map, selection.start)
 7101                } else {
 7102                    selection.start
 7103                };
 7104                selection.collapse_to(cursor, SelectionGoal::None);
 7105            });
 7106        })
 7107    }
 7108
 7109    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7110        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7111            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7112        })
 7113    }
 7114
 7115    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7116        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7117            let line_mode = s.line_mode;
 7118            s.move_with(|map, selection| {
 7119                let cursor = if selection.is_empty() && !line_mode {
 7120                    movement::right(map, selection.end)
 7121                } else {
 7122                    selection.end
 7123                };
 7124                selection.collapse_to(cursor, SelectionGoal::None)
 7125            });
 7126        })
 7127    }
 7128
 7129    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7130        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7131            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7132        })
 7133    }
 7134
 7135    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7136        if self.take_rename(true, cx).is_some() {
 7137            return;
 7138        }
 7139
 7140        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7141            cx.propagate();
 7142            return;
 7143        }
 7144
 7145        let text_layout_details = &self.text_layout_details(cx);
 7146        let selection_count = self.selections.count();
 7147        let first_selection = self.selections.first_anchor();
 7148
 7149        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7150            let line_mode = s.line_mode;
 7151            s.move_with(|map, selection| {
 7152                if !selection.is_empty() && !line_mode {
 7153                    selection.goal = SelectionGoal::None;
 7154                }
 7155                let (cursor, goal) = movement::up(
 7156                    map,
 7157                    selection.start,
 7158                    selection.goal,
 7159                    false,
 7160                    text_layout_details,
 7161                );
 7162                selection.collapse_to(cursor, goal);
 7163            });
 7164        });
 7165
 7166        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7167        {
 7168            cx.propagate();
 7169        }
 7170    }
 7171
 7172    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7173        if self.take_rename(true, cx).is_some() {
 7174            return;
 7175        }
 7176
 7177        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7178            cx.propagate();
 7179            return;
 7180        }
 7181
 7182        let text_layout_details = &self.text_layout_details(cx);
 7183
 7184        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7185            let line_mode = s.line_mode;
 7186            s.move_with(|map, selection| {
 7187                if !selection.is_empty() && !line_mode {
 7188                    selection.goal = SelectionGoal::None;
 7189                }
 7190                let (cursor, goal) = movement::up_by_rows(
 7191                    map,
 7192                    selection.start,
 7193                    action.lines,
 7194                    selection.goal,
 7195                    false,
 7196                    text_layout_details,
 7197                );
 7198                selection.collapse_to(cursor, goal);
 7199            });
 7200        })
 7201    }
 7202
 7203    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7204        if self.take_rename(true, cx).is_some() {
 7205            return;
 7206        }
 7207
 7208        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7209            cx.propagate();
 7210            return;
 7211        }
 7212
 7213        let text_layout_details = &self.text_layout_details(cx);
 7214
 7215        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7216            let line_mode = s.line_mode;
 7217            s.move_with(|map, selection| {
 7218                if !selection.is_empty() && !line_mode {
 7219                    selection.goal = SelectionGoal::None;
 7220                }
 7221                let (cursor, goal) = movement::down_by_rows(
 7222                    map,
 7223                    selection.start,
 7224                    action.lines,
 7225                    selection.goal,
 7226                    false,
 7227                    text_layout_details,
 7228                );
 7229                selection.collapse_to(cursor, goal);
 7230            });
 7231        })
 7232    }
 7233
 7234    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7235        let text_layout_details = &self.text_layout_details(cx);
 7236        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7237            s.move_heads_with(|map, head, goal| {
 7238                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7239            })
 7240        })
 7241    }
 7242
 7243    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7244        let text_layout_details = &self.text_layout_details(cx);
 7245        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7246            s.move_heads_with(|map, head, goal| {
 7247                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7248            })
 7249        })
 7250    }
 7251
 7252    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7253        let Some(row_count) = self.visible_row_count() else {
 7254            return;
 7255        };
 7256
 7257        let text_layout_details = &self.text_layout_details(cx);
 7258
 7259        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7260            s.move_heads_with(|map, head, goal| {
 7261                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7262            })
 7263        })
 7264    }
 7265
 7266    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7267        if self.take_rename(true, cx).is_some() {
 7268            return;
 7269        }
 7270
 7271        if self
 7272            .context_menu
 7273            .write()
 7274            .as_mut()
 7275            .map(|menu| menu.select_first(self.project.as_ref(), cx))
 7276            .unwrap_or(false)
 7277        {
 7278            return;
 7279        }
 7280
 7281        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7282            cx.propagate();
 7283            return;
 7284        }
 7285
 7286        let Some(row_count) = self.visible_row_count() else {
 7287            return;
 7288        };
 7289
 7290        let autoscroll = if action.center_cursor {
 7291            Autoscroll::center()
 7292        } else {
 7293            Autoscroll::fit()
 7294        };
 7295
 7296        let text_layout_details = &self.text_layout_details(cx);
 7297
 7298        self.change_selections(Some(autoscroll), cx, |s| {
 7299            let line_mode = s.line_mode;
 7300            s.move_with(|map, selection| {
 7301                if !selection.is_empty() && !line_mode {
 7302                    selection.goal = SelectionGoal::None;
 7303                }
 7304                let (cursor, goal) = movement::up_by_rows(
 7305                    map,
 7306                    selection.end,
 7307                    row_count,
 7308                    selection.goal,
 7309                    false,
 7310                    text_layout_details,
 7311                );
 7312                selection.collapse_to(cursor, goal);
 7313            });
 7314        });
 7315    }
 7316
 7317    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7318        let text_layout_details = &self.text_layout_details(cx);
 7319        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7320            s.move_heads_with(|map, head, goal| {
 7321                movement::up(map, head, goal, false, text_layout_details)
 7322            })
 7323        })
 7324    }
 7325
 7326    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7327        self.take_rename(true, cx);
 7328
 7329        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7330            cx.propagate();
 7331            return;
 7332        }
 7333
 7334        let text_layout_details = &self.text_layout_details(cx);
 7335        let selection_count = self.selections.count();
 7336        let first_selection = self.selections.first_anchor();
 7337
 7338        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7339            let line_mode = s.line_mode;
 7340            s.move_with(|map, selection| {
 7341                if !selection.is_empty() && !line_mode {
 7342                    selection.goal = SelectionGoal::None;
 7343                }
 7344                let (cursor, goal) = movement::down(
 7345                    map,
 7346                    selection.end,
 7347                    selection.goal,
 7348                    false,
 7349                    text_layout_details,
 7350                );
 7351                selection.collapse_to(cursor, goal);
 7352            });
 7353        });
 7354
 7355        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7356        {
 7357            cx.propagate();
 7358        }
 7359    }
 7360
 7361    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7362        let Some(row_count) = self.visible_row_count() else {
 7363            return;
 7364        };
 7365
 7366        let text_layout_details = &self.text_layout_details(cx);
 7367
 7368        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7369            s.move_heads_with(|map, head, goal| {
 7370                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7371            })
 7372        })
 7373    }
 7374
 7375    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7376        if self.take_rename(true, cx).is_some() {
 7377            return;
 7378        }
 7379
 7380        if self
 7381            .context_menu
 7382            .write()
 7383            .as_mut()
 7384            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 7385            .unwrap_or(false)
 7386        {
 7387            return;
 7388        }
 7389
 7390        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7391            cx.propagate();
 7392            return;
 7393        }
 7394
 7395        let Some(row_count) = self.visible_row_count() else {
 7396            return;
 7397        };
 7398
 7399        let autoscroll = if action.center_cursor {
 7400            Autoscroll::center()
 7401        } else {
 7402            Autoscroll::fit()
 7403        };
 7404
 7405        let text_layout_details = &self.text_layout_details(cx);
 7406        self.change_selections(Some(autoscroll), cx, |s| {
 7407            let line_mode = s.line_mode;
 7408            s.move_with(|map, selection| {
 7409                if !selection.is_empty() && !line_mode {
 7410                    selection.goal = SelectionGoal::None;
 7411                }
 7412                let (cursor, goal) = movement::down_by_rows(
 7413                    map,
 7414                    selection.end,
 7415                    row_count,
 7416                    selection.goal,
 7417                    false,
 7418                    text_layout_details,
 7419                );
 7420                selection.collapse_to(cursor, goal);
 7421            });
 7422        });
 7423    }
 7424
 7425    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7426        let text_layout_details = &self.text_layout_details(cx);
 7427        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7428            s.move_heads_with(|map, head, goal| {
 7429                movement::down(map, head, goal, false, text_layout_details)
 7430            })
 7431        });
 7432    }
 7433
 7434    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7435        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7436            context_menu.select_first(self.project.as_ref(), cx);
 7437        }
 7438    }
 7439
 7440    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7441        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7442            context_menu.select_prev(self.project.as_ref(), cx);
 7443        }
 7444    }
 7445
 7446    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7447        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7448            context_menu.select_next(self.project.as_ref(), cx);
 7449        }
 7450    }
 7451
 7452    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7453        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7454            context_menu.select_last(self.project.as_ref(), cx);
 7455        }
 7456    }
 7457
 7458    pub fn move_to_previous_word_start(
 7459        &mut self,
 7460        _: &MoveToPreviousWordStart,
 7461        cx: &mut ViewContext<Self>,
 7462    ) {
 7463        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7464            s.move_cursors_with(|map, head, _| {
 7465                (
 7466                    movement::previous_word_start(map, head),
 7467                    SelectionGoal::None,
 7468                )
 7469            });
 7470        })
 7471    }
 7472
 7473    pub fn move_to_previous_subword_start(
 7474        &mut self,
 7475        _: &MoveToPreviousSubwordStart,
 7476        cx: &mut ViewContext<Self>,
 7477    ) {
 7478        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7479            s.move_cursors_with(|map, head, _| {
 7480                (
 7481                    movement::previous_subword_start(map, head),
 7482                    SelectionGoal::None,
 7483                )
 7484            });
 7485        })
 7486    }
 7487
 7488    pub fn select_to_previous_word_start(
 7489        &mut self,
 7490        _: &SelectToPreviousWordStart,
 7491        cx: &mut ViewContext<Self>,
 7492    ) {
 7493        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7494            s.move_heads_with(|map, head, _| {
 7495                (
 7496                    movement::previous_word_start(map, head),
 7497                    SelectionGoal::None,
 7498                )
 7499            });
 7500        })
 7501    }
 7502
 7503    pub fn select_to_previous_subword_start(
 7504        &mut self,
 7505        _: &SelectToPreviousSubwordStart,
 7506        cx: &mut ViewContext<Self>,
 7507    ) {
 7508        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7509            s.move_heads_with(|map, head, _| {
 7510                (
 7511                    movement::previous_subword_start(map, head),
 7512                    SelectionGoal::None,
 7513                )
 7514            });
 7515        })
 7516    }
 7517
 7518    pub fn delete_to_previous_word_start(
 7519        &mut self,
 7520        action: &DeleteToPreviousWordStart,
 7521        cx: &mut ViewContext<Self>,
 7522    ) {
 7523        self.transact(cx, |this, cx| {
 7524            this.select_autoclose_pair(cx);
 7525            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7526                let line_mode = s.line_mode;
 7527                s.move_with(|map, selection| {
 7528                    if selection.is_empty() && !line_mode {
 7529                        let cursor = if action.ignore_newlines {
 7530                            movement::previous_word_start(map, selection.head())
 7531                        } else {
 7532                            movement::previous_word_start_or_newline(map, selection.head())
 7533                        };
 7534                        selection.set_head(cursor, SelectionGoal::None);
 7535                    }
 7536                });
 7537            });
 7538            this.insert("", cx);
 7539        });
 7540    }
 7541
 7542    pub fn delete_to_previous_subword_start(
 7543        &mut self,
 7544        _: &DeleteToPreviousSubwordStart,
 7545        cx: &mut ViewContext<Self>,
 7546    ) {
 7547        self.transact(cx, |this, cx| {
 7548            this.select_autoclose_pair(cx);
 7549            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7550                let line_mode = s.line_mode;
 7551                s.move_with(|map, selection| {
 7552                    if selection.is_empty() && !line_mode {
 7553                        let cursor = movement::previous_subword_start(map, selection.head());
 7554                        selection.set_head(cursor, SelectionGoal::None);
 7555                    }
 7556                });
 7557            });
 7558            this.insert("", cx);
 7559        });
 7560    }
 7561
 7562    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7563        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7564            s.move_cursors_with(|map, head, _| {
 7565                (movement::next_word_end(map, head), SelectionGoal::None)
 7566            });
 7567        })
 7568    }
 7569
 7570    pub fn move_to_next_subword_end(
 7571        &mut self,
 7572        _: &MoveToNextSubwordEnd,
 7573        cx: &mut ViewContext<Self>,
 7574    ) {
 7575        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7576            s.move_cursors_with(|map, head, _| {
 7577                (movement::next_subword_end(map, head), SelectionGoal::None)
 7578            });
 7579        })
 7580    }
 7581
 7582    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7583        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7584            s.move_heads_with(|map, head, _| {
 7585                (movement::next_word_end(map, head), SelectionGoal::None)
 7586            });
 7587        })
 7588    }
 7589
 7590    pub fn select_to_next_subword_end(
 7591        &mut self,
 7592        _: &SelectToNextSubwordEnd,
 7593        cx: &mut ViewContext<Self>,
 7594    ) {
 7595        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7596            s.move_heads_with(|map, head, _| {
 7597                (movement::next_subword_end(map, head), SelectionGoal::None)
 7598            });
 7599        })
 7600    }
 7601
 7602    pub fn delete_to_next_word_end(
 7603        &mut self,
 7604        action: &DeleteToNextWordEnd,
 7605        cx: &mut ViewContext<Self>,
 7606    ) {
 7607        self.transact(cx, |this, cx| {
 7608            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7609                let line_mode = s.line_mode;
 7610                s.move_with(|map, selection| {
 7611                    if selection.is_empty() && !line_mode {
 7612                        let cursor = if action.ignore_newlines {
 7613                            movement::next_word_end(map, selection.head())
 7614                        } else {
 7615                            movement::next_word_end_or_newline(map, selection.head())
 7616                        };
 7617                        selection.set_head(cursor, SelectionGoal::None);
 7618                    }
 7619                });
 7620            });
 7621            this.insert("", cx);
 7622        });
 7623    }
 7624
 7625    pub fn delete_to_next_subword_end(
 7626        &mut self,
 7627        _: &DeleteToNextSubwordEnd,
 7628        cx: &mut ViewContext<Self>,
 7629    ) {
 7630        self.transact(cx, |this, cx| {
 7631            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7632                s.move_with(|map, selection| {
 7633                    if selection.is_empty() {
 7634                        let cursor = movement::next_subword_end(map, selection.head());
 7635                        selection.set_head(cursor, SelectionGoal::None);
 7636                    }
 7637                });
 7638            });
 7639            this.insert("", cx);
 7640        });
 7641    }
 7642
 7643    pub fn move_to_beginning_of_line(
 7644        &mut self,
 7645        action: &MoveToBeginningOfLine,
 7646        cx: &mut ViewContext<Self>,
 7647    ) {
 7648        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7649            s.move_cursors_with(|map, head, _| {
 7650                (
 7651                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7652                    SelectionGoal::None,
 7653                )
 7654            });
 7655        })
 7656    }
 7657
 7658    pub fn select_to_beginning_of_line(
 7659        &mut self,
 7660        action: &SelectToBeginningOfLine,
 7661        cx: &mut ViewContext<Self>,
 7662    ) {
 7663        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7664            s.move_heads_with(|map, head, _| {
 7665                (
 7666                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7667                    SelectionGoal::None,
 7668                )
 7669            });
 7670        });
 7671    }
 7672
 7673    pub fn delete_to_beginning_of_line(
 7674        &mut self,
 7675        _: &DeleteToBeginningOfLine,
 7676        cx: &mut ViewContext<Self>,
 7677    ) {
 7678        self.transact(cx, |this, cx| {
 7679            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7680                s.move_with(|_, selection| {
 7681                    selection.reversed = true;
 7682                });
 7683            });
 7684
 7685            this.select_to_beginning_of_line(
 7686                &SelectToBeginningOfLine {
 7687                    stop_at_soft_wraps: false,
 7688                },
 7689                cx,
 7690            );
 7691            this.backspace(&Backspace, cx);
 7692        });
 7693    }
 7694
 7695    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7696        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7697            s.move_cursors_with(|map, head, _| {
 7698                (
 7699                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7700                    SelectionGoal::None,
 7701                )
 7702            });
 7703        })
 7704    }
 7705
 7706    pub fn select_to_end_of_line(
 7707        &mut self,
 7708        action: &SelectToEndOfLine,
 7709        cx: &mut ViewContext<Self>,
 7710    ) {
 7711        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7712            s.move_heads_with(|map, head, _| {
 7713                (
 7714                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7715                    SelectionGoal::None,
 7716                )
 7717            });
 7718        })
 7719    }
 7720
 7721    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7722        self.transact(cx, |this, cx| {
 7723            this.select_to_end_of_line(
 7724                &SelectToEndOfLine {
 7725                    stop_at_soft_wraps: false,
 7726                },
 7727                cx,
 7728            );
 7729            this.delete(&Delete, cx);
 7730        });
 7731    }
 7732
 7733    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7734        self.transact(cx, |this, cx| {
 7735            this.select_to_end_of_line(
 7736                &SelectToEndOfLine {
 7737                    stop_at_soft_wraps: false,
 7738                },
 7739                cx,
 7740            );
 7741            this.cut(&Cut, cx);
 7742        });
 7743    }
 7744
 7745    pub fn move_to_start_of_paragraph(
 7746        &mut self,
 7747        _: &MoveToStartOfParagraph,
 7748        cx: &mut ViewContext<Self>,
 7749    ) {
 7750        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7751            cx.propagate();
 7752            return;
 7753        }
 7754
 7755        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7756            s.move_with(|map, selection| {
 7757                selection.collapse_to(
 7758                    movement::start_of_paragraph(map, selection.head(), 1),
 7759                    SelectionGoal::None,
 7760                )
 7761            });
 7762        })
 7763    }
 7764
 7765    pub fn move_to_end_of_paragraph(
 7766        &mut self,
 7767        _: &MoveToEndOfParagraph,
 7768        cx: &mut ViewContext<Self>,
 7769    ) {
 7770        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7771            cx.propagate();
 7772            return;
 7773        }
 7774
 7775        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7776            s.move_with(|map, selection| {
 7777                selection.collapse_to(
 7778                    movement::end_of_paragraph(map, selection.head(), 1),
 7779                    SelectionGoal::None,
 7780                )
 7781            });
 7782        })
 7783    }
 7784
 7785    pub fn select_to_start_of_paragraph(
 7786        &mut self,
 7787        _: &SelectToStartOfParagraph,
 7788        cx: &mut ViewContext<Self>,
 7789    ) {
 7790        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7791            cx.propagate();
 7792            return;
 7793        }
 7794
 7795        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7796            s.move_heads_with(|map, head, _| {
 7797                (
 7798                    movement::start_of_paragraph(map, head, 1),
 7799                    SelectionGoal::None,
 7800                )
 7801            });
 7802        })
 7803    }
 7804
 7805    pub fn select_to_end_of_paragraph(
 7806        &mut self,
 7807        _: &SelectToEndOfParagraph,
 7808        cx: &mut ViewContext<Self>,
 7809    ) {
 7810        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7811            cx.propagate();
 7812            return;
 7813        }
 7814
 7815        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7816            s.move_heads_with(|map, head, _| {
 7817                (
 7818                    movement::end_of_paragraph(map, head, 1),
 7819                    SelectionGoal::None,
 7820                )
 7821            });
 7822        })
 7823    }
 7824
 7825    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7826        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7827            cx.propagate();
 7828            return;
 7829        }
 7830
 7831        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7832            s.select_ranges(vec![0..0]);
 7833        });
 7834    }
 7835
 7836    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7837        let mut selection = self.selections.last::<Point>(cx);
 7838        selection.set_head(Point::zero(), SelectionGoal::None);
 7839
 7840        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7841            s.select(vec![selection]);
 7842        });
 7843    }
 7844
 7845    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7846        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7847            cx.propagate();
 7848            return;
 7849        }
 7850
 7851        let cursor = self.buffer.read(cx).read(cx).len();
 7852        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7853            s.select_ranges(vec![cursor..cursor])
 7854        });
 7855    }
 7856
 7857    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7858        self.nav_history = nav_history;
 7859    }
 7860
 7861    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7862        self.nav_history.as_ref()
 7863    }
 7864
 7865    fn push_to_nav_history(
 7866        &mut self,
 7867        cursor_anchor: Anchor,
 7868        new_position: Option<Point>,
 7869        cx: &mut ViewContext<Self>,
 7870    ) {
 7871        if let Some(nav_history) = self.nav_history.as_mut() {
 7872            let buffer = self.buffer.read(cx).read(cx);
 7873            let cursor_position = cursor_anchor.to_point(&buffer);
 7874            let scroll_state = self.scroll_manager.anchor();
 7875            let scroll_top_row = scroll_state.top_row(&buffer);
 7876            drop(buffer);
 7877
 7878            if let Some(new_position) = new_position {
 7879                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7880                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7881                    return;
 7882                }
 7883            }
 7884
 7885            nav_history.push(
 7886                Some(NavigationData {
 7887                    cursor_anchor,
 7888                    cursor_position,
 7889                    scroll_anchor: scroll_state,
 7890                    scroll_top_row,
 7891                }),
 7892                cx,
 7893            );
 7894        }
 7895    }
 7896
 7897    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7898        let buffer = self.buffer.read(cx).snapshot(cx);
 7899        let mut selection = self.selections.first::<usize>(cx);
 7900        selection.set_head(buffer.len(), SelectionGoal::None);
 7901        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7902            s.select(vec![selection]);
 7903        });
 7904    }
 7905
 7906    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7907        let end = self.buffer.read(cx).read(cx).len();
 7908        self.change_selections(None, cx, |s| {
 7909            s.select_ranges(vec![0..end]);
 7910        });
 7911    }
 7912
 7913    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7914        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7915        let mut selections = self.selections.all::<Point>(cx);
 7916        let max_point = display_map.buffer_snapshot.max_point();
 7917        for selection in &mut selections {
 7918            let rows = selection.spanned_rows(true, &display_map);
 7919            selection.start = Point::new(rows.start.0, 0);
 7920            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7921            selection.reversed = false;
 7922        }
 7923        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7924            s.select(selections);
 7925        });
 7926    }
 7927
 7928    pub fn split_selection_into_lines(
 7929        &mut self,
 7930        _: &SplitSelectionIntoLines,
 7931        cx: &mut ViewContext<Self>,
 7932    ) {
 7933        let mut to_unfold = Vec::new();
 7934        let mut new_selection_ranges = Vec::new();
 7935        {
 7936            let selections = self.selections.all::<Point>(cx);
 7937            let buffer = self.buffer.read(cx).read(cx);
 7938            for selection in selections {
 7939                for row in selection.start.row..selection.end.row {
 7940                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7941                    new_selection_ranges.push(cursor..cursor);
 7942                }
 7943                new_selection_ranges.push(selection.end..selection.end);
 7944                to_unfold.push(selection.start..selection.end);
 7945            }
 7946        }
 7947        self.unfold_ranges(to_unfold, true, true, cx);
 7948        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7949            s.select_ranges(new_selection_ranges);
 7950        });
 7951    }
 7952
 7953    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7954        self.add_selection(true, cx);
 7955    }
 7956
 7957    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7958        self.add_selection(false, cx);
 7959    }
 7960
 7961    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7962        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7963        let mut selections = self.selections.all::<Point>(cx);
 7964        let text_layout_details = self.text_layout_details(cx);
 7965        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7966            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7967            let range = oldest_selection.display_range(&display_map).sorted();
 7968
 7969            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7970            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7971            let positions = start_x.min(end_x)..start_x.max(end_x);
 7972
 7973            selections.clear();
 7974            let mut stack = Vec::new();
 7975            for row in range.start.row().0..=range.end.row().0 {
 7976                if let Some(selection) = self.selections.build_columnar_selection(
 7977                    &display_map,
 7978                    DisplayRow(row),
 7979                    &positions,
 7980                    oldest_selection.reversed,
 7981                    &text_layout_details,
 7982                ) {
 7983                    stack.push(selection.id);
 7984                    selections.push(selection);
 7985                }
 7986            }
 7987
 7988            if above {
 7989                stack.reverse();
 7990            }
 7991
 7992            AddSelectionsState { above, stack }
 7993        });
 7994
 7995        let last_added_selection = *state.stack.last().unwrap();
 7996        let mut new_selections = Vec::new();
 7997        if above == state.above {
 7998            let end_row = if above {
 7999                DisplayRow(0)
 8000            } else {
 8001                display_map.max_point().row()
 8002            };
 8003
 8004            'outer: for selection in selections {
 8005                if selection.id == last_added_selection {
 8006                    let range = selection.display_range(&display_map).sorted();
 8007                    debug_assert_eq!(range.start.row(), range.end.row());
 8008                    let mut row = range.start.row();
 8009                    let positions =
 8010                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8011                            px(start)..px(end)
 8012                        } else {
 8013                            let start_x =
 8014                                display_map.x_for_display_point(range.start, &text_layout_details);
 8015                            let end_x =
 8016                                display_map.x_for_display_point(range.end, &text_layout_details);
 8017                            start_x.min(end_x)..start_x.max(end_x)
 8018                        };
 8019
 8020                    while row != end_row {
 8021                        if above {
 8022                            row.0 -= 1;
 8023                        } else {
 8024                            row.0 += 1;
 8025                        }
 8026
 8027                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8028                            &display_map,
 8029                            row,
 8030                            &positions,
 8031                            selection.reversed,
 8032                            &text_layout_details,
 8033                        ) {
 8034                            state.stack.push(new_selection.id);
 8035                            if above {
 8036                                new_selections.push(new_selection);
 8037                                new_selections.push(selection);
 8038                            } else {
 8039                                new_selections.push(selection);
 8040                                new_selections.push(new_selection);
 8041                            }
 8042
 8043                            continue 'outer;
 8044                        }
 8045                    }
 8046                }
 8047
 8048                new_selections.push(selection);
 8049            }
 8050        } else {
 8051            new_selections = selections;
 8052            new_selections.retain(|s| s.id != last_added_selection);
 8053            state.stack.pop();
 8054        }
 8055
 8056        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8057            s.select(new_selections);
 8058        });
 8059        if state.stack.len() > 1 {
 8060            self.add_selections_state = Some(state);
 8061        }
 8062    }
 8063
 8064    pub fn select_next_match_internal(
 8065        &mut self,
 8066        display_map: &DisplaySnapshot,
 8067        replace_newest: bool,
 8068        autoscroll: Option<Autoscroll>,
 8069        cx: &mut ViewContext<Self>,
 8070    ) -> Result<()> {
 8071        fn select_next_match_ranges(
 8072            this: &mut Editor,
 8073            range: Range<usize>,
 8074            replace_newest: bool,
 8075            auto_scroll: Option<Autoscroll>,
 8076            cx: &mut ViewContext<Editor>,
 8077        ) {
 8078            this.unfold_ranges([range.clone()], false, true, cx);
 8079            this.change_selections(auto_scroll, cx, |s| {
 8080                if replace_newest {
 8081                    s.delete(s.newest_anchor().id);
 8082                }
 8083                s.insert_range(range.clone());
 8084            });
 8085        }
 8086
 8087        let buffer = &display_map.buffer_snapshot;
 8088        let mut selections = self.selections.all::<usize>(cx);
 8089        if let Some(mut select_next_state) = self.select_next_state.take() {
 8090            let query = &select_next_state.query;
 8091            if !select_next_state.done {
 8092                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8093                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8094                let mut next_selected_range = None;
 8095
 8096                let bytes_after_last_selection =
 8097                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8098                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8099                let query_matches = query
 8100                    .stream_find_iter(bytes_after_last_selection)
 8101                    .map(|result| (last_selection.end, result))
 8102                    .chain(
 8103                        query
 8104                            .stream_find_iter(bytes_before_first_selection)
 8105                            .map(|result| (0, result)),
 8106                    );
 8107
 8108                for (start_offset, query_match) in query_matches {
 8109                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8110                    let offset_range =
 8111                        start_offset + query_match.start()..start_offset + query_match.end();
 8112                    let display_range = offset_range.start.to_display_point(display_map)
 8113                        ..offset_range.end.to_display_point(display_map);
 8114
 8115                    if !select_next_state.wordwise
 8116                        || (!movement::is_inside_word(display_map, display_range.start)
 8117                            && !movement::is_inside_word(display_map, display_range.end))
 8118                    {
 8119                        // TODO: This is n^2, because we might check all the selections
 8120                        if !selections
 8121                            .iter()
 8122                            .any(|selection| selection.range().overlaps(&offset_range))
 8123                        {
 8124                            next_selected_range = Some(offset_range);
 8125                            break;
 8126                        }
 8127                    }
 8128                }
 8129
 8130                if let Some(next_selected_range) = next_selected_range {
 8131                    select_next_match_ranges(
 8132                        self,
 8133                        next_selected_range,
 8134                        replace_newest,
 8135                        autoscroll,
 8136                        cx,
 8137                    );
 8138                } else {
 8139                    select_next_state.done = true;
 8140                }
 8141            }
 8142
 8143            self.select_next_state = Some(select_next_state);
 8144        } else {
 8145            let mut only_carets = true;
 8146            let mut same_text_selected = true;
 8147            let mut selected_text = None;
 8148
 8149            let mut selections_iter = selections.iter().peekable();
 8150            while let Some(selection) = selections_iter.next() {
 8151                if selection.start != selection.end {
 8152                    only_carets = false;
 8153                }
 8154
 8155                if same_text_selected {
 8156                    if selected_text.is_none() {
 8157                        selected_text =
 8158                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8159                    }
 8160
 8161                    if let Some(next_selection) = selections_iter.peek() {
 8162                        if next_selection.range().len() == selection.range().len() {
 8163                            let next_selected_text = buffer
 8164                                .text_for_range(next_selection.range())
 8165                                .collect::<String>();
 8166                            if Some(next_selected_text) != selected_text {
 8167                                same_text_selected = false;
 8168                                selected_text = None;
 8169                            }
 8170                        } else {
 8171                            same_text_selected = false;
 8172                            selected_text = None;
 8173                        }
 8174                    }
 8175                }
 8176            }
 8177
 8178            if only_carets {
 8179                for selection in &mut selections {
 8180                    let word_range = movement::surrounding_word(
 8181                        display_map,
 8182                        selection.start.to_display_point(display_map),
 8183                    );
 8184                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8185                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8186                    selection.goal = SelectionGoal::None;
 8187                    selection.reversed = false;
 8188                    select_next_match_ranges(
 8189                        self,
 8190                        selection.start..selection.end,
 8191                        replace_newest,
 8192                        autoscroll,
 8193                        cx,
 8194                    );
 8195                }
 8196
 8197                if selections.len() == 1 {
 8198                    let selection = selections
 8199                        .last()
 8200                        .expect("ensured that there's only one selection");
 8201                    let query = buffer
 8202                        .text_for_range(selection.start..selection.end)
 8203                        .collect::<String>();
 8204                    let is_empty = query.is_empty();
 8205                    let select_state = SelectNextState {
 8206                        query: AhoCorasick::new(&[query])?,
 8207                        wordwise: true,
 8208                        done: is_empty,
 8209                    };
 8210                    self.select_next_state = Some(select_state);
 8211                } else {
 8212                    self.select_next_state = None;
 8213                }
 8214            } else if let Some(selected_text) = selected_text {
 8215                self.select_next_state = Some(SelectNextState {
 8216                    query: AhoCorasick::new(&[selected_text])?,
 8217                    wordwise: false,
 8218                    done: false,
 8219                });
 8220                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8221            }
 8222        }
 8223        Ok(())
 8224    }
 8225
 8226    pub fn select_all_matches(
 8227        &mut self,
 8228        _action: &SelectAllMatches,
 8229        cx: &mut ViewContext<Self>,
 8230    ) -> Result<()> {
 8231        self.push_to_selection_history();
 8232        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8233
 8234        self.select_next_match_internal(&display_map, false, None, cx)?;
 8235        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8236            return Ok(());
 8237        };
 8238        if select_next_state.done {
 8239            return Ok(());
 8240        }
 8241
 8242        let mut new_selections = self.selections.all::<usize>(cx);
 8243
 8244        let buffer = &display_map.buffer_snapshot;
 8245        let query_matches = select_next_state
 8246            .query
 8247            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8248
 8249        for query_match in query_matches {
 8250            let query_match = query_match.unwrap(); // can only fail due to I/O
 8251            let offset_range = query_match.start()..query_match.end();
 8252            let display_range = offset_range.start.to_display_point(&display_map)
 8253                ..offset_range.end.to_display_point(&display_map);
 8254
 8255            if !select_next_state.wordwise
 8256                || (!movement::is_inside_word(&display_map, display_range.start)
 8257                    && !movement::is_inside_word(&display_map, display_range.end))
 8258            {
 8259                self.selections.change_with(cx, |selections| {
 8260                    new_selections.push(Selection {
 8261                        id: selections.new_selection_id(),
 8262                        start: offset_range.start,
 8263                        end: offset_range.end,
 8264                        reversed: false,
 8265                        goal: SelectionGoal::None,
 8266                    });
 8267                });
 8268            }
 8269        }
 8270
 8271        new_selections.sort_by_key(|selection| selection.start);
 8272        let mut ix = 0;
 8273        while ix + 1 < new_selections.len() {
 8274            let current_selection = &new_selections[ix];
 8275            let next_selection = &new_selections[ix + 1];
 8276            if current_selection.range().overlaps(&next_selection.range()) {
 8277                if current_selection.id < next_selection.id {
 8278                    new_selections.remove(ix + 1);
 8279                } else {
 8280                    new_selections.remove(ix);
 8281                }
 8282            } else {
 8283                ix += 1;
 8284            }
 8285        }
 8286
 8287        select_next_state.done = true;
 8288        self.unfold_ranges(
 8289            new_selections.iter().map(|selection| selection.range()),
 8290            false,
 8291            false,
 8292            cx,
 8293        );
 8294        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8295            selections.select(new_selections)
 8296        });
 8297
 8298        Ok(())
 8299    }
 8300
 8301    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8302        self.push_to_selection_history();
 8303        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8304        self.select_next_match_internal(
 8305            &display_map,
 8306            action.replace_newest,
 8307            Some(Autoscroll::newest()),
 8308            cx,
 8309        )?;
 8310        Ok(())
 8311    }
 8312
 8313    pub fn select_previous(
 8314        &mut self,
 8315        action: &SelectPrevious,
 8316        cx: &mut ViewContext<Self>,
 8317    ) -> Result<()> {
 8318        self.push_to_selection_history();
 8319        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8320        let buffer = &display_map.buffer_snapshot;
 8321        let mut selections = self.selections.all::<usize>(cx);
 8322        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8323            let query = &select_prev_state.query;
 8324            if !select_prev_state.done {
 8325                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8326                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8327                let mut next_selected_range = None;
 8328                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8329                let bytes_before_last_selection =
 8330                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8331                let bytes_after_first_selection =
 8332                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8333                let query_matches = query
 8334                    .stream_find_iter(bytes_before_last_selection)
 8335                    .map(|result| (last_selection.start, result))
 8336                    .chain(
 8337                        query
 8338                            .stream_find_iter(bytes_after_first_selection)
 8339                            .map(|result| (buffer.len(), result)),
 8340                    );
 8341                for (end_offset, query_match) in query_matches {
 8342                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8343                    let offset_range =
 8344                        end_offset - query_match.end()..end_offset - query_match.start();
 8345                    let display_range = offset_range.start.to_display_point(&display_map)
 8346                        ..offset_range.end.to_display_point(&display_map);
 8347
 8348                    if !select_prev_state.wordwise
 8349                        || (!movement::is_inside_word(&display_map, display_range.start)
 8350                            && !movement::is_inside_word(&display_map, display_range.end))
 8351                    {
 8352                        next_selected_range = Some(offset_range);
 8353                        break;
 8354                    }
 8355                }
 8356
 8357                if let Some(next_selected_range) = next_selected_range {
 8358                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 8359                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8360                        if action.replace_newest {
 8361                            s.delete(s.newest_anchor().id);
 8362                        }
 8363                        s.insert_range(next_selected_range);
 8364                    });
 8365                } else {
 8366                    select_prev_state.done = true;
 8367                }
 8368            }
 8369
 8370            self.select_prev_state = Some(select_prev_state);
 8371        } else {
 8372            let mut only_carets = true;
 8373            let mut same_text_selected = true;
 8374            let mut selected_text = None;
 8375
 8376            let mut selections_iter = selections.iter().peekable();
 8377            while let Some(selection) = selections_iter.next() {
 8378                if selection.start != selection.end {
 8379                    only_carets = false;
 8380                }
 8381
 8382                if same_text_selected {
 8383                    if selected_text.is_none() {
 8384                        selected_text =
 8385                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8386                    }
 8387
 8388                    if let Some(next_selection) = selections_iter.peek() {
 8389                        if next_selection.range().len() == selection.range().len() {
 8390                            let next_selected_text = buffer
 8391                                .text_for_range(next_selection.range())
 8392                                .collect::<String>();
 8393                            if Some(next_selected_text) != selected_text {
 8394                                same_text_selected = false;
 8395                                selected_text = None;
 8396                            }
 8397                        } else {
 8398                            same_text_selected = false;
 8399                            selected_text = None;
 8400                        }
 8401                    }
 8402                }
 8403            }
 8404
 8405            if only_carets {
 8406                for selection in &mut selections {
 8407                    let word_range = movement::surrounding_word(
 8408                        &display_map,
 8409                        selection.start.to_display_point(&display_map),
 8410                    );
 8411                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8412                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8413                    selection.goal = SelectionGoal::None;
 8414                    selection.reversed = false;
 8415                }
 8416                if selections.len() == 1 {
 8417                    let selection = selections
 8418                        .last()
 8419                        .expect("ensured that there's only one selection");
 8420                    let query = buffer
 8421                        .text_for_range(selection.start..selection.end)
 8422                        .collect::<String>();
 8423                    let is_empty = query.is_empty();
 8424                    let select_state = SelectNextState {
 8425                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8426                        wordwise: true,
 8427                        done: is_empty,
 8428                    };
 8429                    self.select_prev_state = Some(select_state);
 8430                } else {
 8431                    self.select_prev_state = None;
 8432                }
 8433
 8434                self.unfold_ranges(
 8435                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8436                    false,
 8437                    true,
 8438                    cx,
 8439                );
 8440                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8441                    s.select(selections);
 8442                });
 8443            } else if let Some(selected_text) = selected_text {
 8444                self.select_prev_state = Some(SelectNextState {
 8445                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8446                    wordwise: false,
 8447                    done: false,
 8448                });
 8449                self.select_previous(action, cx)?;
 8450            }
 8451        }
 8452        Ok(())
 8453    }
 8454
 8455    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8456        let text_layout_details = &self.text_layout_details(cx);
 8457        self.transact(cx, |this, cx| {
 8458            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8459            let mut edits = Vec::new();
 8460            let mut selection_edit_ranges = Vec::new();
 8461            let mut last_toggled_row = None;
 8462            let snapshot = this.buffer.read(cx).read(cx);
 8463            let empty_str: Arc<str> = Arc::default();
 8464            let mut suffixes_inserted = Vec::new();
 8465
 8466            fn comment_prefix_range(
 8467                snapshot: &MultiBufferSnapshot,
 8468                row: MultiBufferRow,
 8469                comment_prefix: &str,
 8470                comment_prefix_whitespace: &str,
 8471            ) -> Range<Point> {
 8472                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8473
 8474                let mut line_bytes = snapshot
 8475                    .bytes_in_range(start..snapshot.max_point())
 8476                    .flatten()
 8477                    .copied();
 8478
 8479                // If this line currently begins with the line comment prefix, then record
 8480                // the range containing the prefix.
 8481                if line_bytes
 8482                    .by_ref()
 8483                    .take(comment_prefix.len())
 8484                    .eq(comment_prefix.bytes())
 8485                {
 8486                    // Include any whitespace that matches the comment prefix.
 8487                    let matching_whitespace_len = line_bytes
 8488                        .zip(comment_prefix_whitespace.bytes())
 8489                        .take_while(|(a, b)| a == b)
 8490                        .count() as u32;
 8491                    let end = Point::new(
 8492                        start.row,
 8493                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8494                    );
 8495                    start..end
 8496                } else {
 8497                    start..start
 8498                }
 8499            }
 8500
 8501            fn comment_suffix_range(
 8502                snapshot: &MultiBufferSnapshot,
 8503                row: MultiBufferRow,
 8504                comment_suffix: &str,
 8505                comment_suffix_has_leading_space: bool,
 8506            ) -> Range<Point> {
 8507                let end = Point::new(row.0, snapshot.line_len(row));
 8508                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8509
 8510                let mut line_end_bytes = snapshot
 8511                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8512                    .flatten()
 8513                    .copied();
 8514
 8515                let leading_space_len = if suffix_start_column > 0
 8516                    && line_end_bytes.next() == Some(b' ')
 8517                    && comment_suffix_has_leading_space
 8518                {
 8519                    1
 8520                } else {
 8521                    0
 8522                };
 8523
 8524                // If this line currently begins with the line comment prefix, then record
 8525                // the range containing the prefix.
 8526                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8527                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8528                    start..end
 8529                } else {
 8530                    end..end
 8531                }
 8532            }
 8533
 8534            // TODO: Handle selections that cross excerpts
 8535            for selection in &mut selections {
 8536                let start_column = snapshot
 8537                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8538                    .len;
 8539                let language = if let Some(language) =
 8540                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8541                {
 8542                    language
 8543                } else {
 8544                    continue;
 8545                };
 8546
 8547                selection_edit_ranges.clear();
 8548
 8549                // If multiple selections contain a given row, avoid processing that
 8550                // row more than once.
 8551                let mut start_row = MultiBufferRow(selection.start.row);
 8552                if last_toggled_row == Some(start_row) {
 8553                    start_row = start_row.next_row();
 8554                }
 8555                let end_row =
 8556                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8557                        MultiBufferRow(selection.end.row - 1)
 8558                    } else {
 8559                        MultiBufferRow(selection.end.row)
 8560                    };
 8561                last_toggled_row = Some(end_row);
 8562
 8563                if start_row > end_row {
 8564                    continue;
 8565                }
 8566
 8567                // If the language has line comments, toggle those.
 8568                let full_comment_prefixes = language.line_comment_prefixes();
 8569                if !full_comment_prefixes.is_empty() {
 8570                    let first_prefix = full_comment_prefixes
 8571                        .first()
 8572                        .expect("prefixes is non-empty");
 8573                    let prefix_trimmed_lengths = full_comment_prefixes
 8574                        .iter()
 8575                        .map(|p| p.trim_end_matches(' ').len())
 8576                        .collect::<SmallVec<[usize; 4]>>();
 8577
 8578                    let mut all_selection_lines_are_comments = true;
 8579
 8580                    for row in start_row.0..=end_row.0 {
 8581                        let row = MultiBufferRow(row);
 8582                        if start_row < end_row && snapshot.is_line_blank(row) {
 8583                            continue;
 8584                        }
 8585
 8586                        let prefix_range = full_comment_prefixes
 8587                            .iter()
 8588                            .zip(prefix_trimmed_lengths.iter().copied())
 8589                            .map(|(prefix, trimmed_prefix_len)| {
 8590                                comment_prefix_range(
 8591                                    snapshot.deref(),
 8592                                    row,
 8593                                    &prefix[..trimmed_prefix_len],
 8594                                    &prefix[trimmed_prefix_len..],
 8595                                )
 8596                            })
 8597                            .max_by_key(|range| range.end.column - range.start.column)
 8598                            .expect("prefixes is non-empty");
 8599
 8600                        if prefix_range.is_empty() {
 8601                            all_selection_lines_are_comments = false;
 8602                        }
 8603
 8604                        selection_edit_ranges.push(prefix_range);
 8605                    }
 8606
 8607                    if all_selection_lines_are_comments {
 8608                        edits.extend(
 8609                            selection_edit_ranges
 8610                                .iter()
 8611                                .cloned()
 8612                                .map(|range| (range, empty_str.clone())),
 8613                        );
 8614                    } else {
 8615                        let min_column = selection_edit_ranges
 8616                            .iter()
 8617                            .map(|range| range.start.column)
 8618                            .min()
 8619                            .unwrap_or(0);
 8620                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8621                            let position = Point::new(range.start.row, min_column);
 8622                            (position..position, first_prefix.clone())
 8623                        }));
 8624                    }
 8625                } else if let Some((full_comment_prefix, comment_suffix)) =
 8626                    language.block_comment_delimiters()
 8627                {
 8628                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8629                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8630                    let prefix_range = comment_prefix_range(
 8631                        snapshot.deref(),
 8632                        start_row,
 8633                        comment_prefix,
 8634                        comment_prefix_whitespace,
 8635                    );
 8636                    let suffix_range = comment_suffix_range(
 8637                        snapshot.deref(),
 8638                        end_row,
 8639                        comment_suffix.trim_start_matches(' '),
 8640                        comment_suffix.starts_with(' '),
 8641                    );
 8642
 8643                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8644                        edits.push((
 8645                            prefix_range.start..prefix_range.start,
 8646                            full_comment_prefix.clone(),
 8647                        ));
 8648                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8649                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8650                    } else {
 8651                        edits.push((prefix_range, empty_str.clone()));
 8652                        edits.push((suffix_range, empty_str.clone()));
 8653                    }
 8654                } else {
 8655                    continue;
 8656                }
 8657            }
 8658
 8659            drop(snapshot);
 8660            this.buffer.update(cx, |buffer, cx| {
 8661                buffer.edit(edits, None, cx);
 8662            });
 8663
 8664            // Adjust selections so that they end before any comment suffixes that
 8665            // were inserted.
 8666            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8667            let mut selections = this.selections.all::<Point>(cx);
 8668            let snapshot = this.buffer.read(cx).read(cx);
 8669            for selection in &mut selections {
 8670                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8671                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8672                        Ordering::Less => {
 8673                            suffixes_inserted.next();
 8674                            continue;
 8675                        }
 8676                        Ordering::Greater => break,
 8677                        Ordering::Equal => {
 8678                            if selection.end.column == snapshot.line_len(row) {
 8679                                if selection.is_empty() {
 8680                                    selection.start.column -= suffix_len as u32;
 8681                                }
 8682                                selection.end.column -= suffix_len as u32;
 8683                            }
 8684                            break;
 8685                        }
 8686                    }
 8687                }
 8688            }
 8689
 8690            drop(snapshot);
 8691            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8692
 8693            let selections = this.selections.all::<Point>(cx);
 8694            let selections_on_single_row = selections.windows(2).all(|selections| {
 8695                selections[0].start.row == selections[1].start.row
 8696                    && selections[0].end.row == selections[1].end.row
 8697                    && selections[0].start.row == selections[0].end.row
 8698            });
 8699            let selections_selecting = selections
 8700                .iter()
 8701                .any(|selection| selection.start != selection.end);
 8702            let advance_downwards = action.advance_downwards
 8703                && selections_on_single_row
 8704                && !selections_selecting
 8705                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8706
 8707            if advance_downwards {
 8708                let snapshot = this.buffer.read(cx).snapshot(cx);
 8709
 8710                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8711                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8712                        let mut point = display_point.to_point(display_snapshot);
 8713                        point.row += 1;
 8714                        point = snapshot.clip_point(point, Bias::Left);
 8715                        let display_point = point.to_display_point(display_snapshot);
 8716                        let goal = SelectionGoal::HorizontalPosition(
 8717                            display_snapshot
 8718                                .x_for_display_point(display_point, text_layout_details)
 8719                                .into(),
 8720                        );
 8721                        (display_point, goal)
 8722                    })
 8723                });
 8724            }
 8725        });
 8726    }
 8727
 8728    pub fn select_enclosing_symbol(
 8729        &mut self,
 8730        _: &SelectEnclosingSymbol,
 8731        cx: &mut ViewContext<Self>,
 8732    ) {
 8733        let buffer = self.buffer.read(cx).snapshot(cx);
 8734        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8735
 8736        fn update_selection(
 8737            selection: &Selection<usize>,
 8738            buffer_snap: &MultiBufferSnapshot,
 8739        ) -> Option<Selection<usize>> {
 8740            let cursor = selection.head();
 8741            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8742            for symbol in symbols.iter().rev() {
 8743                let start = symbol.range.start.to_offset(buffer_snap);
 8744                let end = symbol.range.end.to_offset(buffer_snap);
 8745                let new_range = start..end;
 8746                if start < selection.start || end > selection.end {
 8747                    return Some(Selection {
 8748                        id: selection.id,
 8749                        start: new_range.start,
 8750                        end: new_range.end,
 8751                        goal: SelectionGoal::None,
 8752                        reversed: selection.reversed,
 8753                    });
 8754                }
 8755            }
 8756            None
 8757        }
 8758
 8759        let mut selected_larger_symbol = false;
 8760        let new_selections = old_selections
 8761            .iter()
 8762            .map(|selection| match update_selection(selection, &buffer) {
 8763                Some(new_selection) => {
 8764                    if new_selection.range() != selection.range() {
 8765                        selected_larger_symbol = true;
 8766                    }
 8767                    new_selection
 8768                }
 8769                None => selection.clone(),
 8770            })
 8771            .collect::<Vec<_>>();
 8772
 8773        if selected_larger_symbol {
 8774            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8775                s.select(new_selections);
 8776            });
 8777        }
 8778    }
 8779
 8780    pub fn select_larger_syntax_node(
 8781        &mut self,
 8782        _: &SelectLargerSyntaxNode,
 8783        cx: &mut ViewContext<Self>,
 8784    ) {
 8785        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8786        let buffer = self.buffer.read(cx).snapshot(cx);
 8787        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8788
 8789        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8790        let mut selected_larger_node = false;
 8791        let new_selections = old_selections
 8792            .iter()
 8793            .map(|selection| {
 8794                let old_range = selection.start..selection.end;
 8795                let mut new_range = old_range.clone();
 8796                while let Some(containing_range) =
 8797                    buffer.range_for_syntax_ancestor(new_range.clone())
 8798                {
 8799                    new_range = containing_range;
 8800                    if !display_map.intersects_fold(new_range.start)
 8801                        && !display_map.intersects_fold(new_range.end)
 8802                    {
 8803                        break;
 8804                    }
 8805                }
 8806
 8807                selected_larger_node |= new_range != old_range;
 8808                Selection {
 8809                    id: selection.id,
 8810                    start: new_range.start,
 8811                    end: new_range.end,
 8812                    goal: SelectionGoal::None,
 8813                    reversed: selection.reversed,
 8814                }
 8815            })
 8816            .collect::<Vec<_>>();
 8817
 8818        if selected_larger_node {
 8819            stack.push(old_selections);
 8820            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8821                s.select(new_selections);
 8822            });
 8823        }
 8824        self.select_larger_syntax_node_stack = stack;
 8825    }
 8826
 8827    pub fn select_smaller_syntax_node(
 8828        &mut self,
 8829        _: &SelectSmallerSyntaxNode,
 8830        cx: &mut ViewContext<Self>,
 8831    ) {
 8832        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8833        if let Some(selections) = stack.pop() {
 8834            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8835                s.select(selections.to_vec());
 8836            });
 8837        }
 8838        self.select_larger_syntax_node_stack = stack;
 8839    }
 8840
 8841    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8842        if !EditorSettings::get_global(cx).gutter.runnables {
 8843            self.clear_tasks();
 8844            return Task::ready(());
 8845        }
 8846        let project = self.project.clone();
 8847        cx.spawn(|this, mut cx| async move {
 8848            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8849                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8850            }) else {
 8851                return;
 8852            };
 8853
 8854            let Some(project) = project else {
 8855                return;
 8856            };
 8857
 8858            let hide_runnables = project
 8859                .update(&mut cx, |project, cx| {
 8860                    // Do not display any test indicators in non-dev server remote projects.
 8861                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8862                })
 8863                .unwrap_or(true);
 8864            if hide_runnables {
 8865                return;
 8866            }
 8867            let new_rows =
 8868                cx.background_executor()
 8869                    .spawn({
 8870                        let snapshot = display_snapshot.clone();
 8871                        async move {
 8872                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8873                        }
 8874                    })
 8875                    .await;
 8876            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8877
 8878            this.update(&mut cx, |this, _| {
 8879                this.clear_tasks();
 8880                for (key, value) in rows {
 8881                    this.insert_tasks(key, value);
 8882                }
 8883            })
 8884            .ok();
 8885        })
 8886    }
 8887    fn fetch_runnable_ranges(
 8888        snapshot: &DisplaySnapshot,
 8889        range: Range<Anchor>,
 8890    ) -> Vec<language::RunnableRange> {
 8891        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8892    }
 8893
 8894    fn runnable_rows(
 8895        project: Model<Project>,
 8896        snapshot: DisplaySnapshot,
 8897        runnable_ranges: Vec<RunnableRange>,
 8898        mut cx: AsyncWindowContext,
 8899    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8900        runnable_ranges
 8901            .into_iter()
 8902            .filter_map(|mut runnable| {
 8903                let tasks = cx
 8904                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8905                    .ok()?;
 8906                if tasks.is_empty() {
 8907                    return None;
 8908                }
 8909
 8910                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8911
 8912                let row = snapshot
 8913                    .buffer_snapshot
 8914                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8915                    .1
 8916                    .start
 8917                    .row;
 8918
 8919                let context_range =
 8920                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8921                Some((
 8922                    (runnable.buffer_id, row),
 8923                    RunnableTasks {
 8924                        templates: tasks,
 8925                        offset: MultiBufferOffset(runnable.run_range.start),
 8926                        context_range,
 8927                        column: point.column,
 8928                        extra_variables: runnable.extra_captures,
 8929                    },
 8930                ))
 8931            })
 8932            .collect()
 8933    }
 8934
 8935    fn templates_with_tags(
 8936        project: &Model<Project>,
 8937        runnable: &mut Runnable,
 8938        cx: &WindowContext<'_>,
 8939    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8940        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8941            let (worktree_id, file) = project
 8942                .buffer_for_id(runnable.buffer, cx)
 8943                .and_then(|buffer| buffer.read(cx).file())
 8944                .map(|file| (file.worktree_id(cx), file.clone()))
 8945                .unzip();
 8946
 8947            (project.task_inventory().clone(), worktree_id, file)
 8948        });
 8949
 8950        let inventory = inventory.read(cx);
 8951        let tags = mem::take(&mut runnable.tags);
 8952        let mut tags: Vec<_> = tags
 8953            .into_iter()
 8954            .flat_map(|tag| {
 8955                let tag = tag.0.clone();
 8956                inventory
 8957                    .list_tasks(
 8958                        file.clone(),
 8959                        Some(runnable.language.clone()),
 8960                        worktree_id,
 8961                        cx,
 8962                    )
 8963                    .into_iter()
 8964                    .filter(move |(_, template)| {
 8965                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8966                    })
 8967            })
 8968            .sorted_by_key(|(kind, _)| kind.to_owned())
 8969            .collect();
 8970        if let Some((leading_tag_source, _)) = tags.first() {
 8971            // Strongest source wins; if we have worktree tag binding, prefer that to
 8972            // global and language bindings;
 8973            // if we have a global binding, prefer that to language binding.
 8974            let first_mismatch = tags
 8975                .iter()
 8976                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8977            if let Some(index) = first_mismatch {
 8978                tags.truncate(index);
 8979            }
 8980        }
 8981
 8982        tags
 8983    }
 8984
 8985    pub fn move_to_enclosing_bracket(
 8986        &mut self,
 8987        _: &MoveToEnclosingBracket,
 8988        cx: &mut ViewContext<Self>,
 8989    ) {
 8990        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8991            s.move_offsets_with(|snapshot, selection| {
 8992                let Some(enclosing_bracket_ranges) =
 8993                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8994                else {
 8995                    return;
 8996                };
 8997
 8998                let mut best_length = usize::MAX;
 8999                let mut best_inside = false;
 9000                let mut best_in_bracket_range = false;
 9001                let mut best_destination = None;
 9002                for (open, close) in enclosing_bracket_ranges {
 9003                    let close = close.to_inclusive();
 9004                    let length = close.end() - open.start;
 9005                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9006                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9007                        || close.contains(&selection.head());
 9008
 9009                    // If best is next to a bracket and current isn't, skip
 9010                    if !in_bracket_range && best_in_bracket_range {
 9011                        continue;
 9012                    }
 9013
 9014                    // Prefer smaller lengths unless best is inside and current isn't
 9015                    if length > best_length && (best_inside || !inside) {
 9016                        continue;
 9017                    }
 9018
 9019                    best_length = length;
 9020                    best_inside = inside;
 9021                    best_in_bracket_range = in_bracket_range;
 9022                    best_destination = Some(
 9023                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9024                            if inside {
 9025                                open.end
 9026                            } else {
 9027                                open.start
 9028                            }
 9029                        } else if inside {
 9030                            *close.start()
 9031                        } else {
 9032                            *close.end()
 9033                        },
 9034                    );
 9035                }
 9036
 9037                if let Some(destination) = best_destination {
 9038                    selection.collapse_to(destination, SelectionGoal::None);
 9039                }
 9040            })
 9041        });
 9042    }
 9043
 9044    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9045        self.end_selection(cx);
 9046        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9047        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9048            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9049            self.select_next_state = entry.select_next_state;
 9050            self.select_prev_state = entry.select_prev_state;
 9051            self.add_selections_state = entry.add_selections_state;
 9052            self.request_autoscroll(Autoscroll::newest(), cx);
 9053        }
 9054        self.selection_history.mode = SelectionHistoryMode::Normal;
 9055    }
 9056
 9057    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9058        self.end_selection(cx);
 9059        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9060        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9061            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9062            self.select_next_state = entry.select_next_state;
 9063            self.select_prev_state = entry.select_prev_state;
 9064            self.add_selections_state = entry.add_selections_state;
 9065            self.request_autoscroll(Autoscroll::newest(), cx);
 9066        }
 9067        self.selection_history.mode = SelectionHistoryMode::Normal;
 9068    }
 9069
 9070    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9071        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9072    }
 9073
 9074    pub fn expand_excerpts_down(
 9075        &mut self,
 9076        action: &ExpandExcerptsDown,
 9077        cx: &mut ViewContext<Self>,
 9078    ) {
 9079        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9080    }
 9081
 9082    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9083        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9084    }
 9085
 9086    pub fn expand_excerpts_for_direction(
 9087        &mut self,
 9088        lines: u32,
 9089        direction: ExpandExcerptDirection,
 9090        cx: &mut ViewContext<Self>,
 9091    ) {
 9092        let selections = self.selections.disjoint_anchors();
 9093
 9094        let lines = if lines == 0 {
 9095            EditorSettings::get_global(cx).expand_excerpt_lines
 9096        } else {
 9097            lines
 9098        };
 9099
 9100        self.buffer.update(cx, |buffer, cx| {
 9101            buffer.expand_excerpts(
 9102                selections
 9103                    .iter()
 9104                    .map(|selection| selection.head().excerpt_id)
 9105                    .dedup(),
 9106                lines,
 9107                direction,
 9108                cx,
 9109            )
 9110        })
 9111    }
 9112
 9113    pub fn expand_excerpt(
 9114        &mut self,
 9115        excerpt: ExcerptId,
 9116        direction: ExpandExcerptDirection,
 9117        cx: &mut ViewContext<Self>,
 9118    ) {
 9119        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9120        self.buffer.update(cx, |buffer, cx| {
 9121            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9122        })
 9123    }
 9124
 9125    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9126        self.go_to_diagnostic_impl(Direction::Next, cx)
 9127    }
 9128
 9129    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9130        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9131    }
 9132
 9133    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9134        let buffer = self.buffer.read(cx).snapshot(cx);
 9135        let selection = self.selections.newest::<usize>(cx);
 9136
 9137        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9138        if direction == Direction::Next {
 9139            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9140                let (group_id, jump_to) = popover.activation_info();
 9141                if self.activate_diagnostics(group_id, cx) {
 9142                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9143                        let mut new_selection = s.newest_anchor().clone();
 9144                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9145                        s.select_anchors(vec![new_selection.clone()]);
 9146                    });
 9147                }
 9148                return;
 9149            }
 9150        }
 9151
 9152        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9153            active_diagnostics
 9154                .primary_range
 9155                .to_offset(&buffer)
 9156                .to_inclusive()
 9157        });
 9158        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9159            if active_primary_range.contains(&selection.head()) {
 9160                *active_primary_range.start()
 9161            } else {
 9162                selection.head()
 9163            }
 9164        } else {
 9165            selection.head()
 9166        };
 9167        let snapshot = self.snapshot(cx);
 9168        loop {
 9169            let diagnostics = if direction == Direction::Prev {
 9170                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9171            } else {
 9172                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9173            }
 9174            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9175            let group = diagnostics
 9176                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9177                // be sorted in a stable way
 9178                // skip until we are at current active diagnostic, if it exists
 9179                .skip_while(|entry| {
 9180                    (match direction {
 9181                        Direction::Prev => entry.range.start >= search_start,
 9182                        Direction::Next => entry.range.start <= search_start,
 9183                    }) && self
 9184                        .active_diagnostics
 9185                        .as_ref()
 9186                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9187                })
 9188                .find_map(|entry| {
 9189                    if entry.diagnostic.is_primary
 9190                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9191                        && !entry.range.is_empty()
 9192                        // if we match with the active diagnostic, skip it
 9193                        && Some(entry.diagnostic.group_id)
 9194                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9195                    {
 9196                        Some((entry.range, entry.diagnostic.group_id))
 9197                    } else {
 9198                        None
 9199                    }
 9200                });
 9201
 9202            if let Some((primary_range, group_id)) = group {
 9203                if self.activate_diagnostics(group_id, cx) {
 9204                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9205                        s.select(vec![Selection {
 9206                            id: selection.id,
 9207                            start: primary_range.start,
 9208                            end: primary_range.start,
 9209                            reversed: false,
 9210                            goal: SelectionGoal::None,
 9211                        }]);
 9212                    });
 9213                }
 9214                break;
 9215            } else {
 9216                // Cycle around to the start of the buffer, potentially moving back to the start of
 9217                // the currently active diagnostic.
 9218                active_primary_range.take();
 9219                if direction == Direction::Prev {
 9220                    if search_start == buffer.len() {
 9221                        break;
 9222                    } else {
 9223                        search_start = buffer.len();
 9224                    }
 9225                } else if search_start == 0 {
 9226                    break;
 9227                } else {
 9228                    search_start = 0;
 9229                }
 9230            }
 9231        }
 9232    }
 9233
 9234    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9235        let snapshot = self
 9236            .display_map
 9237            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9238        let selection = self.selections.newest::<Point>(cx);
 9239
 9240        if !self.seek_in_direction(
 9241            &snapshot,
 9242            selection.head(),
 9243            false,
 9244            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9245                MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
 9246            ),
 9247            cx,
 9248        ) {
 9249            let wrapped_point = Point::zero();
 9250            self.seek_in_direction(
 9251                &snapshot,
 9252                wrapped_point,
 9253                true,
 9254                snapshot.buffer_snapshot.git_diff_hunks_in_range(
 9255                    MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 9256                ),
 9257                cx,
 9258            );
 9259        }
 9260    }
 9261
 9262    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9263        let snapshot = self
 9264            .display_map
 9265            .update(cx, |display_map, cx| display_map.snapshot(cx));
 9266        let selection = self.selections.newest::<Point>(cx);
 9267
 9268        if !self.seek_in_direction(
 9269            &snapshot,
 9270            selection.head(),
 9271            false,
 9272            snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 9273                MultiBufferRow(0)..MultiBufferRow(selection.head().row),
 9274            ),
 9275            cx,
 9276        ) {
 9277            let wrapped_point = snapshot.buffer_snapshot.max_point();
 9278            self.seek_in_direction(
 9279                &snapshot,
 9280                wrapped_point,
 9281                true,
 9282                snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 9283                    MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
 9284                ),
 9285                cx,
 9286            );
 9287        }
 9288    }
 9289
 9290    fn seek_in_direction(
 9291        &mut self,
 9292        snapshot: &DisplaySnapshot,
 9293        initial_point: Point,
 9294        is_wrapped: bool,
 9295        hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
 9296        cx: &mut ViewContext<Editor>,
 9297    ) -> bool {
 9298        let display_point = initial_point.to_display_point(snapshot);
 9299        let mut hunks = hunks
 9300            .map(|hunk| diff_hunk_to_display(&hunk, snapshot))
 9301            .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
 9302            .dedup();
 9303
 9304        if let Some(hunk) = hunks.next() {
 9305            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9306                let row = hunk.start_display_row();
 9307                let point = DisplayPoint::new(row, 0);
 9308                s.select_display_ranges([point..point]);
 9309            });
 9310
 9311            true
 9312        } else {
 9313            false
 9314        }
 9315    }
 9316
 9317    pub fn go_to_definition(
 9318        &mut self,
 9319        _: &GoToDefinition,
 9320        cx: &mut ViewContext<Self>,
 9321    ) -> Task<Result<Navigated>> {
 9322        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9323        cx.spawn(|editor, mut cx| async move {
 9324            if definition.await? == Navigated::Yes {
 9325                return Ok(Navigated::Yes);
 9326            }
 9327            match editor.update(&mut cx, |editor, cx| {
 9328                editor.find_all_references(&FindAllReferences, cx)
 9329            })? {
 9330                Some(references) => references.await,
 9331                None => Ok(Navigated::No),
 9332            }
 9333        })
 9334    }
 9335
 9336    pub fn go_to_declaration(
 9337        &mut self,
 9338        _: &GoToDeclaration,
 9339        cx: &mut ViewContext<Self>,
 9340    ) -> Task<Result<Navigated>> {
 9341        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9342    }
 9343
 9344    pub fn go_to_declaration_split(
 9345        &mut self,
 9346        _: &GoToDeclaration,
 9347        cx: &mut ViewContext<Self>,
 9348    ) -> Task<Result<Navigated>> {
 9349        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9350    }
 9351
 9352    pub fn go_to_implementation(
 9353        &mut self,
 9354        _: &GoToImplementation,
 9355        cx: &mut ViewContext<Self>,
 9356    ) -> Task<Result<Navigated>> {
 9357        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9358    }
 9359
 9360    pub fn go_to_implementation_split(
 9361        &mut self,
 9362        _: &GoToImplementationSplit,
 9363        cx: &mut ViewContext<Self>,
 9364    ) -> Task<Result<Navigated>> {
 9365        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9366    }
 9367
 9368    pub fn go_to_type_definition(
 9369        &mut self,
 9370        _: &GoToTypeDefinition,
 9371        cx: &mut ViewContext<Self>,
 9372    ) -> Task<Result<Navigated>> {
 9373        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9374    }
 9375
 9376    pub fn go_to_definition_split(
 9377        &mut self,
 9378        _: &GoToDefinitionSplit,
 9379        cx: &mut ViewContext<Self>,
 9380    ) -> Task<Result<Navigated>> {
 9381        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9382    }
 9383
 9384    pub fn go_to_type_definition_split(
 9385        &mut self,
 9386        _: &GoToTypeDefinitionSplit,
 9387        cx: &mut ViewContext<Self>,
 9388    ) -> Task<Result<Navigated>> {
 9389        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9390    }
 9391
 9392    fn go_to_definition_of_kind(
 9393        &mut self,
 9394        kind: GotoDefinitionKind,
 9395        split: bool,
 9396        cx: &mut ViewContext<Self>,
 9397    ) -> Task<Result<Navigated>> {
 9398        let Some(workspace) = self.workspace() else {
 9399            return Task::ready(Ok(Navigated::No));
 9400        };
 9401        let buffer = self.buffer.read(cx);
 9402        let head = self.selections.newest::<usize>(cx).head();
 9403        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9404            text_anchor
 9405        } else {
 9406            return Task::ready(Ok(Navigated::No));
 9407        };
 9408
 9409        let project = workspace.read(cx).project().clone();
 9410        let definitions = project.update(cx, |project, cx| match kind {
 9411            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 9412            GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
 9413            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 9414            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 9415        });
 9416
 9417        cx.spawn(|editor, mut cx| async move {
 9418            let definitions = definitions.await?;
 9419            let navigated = editor
 9420                .update(&mut cx, |editor, cx| {
 9421                    editor.navigate_to_hover_links(
 9422                        Some(kind),
 9423                        definitions
 9424                            .into_iter()
 9425                            .filter(|location| {
 9426                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9427                            })
 9428                            .map(HoverLink::Text)
 9429                            .collect::<Vec<_>>(),
 9430                        split,
 9431                        cx,
 9432                    )
 9433                })?
 9434                .await?;
 9435            anyhow::Ok(navigated)
 9436        })
 9437    }
 9438
 9439    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9440        let position = self.selections.newest_anchor().head();
 9441        let Some((buffer, buffer_position)) =
 9442            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9443        else {
 9444            return;
 9445        };
 9446
 9447        cx.spawn(|editor, mut cx| async move {
 9448            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9449                editor.update(&mut cx, |_, cx| {
 9450                    cx.open_url(&url);
 9451                })
 9452            } else {
 9453                Ok(())
 9454            }
 9455        })
 9456        .detach();
 9457    }
 9458
 9459    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9460        let Some(workspace) = self.workspace() else {
 9461            return;
 9462        };
 9463
 9464        let position = self.selections.newest_anchor().head();
 9465
 9466        let Some((buffer, buffer_position)) =
 9467            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9468        else {
 9469            return;
 9470        };
 9471
 9472        let Some(project) = self.project.clone() else {
 9473            return;
 9474        };
 9475
 9476        cx.spawn(|_, mut cx| async move {
 9477            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9478
 9479            if let Some((_, path)) = result {
 9480                workspace
 9481                    .update(&mut cx, |workspace, cx| {
 9482                        workspace.open_resolved_path(path, cx)
 9483                    })?
 9484                    .await?;
 9485            }
 9486            anyhow::Ok(())
 9487        })
 9488        .detach();
 9489    }
 9490
 9491    pub(crate) fn navigate_to_hover_links(
 9492        &mut self,
 9493        kind: Option<GotoDefinitionKind>,
 9494        mut definitions: Vec<HoverLink>,
 9495        split: bool,
 9496        cx: &mut ViewContext<Editor>,
 9497    ) -> Task<Result<Navigated>> {
 9498        // If there is one definition, just open it directly
 9499        if definitions.len() == 1 {
 9500            let definition = definitions.pop().unwrap();
 9501
 9502            enum TargetTaskResult {
 9503                Location(Option<Location>),
 9504                AlreadyNavigated,
 9505            }
 9506
 9507            let target_task = match definition {
 9508                HoverLink::Text(link) => {
 9509                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9510                }
 9511                HoverLink::InlayHint(lsp_location, server_id) => {
 9512                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9513                    cx.background_executor().spawn(async move {
 9514                        let location = computation.await?;
 9515                        Ok(TargetTaskResult::Location(location))
 9516                    })
 9517                }
 9518                HoverLink::Url(url) => {
 9519                    cx.open_url(&url);
 9520                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9521                }
 9522                HoverLink::File(path) => {
 9523                    if let Some(workspace) = self.workspace() {
 9524                        cx.spawn(|_, mut cx| async move {
 9525                            workspace
 9526                                .update(&mut cx, |workspace, cx| {
 9527                                    workspace.open_resolved_path(path, cx)
 9528                                })?
 9529                                .await
 9530                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9531                        })
 9532                    } else {
 9533                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9534                    }
 9535                }
 9536            };
 9537            cx.spawn(|editor, mut cx| async move {
 9538                let target = match target_task.await.context("target resolution task")? {
 9539                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9540                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9541                    TargetTaskResult::Location(Some(target)) => target,
 9542                };
 9543
 9544                editor.update(&mut cx, |editor, cx| {
 9545                    let Some(workspace) = editor.workspace() else {
 9546                        return Navigated::No;
 9547                    };
 9548                    let pane = workspace.read(cx).active_pane().clone();
 9549
 9550                    let range = target.range.to_offset(target.buffer.read(cx));
 9551                    let range = editor.range_for_match(&range);
 9552
 9553                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9554                        let buffer = target.buffer.read(cx);
 9555                        let range = check_multiline_range(buffer, range);
 9556                        editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 9557                            s.select_ranges([range]);
 9558                        });
 9559                    } else {
 9560                        cx.window_context().defer(move |cx| {
 9561                            let target_editor: View<Self> =
 9562                                workspace.update(cx, |workspace, cx| {
 9563                                    let pane = if split {
 9564                                        workspace.adjacent_pane(cx)
 9565                                    } else {
 9566                                        workspace.active_pane().clone()
 9567                                    };
 9568
 9569                                    workspace.open_project_item(
 9570                                        pane,
 9571                                        target.buffer.clone(),
 9572                                        true,
 9573                                        true,
 9574                                        cx,
 9575                                    )
 9576                                });
 9577                            target_editor.update(cx, |target_editor, cx| {
 9578                                // When selecting a definition in a different buffer, disable the nav history
 9579                                // to avoid creating a history entry at the previous cursor location.
 9580                                pane.update(cx, |pane, _| pane.disable_history());
 9581                                let buffer = target.buffer.read(cx);
 9582                                let range = check_multiline_range(buffer, range);
 9583                                target_editor.change_selections(
 9584                                    Some(Autoscroll::focused()),
 9585                                    cx,
 9586                                    |s| {
 9587                                        s.select_ranges([range]);
 9588                                    },
 9589                                );
 9590                                pane.update(cx, |pane, _| pane.enable_history());
 9591                            });
 9592                        });
 9593                    }
 9594                    Navigated::Yes
 9595                })
 9596            })
 9597        } else if !definitions.is_empty() {
 9598            let replica_id = self.replica_id(cx);
 9599            cx.spawn(|editor, mut cx| async move {
 9600                let (title, location_tasks, workspace) = editor
 9601                    .update(&mut cx, |editor, cx| {
 9602                        let tab_kind = match kind {
 9603                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9604                            _ => "Definitions",
 9605                        };
 9606                        let title = definitions
 9607                            .iter()
 9608                            .find_map(|definition| match definition {
 9609                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9610                                    let buffer = origin.buffer.read(cx);
 9611                                    format!(
 9612                                        "{} for {}",
 9613                                        tab_kind,
 9614                                        buffer
 9615                                            .text_for_range(origin.range.clone())
 9616                                            .collect::<String>()
 9617                                    )
 9618                                }),
 9619                                HoverLink::InlayHint(_, _) => None,
 9620                                HoverLink::Url(_) => None,
 9621                                HoverLink::File(_) => None,
 9622                            })
 9623                            .unwrap_or(tab_kind.to_string());
 9624                        let location_tasks = definitions
 9625                            .into_iter()
 9626                            .map(|definition| match definition {
 9627                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9628                                HoverLink::InlayHint(lsp_location, server_id) => {
 9629                                    editor.compute_target_location(lsp_location, server_id, cx)
 9630                                }
 9631                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9632                                HoverLink::File(_) => Task::ready(Ok(None)),
 9633                            })
 9634                            .collect::<Vec<_>>();
 9635                        (title, location_tasks, editor.workspace().clone())
 9636                    })
 9637                    .context("location tasks preparation")?;
 9638
 9639                let locations = futures::future::join_all(location_tasks)
 9640                    .await
 9641                    .into_iter()
 9642                    .filter_map(|location| location.transpose())
 9643                    .collect::<Result<_>>()
 9644                    .context("location tasks")?;
 9645
 9646                let Some(workspace) = workspace else {
 9647                    return Ok(Navigated::No);
 9648                };
 9649                let opened = workspace
 9650                    .update(&mut cx, |workspace, cx| {
 9651                        Self::open_locations_in_multibuffer(
 9652                            workspace, locations, replica_id, title, split, cx,
 9653                        )
 9654                    })
 9655                    .ok();
 9656
 9657                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9658            })
 9659        } else {
 9660            Task::ready(Ok(Navigated::No))
 9661        }
 9662    }
 9663
 9664    fn compute_target_location(
 9665        &self,
 9666        lsp_location: lsp::Location,
 9667        server_id: LanguageServerId,
 9668        cx: &mut ViewContext<Editor>,
 9669    ) -> Task<anyhow::Result<Option<Location>>> {
 9670        let Some(project) = self.project.clone() else {
 9671            return Task::Ready(Some(Ok(None)));
 9672        };
 9673
 9674        cx.spawn(move |editor, mut cx| async move {
 9675            let location_task = editor.update(&mut cx, |editor, cx| {
 9676                project.update(cx, |project, cx| {
 9677                    let language_server_name =
 9678                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 9679                            project
 9680                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 9681                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 9682                        });
 9683                    language_server_name.map(|language_server_name| {
 9684                        project.open_local_buffer_via_lsp(
 9685                            lsp_location.uri.clone(),
 9686                            server_id,
 9687                            language_server_name,
 9688                            cx,
 9689                        )
 9690                    })
 9691                })
 9692            })?;
 9693            let location = match location_task {
 9694                Some(task) => Some({
 9695                    let target_buffer_handle = task.await.context("open local buffer")?;
 9696                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9697                        let target_start = target_buffer
 9698                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9699                        let target_end = target_buffer
 9700                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9701                        target_buffer.anchor_after(target_start)
 9702                            ..target_buffer.anchor_before(target_end)
 9703                    })?;
 9704                    Location {
 9705                        buffer: target_buffer_handle,
 9706                        range,
 9707                    }
 9708                }),
 9709                None => None,
 9710            };
 9711            Ok(location)
 9712        })
 9713    }
 9714
 9715    pub fn find_all_references(
 9716        &mut self,
 9717        _: &FindAllReferences,
 9718        cx: &mut ViewContext<Self>,
 9719    ) -> Option<Task<Result<Navigated>>> {
 9720        let multi_buffer = self.buffer.read(cx);
 9721        let selection = self.selections.newest::<usize>(cx);
 9722        let head = selection.head();
 9723
 9724        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9725        let head_anchor = multi_buffer_snapshot.anchor_at(
 9726            head,
 9727            if head < selection.tail() {
 9728                Bias::Right
 9729            } else {
 9730                Bias::Left
 9731            },
 9732        );
 9733
 9734        match self
 9735            .find_all_references_task_sources
 9736            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9737        {
 9738            Ok(_) => {
 9739                log::info!(
 9740                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9741                );
 9742                return None;
 9743            }
 9744            Err(i) => {
 9745                self.find_all_references_task_sources.insert(i, head_anchor);
 9746            }
 9747        }
 9748
 9749        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9750        let replica_id = self.replica_id(cx);
 9751        let workspace = self.workspace()?;
 9752        let project = workspace.read(cx).project().clone();
 9753        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9754        Some(cx.spawn(|editor, mut cx| async move {
 9755            let _cleanup = defer({
 9756                let mut cx = cx.clone();
 9757                move || {
 9758                    let _ = editor.update(&mut cx, |editor, _| {
 9759                        if let Ok(i) =
 9760                            editor
 9761                                .find_all_references_task_sources
 9762                                .binary_search_by(|anchor| {
 9763                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9764                                })
 9765                        {
 9766                            editor.find_all_references_task_sources.remove(i);
 9767                        }
 9768                    });
 9769                }
 9770            });
 9771
 9772            let locations = references.await?;
 9773            if locations.is_empty() {
 9774                return anyhow::Ok(Navigated::No);
 9775            }
 9776
 9777            workspace.update(&mut cx, |workspace, cx| {
 9778                let title = locations
 9779                    .first()
 9780                    .as_ref()
 9781                    .map(|location| {
 9782                        let buffer = location.buffer.read(cx);
 9783                        format!(
 9784                            "References to `{}`",
 9785                            buffer
 9786                                .text_for_range(location.range.clone())
 9787                                .collect::<String>()
 9788                        )
 9789                    })
 9790                    .unwrap();
 9791                Self::open_locations_in_multibuffer(
 9792                    workspace, locations, replica_id, title, false, cx,
 9793                );
 9794                Navigated::Yes
 9795            })
 9796        }))
 9797    }
 9798
 9799    /// Opens a multibuffer with the given project locations in it
 9800    pub fn open_locations_in_multibuffer(
 9801        workspace: &mut Workspace,
 9802        mut locations: Vec<Location>,
 9803        replica_id: ReplicaId,
 9804        title: String,
 9805        split: bool,
 9806        cx: &mut ViewContext<Workspace>,
 9807    ) {
 9808        // If there are multiple definitions, open them in a multibuffer
 9809        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9810        let mut locations = locations.into_iter().peekable();
 9811        let mut ranges_to_highlight = Vec::new();
 9812        let capability = workspace.project().read(cx).capability();
 9813
 9814        let excerpt_buffer = cx.new_model(|cx| {
 9815            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 9816            while let Some(location) = locations.next() {
 9817                let buffer = location.buffer.read(cx);
 9818                let mut ranges_for_buffer = Vec::new();
 9819                let range = location.range.to_offset(buffer);
 9820                ranges_for_buffer.push(range.clone());
 9821
 9822                while let Some(next_location) = locations.peek() {
 9823                    if next_location.buffer == location.buffer {
 9824                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9825                        locations.next();
 9826                    } else {
 9827                        break;
 9828                    }
 9829                }
 9830
 9831                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9832                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9833                    location.buffer.clone(),
 9834                    ranges_for_buffer,
 9835                    DEFAULT_MULTIBUFFER_CONTEXT,
 9836                    cx,
 9837                ))
 9838            }
 9839
 9840            multibuffer.with_title(title)
 9841        });
 9842
 9843        let editor = cx.new_view(|cx| {
 9844            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9845        });
 9846        editor.update(cx, |editor, cx| {
 9847            if let Some(first_range) = ranges_to_highlight.first() {
 9848                editor.change_selections(None, cx, |selections| {
 9849                    selections.clear_disjoint();
 9850                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9851                });
 9852            }
 9853            editor.highlight_background::<Self>(
 9854                &ranges_to_highlight,
 9855                |theme| theme.editor_highlighted_line_background,
 9856                cx,
 9857            );
 9858        });
 9859
 9860        let item = Box::new(editor);
 9861        let item_id = item.item_id();
 9862
 9863        if split {
 9864            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9865        } else {
 9866            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9867                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9868                    pane.close_current_preview_item(cx)
 9869                } else {
 9870                    None
 9871                }
 9872            });
 9873            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9874        }
 9875        workspace.active_pane().update(cx, |pane, cx| {
 9876            pane.set_preview_item_id(Some(item_id), cx);
 9877        });
 9878    }
 9879
 9880    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9881        use language::ToOffset as _;
 9882
 9883        let project = self.project.clone()?;
 9884        let selection = self.selections.newest_anchor().clone();
 9885        let (cursor_buffer, cursor_buffer_position) = self
 9886            .buffer
 9887            .read(cx)
 9888            .text_anchor_for_position(selection.head(), cx)?;
 9889        let (tail_buffer, cursor_buffer_position_end) = self
 9890            .buffer
 9891            .read(cx)
 9892            .text_anchor_for_position(selection.tail(), cx)?;
 9893        if tail_buffer != cursor_buffer {
 9894            return None;
 9895        }
 9896
 9897        let snapshot = cursor_buffer.read(cx).snapshot();
 9898        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9899        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9900        let prepare_rename = project.update(cx, |project, cx| {
 9901            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 9902        });
 9903        drop(snapshot);
 9904
 9905        Some(cx.spawn(|this, mut cx| async move {
 9906            let rename_range = if let Some(range) = prepare_rename.await? {
 9907                Some(range)
 9908            } else {
 9909                this.update(&mut cx, |this, cx| {
 9910                    let buffer = this.buffer.read(cx).snapshot(cx);
 9911                    let mut buffer_highlights = this
 9912                        .document_highlights_for_position(selection.head(), &buffer)
 9913                        .filter(|highlight| {
 9914                            highlight.start.excerpt_id == selection.head().excerpt_id
 9915                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9916                        });
 9917                    buffer_highlights
 9918                        .next()
 9919                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9920                })?
 9921            };
 9922            if let Some(rename_range) = rename_range {
 9923                this.update(&mut cx, |this, cx| {
 9924                    let snapshot = cursor_buffer.read(cx).snapshot();
 9925                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9926                    let cursor_offset_in_rename_range =
 9927                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9928                    let cursor_offset_in_rename_range_end =
 9929                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9930
 9931                    this.take_rename(false, cx);
 9932                    let buffer = this.buffer.read(cx).read(cx);
 9933                    let cursor_offset = selection.head().to_offset(&buffer);
 9934                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9935                    let rename_end = rename_start + rename_buffer_range.len();
 9936                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9937                    let mut old_highlight_id = None;
 9938                    let old_name: Arc<str> = buffer
 9939                        .chunks(rename_start..rename_end, true)
 9940                        .map(|chunk| {
 9941                            if old_highlight_id.is_none() {
 9942                                old_highlight_id = chunk.syntax_highlight_id;
 9943                            }
 9944                            chunk.text
 9945                        })
 9946                        .collect::<String>()
 9947                        .into();
 9948
 9949                    drop(buffer);
 9950
 9951                    // Position the selection in the rename editor so that it matches the current selection.
 9952                    this.show_local_selections = false;
 9953                    let rename_editor = cx.new_view(|cx| {
 9954                        let mut editor = Editor::single_line(cx);
 9955                        editor.buffer.update(cx, |buffer, cx| {
 9956                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9957                        });
 9958                        let rename_selection_range = match cursor_offset_in_rename_range
 9959                            .cmp(&cursor_offset_in_rename_range_end)
 9960                        {
 9961                            Ordering::Equal => {
 9962                                editor.select_all(&SelectAll, cx);
 9963                                return editor;
 9964                            }
 9965                            Ordering::Less => {
 9966                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9967                            }
 9968                            Ordering::Greater => {
 9969                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9970                            }
 9971                        };
 9972                        if rename_selection_range.end > old_name.len() {
 9973                            editor.select_all(&SelectAll, cx);
 9974                        } else {
 9975                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9976                                s.select_ranges([rename_selection_range]);
 9977                            });
 9978                        }
 9979                        editor
 9980                    });
 9981                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
 9982                        if e == &EditorEvent::Focused {
 9983                            cx.emit(EditorEvent::FocusedIn)
 9984                        }
 9985                    })
 9986                    .detach();
 9987
 9988                    let write_highlights =
 9989                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9990                    let read_highlights =
 9991                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9992                    let ranges = write_highlights
 9993                        .iter()
 9994                        .flat_map(|(_, ranges)| ranges.iter())
 9995                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9996                        .cloned()
 9997                        .collect();
 9998
 9999                    this.highlight_text::<Rename>(
10000                        ranges,
10001                        HighlightStyle {
10002                            fade_out: Some(0.6),
10003                            ..Default::default()
10004                        },
10005                        cx,
10006                    );
10007                    let rename_focus_handle = rename_editor.focus_handle(cx);
10008                    cx.focus(&rename_focus_handle);
10009                    let block_id = this.insert_blocks(
10010                        [BlockProperties {
10011                            style: BlockStyle::Flex,
10012                            position: range.start,
10013                            height: 1,
10014                            render: Box::new({
10015                                let rename_editor = rename_editor.clone();
10016                                move |cx: &mut BlockContext| {
10017                                    let mut text_style = cx.editor_style.text.clone();
10018                                    if let Some(highlight_style) = old_highlight_id
10019                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10020                                    {
10021                                        text_style = text_style.highlight(highlight_style);
10022                                    }
10023                                    div()
10024                                        .pl(cx.anchor_x)
10025                                        .child(EditorElement::new(
10026                                            &rename_editor,
10027                                            EditorStyle {
10028                                                background: cx.theme().system().transparent,
10029                                                local_player: cx.editor_style.local_player,
10030                                                text: text_style,
10031                                                scrollbar_width: cx.editor_style.scrollbar_width,
10032                                                syntax: cx.editor_style.syntax.clone(),
10033                                                status: cx.editor_style.status.clone(),
10034                                                inlay_hints_style: HighlightStyle {
10035                                                    color: Some(cx.theme().status().hint),
10036                                                    font_weight: Some(FontWeight::BOLD),
10037                                                    ..HighlightStyle::default()
10038                                                },
10039                                                suggestions_style: HighlightStyle {
10040                                                    color: Some(cx.theme().status().predictive),
10041                                                    ..HighlightStyle::default()
10042                                                },
10043                                                ..EditorStyle::default()
10044                                            },
10045                                        ))
10046                                        .into_any_element()
10047                                }
10048                            }),
10049                            disposition: BlockDisposition::Below,
10050                            priority: 0,
10051                        }],
10052                        Some(Autoscroll::fit()),
10053                        cx,
10054                    )[0];
10055                    this.pending_rename = Some(RenameState {
10056                        range,
10057                        old_name,
10058                        editor: rename_editor,
10059                        block_id,
10060                    });
10061                })?;
10062            }
10063
10064            Ok(())
10065        }))
10066    }
10067
10068    pub fn confirm_rename(
10069        &mut self,
10070        _: &ConfirmRename,
10071        cx: &mut ViewContext<Self>,
10072    ) -> Option<Task<Result<()>>> {
10073        let rename = self.take_rename(false, cx)?;
10074        let workspace = self.workspace()?;
10075        let (start_buffer, start) = self
10076            .buffer
10077            .read(cx)
10078            .text_anchor_for_position(rename.range.start, cx)?;
10079        let (end_buffer, end) = self
10080            .buffer
10081            .read(cx)
10082            .text_anchor_for_position(rename.range.end, cx)?;
10083        if start_buffer != end_buffer {
10084            return None;
10085        }
10086
10087        let buffer = start_buffer;
10088        let range = start..end;
10089        let old_name = rename.old_name;
10090        let new_name = rename.editor.read(cx).text(cx);
10091
10092        let rename = workspace
10093            .read(cx)
10094            .project()
10095            .clone()
10096            .update(cx, |project, cx| {
10097                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
10098            });
10099        let workspace = workspace.downgrade();
10100
10101        Some(cx.spawn(|editor, mut cx| async move {
10102            let project_transaction = rename.await?;
10103            Self::open_project_transaction(
10104                &editor,
10105                workspace,
10106                project_transaction,
10107                format!("Rename: {}{}", old_name, new_name),
10108                cx.clone(),
10109            )
10110            .await?;
10111
10112            editor.update(&mut cx, |editor, cx| {
10113                editor.refresh_document_highlights(cx);
10114            })?;
10115            Ok(())
10116        }))
10117    }
10118
10119    fn take_rename(
10120        &mut self,
10121        moving_cursor: bool,
10122        cx: &mut ViewContext<Self>,
10123    ) -> Option<RenameState> {
10124        let rename = self.pending_rename.take()?;
10125        if rename.editor.focus_handle(cx).is_focused(cx) {
10126            cx.focus(&self.focus_handle);
10127        }
10128
10129        self.remove_blocks(
10130            [rename.block_id].into_iter().collect(),
10131            Some(Autoscroll::fit()),
10132            cx,
10133        );
10134        self.clear_highlights::<Rename>(cx);
10135        self.show_local_selections = true;
10136
10137        if moving_cursor {
10138            let rename_editor = rename.editor.read(cx);
10139            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10140
10141            // Update the selection to match the position of the selection inside
10142            // the rename editor.
10143            let snapshot = self.buffer.read(cx).read(cx);
10144            let rename_range = rename.range.to_offset(&snapshot);
10145            let cursor_in_editor = snapshot
10146                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10147                .min(rename_range.end);
10148            drop(snapshot);
10149
10150            self.change_selections(None, cx, |s| {
10151                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10152            });
10153        } else {
10154            self.refresh_document_highlights(cx);
10155        }
10156
10157        Some(rename)
10158    }
10159
10160    pub fn pending_rename(&self) -> Option<&RenameState> {
10161        self.pending_rename.as_ref()
10162    }
10163
10164    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10165        let project = match &self.project {
10166            Some(project) => project.clone(),
10167            None => return None,
10168        };
10169
10170        Some(self.perform_format(project, FormatTrigger::Manual, cx))
10171    }
10172
10173    fn perform_format(
10174        &mut self,
10175        project: Model<Project>,
10176        trigger: FormatTrigger,
10177        cx: &mut ViewContext<Self>,
10178    ) -> Task<Result<()>> {
10179        let buffer = self.buffer().clone();
10180        let mut buffers = buffer.read(cx).all_buffers();
10181        if trigger == FormatTrigger::Save {
10182            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10183        }
10184
10185        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10186        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
10187
10188        cx.spawn(|_, mut cx| async move {
10189            let transaction = futures::select_biased! {
10190                () = timeout => {
10191                    log::warn!("timed out waiting for formatting");
10192                    None
10193                }
10194                transaction = format.log_err().fuse() => transaction,
10195            };
10196
10197            buffer
10198                .update(&mut cx, |buffer, cx| {
10199                    if let Some(transaction) = transaction {
10200                        if !buffer.is_singleton() {
10201                            buffer.push_transaction(&transaction.0, cx);
10202                        }
10203                    }
10204
10205                    cx.notify();
10206                })
10207                .ok();
10208
10209            Ok(())
10210        })
10211    }
10212
10213    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10214        if let Some(project) = self.project.clone() {
10215            self.buffer.update(cx, |multi_buffer, cx| {
10216                project.update(cx, |project, cx| {
10217                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10218                });
10219            })
10220        }
10221    }
10222
10223    fn cancel_language_server_work(
10224        &mut self,
10225        _: &CancelLanguageServerWork,
10226        cx: &mut ViewContext<Self>,
10227    ) {
10228        if let Some(project) = self.project.clone() {
10229            self.buffer.update(cx, |multi_buffer, cx| {
10230                project.update(cx, |project, cx| {
10231                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10232                });
10233            })
10234        }
10235    }
10236
10237    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10238        cx.show_character_palette();
10239    }
10240
10241    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10242        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10243            let buffer = self.buffer.read(cx).snapshot(cx);
10244            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10245            let is_valid = buffer
10246                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10247                .any(|entry| {
10248                    entry.diagnostic.is_primary
10249                        && !entry.range.is_empty()
10250                        && entry.range.start == primary_range_start
10251                        && entry.diagnostic.message == active_diagnostics.primary_message
10252                });
10253
10254            if is_valid != active_diagnostics.is_valid {
10255                active_diagnostics.is_valid = is_valid;
10256                let mut new_styles = HashMap::default();
10257                for (block_id, diagnostic) in &active_diagnostics.blocks {
10258                    new_styles.insert(
10259                        *block_id,
10260                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10261                    );
10262                }
10263                self.display_map.update(cx, |display_map, _cx| {
10264                    display_map.replace_blocks(new_styles)
10265                });
10266            }
10267        }
10268    }
10269
10270    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10271        self.dismiss_diagnostics(cx);
10272        let snapshot = self.snapshot(cx);
10273        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10274            let buffer = self.buffer.read(cx).snapshot(cx);
10275
10276            let mut primary_range = None;
10277            let mut primary_message = None;
10278            let mut group_end = Point::zero();
10279            let diagnostic_group = buffer
10280                .diagnostic_group::<MultiBufferPoint>(group_id)
10281                .filter_map(|entry| {
10282                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10283                        && (entry.range.start.row == entry.range.end.row
10284                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10285                    {
10286                        return None;
10287                    }
10288                    if entry.range.end > group_end {
10289                        group_end = entry.range.end;
10290                    }
10291                    if entry.diagnostic.is_primary {
10292                        primary_range = Some(entry.range.clone());
10293                        primary_message = Some(entry.diagnostic.message.clone());
10294                    }
10295                    Some(entry)
10296                })
10297                .collect::<Vec<_>>();
10298            let primary_range = primary_range?;
10299            let primary_message = primary_message?;
10300            let primary_range =
10301                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10302
10303            let blocks = display_map
10304                .insert_blocks(
10305                    diagnostic_group.iter().map(|entry| {
10306                        let diagnostic = entry.diagnostic.clone();
10307                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10308                        BlockProperties {
10309                            style: BlockStyle::Fixed,
10310                            position: buffer.anchor_after(entry.range.start),
10311                            height: message_height,
10312                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10313                            disposition: BlockDisposition::Below,
10314                            priority: 0,
10315                        }
10316                    }),
10317                    cx,
10318                )
10319                .into_iter()
10320                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10321                .collect();
10322
10323            Some(ActiveDiagnosticGroup {
10324                primary_range,
10325                primary_message,
10326                group_id,
10327                blocks,
10328                is_valid: true,
10329            })
10330        });
10331        self.active_diagnostics.is_some()
10332    }
10333
10334    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10335        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10336            self.display_map.update(cx, |display_map, cx| {
10337                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10338            });
10339            cx.notify();
10340        }
10341    }
10342
10343    pub fn set_selections_from_remote(
10344        &mut self,
10345        selections: Vec<Selection<Anchor>>,
10346        pending_selection: Option<Selection<Anchor>>,
10347        cx: &mut ViewContext<Self>,
10348    ) {
10349        let old_cursor_position = self.selections.newest_anchor().head();
10350        self.selections.change_with(cx, |s| {
10351            s.select_anchors(selections);
10352            if let Some(pending_selection) = pending_selection {
10353                s.set_pending(pending_selection, SelectMode::Character);
10354            } else {
10355                s.clear_pending();
10356            }
10357        });
10358        self.selections_did_change(false, &old_cursor_position, true, cx);
10359    }
10360
10361    fn push_to_selection_history(&mut self) {
10362        self.selection_history.push(SelectionHistoryEntry {
10363            selections: self.selections.disjoint_anchors(),
10364            select_next_state: self.select_next_state.clone(),
10365            select_prev_state: self.select_prev_state.clone(),
10366            add_selections_state: self.add_selections_state.clone(),
10367        });
10368    }
10369
10370    pub fn transact(
10371        &mut self,
10372        cx: &mut ViewContext<Self>,
10373        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10374    ) -> Option<TransactionId> {
10375        self.start_transaction_at(Instant::now(), cx);
10376        update(self, cx);
10377        self.end_transaction_at(Instant::now(), cx)
10378    }
10379
10380    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10381        self.end_selection(cx);
10382        if let Some(tx_id) = self
10383            .buffer
10384            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10385        {
10386            self.selection_history
10387                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10388            cx.emit(EditorEvent::TransactionBegun {
10389                transaction_id: tx_id,
10390            })
10391        }
10392    }
10393
10394    fn end_transaction_at(
10395        &mut self,
10396        now: Instant,
10397        cx: &mut ViewContext<Self>,
10398    ) -> Option<TransactionId> {
10399        if let Some(transaction_id) = self
10400            .buffer
10401            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10402        {
10403            if let Some((_, end_selections)) =
10404                self.selection_history.transaction_mut(transaction_id)
10405            {
10406                *end_selections = Some(self.selections.disjoint_anchors());
10407            } else {
10408                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10409            }
10410
10411            cx.emit(EditorEvent::Edited { transaction_id });
10412            Some(transaction_id)
10413        } else {
10414            None
10415        }
10416    }
10417
10418    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10419        let mut fold_ranges = Vec::new();
10420
10421        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10422
10423        let selections = self.selections.all_adjusted(cx);
10424        for selection in selections {
10425            let range = selection.range().sorted();
10426            let buffer_start_row = range.start.row;
10427
10428            for row in (0..=range.end.row).rev() {
10429                if let Some((foldable_range, fold_text)) =
10430                    display_map.foldable_range(MultiBufferRow(row))
10431                {
10432                    if foldable_range.end.row >= buffer_start_row {
10433                        fold_ranges.push((foldable_range, fold_text));
10434                        if row <= range.start.row {
10435                            break;
10436                        }
10437                    }
10438                }
10439            }
10440        }
10441
10442        self.fold_ranges(fold_ranges, true, cx);
10443    }
10444
10445    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10446        let buffer_row = fold_at.buffer_row;
10447        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10448
10449        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10450            let autoscroll = self
10451                .selections
10452                .all::<Point>(cx)
10453                .iter()
10454                .any(|selection| fold_range.overlaps(&selection.range()));
10455
10456            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10457        }
10458    }
10459
10460    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10461        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10462        let buffer = &display_map.buffer_snapshot;
10463        let selections = self.selections.all::<Point>(cx);
10464        let ranges = selections
10465            .iter()
10466            .map(|s| {
10467                let range = s.display_range(&display_map).sorted();
10468                let mut start = range.start.to_point(&display_map);
10469                let mut end = range.end.to_point(&display_map);
10470                start.column = 0;
10471                end.column = buffer.line_len(MultiBufferRow(end.row));
10472                start..end
10473            })
10474            .collect::<Vec<_>>();
10475
10476        self.unfold_ranges(ranges, true, true, cx);
10477    }
10478
10479    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10480        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10481
10482        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10483            ..Point::new(
10484                unfold_at.buffer_row.0,
10485                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10486            );
10487
10488        let autoscroll = self
10489            .selections
10490            .all::<Point>(cx)
10491            .iter()
10492            .any(|selection| selection.range().overlaps(&intersection_range));
10493
10494        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10495    }
10496
10497    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10498        let selections = self.selections.all::<Point>(cx);
10499        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10500        let line_mode = self.selections.line_mode;
10501        let ranges = selections.into_iter().map(|s| {
10502            if line_mode {
10503                let start = Point::new(s.start.row, 0);
10504                let end = Point::new(
10505                    s.end.row,
10506                    display_map
10507                        .buffer_snapshot
10508                        .line_len(MultiBufferRow(s.end.row)),
10509                );
10510                (start..end, display_map.fold_placeholder.clone())
10511            } else {
10512                (s.start..s.end, display_map.fold_placeholder.clone())
10513            }
10514        });
10515        self.fold_ranges(ranges, true, cx);
10516    }
10517
10518    pub fn fold_ranges<T: ToOffset + Clone>(
10519        &mut self,
10520        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10521        auto_scroll: bool,
10522        cx: &mut ViewContext<Self>,
10523    ) {
10524        let mut fold_ranges = Vec::new();
10525        let mut buffers_affected = HashMap::default();
10526        let multi_buffer = self.buffer().read(cx);
10527        for (fold_range, fold_text) in ranges {
10528            if let Some((_, buffer, _)) =
10529                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10530            {
10531                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10532            };
10533            fold_ranges.push((fold_range, fold_text));
10534        }
10535
10536        let mut ranges = fold_ranges.into_iter().peekable();
10537        if ranges.peek().is_some() {
10538            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10539
10540            if auto_scroll {
10541                self.request_autoscroll(Autoscroll::fit(), cx);
10542            }
10543
10544            for buffer in buffers_affected.into_values() {
10545                self.sync_expanded_diff_hunks(buffer, cx);
10546            }
10547
10548            cx.notify();
10549
10550            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10551                // Clear diagnostics block when folding a range that contains it.
10552                let snapshot = self.snapshot(cx);
10553                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10554                    drop(snapshot);
10555                    self.active_diagnostics = Some(active_diagnostics);
10556                    self.dismiss_diagnostics(cx);
10557                } else {
10558                    self.active_diagnostics = Some(active_diagnostics);
10559                }
10560            }
10561
10562            self.scrollbar_marker_state.dirty = true;
10563        }
10564    }
10565
10566    pub fn unfold_ranges<T: ToOffset + Clone>(
10567        &mut self,
10568        ranges: impl IntoIterator<Item = Range<T>>,
10569        inclusive: bool,
10570        auto_scroll: bool,
10571        cx: &mut ViewContext<Self>,
10572    ) {
10573        let mut unfold_ranges = Vec::new();
10574        let mut buffers_affected = HashMap::default();
10575        let multi_buffer = self.buffer().read(cx);
10576        for range in ranges {
10577            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10578                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10579            };
10580            unfold_ranges.push(range);
10581        }
10582
10583        let mut ranges = unfold_ranges.into_iter().peekable();
10584        if ranges.peek().is_some() {
10585            self.display_map
10586                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10587            if auto_scroll {
10588                self.request_autoscroll(Autoscroll::fit(), cx);
10589            }
10590
10591            for buffer in buffers_affected.into_values() {
10592                self.sync_expanded_diff_hunks(buffer, cx);
10593            }
10594
10595            cx.notify();
10596            self.scrollbar_marker_state.dirty = true;
10597            self.active_indent_guides_state.dirty = true;
10598        }
10599    }
10600
10601    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10602        self.display_map.read(cx).fold_placeholder.clone()
10603    }
10604
10605    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10606        if hovered != self.gutter_hovered {
10607            self.gutter_hovered = hovered;
10608            cx.notify();
10609        }
10610    }
10611
10612    pub fn insert_blocks(
10613        &mut self,
10614        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10615        autoscroll: Option<Autoscroll>,
10616        cx: &mut ViewContext<Self>,
10617    ) -> Vec<CustomBlockId> {
10618        let blocks = self
10619            .display_map
10620            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10621        if let Some(autoscroll) = autoscroll {
10622            self.request_autoscroll(autoscroll, cx);
10623        }
10624        cx.notify();
10625        blocks
10626    }
10627
10628    pub fn resize_blocks(
10629        &mut self,
10630        heights: HashMap<CustomBlockId, u32>,
10631        autoscroll: Option<Autoscroll>,
10632        cx: &mut ViewContext<Self>,
10633    ) {
10634        self.display_map
10635            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10636        if let Some(autoscroll) = autoscroll {
10637            self.request_autoscroll(autoscroll, cx);
10638        }
10639        cx.notify();
10640    }
10641
10642    pub fn replace_blocks(
10643        &mut self,
10644        renderers: HashMap<CustomBlockId, RenderBlock>,
10645        autoscroll: Option<Autoscroll>,
10646        cx: &mut ViewContext<Self>,
10647    ) {
10648        self.display_map
10649            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10650        if let Some(autoscroll) = autoscroll {
10651            self.request_autoscroll(autoscroll, cx);
10652        }
10653        cx.notify();
10654    }
10655
10656    pub fn remove_blocks(
10657        &mut self,
10658        block_ids: HashSet<CustomBlockId>,
10659        autoscroll: Option<Autoscroll>,
10660        cx: &mut ViewContext<Self>,
10661    ) {
10662        self.display_map.update(cx, |display_map, cx| {
10663            display_map.remove_blocks(block_ids, cx)
10664        });
10665        if let Some(autoscroll) = autoscroll {
10666            self.request_autoscroll(autoscroll, cx);
10667        }
10668        cx.notify();
10669    }
10670
10671    pub fn row_for_block(
10672        &self,
10673        block_id: CustomBlockId,
10674        cx: &mut ViewContext<Self>,
10675    ) -> Option<DisplayRow> {
10676        self.display_map
10677            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10678    }
10679
10680    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10681        self.focused_block = Some(focused_block);
10682    }
10683
10684    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10685        self.focused_block.take()
10686    }
10687
10688    pub fn insert_creases(
10689        &mut self,
10690        creases: impl IntoIterator<Item = Crease>,
10691        cx: &mut ViewContext<Self>,
10692    ) -> Vec<CreaseId> {
10693        self.display_map
10694            .update(cx, |map, cx| map.insert_creases(creases, cx))
10695    }
10696
10697    pub fn remove_creases(
10698        &mut self,
10699        ids: impl IntoIterator<Item = CreaseId>,
10700        cx: &mut ViewContext<Self>,
10701    ) {
10702        self.display_map
10703            .update(cx, |map, cx| map.remove_creases(ids, cx));
10704    }
10705
10706    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10707        self.display_map
10708            .update(cx, |map, cx| map.snapshot(cx))
10709            .longest_row()
10710    }
10711
10712    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10713        self.display_map
10714            .update(cx, |map, cx| map.snapshot(cx))
10715            .max_point()
10716    }
10717
10718    pub fn text(&self, cx: &AppContext) -> String {
10719        self.buffer.read(cx).read(cx).text()
10720    }
10721
10722    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10723        let text = self.text(cx);
10724        let text = text.trim();
10725
10726        if text.is_empty() {
10727            return None;
10728        }
10729
10730        Some(text.to_string())
10731    }
10732
10733    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10734        self.transact(cx, |this, cx| {
10735            this.buffer
10736                .read(cx)
10737                .as_singleton()
10738                .expect("you can only call set_text on editors for singleton buffers")
10739                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10740        });
10741    }
10742
10743    pub fn display_text(&self, cx: &mut AppContext) -> String {
10744        self.display_map
10745            .update(cx, |map, cx| map.snapshot(cx))
10746            .text()
10747    }
10748
10749    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10750        let mut wrap_guides = smallvec::smallvec![];
10751
10752        if self.show_wrap_guides == Some(false) {
10753            return wrap_guides;
10754        }
10755
10756        let settings = self.buffer.read(cx).settings_at(0, cx);
10757        if settings.show_wrap_guides {
10758            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10759                wrap_guides.push((soft_wrap as usize, true));
10760            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10761                wrap_guides.push((soft_wrap as usize, true));
10762            }
10763            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10764        }
10765
10766        wrap_guides
10767    }
10768
10769    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10770        let settings = self.buffer.read(cx).settings_at(0, cx);
10771        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10772        match mode {
10773            language_settings::SoftWrap::None => SoftWrap::None,
10774            language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10775            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10776            language_settings::SoftWrap::PreferredLineLength => {
10777                SoftWrap::Column(settings.preferred_line_length)
10778            }
10779            language_settings::SoftWrap::Bounded => {
10780                SoftWrap::Bounded(settings.preferred_line_length)
10781            }
10782        }
10783    }
10784
10785    pub fn set_soft_wrap_mode(
10786        &mut self,
10787        mode: language_settings::SoftWrap,
10788        cx: &mut ViewContext<Self>,
10789    ) {
10790        self.soft_wrap_mode_override = Some(mode);
10791        cx.notify();
10792    }
10793
10794    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10795        let rem_size = cx.rem_size();
10796        self.display_map.update(cx, |map, cx| {
10797            map.set_font(
10798                style.text.font(),
10799                style.text.font_size.to_pixels(rem_size),
10800                cx,
10801            )
10802        });
10803        self.style = Some(style);
10804    }
10805
10806    pub fn style(&self) -> Option<&EditorStyle> {
10807        self.style.as_ref()
10808    }
10809
10810    // Called by the element. This method is not designed to be called outside of the editor
10811    // element's layout code because it does not notify when rewrapping is computed synchronously.
10812    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10813        self.display_map
10814            .update(cx, |map, cx| map.set_wrap_width(width, cx))
10815    }
10816
10817    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10818        if self.soft_wrap_mode_override.is_some() {
10819            self.soft_wrap_mode_override.take();
10820        } else {
10821            let soft_wrap = match self.soft_wrap_mode(cx) {
10822                SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10823                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10824                    language_settings::SoftWrap::PreferLine
10825                }
10826            };
10827            self.soft_wrap_mode_override = Some(soft_wrap);
10828        }
10829        cx.notify();
10830    }
10831
10832    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10833        let Some(workspace) = self.workspace() else {
10834            return;
10835        };
10836        let fs = workspace.read(cx).app_state().fs.clone();
10837        let current_show = TabBarSettings::get_global(cx).show;
10838        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10839            setting.show = Some(!current_show);
10840        });
10841    }
10842
10843    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10844        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10845            self.buffer
10846                .read(cx)
10847                .settings_at(0, cx)
10848                .indent_guides
10849                .enabled
10850        });
10851        self.show_indent_guides = Some(!currently_enabled);
10852        cx.notify();
10853    }
10854
10855    fn should_show_indent_guides(&self) -> Option<bool> {
10856        self.show_indent_guides
10857    }
10858
10859    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10860        let mut editor_settings = EditorSettings::get_global(cx).clone();
10861        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10862        EditorSettings::override_global(editor_settings, cx);
10863    }
10864
10865    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10866        self.use_relative_line_numbers
10867            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10868    }
10869
10870    pub fn toggle_relative_line_numbers(
10871        &mut self,
10872        _: &ToggleRelativeLineNumbers,
10873        cx: &mut ViewContext<Self>,
10874    ) {
10875        let is_relative = self.should_use_relative_line_numbers(cx);
10876        self.set_relative_line_number(Some(!is_relative), cx)
10877    }
10878
10879    pub fn set_relative_line_number(
10880        &mut self,
10881        is_relative: Option<bool>,
10882        cx: &mut ViewContext<Self>,
10883    ) {
10884        self.use_relative_line_numbers = is_relative;
10885        cx.notify();
10886    }
10887
10888    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10889        self.show_gutter = show_gutter;
10890        cx.notify();
10891    }
10892
10893    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10894        self.show_line_numbers = Some(show_line_numbers);
10895        cx.notify();
10896    }
10897
10898    pub fn set_show_git_diff_gutter(
10899        &mut self,
10900        show_git_diff_gutter: bool,
10901        cx: &mut ViewContext<Self>,
10902    ) {
10903        self.show_git_diff_gutter = Some(show_git_diff_gutter);
10904        cx.notify();
10905    }
10906
10907    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10908        self.show_code_actions = Some(show_code_actions);
10909        cx.notify();
10910    }
10911
10912    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10913        self.show_runnables = Some(show_runnables);
10914        cx.notify();
10915    }
10916
10917    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10918        if self.display_map.read(cx).masked != masked {
10919            self.display_map.update(cx, |map, _| map.masked = masked);
10920        }
10921        cx.notify()
10922    }
10923
10924    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10925        self.show_wrap_guides = Some(show_wrap_guides);
10926        cx.notify();
10927    }
10928
10929    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10930        self.show_indent_guides = Some(show_indent_guides);
10931        cx.notify();
10932    }
10933
10934    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10935        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10936            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10937                if let Some(dir) = file.abs_path(cx).parent() {
10938                    return Some(dir.to_owned());
10939                }
10940            }
10941
10942            if let Some(project_path) = buffer.read(cx).project_path(cx) {
10943                return Some(project_path.path.to_path_buf());
10944            }
10945        }
10946
10947        None
10948    }
10949
10950    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10951        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10952            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10953                cx.reveal_path(&file.abs_path(cx));
10954            }
10955        }
10956    }
10957
10958    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10959        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10960            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10961                if let Some(path) = file.abs_path(cx).to_str() {
10962                    cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10963                }
10964            }
10965        }
10966    }
10967
10968    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10969        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10970            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10971                if let Some(path) = file.path().to_str() {
10972                    cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10973                }
10974            }
10975        }
10976    }
10977
10978    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10979        self.show_git_blame_gutter = !self.show_git_blame_gutter;
10980
10981        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10982            self.start_git_blame(true, cx);
10983        }
10984
10985        cx.notify();
10986    }
10987
10988    pub fn toggle_git_blame_inline(
10989        &mut self,
10990        _: &ToggleGitBlameInline,
10991        cx: &mut ViewContext<Self>,
10992    ) {
10993        self.toggle_git_blame_inline_internal(true, cx);
10994        cx.notify();
10995    }
10996
10997    pub fn git_blame_inline_enabled(&self) -> bool {
10998        self.git_blame_inline_enabled
10999    }
11000
11001    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11002        self.show_selection_menu = self
11003            .show_selection_menu
11004            .map(|show_selections_menu| !show_selections_menu)
11005            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11006
11007        cx.notify();
11008    }
11009
11010    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11011        self.show_selection_menu
11012            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11013    }
11014
11015    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11016        if let Some(project) = self.project.as_ref() {
11017            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11018                return;
11019            };
11020
11021            if buffer.read(cx).file().is_none() {
11022                return;
11023            }
11024
11025            let focused = self.focus_handle(cx).contains_focused(cx);
11026
11027            let project = project.clone();
11028            let blame =
11029                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11030            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11031            self.blame = Some(blame);
11032        }
11033    }
11034
11035    fn toggle_git_blame_inline_internal(
11036        &mut self,
11037        user_triggered: bool,
11038        cx: &mut ViewContext<Self>,
11039    ) {
11040        if self.git_blame_inline_enabled {
11041            self.git_blame_inline_enabled = false;
11042            self.show_git_blame_inline = false;
11043            self.show_git_blame_inline_delay_task.take();
11044        } else {
11045            self.git_blame_inline_enabled = true;
11046            self.start_git_blame_inline(user_triggered, cx);
11047        }
11048
11049        cx.notify();
11050    }
11051
11052    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11053        self.start_git_blame(user_triggered, cx);
11054
11055        if ProjectSettings::get_global(cx)
11056            .git
11057            .inline_blame_delay()
11058            .is_some()
11059        {
11060            self.start_inline_blame_timer(cx);
11061        } else {
11062            self.show_git_blame_inline = true
11063        }
11064    }
11065
11066    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11067        self.blame.as_ref()
11068    }
11069
11070    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11071        self.show_git_blame_gutter && self.has_blame_entries(cx)
11072    }
11073
11074    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11075        self.show_git_blame_inline
11076            && self.focus_handle.is_focused(cx)
11077            && !self.newest_selection_head_on_empty_line(cx)
11078            && self.has_blame_entries(cx)
11079    }
11080
11081    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11082        self.blame()
11083            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11084    }
11085
11086    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11087        let cursor_anchor = self.selections.newest_anchor().head();
11088
11089        let snapshot = self.buffer.read(cx).snapshot(cx);
11090        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11091
11092        snapshot.line_len(buffer_row) == 0
11093    }
11094
11095    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11096        let (path, selection, repo) = maybe!({
11097            let project_handle = self.project.as_ref()?.clone();
11098            let project = project_handle.read(cx);
11099
11100            let selection = self.selections.newest::<Point>(cx);
11101            let selection_range = selection.range();
11102
11103            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11104                (buffer, selection_range.start.row..selection_range.end.row)
11105            } else {
11106                let buffer_ranges = self
11107                    .buffer()
11108                    .read(cx)
11109                    .range_to_buffer_ranges(selection_range, cx);
11110
11111                let (buffer, range, _) = if selection.reversed {
11112                    buffer_ranges.first()
11113                } else {
11114                    buffer_ranges.last()
11115                }?;
11116
11117                let snapshot = buffer.read(cx).snapshot();
11118                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11119                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11120                (buffer.clone(), selection)
11121            };
11122
11123            let path = buffer
11124                .read(cx)
11125                .file()?
11126                .as_local()?
11127                .path()
11128                .to_str()?
11129                .to_string();
11130            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11131            Some((path, selection, repo))
11132        })
11133        .ok_or_else(|| anyhow!("unable to open git repository"))?;
11134
11135        const REMOTE_NAME: &str = "origin";
11136        let origin_url = repo
11137            .remote_url(REMOTE_NAME)
11138            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11139        let sha = repo
11140            .head_sha()
11141            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11142
11143        let (provider, remote) =
11144            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11145                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11146
11147        Ok(provider.build_permalink(
11148            remote,
11149            BuildPermalinkParams {
11150                sha: &sha,
11151                path: &path,
11152                selection: Some(selection),
11153            },
11154        ))
11155    }
11156
11157    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11158        let permalink = self.get_permalink_to_line(cx);
11159
11160        match permalink {
11161            Ok(permalink) => {
11162                cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11163            }
11164            Err(err) => {
11165                let message = format!("Failed to copy permalink: {err}");
11166
11167                Err::<(), anyhow::Error>(err).log_err();
11168
11169                if let Some(workspace) = self.workspace() {
11170                    workspace.update(cx, |workspace, cx| {
11171                        struct CopyPermalinkToLine;
11172
11173                        workspace.show_toast(
11174                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11175                            cx,
11176                        )
11177                    })
11178                }
11179            }
11180        }
11181    }
11182
11183    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11184        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11185            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11186                if let Some(path) = file.path().to_str() {
11187                    let selection = self.selections.newest::<Point>(cx).start.row + 1;
11188                    cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11189                }
11190            }
11191        }
11192    }
11193
11194    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11195        let permalink = self.get_permalink_to_line(cx);
11196
11197        match permalink {
11198            Ok(permalink) => {
11199                cx.open_url(permalink.as_ref());
11200            }
11201            Err(err) => {
11202                let message = format!("Failed to open permalink: {err}");
11203
11204                Err::<(), anyhow::Error>(err).log_err();
11205
11206                if let Some(workspace) = self.workspace() {
11207                    workspace.update(cx, |workspace, cx| {
11208                        struct OpenPermalinkToLine;
11209
11210                        workspace.show_toast(
11211                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11212                            cx,
11213                        )
11214                    })
11215                }
11216            }
11217        }
11218    }
11219
11220    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
11221    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
11222    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
11223    pub fn highlight_rows<T: 'static>(
11224        &mut self,
11225        rows: RangeInclusive<Anchor>,
11226        color: Option<Hsla>,
11227        should_autoscroll: bool,
11228        cx: &mut ViewContext<Self>,
11229    ) {
11230        let snapshot = self.buffer().read(cx).snapshot(cx);
11231        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11232        let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
11233            highlight
11234                .range
11235                .start()
11236                .cmp(rows.start(), &snapshot)
11237                .then(highlight.range.end().cmp(rows.end(), &snapshot))
11238        });
11239        match (color, existing_highlight_index) {
11240            (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
11241                ix,
11242                RowHighlight {
11243                    index: post_inc(&mut self.highlight_order),
11244                    range: rows,
11245                    should_autoscroll,
11246                    color,
11247                },
11248            ),
11249            (None, Ok(i)) => {
11250                row_highlights.remove(i);
11251            }
11252        }
11253    }
11254
11255    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11256    pub fn clear_row_highlights<T: 'static>(&mut self) {
11257        self.highlighted_rows.remove(&TypeId::of::<T>());
11258    }
11259
11260    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11261    pub fn highlighted_rows<T: 'static>(
11262        &self,
11263    ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
11264        Some(
11265            self.highlighted_rows
11266                .get(&TypeId::of::<T>())?
11267                .iter()
11268                .map(|highlight| (&highlight.range, highlight.color.as_ref())),
11269        )
11270    }
11271
11272    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11273    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11274    /// Allows to ignore certain kinds of highlights.
11275    pub fn highlighted_display_rows(
11276        &mut self,
11277        cx: &mut WindowContext,
11278    ) -> BTreeMap<DisplayRow, Hsla> {
11279        let snapshot = self.snapshot(cx);
11280        let mut used_highlight_orders = HashMap::default();
11281        self.highlighted_rows
11282            .iter()
11283            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11284            .fold(
11285                BTreeMap::<DisplayRow, Hsla>::new(),
11286                |mut unique_rows, highlight| {
11287                    let start_row = highlight.range.start().to_display_point(&snapshot).row();
11288                    let end_row = highlight.range.end().to_display_point(&snapshot).row();
11289                    for row in start_row.0..=end_row.0 {
11290                        let used_index =
11291                            used_highlight_orders.entry(row).or_insert(highlight.index);
11292                        if highlight.index >= *used_index {
11293                            *used_index = highlight.index;
11294                            match highlight.color {
11295                                Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
11296                                None => unique_rows.remove(&DisplayRow(row)),
11297                            };
11298                        }
11299                    }
11300                    unique_rows
11301                },
11302            )
11303    }
11304
11305    pub fn highlighted_display_row_for_autoscroll(
11306        &self,
11307        snapshot: &DisplaySnapshot,
11308    ) -> Option<DisplayRow> {
11309        self.highlighted_rows
11310            .values()
11311            .flat_map(|highlighted_rows| highlighted_rows.iter())
11312            .filter_map(|highlight| {
11313                if highlight.color.is_none() || !highlight.should_autoscroll {
11314                    return None;
11315                }
11316                Some(highlight.range.start().to_display_point(snapshot).row())
11317            })
11318            .min()
11319    }
11320
11321    pub fn set_search_within_ranges(
11322        &mut self,
11323        ranges: &[Range<Anchor>],
11324        cx: &mut ViewContext<Self>,
11325    ) {
11326        self.highlight_background::<SearchWithinRange>(
11327            ranges,
11328            |colors| colors.editor_document_highlight_read_background,
11329            cx,
11330        )
11331    }
11332
11333    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11334        self.breadcrumb_header = Some(new_header);
11335    }
11336
11337    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11338        self.clear_background_highlights::<SearchWithinRange>(cx);
11339    }
11340
11341    pub fn highlight_background<T: 'static>(
11342        &mut self,
11343        ranges: &[Range<Anchor>],
11344        color_fetcher: fn(&ThemeColors) -> Hsla,
11345        cx: &mut ViewContext<Self>,
11346    ) {
11347        self.background_highlights
11348            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11349        self.scrollbar_marker_state.dirty = true;
11350        cx.notify();
11351    }
11352
11353    pub fn clear_background_highlights<T: 'static>(
11354        &mut self,
11355        cx: &mut ViewContext<Self>,
11356    ) -> Option<BackgroundHighlight> {
11357        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11358        if !text_highlights.1.is_empty() {
11359            self.scrollbar_marker_state.dirty = true;
11360            cx.notify();
11361        }
11362        Some(text_highlights)
11363    }
11364
11365    pub fn highlight_gutter<T: 'static>(
11366        &mut self,
11367        ranges: &[Range<Anchor>],
11368        color_fetcher: fn(&AppContext) -> Hsla,
11369        cx: &mut ViewContext<Self>,
11370    ) {
11371        self.gutter_highlights
11372            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11373        cx.notify();
11374    }
11375
11376    pub fn clear_gutter_highlights<T: 'static>(
11377        &mut self,
11378        cx: &mut ViewContext<Self>,
11379    ) -> Option<GutterHighlight> {
11380        cx.notify();
11381        self.gutter_highlights.remove(&TypeId::of::<T>())
11382    }
11383
11384    #[cfg(feature = "test-support")]
11385    pub fn all_text_background_highlights(
11386        &mut self,
11387        cx: &mut ViewContext<Self>,
11388    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11389        let snapshot = self.snapshot(cx);
11390        let buffer = &snapshot.buffer_snapshot;
11391        let start = buffer.anchor_before(0);
11392        let end = buffer.anchor_after(buffer.len());
11393        let theme = cx.theme().colors();
11394        self.background_highlights_in_range(start..end, &snapshot, theme)
11395    }
11396
11397    #[cfg(feature = "test-support")]
11398    pub fn search_background_highlights(
11399        &mut self,
11400        cx: &mut ViewContext<Self>,
11401    ) -> Vec<Range<Point>> {
11402        let snapshot = self.buffer().read(cx).snapshot(cx);
11403
11404        let highlights = self
11405            .background_highlights
11406            .get(&TypeId::of::<items::BufferSearchHighlights>());
11407
11408        if let Some((_color, ranges)) = highlights {
11409            ranges
11410                .iter()
11411                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11412                .collect_vec()
11413        } else {
11414            vec![]
11415        }
11416    }
11417
11418    fn document_highlights_for_position<'a>(
11419        &'a self,
11420        position: Anchor,
11421        buffer: &'a MultiBufferSnapshot,
11422    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11423        let read_highlights = self
11424            .background_highlights
11425            .get(&TypeId::of::<DocumentHighlightRead>())
11426            .map(|h| &h.1);
11427        let write_highlights = self
11428            .background_highlights
11429            .get(&TypeId::of::<DocumentHighlightWrite>())
11430            .map(|h| &h.1);
11431        let left_position = position.bias_left(buffer);
11432        let right_position = position.bias_right(buffer);
11433        read_highlights
11434            .into_iter()
11435            .chain(write_highlights)
11436            .flat_map(move |ranges| {
11437                let start_ix = match ranges.binary_search_by(|probe| {
11438                    let cmp = probe.end.cmp(&left_position, buffer);
11439                    if cmp.is_ge() {
11440                        Ordering::Greater
11441                    } else {
11442                        Ordering::Less
11443                    }
11444                }) {
11445                    Ok(i) | Err(i) => i,
11446                };
11447
11448                ranges[start_ix..]
11449                    .iter()
11450                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11451            })
11452    }
11453
11454    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11455        self.background_highlights
11456            .get(&TypeId::of::<T>())
11457            .map_or(false, |(_, highlights)| !highlights.is_empty())
11458    }
11459
11460    pub fn background_highlights_in_range(
11461        &self,
11462        search_range: Range<Anchor>,
11463        display_snapshot: &DisplaySnapshot,
11464        theme: &ThemeColors,
11465    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11466        let mut results = Vec::new();
11467        for (color_fetcher, ranges) in self.background_highlights.values() {
11468            let color = color_fetcher(theme);
11469            let start_ix = match ranges.binary_search_by(|probe| {
11470                let cmp = probe
11471                    .end
11472                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11473                if cmp.is_gt() {
11474                    Ordering::Greater
11475                } else {
11476                    Ordering::Less
11477                }
11478            }) {
11479                Ok(i) | Err(i) => i,
11480            };
11481            for range in &ranges[start_ix..] {
11482                if range
11483                    .start
11484                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11485                    .is_ge()
11486                {
11487                    break;
11488                }
11489
11490                let start = range.start.to_display_point(display_snapshot);
11491                let end = range.end.to_display_point(display_snapshot);
11492                results.push((start..end, color))
11493            }
11494        }
11495        results
11496    }
11497
11498    pub fn background_highlight_row_ranges<T: 'static>(
11499        &self,
11500        search_range: Range<Anchor>,
11501        display_snapshot: &DisplaySnapshot,
11502        count: usize,
11503    ) -> Vec<RangeInclusive<DisplayPoint>> {
11504        let mut results = Vec::new();
11505        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11506            return vec![];
11507        };
11508
11509        let start_ix = match ranges.binary_search_by(|probe| {
11510            let cmp = probe
11511                .end
11512                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11513            if cmp.is_gt() {
11514                Ordering::Greater
11515            } else {
11516                Ordering::Less
11517            }
11518        }) {
11519            Ok(i) | Err(i) => i,
11520        };
11521        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11522            if let (Some(start_display), Some(end_display)) = (start, end) {
11523                results.push(
11524                    start_display.to_display_point(display_snapshot)
11525                        ..=end_display.to_display_point(display_snapshot),
11526                );
11527            }
11528        };
11529        let mut start_row: Option<Point> = None;
11530        let mut end_row: Option<Point> = None;
11531        if ranges.len() > count {
11532            return Vec::new();
11533        }
11534        for range in &ranges[start_ix..] {
11535            if range
11536                .start
11537                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11538                .is_ge()
11539            {
11540                break;
11541            }
11542            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11543            if let Some(current_row) = &end_row {
11544                if end.row == current_row.row {
11545                    continue;
11546                }
11547            }
11548            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11549            if start_row.is_none() {
11550                assert_eq!(end_row, None);
11551                start_row = Some(start);
11552                end_row = Some(end);
11553                continue;
11554            }
11555            if let Some(current_end) = end_row.as_mut() {
11556                if start.row > current_end.row + 1 {
11557                    push_region(start_row, end_row);
11558                    start_row = Some(start);
11559                    end_row = Some(end);
11560                } else {
11561                    // Merge two hunks.
11562                    *current_end = end;
11563                }
11564            } else {
11565                unreachable!();
11566            }
11567        }
11568        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11569        push_region(start_row, end_row);
11570        results
11571    }
11572
11573    pub fn gutter_highlights_in_range(
11574        &self,
11575        search_range: Range<Anchor>,
11576        display_snapshot: &DisplaySnapshot,
11577        cx: &AppContext,
11578    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11579        let mut results = Vec::new();
11580        for (color_fetcher, ranges) in self.gutter_highlights.values() {
11581            let color = color_fetcher(cx);
11582            let start_ix = match ranges.binary_search_by(|probe| {
11583                let cmp = probe
11584                    .end
11585                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11586                if cmp.is_gt() {
11587                    Ordering::Greater
11588                } else {
11589                    Ordering::Less
11590                }
11591            }) {
11592                Ok(i) | Err(i) => i,
11593            };
11594            for range in &ranges[start_ix..] {
11595                if range
11596                    .start
11597                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11598                    .is_ge()
11599                {
11600                    break;
11601                }
11602
11603                let start = range.start.to_display_point(display_snapshot);
11604                let end = range.end.to_display_point(display_snapshot);
11605                results.push((start..end, color))
11606            }
11607        }
11608        results
11609    }
11610
11611    /// Get the text ranges corresponding to the redaction query
11612    pub fn redacted_ranges(
11613        &self,
11614        search_range: Range<Anchor>,
11615        display_snapshot: &DisplaySnapshot,
11616        cx: &WindowContext,
11617    ) -> Vec<Range<DisplayPoint>> {
11618        display_snapshot
11619            .buffer_snapshot
11620            .redacted_ranges(search_range, |file| {
11621                if let Some(file) = file {
11622                    file.is_private()
11623                        && EditorSettings::get(
11624                            Some(SettingsLocation {
11625                                worktree_id: file.worktree_id(cx),
11626                                path: file.path().as_ref(),
11627                            }),
11628                            cx,
11629                        )
11630                        .redact_private_values
11631                } else {
11632                    false
11633                }
11634            })
11635            .map(|range| {
11636                range.start.to_display_point(display_snapshot)
11637                    ..range.end.to_display_point(display_snapshot)
11638            })
11639            .collect()
11640    }
11641
11642    pub fn highlight_text<T: 'static>(
11643        &mut self,
11644        ranges: Vec<Range<Anchor>>,
11645        style: HighlightStyle,
11646        cx: &mut ViewContext<Self>,
11647    ) {
11648        self.display_map.update(cx, |map, _| {
11649            map.highlight_text(TypeId::of::<T>(), ranges, style)
11650        });
11651        cx.notify();
11652    }
11653
11654    pub(crate) fn highlight_inlays<T: 'static>(
11655        &mut self,
11656        highlights: Vec<InlayHighlight>,
11657        style: HighlightStyle,
11658        cx: &mut ViewContext<Self>,
11659    ) {
11660        self.display_map.update(cx, |map, _| {
11661            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11662        });
11663        cx.notify();
11664    }
11665
11666    pub fn text_highlights<'a, T: 'static>(
11667        &'a self,
11668        cx: &'a AppContext,
11669    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11670        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11671    }
11672
11673    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11674        let cleared = self
11675            .display_map
11676            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11677        if cleared {
11678            cx.notify();
11679        }
11680    }
11681
11682    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11683        (self.read_only(cx) || self.blink_manager.read(cx).visible())
11684            && self.focus_handle.is_focused(cx)
11685    }
11686
11687    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11688        self.show_cursor_when_unfocused = is_enabled;
11689        cx.notify();
11690    }
11691
11692    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11693        cx.notify();
11694    }
11695
11696    fn on_buffer_event(
11697        &mut self,
11698        multibuffer: Model<MultiBuffer>,
11699        event: &multi_buffer::Event,
11700        cx: &mut ViewContext<Self>,
11701    ) {
11702        match event {
11703            multi_buffer::Event::Edited {
11704                singleton_buffer_edited,
11705            } => {
11706                self.scrollbar_marker_state.dirty = true;
11707                self.active_indent_guides_state.dirty = true;
11708                self.refresh_active_diagnostics(cx);
11709                self.refresh_code_actions(cx);
11710                if self.has_active_inline_completion(cx) {
11711                    self.update_visible_inline_completion(cx);
11712                }
11713                cx.emit(EditorEvent::BufferEdited);
11714                cx.emit(SearchEvent::MatchesInvalidated);
11715                if *singleton_buffer_edited {
11716                    if let Some(project) = &self.project {
11717                        let project = project.read(cx);
11718                        #[allow(clippy::mutable_key_type)]
11719                        let languages_affected = multibuffer
11720                            .read(cx)
11721                            .all_buffers()
11722                            .into_iter()
11723                            .filter_map(|buffer| {
11724                                let buffer = buffer.read(cx);
11725                                let language = buffer.language()?;
11726                                if project.is_local_or_ssh()
11727                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
11728                                {
11729                                    None
11730                                } else {
11731                                    Some(language)
11732                                }
11733                            })
11734                            .cloned()
11735                            .collect::<HashSet<_>>();
11736                        if !languages_affected.is_empty() {
11737                            self.refresh_inlay_hints(
11738                                InlayHintRefreshReason::BufferEdited(languages_affected),
11739                                cx,
11740                            );
11741                        }
11742                    }
11743                }
11744
11745                let Some(project) = &self.project else { return };
11746                let telemetry = project.read(cx).client().telemetry().clone();
11747                refresh_linked_ranges(self, cx);
11748                telemetry.log_edit_event("editor");
11749            }
11750            multi_buffer::Event::ExcerptsAdded {
11751                buffer,
11752                predecessor,
11753                excerpts,
11754            } => {
11755                self.tasks_update_task = Some(self.refresh_runnables(cx));
11756                cx.emit(EditorEvent::ExcerptsAdded {
11757                    buffer: buffer.clone(),
11758                    predecessor: *predecessor,
11759                    excerpts: excerpts.clone(),
11760                });
11761                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11762            }
11763            multi_buffer::Event::ExcerptsRemoved { ids } => {
11764                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11765                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11766            }
11767            multi_buffer::Event::ExcerptsEdited { ids } => {
11768                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11769            }
11770            multi_buffer::Event::ExcerptsExpanded { ids } => {
11771                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11772            }
11773            multi_buffer::Event::Reparsed(buffer_id) => {
11774                self.tasks_update_task = Some(self.refresh_runnables(cx));
11775
11776                cx.emit(EditorEvent::Reparsed(*buffer_id));
11777            }
11778            multi_buffer::Event::LanguageChanged(buffer_id) => {
11779                linked_editing_ranges::refresh_linked_ranges(self, cx);
11780                cx.emit(EditorEvent::Reparsed(*buffer_id));
11781                cx.notify();
11782            }
11783            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11784            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11785            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11786                cx.emit(EditorEvent::TitleChanged)
11787            }
11788            multi_buffer::Event::DiffBaseChanged => {
11789                self.scrollbar_marker_state.dirty = true;
11790                cx.emit(EditorEvent::DiffBaseChanged);
11791                cx.notify();
11792            }
11793            multi_buffer::Event::DiffUpdated { buffer } => {
11794                self.sync_expanded_diff_hunks(buffer.clone(), cx);
11795                cx.notify();
11796            }
11797            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11798            multi_buffer::Event::DiagnosticsUpdated => {
11799                self.refresh_active_diagnostics(cx);
11800                self.scrollbar_marker_state.dirty = true;
11801                cx.notify();
11802            }
11803            _ => {}
11804        };
11805    }
11806
11807    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11808        cx.notify();
11809    }
11810
11811    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11812        self.tasks_update_task = Some(self.refresh_runnables(cx));
11813        self.refresh_inline_completion(true, false, cx);
11814        self.refresh_inlay_hints(
11815            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11816                self.selections.newest_anchor().head(),
11817                &self.buffer.read(cx).snapshot(cx),
11818                cx,
11819            )),
11820            cx,
11821        );
11822        let editor_settings = EditorSettings::get_global(cx);
11823        self.cursor_shape = editor_settings.cursor_shape;
11824        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11825        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11826
11827        let project_settings = ProjectSettings::get_global(cx);
11828        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11829
11830        if self.mode == EditorMode::Full {
11831            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11832            if self.git_blame_inline_enabled != inline_blame_enabled {
11833                self.toggle_git_blame_inline_internal(false, cx);
11834            }
11835        }
11836
11837        cx.notify();
11838    }
11839
11840    pub fn set_searchable(&mut self, searchable: bool) {
11841        self.searchable = searchable;
11842    }
11843
11844    pub fn searchable(&self) -> bool {
11845        self.searchable
11846    }
11847
11848    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11849        self.open_excerpts_common(true, cx)
11850    }
11851
11852    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11853        self.open_excerpts_common(false, cx)
11854    }
11855
11856    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11857        let buffer = self.buffer.read(cx);
11858        if buffer.is_singleton() {
11859            cx.propagate();
11860            return;
11861        }
11862
11863        let Some(workspace) = self.workspace() else {
11864            cx.propagate();
11865            return;
11866        };
11867
11868        let mut new_selections_by_buffer = HashMap::default();
11869        for selection in self.selections.all::<usize>(cx) {
11870            for (buffer, mut range, _) in
11871                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11872            {
11873                if selection.reversed {
11874                    mem::swap(&mut range.start, &mut range.end);
11875                }
11876                new_selections_by_buffer
11877                    .entry(buffer)
11878                    .or_insert(Vec::new())
11879                    .push(range)
11880            }
11881        }
11882
11883        // We defer the pane interaction because we ourselves are a workspace item
11884        // and activating a new item causes the pane to call a method on us reentrantly,
11885        // which panics if we're on the stack.
11886        cx.window_context().defer(move |cx| {
11887            workspace.update(cx, |workspace, cx| {
11888                let pane = if split {
11889                    workspace.adjacent_pane(cx)
11890                } else {
11891                    workspace.active_pane().clone()
11892                };
11893
11894                for (buffer, ranges) in new_selections_by_buffer {
11895                    let editor =
11896                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11897                    editor.update(cx, |editor, cx| {
11898                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11899                            s.select_ranges(ranges);
11900                        });
11901                    });
11902                }
11903            })
11904        });
11905    }
11906
11907    fn jump(
11908        &mut self,
11909        path: ProjectPath,
11910        position: Point,
11911        anchor: language::Anchor,
11912        offset_from_top: u32,
11913        cx: &mut ViewContext<Self>,
11914    ) {
11915        let workspace = self.workspace();
11916        cx.spawn(|_, mut cx| async move {
11917            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11918            let editor = workspace.update(&mut cx, |workspace, cx| {
11919                // Reset the preview item id before opening the new item
11920                workspace.active_pane().update(cx, |pane, cx| {
11921                    pane.set_preview_item_id(None, cx);
11922                });
11923                workspace.open_path_preview(path, None, true, true, cx)
11924            })?;
11925            let editor = editor
11926                .await?
11927                .downcast::<Editor>()
11928                .ok_or_else(|| anyhow!("opened item was not an editor"))?
11929                .downgrade();
11930            editor.update(&mut cx, |editor, cx| {
11931                let buffer = editor
11932                    .buffer()
11933                    .read(cx)
11934                    .as_singleton()
11935                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11936                let buffer = buffer.read(cx);
11937                let cursor = if buffer.can_resolve(&anchor) {
11938                    language::ToPoint::to_point(&anchor, buffer)
11939                } else {
11940                    buffer.clip_point(position, Bias::Left)
11941                };
11942
11943                let nav_history = editor.nav_history.take();
11944                editor.change_selections(
11945                    Some(Autoscroll::top_relative(offset_from_top as usize)),
11946                    cx,
11947                    |s| {
11948                        s.select_ranges([cursor..cursor]);
11949                    },
11950                );
11951                editor.nav_history = nav_history;
11952
11953                anyhow::Ok(())
11954            })??;
11955
11956            anyhow::Ok(())
11957        })
11958        .detach_and_log_err(cx);
11959    }
11960
11961    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11962        let snapshot = self.buffer.read(cx).read(cx);
11963        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11964        Some(
11965            ranges
11966                .iter()
11967                .map(move |range| {
11968                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11969                })
11970                .collect(),
11971        )
11972    }
11973
11974    fn selection_replacement_ranges(
11975        &self,
11976        range: Range<OffsetUtf16>,
11977        cx: &AppContext,
11978    ) -> Vec<Range<OffsetUtf16>> {
11979        let selections = self.selections.all::<OffsetUtf16>(cx);
11980        let newest_selection = selections
11981            .iter()
11982            .max_by_key(|selection| selection.id)
11983            .unwrap();
11984        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11985        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11986        let snapshot = self.buffer.read(cx).read(cx);
11987        selections
11988            .into_iter()
11989            .map(|mut selection| {
11990                selection.start.0 =
11991                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
11992                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11993                snapshot.clip_offset_utf16(selection.start, Bias::Left)
11994                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11995            })
11996            .collect()
11997    }
11998
11999    fn report_editor_event(
12000        &self,
12001        operation: &'static str,
12002        file_extension: Option<String>,
12003        cx: &AppContext,
12004    ) {
12005        if cfg!(any(test, feature = "test-support")) {
12006            return;
12007        }
12008
12009        let Some(project) = &self.project else { return };
12010
12011        // If None, we are in a file without an extension
12012        let file = self
12013            .buffer
12014            .read(cx)
12015            .as_singleton()
12016            .and_then(|b| b.read(cx).file());
12017        let file_extension = file_extension.or(file
12018            .as_ref()
12019            .and_then(|file| Path::new(file.file_name(cx)).extension())
12020            .and_then(|e| e.to_str())
12021            .map(|a| a.to_string()));
12022
12023        let vim_mode = cx
12024            .global::<SettingsStore>()
12025            .raw_user_settings()
12026            .get("vim_mode")
12027            == Some(&serde_json::Value::Bool(true));
12028
12029        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12030            == language::language_settings::InlineCompletionProvider::Copilot;
12031        let copilot_enabled_for_language = self
12032            .buffer
12033            .read(cx)
12034            .settings_at(0, cx)
12035            .show_inline_completions;
12036
12037        let telemetry = project.read(cx).client().telemetry().clone();
12038        telemetry.report_editor_event(
12039            file_extension,
12040            vim_mode,
12041            operation,
12042            copilot_enabled,
12043            copilot_enabled_for_language,
12044        )
12045    }
12046
12047    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12048    /// with each line being an array of {text, highlight} objects.
12049    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12050        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12051            return;
12052        };
12053
12054        #[derive(Serialize)]
12055        struct Chunk<'a> {
12056            text: String,
12057            highlight: Option<&'a str>,
12058        }
12059
12060        let snapshot = buffer.read(cx).snapshot();
12061        let range = self
12062            .selected_text_range(false, cx)
12063            .and_then(|selection| {
12064                if selection.range.is_empty() {
12065                    None
12066                } else {
12067                    Some(selection.range)
12068                }
12069            })
12070            .unwrap_or_else(|| 0..snapshot.len());
12071
12072        let chunks = snapshot.chunks(range, true);
12073        let mut lines = Vec::new();
12074        let mut line: VecDeque<Chunk> = VecDeque::new();
12075
12076        let Some(style) = self.style.as_ref() else {
12077            return;
12078        };
12079
12080        for chunk in chunks {
12081            let highlight = chunk
12082                .syntax_highlight_id
12083                .and_then(|id| id.name(&style.syntax));
12084            let mut chunk_lines = chunk.text.split('\n').peekable();
12085            while let Some(text) = chunk_lines.next() {
12086                let mut merged_with_last_token = false;
12087                if let Some(last_token) = line.back_mut() {
12088                    if last_token.highlight == highlight {
12089                        last_token.text.push_str(text);
12090                        merged_with_last_token = true;
12091                    }
12092                }
12093
12094                if !merged_with_last_token {
12095                    line.push_back(Chunk {
12096                        text: text.into(),
12097                        highlight,
12098                    });
12099                }
12100
12101                if chunk_lines.peek().is_some() {
12102                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12103                        line.pop_front();
12104                    }
12105                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12106                        line.pop_back();
12107                    }
12108
12109                    lines.push(mem::take(&mut line));
12110                }
12111            }
12112        }
12113
12114        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12115            return;
12116        };
12117        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12118    }
12119
12120    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12121        &self.inlay_hint_cache
12122    }
12123
12124    pub fn replay_insert_event(
12125        &mut self,
12126        text: &str,
12127        relative_utf16_range: Option<Range<isize>>,
12128        cx: &mut ViewContext<Self>,
12129    ) {
12130        if !self.input_enabled {
12131            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12132            return;
12133        }
12134        if let Some(relative_utf16_range) = relative_utf16_range {
12135            let selections = self.selections.all::<OffsetUtf16>(cx);
12136            self.change_selections(None, cx, |s| {
12137                let new_ranges = selections.into_iter().map(|range| {
12138                    let start = OffsetUtf16(
12139                        range
12140                            .head()
12141                            .0
12142                            .saturating_add_signed(relative_utf16_range.start),
12143                    );
12144                    let end = OffsetUtf16(
12145                        range
12146                            .head()
12147                            .0
12148                            .saturating_add_signed(relative_utf16_range.end),
12149                    );
12150                    start..end
12151                });
12152                s.select_ranges(new_ranges);
12153            });
12154        }
12155
12156        self.handle_input(text, cx);
12157    }
12158
12159    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12160        let Some(project) = self.project.as_ref() else {
12161            return false;
12162        };
12163        let project = project.read(cx);
12164
12165        let mut supports = false;
12166        self.buffer().read(cx).for_each_buffer(|buffer| {
12167            if !supports {
12168                supports = project
12169                    .language_servers_for_buffer(buffer.read(cx), cx)
12170                    .any(
12171                        |(_, server)| match server.capabilities().inlay_hint_provider {
12172                            Some(lsp::OneOf::Left(enabled)) => enabled,
12173                            Some(lsp::OneOf::Right(_)) => true,
12174                            None => false,
12175                        },
12176                    )
12177            }
12178        });
12179        supports
12180    }
12181
12182    pub fn focus(&self, cx: &mut WindowContext) {
12183        cx.focus(&self.focus_handle)
12184    }
12185
12186    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12187        self.focus_handle.is_focused(cx)
12188    }
12189
12190    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12191        cx.emit(EditorEvent::Focused);
12192
12193        if let Some(descendant) = self
12194            .last_focused_descendant
12195            .take()
12196            .and_then(|descendant| descendant.upgrade())
12197        {
12198            cx.focus(&descendant);
12199        } else {
12200            if let Some(blame) = self.blame.as_ref() {
12201                blame.update(cx, GitBlame::focus)
12202            }
12203
12204            self.blink_manager.update(cx, BlinkManager::enable);
12205            self.show_cursor_names(cx);
12206            self.buffer.update(cx, |buffer, cx| {
12207                buffer.finalize_last_transaction(cx);
12208                if self.leader_peer_id.is_none() {
12209                    buffer.set_active_selections(
12210                        &self.selections.disjoint_anchors(),
12211                        self.selections.line_mode,
12212                        self.cursor_shape,
12213                        cx,
12214                    );
12215                }
12216            });
12217        }
12218    }
12219
12220    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12221        cx.emit(EditorEvent::FocusedIn)
12222    }
12223
12224    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12225        if event.blurred != self.focus_handle {
12226            self.last_focused_descendant = Some(event.blurred);
12227        }
12228    }
12229
12230    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12231        self.blink_manager.update(cx, BlinkManager::disable);
12232        self.buffer
12233            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12234
12235        if let Some(blame) = self.blame.as_ref() {
12236            blame.update(cx, GitBlame::blur)
12237        }
12238        if !self.hover_state.focused(cx) {
12239            hide_hover(self, cx);
12240        }
12241
12242        self.hide_context_menu(cx);
12243        cx.emit(EditorEvent::Blurred);
12244        cx.notify();
12245    }
12246
12247    pub fn register_action<A: Action>(
12248        &mut self,
12249        listener: impl Fn(&A, &mut WindowContext) + 'static,
12250    ) -> Subscription {
12251        let id = self.next_editor_action_id.post_inc();
12252        let listener = Arc::new(listener);
12253        self.editor_actions.borrow_mut().insert(
12254            id,
12255            Box::new(move |cx| {
12256                let cx = cx.window_context();
12257                let listener = listener.clone();
12258                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12259                    let action = action.downcast_ref().unwrap();
12260                    if phase == DispatchPhase::Bubble {
12261                        listener(action, cx)
12262                    }
12263                })
12264            }),
12265        );
12266
12267        let editor_actions = self.editor_actions.clone();
12268        Subscription::new(move || {
12269            editor_actions.borrow_mut().remove(&id);
12270        })
12271    }
12272
12273    pub fn file_header_size(&self) -> u32 {
12274        self.file_header_size
12275    }
12276
12277    pub fn revert(
12278        &mut self,
12279        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12280        cx: &mut ViewContext<Self>,
12281    ) {
12282        self.buffer().update(cx, |multi_buffer, cx| {
12283            for (buffer_id, changes) in revert_changes {
12284                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12285                    buffer.update(cx, |buffer, cx| {
12286                        buffer.edit(
12287                            changes.into_iter().map(|(range, text)| {
12288                                (range, text.to_string().map(Arc::<str>::from))
12289                            }),
12290                            None,
12291                            cx,
12292                        );
12293                    });
12294                }
12295            }
12296        });
12297        self.change_selections(None, cx, |selections| selections.refresh());
12298    }
12299
12300    pub fn to_pixel_point(
12301        &mut self,
12302        source: multi_buffer::Anchor,
12303        editor_snapshot: &EditorSnapshot,
12304        cx: &mut ViewContext<Self>,
12305    ) -> Option<gpui::Point<Pixels>> {
12306        let source_point = source.to_display_point(editor_snapshot);
12307        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12308    }
12309
12310    pub fn display_to_pixel_point(
12311        &mut self,
12312        source: DisplayPoint,
12313        editor_snapshot: &EditorSnapshot,
12314        cx: &mut ViewContext<Self>,
12315    ) -> Option<gpui::Point<Pixels>> {
12316        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12317        let text_layout_details = self.text_layout_details(cx);
12318        let scroll_top = text_layout_details
12319            .scroll_anchor
12320            .scroll_position(editor_snapshot)
12321            .y;
12322
12323        if source.row().as_f32() < scroll_top.floor() {
12324            return None;
12325        }
12326        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12327        let source_y = line_height * (source.row().as_f32() - scroll_top);
12328        Some(gpui::Point::new(source_x, source_y))
12329    }
12330
12331    fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
12332        let bounds = self.last_bounds?;
12333        Some(element::gutter_bounds(bounds, self.gutter_dimensions))
12334    }
12335
12336    pub fn has_active_completions_menu(&self) -> bool {
12337        self.context_menu.read().as_ref().map_or(false, |menu| {
12338            menu.visible() && matches!(menu, ContextMenu::Completions(_))
12339        })
12340    }
12341
12342    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12343        self.addons
12344            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12345    }
12346
12347    pub fn unregister_addon<T: Addon>(&mut self) {
12348        self.addons.remove(&std::any::TypeId::of::<T>());
12349    }
12350
12351    pub fn addon<T: Addon>(&self) -> Option<&T> {
12352        let type_id = std::any::TypeId::of::<T>();
12353        self.addons
12354            .get(&type_id)
12355            .and_then(|item| item.to_any().downcast_ref::<T>())
12356    }
12357}
12358
12359fn hunks_for_selections(
12360    multi_buffer_snapshot: &MultiBufferSnapshot,
12361    selections: &[Selection<Anchor>],
12362) -> Vec<DiffHunk<MultiBufferRow>> {
12363    let buffer_rows_for_selections = selections.iter().map(|selection| {
12364        let head = selection.head();
12365        let tail = selection.tail();
12366        let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12367        let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12368        if start > end {
12369            end..start
12370        } else {
12371            start..end
12372        }
12373    });
12374
12375    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12376}
12377
12378pub fn hunks_for_rows(
12379    rows: impl Iterator<Item = Range<MultiBufferRow>>,
12380    multi_buffer_snapshot: &MultiBufferSnapshot,
12381) -> Vec<DiffHunk<MultiBufferRow>> {
12382    let mut hunks = Vec::new();
12383    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12384        HashMap::default();
12385    for selected_multi_buffer_rows in rows {
12386        let query_rows =
12387            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12388        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12389            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12390            // when the caret is just above or just below the deleted hunk.
12391            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12392            let related_to_selection = if allow_adjacent {
12393                hunk.associated_range.overlaps(&query_rows)
12394                    || hunk.associated_range.start == query_rows.end
12395                    || hunk.associated_range.end == query_rows.start
12396            } else {
12397                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12398                // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12399                hunk.associated_range.overlaps(&selected_multi_buffer_rows)
12400                    || selected_multi_buffer_rows.end == hunk.associated_range.start
12401            };
12402            if related_to_selection {
12403                if !processed_buffer_rows
12404                    .entry(hunk.buffer_id)
12405                    .or_default()
12406                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12407                {
12408                    continue;
12409                }
12410                hunks.push(hunk);
12411            }
12412        }
12413    }
12414
12415    hunks
12416}
12417
12418pub trait CollaborationHub {
12419    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12420    fn user_participant_indices<'a>(
12421        &self,
12422        cx: &'a AppContext,
12423    ) -> &'a HashMap<u64, ParticipantIndex>;
12424    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12425}
12426
12427impl CollaborationHub for Model<Project> {
12428    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12429        self.read(cx).collaborators()
12430    }
12431
12432    fn user_participant_indices<'a>(
12433        &self,
12434        cx: &'a AppContext,
12435    ) -> &'a HashMap<u64, ParticipantIndex> {
12436        self.read(cx).user_store().read(cx).participant_indices()
12437    }
12438
12439    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12440        let this = self.read(cx);
12441        let user_ids = this.collaborators().values().map(|c| c.user_id);
12442        this.user_store().read_with(cx, |user_store, cx| {
12443            user_store.participant_names(user_ids, cx)
12444        })
12445    }
12446}
12447
12448pub trait CompletionProvider {
12449    fn completions(
12450        &self,
12451        buffer: &Model<Buffer>,
12452        buffer_position: text::Anchor,
12453        trigger: CompletionContext,
12454        cx: &mut ViewContext<Editor>,
12455    ) -> Task<Result<Vec<Completion>>>;
12456
12457    fn resolve_completions(
12458        &self,
12459        buffer: Model<Buffer>,
12460        completion_indices: Vec<usize>,
12461        completions: Arc<RwLock<Box<[Completion]>>>,
12462        cx: &mut ViewContext<Editor>,
12463    ) -> Task<Result<bool>>;
12464
12465    fn apply_additional_edits_for_completion(
12466        &self,
12467        buffer: Model<Buffer>,
12468        completion: Completion,
12469        push_to_history: bool,
12470        cx: &mut ViewContext<Editor>,
12471    ) -> Task<Result<Option<language::Transaction>>>;
12472
12473    fn is_completion_trigger(
12474        &self,
12475        buffer: &Model<Buffer>,
12476        position: language::Anchor,
12477        text: &str,
12478        trigger_in_words: bool,
12479        cx: &mut ViewContext<Editor>,
12480    ) -> bool;
12481
12482    fn sort_completions(&self) -> bool {
12483        true
12484    }
12485}
12486
12487fn snippet_completions(
12488    project: &Project,
12489    buffer: &Model<Buffer>,
12490    buffer_position: text::Anchor,
12491    cx: &mut AppContext,
12492) -> Vec<Completion> {
12493    let language = buffer.read(cx).language_at(buffer_position);
12494    let language_name = language.as_ref().map(|language| language.lsp_id());
12495    let snippet_store = project.snippets().read(cx);
12496    let snippets = snippet_store.snippets_for(language_name, cx);
12497
12498    if snippets.is_empty() {
12499        return vec![];
12500    }
12501    let snapshot = buffer.read(cx).text_snapshot();
12502    let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12503
12504    let mut lines = chunks.lines();
12505    let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12506        return vec![];
12507    };
12508
12509    let scope = language.map(|language| language.default_scope());
12510    let classifier = CharClassifier::new(scope).for_completion(true);
12511    let mut last_word = line_at
12512        .chars()
12513        .rev()
12514        .take_while(|c| classifier.is_word(*c))
12515        .collect::<String>();
12516    last_word = last_word.chars().rev().collect();
12517    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12518    let to_lsp = |point: &text::Anchor| {
12519        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12520        point_to_lsp(end)
12521    };
12522    let lsp_end = to_lsp(&buffer_position);
12523    snippets
12524        .into_iter()
12525        .filter_map(|snippet| {
12526            let matching_prefix = snippet
12527                .prefix
12528                .iter()
12529                .find(|prefix| prefix.starts_with(&last_word))?;
12530            let start = as_offset - last_word.len();
12531            let start = snapshot.anchor_before(start);
12532            let range = start..buffer_position;
12533            let lsp_start = to_lsp(&start);
12534            let lsp_range = lsp::Range {
12535                start: lsp_start,
12536                end: lsp_end,
12537            };
12538            Some(Completion {
12539                old_range: range,
12540                new_text: snippet.body.clone(),
12541                label: CodeLabel {
12542                    text: matching_prefix.clone(),
12543                    runs: vec![],
12544                    filter_range: 0..matching_prefix.len(),
12545                },
12546                server_id: LanguageServerId(usize::MAX),
12547                documentation: snippet.description.clone().map(Documentation::SingleLine),
12548                lsp_completion: lsp::CompletionItem {
12549                    label: snippet.prefix.first().unwrap().clone(),
12550                    kind: Some(CompletionItemKind::SNIPPET),
12551                    label_details: snippet.description.as_ref().map(|description| {
12552                        lsp::CompletionItemLabelDetails {
12553                            detail: Some(description.clone()),
12554                            description: None,
12555                        }
12556                    }),
12557                    insert_text_format: Some(InsertTextFormat::SNIPPET),
12558                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12559                        lsp::InsertReplaceEdit {
12560                            new_text: snippet.body.clone(),
12561                            insert: lsp_range,
12562                            replace: lsp_range,
12563                        },
12564                    )),
12565                    filter_text: Some(snippet.body.clone()),
12566                    sort_text: Some(char::MAX.to_string()),
12567                    ..Default::default()
12568                },
12569                confirm: None,
12570            })
12571        })
12572        .collect()
12573}
12574
12575impl CompletionProvider for Model<Project> {
12576    fn completions(
12577        &self,
12578        buffer: &Model<Buffer>,
12579        buffer_position: text::Anchor,
12580        options: CompletionContext,
12581        cx: &mut ViewContext<Editor>,
12582    ) -> Task<Result<Vec<Completion>>> {
12583        self.update(cx, |project, cx| {
12584            let snippets = snippet_completions(project, buffer, buffer_position, cx);
12585            let project_completions = project.completions(buffer, buffer_position, options, cx);
12586            cx.background_executor().spawn(async move {
12587                let mut completions = project_completions.await?;
12588                //let snippets = snippets.into_iter().;
12589                completions.extend(snippets);
12590                Ok(completions)
12591            })
12592        })
12593    }
12594
12595    fn resolve_completions(
12596        &self,
12597        buffer: Model<Buffer>,
12598        completion_indices: Vec<usize>,
12599        completions: Arc<RwLock<Box<[Completion]>>>,
12600        cx: &mut ViewContext<Editor>,
12601    ) -> Task<Result<bool>> {
12602        self.update(cx, |project, cx| {
12603            project.resolve_completions(buffer, completion_indices, completions, cx)
12604        })
12605    }
12606
12607    fn apply_additional_edits_for_completion(
12608        &self,
12609        buffer: Model<Buffer>,
12610        completion: Completion,
12611        push_to_history: bool,
12612        cx: &mut ViewContext<Editor>,
12613    ) -> Task<Result<Option<language::Transaction>>> {
12614        self.update(cx, |project, cx| {
12615            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12616        })
12617    }
12618
12619    fn is_completion_trigger(
12620        &self,
12621        buffer: &Model<Buffer>,
12622        position: language::Anchor,
12623        text: &str,
12624        trigger_in_words: bool,
12625        cx: &mut ViewContext<Editor>,
12626    ) -> bool {
12627        if !EditorSettings::get_global(cx).show_completions_on_input {
12628            return false;
12629        }
12630
12631        let mut chars = text.chars();
12632        let char = if let Some(char) = chars.next() {
12633            char
12634        } else {
12635            return false;
12636        };
12637        if chars.next().is_some() {
12638            return false;
12639        }
12640
12641        let buffer = buffer.read(cx);
12642        let classifier = buffer
12643            .snapshot()
12644            .char_classifier_at(position)
12645            .for_completion(true);
12646        if trigger_in_words && classifier.is_word(char) {
12647            return true;
12648        }
12649
12650        buffer
12651            .completion_triggers()
12652            .iter()
12653            .any(|string| string == text)
12654    }
12655}
12656
12657fn inlay_hint_settings(
12658    location: Anchor,
12659    snapshot: &MultiBufferSnapshot,
12660    cx: &mut ViewContext<'_, Editor>,
12661) -> InlayHintSettings {
12662    let file = snapshot.file_at(location);
12663    let language = snapshot.language_at(location);
12664    let settings = all_language_settings(file, cx);
12665    settings
12666        .language(language.map(|l| l.name()).as_ref())
12667        .inlay_hints
12668}
12669
12670fn consume_contiguous_rows(
12671    contiguous_row_selections: &mut Vec<Selection<Point>>,
12672    selection: &Selection<Point>,
12673    display_map: &DisplaySnapshot,
12674    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12675) -> (MultiBufferRow, MultiBufferRow) {
12676    contiguous_row_selections.push(selection.clone());
12677    let start_row = MultiBufferRow(selection.start.row);
12678    let mut end_row = ending_row(selection, display_map);
12679
12680    while let Some(next_selection) = selections.peek() {
12681        if next_selection.start.row <= end_row.0 {
12682            end_row = ending_row(next_selection, display_map);
12683            contiguous_row_selections.push(selections.next().unwrap().clone());
12684        } else {
12685            break;
12686        }
12687    }
12688    (start_row, end_row)
12689}
12690
12691fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12692    if next_selection.end.column > 0 || next_selection.is_empty() {
12693        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12694    } else {
12695        MultiBufferRow(next_selection.end.row)
12696    }
12697}
12698
12699impl EditorSnapshot {
12700    pub fn remote_selections_in_range<'a>(
12701        &'a self,
12702        range: &'a Range<Anchor>,
12703        collaboration_hub: &dyn CollaborationHub,
12704        cx: &'a AppContext,
12705    ) -> impl 'a + Iterator<Item = RemoteSelection> {
12706        let participant_names = collaboration_hub.user_names(cx);
12707        let participant_indices = collaboration_hub.user_participant_indices(cx);
12708        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12709        let collaborators_by_replica_id = collaborators_by_peer_id
12710            .iter()
12711            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12712            .collect::<HashMap<_, _>>();
12713        self.buffer_snapshot
12714            .selections_in_range(range, false)
12715            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12716                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12717                let participant_index = participant_indices.get(&collaborator.user_id).copied();
12718                let user_name = participant_names.get(&collaborator.user_id).cloned();
12719                Some(RemoteSelection {
12720                    replica_id,
12721                    selection,
12722                    cursor_shape,
12723                    line_mode,
12724                    participant_index,
12725                    peer_id: collaborator.peer_id,
12726                    user_name,
12727                })
12728            })
12729    }
12730
12731    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12732        self.display_snapshot.buffer_snapshot.language_at(position)
12733    }
12734
12735    pub fn is_focused(&self) -> bool {
12736        self.is_focused
12737    }
12738
12739    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12740        self.placeholder_text.as_ref()
12741    }
12742
12743    pub fn scroll_position(&self) -> gpui::Point<f32> {
12744        self.scroll_anchor.scroll_position(&self.display_snapshot)
12745    }
12746
12747    fn gutter_dimensions(
12748        &self,
12749        font_id: FontId,
12750        font_size: Pixels,
12751        em_width: Pixels,
12752        max_line_number_width: Pixels,
12753        cx: &AppContext,
12754    ) -> GutterDimensions {
12755        if !self.show_gutter {
12756            return GutterDimensions::default();
12757        }
12758        let descent = cx.text_system().descent(font_id, font_size);
12759
12760        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12761            matches!(
12762                ProjectSettings::get_global(cx).git.git_gutter,
12763                Some(GitGutterSetting::TrackedFiles)
12764            )
12765        });
12766        let gutter_settings = EditorSettings::get_global(cx).gutter;
12767        let show_line_numbers = self
12768            .show_line_numbers
12769            .unwrap_or(gutter_settings.line_numbers);
12770        let line_gutter_width = if show_line_numbers {
12771            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12772            let min_width_for_number_on_gutter = em_width * 4.0;
12773            max_line_number_width.max(min_width_for_number_on_gutter)
12774        } else {
12775            0.0.into()
12776        };
12777
12778        let show_code_actions = self
12779            .show_code_actions
12780            .unwrap_or(gutter_settings.code_actions);
12781
12782        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12783
12784        let git_blame_entries_width = self
12785            .render_git_blame_gutter
12786            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12787
12788        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12789        left_padding += if show_code_actions || show_runnables {
12790            em_width * 3.0
12791        } else if show_git_gutter && show_line_numbers {
12792            em_width * 2.0
12793        } else if show_git_gutter || show_line_numbers {
12794            em_width
12795        } else {
12796            px(0.)
12797        };
12798
12799        let right_padding = if gutter_settings.folds && show_line_numbers {
12800            em_width * 4.0
12801        } else if gutter_settings.folds {
12802            em_width * 3.0
12803        } else if show_line_numbers {
12804            em_width
12805        } else {
12806            px(0.)
12807        };
12808
12809        GutterDimensions {
12810            left_padding,
12811            right_padding,
12812            width: line_gutter_width + left_padding + right_padding,
12813            margin: -descent,
12814            git_blame_entries_width,
12815        }
12816    }
12817
12818    pub fn render_fold_toggle(
12819        &self,
12820        buffer_row: MultiBufferRow,
12821        row_contains_cursor: bool,
12822        editor: View<Editor>,
12823        cx: &mut WindowContext,
12824    ) -> Option<AnyElement> {
12825        let folded = self.is_line_folded(buffer_row);
12826
12827        if let Some(crease) = self
12828            .crease_snapshot
12829            .query_row(buffer_row, &self.buffer_snapshot)
12830        {
12831            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12832                if folded {
12833                    editor.update(cx, |editor, cx| {
12834                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12835                    });
12836                } else {
12837                    editor.update(cx, |editor, cx| {
12838                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12839                    });
12840                }
12841            });
12842
12843            Some((crease.render_toggle)(
12844                buffer_row,
12845                folded,
12846                toggle_callback,
12847                cx,
12848            ))
12849        } else if folded
12850            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12851        {
12852            Some(
12853                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12854                    .selected(folded)
12855                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12856                        if folded {
12857                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
12858                        } else {
12859                            this.fold_at(&FoldAt { buffer_row }, cx);
12860                        }
12861                    }))
12862                    .into_any_element(),
12863            )
12864        } else {
12865            None
12866        }
12867    }
12868
12869    pub fn render_crease_trailer(
12870        &self,
12871        buffer_row: MultiBufferRow,
12872        cx: &mut WindowContext,
12873    ) -> Option<AnyElement> {
12874        let folded = self.is_line_folded(buffer_row);
12875        let crease = self
12876            .crease_snapshot
12877            .query_row(buffer_row, &self.buffer_snapshot)?;
12878        Some((crease.render_trailer)(buffer_row, folded, cx))
12879    }
12880}
12881
12882impl Deref for EditorSnapshot {
12883    type Target = DisplaySnapshot;
12884
12885    fn deref(&self) -> &Self::Target {
12886        &self.display_snapshot
12887    }
12888}
12889
12890#[derive(Clone, Debug, PartialEq, Eq)]
12891pub enum EditorEvent {
12892    InputIgnored {
12893        text: Arc<str>,
12894    },
12895    InputHandled {
12896        utf16_range_to_replace: Option<Range<isize>>,
12897        text: Arc<str>,
12898    },
12899    ExcerptsAdded {
12900        buffer: Model<Buffer>,
12901        predecessor: ExcerptId,
12902        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12903    },
12904    ExcerptsRemoved {
12905        ids: Vec<ExcerptId>,
12906    },
12907    ExcerptsEdited {
12908        ids: Vec<ExcerptId>,
12909    },
12910    ExcerptsExpanded {
12911        ids: Vec<ExcerptId>,
12912    },
12913    BufferEdited,
12914    Edited {
12915        transaction_id: clock::Lamport,
12916    },
12917    Reparsed(BufferId),
12918    Focused,
12919    FocusedIn,
12920    Blurred,
12921    DirtyChanged,
12922    Saved,
12923    TitleChanged,
12924    DiffBaseChanged,
12925    SelectionsChanged {
12926        local: bool,
12927    },
12928    ScrollPositionChanged {
12929        local: bool,
12930        autoscroll: bool,
12931    },
12932    Closed,
12933    TransactionUndone {
12934        transaction_id: clock::Lamport,
12935    },
12936    TransactionBegun {
12937        transaction_id: clock::Lamport,
12938    },
12939}
12940
12941impl EventEmitter<EditorEvent> for Editor {}
12942
12943impl FocusableView for Editor {
12944    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12945        self.focus_handle.clone()
12946    }
12947}
12948
12949impl Render for Editor {
12950    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12951        let settings = ThemeSettings::get_global(cx);
12952
12953        let text_style = match self.mode {
12954            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12955                color: cx.theme().colors().editor_foreground,
12956                font_family: settings.ui_font.family.clone(),
12957                font_features: settings.ui_font.features.clone(),
12958                font_fallbacks: settings.ui_font.fallbacks.clone(),
12959                font_size: rems(0.875).into(),
12960                font_weight: settings.ui_font.weight,
12961                line_height: relative(settings.buffer_line_height.value()),
12962                ..Default::default()
12963            },
12964            EditorMode::Full => TextStyle {
12965                color: cx.theme().colors().editor_foreground,
12966                font_family: settings.buffer_font.family.clone(),
12967                font_features: settings.buffer_font.features.clone(),
12968                font_fallbacks: settings.buffer_font.fallbacks.clone(),
12969                font_size: settings.buffer_font_size(cx).into(),
12970                font_weight: settings.buffer_font.weight,
12971                line_height: relative(settings.buffer_line_height.value()),
12972                ..Default::default()
12973            },
12974        };
12975
12976        let background = match self.mode {
12977            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12978            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12979            EditorMode::Full => cx.theme().colors().editor_background,
12980        };
12981
12982        EditorElement::new(
12983            cx.view(),
12984            EditorStyle {
12985                background,
12986                local_player: cx.theme().players().local(),
12987                text: text_style,
12988                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12989                syntax: cx.theme().syntax().clone(),
12990                status: cx.theme().status().clone(),
12991                inlay_hints_style: HighlightStyle {
12992                    color: Some(cx.theme().status().hint),
12993                    ..HighlightStyle::default()
12994                },
12995                suggestions_style: HighlightStyle {
12996                    color: Some(cx.theme().status().predictive),
12997                    ..HighlightStyle::default()
12998                },
12999                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13000            },
13001        )
13002    }
13003}
13004
13005impl ViewInputHandler for Editor {
13006    fn text_for_range(
13007        &mut self,
13008        range_utf16: Range<usize>,
13009        cx: &mut ViewContext<Self>,
13010    ) -> Option<String> {
13011        Some(
13012            self.buffer
13013                .read(cx)
13014                .read(cx)
13015                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13016                .collect(),
13017        )
13018    }
13019
13020    fn selected_text_range(
13021        &mut self,
13022        ignore_disabled_input: bool,
13023        cx: &mut ViewContext<Self>,
13024    ) -> Option<UTF16Selection> {
13025        // Prevent the IME menu from appearing when holding down an alphabetic key
13026        // while input is disabled.
13027        if !ignore_disabled_input && !self.input_enabled {
13028            return None;
13029        }
13030
13031        let selection = self.selections.newest::<OffsetUtf16>(cx);
13032        let range = selection.range();
13033
13034        Some(UTF16Selection {
13035            range: range.start.0..range.end.0,
13036            reversed: selection.reversed,
13037        })
13038    }
13039
13040    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13041        let snapshot = self.buffer.read(cx).read(cx);
13042        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13043        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13044    }
13045
13046    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13047        self.clear_highlights::<InputComposition>(cx);
13048        self.ime_transaction.take();
13049    }
13050
13051    fn replace_text_in_range(
13052        &mut self,
13053        range_utf16: Option<Range<usize>>,
13054        text: &str,
13055        cx: &mut ViewContext<Self>,
13056    ) {
13057        if !self.input_enabled {
13058            cx.emit(EditorEvent::InputIgnored { text: text.into() });
13059            return;
13060        }
13061
13062        self.transact(cx, |this, cx| {
13063            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13064                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13065                Some(this.selection_replacement_ranges(range_utf16, cx))
13066            } else {
13067                this.marked_text_ranges(cx)
13068            };
13069
13070            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13071                let newest_selection_id = this.selections.newest_anchor().id;
13072                this.selections
13073                    .all::<OffsetUtf16>(cx)
13074                    .iter()
13075                    .zip(ranges_to_replace.iter())
13076                    .find_map(|(selection, range)| {
13077                        if selection.id == newest_selection_id {
13078                            Some(
13079                                (range.start.0 as isize - selection.head().0 as isize)
13080                                    ..(range.end.0 as isize - selection.head().0 as isize),
13081                            )
13082                        } else {
13083                            None
13084                        }
13085                    })
13086            });
13087
13088            cx.emit(EditorEvent::InputHandled {
13089                utf16_range_to_replace: range_to_replace,
13090                text: text.into(),
13091            });
13092
13093            if let Some(new_selected_ranges) = new_selected_ranges {
13094                this.change_selections(None, cx, |selections| {
13095                    selections.select_ranges(new_selected_ranges)
13096                });
13097                this.backspace(&Default::default(), cx);
13098            }
13099
13100            this.handle_input(text, cx);
13101        });
13102
13103        if let Some(transaction) = self.ime_transaction {
13104            self.buffer.update(cx, |buffer, cx| {
13105                buffer.group_until_transaction(transaction, cx);
13106            });
13107        }
13108
13109        self.unmark_text(cx);
13110    }
13111
13112    fn replace_and_mark_text_in_range(
13113        &mut self,
13114        range_utf16: Option<Range<usize>>,
13115        text: &str,
13116        new_selected_range_utf16: Option<Range<usize>>,
13117        cx: &mut ViewContext<Self>,
13118    ) {
13119        if !self.input_enabled {
13120            return;
13121        }
13122
13123        let transaction = self.transact(cx, |this, cx| {
13124            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13125                let snapshot = this.buffer.read(cx).read(cx);
13126                if let Some(relative_range_utf16) = range_utf16.as_ref() {
13127                    for marked_range in &mut marked_ranges {
13128                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13129                        marked_range.start.0 += relative_range_utf16.start;
13130                        marked_range.start =
13131                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13132                        marked_range.end =
13133                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13134                    }
13135                }
13136                Some(marked_ranges)
13137            } else if let Some(range_utf16) = range_utf16 {
13138                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13139                Some(this.selection_replacement_ranges(range_utf16, cx))
13140            } else {
13141                None
13142            };
13143
13144            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13145                let newest_selection_id = this.selections.newest_anchor().id;
13146                this.selections
13147                    .all::<OffsetUtf16>(cx)
13148                    .iter()
13149                    .zip(ranges_to_replace.iter())
13150                    .find_map(|(selection, range)| {
13151                        if selection.id == newest_selection_id {
13152                            Some(
13153                                (range.start.0 as isize - selection.head().0 as isize)
13154                                    ..(range.end.0 as isize - selection.head().0 as isize),
13155                            )
13156                        } else {
13157                            None
13158                        }
13159                    })
13160            });
13161
13162            cx.emit(EditorEvent::InputHandled {
13163                utf16_range_to_replace: range_to_replace,
13164                text: text.into(),
13165            });
13166
13167            if let Some(ranges) = ranges_to_replace {
13168                this.change_selections(None, cx, |s| s.select_ranges(ranges));
13169            }
13170
13171            let marked_ranges = {
13172                let snapshot = this.buffer.read(cx).read(cx);
13173                this.selections
13174                    .disjoint_anchors()
13175                    .iter()
13176                    .map(|selection| {
13177                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13178                    })
13179                    .collect::<Vec<_>>()
13180            };
13181
13182            if text.is_empty() {
13183                this.unmark_text(cx);
13184            } else {
13185                this.highlight_text::<InputComposition>(
13186                    marked_ranges.clone(),
13187                    HighlightStyle {
13188                        underline: Some(UnderlineStyle {
13189                            thickness: px(1.),
13190                            color: None,
13191                            wavy: false,
13192                        }),
13193                        ..Default::default()
13194                    },
13195                    cx,
13196                );
13197            }
13198
13199            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13200            let use_autoclose = this.use_autoclose;
13201            let use_auto_surround = this.use_auto_surround;
13202            this.set_use_autoclose(false);
13203            this.set_use_auto_surround(false);
13204            this.handle_input(text, cx);
13205            this.set_use_autoclose(use_autoclose);
13206            this.set_use_auto_surround(use_auto_surround);
13207
13208            if let Some(new_selected_range) = new_selected_range_utf16 {
13209                let snapshot = this.buffer.read(cx).read(cx);
13210                let new_selected_ranges = marked_ranges
13211                    .into_iter()
13212                    .map(|marked_range| {
13213                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13214                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13215                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13216                        snapshot.clip_offset_utf16(new_start, Bias::Left)
13217                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13218                    })
13219                    .collect::<Vec<_>>();
13220
13221                drop(snapshot);
13222                this.change_selections(None, cx, |selections| {
13223                    selections.select_ranges(new_selected_ranges)
13224                });
13225            }
13226        });
13227
13228        self.ime_transaction = self.ime_transaction.or(transaction);
13229        if let Some(transaction) = self.ime_transaction {
13230            self.buffer.update(cx, |buffer, cx| {
13231                buffer.group_until_transaction(transaction, cx);
13232            });
13233        }
13234
13235        if self.text_highlights::<InputComposition>(cx).is_none() {
13236            self.ime_transaction.take();
13237        }
13238    }
13239
13240    fn bounds_for_range(
13241        &mut self,
13242        range_utf16: Range<usize>,
13243        element_bounds: gpui::Bounds<Pixels>,
13244        cx: &mut ViewContext<Self>,
13245    ) -> Option<gpui::Bounds<Pixels>> {
13246        let text_layout_details = self.text_layout_details(cx);
13247        let style = &text_layout_details.editor_style;
13248        let font_id = cx.text_system().resolve_font(&style.text.font());
13249        let font_size = style.text.font_size.to_pixels(cx.rem_size());
13250        let line_height = style.text.line_height_in_pixels(cx.rem_size());
13251
13252        let em_width = cx
13253            .text_system()
13254            .typographic_bounds(font_id, font_size, 'm')
13255            .unwrap()
13256            .size
13257            .width;
13258
13259        let snapshot = self.snapshot(cx);
13260        let scroll_position = snapshot.scroll_position();
13261        let scroll_left = scroll_position.x * em_width;
13262
13263        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13264        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13265            + self.gutter_dimensions.width;
13266        let y = line_height * (start.row().as_f32() - scroll_position.y);
13267
13268        Some(Bounds {
13269            origin: element_bounds.origin + point(x, y),
13270            size: size(em_width, line_height),
13271        })
13272    }
13273}
13274
13275trait SelectionExt {
13276    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13277    fn spanned_rows(
13278        &self,
13279        include_end_if_at_line_start: bool,
13280        map: &DisplaySnapshot,
13281    ) -> Range<MultiBufferRow>;
13282}
13283
13284impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13285    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13286        let start = self
13287            .start
13288            .to_point(&map.buffer_snapshot)
13289            .to_display_point(map);
13290        let end = self
13291            .end
13292            .to_point(&map.buffer_snapshot)
13293            .to_display_point(map);
13294        if self.reversed {
13295            end..start
13296        } else {
13297            start..end
13298        }
13299    }
13300
13301    fn spanned_rows(
13302        &self,
13303        include_end_if_at_line_start: bool,
13304        map: &DisplaySnapshot,
13305    ) -> Range<MultiBufferRow> {
13306        let start = self.start.to_point(&map.buffer_snapshot);
13307        let mut end = self.end.to_point(&map.buffer_snapshot);
13308        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13309            end.row -= 1;
13310        }
13311
13312        let buffer_start = map.prev_line_boundary(start).0;
13313        let buffer_end = map.next_line_boundary(end).0;
13314        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13315    }
13316}
13317
13318impl<T: InvalidationRegion> InvalidationStack<T> {
13319    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13320    where
13321        S: Clone + ToOffset,
13322    {
13323        while let Some(region) = self.last() {
13324            let all_selections_inside_invalidation_ranges =
13325                if selections.len() == region.ranges().len() {
13326                    selections
13327                        .iter()
13328                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13329                        .all(|(selection, invalidation_range)| {
13330                            let head = selection.head().to_offset(buffer);
13331                            invalidation_range.start <= head && invalidation_range.end >= head
13332                        })
13333                } else {
13334                    false
13335                };
13336
13337            if all_selections_inside_invalidation_ranges {
13338                break;
13339            } else {
13340                self.pop();
13341            }
13342        }
13343    }
13344}
13345
13346impl<T> Default for InvalidationStack<T> {
13347    fn default() -> Self {
13348        Self(Default::default())
13349    }
13350}
13351
13352impl<T> Deref for InvalidationStack<T> {
13353    type Target = Vec<T>;
13354
13355    fn deref(&self) -> &Self::Target {
13356        &self.0
13357    }
13358}
13359
13360impl<T> DerefMut for InvalidationStack<T> {
13361    fn deref_mut(&mut self) -> &mut Self::Target {
13362        &mut self.0
13363    }
13364}
13365
13366impl InvalidationRegion for SnippetState {
13367    fn ranges(&self) -> &[Range<Anchor>] {
13368        &self.ranges[self.active_index]
13369    }
13370}
13371
13372pub fn diagnostic_block_renderer(
13373    diagnostic: Diagnostic,
13374    max_message_rows: Option<u8>,
13375    allow_closing: bool,
13376    _is_valid: bool,
13377) -> RenderBlock {
13378    let (text_without_backticks, code_ranges) =
13379        highlight_diagnostic_message(&diagnostic, max_message_rows);
13380
13381    Box::new(move |cx: &mut BlockContext| {
13382        let group_id: SharedString = cx.block_id.to_string().into();
13383
13384        let mut text_style = cx.text_style().clone();
13385        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13386        let theme_settings = ThemeSettings::get_global(cx);
13387        text_style.font_family = theme_settings.buffer_font.family.clone();
13388        text_style.font_style = theme_settings.buffer_font.style;
13389        text_style.font_features = theme_settings.buffer_font.features.clone();
13390        text_style.font_weight = theme_settings.buffer_font.weight;
13391
13392        let multi_line_diagnostic = diagnostic.message.contains('\n');
13393
13394        let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13395            if multi_line_diagnostic {
13396                v_flex()
13397            } else {
13398                h_flex()
13399            }
13400            .when(allow_closing, |div| {
13401                div.children(diagnostic.is_primary.then(|| {
13402                    IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13403                        .icon_color(Color::Muted)
13404                        .size(ButtonSize::Compact)
13405                        .style(ButtonStyle::Transparent)
13406                        .visible_on_hover(group_id.clone())
13407                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13408                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13409                }))
13410            })
13411            .child(
13412                IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13413                    .icon_color(Color::Muted)
13414                    .size(ButtonSize::Compact)
13415                    .style(ButtonStyle::Transparent)
13416                    .visible_on_hover(group_id.clone())
13417                    .on_click({
13418                        let message = diagnostic.message.clone();
13419                        move |_click, cx| {
13420                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13421                        }
13422                    })
13423                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13424            )
13425        };
13426
13427        let icon_size = buttons(&diagnostic, cx.block_id)
13428            .into_any_element()
13429            .layout_as_root(AvailableSpace::min_size(), cx);
13430
13431        h_flex()
13432            .id(cx.block_id)
13433            .group(group_id.clone())
13434            .relative()
13435            .size_full()
13436            .pl(cx.gutter_dimensions.width)
13437            .w(cx.max_width + cx.gutter_dimensions.width)
13438            .child(
13439                div()
13440                    .flex()
13441                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13442                    .flex_shrink(),
13443            )
13444            .child(buttons(&diagnostic, cx.block_id))
13445            .child(div().flex().flex_shrink_0().child(
13446                StyledText::new(text_without_backticks.clone()).with_highlights(
13447                    &text_style,
13448                    code_ranges.iter().map(|range| {
13449                        (
13450                            range.clone(),
13451                            HighlightStyle {
13452                                font_weight: Some(FontWeight::BOLD),
13453                                ..Default::default()
13454                            },
13455                        )
13456                    }),
13457                ),
13458            ))
13459            .into_any_element()
13460    })
13461}
13462
13463pub fn highlight_diagnostic_message(
13464    diagnostic: &Diagnostic,
13465    mut max_message_rows: Option<u8>,
13466) -> (SharedString, Vec<Range<usize>>) {
13467    let mut text_without_backticks = String::new();
13468    let mut code_ranges = Vec::new();
13469
13470    if let Some(source) = &diagnostic.source {
13471        text_without_backticks.push_str(source);
13472        code_ranges.push(0..source.len());
13473        text_without_backticks.push_str(": ");
13474    }
13475
13476    let mut prev_offset = 0;
13477    let mut in_code_block = false;
13478    let has_row_limit = max_message_rows.is_some();
13479    let mut newline_indices = diagnostic
13480        .message
13481        .match_indices('\n')
13482        .filter(|_| has_row_limit)
13483        .map(|(ix, _)| ix)
13484        .fuse()
13485        .peekable();
13486
13487    for (quote_ix, _) in diagnostic
13488        .message
13489        .match_indices('`')
13490        .chain([(diagnostic.message.len(), "")])
13491    {
13492        let mut first_newline_ix = None;
13493        let mut last_newline_ix = None;
13494        while let Some(newline_ix) = newline_indices.peek() {
13495            if *newline_ix < quote_ix {
13496                if first_newline_ix.is_none() {
13497                    first_newline_ix = Some(*newline_ix);
13498                }
13499                last_newline_ix = Some(*newline_ix);
13500
13501                if let Some(rows_left) = &mut max_message_rows {
13502                    if *rows_left == 0 {
13503                        break;
13504                    } else {
13505                        *rows_left -= 1;
13506                    }
13507                }
13508                let _ = newline_indices.next();
13509            } else {
13510                break;
13511            }
13512        }
13513        let prev_len = text_without_backticks.len();
13514        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13515        text_without_backticks.push_str(new_text);
13516        if in_code_block {
13517            code_ranges.push(prev_len..text_without_backticks.len());
13518        }
13519        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13520        in_code_block = !in_code_block;
13521        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13522            text_without_backticks.push_str("...");
13523            break;
13524        }
13525    }
13526
13527    (text_without_backticks.into(), code_ranges)
13528}
13529
13530fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13531    match severity {
13532        DiagnosticSeverity::ERROR => colors.error,
13533        DiagnosticSeverity::WARNING => colors.warning,
13534        DiagnosticSeverity::INFORMATION => colors.info,
13535        DiagnosticSeverity::HINT => colors.info,
13536        _ => colors.ignored,
13537    }
13538}
13539
13540pub fn styled_runs_for_code_label<'a>(
13541    label: &'a CodeLabel,
13542    syntax_theme: &'a theme::SyntaxTheme,
13543) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13544    let fade_out = HighlightStyle {
13545        fade_out: Some(0.35),
13546        ..Default::default()
13547    };
13548
13549    let mut prev_end = label.filter_range.end;
13550    label
13551        .runs
13552        .iter()
13553        .enumerate()
13554        .flat_map(move |(ix, (range, highlight_id))| {
13555            let style = if let Some(style) = highlight_id.style(syntax_theme) {
13556                style
13557            } else {
13558                return Default::default();
13559            };
13560            let mut muted_style = style;
13561            muted_style.highlight(fade_out);
13562
13563            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13564            if range.start >= label.filter_range.end {
13565                if range.start > prev_end {
13566                    runs.push((prev_end..range.start, fade_out));
13567                }
13568                runs.push((range.clone(), muted_style));
13569            } else if range.end <= label.filter_range.end {
13570                runs.push((range.clone(), style));
13571            } else {
13572                runs.push((range.start..label.filter_range.end, style));
13573                runs.push((label.filter_range.end..range.end, muted_style));
13574            }
13575            prev_end = cmp::max(prev_end, range.end);
13576
13577            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13578                runs.push((prev_end..label.text.len(), fade_out));
13579            }
13580
13581            runs
13582        })
13583}
13584
13585pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13586    let mut prev_index = 0;
13587    let mut prev_codepoint: Option<char> = None;
13588    text.char_indices()
13589        .chain([(text.len(), '\0')])
13590        .filter_map(move |(index, codepoint)| {
13591            let prev_codepoint = prev_codepoint.replace(codepoint)?;
13592            let is_boundary = index == text.len()
13593                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13594                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13595            if is_boundary {
13596                let chunk = &text[prev_index..index];
13597                prev_index = index;
13598                Some(chunk)
13599            } else {
13600                None
13601            }
13602        })
13603}
13604
13605pub trait RangeToAnchorExt: Sized {
13606    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13607
13608    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13609        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13610        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
13611    }
13612}
13613
13614impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13615    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13616        let start_offset = self.start.to_offset(snapshot);
13617        let end_offset = self.end.to_offset(snapshot);
13618        if start_offset == end_offset {
13619            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13620        } else {
13621            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13622        }
13623    }
13624}
13625
13626pub trait RowExt {
13627    fn as_f32(&self) -> f32;
13628
13629    fn next_row(&self) -> Self;
13630
13631    fn previous_row(&self) -> Self;
13632
13633    fn minus(&self, other: Self) -> u32;
13634}
13635
13636impl RowExt for DisplayRow {
13637    fn as_f32(&self) -> f32 {
13638        self.0 as f32
13639    }
13640
13641    fn next_row(&self) -> Self {
13642        Self(self.0 + 1)
13643    }
13644
13645    fn previous_row(&self) -> Self {
13646        Self(self.0.saturating_sub(1))
13647    }
13648
13649    fn minus(&self, other: Self) -> u32 {
13650        self.0 - other.0
13651    }
13652}
13653
13654impl RowExt for MultiBufferRow {
13655    fn as_f32(&self) -> f32 {
13656        self.0 as f32
13657    }
13658
13659    fn next_row(&self) -> Self {
13660        Self(self.0 + 1)
13661    }
13662
13663    fn previous_row(&self) -> Self {
13664        Self(self.0.saturating_sub(1))
13665    }
13666
13667    fn minus(&self, other: Self) -> u32 {
13668        self.0 - other.0
13669    }
13670}
13671
13672trait RowRangeExt {
13673    type Row;
13674
13675    fn len(&self) -> usize;
13676
13677    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13678}
13679
13680impl RowRangeExt for Range<MultiBufferRow> {
13681    type Row = MultiBufferRow;
13682
13683    fn len(&self) -> usize {
13684        (self.end.0 - self.start.0) as usize
13685    }
13686
13687    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13688        (self.start.0..self.end.0).map(MultiBufferRow)
13689    }
13690}
13691
13692impl RowRangeExt for Range<DisplayRow> {
13693    type Row = DisplayRow;
13694
13695    fn len(&self) -> usize {
13696        (self.end.0 - self.start.0) as usize
13697    }
13698
13699    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13700        (self.start.0..self.end.0).map(DisplayRow)
13701    }
13702}
13703
13704fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13705    if hunk.diff_base_byte_range.is_empty() {
13706        DiffHunkStatus::Added
13707    } else if hunk.associated_range.is_empty() {
13708        DiffHunkStatus::Removed
13709    } else {
13710        DiffHunkStatus::Modified
13711    }
13712}
13713
13714/// If select range has more than one line, we
13715/// just point the cursor to range.start.
13716fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13717    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13718        range
13719    } else {
13720        range.start..range.start
13721    }
13722}