editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behaviour.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod debounced_delay;
   19pub mod display_map;
   20mod editor_settings;
   21mod element;
   22mod git;
   23mod highlight_matching_bracket;
   24mod hover_links;
   25mod hover_popover;
   26mod hunk_diff;
   27mod indent_guides;
   28mod inlay_hint_cache;
   29mod inline_completion_provider;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod mouse_context_menu;
   33pub mod movement;
   34mod persistence;
   35mod rust_analyzer_ext;
   36pub mod scroll;
   37mod selections_collection;
   38pub mod tasks;
   39
   40#[cfg(test)]
   41mod editor_tests;
   42mod signature_help;
   43#[cfg(any(test, feature = "test-support"))]
   44pub mod test;
   45
   46use ::git::diff::{DiffHunk, DiffHunkStatus};
   47use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
   48pub(crate) use actions::*;
   49use aho_corasick::AhoCorasick;
   50use anyhow::{anyhow, Context as _, Result};
   51use blink_manager::BlinkManager;
   52use client::{Collaborator, ParticipantIndex};
   53use clock::ReplicaId;
   54use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   55use convert_case::{Case, Casing};
   56use debounced_delay::DebouncedDelay;
   57use display_map::*;
   58pub use display_map::{DisplayPoint, FoldPlaceholder};
   59pub use editor_settings::{CurrentLineHighlight, EditorSettings};
   60use element::LineWithInvisibles;
   61pub use element::{
   62    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   63};
   64use futures::FutureExt;
   65use fuzzy::{StringMatch, StringMatchCandidate};
   66use git::blame::GitBlame;
   67use git::diff_hunk_to_display;
   68use gpui::{
   69    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   70    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardItem,
   71    Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle, FocusOutEvent,
   72    FocusableView, FontId, FontStyle, FontWeight, HighlightStyle, Hsla, InteractiveText,
   73    KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
   74    SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
   75    UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext,
   76    WeakFocusHandle, WeakView, WhiteSpace, WindowContext,
   77};
   78use highlight_matching_bracket::refresh_matching_bracket_highlights;
   79use hover_popover::{hide_hover, HoverState};
   80use hunk_diff::ExpandedHunks;
   81pub(crate) use hunk_diff::HunkToExpand;
   82use indent_guides::ActiveIndentGuidesState;
   83use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   84pub use inline_completion_provider::*;
   85pub use items::MAX_TAB_TITLE_LEN;
   86use itertools::Itertools;
   87use language::{
   88    char_kind,
   89    language_settings::{self, all_language_settings, InlayHintSettings},
   90    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   91    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   92    Point, Selection, SelectionGoal, TransactionId,
   93};
   94use language::{point_to_lsp, BufferRow, Runnable, RunnableRange};
   95use linked_editing_ranges::refresh_linked_ranges;
   96use task::{ResolvedTask, TaskTemplate, TaskVariables};
   97
   98use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
   99pub use lsp::CompletionContext;
  100use lsp::{
  101    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  102    LanguageServerId,
  103};
  104use mouse_context_menu::MouseContextMenu;
  105use movement::TextLayoutDetails;
  106pub use multi_buffer::{
  107    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  108    ToPoint,
  109};
  110use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
  111use ordered_float::OrderedFloat;
  112use parking_lot::{Mutex, RwLock};
  113use project::project_settings::{GitGutterSetting, ProjectSettings};
  114use project::{
  115    CodeAction, Completion, FormatTrigger, Item, Location, Project, ProjectPath,
  116    ProjectTransaction, TaskSourceKind, WorktreeId,
  117};
  118use rand::prelude::*;
  119use rpc::{proto::*, ErrorExt};
  120use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  121use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  122use serde::{Deserialize, Serialize};
  123use settings::{update_settings_file, Settings, SettingsStore};
  124use smallvec::SmallVec;
  125use snippet::Snippet;
  126use std::{
  127    any::TypeId,
  128    borrow::Cow,
  129    cell::RefCell,
  130    cmp::{self, Ordering, Reverse},
  131    mem,
  132    num::NonZeroU32,
  133    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  134    path::Path,
  135    rc::Rc,
  136    sync::Arc,
  137    time::{Duration, Instant},
  138};
  139pub use sum_tree::Bias;
  140use sum_tree::TreeMap;
  141use text::{BufferId, OffsetUtf16, Rope};
  142use theme::{
  143    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  144    ThemeColors, ThemeSettings,
  145};
  146use ui::{
  147    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  148    ListItem, Popover, Tooltip,
  149};
  150use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  151use workspace::item::{ItemHandle, PreviewTabsSettings};
  152use workspace::notifications::{DetachAndPromptErr, NotificationId};
  153use workspace::{
  154    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  155};
  156use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  157
  158use crate::hover_links::find_url;
  159use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  160
  161pub const FILE_HEADER_HEIGHT: u8 = 1;
  162pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u8 = 1;
  163pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u8 = 1;
  164pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  165const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  166const MAX_LINE_LEN: usize = 1024;
  167const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  168const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  169pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  170#[doc(hidden)]
  171pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  172#[doc(hidden)]
  173pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  174
  175pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  176
  177pub fn render_parsed_markdown(
  178    element_id: impl Into<ElementId>,
  179    parsed: &language::ParsedMarkdown,
  180    editor_style: &EditorStyle,
  181    workspace: Option<WeakView<Workspace>>,
  182    cx: &mut WindowContext,
  183) -> InteractiveText {
  184    let code_span_background_color = cx
  185        .theme()
  186        .colors()
  187        .editor_document_highlight_read_background;
  188
  189    let highlights = gpui::combine_highlights(
  190        parsed.highlights.iter().filter_map(|(range, highlight)| {
  191            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  192            Some((range.clone(), highlight))
  193        }),
  194        parsed
  195            .regions
  196            .iter()
  197            .zip(&parsed.region_ranges)
  198            .filter_map(|(region, range)| {
  199                if region.code {
  200                    Some((
  201                        range.clone(),
  202                        HighlightStyle {
  203                            background_color: Some(code_span_background_color),
  204                            ..Default::default()
  205                        },
  206                    ))
  207                } else {
  208                    None
  209                }
  210            }),
  211    );
  212
  213    let mut links = Vec::new();
  214    let mut link_ranges = Vec::new();
  215    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  216        if let Some(link) = region.link.clone() {
  217            links.push(link);
  218            link_ranges.push(range.clone());
  219        }
  220    }
  221
  222    InteractiveText::new(
  223        element_id,
  224        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  225    )
  226    .on_click(link_ranges, move |clicked_range_ix, cx| {
  227        match &links[clicked_range_ix] {
  228            markdown::Link::Web { url } => cx.open_url(url),
  229            markdown::Link::Path { path } => {
  230                if let Some(workspace) = &workspace {
  231                    _ = workspace.update(cx, |workspace, cx| {
  232                        workspace.open_abs_path(path.clone(), false, cx).detach();
  233                    });
  234                }
  235            }
  236        }
  237    })
  238}
  239
  240#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  241pub(crate) enum InlayId {
  242    Suggestion(usize),
  243    Hint(usize),
  244}
  245
  246impl InlayId {
  247    fn id(&self) -> usize {
  248        match self {
  249            Self::Suggestion(id) => *id,
  250            Self::Hint(id) => *id,
  251        }
  252    }
  253}
  254
  255enum DiffRowHighlight {}
  256enum DocumentHighlightRead {}
  257enum DocumentHighlightWrite {}
  258enum InputComposition {}
  259
  260#[derive(Copy, Clone, PartialEq, Eq)]
  261pub enum Direction {
  262    Prev,
  263    Next,
  264}
  265
  266pub fn init_settings(cx: &mut AppContext) {
  267    EditorSettings::register(cx);
  268}
  269
  270pub fn init(cx: &mut AppContext) {
  271    init_settings(cx);
  272
  273    workspace::register_project_item::<Editor>(cx);
  274    workspace::FollowableViewRegistry::register::<Editor>(cx);
  275    workspace::register_deserializable_item::<Editor>(cx);
  276    cx.observe_new_views(
  277        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  278            workspace.register_action(Editor::new_file);
  279            workspace.register_action(Editor::new_file_in_direction);
  280        },
  281    )
  282    .detach();
  283
  284    cx.on_action(move |_: &workspace::NewFile, cx| {
  285        let app_state = workspace::AppState::global(cx);
  286        if let Some(app_state) = app_state.upgrade() {
  287            workspace::open_new(app_state, cx, |workspace, cx| {
  288                Editor::new_file(workspace, &Default::default(), cx)
  289            })
  290            .detach();
  291        }
  292    });
  293    cx.on_action(move |_: &workspace::NewWindow, cx| {
  294        let app_state = workspace::AppState::global(cx);
  295        if let Some(app_state) = app_state.upgrade() {
  296            workspace::open_new(app_state, cx, |workspace, cx| {
  297                Editor::new_file(workspace, &Default::default(), cx)
  298            })
  299            .detach();
  300        }
  301    });
  302}
  303
  304pub struct SearchWithinRange;
  305
  306trait InvalidationRegion {
  307    fn ranges(&self) -> &[Range<Anchor>];
  308}
  309
  310#[derive(Clone, Debug, PartialEq)]
  311pub enum SelectPhase {
  312    Begin {
  313        position: DisplayPoint,
  314        add: bool,
  315        click_count: usize,
  316    },
  317    BeginColumnar {
  318        position: DisplayPoint,
  319        reset: bool,
  320        goal_column: u32,
  321    },
  322    Extend {
  323        position: DisplayPoint,
  324        click_count: usize,
  325    },
  326    Update {
  327        position: DisplayPoint,
  328        goal_column: u32,
  329        scroll_delta: gpui::Point<f32>,
  330    },
  331    End,
  332}
  333
  334#[derive(Clone, Debug)]
  335pub enum SelectMode {
  336    Character,
  337    Word(Range<Anchor>),
  338    Line(Range<Anchor>),
  339    All,
  340}
  341
  342#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  343pub enum EditorMode {
  344    SingleLine { auto_width: bool },
  345    AutoHeight { max_lines: usize },
  346    Full,
  347}
  348
  349#[derive(Clone, Debug)]
  350pub enum SoftWrap {
  351    None,
  352    PreferLine,
  353    EditorWidth,
  354    Column(u32),
  355}
  356
  357#[derive(Clone)]
  358pub struct EditorStyle {
  359    pub background: Hsla,
  360    pub local_player: PlayerColor,
  361    pub text: TextStyle,
  362    pub scrollbar_width: Pixels,
  363    pub syntax: Arc<SyntaxTheme>,
  364    pub status: StatusColors,
  365    pub inlay_hints_style: HighlightStyle,
  366    pub suggestions_style: HighlightStyle,
  367}
  368
  369impl Default for EditorStyle {
  370    fn default() -> Self {
  371        Self {
  372            background: Hsla::default(),
  373            local_player: PlayerColor::default(),
  374            text: TextStyle::default(),
  375            scrollbar_width: Pixels::default(),
  376            syntax: Default::default(),
  377            // HACK: Status colors don't have a real default.
  378            // We should look into removing the status colors from the editor
  379            // style and retrieve them directly from the theme.
  380            status: StatusColors::dark(),
  381            inlay_hints_style: HighlightStyle::default(),
  382            suggestions_style: HighlightStyle::default(),
  383        }
  384    }
  385}
  386
  387type CompletionId = usize;
  388
  389#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  390struct EditorActionId(usize);
  391
  392impl EditorActionId {
  393    pub fn post_inc(&mut self) -> Self {
  394        let answer = self.0;
  395
  396        *self = Self(answer + 1);
  397
  398        Self(answer)
  399    }
  400}
  401
  402// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  403// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  404
  405type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  406type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  407
  408struct ScrollbarMarkerState {
  409    scrollbar_size: Size<Pixels>,
  410    dirty: bool,
  411    markers: Arc<[PaintQuad]>,
  412    pending_refresh: Option<Task<Result<()>>>,
  413}
  414
  415impl ScrollbarMarkerState {
  416    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  417        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  418    }
  419}
  420
  421impl Default for ScrollbarMarkerState {
  422    fn default() -> Self {
  423        Self {
  424            scrollbar_size: Size::default(),
  425            dirty: false,
  426            markers: Arc::from([]),
  427            pending_refresh: None,
  428        }
  429    }
  430}
  431
  432#[derive(Clone, Debug)]
  433struct RunnableTasks {
  434    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  435    offset: MultiBufferOffset,
  436    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  437    column: u32,
  438    // Values of all named captures, including those starting with '_'
  439    extra_variables: HashMap<String, String>,
  440    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  441    context_range: Range<BufferOffset>,
  442}
  443
  444#[derive(Clone)]
  445struct ResolvedTasks {
  446    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  447    position: Anchor,
  448}
  449#[derive(Copy, Clone, Debug)]
  450struct MultiBufferOffset(usize);
  451#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  452struct BufferOffset(usize);
  453/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  454///
  455/// See the [module level documentation](self) for more information.
  456pub struct Editor {
  457    focus_handle: FocusHandle,
  458    last_focused_descendant: Option<WeakFocusHandle>,
  459    /// The text buffer being edited
  460    buffer: Model<MultiBuffer>,
  461    /// Map of how text in the buffer should be displayed.
  462    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  463    pub display_map: Model<DisplayMap>,
  464    pub selections: SelectionsCollection,
  465    pub scroll_manager: ScrollManager,
  466    /// When inline assist editors are linked, they all render cursors because
  467    /// typing enters text into each of them, even the ones that aren't focused.
  468    pub(crate) show_cursor_when_unfocused: bool,
  469    columnar_selection_tail: Option<Anchor>,
  470    add_selections_state: Option<AddSelectionsState>,
  471    select_next_state: Option<SelectNextState>,
  472    select_prev_state: Option<SelectNextState>,
  473    selection_history: SelectionHistory,
  474    autoclose_regions: Vec<AutocloseRegion>,
  475    snippet_stack: InvalidationStack<SnippetState>,
  476    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  477    ime_transaction: Option<TransactionId>,
  478    active_diagnostics: Option<ActiveDiagnosticGroup>,
  479    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  480    project: Option<Model<Project>>,
  481    completion_provider: Option<Box<dyn CompletionProvider>>,
  482    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  483    blink_manager: Model<BlinkManager>,
  484    show_cursor_names: bool,
  485    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  486    pub show_local_selections: bool,
  487    mode: EditorMode,
  488    show_breadcrumbs: bool,
  489    show_gutter: bool,
  490    show_line_numbers: Option<bool>,
  491    show_git_diff_gutter: Option<bool>,
  492    show_code_actions: Option<bool>,
  493    show_runnables: Option<bool>,
  494    show_wrap_guides: Option<bool>,
  495    show_indent_guides: Option<bool>,
  496    placeholder_text: Option<Arc<str>>,
  497    highlight_order: usize,
  498    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  499    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  500    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  501    scrollbar_marker_state: ScrollbarMarkerState,
  502    active_indent_guides_state: ActiveIndentGuidesState,
  503    nav_history: Option<ItemNavHistory>,
  504    context_menu: RwLock<Option<ContextMenu>>,
  505    mouse_context_menu: Option<MouseContextMenu>,
  506    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  507    signature_help_state: SignatureHelpState,
  508    auto_signature_help: Option<bool>,
  509    find_all_references_task_sources: Vec<Anchor>,
  510    next_completion_id: CompletionId,
  511    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  512    available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
  513    code_actions_task: Option<Task<()>>,
  514    document_highlights_task: Option<Task<()>>,
  515    linked_editing_range_task: Option<Task<Option<()>>>,
  516    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  517    pending_rename: Option<RenameState>,
  518    searchable: bool,
  519    cursor_shape: CursorShape,
  520    current_line_highlight: Option<CurrentLineHighlight>,
  521    collapse_matches: bool,
  522    autoindent_mode: Option<AutoindentMode>,
  523    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  524    keymap_context_layers: BTreeMap<TypeId, KeyContext>,
  525    input_enabled: bool,
  526    use_modal_editing: bool,
  527    read_only: bool,
  528    leader_peer_id: Option<PeerId>,
  529    remote_id: Option<ViewId>,
  530    hover_state: HoverState,
  531    gutter_hovered: bool,
  532    hovered_link_state: Option<HoveredLinkState>,
  533    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  534    active_inline_completion: Option<Inlay>,
  535    show_inline_completions: bool,
  536    inlay_hint_cache: InlayHintCache,
  537    expanded_hunks: ExpandedHunks,
  538    next_inlay_id: usize,
  539    _subscriptions: Vec<Subscription>,
  540    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  541    gutter_dimensions: GutterDimensions,
  542    pub vim_replace_map: HashMap<Range<usize>, String>,
  543    style: Option<EditorStyle>,
  544    next_editor_action_id: EditorActionId,
  545    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  546    use_autoclose: bool,
  547    use_auto_surround: bool,
  548    auto_replace_emoji_shortcode: bool,
  549    show_git_blame_gutter: bool,
  550    show_git_blame_inline: bool,
  551    show_git_blame_inline_delay_task: Option<Task<()>>,
  552    git_blame_inline_enabled: bool,
  553    show_selection_menu: Option<bool>,
  554    blame: Option<Model<GitBlame>>,
  555    blame_subscription: Option<Subscription>,
  556    custom_context_menu: Option<
  557        Box<
  558            dyn 'static
  559                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  560        >,
  561    >,
  562    last_bounds: Option<Bounds<Pixels>>,
  563    expect_bounds_change: Option<Bounds<Pixels>>,
  564    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  565    tasks_update_task: Option<Task<()>>,
  566    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  567    file_header_size: u8,
  568    breadcrumb_header: Option<String>,
  569}
  570
  571#[derive(Clone)]
  572pub struct EditorSnapshot {
  573    pub mode: EditorMode,
  574    show_gutter: bool,
  575    show_line_numbers: Option<bool>,
  576    show_git_diff_gutter: Option<bool>,
  577    show_code_actions: Option<bool>,
  578    show_runnables: Option<bool>,
  579    render_git_blame_gutter: bool,
  580    pub display_snapshot: DisplaySnapshot,
  581    pub placeholder_text: Option<Arc<str>>,
  582    is_focused: bool,
  583    scroll_anchor: ScrollAnchor,
  584    ongoing_scroll: OngoingScroll,
  585    current_line_highlight: CurrentLineHighlight,
  586    gutter_hovered: bool,
  587}
  588
  589const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
  590
  591#[derive(Debug, Clone, Copy)]
  592pub struct GutterDimensions {
  593    pub left_padding: Pixels,
  594    pub right_padding: Pixels,
  595    pub width: Pixels,
  596    pub margin: Pixels,
  597    pub git_blame_entries_width: Option<Pixels>,
  598}
  599
  600impl GutterDimensions {
  601    /// The full width of the space taken up by the gutter.
  602    pub fn full_width(&self) -> Pixels {
  603        self.margin + self.width
  604    }
  605
  606    /// The width of the space reserved for the fold indicators,
  607    /// use alongside 'justify_end' and `gutter_width` to
  608    /// right align content with the line numbers
  609    pub fn fold_area_width(&self) -> Pixels {
  610        self.margin + self.right_padding
  611    }
  612}
  613
  614impl Default for GutterDimensions {
  615    fn default() -> Self {
  616        Self {
  617            left_padding: Pixels::ZERO,
  618            right_padding: Pixels::ZERO,
  619            width: Pixels::ZERO,
  620            margin: Pixels::ZERO,
  621            git_blame_entries_width: None,
  622        }
  623    }
  624}
  625
  626#[derive(Debug)]
  627pub struct RemoteSelection {
  628    pub replica_id: ReplicaId,
  629    pub selection: Selection<Anchor>,
  630    pub cursor_shape: CursorShape,
  631    pub peer_id: PeerId,
  632    pub line_mode: bool,
  633    pub participant_index: Option<ParticipantIndex>,
  634    pub user_name: Option<SharedString>,
  635}
  636
  637#[derive(Clone, Debug)]
  638struct SelectionHistoryEntry {
  639    selections: Arc<[Selection<Anchor>]>,
  640    select_next_state: Option<SelectNextState>,
  641    select_prev_state: Option<SelectNextState>,
  642    add_selections_state: Option<AddSelectionsState>,
  643}
  644
  645enum SelectionHistoryMode {
  646    Normal,
  647    Undoing,
  648    Redoing,
  649}
  650
  651#[derive(Clone, PartialEq, Eq, Hash)]
  652struct HoveredCursor {
  653    replica_id: u16,
  654    selection_id: usize,
  655}
  656
  657impl Default for SelectionHistoryMode {
  658    fn default() -> Self {
  659        Self::Normal
  660    }
  661}
  662
  663#[derive(Default)]
  664struct SelectionHistory {
  665    #[allow(clippy::type_complexity)]
  666    selections_by_transaction:
  667        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  668    mode: SelectionHistoryMode,
  669    undo_stack: VecDeque<SelectionHistoryEntry>,
  670    redo_stack: VecDeque<SelectionHistoryEntry>,
  671}
  672
  673impl SelectionHistory {
  674    fn insert_transaction(
  675        &mut self,
  676        transaction_id: TransactionId,
  677        selections: Arc<[Selection<Anchor>]>,
  678    ) {
  679        self.selections_by_transaction
  680            .insert(transaction_id, (selections, None));
  681    }
  682
  683    #[allow(clippy::type_complexity)]
  684    fn transaction(
  685        &self,
  686        transaction_id: TransactionId,
  687    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  688        self.selections_by_transaction.get(&transaction_id)
  689    }
  690
  691    #[allow(clippy::type_complexity)]
  692    fn transaction_mut(
  693        &mut self,
  694        transaction_id: TransactionId,
  695    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  696        self.selections_by_transaction.get_mut(&transaction_id)
  697    }
  698
  699    fn push(&mut self, entry: SelectionHistoryEntry) {
  700        if !entry.selections.is_empty() {
  701            match self.mode {
  702                SelectionHistoryMode::Normal => {
  703                    self.push_undo(entry);
  704                    self.redo_stack.clear();
  705                }
  706                SelectionHistoryMode::Undoing => self.push_redo(entry),
  707                SelectionHistoryMode::Redoing => self.push_undo(entry),
  708            }
  709        }
  710    }
  711
  712    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  713        if self
  714            .undo_stack
  715            .back()
  716            .map_or(true, |e| e.selections != entry.selections)
  717        {
  718            self.undo_stack.push_back(entry);
  719            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  720                self.undo_stack.pop_front();
  721            }
  722        }
  723    }
  724
  725    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  726        if self
  727            .redo_stack
  728            .back()
  729            .map_or(true, |e| e.selections != entry.selections)
  730        {
  731            self.redo_stack.push_back(entry);
  732            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  733                self.redo_stack.pop_front();
  734            }
  735        }
  736    }
  737}
  738
  739struct RowHighlight {
  740    index: usize,
  741    range: RangeInclusive<Anchor>,
  742    color: Option<Hsla>,
  743    should_autoscroll: bool,
  744}
  745
  746#[derive(Clone, Debug)]
  747struct AddSelectionsState {
  748    above: bool,
  749    stack: Vec<usize>,
  750}
  751
  752#[derive(Clone)]
  753struct SelectNextState {
  754    query: AhoCorasick,
  755    wordwise: bool,
  756    done: bool,
  757}
  758
  759impl std::fmt::Debug for SelectNextState {
  760    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  761        f.debug_struct(std::any::type_name::<Self>())
  762            .field("wordwise", &self.wordwise)
  763            .field("done", &self.done)
  764            .finish()
  765    }
  766}
  767
  768#[derive(Debug)]
  769struct AutocloseRegion {
  770    selection_id: usize,
  771    range: Range<Anchor>,
  772    pair: BracketPair,
  773}
  774
  775#[derive(Debug)]
  776struct SnippetState {
  777    ranges: Vec<Vec<Range<Anchor>>>,
  778    active_index: usize,
  779}
  780
  781#[doc(hidden)]
  782pub struct RenameState {
  783    pub range: Range<Anchor>,
  784    pub old_name: Arc<str>,
  785    pub editor: View<Editor>,
  786    block_id: BlockId,
  787}
  788
  789struct InvalidationStack<T>(Vec<T>);
  790
  791struct RegisteredInlineCompletionProvider {
  792    provider: Arc<dyn InlineCompletionProviderHandle>,
  793    _subscription: Subscription,
  794}
  795
  796enum ContextMenu {
  797    Completions(CompletionsMenu),
  798    CodeActions(CodeActionsMenu),
  799}
  800
  801impl ContextMenu {
  802    fn select_first(
  803        &mut self,
  804        project: Option<&Model<Project>>,
  805        cx: &mut ViewContext<Editor>,
  806    ) -> bool {
  807        if self.visible() {
  808            match self {
  809                ContextMenu::Completions(menu) => menu.select_first(project, cx),
  810                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  811            }
  812            true
  813        } else {
  814            false
  815        }
  816    }
  817
  818    fn select_prev(
  819        &mut self,
  820        project: Option<&Model<Project>>,
  821        cx: &mut ViewContext<Editor>,
  822    ) -> bool {
  823        if self.visible() {
  824            match self {
  825                ContextMenu::Completions(menu) => menu.select_prev(project, cx),
  826                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  827            }
  828            true
  829        } else {
  830            false
  831        }
  832    }
  833
  834    fn select_next(
  835        &mut self,
  836        project: Option<&Model<Project>>,
  837        cx: &mut ViewContext<Editor>,
  838    ) -> bool {
  839        if self.visible() {
  840            match self {
  841                ContextMenu::Completions(menu) => menu.select_next(project, cx),
  842                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  843            }
  844            true
  845        } else {
  846            false
  847        }
  848    }
  849
  850    fn select_last(
  851        &mut self,
  852        project: Option<&Model<Project>>,
  853        cx: &mut ViewContext<Editor>,
  854    ) -> bool {
  855        if self.visible() {
  856            match self {
  857                ContextMenu::Completions(menu) => menu.select_last(project, cx),
  858                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  859            }
  860            true
  861        } else {
  862            false
  863        }
  864    }
  865
  866    fn visible(&self) -> bool {
  867        match self {
  868            ContextMenu::Completions(menu) => menu.visible(),
  869            ContextMenu::CodeActions(menu) => menu.visible(),
  870        }
  871    }
  872
  873    fn render(
  874        &self,
  875        cursor_position: DisplayPoint,
  876        style: &EditorStyle,
  877        max_height: Pixels,
  878        workspace: Option<WeakView<Workspace>>,
  879        cx: &mut ViewContext<Editor>,
  880    ) -> (ContextMenuOrigin, AnyElement) {
  881        match self {
  882            ContextMenu::Completions(menu) => (
  883                ContextMenuOrigin::EditorPoint(cursor_position),
  884                menu.render(style, max_height, workspace, cx),
  885            ),
  886            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  887        }
  888    }
  889}
  890
  891enum ContextMenuOrigin {
  892    EditorPoint(DisplayPoint),
  893    GutterIndicator(DisplayRow),
  894}
  895
  896#[derive(Clone)]
  897struct CompletionsMenu {
  898    id: CompletionId,
  899    initial_position: Anchor,
  900    buffer: Model<Buffer>,
  901    completions: Arc<RwLock<Box<[Completion]>>>,
  902    match_candidates: Arc<[StringMatchCandidate]>,
  903    matches: Arc<[StringMatch]>,
  904    selected_item: usize,
  905    scroll_handle: UniformListScrollHandle,
  906    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  907}
  908
  909impl CompletionsMenu {
  910    fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  911        self.selected_item = 0;
  912        self.scroll_handle.scroll_to_item(self.selected_item);
  913        self.attempt_resolve_selected_completion_documentation(project, cx);
  914        cx.notify();
  915    }
  916
  917    fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  918        if self.selected_item > 0 {
  919            self.selected_item -= 1;
  920        } else {
  921            self.selected_item = self.matches.len() - 1;
  922        }
  923        self.scroll_handle.scroll_to_item(self.selected_item);
  924        self.attempt_resolve_selected_completion_documentation(project, cx);
  925        cx.notify();
  926    }
  927
  928    fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  929        if self.selected_item + 1 < self.matches.len() {
  930            self.selected_item += 1;
  931        } else {
  932            self.selected_item = 0;
  933        }
  934        self.scroll_handle.scroll_to_item(self.selected_item);
  935        self.attempt_resolve_selected_completion_documentation(project, cx);
  936        cx.notify();
  937    }
  938
  939    fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  940        self.selected_item = self.matches.len() - 1;
  941        self.scroll_handle.scroll_to_item(self.selected_item);
  942        self.attempt_resolve_selected_completion_documentation(project, cx);
  943        cx.notify();
  944    }
  945
  946    fn pre_resolve_completion_documentation(
  947        buffer: Model<Buffer>,
  948        completions: Arc<RwLock<Box<[Completion]>>>,
  949        matches: Arc<[StringMatch]>,
  950        editor: &Editor,
  951        cx: &mut ViewContext<Editor>,
  952    ) -> Task<()> {
  953        let settings = EditorSettings::get_global(cx);
  954        if !settings.show_completion_documentation {
  955            return Task::ready(());
  956        }
  957
  958        let Some(provider) = editor.completion_provider.as_ref() else {
  959            return Task::ready(());
  960        };
  961
  962        let resolve_task = provider.resolve_completions(
  963            buffer,
  964            matches.iter().map(|m| m.candidate_id).collect(),
  965            completions.clone(),
  966            cx,
  967        );
  968
  969        return cx.spawn(move |this, mut cx| async move {
  970            if let Some(true) = resolve_task.await.log_err() {
  971                this.update(&mut cx, |_, cx| cx.notify()).ok();
  972            }
  973        });
  974    }
  975
  976    fn attempt_resolve_selected_completion_documentation(
  977        &mut self,
  978        project: Option<&Model<Project>>,
  979        cx: &mut ViewContext<Editor>,
  980    ) {
  981        let settings = EditorSettings::get_global(cx);
  982        if !settings.show_completion_documentation {
  983            return;
  984        }
  985
  986        let completion_index = self.matches[self.selected_item].candidate_id;
  987        let Some(project) = project else {
  988            return;
  989        };
  990
  991        let resolve_task = project.update(cx, |project, cx| {
  992            project.resolve_completions(
  993                self.buffer.clone(),
  994                vec![completion_index],
  995                self.completions.clone(),
  996                cx,
  997            )
  998        });
  999
 1000        let delay_ms =
 1001            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1002        let delay = Duration::from_millis(delay_ms);
 1003
 1004        self.selected_completion_documentation_resolve_debounce
 1005            .lock()
 1006            .fire_new(delay, cx, |_, cx| {
 1007                cx.spawn(move |this, mut cx| async move {
 1008                    if let Some(true) = resolve_task.await.log_err() {
 1009                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1010                    }
 1011                })
 1012            });
 1013    }
 1014
 1015    fn visible(&self) -> bool {
 1016        !self.matches.is_empty()
 1017    }
 1018
 1019    fn render(
 1020        &self,
 1021        style: &EditorStyle,
 1022        max_height: Pixels,
 1023        workspace: Option<WeakView<Workspace>>,
 1024        cx: &mut ViewContext<Editor>,
 1025    ) -> AnyElement {
 1026        let settings = EditorSettings::get_global(cx);
 1027        let show_completion_documentation = settings.show_completion_documentation;
 1028
 1029        let widest_completion_ix = self
 1030            .matches
 1031            .iter()
 1032            .enumerate()
 1033            .max_by_key(|(_, mat)| {
 1034                let completions = self.completions.read();
 1035                let completion = &completions[mat.candidate_id];
 1036                let documentation = &completion.documentation;
 1037
 1038                let mut len = completion.label.text.chars().count();
 1039                if let Some(Documentation::SingleLine(text)) = documentation {
 1040                    if show_completion_documentation {
 1041                        len += text.chars().count();
 1042                    }
 1043                }
 1044
 1045                len
 1046            })
 1047            .map(|(ix, _)| ix);
 1048
 1049        let completions = self.completions.clone();
 1050        let matches = self.matches.clone();
 1051        let selected_item = self.selected_item;
 1052        let style = style.clone();
 1053
 1054        let multiline_docs = if show_completion_documentation {
 1055            let mat = &self.matches[selected_item];
 1056            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1057                Some(Documentation::MultiLinePlainText(text)) => {
 1058                    Some(div().child(SharedString::from(text.clone())))
 1059                }
 1060                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1061                    Some(div().child(render_parsed_markdown(
 1062                        "completions_markdown",
 1063                        parsed,
 1064                        &style,
 1065                        workspace,
 1066                        cx,
 1067                    )))
 1068                }
 1069                _ => None,
 1070            };
 1071            multiline_docs.map(|div| {
 1072                div.id("multiline_docs")
 1073                    .max_h(max_height)
 1074                    .flex_1()
 1075                    .px_1p5()
 1076                    .py_1()
 1077                    .min_w(px(260.))
 1078                    .max_w(px(640.))
 1079                    .w(px(500.))
 1080                    .overflow_y_scroll()
 1081                    .occlude()
 1082            })
 1083        } else {
 1084            None
 1085        };
 1086
 1087        let list = uniform_list(
 1088            cx.view().clone(),
 1089            "completions",
 1090            matches.len(),
 1091            move |_editor, range, cx| {
 1092                let start_ix = range.start;
 1093                let completions_guard = completions.read();
 1094
 1095                matches[range]
 1096                    .iter()
 1097                    .enumerate()
 1098                    .map(|(ix, mat)| {
 1099                        let item_ix = start_ix + ix;
 1100                        let candidate_id = mat.candidate_id;
 1101                        let completion = &completions_guard[candidate_id];
 1102
 1103                        let documentation = if show_completion_documentation {
 1104                            &completion.documentation
 1105                        } else {
 1106                            &None
 1107                        };
 1108
 1109                        let highlights = gpui::combine_highlights(
 1110                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1111                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1112                                |(range, mut highlight)| {
 1113                                    // Ignore font weight for syntax highlighting, as we'll use it
 1114                                    // for fuzzy matches.
 1115                                    highlight.font_weight = None;
 1116
 1117                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1118                                        highlight.strikethrough = Some(StrikethroughStyle {
 1119                                            thickness: 1.0.into(),
 1120                                            ..Default::default()
 1121                                        });
 1122                                        highlight.color = Some(cx.theme().colors().text_muted);
 1123                                    }
 1124
 1125                                    (range, highlight)
 1126                                },
 1127                            ),
 1128                        );
 1129                        let completion_label = StyledText::new(completion.label.text.clone())
 1130                            .with_highlights(&style.text, highlights);
 1131                        let documentation_label =
 1132                            if let Some(Documentation::SingleLine(text)) = documentation {
 1133                                if text.trim().is_empty() {
 1134                                    None
 1135                                } else {
 1136                                    Some(
 1137                                        Label::new(text.clone())
 1138                                            .ml_4()
 1139                                            .size(LabelSize::Small)
 1140                                            .color(Color::Muted),
 1141                                    )
 1142                                }
 1143                            } else {
 1144                                None
 1145                            };
 1146
 1147                        div().min_w(px(220.)).max_w(px(540.)).child(
 1148                            ListItem::new(mat.candidate_id)
 1149                                .inset(true)
 1150                                .selected(item_ix == selected_item)
 1151                                .on_click(cx.listener(move |editor, _event, cx| {
 1152                                    cx.stop_propagation();
 1153                                    if let Some(task) = editor.confirm_completion(
 1154                                        &ConfirmCompletion {
 1155                                            item_ix: Some(item_ix),
 1156                                        },
 1157                                        cx,
 1158                                    ) {
 1159                                        task.detach_and_log_err(cx)
 1160                                    }
 1161                                }))
 1162                                .child(h_flex().overflow_hidden().child(completion_label))
 1163                                .end_slot::<Label>(documentation_label),
 1164                        )
 1165                    })
 1166                    .collect()
 1167            },
 1168        )
 1169        .occlude()
 1170        .max_h(max_height)
 1171        .track_scroll(self.scroll_handle.clone())
 1172        .with_width_from_item(widest_completion_ix)
 1173        .with_sizing_behavior(ListSizingBehavior::Infer);
 1174
 1175        Popover::new()
 1176            .child(list)
 1177            .when_some(multiline_docs, |popover, multiline_docs| {
 1178                popover.aside(multiline_docs)
 1179            })
 1180            .into_any_element()
 1181    }
 1182
 1183    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1184        let mut matches = if let Some(query) = query {
 1185            fuzzy::match_strings(
 1186                &self.match_candidates,
 1187                query,
 1188                query.chars().any(|c| c.is_uppercase()),
 1189                100,
 1190                &Default::default(),
 1191                executor,
 1192            )
 1193            .await
 1194        } else {
 1195            self.match_candidates
 1196                .iter()
 1197                .enumerate()
 1198                .map(|(candidate_id, candidate)| StringMatch {
 1199                    candidate_id,
 1200                    score: Default::default(),
 1201                    positions: Default::default(),
 1202                    string: candidate.string.clone(),
 1203                })
 1204                .collect()
 1205        };
 1206
 1207        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1208        if let Some(query) = query {
 1209            if let Some(query_start) = query.chars().next() {
 1210                matches.retain(|string_match| {
 1211                    split_words(&string_match.string).any(|word| {
 1212                        // Check that the first codepoint of the word as lowercase matches the first
 1213                        // codepoint of the query as lowercase
 1214                        word.chars()
 1215                            .flat_map(|codepoint| codepoint.to_lowercase())
 1216                            .zip(query_start.to_lowercase())
 1217                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1218                    })
 1219                });
 1220            }
 1221        }
 1222
 1223        let completions = self.completions.read();
 1224        matches.sort_unstable_by_key(|mat| {
 1225            // We do want to strike a balance here between what the language server tells us
 1226            // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1227            // `Creat` and there is a local variable called `CreateComponent`).
 1228            // So what we do is: we bucket all matches into two buckets
 1229            // - Strong matches
 1230            // - Weak matches
 1231            // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1232            // and the Weak matches are the rest.
 1233            //
 1234            // For the strong matches, we sort by the language-servers score first and for the weak
 1235            // matches, we prefer our fuzzy finder first.
 1236            //
 1237            // The thinking behind that: it's useless to take the sort_text the language-server gives
 1238            // us into account when it's obviously a bad match.
 1239
 1240            #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1241            enum MatchScore<'a> {
 1242                Strong {
 1243                    sort_text: Option<&'a str>,
 1244                    score: Reverse<OrderedFloat<f64>>,
 1245                    sort_key: (usize, &'a str),
 1246                },
 1247                Weak {
 1248                    score: Reverse<OrderedFloat<f64>>,
 1249                    sort_text: Option<&'a str>,
 1250                    sort_key: (usize, &'a str),
 1251                },
 1252            }
 1253
 1254            let completion = &completions[mat.candidate_id];
 1255            let sort_key = completion.sort_key();
 1256            let sort_text = completion.lsp_completion.sort_text.as_deref();
 1257            let score = Reverse(OrderedFloat(mat.score));
 1258
 1259            if mat.score >= 0.2 {
 1260                MatchScore::Strong {
 1261                    sort_text,
 1262                    score,
 1263                    sort_key,
 1264                }
 1265            } else {
 1266                MatchScore::Weak {
 1267                    score,
 1268                    sort_text,
 1269                    sort_key,
 1270                }
 1271            }
 1272        });
 1273
 1274        for mat in &mut matches {
 1275            let completion = &completions[mat.candidate_id];
 1276            mat.string.clone_from(&completion.label.text);
 1277            for position in &mut mat.positions {
 1278                *position += completion.label.filter_range.start;
 1279            }
 1280        }
 1281        drop(completions);
 1282
 1283        self.matches = matches.into();
 1284        self.selected_item = 0;
 1285    }
 1286}
 1287
 1288#[derive(Clone)]
 1289struct CodeActionContents {
 1290    tasks: Option<Arc<ResolvedTasks>>,
 1291    actions: Option<Arc<[CodeAction]>>,
 1292}
 1293
 1294impl CodeActionContents {
 1295    fn len(&self) -> usize {
 1296        match (&self.tasks, &self.actions) {
 1297            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1298            (Some(tasks), None) => tasks.templates.len(),
 1299            (None, Some(actions)) => actions.len(),
 1300            (None, None) => 0,
 1301        }
 1302    }
 1303
 1304    fn is_empty(&self) -> bool {
 1305        match (&self.tasks, &self.actions) {
 1306            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1307            (Some(tasks), None) => tasks.templates.is_empty(),
 1308            (None, Some(actions)) => actions.is_empty(),
 1309            (None, None) => true,
 1310        }
 1311    }
 1312
 1313    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1314        self.tasks
 1315            .iter()
 1316            .flat_map(|tasks| {
 1317                tasks
 1318                    .templates
 1319                    .iter()
 1320                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1321            })
 1322            .chain(self.actions.iter().flat_map(|actions| {
 1323                actions
 1324                    .iter()
 1325                    .map(|action| CodeActionsItem::CodeAction(action.clone()))
 1326            }))
 1327    }
 1328    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1329        match (&self.tasks, &self.actions) {
 1330            (Some(tasks), Some(actions)) => {
 1331                if index < tasks.templates.len() {
 1332                    tasks
 1333                        .templates
 1334                        .get(index)
 1335                        .cloned()
 1336                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1337                } else {
 1338                    actions
 1339                        .get(index - tasks.templates.len())
 1340                        .cloned()
 1341                        .map(CodeActionsItem::CodeAction)
 1342                }
 1343            }
 1344            (Some(tasks), None) => tasks
 1345                .templates
 1346                .get(index)
 1347                .cloned()
 1348                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1349            (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
 1350            (None, None) => None,
 1351        }
 1352    }
 1353}
 1354
 1355#[allow(clippy::large_enum_variant)]
 1356#[derive(Clone)]
 1357enum CodeActionsItem {
 1358    Task(TaskSourceKind, ResolvedTask),
 1359    CodeAction(CodeAction),
 1360}
 1361
 1362impl CodeActionsItem {
 1363    fn as_task(&self) -> Option<&ResolvedTask> {
 1364        let Self::Task(_, task) = self else {
 1365            return None;
 1366        };
 1367        Some(task)
 1368    }
 1369    fn as_code_action(&self) -> Option<&CodeAction> {
 1370        let Self::CodeAction(action) = self else {
 1371            return None;
 1372        };
 1373        Some(action)
 1374    }
 1375    fn label(&self) -> String {
 1376        match self {
 1377            Self::CodeAction(action) => action.lsp_action.title.clone(),
 1378            Self::Task(_, task) => task.resolved_label.clone(),
 1379        }
 1380    }
 1381}
 1382
 1383struct CodeActionsMenu {
 1384    actions: CodeActionContents,
 1385    buffer: Model<Buffer>,
 1386    selected_item: usize,
 1387    scroll_handle: UniformListScrollHandle,
 1388    deployed_from_indicator: Option<DisplayRow>,
 1389}
 1390
 1391impl CodeActionsMenu {
 1392    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1393        self.selected_item = 0;
 1394        self.scroll_handle.scroll_to_item(self.selected_item);
 1395        cx.notify()
 1396    }
 1397
 1398    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1399        if self.selected_item > 0 {
 1400            self.selected_item -= 1;
 1401        } else {
 1402            self.selected_item = self.actions.len() - 1;
 1403        }
 1404        self.scroll_handle.scroll_to_item(self.selected_item);
 1405        cx.notify();
 1406    }
 1407
 1408    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1409        if self.selected_item + 1 < self.actions.len() {
 1410            self.selected_item += 1;
 1411        } else {
 1412            self.selected_item = 0;
 1413        }
 1414        self.scroll_handle.scroll_to_item(self.selected_item);
 1415        cx.notify();
 1416    }
 1417
 1418    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1419        self.selected_item = self.actions.len() - 1;
 1420        self.scroll_handle.scroll_to_item(self.selected_item);
 1421        cx.notify()
 1422    }
 1423
 1424    fn visible(&self) -> bool {
 1425        !self.actions.is_empty()
 1426    }
 1427
 1428    fn render(
 1429        &self,
 1430        cursor_position: DisplayPoint,
 1431        _style: &EditorStyle,
 1432        max_height: Pixels,
 1433        cx: &mut ViewContext<Editor>,
 1434    ) -> (ContextMenuOrigin, AnyElement) {
 1435        let actions = self.actions.clone();
 1436        let selected_item = self.selected_item;
 1437        let element = uniform_list(
 1438            cx.view().clone(),
 1439            "code_actions_menu",
 1440            self.actions.len(),
 1441            move |_this, range, cx| {
 1442                actions
 1443                    .iter()
 1444                    .skip(range.start)
 1445                    .take(range.end - range.start)
 1446                    .enumerate()
 1447                    .map(|(ix, action)| {
 1448                        let item_ix = range.start + ix;
 1449                        let selected = selected_item == item_ix;
 1450                        let colors = cx.theme().colors();
 1451                        div()
 1452                            .px_2()
 1453                            .text_color(colors.text)
 1454                            .when(selected, |style| {
 1455                                style
 1456                                    .bg(colors.element_active)
 1457                                    .text_color(colors.text_accent)
 1458                            })
 1459                            .hover(|style| {
 1460                                style
 1461                                    .bg(colors.element_hover)
 1462                                    .text_color(colors.text_accent)
 1463                            })
 1464                            .whitespace_nowrap()
 1465                            .when_some(action.as_code_action(), |this, action| {
 1466                                this.on_mouse_down(
 1467                                    MouseButton::Left,
 1468                                    cx.listener(move |editor, _, cx| {
 1469                                        cx.stop_propagation();
 1470                                        if let Some(task) = editor.confirm_code_action(
 1471                                            &ConfirmCodeAction {
 1472                                                item_ix: Some(item_ix),
 1473                                            },
 1474                                            cx,
 1475                                        ) {
 1476                                            task.detach_and_log_err(cx)
 1477                                        }
 1478                                    }),
 1479                                )
 1480                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1481                                .child(SharedString::from(action.lsp_action.title.clone()))
 1482                            })
 1483                            .when_some(action.as_task(), |this, task| {
 1484                                this.on_mouse_down(
 1485                                    MouseButton::Left,
 1486                                    cx.listener(move |editor, _, cx| {
 1487                                        cx.stop_propagation();
 1488                                        if let Some(task) = editor.confirm_code_action(
 1489                                            &ConfirmCodeAction {
 1490                                                item_ix: Some(item_ix),
 1491                                            },
 1492                                            cx,
 1493                                        ) {
 1494                                            task.detach_and_log_err(cx)
 1495                                        }
 1496                                    }),
 1497                                )
 1498                                .child(SharedString::from(task.resolved_label.clone()))
 1499                            })
 1500                    })
 1501                    .collect()
 1502            },
 1503        )
 1504        .elevation_1(cx)
 1505        .px_2()
 1506        .py_1()
 1507        .max_h(max_height)
 1508        .occlude()
 1509        .track_scroll(self.scroll_handle.clone())
 1510        .with_width_from_item(
 1511            self.actions
 1512                .iter()
 1513                .enumerate()
 1514                .max_by_key(|(_, action)| match action {
 1515                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1516                    CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
 1517                })
 1518                .map(|(ix, _)| ix),
 1519        )
 1520        .with_sizing_behavior(ListSizingBehavior::Infer)
 1521        .into_any_element();
 1522
 1523        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1524            ContextMenuOrigin::GutterIndicator(row)
 1525        } else {
 1526            ContextMenuOrigin::EditorPoint(cursor_position)
 1527        };
 1528
 1529        (cursor_position, element)
 1530    }
 1531}
 1532
 1533#[derive(Debug)]
 1534struct ActiveDiagnosticGroup {
 1535    primary_range: Range<Anchor>,
 1536    primary_message: String,
 1537    group_id: usize,
 1538    blocks: HashMap<BlockId, Diagnostic>,
 1539    is_valid: bool,
 1540}
 1541
 1542#[derive(Serialize, Deserialize, Clone, Debug)]
 1543pub struct ClipboardSelection {
 1544    pub len: usize,
 1545    pub is_entire_line: bool,
 1546    pub first_line_indent: u32,
 1547}
 1548
 1549#[derive(Debug)]
 1550pub(crate) struct NavigationData {
 1551    cursor_anchor: Anchor,
 1552    cursor_position: Point,
 1553    scroll_anchor: ScrollAnchor,
 1554    scroll_top_row: u32,
 1555}
 1556
 1557enum GotoDefinitionKind {
 1558    Symbol,
 1559    Type,
 1560    Implementation,
 1561}
 1562
 1563#[derive(Debug, Clone)]
 1564enum InlayHintRefreshReason {
 1565    Toggle(bool),
 1566    SettingsChange(InlayHintSettings),
 1567    NewLinesShown,
 1568    BufferEdited(HashSet<Arc<Language>>),
 1569    RefreshRequested,
 1570    ExcerptsRemoved(Vec<ExcerptId>),
 1571}
 1572
 1573impl InlayHintRefreshReason {
 1574    fn description(&self) -> &'static str {
 1575        match self {
 1576            Self::Toggle(_) => "toggle",
 1577            Self::SettingsChange(_) => "settings change",
 1578            Self::NewLinesShown => "new lines shown",
 1579            Self::BufferEdited(_) => "buffer edited",
 1580            Self::RefreshRequested => "refresh requested",
 1581            Self::ExcerptsRemoved(_) => "excerpts removed",
 1582        }
 1583    }
 1584}
 1585
 1586impl Editor {
 1587    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1588        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1589        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1590        Self::new(
 1591            EditorMode::SingleLine { auto_width: false },
 1592            buffer,
 1593            None,
 1594            false,
 1595            cx,
 1596        )
 1597    }
 1598
 1599    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1600        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1601        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1602        Self::new(EditorMode::Full, buffer, None, false, cx)
 1603    }
 1604
 1605    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1606        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1607        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1608        Self::new(
 1609            EditorMode::SingleLine { auto_width: true },
 1610            buffer,
 1611            None,
 1612            false,
 1613            cx,
 1614        )
 1615    }
 1616
 1617    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1618        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1619        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1620        Self::new(
 1621            EditorMode::AutoHeight { max_lines },
 1622            buffer,
 1623            None,
 1624            false,
 1625            cx,
 1626        )
 1627    }
 1628
 1629    pub fn for_buffer(
 1630        buffer: Model<Buffer>,
 1631        project: Option<Model<Project>>,
 1632        cx: &mut ViewContext<Self>,
 1633    ) -> Self {
 1634        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1635        Self::new(EditorMode::Full, buffer, project, false, cx)
 1636    }
 1637
 1638    pub fn for_multibuffer(
 1639        buffer: Model<MultiBuffer>,
 1640        project: Option<Model<Project>>,
 1641        show_excerpt_controls: bool,
 1642        cx: &mut ViewContext<Self>,
 1643    ) -> Self {
 1644        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1645    }
 1646
 1647    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1648        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1649        let mut clone = Self::new(
 1650            self.mode,
 1651            self.buffer.clone(),
 1652            self.project.clone(),
 1653            show_excerpt_controls,
 1654            cx,
 1655        );
 1656        self.display_map.update(cx, |display_map, cx| {
 1657            let snapshot = display_map.snapshot(cx);
 1658            clone.display_map.update(cx, |display_map, cx| {
 1659                display_map.set_state(&snapshot, cx);
 1660            });
 1661        });
 1662        clone.selections.clone_state(&self.selections);
 1663        clone.scroll_manager.clone_state(&self.scroll_manager);
 1664        clone.searchable = self.searchable;
 1665        clone
 1666    }
 1667
 1668    pub fn new(
 1669        mode: EditorMode,
 1670        buffer: Model<MultiBuffer>,
 1671        project: Option<Model<Project>>,
 1672        show_excerpt_controls: bool,
 1673        cx: &mut ViewContext<Self>,
 1674    ) -> Self {
 1675        let style = cx.text_style();
 1676        let font_size = style.font_size.to_pixels(cx.rem_size());
 1677        let editor = cx.view().downgrade();
 1678        let fold_placeholder = FoldPlaceholder {
 1679            constrain_width: true,
 1680            render: Arc::new(move |fold_id, fold_range, cx| {
 1681                let editor = editor.clone();
 1682                div()
 1683                    .id(fold_id)
 1684                    .bg(cx.theme().colors().ghost_element_background)
 1685                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1686                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1687                    .rounded_sm()
 1688                    .size_full()
 1689                    .cursor_pointer()
 1690                    .child("")
 1691                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1692                    .on_click(move |_, cx| {
 1693                        editor
 1694                            .update(cx, |editor, cx| {
 1695                                editor.unfold_ranges(
 1696                                    [fold_range.start..fold_range.end],
 1697                                    true,
 1698                                    false,
 1699                                    cx,
 1700                                );
 1701                                cx.stop_propagation();
 1702                            })
 1703                            .ok();
 1704                    })
 1705                    .into_any()
 1706            }),
 1707            merge_adjacent: true,
 1708        };
 1709        let file_header_size = if show_excerpt_controls { 3 } else { 2 };
 1710        let display_map = cx.new_model(|cx| {
 1711            DisplayMap::new(
 1712                buffer.clone(),
 1713                style.font(),
 1714                font_size,
 1715                None,
 1716                show_excerpt_controls,
 1717                file_header_size,
 1718                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1719                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1720                fold_placeholder,
 1721                cx,
 1722            )
 1723        });
 1724
 1725        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1726
 1727        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1728
 1729        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1730            .then(|| language_settings::SoftWrap::PreferLine);
 1731
 1732        let mut project_subscriptions = Vec::new();
 1733        if mode == EditorMode::Full {
 1734            if let Some(project) = project.as_ref() {
 1735                if buffer.read(cx).is_singleton() {
 1736                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1737                        cx.emit(EditorEvent::TitleChanged);
 1738                    }));
 1739                }
 1740                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1741                    if let project::Event::RefreshInlayHints = event {
 1742                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1743                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1744                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1745                            let focus_handle = editor.focus_handle(cx);
 1746                            if focus_handle.is_focused(cx) {
 1747                                let snapshot = buffer.read(cx).snapshot();
 1748                                for (range, snippet) in snippet_edits {
 1749                                    let editor_range =
 1750                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1751                                    editor
 1752                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1753                                        .ok();
 1754                                }
 1755                            }
 1756                        }
 1757                    }
 1758                }));
 1759                let task_inventory = project.read(cx).task_inventory().clone();
 1760                project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1761                    editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1762                }));
 1763            }
 1764        }
 1765
 1766        let inlay_hint_settings = inlay_hint_settings(
 1767            selections.newest_anchor().head(),
 1768            &buffer.read(cx).snapshot(cx),
 1769            cx,
 1770        );
 1771        let focus_handle = cx.focus_handle();
 1772        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1773        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1774            .detach();
 1775        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1776            .detach();
 1777        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1778
 1779        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1780            Some(false)
 1781        } else {
 1782            None
 1783        };
 1784
 1785        let mut this = Self {
 1786            focus_handle,
 1787            show_cursor_when_unfocused: false,
 1788            last_focused_descendant: None,
 1789            buffer: buffer.clone(),
 1790            display_map: display_map.clone(),
 1791            selections,
 1792            scroll_manager: ScrollManager::new(cx),
 1793            columnar_selection_tail: None,
 1794            add_selections_state: None,
 1795            select_next_state: None,
 1796            select_prev_state: None,
 1797            selection_history: Default::default(),
 1798            autoclose_regions: Default::default(),
 1799            snippet_stack: Default::default(),
 1800            select_larger_syntax_node_stack: Vec::new(),
 1801            ime_transaction: Default::default(),
 1802            active_diagnostics: None,
 1803            soft_wrap_mode_override,
 1804            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1805            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1806            project,
 1807            blink_manager: blink_manager.clone(),
 1808            show_local_selections: true,
 1809            mode,
 1810            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1811            show_gutter: mode == EditorMode::Full,
 1812            show_line_numbers: None,
 1813            show_git_diff_gutter: None,
 1814            show_code_actions: None,
 1815            show_runnables: None,
 1816            show_wrap_guides: None,
 1817            show_indent_guides,
 1818            placeholder_text: None,
 1819            highlight_order: 0,
 1820            highlighted_rows: HashMap::default(),
 1821            background_highlights: Default::default(),
 1822            gutter_highlights: TreeMap::default(),
 1823            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1824            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1825            nav_history: None,
 1826            context_menu: RwLock::new(None),
 1827            mouse_context_menu: None,
 1828            completion_tasks: Default::default(),
 1829            signature_help_state: SignatureHelpState::default(),
 1830            auto_signature_help: None,
 1831            find_all_references_task_sources: Vec::new(),
 1832            next_completion_id: 0,
 1833            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1834            next_inlay_id: 0,
 1835            available_code_actions: Default::default(),
 1836            code_actions_task: Default::default(),
 1837            document_highlights_task: Default::default(),
 1838            linked_editing_range_task: Default::default(),
 1839            pending_rename: Default::default(),
 1840            searchable: true,
 1841            cursor_shape: Default::default(),
 1842            current_line_highlight: None,
 1843            autoindent_mode: Some(AutoindentMode::EachLine),
 1844            collapse_matches: false,
 1845            workspace: None,
 1846            keymap_context_layers: Default::default(),
 1847            input_enabled: true,
 1848            use_modal_editing: mode == EditorMode::Full,
 1849            read_only: false,
 1850            use_autoclose: true,
 1851            use_auto_surround: true,
 1852            auto_replace_emoji_shortcode: false,
 1853            leader_peer_id: None,
 1854            remote_id: None,
 1855            hover_state: Default::default(),
 1856            hovered_link_state: Default::default(),
 1857            inline_completion_provider: None,
 1858            active_inline_completion: None,
 1859            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1860            expanded_hunks: ExpandedHunks::default(),
 1861            gutter_hovered: false,
 1862            pixel_position_of_newest_cursor: None,
 1863            last_bounds: None,
 1864            expect_bounds_change: None,
 1865            gutter_dimensions: GutterDimensions::default(),
 1866            style: None,
 1867            show_cursor_names: false,
 1868            hovered_cursors: Default::default(),
 1869            next_editor_action_id: EditorActionId::default(),
 1870            editor_actions: Rc::default(),
 1871            vim_replace_map: Default::default(),
 1872            show_inline_completions: mode == EditorMode::Full,
 1873            custom_context_menu: None,
 1874            show_git_blame_gutter: false,
 1875            show_git_blame_inline: false,
 1876            show_selection_menu: None,
 1877            show_git_blame_inline_delay_task: None,
 1878            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1879            blame: None,
 1880            blame_subscription: None,
 1881            file_header_size,
 1882            tasks: Default::default(),
 1883            _subscriptions: vec![
 1884                cx.observe(&buffer, Self::on_buffer_changed),
 1885                cx.subscribe(&buffer, Self::on_buffer_event),
 1886                cx.observe(&display_map, Self::on_display_map_changed),
 1887                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1888                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1889                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1890                cx.observe_window_activation(|editor, cx| {
 1891                    let active = cx.is_window_active();
 1892                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1893                        if active {
 1894                            blink_manager.enable(cx);
 1895                        } else {
 1896                            blink_manager.show_cursor(cx);
 1897                            blink_manager.disable(cx);
 1898                        }
 1899                    });
 1900                }),
 1901            ],
 1902            tasks_update_task: None,
 1903            linked_edit_ranges: Default::default(),
 1904            previous_search_ranges: None,
 1905            breadcrumb_header: None,
 1906        };
 1907        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1908        this._subscriptions.extend(project_subscriptions);
 1909
 1910        this.end_selection(cx);
 1911        this.scroll_manager.show_scrollbar(cx);
 1912
 1913        if mode == EditorMode::Full {
 1914            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1915            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1916
 1917            if this.git_blame_inline_enabled {
 1918                this.git_blame_inline_enabled = true;
 1919                this.start_git_blame_inline(false, cx);
 1920            }
 1921        }
 1922
 1923        this.report_editor_event("open", None, cx);
 1924        this
 1925    }
 1926
 1927    pub fn mouse_menu_is_focused(&self, cx: &mut WindowContext) -> bool {
 1928        self.mouse_context_menu
 1929            .as_ref()
 1930            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1931    }
 1932
 1933    fn key_context(&self, cx: &AppContext) -> KeyContext {
 1934        let mut key_context = KeyContext::new_with_defaults();
 1935        key_context.add("Editor");
 1936        let mode = match self.mode {
 1937            EditorMode::SingleLine { .. } => "single_line",
 1938            EditorMode::AutoHeight { .. } => "auto_height",
 1939            EditorMode::Full => "full",
 1940        };
 1941
 1942        if EditorSettings::get_global(cx).jupyter.enabled {
 1943            key_context.add("jupyter");
 1944        }
 1945
 1946        key_context.set("mode", mode);
 1947        if self.pending_rename.is_some() {
 1948            key_context.add("renaming");
 1949        }
 1950        if self.context_menu_visible() {
 1951            match self.context_menu.read().as_ref() {
 1952                Some(ContextMenu::Completions(_)) => {
 1953                    key_context.add("menu");
 1954                    key_context.add("showing_completions")
 1955                }
 1956                Some(ContextMenu::CodeActions(_)) => {
 1957                    key_context.add("menu");
 1958                    key_context.add("showing_code_actions")
 1959                }
 1960                None => {}
 1961            }
 1962        }
 1963
 1964        for layer in self.keymap_context_layers.values() {
 1965            key_context.extend(layer);
 1966        }
 1967
 1968        if let Some(extension) = self
 1969            .buffer
 1970            .read(cx)
 1971            .as_singleton()
 1972            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1973        {
 1974            key_context.set("extension", extension.to_string());
 1975        }
 1976
 1977        if self.has_active_inline_completion(cx) {
 1978            key_context.add("copilot_suggestion");
 1979            key_context.add("inline_completion");
 1980        }
 1981
 1982        key_context
 1983    }
 1984
 1985    pub fn new_file(
 1986        workspace: &mut Workspace,
 1987        _: &workspace::NewFile,
 1988        cx: &mut ViewContext<Workspace>,
 1989    ) {
 1990        let project = workspace.project().clone();
 1991        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1992
 1993        cx.spawn(|workspace, mut cx| async move {
 1994            let buffer = create.await?;
 1995            workspace.update(&mut cx, |workspace, cx| {
 1996                workspace.add_item_to_active_pane(
 1997                    Box::new(
 1998                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1999                    ),
 2000                    None,
 2001                    cx,
 2002                )
 2003            })
 2004        })
 2005        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2006            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2007                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2008                e.error_tag("required").unwrap_or("the latest version")
 2009            )),
 2010            _ => None,
 2011        });
 2012    }
 2013
 2014    pub fn new_file_in_direction(
 2015        workspace: &mut Workspace,
 2016        action: &workspace::NewFileInDirection,
 2017        cx: &mut ViewContext<Workspace>,
 2018    ) {
 2019        let project = workspace.project().clone();
 2020        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2021        let direction = action.0;
 2022
 2023        cx.spawn(|workspace, mut cx| async move {
 2024            let buffer = create.await?;
 2025            workspace.update(&mut cx, move |workspace, cx| {
 2026                workspace.split_item(
 2027                    direction,
 2028                    Box::new(
 2029                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2030                    ),
 2031                    cx,
 2032                )
 2033            })?;
 2034            anyhow::Ok(())
 2035        })
 2036        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2037            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2038                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2039                e.error_tag("required").unwrap_or("the latest version")
 2040            )),
 2041            _ => None,
 2042        });
 2043    }
 2044
 2045    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
 2046        self.buffer.read(cx).replica_id()
 2047    }
 2048
 2049    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2050        self.leader_peer_id
 2051    }
 2052
 2053    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2054        &self.buffer
 2055    }
 2056
 2057    pub fn workspace(&self) -> Option<View<Workspace>> {
 2058        self.workspace.as_ref()?.0.upgrade()
 2059    }
 2060
 2061    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2062        self.buffer().read(cx).title(cx)
 2063    }
 2064
 2065    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2066        EditorSnapshot {
 2067            mode: self.mode,
 2068            show_gutter: self.show_gutter,
 2069            show_line_numbers: self.show_line_numbers,
 2070            show_git_diff_gutter: self.show_git_diff_gutter,
 2071            show_code_actions: self.show_code_actions,
 2072            show_runnables: self.show_runnables,
 2073            render_git_blame_gutter: self.render_git_blame_gutter(cx),
 2074            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2075            scroll_anchor: self.scroll_manager.anchor(),
 2076            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2077            placeholder_text: self.placeholder_text.clone(),
 2078            is_focused: self.focus_handle.is_focused(cx),
 2079            current_line_highlight: self
 2080                .current_line_highlight
 2081                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2082            gutter_hovered: self.gutter_hovered,
 2083        }
 2084    }
 2085
 2086    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2087        self.buffer.read(cx).language_at(point, cx)
 2088    }
 2089
 2090    pub fn file_at<T: ToOffset>(
 2091        &self,
 2092        point: T,
 2093        cx: &AppContext,
 2094    ) -> Option<Arc<dyn language::File>> {
 2095        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2096    }
 2097
 2098    pub fn active_excerpt(
 2099        &self,
 2100        cx: &AppContext,
 2101    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2102        self.buffer
 2103            .read(cx)
 2104            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2105    }
 2106
 2107    pub fn mode(&self) -> EditorMode {
 2108        self.mode
 2109    }
 2110
 2111    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2112        self.collaboration_hub.as_deref()
 2113    }
 2114
 2115    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2116        self.collaboration_hub = Some(hub);
 2117    }
 2118
 2119    pub fn set_custom_context_menu(
 2120        &mut self,
 2121        f: impl 'static
 2122            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2123    ) {
 2124        self.custom_context_menu = Some(Box::new(f))
 2125    }
 2126
 2127    pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
 2128        self.completion_provider = Some(provider);
 2129    }
 2130
 2131    pub fn set_inline_completion_provider<T>(
 2132        &mut self,
 2133        provider: Option<Model<T>>,
 2134        cx: &mut ViewContext<Self>,
 2135    ) where
 2136        T: InlineCompletionProvider,
 2137    {
 2138        self.inline_completion_provider =
 2139            provider.map(|provider| RegisteredInlineCompletionProvider {
 2140                _subscription: cx.observe(&provider, |this, _, cx| {
 2141                    if this.focus_handle.is_focused(cx) {
 2142                        this.update_visible_inline_completion(cx);
 2143                    }
 2144                }),
 2145                provider: Arc::new(provider),
 2146            });
 2147        self.refresh_inline_completion(false, cx);
 2148    }
 2149
 2150    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2151        self.placeholder_text.as_deref()
 2152    }
 2153
 2154    pub fn set_placeholder_text(
 2155        &mut self,
 2156        placeholder_text: impl Into<Arc<str>>,
 2157        cx: &mut ViewContext<Self>,
 2158    ) {
 2159        let placeholder_text = Some(placeholder_text.into());
 2160        if self.placeholder_text != placeholder_text {
 2161            self.placeholder_text = placeholder_text;
 2162            cx.notify();
 2163        }
 2164    }
 2165
 2166    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2167        self.cursor_shape = cursor_shape;
 2168
 2169        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2170        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2171
 2172        cx.notify();
 2173    }
 2174
 2175    pub fn set_current_line_highlight(
 2176        &mut self,
 2177        current_line_highlight: Option<CurrentLineHighlight>,
 2178    ) {
 2179        self.current_line_highlight = current_line_highlight;
 2180    }
 2181
 2182    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2183        self.collapse_matches = collapse_matches;
 2184    }
 2185
 2186    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2187        if self.collapse_matches {
 2188            return range.start..range.start;
 2189        }
 2190        range.clone()
 2191    }
 2192
 2193    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2194        if self.display_map.read(cx).clip_at_line_ends != clip {
 2195            self.display_map
 2196                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2197        }
 2198    }
 2199
 2200    pub fn set_keymap_context_layer<Tag: 'static>(
 2201        &mut self,
 2202        context: KeyContext,
 2203        cx: &mut ViewContext<Self>,
 2204    ) {
 2205        self.keymap_context_layers
 2206            .insert(TypeId::of::<Tag>(), context);
 2207        cx.notify();
 2208    }
 2209
 2210    pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
 2211        self.keymap_context_layers.remove(&TypeId::of::<Tag>());
 2212        cx.notify();
 2213    }
 2214
 2215    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2216        self.input_enabled = input_enabled;
 2217    }
 2218
 2219    pub fn set_autoindent(&mut self, autoindent: bool) {
 2220        if autoindent {
 2221            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2222        } else {
 2223            self.autoindent_mode = None;
 2224        }
 2225    }
 2226
 2227    pub fn read_only(&self, cx: &AppContext) -> bool {
 2228        self.read_only || self.buffer.read(cx).read_only()
 2229    }
 2230
 2231    pub fn set_read_only(&mut self, read_only: bool) {
 2232        self.read_only = read_only;
 2233    }
 2234
 2235    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2236        self.use_autoclose = autoclose;
 2237    }
 2238
 2239    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2240        self.use_auto_surround = auto_surround;
 2241    }
 2242
 2243    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2244        self.auto_replace_emoji_shortcode = auto_replace;
 2245    }
 2246
 2247    pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
 2248        self.show_inline_completions = show_inline_completions;
 2249    }
 2250
 2251    pub fn set_use_modal_editing(&mut self, to: bool) {
 2252        self.use_modal_editing = to;
 2253    }
 2254
 2255    pub fn use_modal_editing(&self) -> bool {
 2256        self.use_modal_editing
 2257    }
 2258
 2259    fn selections_did_change(
 2260        &mut self,
 2261        local: bool,
 2262        old_cursor_position: &Anchor,
 2263        show_completions: bool,
 2264        cx: &mut ViewContext<Self>,
 2265    ) {
 2266        // Copy selections to primary selection buffer
 2267        #[cfg(target_os = "linux")]
 2268        if local {
 2269            let selections = self.selections.all::<usize>(cx);
 2270            let buffer_handle = self.buffer.read(cx).read(cx);
 2271
 2272            let mut text = String::new();
 2273            for (index, selection) in selections.iter().enumerate() {
 2274                let text_for_selection = buffer_handle
 2275                    .text_for_range(selection.start..selection.end)
 2276                    .collect::<String>();
 2277
 2278                text.push_str(&text_for_selection);
 2279                if index != selections.len() - 1 {
 2280                    text.push('\n');
 2281                }
 2282            }
 2283
 2284            if !text.is_empty() {
 2285                cx.write_to_primary(ClipboardItem::new(text));
 2286            }
 2287        }
 2288
 2289        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2290            self.buffer.update(cx, |buffer, cx| {
 2291                buffer.set_active_selections(
 2292                    &self.selections.disjoint_anchors(),
 2293                    self.selections.line_mode,
 2294                    self.cursor_shape,
 2295                    cx,
 2296                )
 2297            });
 2298        }
 2299        let display_map = self
 2300            .display_map
 2301            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2302        let buffer = &display_map.buffer_snapshot;
 2303        self.add_selections_state = None;
 2304        self.select_next_state = None;
 2305        self.select_prev_state = None;
 2306        self.select_larger_syntax_node_stack.clear();
 2307        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2308        self.snippet_stack
 2309            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2310        self.take_rename(false, cx);
 2311
 2312        let new_cursor_position = self.selections.newest_anchor().head();
 2313
 2314        self.push_to_nav_history(
 2315            *old_cursor_position,
 2316            Some(new_cursor_position.to_point(buffer)),
 2317            cx,
 2318        );
 2319
 2320        if local {
 2321            let new_cursor_position = self.selections.newest_anchor().head();
 2322            let mut context_menu = self.context_menu.write();
 2323            let completion_menu = match context_menu.as_ref() {
 2324                Some(ContextMenu::Completions(menu)) => Some(menu),
 2325
 2326                _ => {
 2327                    *context_menu = None;
 2328                    None
 2329                }
 2330            };
 2331
 2332            if let Some(completion_menu) = completion_menu {
 2333                let cursor_position = new_cursor_position.to_offset(buffer);
 2334                let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
 2335                if kind == Some(CharKind::Word)
 2336                    && word_range.to_inclusive().contains(&cursor_position)
 2337                {
 2338                    let mut completion_menu = completion_menu.clone();
 2339                    drop(context_menu);
 2340
 2341                    let query = Self::completion_query(buffer, cursor_position);
 2342                    cx.spawn(move |this, mut cx| async move {
 2343                        completion_menu
 2344                            .filter(query.as_deref(), cx.background_executor().clone())
 2345                            .await;
 2346
 2347                        this.update(&mut cx, |this, cx| {
 2348                            let mut context_menu = this.context_menu.write();
 2349                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2350                                return;
 2351                            };
 2352
 2353                            if menu.id > completion_menu.id {
 2354                                return;
 2355                            }
 2356
 2357                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2358                            drop(context_menu);
 2359                            cx.notify();
 2360                        })
 2361                    })
 2362                    .detach();
 2363
 2364                    if show_completions {
 2365                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2366                    }
 2367                } else {
 2368                    drop(context_menu);
 2369                    self.hide_context_menu(cx);
 2370                }
 2371            } else {
 2372                drop(context_menu);
 2373            }
 2374
 2375            hide_hover(self, cx);
 2376
 2377            if old_cursor_position.to_display_point(&display_map).row()
 2378                != new_cursor_position.to_display_point(&display_map).row()
 2379            {
 2380                self.available_code_actions.take();
 2381            }
 2382            self.refresh_code_actions(cx);
 2383            self.refresh_document_highlights(cx);
 2384            refresh_matching_bracket_highlights(self, cx);
 2385            self.discard_inline_completion(false, cx);
 2386            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2387            if self.git_blame_inline_enabled {
 2388                self.start_inline_blame_timer(cx);
 2389            }
 2390        }
 2391
 2392        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2393        cx.emit(EditorEvent::SelectionsChanged { local });
 2394
 2395        if self.selections.disjoint_anchors().len() == 1 {
 2396            cx.emit(SearchEvent::ActiveMatchChanged)
 2397        }
 2398        cx.notify();
 2399    }
 2400
 2401    pub fn change_selections<R>(
 2402        &mut self,
 2403        autoscroll: Option<Autoscroll>,
 2404        cx: &mut ViewContext<Self>,
 2405        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2406    ) -> R {
 2407        self.change_selections_inner(autoscroll, true, cx, change)
 2408    }
 2409
 2410    pub fn change_selections_inner<R>(
 2411        &mut self,
 2412        autoscroll: Option<Autoscroll>,
 2413        request_completions: bool,
 2414        cx: &mut ViewContext<Self>,
 2415        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2416    ) -> R {
 2417        let old_cursor_position = self.selections.newest_anchor().head();
 2418        self.push_to_selection_history();
 2419
 2420        let (changed, result) = self.selections.change_with(cx, change);
 2421
 2422        if changed {
 2423            if let Some(autoscroll) = autoscroll {
 2424                self.request_autoscroll(autoscroll, cx);
 2425            }
 2426            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2427
 2428            if self.should_open_signature_help_automatically(
 2429                &old_cursor_position,
 2430                self.signature_help_state.backspace_pressed(),
 2431                cx,
 2432            ) {
 2433                self.show_signature_help(&ShowSignatureHelp, cx);
 2434            }
 2435            self.signature_help_state.set_backspace_pressed(false);
 2436        }
 2437
 2438        result
 2439    }
 2440
 2441    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2442    where
 2443        I: IntoIterator<Item = (Range<S>, T)>,
 2444        S: ToOffset,
 2445        T: Into<Arc<str>>,
 2446    {
 2447        if self.read_only(cx) {
 2448            return;
 2449        }
 2450
 2451        self.buffer
 2452            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2453    }
 2454
 2455    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2456    where
 2457        I: IntoIterator<Item = (Range<S>, T)>,
 2458        S: ToOffset,
 2459        T: Into<Arc<str>>,
 2460    {
 2461        if self.read_only(cx) {
 2462            return;
 2463        }
 2464
 2465        self.buffer.update(cx, |buffer, cx| {
 2466            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2467        });
 2468    }
 2469
 2470    pub fn edit_with_block_indent<I, S, T>(
 2471        &mut self,
 2472        edits: I,
 2473        original_indent_columns: Vec<u32>,
 2474        cx: &mut ViewContext<Self>,
 2475    ) where
 2476        I: IntoIterator<Item = (Range<S>, T)>,
 2477        S: ToOffset,
 2478        T: Into<Arc<str>>,
 2479    {
 2480        if self.read_only(cx) {
 2481            return;
 2482        }
 2483
 2484        self.buffer.update(cx, |buffer, cx| {
 2485            buffer.edit(
 2486                edits,
 2487                Some(AutoindentMode::Block {
 2488                    original_indent_columns,
 2489                }),
 2490                cx,
 2491            )
 2492        });
 2493    }
 2494
 2495    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2496        self.hide_context_menu(cx);
 2497
 2498        match phase {
 2499            SelectPhase::Begin {
 2500                position,
 2501                add,
 2502                click_count,
 2503            } => self.begin_selection(position, add, click_count, cx),
 2504            SelectPhase::BeginColumnar {
 2505                position,
 2506                goal_column,
 2507                reset,
 2508            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2509            SelectPhase::Extend {
 2510                position,
 2511                click_count,
 2512            } => self.extend_selection(position, click_count, cx),
 2513            SelectPhase::Update {
 2514                position,
 2515                goal_column,
 2516                scroll_delta,
 2517            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2518            SelectPhase::End => self.end_selection(cx),
 2519        }
 2520    }
 2521
 2522    fn extend_selection(
 2523        &mut self,
 2524        position: DisplayPoint,
 2525        click_count: usize,
 2526        cx: &mut ViewContext<Self>,
 2527    ) {
 2528        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2529        let tail = self.selections.newest::<usize>(cx).tail();
 2530        self.begin_selection(position, false, click_count, cx);
 2531
 2532        let position = position.to_offset(&display_map, Bias::Left);
 2533        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2534
 2535        let mut pending_selection = self
 2536            .selections
 2537            .pending_anchor()
 2538            .expect("extend_selection not called with pending selection");
 2539        if position >= tail {
 2540            pending_selection.start = tail_anchor;
 2541        } else {
 2542            pending_selection.end = tail_anchor;
 2543            pending_selection.reversed = true;
 2544        }
 2545
 2546        let mut pending_mode = self.selections.pending_mode().unwrap();
 2547        match &mut pending_mode {
 2548            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2549            _ => {}
 2550        }
 2551
 2552        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2553            s.set_pending(pending_selection, pending_mode)
 2554        });
 2555    }
 2556
 2557    fn begin_selection(
 2558        &mut self,
 2559        position: DisplayPoint,
 2560        add: bool,
 2561        click_count: usize,
 2562        cx: &mut ViewContext<Self>,
 2563    ) {
 2564        if !self.focus_handle.is_focused(cx) {
 2565            self.last_focused_descendant = None;
 2566            cx.focus(&self.focus_handle);
 2567        }
 2568
 2569        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2570        let buffer = &display_map.buffer_snapshot;
 2571        let newest_selection = self.selections.newest_anchor().clone();
 2572        let position = display_map.clip_point(position, Bias::Left);
 2573
 2574        let start;
 2575        let end;
 2576        let mode;
 2577        let auto_scroll;
 2578        match click_count {
 2579            1 => {
 2580                start = buffer.anchor_before(position.to_point(&display_map));
 2581                end = start;
 2582                mode = SelectMode::Character;
 2583                auto_scroll = true;
 2584            }
 2585            2 => {
 2586                let range = movement::surrounding_word(&display_map, position);
 2587                start = buffer.anchor_before(range.start.to_point(&display_map));
 2588                end = buffer.anchor_before(range.end.to_point(&display_map));
 2589                mode = SelectMode::Word(start..end);
 2590                auto_scroll = true;
 2591            }
 2592            3 => {
 2593                let position = display_map
 2594                    .clip_point(position, Bias::Left)
 2595                    .to_point(&display_map);
 2596                let line_start = display_map.prev_line_boundary(position).0;
 2597                let next_line_start = buffer.clip_point(
 2598                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2599                    Bias::Left,
 2600                );
 2601                start = buffer.anchor_before(line_start);
 2602                end = buffer.anchor_before(next_line_start);
 2603                mode = SelectMode::Line(start..end);
 2604                auto_scroll = true;
 2605            }
 2606            _ => {
 2607                start = buffer.anchor_before(0);
 2608                end = buffer.anchor_before(buffer.len());
 2609                mode = SelectMode::All;
 2610                auto_scroll = false;
 2611            }
 2612        }
 2613
 2614        let point_to_delete: Option<usize> = {
 2615            let selected_points: Vec<Selection<Point>> =
 2616                self.selections.disjoint_in_range(start..end, cx);
 2617
 2618            if !add || click_count > 1 {
 2619                None
 2620            } else if selected_points.len() > 0 {
 2621                Some(selected_points[0].id)
 2622            } else {
 2623                let clicked_point_already_selected =
 2624                    self.selections.disjoint.iter().find(|selection| {
 2625                        selection.start.to_point(buffer) == start.to_point(buffer)
 2626                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2627                    });
 2628
 2629                if let Some(selection) = clicked_point_already_selected {
 2630                    Some(selection.id)
 2631                } else {
 2632                    None
 2633                }
 2634            }
 2635        };
 2636
 2637        let selections_count = self.selections.count();
 2638
 2639        self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
 2640            if let Some(point_to_delete) = point_to_delete {
 2641                s.delete(point_to_delete);
 2642
 2643                if selections_count == 1 {
 2644                    s.set_pending_anchor_range(start..end, mode);
 2645                }
 2646            } else {
 2647                if !add {
 2648                    s.clear_disjoint();
 2649                } else if click_count > 1 {
 2650                    s.delete(newest_selection.id)
 2651                }
 2652
 2653                s.set_pending_anchor_range(start..end, mode);
 2654            }
 2655        });
 2656    }
 2657
 2658    fn begin_columnar_selection(
 2659        &mut self,
 2660        position: DisplayPoint,
 2661        goal_column: u32,
 2662        reset: bool,
 2663        cx: &mut ViewContext<Self>,
 2664    ) {
 2665        if !self.focus_handle.is_focused(cx) {
 2666            self.last_focused_descendant = None;
 2667            cx.focus(&self.focus_handle);
 2668        }
 2669
 2670        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2671
 2672        if reset {
 2673            let pointer_position = display_map
 2674                .buffer_snapshot
 2675                .anchor_before(position.to_point(&display_map));
 2676
 2677            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2678                s.clear_disjoint();
 2679                s.set_pending_anchor_range(
 2680                    pointer_position..pointer_position,
 2681                    SelectMode::Character,
 2682                );
 2683            });
 2684        }
 2685
 2686        let tail = self.selections.newest::<Point>(cx).tail();
 2687        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2688
 2689        if !reset {
 2690            self.select_columns(
 2691                tail.to_display_point(&display_map),
 2692                position,
 2693                goal_column,
 2694                &display_map,
 2695                cx,
 2696            );
 2697        }
 2698    }
 2699
 2700    fn update_selection(
 2701        &mut self,
 2702        position: DisplayPoint,
 2703        goal_column: u32,
 2704        scroll_delta: gpui::Point<f32>,
 2705        cx: &mut ViewContext<Self>,
 2706    ) {
 2707        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2708
 2709        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2710            let tail = tail.to_display_point(&display_map);
 2711            self.select_columns(tail, position, goal_column, &display_map, cx);
 2712        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2713            let buffer = self.buffer.read(cx).snapshot(cx);
 2714            let head;
 2715            let tail;
 2716            let mode = self.selections.pending_mode().unwrap();
 2717            match &mode {
 2718                SelectMode::Character => {
 2719                    head = position.to_point(&display_map);
 2720                    tail = pending.tail().to_point(&buffer);
 2721                }
 2722                SelectMode::Word(original_range) => {
 2723                    let original_display_range = original_range.start.to_display_point(&display_map)
 2724                        ..original_range.end.to_display_point(&display_map);
 2725                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2726                        ..original_display_range.end.to_point(&display_map);
 2727                    if movement::is_inside_word(&display_map, position)
 2728                        || original_display_range.contains(&position)
 2729                    {
 2730                        let word_range = movement::surrounding_word(&display_map, position);
 2731                        if word_range.start < original_display_range.start {
 2732                            head = word_range.start.to_point(&display_map);
 2733                        } else {
 2734                            head = word_range.end.to_point(&display_map);
 2735                        }
 2736                    } else {
 2737                        head = position.to_point(&display_map);
 2738                    }
 2739
 2740                    if head <= original_buffer_range.start {
 2741                        tail = original_buffer_range.end;
 2742                    } else {
 2743                        tail = original_buffer_range.start;
 2744                    }
 2745                }
 2746                SelectMode::Line(original_range) => {
 2747                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2748
 2749                    let position = display_map
 2750                        .clip_point(position, Bias::Left)
 2751                        .to_point(&display_map);
 2752                    let line_start = display_map.prev_line_boundary(position).0;
 2753                    let next_line_start = buffer.clip_point(
 2754                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2755                        Bias::Left,
 2756                    );
 2757
 2758                    if line_start < original_range.start {
 2759                        head = line_start
 2760                    } else {
 2761                        head = next_line_start
 2762                    }
 2763
 2764                    if head <= original_range.start {
 2765                        tail = original_range.end;
 2766                    } else {
 2767                        tail = original_range.start;
 2768                    }
 2769                }
 2770                SelectMode::All => {
 2771                    return;
 2772                }
 2773            };
 2774
 2775            if head < tail {
 2776                pending.start = buffer.anchor_before(head);
 2777                pending.end = buffer.anchor_before(tail);
 2778                pending.reversed = true;
 2779            } else {
 2780                pending.start = buffer.anchor_before(tail);
 2781                pending.end = buffer.anchor_before(head);
 2782                pending.reversed = false;
 2783            }
 2784
 2785            self.change_selections(None, cx, |s| {
 2786                s.set_pending(pending, mode);
 2787            });
 2788        } else {
 2789            log::error!("update_selection dispatched with no pending selection");
 2790            return;
 2791        }
 2792
 2793        self.apply_scroll_delta(scroll_delta, cx);
 2794        cx.notify();
 2795    }
 2796
 2797    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2798        self.columnar_selection_tail.take();
 2799        if self.selections.pending_anchor().is_some() {
 2800            let selections = self.selections.all::<usize>(cx);
 2801            self.change_selections(None, cx, |s| {
 2802                s.select(selections);
 2803                s.clear_pending();
 2804            });
 2805        }
 2806    }
 2807
 2808    fn select_columns(
 2809        &mut self,
 2810        tail: DisplayPoint,
 2811        head: DisplayPoint,
 2812        goal_column: u32,
 2813        display_map: &DisplaySnapshot,
 2814        cx: &mut ViewContext<Self>,
 2815    ) {
 2816        let start_row = cmp::min(tail.row(), head.row());
 2817        let end_row = cmp::max(tail.row(), head.row());
 2818        let start_column = cmp::min(tail.column(), goal_column);
 2819        let end_column = cmp::max(tail.column(), goal_column);
 2820        let reversed = start_column < tail.column();
 2821
 2822        let selection_ranges = (start_row.0..=end_row.0)
 2823            .map(DisplayRow)
 2824            .filter_map(|row| {
 2825                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2826                    let start = display_map
 2827                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2828                        .to_point(display_map);
 2829                    let end = display_map
 2830                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2831                        .to_point(display_map);
 2832                    if reversed {
 2833                        Some(end..start)
 2834                    } else {
 2835                        Some(start..end)
 2836                    }
 2837                } else {
 2838                    None
 2839                }
 2840            })
 2841            .collect::<Vec<_>>();
 2842
 2843        self.change_selections(None, cx, |s| {
 2844            s.select_ranges(selection_ranges);
 2845        });
 2846        cx.notify();
 2847    }
 2848
 2849    pub fn has_pending_nonempty_selection(&self) -> bool {
 2850        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2851            Some(Selection { start, end, .. }) => start != end,
 2852            None => false,
 2853        };
 2854
 2855        pending_nonempty_selection
 2856            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2857    }
 2858
 2859    pub fn has_pending_selection(&self) -> bool {
 2860        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2861    }
 2862
 2863    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2864        self.clear_expanded_diff_hunks(cx);
 2865        if self.dismiss_menus_and_popups(true, cx) {
 2866            return;
 2867        }
 2868
 2869        if self.mode == EditorMode::Full {
 2870            if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
 2871                return;
 2872            }
 2873        }
 2874
 2875        cx.propagate();
 2876    }
 2877
 2878    pub fn dismiss_menus_and_popups(
 2879        &mut self,
 2880        should_report_inline_completion_event: bool,
 2881        cx: &mut ViewContext<Self>,
 2882    ) -> bool {
 2883        if self.take_rename(false, cx).is_some() {
 2884            return true;
 2885        }
 2886
 2887        if hide_hover(self, cx) {
 2888            return true;
 2889        }
 2890
 2891        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2892            return true;
 2893        }
 2894
 2895        if self.hide_context_menu(cx).is_some() {
 2896            return true;
 2897        }
 2898
 2899        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2900            return true;
 2901        }
 2902
 2903        if self.snippet_stack.pop().is_some() {
 2904            return true;
 2905        }
 2906
 2907        if self.mode == EditorMode::Full {
 2908            if self.active_diagnostics.is_some() {
 2909                self.dismiss_diagnostics(cx);
 2910                return true;
 2911            }
 2912        }
 2913
 2914        false
 2915    }
 2916
 2917    fn linked_editing_ranges_for(
 2918        &self,
 2919        selection: Range<text::Anchor>,
 2920        cx: &AppContext,
 2921    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2922        if self.linked_edit_ranges.is_empty() {
 2923            return None;
 2924        }
 2925        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2926            selection.end.buffer_id.and_then(|end_buffer_id| {
 2927                if selection.start.buffer_id != Some(end_buffer_id) {
 2928                    return None;
 2929                }
 2930                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2931                let snapshot = buffer.read(cx).snapshot();
 2932                self.linked_edit_ranges
 2933                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2934                    .map(|ranges| (ranges, snapshot, buffer))
 2935            })?;
 2936        use text::ToOffset as TO;
 2937        // find offset from the start of current range to current cursor position
 2938        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2939
 2940        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2941        let start_difference = start_offset - start_byte_offset;
 2942        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2943        let end_difference = end_offset - start_byte_offset;
 2944        // Current range has associated linked ranges.
 2945        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2946        for range in linked_ranges.iter() {
 2947            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2948            let end_offset = start_offset + end_difference;
 2949            let start_offset = start_offset + start_difference;
 2950            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2951                continue;
 2952            }
 2953            let start = buffer_snapshot.anchor_after(start_offset);
 2954            let end = buffer_snapshot.anchor_after(end_offset);
 2955            linked_edits
 2956                .entry(buffer.clone())
 2957                .or_default()
 2958                .push(start..end);
 2959        }
 2960        Some(linked_edits)
 2961    }
 2962
 2963    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2964        let text: Arc<str> = text.into();
 2965
 2966        if self.read_only(cx) {
 2967            return;
 2968        }
 2969
 2970        let selections = self.selections.all_adjusted(cx);
 2971        let mut bracket_inserted = false;
 2972        let mut edits = Vec::new();
 2973        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2974        let mut new_selections = Vec::with_capacity(selections.len());
 2975        let mut new_autoclose_regions = Vec::new();
 2976        let snapshot = self.buffer.read(cx).read(cx);
 2977
 2978        for (selection, autoclose_region) in
 2979            self.selections_with_autoclose_regions(selections, &snapshot)
 2980        {
 2981            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2982                // Determine if the inserted text matches the opening or closing
 2983                // bracket of any of this language's bracket pairs.
 2984                let mut bracket_pair = None;
 2985                let mut is_bracket_pair_start = false;
 2986                let mut is_bracket_pair_end = false;
 2987                if !text.is_empty() {
 2988                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2989                    //  and they are removing the character that triggered IME popup.
 2990                    for (pair, enabled) in scope.brackets() {
 2991                        if !pair.close && !pair.surround {
 2992                            continue;
 2993                        }
 2994
 2995                        if enabled && pair.start.ends_with(text.as_ref()) {
 2996                            bracket_pair = Some(pair.clone());
 2997                            is_bracket_pair_start = true;
 2998                            break;
 2999                        }
 3000                        if pair.end.as_str() == text.as_ref() {
 3001                            bracket_pair = Some(pair.clone());
 3002                            is_bracket_pair_end = true;
 3003                            break;
 3004                        }
 3005                    }
 3006                }
 3007
 3008                if let Some(bracket_pair) = bracket_pair {
 3009                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3010                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3011                    let auto_surround =
 3012                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3013                    if selection.is_empty() {
 3014                        if is_bracket_pair_start {
 3015                            let prefix_len = bracket_pair.start.len() - text.len();
 3016
 3017                            // If the inserted text is a suffix of an opening bracket and the
 3018                            // selection is preceded by the rest of the opening bracket, then
 3019                            // insert the closing bracket.
 3020                            let following_text_allows_autoclose = snapshot
 3021                                .chars_at(selection.start)
 3022                                .next()
 3023                                .map_or(true, |c| scope.should_autoclose_before(c));
 3024                            let preceding_text_matches_prefix = prefix_len == 0
 3025                                || (selection.start.column >= (prefix_len as u32)
 3026                                    && snapshot.contains_str_at(
 3027                                        Point::new(
 3028                                            selection.start.row,
 3029                                            selection.start.column - (prefix_len as u32),
 3030                                        ),
 3031                                        &bracket_pair.start[..prefix_len],
 3032                                    ));
 3033
 3034                            if autoclose
 3035                                && bracket_pair.close
 3036                                && following_text_allows_autoclose
 3037                                && preceding_text_matches_prefix
 3038                            {
 3039                                let anchor = snapshot.anchor_before(selection.end);
 3040                                new_selections.push((selection.map(|_| anchor), text.len()));
 3041                                new_autoclose_regions.push((
 3042                                    anchor,
 3043                                    text.len(),
 3044                                    selection.id,
 3045                                    bracket_pair.clone(),
 3046                                ));
 3047                                edits.push((
 3048                                    selection.range(),
 3049                                    format!("{}{}", text, bracket_pair.end).into(),
 3050                                ));
 3051                                bracket_inserted = true;
 3052                                continue;
 3053                            }
 3054                        }
 3055
 3056                        if let Some(region) = autoclose_region {
 3057                            // If the selection is followed by an auto-inserted closing bracket,
 3058                            // then don't insert that closing bracket again; just move the selection
 3059                            // past the closing bracket.
 3060                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3061                                && text.as_ref() == region.pair.end.as_str();
 3062                            if should_skip {
 3063                                let anchor = snapshot.anchor_after(selection.end);
 3064                                new_selections
 3065                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3066                                continue;
 3067                            }
 3068                        }
 3069
 3070                        let always_treat_brackets_as_autoclosed = snapshot
 3071                            .settings_at(selection.start, cx)
 3072                            .always_treat_brackets_as_autoclosed;
 3073                        if always_treat_brackets_as_autoclosed
 3074                            && is_bracket_pair_end
 3075                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3076                        {
 3077                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3078                            // and the inserted text is a closing bracket and the selection is followed
 3079                            // by the closing bracket then move the selection past the closing bracket.
 3080                            let anchor = snapshot.anchor_after(selection.end);
 3081                            new_selections.push((selection.map(|_| anchor), text.len()));
 3082                            continue;
 3083                        }
 3084                    }
 3085                    // If an opening bracket is 1 character long and is typed while
 3086                    // text is selected, then surround that text with the bracket pair.
 3087                    else if auto_surround
 3088                        && bracket_pair.surround
 3089                        && is_bracket_pair_start
 3090                        && bracket_pair.start.chars().count() == 1
 3091                    {
 3092                        edits.push((selection.start..selection.start, text.clone()));
 3093                        edits.push((
 3094                            selection.end..selection.end,
 3095                            bracket_pair.end.as_str().into(),
 3096                        ));
 3097                        bracket_inserted = true;
 3098                        new_selections.push((
 3099                            Selection {
 3100                                id: selection.id,
 3101                                start: snapshot.anchor_after(selection.start),
 3102                                end: snapshot.anchor_before(selection.end),
 3103                                reversed: selection.reversed,
 3104                                goal: selection.goal,
 3105                            },
 3106                            0,
 3107                        ));
 3108                        continue;
 3109                    }
 3110                }
 3111            }
 3112
 3113            if self.auto_replace_emoji_shortcode
 3114                && selection.is_empty()
 3115                && text.as_ref().ends_with(':')
 3116            {
 3117                if let Some(possible_emoji_short_code) =
 3118                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3119                {
 3120                    if !possible_emoji_short_code.is_empty() {
 3121                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3122                            let emoji_shortcode_start = Point::new(
 3123                                selection.start.row,
 3124                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3125                            );
 3126
 3127                            // Remove shortcode from buffer
 3128                            edits.push((
 3129                                emoji_shortcode_start..selection.start,
 3130                                "".to_string().into(),
 3131                            ));
 3132                            new_selections.push((
 3133                                Selection {
 3134                                    id: selection.id,
 3135                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3136                                    end: snapshot.anchor_before(selection.start),
 3137                                    reversed: selection.reversed,
 3138                                    goal: selection.goal,
 3139                                },
 3140                                0,
 3141                            ));
 3142
 3143                            // Insert emoji
 3144                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3145                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3146                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3147
 3148                            continue;
 3149                        }
 3150                    }
 3151                }
 3152            }
 3153
 3154            // If not handling any auto-close operation, then just replace the selected
 3155            // text with the given input and move the selection to the end of the
 3156            // newly inserted text.
 3157            let anchor = snapshot.anchor_after(selection.end);
 3158            if !self.linked_edit_ranges.is_empty() {
 3159                let start_anchor = snapshot.anchor_before(selection.start);
 3160
 3161                let is_word_char = text.chars().next().map_or(true, |char| {
 3162                    let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
 3163                    let kind = char_kind(&scope, char);
 3164
 3165                    kind == CharKind::Word
 3166                });
 3167
 3168                if is_word_char {
 3169                    if let Some(ranges) = self
 3170                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3171                    {
 3172                        for (buffer, edits) in ranges {
 3173                            linked_edits
 3174                                .entry(buffer.clone())
 3175                                .or_default()
 3176                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3177                        }
 3178                    }
 3179                }
 3180            }
 3181
 3182            new_selections.push((selection.map(|_| anchor), 0));
 3183            edits.push((selection.start..selection.end, text.clone()));
 3184        }
 3185
 3186        drop(snapshot);
 3187
 3188        self.transact(cx, |this, cx| {
 3189            this.buffer.update(cx, |buffer, cx| {
 3190                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3191            });
 3192            for (buffer, edits) in linked_edits {
 3193                buffer.update(cx, |buffer, cx| {
 3194                    let snapshot = buffer.snapshot();
 3195                    let edits = edits
 3196                        .into_iter()
 3197                        .map(|(range, text)| {
 3198                            use text::ToPoint as TP;
 3199                            let end_point = TP::to_point(&range.end, &snapshot);
 3200                            let start_point = TP::to_point(&range.start, &snapshot);
 3201                            (start_point..end_point, text)
 3202                        })
 3203                        .sorted_by_key(|(range, _)| range.start)
 3204                        .collect::<Vec<_>>();
 3205                    buffer.edit(edits, None, cx);
 3206                })
 3207            }
 3208            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3209            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3210            let snapshot = this.buffer.read(cx).read(cx);
 3211            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3212                .zip(new_selection_deltas)
 3213                .map(|(selection, delta)| Selection {
 3214                    id: selection.id,
 3215                    start: selection.start + delta,
 3216                    end: selection.end + delta,
 3217                    reversed: selection.reversed,
 3218                    goal: SelectionGoal::None,
 3219                })
 3220                .collect::<Vec<_>>();
 3221
 3222            let mut i = 0;
 3223            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3224                let position = position.to_offset(&snapshot) + delta;
 3225                let start = snapshot.anchor_before(position);
 3226                let end = snapshot.anchor_after(position);
 3227                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3228                    match existing_state.range.start.cmp(&start, &snapshot) {
 3229                        Ordering::Less => i += 1,
 3230                        Ordering::Greater => break,
 3231                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3232                            Ordering::Less => i += 1,
 3233                            Ordering::Equal => break,
 3234                            Ordering::Greater => break,
 3235                        },
 3236                    }
 3237                }
 3238                this.autoclose_regions.insert(
 3239                    i,
 3240                    AutocloseRegion {
 3241                        selection_id,
 3242                        range: start..end,
 3243                        pair,
 3244                    },
 3245                );
 3246            }
 3247
 3248            drop(snapshot);
 3249            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3250            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3251                s.select(new_selections)
 3252            });
 3253
 3254            if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
 3255                if let Some(on_type_format_task) =
 3256                    this.trigger_on_type_formatting(text.to_string(), cx)
 3257                {
 3258                    on_type_format_task.detach_and_log_err(cx);
 3259                }
 3260            }
 3261
 3262            let editor_settings = EditorSettings::get_global(cx);
 3263            if bracket_inserted
 3264                && (editor_settings.auto_signature_help
 3265                    || editor_settings.show_signature_help_after_edits)
 3266            {
 3267                this.show_signature_help(&ShowSignatureHelp, cx);
 3268            }
 3269
 3270            let trigger_in_words = !had_active_inline_completion;
 3271            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3272            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3273            this.refresh_inline_completion(true, cx);
 3274        });
 3275    }
 3276
 3277    fn find_possible_emoji_shortcode_at_position(
 3278        snapshot: &MultiBufferSnapshot,
 3279        position: Point,
 3280    ) -> Option<String> {
 3281        let mut chars = Vec::new();
 3282        let mut found_colon = false;
 3283        for char in snapshot.reversed_chars_at(position).take(100) {
 3284            // Found a possible emoji shortcode in the middle of the buffer
 3285            if found_colon {
 3286                if char.is_whitespace() {
 3287                    chars.reverse();
 3288                    return Some(chars.iter().collect());
 3289                }
 3290                // If the previous character is not a whitespace, we are in the middle of a word
 3291                // and we only want to complete the shortcode if the word is made up of other emojis
 3292                let mut containing_word = String::new();
 3293                for ch in snapshot
 3294                    .reversed_chars_at(position)
 3295                    .skip(chars.len() + 1)
 3296                    .take(100)
 3297                {
 3298                    if ch.is_whitespace() {
 3299                        break;
 3300                    }
 3301                    containing_word.push(ch);
 3302                }
 3303                let containing_word = containing_word.chars().rev().collect::<String>();
 3304                if util::word_consists_of_emojis(containing_word.as_str()) {
 3305                    chars.reverse();
 3306                    return Some(chars.iter().collect());
 3307                }
 3308            }
 3309
 3310            if char.is_whitespace() || !char.is_ascii() {
 3311                return None;
 3312            }
 3313            if char == ':' {
 3314                found_colon = true;
 3315            } else {
 3316                chars.push(char);
 3317            }
 3318        }
 3319        // Found a possible emoji shortcode at the beginning of the buffer
 3320        chars.reverse();
 3321        Some(chars.iter().collect())
 3322    }
 3323
 3324    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3325        self.transact(cx, |this, cx| {
 3326            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3327                let selections = this.selections.all::<usize>(cx);
 3328                let multi_buffer = this.buffer.read(cx);
 3329                let buffer = multi_buffer.snapshot(cx);
 3330                selections
 3331                    .iter()
 3332                    .map(|selection| {
 3333                        let start_point = selection.start.to_point(&buffer);
 3334                        let mut indent =
 3335                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3336                        indent.len = cmp::min(indent.len, start_point.column);
 3337                        let start = selection.start;
 3338                        let end = selection.end;
 3339                        let selection_is_empty = start == end;
 3340                        let language_scope = buffer.language_scope_at(start);
 3341                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3342                            &language_scope
 3343                        {
 3344                            let leading_whitespace_len = buffer
 3345                                .reversed_chars_at(start)
 3346                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3347                                .map(|c| c.len_utf8())
 3348                                .sum::<usize>();
 3349
 3350                            let trailing_whitespace_len = buffer
 3351                                .chars_at(end)
 3352                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3353                                .map(|c| c.len_utf8())
 3354                                .sum::<usize>();
 3355
 3356                            let insert_extra_newline =
 3357                                language.brackets().any(|(pair, enabled)| {
 3358                                    let pair_start = pair.start.trim_end();
 3359                                    let pair_end = pair.end.trim_start();
 3360
 3361                                    enabled
 3362                                        && pair.newline
 3363                                        && buffer.contains_str_at(
 3364                                            end + trailing_whitespace_len,
 3365                                            pair_end,
 3366                                        )
 3367                                        && buffer.contains_str_at(
 3368                                            (start - leading_whitespace_len)
 3369                                                .saturating_sub(pair_start.len()),
 3370                                            pair_start,
 3371                                        )
 3372                                });
 3373
 3374                            // Comment extension on newline is allowed only for cursor selections
 3375                            let comment_delimiter = maybe!({
 3376                                if !selection_is_empty {
 3377                                    return None;
 3378                                }
 3379
 3380                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3381                                    return None;
 3382                                }
 3383
 3384                                let delimiters = language.line_comment_prefixes();
 3385                                let max_len_of_delimiter =
 3386                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3387                                let (snapshot, range) =
 3388                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3389
 3390                                let mut index_of_first_non_whitespace = 0;
 3391                                let comment_candidate = snapshot
 3392                                    .chars_for_range(range)
 3393                                    .skip_while(|c| {
 3394                                        let should_skip = c.is_whitespace();
 3395                                        if should_skip {
 3396                                            index_of_first_non_whitespace += 1;
 3397                                        }
 3398                                        should_skip
 3399                                    })
 3400                                    .take(max_len_of_delimiter)
 3401                                    .collect::<String>();
 3402                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3403                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3404                                })?;
 3405                                let cursor_is_placed_after_comment_marker =
 3406                                    index_of_first_non_whitespace + comment_prefix.len()
 3407                                        <= start_point.column as usize;
 3408                                if cursor_is_placed_after_comment_marker {
 3409                                    Some(comment_prefix.clone())
 3410                                } else {
 3411                                    None
 3412                                }
 3413                            });
 3414                            (comment_delimiter, insert_extra_newline)
 3415                        } else {
 3416                            (None, false)
 3417                        };
 3418
 3419                        let capacity_for_delimiter = comment_delimiter
 3420                            .as_deref()
 3421                            .map(str::len)
 3422                            .unwrap_or_default();
 3423                        let mut new_text =
 3424                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3425                        new_text.push_str("\n");
 3426                        new_text.extend(indent.chars());
 3427                        if let Some(delimiter) = &comment_delimiter {
 3428                            new_text.push_str(&delimiter);
 3429                        }
 3430                        if insert_extra_newline {
 3431                            new_text = new_text.repeat(2);
 3432                        }
 3433
 3434                        let anchor = buffer.anchor_after(end);
 3435                        let new_selection = selection.map(|_| anchor);
 3436                        (
 3437                            (start..end, new_text),
 3438                            (insert_extra_newline, new_selection),
 3439                        )
 3440                    })
 3441                    .unzip()
 3442            };
 3443
 3444            this.edit_with_autoindent(edits, cx);
 3445            let buffer = this.buffer.read(cx).snapshot(cx);
 3446            let new_selections = selection_fixup_info
 3447                .into_iter()
 3448                .map(|(extra_newline_inserted, new_selection)| {
 3449                    let mut cursor = new_selection.end.to_point(&buffer);
 3450                    if extra_newline_inserted {
 3451                        cursor.row -= 1;
 3452                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3453                    }
 3454                    new_selection.map(|_| cursor)
 3455                })
 3456                .collect();
 3457
 3458            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3459            this.refresh_inline_completion(true, cx);
 3460        });
 3461    }
 3462
 3463    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3464        let buffer = self.buffer.read(cx);
 3465        let snapshot = buffer.snapshot(cx);
 3466
 3467        let mut edits = Vec::new();
 3468        let mut rows = Vec::new();
 3469
 3470        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3471            let cursor = selection.head();
 3472            let row = cursor.row;
 3473
 3474            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3475
 3476            let newline = "\n".to_string();
 3477            edits.push((start_of_line..start_of_line, newline));
 3478
 3479            rows.push(row + rows_inserted as u32);
 3480        }
 3481
 3482        self.transact(cx, |editor, cx| {
 3483            editor.edit(edits, cx);
 3484
 3485            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3486                let mut index = 0;
 3487                s.move_cursors_with(|map, _, _| {
 3488                    let row = rows[index];
 3489                    index += 1;
 3490
 3491                    let point = Point::new(row, 0);
 3492                    let boundary = map.next_line_boundary(point).1;
 3493                    let clipped = map.clip_point(boundary, Bias::Left);
 3494
 3495                    (clipped, SelectionGoal::None)
 3496                });
 3497            });
 3498
 3499            let mut indent_edits = Vec::new();
 3500            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3501            for row in rows {
 3502                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3503                for (row, indent) in indents {
 3504                    if indent.len == 0 {
 3505                        continue;
 3506                    }
 3507
 3508                    let text = match indent.kind {
 3509                        IndentKind::Space => " ".repeat(indent.len as usize),
 3510                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3511                    };
 3512                    let point = Point::new(row.0, 0);
 3513                    indent_edits.push((point..point, text));
 3514                }
 3515            }
 3516            editor.edit(indent_edits, cx);
 3517        });
 3518    }
 3519
 3520    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3521        let buffer = self.buffer.read(cx);
 3522        let snapshot = buffer.snapshot(cx);
 3523
 3524        let mut edits = Vec::new();
 3525        let mut rows = Vec::new();
 3526        let mut rows_inserted = 0;
 3527
 3528        for selection in self.selections.all_adjusted(cx) {
 3529            let cursor = selection.head();
 3530            let row = cursor.row;
 3531
 3532            let point = Point::new(row + 1, 0);
 3533            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3534
 3535            let newline = "\n".to_string();
 3536            edits.push((start_of_line..start_of_line, newline));
 3537
 3538            rows_inserted += 1;
 3539            rows.push(row + rows_inserted);
 3540        }
 3541
 3542        self.transact(cx, |editor, cx| {
 3543            editor.edit(edits, cx);
 3544
 3545            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3546                let mut index = 0;
 3547                s.move_cursors_with(|map, _, _| {
 3548                    let row = rows[index];
 3549                    index += 1;
 3550
 3551                    let point = Point::new(row, 0);
 3552                    let boundary = map.next_line_boundary(point).1;
 3553                    let clipped = map.clip_point(boundary, Bias::Left);
 3554
 3555                    (clipped, SelectionGoal::None)
 3556                });
 3557            });
 3558
 3559            let mut indent_edits = Vec::new();
 3560            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3561            for row in rows {
 3562                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3563                for (row, indent) in indents {
 3564                    if indent.len == 0 {
 3565                        continue;
 3566                    }
 3567
 3568                    let text = match indent.kind {
 3569                        IndentKind::Space => " ".repeat(indent.len as usize),
 3570                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3571                    };
 3572                    let point = Point::new(row.0, 0);
 3573                    indent_edits.push((point..point, text));
 3574                }
 3575            }
 3576            editor.edit(indent_edits, cx);
 3577        });
 3578    }
 3579
 3580    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3581        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3582            original_indent_columns: Vec::new(),
 3583        });
 3584        self.insert_with_autoindent_mode(text, autoindent, cx);
 3585    }
 3586
 3587    fn insert_with_autoindent_mode(
 3588        &mut self,
 3589        text: &str,
 3590        autoindent_mode: Option<AutoindentMode>,
 3591        cx: &mut ViewContext<Self>,
 3592    ) {
 3593        if self.read_only(cx) {
 3594            return;
 3595        }
 3596
 3597        let text: Arc<str> = text.into();
 3598        self.transact(cx, |this, cx| {
 3599            let old_selections = this.selections.all_adjusted(cx);
 3600            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3601                let anchors = {
 3602                    let snapshot = buffer.read(cx);
 3603                    old_selections
 3604                        .iter()
 3605                        .map(|s| {
 3606                            let anchor = snapshot.anchor_after(s.head());
 3607                            s.map(|_| anchor)
 3608                        })
 3609                        .collect::<Vec<_>>()
 3610                };
 3611                buffer.edit(
 3612                    old_selections
 3613                        .iter()
 3614                        .map(|s| (s.start..s.end, text.clone())),
 3615                    autoindent_mode,
 3616                    cx,
 3617                );
 3618                anchors
 3619            });
 3620
 3621            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3622                s.select_anchors(selection_anchors);
 3623            })
 3624        });
 3625    }
 3626
 3627    fn trigger_completion_on_input(
 3628        &mut self,
 3629        text: &str,
 3630        trigger_in_words: bool,
 3631        cx: &mut ViewContext<Self>,
 3632    ) {
 3633        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3634            self.show_completions(
 3635                &ShowCompletions {
 3636                    trigger: text.chars().last(),
 3637                },
 3638                cx,
 3639            );
 3640        } else {
 3641            self.hide_context_menu(cx);
 3642        }
 3643    }
 3644
 3645    fn is_completion_trigger(
 3646        &self,
 3647        text: &str,
 3648        trigger_in_words: bool,
 3649        cx: &mut ViewContext<Self>,
 3650    ) -> bool {
 3651        let position = self.selections.newest_anchor().head();
 3652        let multibuffer = self.buffer.read(cx);
 3653        let Some(buffer) = position
 3654            .buffer_id
 3655            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3656        else {
 3657            return false;
 3658        };
 3659
 3660        if let Some(completion_provider) = &self.completion_provider {
 3661            completion_provider.is_completion_trigger(
 3662                &buffer,
 3663                position.text_anchor,
 3664                text,
 3665                trigger_in_words,
 3666                cx,
 3667            )
 3668        } else {
 3669            false
 3670        }
 3671    }
 3672
 3673    /// If any empty selections is touching the start of its innermost containing autoclose
 3674    /// region, expand it to select the brackets.
 3675    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3676        let selections = self.selections.all::<usize>(cx);
 3677        let buffer = self.buffer.read(cx).read(cx);
 3678        let new_selections = self
 3679            .selections_with_autoclose_regions(selections, &buffer)
 3680            .map(|(mut selection, region)| {
 3681                if !selection.is_empty() {
 3682                    return selection;
 3683                }
 3684
 3685                if let Some(region) = region {
 3686                    let mut range = region.range.to_offset(&buffer);
 3687                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3688                        range.start -= region.pair.start.len();
 3689                        if buffer.contains_str_at(range.start, &region.pair.start)
 3690                            && buffer.contains_str_at(range.end, &region.pair.end)
 3691                        {
 3692                            range.end += region.pair.end.len();
 3693                            selection.start = range.start;
 3694                            selection.end = range.end;
 3695
 3696                            return selection;
 3697                        }
 3698                    }
 3699                }
 3700
 3701                let always_treat_brackets_as_autoclosed = buffer
 3702                    .settings_at(selection.start, cx)
 3703                    .always_treat_brackets_as_autoclosed;
 3704
 3705                if !always_treat_brackets_as_autoclosed {
 3706                    return selection;
 3707                }
 3708
 3709                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3710                    for (pair, enabled) in scope.brackets() {
 3711                        if !enabled || !pair.close {
 3712                            continue;
 3713                        }
 3714
 3715                        if buffer.contains_str_at(selection.start, &pair.end) {
 3716                            let pair_start_len = pair.start.len();
 3717                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3718                            {
 3719                                selection.start -= pair_start_len;
 3720                                selection.end += pair.end.len();
 3721
 3722                                return selection;
 3723                            }
 3724                        }
 3725                    }
 3726                }
 3727
 3728                selection
 3729            })
 3730            .collect();
 3731
 3732        drop(buffer);
 3733        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3734    }
 3735
 3736    /// Iterate the given selections, and for each one, find the smallest surrounding
 3737    /// autoclose region. This uses the ordering of the selections and the autoclose
 3738    /// regions to avoid repeated comparisons.
 3739    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3740        &'a self,
 3741        selections: impl IntoIterator<Item = Selection<D>>,
 3742        buffer: &'a MultiBufferSnapshot,
 3743    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3744        let mut i = 0;
 3745        let mut regions = self.autoclose_regions.as_slice();
 3746        selections.into_iter().map(move |selection| {
 3747            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3748
 3749            let mut enclosing = None;
 3750            while let Some(pair_state) = regions.get(i) {
 3751                if pair_state.range.end.to_offset(buffer) < range.start {
 3752                    regions = &regions[i + 1..];
 3753                    i = 0;
 3754                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3755                    break;
 3756                } else {
 3757                    if pair_state.selection_id == selection.id {
 3758                        enclosing = Some(pair_state);
 3759                    }
 3760                    i += 1;
 3761                }
 3762            }
 3763
 3764            (selection.clone(), enclosing)
 3765        })
 3766    }
 3767
 3768    /// Remove any autoclose regions that no longer contain their selection.
 3769    fn invalidate_autoclose_regions(
 3770        &mut self,
 3771        mut selections: &[Selection<Anchor>],
 3772        buffer: &MultiBufferSnapshot,
 3773    ) {
 3774        self.autoclose_regions.retain(|state| {
 3775            let mut i = 0;
 3776            while let Some(selection) = selections.get(i) {
 3777                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3778                    selections = &selections[1..];
 3779                    continue;
 3780                }
 3781                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3782                    break;
 3783                }
 3784                if selection.id == state.selection_id {
 3785                    return true;
 3786                } else {
 3787                    i += 1;
 3788                }
 3789            }
 3790            false
 3791        });
 3792    }
 3793
 3794    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3795        let offset = position.to_offset(buffer);
 3796        let (word_range, kind) = buffer.surrounding_word(offset);
 3797        if offset > word_range.start && kind == Some(CharKind::Word) {
 3798            Some(
 3799                buffer
 3800                    .text_for_range(word_range.start..offset)
 3801                    .collect::<String>(),
 3802            )
 3803        } else {
 3804            None
 3805        }
 3806    }
 3807
 3808    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3809        self.refresh_inlay_hints(
 3810            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3811            cx,
 3812        );
 3813    }
 3814
 3815    pub fn inlay_hints_enabled(&self) -> bool {
 3816        self.inlay_hint_cache.enabled
 3817    }
 3818
 3819    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3820        if self.project.is_none() || self.mode != EditorMode::Full {
 3821            return;
 3822        }
 3823
 3824        let reason_description = reason.description();
 3825        let ignore_debounce = matches!(
 3826            reason,
 3827            InlayHintRefreshReason::SettingsChange(_)
 3828                | InlayHintRefreshReason::Toggle(_)
 3829                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3830        );
 3831        let (invalidate_cache, required_languages) = match reason {
 3832            InlayHintRefreshReason::Toggle(enabled) => {
 3833                self.inlay_hint_cache.enabled = enabled;
 3834                if enabled {
 3835                    (InvalidationStrategy::RefreshRequested, None)
 3836                } else {
 3837                    self.inlay_hint_cache.clear();
 3838                    self.splice_inlays(
 3839                        self.visible_inlay_hints(cx)
 3840                            .iter()
 3841                            .map(|inlay| inlay.id)
 3842                            .collect(),
 3843                        Vec::new(),
 3844                        cx,
 3845                    );
 3846                    return;
 3847                }
 3848            }
 3849            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3850                match self.inlay_hint_cache.update_settings(
 3851                    &self.buffer,
 3852                    new_settings,
 3853                    self.visible_inlay_hints(cx),
 3854                    cx,
 3855                ) {
 3856                    ControlFlow::Break(Some(InlaySplice {
 3857                        to_remove,
 3858                        to_insert,
 3859                    })) => {
 3860                        self.splice_inlays(to_remove, to_insert, cx);
 3861                        return;
 3862                    }
 3863                    ControlFlow::Break(None) => return,
 3864                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3865                }
 3866            }
 3867            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3868                if let Some(InlaySplice {
 3869                    to_remove,
 3870                    to_insert,
 3871                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3872                {
 3873                    self.splice_inlays(to_remove, to_insert, cx);
 3874                }
 3875                return;
 3876            }
 3877            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3878            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3879                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3880            }
 3881            InlayHintRefreshReason::RefreshRequested => {
 3882                (InvalidationStrategy::RefreshRequested, None)
 3883            }
 3884        };
 3885
 3886        if let Some(InlaySplice {
 3887            to_remove,
 3888            to_insert,
 3889        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3890            reason_description,
 3891            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3892            invalidate_cache,
 3893            ignore_debounce,
 3894            cx,
 3895        ) {
 3896            self.splice_inlays(to_remove, to_insert, cx);
 3897        }
 3898    }
 3899
 3900    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3901        self.display_map
 3902            .read(cx)
 3903            .current_inlays()
 3904            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3905            .cloned()
 3906            .collect()
 3907    }
 3908
 3909    pub fn excerpts_for_inlay_hints_query(
 3910        &self,
 3911        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3912        cx: &mut ViewContext<Editor>,
 3913    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3914        let Some(project) = self.project.as_ref() else {
 3915            return HashMap::default();
 3916        };
 3917        let project = project.read(cx);
 3918        let multi_buffer = self.buffer().read(cx);
 3919        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3920        let multi_buffer_visible_start = self
 3921            .scroll_manager
 3922            .anchor()
 3923            .anchor
 3924            .to_point(&multi_buffer_snapshot);
 3925        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3926            multi_buffer_visible_start
 3927                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3928            Bias::Left,
 3929        );
 3930        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3931        multi_buffer
 3932            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3933            .into_iter()
 3934            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3935            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3936                let buffer = buffer_handle.read(cx);
 3937                let buffer_file = project::File::from_dyn(buffer.file())?;
 3938                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3939                let worktree_entry = buffer_worktree
 3940                    .read(cx)
 3941                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3942                if worktree_entry.is_ignored {
 3943                    return None;
 3944                }
 3945
 3946                let language = buffer.language()?;
 3947                if let Some(restrict_to_languages) = restrict_to_languages {
 3948                    if !restrict_to_languages.contains(language) {
 3949                        return None;
 3950                    }
 3951                }
 3952                Some((
 3953                    excerpt_id,
 3954                    (
 3955                        buffer_handle,
 3956                        buffer.version().clone(),
 3957                        excerpt_visible_range,
 3958                    ),
 3959                ))
 3960            })
 3961            .collect()
 3962    }
 3963
 3964    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3965        TextLayoutDetails {
 3966            text_system: cx.text_system().clone(),
 3967            editor_style: self.style.clone().unwrap(),
 3968            rem_size: cx.rem_size(),
 3969            scroll_anchor: self.scroll_manager.anchor(),
 3970            visible_rows: self.visible_line_count(),
 3971            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3972        }
 3973    }
 3974
 3975    fn splice_inlays(
 3976        &self,
 3977        to_remove: Vec<InlayId>,
 3978        to_insert: Vec<Inlay>,
 3979        cx: &mut ViewContext<Self>,
 3980    ) {
 3981        self.display_map.update(cx, |display_map, cx| {
 3982            display_map.splice_inlays(to_remove, to_insert, cx);
 3983        });
 3984        cx.notify();
 3985    }
 3986
 3987    fn trigger_on_type_formatting(
 3988        &self,
 3989        input: String,
 3990        cx: &mut ViewContext<Self>,
 3991    ) -> Option<Task<Result<()>>> {
 3992        if input.len() != 1 {
 3993            return None;
 3994        }
 3995
 3996        let project = self.project.as_ref()?;
 3997        let position = self.selections.newest_anchor().head();
 3998        let (buffer, buffer_position) = self
 3999            .buffer
 4000            .read(cx)
 4001            .text_anchor_for_position(position, cx)?;
 4002
 4003        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4004        // hence we do LSP request & edit on host side only — add formats to host's history.
 4005        let push_to_lsp_host_history = true;
 4006        // If this is not the host, append its history with new edits.
 4007        let push_to_client_history = project.read(cx).is_remote();
 4008
 4009        let on_type_formatting = project.update(cx, |project, cx| {
 4010            project.on_type_format(
 4011                buffer.clone(),
 4012                buffer_position,
 4013                input,
 4014                push_to_lsp_host_history,
 4015                cx,
 4016            )
 4017        });
 4018        Some(cx.spawn(|editor, mut cx| async move {
 4019            if let Some(transaction) = on_type_formatting.await? {
 4020                if push_to_client_history {
 4021                    buffer
 4022                        .update(&mut cx, |buffer, _| {
 4023                            buffer.push_transaction(transaction, Instant::now());
 4024                        })
 4025                        .ok();
 4026                }
 4027                editor.update(&mut cx, |editor, cx| {
 4028                    editor.refresh_document_highlights(cx);
 4029                })?;
 4030            }
 4031            Ok(())
 4032        }))
 4033    }
 4034
 4035    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4036        if self.pending_rename.is_some() {
 4037            return;
 4038        }
 4039
 4040        let Some(provider) = self.completion_provider.as_ref() else {
 4041            return;
 4042        };
 4043
 4044        let position = self.selections.newest_anchor().head();
 4045        let (buffer, buffer_position) =
 4046            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4047                output
 4048            } else {
 4049                return;
 4050            };
 4051
 4052        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4053        let is_followup_invoke = {
 4054            let context_menu_state = self.context_menu.read();
 4055            matches!(
 4056                context_menu_state.deref(),
 4057                Some(ContextMenu::Completions(_))
 4058            )
 4059        };
 4060        let trigger_kind = match (options.trigger, is_followup_invoke) {
 4061            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4062            (Some(_), _) => CompletionTriggerKind::TRIGGER_CHARACTER,
 4063            _ => CompletionTriggerKind::INVOKED,
 4064        };
 4065        let completion_context = CompletionContext {
 4066            trigger_character: options.trigger.and_then(|c| {
 4067                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4068                    Some(String::from(c))
 4069                } else {
 4070                    None
 4071                }
 4072            }),
 4073            trigger_kind,
 4074        };
 4075        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4076
 4077        let id = post_inc(&mut self.next_completion_id);
 4078        let task = cx.spawn(|this, mut cx| {
 4079            async move {
 4080                this.update(&mut cx, |this, _| {
 4081                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4082                })?;
 4083                let completions = completions.await.log_err();
 4084                let menu = if let Some(completions) = completions {
 4085                    let mut menu = CompletionsMenu {
 4086                        id,
 4087                        initial_position: position,
 4088                        match_candidates: completions
 4089                            .iter()
 4090                            .enumerate()
 4091                            .map(|(id, completion)| {
 4092                                StringMatchCandidate::new(
 4093                                    id,
 4094                                    completion.label.text[completion.label.filter_range.clone()]
 4095                                        .into(),
 4096                                )
 4097                            })
 4098                            .collect(),
 4099                        buffer: buffer.clone(),
 4100                        completions: Arc::new(RwLock::new(completions.into())),
 4101                        matches: Vec::new().into(),
 4102                        selected_item: 0,
 4103                        scroll_handle: UniformListScrollHandle::new(),
 4104                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4105                            DebouncedDelay::new(),
 4106                        )),
 4107                    };
 4108                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4109                        .await;
 4110
 4111                    if menu.matches.is_empty() {
 4112                        None
 4113                    } else {
 4114                        this.update(&mut cx, |editor, cx| {
 4115                            let completions = menu.completions.clone();
 4116                            let matches = menu.matches.clone();
 4117
 4118                            let delay_ms = EditorSettings::get_global(cx)
 4119                                .completion_documentation_secondary_query_debounce;
 4120                            let delay = Duration::from_millis(delay_ms);
 4121                            editor
 4122                                .completion_documentation_pre_resolve_debounce
 4123                                .fire_new(delay, cx, |editor, cx| {
 4124                                    CompletionsMenu::pre_resolve_completion_documentation(
 4125                                        buffer,
 4126                                        completions,
 4127                                        matches,
 4128                                        editor,
 4129                                        cx,
 4130                                    )
 4131                                });
 4132                        })
 4133                        .ok();
 4134                        Some(menu)
 4135                    }
 4136                } else {
 4137                    None
 4138                };
 4139
 4140                this.update(&mut cx, |this, cx| {
 4141                    let mut context_menu = this.context_menu.write();
 4142                    match context_menu.as_ref() {
 4143                        None => {}
 4144
 4145                        Some(ContextMenu::Completions(prev_menu)) => {
 4146                            if prev_menu.id > id {
 4147                                return;
 4148                            }
 4149                        }
 4150
 4151                        _ => return,
 4152                    }
 4153
 4154                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4155                        let menu = menu.unwrap();
 4156                        *context_menu = Some(ContextMenu::Completions(menu));
 4157                        drop(context_menu);
 4158                        this.discard_inline_completion(false, cx);
 4159                        cx.notify();
 4160                    } else if this.completion_tasks.len() <= 1 {
 4161                        // If there are no more completion tasks and the last menu was
 4162                        // empty, we should hide it. If it was already hidden, we should
 4163                        // also show the copilot completion when available.
 4164                        drop(context_menu);
 4165                        if this.hide_context_menu(cx).is_none() {
 4166                            this.update_visible_inline_completion(cx);
 4167                        }
 4168                    }
 4169                })?;
 4170
 4171                Ok::<_, anyhow::Error>(())
 4172            }
 4173            .log_err()
 4174        });
 4175
 4176        self.completion_tasks.push((id, task));
 4177    }
 4178
 4179    pub fn confirm_completion(
 4180        &mut self,
 4181        action: &ConfirmCompletion,
 4182        cx: &mut ViewContext<Self>,
 4183    ) -> Option<Task<Result<()>>> {
 4184        use language::ToOffset as _;
 4185
 4186        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4187            menu
 4188        } else {
 4189            return None;
 4190        };
 4191
 4192        let mat = completions_menu
 4193            .matches
 4194            .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
 4195        let buffer_handle = completions_menu.buffer;
 4196        let completions = completions_menu.completions.read();
 4197        let completion = completions.get(mat.candidate_id)?;
 4198        cx.stop_propagation();
 4199
 4200        let snippet;
 4201        let text;
 4202
 4203        if completion.is_snippet() {
 4204            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4205            text = snippet.as_ref().unwrap().text.clone();
 4206        } else {
 4207            snippet = None;
 4208            text = completion.new_text.clone();
 4209        };
 4210        let selections = self.selections.all::<usize>(cx);
 4211        let buffer = buffer_handle.read(cx);
 4212        let old_range = completion.old_range.to_offset(buffer);
 4213        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4214
 4215        let newest_selection = self.selections.newest_anchor();
 4216        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4217            return None;
 4218        }
 4219
 4220        let lookbehind = newest_selection
 4221            .start
 4222            .text_anchor
 4223            .to_offset(buffer)
 4224            .saturating_sub(old_range.start);
 4225        let lookahead = old_range
 4226            .end
 4227            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4228        let mut common_prefix_len = old_text
 4229            .bytes()
 4230            .zip(text.bytes())
 4231            .take_while(|(a, b)| a == b)
 4232            .count();
 4233
 4234        let snapshot = self.buffer.read(cx).snapshot(cx);
 4235        let mut range_to_replace: Option<Range<isize>> = None;
 4236        let mut ranges = Vec::new();
 4237        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4238        for selection in &selections {
 4239            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4240                let start = selection.start.saturating_sub(lookbehind);
 4241                let end = selection.end + lookahead;
 4242                if selection.id == newest_selection.id {
 4243                    range_to_replace = Some(
 4244                        ((start + common_prefix_len) as isize - selection.start as isize)
 4245                            ..(end as isize - selection.start as isize),
 4246                    );
 4247                }
 4248                ranges.push(start + common_prefix_len..end);
 4249            } else {
 4250                common_prefix_len = 0;
 4251                ranges.clear();
 4252                ranges.extend(selections.iter().map(|s| {
 4253                    if s.id == newest_selection.id {
 4254                        range_to_replace = Some(
 4255                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4256                                - selection.start as isize
 4257                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4258                                    - selection.start as isize,
 4259                        );
 4260                        old_range.clone()
 4261                    } else {
 4262                        s.start..s.end
 4263                    }
 4264                }));
 4265                break;
 4266            }
 4267            if !self.linked_edit_ranges.is_empty() {
 4268                let start_anchor = snapshot.anchor_before(selection.head());
 4269                let end_anchor = snapshot.anchor_after(selection.tail());
 4270                if let Some(ranges) = self
 4271                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4272                {
 4273                    for (buffer, edits) in ranges {
 4274                        linked_edits.entry(buffer.clone()).or_default().extend(
 4275                            edits
 4276                                .into_iter()
 4277                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4278                        );
 4279                    }
 4280                }
 4281            }
 4282        }
 4283        let text = &text[common_prefix_len..];
 4284
 4285        cx.emit(EditorEvent::InputHandled {
 4286            utf16_range_to_replace: range_to_replace,
 4287            text: text.into(),
 4288        });
 4289
 4290        self.transact(cx, |this, cx| {
 4291            if let Some(mut snippet) = snippet {
 4292                snippet.text = text.to_string();
 4293                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4294                    tabstop.start -= common_prefix_len as isize;
 4295                    tabstop.end -= common_prefix_len as isize;
 4296                }
 4297
 4298                this.insert_snippet(&ranges, snippet, cx).log_err();
 4299            } else {
 4300                this.buffer.update(cx, |buffer, cx| {
 4301                    buffer.edit(
 4302                        ranges.iter().map(|range| (range.clone(), text)),
 4303                        this.autoindent_mode.clone(),
 4304                        cx,
 4305                    );
 4306                });
 4307            }
 4308            for (buffer, edits) in linked_edits {
 4309                buffer.update(cx, |buffer, cx| {
 4310                    let snapshot = buffer.snapshot();
 4311                    let edits = edits
 4312                        .into_iter()
 4313                        .map(|(range, text)| {
 4314                            use text::ToPoint as TP;
 4315                            let end_point = TP::to_point(&range.end, &snapshot);
 4316                            let start_point = TP::to_point(&range.start, &snapshot);
 4317                            (start_point..end_point, text)
 4318                        })
 4319                        .sorted_by_key(|(range, _)| range.start)
 4320                        .collect::<Vec<_>>();
 4321                    buffer.edit(edits, None, cx);
 4322                })
 4323            }
 4324
 4325            this.refresh_inline_completion(true, cx);
 4326        });
 4327
 4328        if let Some(confirm) = completion.confirm.as_ref() {
 4329            (confirm)(cx);
 4330        }
 4331
 4332        if completion.show_new_completions_on_confirm {
 4333            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4334        }
 4335
 4336        let provider = self.completion_provider.as_ref()?;
 4337        let apply_edits = provider.apply_additional_edits_for_completion(
 4338            buffer_handle,
 4339            completion.clone(),
 4340            true,
 4341            cx,
 4342        );
 4343
 4344        let editor_settings = EditorSettings::get_global(cx);
 4345        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4346            // After the code completion is finished, users often want to know what signatures are needed.
 4347            // so we should automatically call signature_help
 4348            self.show_signature_help(&ShowSignatureHelp, cx);
 4349        }
 4350
 4351        Some(cx.foreground_executor().spawn(async move {
 4352            apply_edits.await?;
 4353            Ok(())
 4354        }))
 4355    }
 4356
 4357    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4358        let mut context_menu = self.context_menu.write();
 4359        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4360            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4361                // Toggle if we're selecting the same one
 4362                *context_menu = None;
 4363                cx.notify();
 4364                return;
 4365            } else {
 4366                // Otherwise, clear it and start a new one
 4367                *context_menu = None;
 4368                cx.notify();
 4369            }
 4370        }
 4371        drop(context_menu);
 4372        let snapshot = self.snapshot(cx);
 4373        let deployed_from_indicator = action.deployed_from_indicator;
 4374        let mut task = self.code_actions_task.take();
 4375        let action = action.clone();
 4376        cx.spawn(|editor, mut cx| async move {
 4377            while let Some(prev_task) = task {
 4378                prev_task.await;
 4379                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4380            }
 4381
 4382            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4383                if editor.focus_handle.is_focused(cx) {
 4384                    let multibuffer_point = action
 4385                        .deployed_from_indicator
 4386                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4387                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4388                    let (buffer, buffer_row) = snapshot
 4389                        .buffer_snapshot
 4390                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4391                        .and_then(|(buffer_snapshot, range)| {
 4392                            editor
 4393                                .buffer
 4394                                .read(cx)
 4395                                .buffer(buffer_snapshot.remote_id())
 4396                                .map(|buffer| (buffer, range.start.row))
 4397                        })?;
 4398                    let (_, code_actions) = editor
 4399                        .available_code_actions
 4400                        .clone()
 4401                        .and_then(|(location, code_actions)| {
 4402                            let snapshot = location.buffer.read(cx).snapshot();
 4403                            let point_range = location.range.to_point(&snapshot);
 4404                            let point_range = point_range.start.row..=point_range.end.row;
 4405                            if point_range.contains(&buffer_row) {
 4406                                Some((location, code_actions))
 4407                            } else {
 4408                                None
 4409                            }
 4410                        })
 4411                        .unzip();
 4412                    let buffer_id = buffer.read(cx).remote_id();
 4413                    let tasks = editor
 4414                        .tasks
 4415                        .get(&(buffer_id, buffer_row))
 4416                        .map(|t| Arc::new(t.to_owned()));
 4417                    if tasks.is_none() && code_actions.is_none() {
 4418                        return None;
 4419                    }
 4420
 4421                    editor.completion_tasks.clear();
 4422                    editor.discard_inline_completion(false, cx);
 4423                    let task_context =
 4424                        tasks
 4425                            .as_ref()
 4426                            .zip(editor.project.clone())
 4427                            .map(|(tasks, project)| {
 4428                                let position = Point::new(buffer_row, tasks.column);
 4429                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4430                                let location = Location {
 4431                                    buffer: buffer.clone(),
 4432                                    range: range_start..range_start,
 4433                                };
 4434                                // Fill in the environmental variables from the tree-sitter captures
 4435                                let mut captured_task_variables = TaskVariables::default();
 4436                                for (capture_name, value) in tasks.extra_variables.clone() {
 4437                                    captured_task_variables.insert(
 4438                                        task::VariableName::Custom(capture_name.into()),
 4439                                        value.clone(),
 4440                                    );
 4441                                }
 4442                                project.update(cx, |project, cx| {
 4443                                    project.task_context_for_location(
 4444                                        captured_task_variables,
 4445                                        location,
 4446                                        cx,
 4447                                    )
 4448                                })
 4449                            });
 4450
 4451                    Some(cx.spawn(|editor, mut cx| async move {
 4452                        let task_context = match task_context {
 4453                            Some(task_context) => task_context.await,
 4454                            None => None,
 4455                        };
 4456                        let resolved_tasks =
 4457                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4458                                Arc::new(ResolvedTasks {
 4459                                    templates: tasks
 4460                                        .templates
 4461                                        .iter()
 4462                                        .filter_map(|(kind, template)| {
 4463                                            template
 4464                                                .resolve_task(&kind.to_id_base(), &task_context)
 4465                                                .map(|task| (kind.clone(), task))
 4466                                        })
 4467                                        .collect(),
 4468                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4469                                        multibuffer_point.row,
 4470                                        tasks.column,
 4471                                    )),
 4472                                })
 4473                            });
 4474                        let spawn_straight_away = resolved_tasks
 4475                            .as_ref()
 4476                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4477                            && code_actions
 4478                                .as_ref()
 4479                                .map_or(true, |actions| actions.is_empty());
 4480                        if let Some(task) = editor
 4481                            .update(&mut cx, |editor, cx| {
 4482                                *editor.context_menu.write() =
 4483                                    Some(ContextMenu::CodeActions(CodeActionsMenu {
 4484                                        buffer,
 4485                                        actions: CodeActionContents {
 4486                                            tasks: resolved_tasks,
 4487                                            actions: code_actions,
 4488                                        },
 4489                                        selected_item: Default::default(),
 4490                                        scroll_handle: UniformListScrollHandle::default(),
 4491                                        deployed_from_indicator,
 4492                                    }));
 4493                                if spawn_straight_away {
 4494                                    if let Some(task) = editor.confirm_code_action(
 4495                                        &ConfirmCodeAction { item_ix: Some(0) },
 4496                                        cx,
 4497                                    ) {
 4498                                        cx.notify();
 4499                                        return task;
 4500                                    }
 4501                                }
 4502                                cx.notify();
 4503                                Task::ready(Ok(()))
 4504                            })
 4505                            .ok()
 4506                        {
 4507                            task.await
 4508                        } else {
 4509                            Ok(())
 4510                        }
 4511                    }))
 4512                } else {
 4513                    Some(Task::ready(Ok(())))
 4514                }
 4515            })?;
 4516            if let Some(task) = spawned_test_task {
 4517                task.await?;
 4518            }
 4519
 4520            Ok::<_, anyhow::Error>(())
 4521        })
 4522        .detach_and_log_err(cx);
 4523    }
 4524
 4525    pub fn confirm_code_action(
 4526        &mut self,
 4527        action: &ConfirmCodeAction,
 4528        cx: &mut ViewContext<Self>,
 4529    ) -> Option<Task<Result<()>>> {
 4530        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4531            menu
 4532        } else {
 4533            return None;
 4534        };
 4535        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4536        let action = actions_menu.actions.get(action_ix)?;
 4537        let title = action.label();
 4538        let buffer = actions_menu.buffer;
 4539        let workspace = self.workspace()?;
 4540
 4541        match action {
 4542            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4543                workspace.update(cx, |workspace, cx| {
 4544                    workspace::tasks::schedule_resolved_task(
 4545                        workspace,
 4546                        task_source_kind,
 4547                        resolved_task,
 4548                        false,
 4549                        cx,
 4550                    );
 4551
 4552                    Some(Task::ready(Ok(())))
 4553                })
 4554            }
 4555            CodeActionsItem::CodeAction(action) => {
 4556                let apply_code_actions = workspace
 4557                    .read(cx)
 4558                    .project()
 4559                    .clone()
 4560                    .update(cx, |project, cx| {
 4561                        project.apply_code_action(buffer, action, true, cx)
 4562                    });
 4563                let workspace = workspace.downgrade();
 4564                Some(cx.spawn(|editor, cx| async move {
 4565                    let project_transaction = apply_code_actions.await?;
 4566                    Self::open_project_transaction(
 4567                        &editor,
 4568                        workspace,
 4569                        project_transaction,
 4570                        title,
 4571                        cx,
 4572                    )
 4573                    .await
 4574                }))
 4575            }
 4576        }
 4577    }
 4578
 4579    pub async fn open_project_transaction(
 4580        this: &WeakView<Editor>,
 4581        workspace: WeakView<Workspace>,
 4582        transaction: ProjectTransaction,
 4583        title: String,
 4584        mut cx: AsyncWindowContext,
 4585    ) -> Result<()> {
 4586        let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
 4587
 4588        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4589        cx.update(|cx| {
 4590            entries.sort_unstable_by_key(|(buffer, _)| {
 4591                buffer.read(cx).file().map(|f| f.path().clone())
 4592            });
 4593        })?;
 4594
 4595        // If the project transaction's edits are all contained within this editor, then
 4596        // avoid opening a new editor to display them.
 4597
 4598        if let Some((buffer, transaction)) = entries.first() {
 4599            if entries.len() == 1 {
 4600                let excerpt = this.update(&mut cx, |editor, cx| {
 4601                    editor
 4602                        .buffer()
 4603                        .read(cx)
 4604                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4605                })?;
 4606                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4607                    if excerpted_buffer == *buffer {
 4608                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4609                            let excerpt_range = excerpt_range.to_offset(buffer);
 4610                            buffer
 4611                                .edited_ranges_for_transaction::<usize>(transaction)
 4612                                .all(|range| {
 4613                                    excerpt_range.start <= range.start
 4614                                        && excerpt_range.end >= range.end
 4615                                })
 4616                        })?;
 4617
 4618                        if all_edits_within_excerpt {
 4619                            return Ok(());
 4620                        }
 4621                    }
 4622                }
 4623            }
 4624        } else {
 4625            return Ok(());
 4626        }
 4627
 4628        let mut ranges_to_highlight = Vec::new();
 4629        let excerpt_buffer = cx.new_model(|cx| {
 4630            let mut multibuffer =
 4631                MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
 4632            for (buffer_handle, transaction) in &entries {
 4633                let buffer = buffer_handle.read(cx);
 4634                ranges_to_highlight.extend(
 4635                    multibuffer.push_excerpts_with_context_lines(
 4636                        buffer_handle.clone(),
 4637                        buffer
 4638                            .edited_ranges_for_transaction::<usize>(transaction)
 4639                            .collect(),
 4640                        DEFAULT_MULTIBUFFER_CONTEXT,
 4641                        cx,
 4642                    ),
 4643                );
 4644            }
 4645            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4646            multibuffer
 4647        })?;
 4648
 4649        workspace.update(&mut cx, |workspace, cx| {
 4650            let project = workspace.project().clone();
 4651            let editor =
 4652                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4653            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, cx);
 4654            editor.update(cx, |editor, cx| {
 4655                editor.highlight_background::<Self>(
 4656                    &ranges_to_highlight,
 4657                    |theme| theme.editor_highlighted_line_background,
 4658                    cx,
 4659                );
 4660            });
 4661        })?;
 4662
 4663        Ok(())
 4664    }
 4665
 4666    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4667        let project = self.project.clone()?;
 4668        let buffer = self.buffer.read(cx);
 4669        let newest_selection = self.selections.newest_anchor().clone();
 4670        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4671        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4672        if start_buffer != end_buffer {
 4673            return None;
 4674        }
 4675
 4676        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4677            cx.background_executor()
 4678                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4679                .await;
 4680
 4681            let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
 4682                project.code_actions(&start_buffer, start..end, cx)
 4683            }) {
 4684                code_actions.await
 4685            } else {
 4686                Vec::new()
 4687            };
 4688
 4689            this.update(&mut cx, |this, cx| {
 4690                this.available_code_actions = if actions.is_empty() {
 4691                    None
 4692                } else {
 4693                    Some((
 4694                        Location {
 4695                            buffer: start_buffer,
 4696                            range: start..end,
 4697                        },
 4698                        actions.into(),
 4699                    ))
 4700                };
 4701                cx.notify();
 4702            })
 4703            .log_err();
 4704        }));
 4705        None
 4706    }
 4707
 4708    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4709        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4710            self.show_git_blame_inline = false;
 4711
 4712            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4713                cx.background_executor().timer(delay).await;
 4714
 4715                this.update(&mut cx, |this, cx| {
 4716                    this.show_git_blame_inline = true;
 4717                    cx.notify();
 4718                })
 4719                .log_err();
 4720            }));
 4721        }
 4722    }
 4723
 4724    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4725        if self.pending_rename.is_some() {
 4726            return None;
 4727        }
 4728
 4729        let project = self.project.clone()?;
 4730        let buffer = self.buffer.read(cx);
 4731        let newest_selection = self.selections.newest_anchor().clone();
 4732        let cursor_position = newest_selection.head();
 4733        let (cursor_buffer, cursor_buffer_position) =
 4734            buffer.text_anchor_for_position(cursor_position, cx)?;
 4735        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4736        if cursor_buffer != tail_buffer {
 4737            return None;
 4738        }
 4739
 4740        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4741            cx.background_executor()
 4742                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 4743                .await;
 4744
 4745            let highlights = if let Some(highlights) = project
 4746                .update(&mut cx, |project, cx| {
 4747                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4748                })
 4749                .log_err()
 4750            {
 4751                highlights.await.log_err()
 4752            } else {
 4753                None
 4754            };
 4755
 4756            if let Some(highlights) = highlights {
 4757                this.update(&mut cx, |this, cx| {
 4758                    if this.pending_rename.is_some() {
 4759                        return;
 4760                    }
 4761
 4762                    let buffer_id = cursor_position.buffer_id;
 4763                    let buffer = this.buffer.read(cx);
 4764                    if !buffer
 4765                        .text_anchor_for_position(cursor_position, cx)
 4766                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4767                    {
 4768                        return;
 4769                    }
 4770
 4771                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4772                    let mut write_ranges = Vec::new();
 4773                    let mut read_ranges = Vec::new();
 4774                    for highlight in highlights {
 4775                        for (excerpt_id, excerpt_range) in
 4776                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4777                        {
 4778                            let start = highlight
 4779                                .range
 4780                                .start
 4781                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4782                            let end = highlight
 4783                                .range
 4784                                .end
 4785                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4786                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4787                                continue;
 4788                            }
 4789
 4790                            let range = Anchor {
 4791                                buffer_id,
 4792                                excerpt_id: excerpt_id,
 4793                                text_anchor: start,
 4794                            }..Anchor {
 4795                                buffer_id,
 4796                                excerpt_id,
 4797                                text_anchor: end,
 4798                            };
 4799                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4800                                write_ranges.push(range);
 4801                            } else {
 4802                                read_ranges.push(range);
 4803                            }
 4804                        }
 4805                    }
 4806
 4807                    this.highlight_background::<DocumentHighlightRead>(
 4808                        &read_ranges,
 4809                        |theme| theme.editor_document_highlight_read_background,
 4810                        cx,
 4811                    );
 4812                    this.highlight_background::<DocumentHighlightWrite>(
 4813                        &write_ranges,
 4814                        |theme| theme.editor_document_highlight_write_background,
 4815                        cx,
 4816                    );
 4817                    cx.notify();
 4818                })
 4819                .log_err();
 4820            }
 4821        }));
 4822        None
 4823    }
 4824
 4825    fn refresh_inline_completion(
 4826        &mut self,
 4827        debounce: bool,
 4828        cx: &mut ViewContext<Self>,
 4829    ) -> Option<()> {
 4830        let provider = self.inline_completion_provider()?;
 4831        let cursor = self.selections.newest_anchor().head();
 4832        let (buffer, cursor_buffer_position) =
 4833            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4834        if !self.show_inline_completions
 4835            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4836        {
 4837            self.discard_inline_completion(false, cx);
 4838            return None;
 4839        }
 4840
 4841        self.update_visible_inline_completion(cx);
 4842        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4843        Some(())
 4844    }
 4845
 4846    fn cycle_inline_completion(
 4847        &mut self,
 4848        direction: Direction,
 4849        cx: &mut ViewContext<Self>,
 4850    ) -> Option<()> {
 4851        let provider = self.inline_completion_provider()?;
 4852        let cursor = self.selections.newest_anchor().head();
 4853        let (buffer, cursor_buffer_position) =
 4854            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4855        if !self.show_inline_completions
 4856            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4857        {
 4858            return None;
 4859        }
 4860
 4861        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4862        self.update_visible_inline_completion(cx);
 4863
 4864        Some(())
 4865    }
 4866
 4867    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4868        if !self.has_active_inline_completion(cx) {
 4869            self.refresh_inline_completion(false, cx);
 4870            return;
 4871        }
 4872
 4873        self.update_visible_inline_completion(cx);
 4874    }
 4875
 4876    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4877        self.show_cursor_names(cx);
 4878    }
 4879
 4880    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4881        self.show_cursor_names = true;
 4882        cx.notify();
 4883        cx.spawn(|this, mut cx| async move {
 4884            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4885            this.update(&mut cx, |this, cx| {
 4886                this.show_cursor_names = false;
 4887                cx.notify()
 4888            })
 4889            .ok()
 4890        })
 4891        .detach();
 4892    }
 4893
 4894    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4895        if self.has_active_inline_completion(cx) {
 4896            self.cycle_inline_completion(Direction::Next, cx);
 4897        } else {
 4898            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4899            if is_copilot_disabled {
 4900                cx.propagate();
 4901            }
 4902        }
 4903    }
 4904
 4905    pub fn previous_inline_completion(
 4906        &mut self,
 4907        _: &PreviousInlineCompletion,
 4908        cx: &mut ViewContext<Self>,
 4909    ) {
 4910        if self.has_active_inline_completion(cx) {
 4911            self.cycle_inline_completion(Direction::Prev, cx);
 4912        } else {
 4913            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4914            if is_copilot_disabled {
 4915                cx.propagate();
 4916            }
 4917        }
 4918    }
 4919
 4920    pub fn accept_inline_completion(
 4921        &mut self,
 4922        _: &AcceptInlineCompletion,
 4923        cx: &mut ViewContext<Self>,
 4924    ) {
 4925        let Some(completion) = self.take_active_inline_completion(cx) else {
 4926            return;
 4927        };
 4928        if let Some(provider) = self.inline_completion_provider() {
 4929            provider.accept(cx);
 4930        }
 4931
 4932        cx.emit(EditorEvent::InputHandled {
 4933            utf16_range_to_replace: None,
 4934            text: completion.text.to_string().into(),
 4935        });
 4936        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 4937        self.refresh_inline_completion(true, cx);
 4938        cx.notify();
 4939    }
 4940
 4941    pub fn accept_partial_inline_completion(
 4942        &mut self,
 4943        _: &AcceptPartialInlineCompletion,
 4944        cx: &mut ViewContext<Self>,
 4945    ) {
 4946        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 4947            if let Some(completion) = self.take_active_inline_completion(cx) {
 4948                let mut partial_completion = completion
 4949                    .text
 4950                    .chars()
 4951                    .by_ref()
 4952                    .take_while(|c| c.is_alphabetic())
 4953                    .collect::<String>();
 4954                if partial_completion.is_empty() {
 4955                    partial_completion = completion
 4956                        .text
 4957                        .chars()
 4958                        .by_ref()
 4959                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4960                        .collect::<String>();
 4961                }
 4962
 4963                cx.emit(EditorEvent::InputHandled {
 4964                    utf16_range_to_replace: None,
 4965                    text: partial_completion.clone().into(),
 4966                });
 4967                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4968                self.refresh_inline_completion(true, cx);
 4969                cx.notify();
 4970            }
 4971        }
 4972    }
 4973
 4974    fn discard_inline_completion(
 4975        &mut self,
 4976        should_report_inline_completion_event: bool,
 4977        cx: &mut ViewContext<Self>,
 4978    ) -> bool {
 4979        if let Some(provider) = self.inline_completion_provider() {
 4980            provider.discard(should_report_inline_completion_event, cx);
 4981        }
 4982
 4983        self.take_active_inline_completion(cx).is_some()
 4984    }
 4985
 4986    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 4987        if let Some(completion) = self.active_inline_completion.as_ref() {
 4988            let buffer = self.buffer.read(cx).read(cx);
 4989            completion.position.is_valid(&buffer)
 4990        } else {
 4991            false
 4992        }
 4993    }
 4994
 4995    fn take_active_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
 4996        let completion = self.active_inline_completion.take()?;
 4997        self.display_map.update(cx, |map, cx| {
 4998            map.splice_inlays(vec![completion.id], Default::default(), cx);
 4999        });
 5000        let buffer = self.buffer.read(cx).read(cx);
 5001
 5002        if completion.position.is_valid(&buffer) {
 5003            Some(completion)
 5004        } else {
 5005            None
 5006        }
 5007    }
 5008
 5009    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5010        let selection = self.selections.newest_anchor();
 5011        let cursor = selection.head();
 5012
 5013        if self.context_menu.read().is_none()
 5014            && self.completion_tasks.is_empty()
 5015            && selection.start == selection.end
 5016        {
 5017            if let Some(provider) = self.inline_completion_provider() {
 5018                if let Some((buffer, cursor_buffer_position)) =
 5019                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5020                {
 5021                    if let Some(text) =
 5022                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5023                    {
 5024                        let text = Rope::from(text);
 5025                        let mut to_remove = Vec::new();
 5026                        if let Some(completion) = self.active_inline_completion.take() {
 5027                            to_remove.push(completion.id);
 5028                        }
 5029
 5030                        let completion_inlay =
 5031                            Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
 5032                        self.active_inline_completion = Some(completion_inlay.clone());
 5033                        self.display_map.update(cx, move |map, cx| {
 5034                            map.splice_inlays(to_remove, vec![completion_inlay], cx)
 5035                        });
 5036                        cx.notify();
 5037                        return;
 5038                    }
 5039                }
 5040            }
 5041        }
 5042
 5043        self.discard_inline_completion(false, cx);
 5044    }
 5045
 5046    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5047        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5048    }
 5049
 5050    fn render_code_actions_indicator(
 5051        &self,
 5052        _style: &EditorStyle,
 5053        row: DisplayRow,
 5054        is_active: bool,
 5055        cx: &mut ViewContext<Self>,
 5056    ) -> Option<IconButton> {
 5057        if self.available_code_actions.is_some() {
 5058            Some(
 5059                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5060                    .shape(ui::IconButtonShape::Square)
 5061                    .icon_size(IconSize::XSmall)
 5062                    .icon_color(Color::Muted)
 5063                    .selected(is_active)
 5064                    .on_click(cx.listener(move |editor, _e, cx| {
 5065                        editor.focus(cx);
 5066                        editor.toggle_code_actions(
 5067                            &ToggleCodeActions {
 5068                                deployed_from_indicator: Some(row),
 5069                            },
 5070                            cx,
 5071                        );
 5072                    })),
 5073            )
 5074        } else {
 5075            None
 5076        }
 5077    }
 5078
 5079    fn clear_tasks(&mut self) {
 5080        self.tasks.clear()
 5081    }
 5082
 5083    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5084        if let Some(_) = self.tasks.insert(key, value) {
 5085            // This case should hopefully be rare, but just in case...
 5086            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5087        }
 5088    }
 5089
 5090    fn render_run_indicator(
 5091        &self,
 5092        _style: &EditorStyle,
 5093        is_active: bool,
 5094        row: DisplayRow,
 5095        cx: &mut ViewContext<Self>,
 5096    ) -> IconButton {
 5097        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5098            .shape(ui::IconButtonShape::Square)
 5099            .icon_size(IconSize::XSmall)
 5100            .icon_color(Color::Muted)
 5101            .selected(is_active)
 5102            .on_click(cx.listener(move |editor, _e, cx| {
 5103                editor.focus(cx);
 5104                editor.toggle_code_actions(
 5105                    &ToggleCodeActions {
 5106                        deployed_from_indicator: Some(row),
 5107                    },
 5108                    cx,
 5109                );
 5110            }))
 5111    }
 5112
 5113    pub fn context_menu_visible(&self) -> bool {
 5114        self.context_menu
 5115            .read()
 5116            .as_ref()
 5117            .map_or(false, |menu| menu.visible())
 5118    }
 5119
 5120    fn render_context_menu(
 5121        &self,
 5122        cursor_position: DisplayPoint,
 5123        style: &EditorStyle,
 5124        max_height: Pixels,
 5125        cx: &mut ViewContext<Editor>,
 5126    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5127        self.context_menu.read().as_ref().map(|menu| {
 5128            menu.render(
 5129                cursor_position,
 5130                style,
 5131                max_height,
 5132                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5133                cx,
 5134            )
 5135        })
 5136    }
 5137
 5138    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5139        cx.notify();
 5140        self.completion_tasks.clear();
 5141        let context_menu = self.context_menu.write().take();
 5142        if context_menu.is_some() {
 5143            self.update_visible_inline_completion(cx);
 5144        }
 5145        context_menu
 5146    }
 5147
 5148    pub fn insert_snippet(
 5149        &mut self,
 5150        insertion_ranges: &[Range<usize>],
 5151        snippet: Snippet,
 5152        cx: &mut ViewContext<Self>,
 5153    ) -> Result<()> {
 5154        struct Tabstop<T> {
 5155            is_end_tabstop: bool,
 5156            ranges: Vec<Range<T>>,
 5157        }
 5158
 5159        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5160            let snippet_text: Arc<str> = snippet.text.clone().into();
 5161            buffer.edit(
 5162                insertion_ranges
 5163                    .iter()
 5164                    .cloned()
 5165                    .map(|range| (range, snippet_text.clone())),
 5166                Some(AutoindentMode::EachLine),
 5167                cx,
 5168            );
 5169
 5170            let snapshot = &*buffer.read(cx);
 5171            let snippet = &snippet;
 5172            snippet
 5173                .tabstops
 5174                .iter()
 5175                .map(|tabstop| {
 5176                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5177                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5178                    });
 5179                    let mut tabstop_ranges = tabstop
 5180                        .iter()
 5181                        .flat_map(|tabstop_range| {
 5182                            let mut delta = 0_isize;
 5183                            insertion_ranges.iter().map(move |insertion_range| {
 5184                                let insertion_start = insertion_range.start as isize + delta;
 5185                                delta +=
 5186                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5187
 5188                                let start = ((insertion_start + tabstop_range.start) as usize)
 5189                                    .min(snapshot.len());
 5190                                let end = ((insertion_start + tabstop_range.end) as usize)
 5191                                    .min(snapshot.len());
 5192                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5193                            })
 5194                        })
 5195                        .collect::<Vec<_>>();
 5196                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5197
 5198                    Tabstop {
 5199                        is_end_tabstop,
 5200                        ranges: tabstop_ranges,
 5201                    }
 5202                })
 5203                .collect::<Vec<_>>()
 5204        });
 5205        if let Some(tabstop) = tabstops.first() {
 5206            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5207                s.select_ranges(tabstop.ranges.iter().cloned());
 5208            });
 5209
 5210            // If we're already at the last tabstop and it's at the end of the snippet,
 5211            // we're done, we don't need to keep the state around.
 5212            if !tabstop.is_end_tabstop {
 5213                let ranges = tabstops
 5214                    .into_iter()
 5215                    .map(|tabstop| tabstop.ranges)
 5216                    .collect::<Vec<_>>();
 5217                self.snippet_stack.push(SnippetState {
 5218                    active_index: 0,
 5219                    ranges,
 5220                });
 5221            }
 5222
 5223            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5224            if self.autoclose_regions.is_empty() {
 5225                let snapshot = self.buffer.read(cx).snapshot(cx);
 5226                for selection in &mut self.selections.all::<Point>(cx) {
 5227                    let selection_head = selection.head();
 5228                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5229                        continue;
 5230                    };
 5231
 5232                    let mut bracket_pair = None;
 5233                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5234                    let prev_chars = snapshot
 5235                        .reversed_chars_at(selection_head)
 5236                        .collect::<String>();
 5237                    for (pair, enabled) in scope.brackets() {
 5238                        if enabled
 5239                            && pair.close
 5240                            && prev_chars.starts_with(pair.start.as_str())
 5241                            && next_chars.starts_with(pair.end.as_str())
 5242                        {
 5243                            bracket_pair = Some(pair.clone());
 5244                            break;
 5245                        }
 5246                    }
 5247                    if let Some(pair) = bracket_pair {
 5248                        let start = snapshot.anchor_after(selection_head);
 5249                        let end = snapshot.anchor_after(selection_head);
 5250                        self.autoclose_regions.push(AutocloseRegion {
 5251                            selection_id: selection.id,
 5252                            range: start..end,
 5253                            pair,
 5254                        });
 5255                    }
 5256                }
 5257            }
 5258        }
 5259        Ok(())
 5260    }
 5261
 5262    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5263        self.move_to_snippet_tabstop(Bias::Right, cx)
 5264    }
 5265
 5266    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5267        self.move_to_snippet_tabstop(Bias::Left, cx)
 5268    }
 5269
 5270    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5271        if let Some(mut snippet) = self.snippet_stack.pop() {
 5272            match bias {
 5273                Bias::Left => {
 5274                    if snippet.active_index > 0 {
 5275                        snippet.active_index -= 1;
 5276                    } else {
 5277                        self.snippet_stack.push(snippet);
 5278                        return false;
 5279                    }
 5280                }
 5281                Bias::Right => {
 5282                    if snippet.active_index + 1 < snippet.ranges.len() {
 5283                        snippet.active_index += 1;
 5284                    } else {
 5285                        self.snippet_stack.push(snippet);
 5286                        return false;
 5287                    }
 5288                }
 5289            }
 5290            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5291                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5292                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5293                });
 5294                // If snippet state is not at the last tabstop, push it back on the stack
 5295                if snippet.active_index + 1 < snippet.ranges.len() {
 5296                    self.snippet_stack.push(snippet);
 5297                }
 5298                return true;
 5299            }
 5300        }
 5301
 5302        false
 5303    }
 5304
 5305    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5306        self.transact(cx, |this, cx| {
 5307            this.select_all(&SelectAll, cx);
 5308            this.insert("", cx);
 5309        });
 5310    }
 5311
 5312    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5313        self.transact(cx, |this, cx| {
 5314            this.select_autoclose_pair(cx);
 5315            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5316            if !this.linked_edit_ranges.is_empty() {
 5317                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5318                let snapshot = this.buffer.read(cx).snapshot(cx);
 5319
 5320                for selection in selections.iter() {
 5321                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5322                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5323                    if selection_start.buffer_id != selection_end.buffer_id {
 5324                        continue;
 5325                    }
 5326                    if let Some(ranges) =
 5327                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5328                    {
 5329                        for (buffer, entries) in ranges {
 5330                            linked_ranges.entry(buffer).or_default().extend(entries);
 5331                        }
 5332                    }
 5333                }
 5334            }
 5335
 5336            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5337            if !this.selections.line_mode {
 5338                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5339                for selection in &mut selections {
 5340                    if selection.is_empty() {
 5341                        let old_head = selection.head();
 5342                        let mut new_head =
 5343                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5344                                .to_point(&display_map);
 5345                        if let Some((buffer, line_buffer_range)) = display_map
 5346                            .buffer_snapshot
 5347                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5348                        {
 5349                            let indent_size =
 5350                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5351                            let indent_len = match indent_size.kind {
 5352                                IndentKind::Space => {
 5353                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5354                                }
 5355                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5356                            };
 5357                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5358                                let indent_len = indent_len.get();
 5359                                new_head = cmp::min(
 5360                                    new_head,
 5361                                    MultiBufferPoint::new(
 5362                                        old_head.row,
 5363                                        ((old_head.column - 1) / indent_len) * indent_len,
 5364                                    ),
 5365                                );
 5366                            }
 5367                        }
 5368
 5369                        selection.set_head(new_head, SelectionGoal::None);
 5370                    }
 5371                }
 5372            }
 5373
 5374            this.signature_help_state.set_backspace_pressed(true);
 5375            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5376            this.insert("", cx);
 5377            let empty_str: Arc<str> = Arc::from("");
 5378            for (buffer, edits) in linked_ranges {
 5379                let snapshot = buffer.read(cx).snapshot();
 5380                use text::ToPoint as TP;
 5381
 5382                let edits = edits
 5383                    .into_iter()
 5384                    .map(|range| {
 5385                        let end_point = TP::to_point(&range.end, &snapshot);
 5386                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5387
 5388                        if end_point == start_point {
 5389                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5390                                .saturating_sub(1);
 5391                            start_point = TP::to_point(&offset, &snapshot);
 5392                        };
 5393
 5394                        (start_point..end_point, empty_str.clone())
 5395                    })
 5396                    .sorted_by_key(|(range, _)| range.start)
 5397                    .collect::<Vec<_>>();
 5398                buffer.update(cx, |this, cx| {
 5399                    this.edit(edits, None, cx);
 5400                })
 5401            }
 5402            this.refresh_inline_completion(true, cx);
 5403            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5404        });
 5405    }
 5406
 5407    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5408        self.transact(cx, |this, cx| {
 5409            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5410                let line_mode = s.line_mode;
 5411                s.move_with(|map, selection| {
 5412                    if selection.is_empty() && !line_mode {
 5413                        let cursor = movement::right(map, selection.head());
 5414                        selection.end = cursor;
 5415                        selection.reversed = true;
 5416                        selection.goal = SelectionGoal::None;
 5417                    }
 5418                })
 5419            });
 5420            this.insert("", cx);
 5421            this.refresh_inline_completion(true, cx);
 5422        });
 5423    }
 5424
 5425    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5426        if self.move_to_prev_snippet_tabstop(cx) {
 5427            return;
 5428        }
 5429
 5430        self.outdent(&Outdent, cx);
 5431    }
 5432
 5433    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5434        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5435            return;
 5436        }
 5437
 5438        let mut selections = self.selections.all_adjusted(cx);
 5439        let buffer = self.buffer.read(cx);
 5440        let snapshot = buffer.snapshot(cx);
 5441        let rows_iter = selections.iter().map(|s| s.head().row);
 5442        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5443
 5444        let mut edits = Vec::new();
 5445        let mut prev_edited_row = 0;
 5446        let mut row_delta = 0;
 5447        for selection in &mut selections {
 5448            if selection.start.row != prev_edited_row {
 5449                row_delta = 0;
 5450            }
 5451            prev_edited_row = selection.end.row;
 5452
 5453            // If the selection is non-empty, then increase the indentation of the selected lines.
 5454            if !selection.is_empty() {
 5455                row_delta =
 5456                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5457                continue;
 5458            }
 5459
 5460            // If the selection is empty and the cursor is in the leading whitespace before the
 5461            // suggested indentation, then auto-indent the line.
 5462            let cursor = selection.head();
 5463            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5464            if let Some(suggested_indent) =
 5465                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5466            {
 5467                if cursor.column < suggested_indent.len
 5468                    && cursor.column <= current_indent.len
 5469                    && current_indent.len <= suggested_indent.len
 5470                {
 5471                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5472                    selection.end = selection.start;
 5473                    if row_delta == 0 {
 5474                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5475                            cursor.row,
 5476                            current_indent,
 5477                            suggested_indent,
 5478                        ));
 5479                        row_delta = suggested_indent.len - current_indent.len;
 5480                    }
 5481                    continue;
 5482                }
 5483            }
 5484
 5485            // Otherwise, insert a hard or soft tab.
 5486            let settings = buffer.settings_at(cursor, cx);
 5487            let tab_size = if settings.hard_tabs {
 5488                IndentSize::tab()
 5489            } else {
 5490                let tab_size = settings.tab_size.get();
 5491                let char_column = snapshot
 5492                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5493                    .flat_map(str::chars)
 5494                    .count()
 5495                    + row_delta as usize;
 5496                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5497                IndentSize::spaces(chars_to_next_tab_stop)
 5498            };
 5499            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5500            selection.end = selection.start;
 5501            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5502            row_delta += tab_size.len;
 5503        }
 5504
 5505        self.transact(cx, |this, cx| {
 5506            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5507            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5508            this.refresh_inline_completion(true, cx);
 5509        });
 5510    }
 5511
 5512    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5513        if self.read_only(cx) {
 5514            return;
 5515        }
 5516        let mut selections = self.selections.all::<Point>(cx);
 5517        let mut prev_edited_row = 0;
 5518        let mut row_delta = 0;
 5519        let mut edits = Vec::new();
 5520        let buffer = self.buffer.read(cx);
 5521        let snapshot = buffer.snapshot(cx);
 5522        for selection in &mut selections {
 5523            if selection.start.row != prev_edited_row {
 5524                row_delta = 0;
 5525            }
 5526            prev_edited_row = selection.end.row;
 5527
 5528            row_delta =
 5529                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5530        }
 5531
 5532        self.transact(cx, |this, cx| {
 5533            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5534            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5535        });
 5536    }
 5537
 5538    fn indent_selection(
 5539        buffer: &MultiBuffer,
 5540        snapshot: &MultiBufferSnapshot,
 5541        selection: &mut Selection<Point>,
 5542        edits: &mut Vec<(Range<Point>, String)>,
 5543        delta_for_start_row: u32,
 5544        cx: &AppContext,
 5545    ) -> u32 {
 5546        let settings = buffer.settings_at(selection.start, cx);
 5547        let tab_size = settings.tab_size.get();
 5548        let indent_kind = if settings.hard_tabs {
 5549            IndentKind::Tab
 5550        } else {
 5551            IndentKind::Space
 5552        };
 5553        let mut start_row = selection.start.row;
 5554        let mut end_row = selection.end.row + 1;
 5555
 5556        // If a selection ends at the beginning of a line, don't indent
 5557        // that last line.
 5558        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5559            end_row -= 1;
 5560        }
 5561
 5562        // Avoid re-indenting a row that has already been indented by a
 5563        // previous selection, but still update this selection's column
 5564        // to reflect that indentation.
 5565        if delta_for_start_row > 0 {
 5566            start_row += 1;
 5567            selection.start.column += delta_for_start_row;
 5568            if selection.end.row == selection.start.row {
 5569                selection.end.column += delta_for_start_row;
 5570            }
 5571        }
 5572
 5573        let mut delta_for_end_row = 0;
 5574        let has_multiple_rows = start_row + 1 != end_row;
 5575        for row in start_row..end_row {
 5576            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5577            let indent_delta = match (current_indent.kind, indent_kind) {
 5578                (IndentKind::Space, IndentKind::Space) => {
 5579                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5580                    IndentSize::spaces(columns_to_next_tab_stop)
 5581                }
 5582                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5583                (_, IndentKind::Tab) => IndentSize::tab(),
 5584            };
 5585
 5586            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5587                0
 5588            } else {
 5589                selection.start.column
 5590            };
 5591            let row_start = Point::new(row, start);
 5592            edits.push((
 5593                row_start..row_start,
 5594                indent_delta.chars().collect::<String>(),
 5595            ));
 5596
 5597            // Update this selection's endpoints to reflect the indentation.
 5598            if row == selection.start.row {
 5599                selection.start.column += indent_delta.len;
 5600            }
 5601            if row == selection.end.row {
 5602                selection.end.column += indent_delta.len;
 5603                delta_for_end_row = indent_delta.len;
 5604            }
 5605        }
 5606
 5607        if selection.start.row == selection.end.row {
 5608            delta_for_start_row + delta_for_end_row
 5609        } else {
 5610            delta_for_end_row
 5611        }
 5612    }
 5613
 5614    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5615        if self.read_only(cx) {
 5616            return;
 5617        }
 5618        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5619        let selections = self.selections.all::<Point>(cx);
 5620        let mut deletion_ranges = Vec::new();
 5621        let mut last_outdent = None;
 5622        {
 5623            let buffer = self.buffer.read(cx);
 5624            let snapshot = buffer.snapshot(cx);
 5625            for selection in &selections {
 5626                let settings = buffer.settings_at(selection.start, cx);
 5627                let tab_size = settings.tab_size.get();
 5628                let mut rows = selection.spanned_rows(false, &display_map);
 5629
 5630                // Avoid re-outdenting a row that has already been outdented by a
 5631                // previous selection.
 5632                if let Some(last_row) = last_outdent {
 5633                    if last_row == rows.start {
 5634                        rows.start = rows.start.next_row();
 5635                    }
 5636                }
 5637                let has_multiple_rows = rows.len() > 1;
 5638                for row in rows.iter_rows() {
 5639                    let indent_size = snapshot.indent_size_for_line(row);
 5640                    if indent_size.len > 0 {
 5641                        let deletion_len = match indent_size.kind {
 5642                            IndentKind::Space => {
 5643                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5644                                if columns_to_prev_tab_stop == 0 {
 5645                                    tab_size
 5646                                } else {
 5647                                    columns_to_prev_tab_stop
 5648                                }
 5649                            }
 5650                            IndentKind::Tab => 1,
 5651                        };
 5652                        let start = if has_multiple_rows
 5653                            || deletion_len > selection.start.column
 5654                            || indent_size.len < selection.start.column
 5655                        {
 5656                            0
 5657                        } else {
 5658                            selection.start.column - deletion_len
 5659                        };
 5660                        deletion_ranges.push(
 5661                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5662                        );
 5663                        last_outdent = Some(row);
 5664                    }
 5665                }
 5666            }
 5667        }
 5668
 5669        self.transact(cx, |this, cx| {
 5670            this.buffer.update(cx, |buffer, cx| {
 5671                let empty_str: Arc<str> = "".into();
 5672                buffer.edit(
 5673                    deletion_ranges
 5674                        .into_iter()
 5675                        .map(|range| (range, empty_str.clone())),
 5676                    None,
 5677                    cx,
 5678                );
 5679            });
 5680            let selections = this.selections.all::<usize>(cx);
 5681            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5682        });
 5683    }
 5684
 5685    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5686        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5687        let selections = self.selections.all::<Point>(cx);
 5688
 5689        let mut new_cursors = Vec::new();
 5690        let mut edit_ranges = Vec::new();
 5691        let mut selections = selections.iter().peekable();
 5692        while let Some(selection) = selections.next() {
 5693            let mut rows = selection.spanned_rows(false, &display_map);
 5694            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5695
 5696            // Accumulate contiguous regions of rows that we want to delete.
 5697            while let Some(next_selection) = selections.peek() {
 5698                let next_rows = next_selection.spanned_rows(false, &display_map);
 5699                if next_rows.start <= rows.end {
 5700                    rows.end = next_rows.end;
 5701                    selections.next().unwrap();
 5702                } else {
 5703                    break;
 5704                }
 5705            }
 5706
 5707            let buffer = &display_map.buffer_snapshot;
 5708            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5709            let edit_end;
 5710            let cursor_buffer_row;
 5711            if buffer.max_point().row >= rows.end.0 {
 5712                // If there's a line after the range, delete the \n from the end of the row range
 5713                // and position the cursor on the next line.
 5714                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5715                cursor_buffer_row = rows.end;
 5716            } else {
 5717                // If there isn't a line after the range, delete the \n from the line before the
 5718                // start of the row range and position the cursor there.
 5719                edit_start = edit_start.saturating_sub(1);
 5720                edit_end = buffer.len();
 5721                cursor_buffer_row = rows.start.previous_row();
 5722            }
 5723
 5724            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5725            *cursor.column_mut() =
 5726                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5727
 5728            new_cursors.push((
 5729                selection.id,
 5730                buffer.anchor_after(cursor.to_point(&display_map)),
 5731            ));
 5732            edit_ranges.push(edit_start..edit_end);
 5733        }
 5734
 5735        self.transact(cx, |this, cx| {
 5736            let buffer = this.buffer.update(cx, |buffer, cx| {
 5737                let empty_str: Arc<str> = "".into();
 5738                buffer.edit(
 5739                    edit_ranges
 5740                        .into_iter()
 5741                        .map(|range| (range, empty_str.clone())),
 5742                    None,
 5743                    cx,
 5744                );
 5745                buffer.snapshot(cx)
 5746            });
 5747            let new_selections = new_cursors
 5748                .into_iter()
 5749                .map(|(id, cursor)| {
 5750                    let cursor = cursor.to_point(&buffer);
 5751                    Selection {
 5752                        id,
 5753                        start: cursor,
 5754                        end: cursor,
 5755                        reversed: false,
 5756                        goal: SelectionGoal::None,
 5757                    }
 5758                })
 5759                .collect();
 5760
 5761            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5762                s.select(new_selections);
 5763            });
 5764        });
 5765    }
 5766
 5767    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5768        if self.read_only(cx) {
 5769            return;
 5770        }
 5771        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5772        for selection in self.selections.all::<Point>(cx) {
 5773            let start = MultiBufferRow(selection.start.row);
 5774            let end = if selection.start.row == selection.end.row {
 5775                MultiBufferRow(selection.start.row + 1)
 5776            } else {
 5777                MultiBufferRow(selection.end.row)
 5778            };
 5779
 5780            if let Some(last_row_range) = row_ranges.last_mut() {
 5781                if start <= last_row_range.end {
 5782                    last_row_range.end = end;
 5783                    continue;
 5784                }
 5785            }
 5786            row_ranges.push(start..end);
 5787        }
 5788
 5789        let snapshot = self.buffer.read(cx).snapshot(cx);
 5790        let mut cursor_positions = Vec::new();
 5791        for row_range in &row_ranges {
 5792            let anchor = snapshot.anchor_before(Point::new(
 5793                row_range.end.previous_row().0,
 5794                snapshot.line_len(row_range.end.previous_row()),
 5795            ));
 5796            cursor_positions.push(anchor..anchor);
 5797        }
 5798
 5799        self.transact(cx, |this, cx| {
 5800            for row_range in row_ranges.into_iter().rev() {
 5801                for row in row_range.iter_rows().rev() {
 5802                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5803                    let next_line_row = row.next_row();
 5804                    let indent = snapshot.indent_size_for_line(next_line_row);
 5805                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5806
 5807                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5808                        " "
 5809                    } else {
 5810                        ""
 5811                    };
 5812
 5813                    this.buffer.update(cx, |buffer, cx| {
 5814                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5815                    });
 5816                }
 5817            }
 5818
 5819            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5820                s.select_anchor_ranges(cursor_positions)
 5821            });
 5822        });
 5823    }
 5824
 5825    pub fn sort_lines_case_sensitive(
 5826        &mut self,
 5827        _: &SortLinesCaseSensitive,
 5828        cx: &mut ViewContext<Self>,
 5829    ) {
 5830        self.manipulate_lines(cx, |lines| lines.sort())
 5831    }
 5832
 5833    pub fn sort_lines_case_insensitive(
 5834        &mut self,
 5835        _: &SortLinesCaseInsensitive,
 5836        cx: &mut ViewContext<Self>,
 5837    ) {
 5838        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5839    }
 5840
 5841    pub fn unique_lines_case_insensitive(
 5842        &mut self,
 5843        _: &UniqueLinesCaseInsensitive,
 5844        cx: &mut ViewContext<Self>,
 5845    ) {
 5846        self.manipulate_lines(cx, |lines| {
 5847            let mut seen = HashSet::default();
 5848            lines.retain(|line| seen.insert(line.to_lowercase()));
 5849        })
 5850    }
 5851
 5852    pub fn unique_lines_case_sensitive(
 5853        &mut self,
 5854        _: &UniqueLinesCaseSensitive,
 5855        cx: &mut ViewContext<Self>,
 5856    ) {
 5857        self.manipulate_lines(cx, |lines| {
 5858            let mut seen = HashSet::default();
 5859            lines.retain(|line| seen.insert(*line));
 5860        })
 5861    }
 5862
 5863    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5864        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 5865        if !revert_changes.is_empty() {
 5866            self.transact(cx, |editor, cx| {
 5867                editor.buffer().update(cx, |multi_buffer, cx| {
 5868                    for (buffer_id, changes) in revert_changes {
 5869                        if let Some(buffer) = multi_buffer.buffer(buffer_id) {
 5870                            buffer.update(cx, |buffer, cx| {
 5871                                buffer.edit(
 5872                                    changes.into_iter().map(|(range, text)| {
 5873                                        (range, text.to_string().map(Arc::<str>::from))
 5874                                    }),
 5875                                    None,
 5876                                    cx,
 5877                                );
 5878                            });
 5879                        }
 5880                    }
 5881                });
 5882                editor.change_selections(None, cx, |selections| selections.refresh());
 5883            });
 5884        }
 5885    }
 5886
 5887    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5888        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5889            let project_path = buffer.read(cx).project_path(cx)?;
 5890            let project = self.project.as_ref()?.read(cx);
 5891            let entry = project.entry_for_path(&project_path, cx)?;
 5892            let abs_path = project.absolute_path(&project_path, cx)?;
 5893            let parent = if entry.is_symlink {
 5894                abs_path.canonicalize().ok()?
 5895            } else {
 5896                abs_path
 5897            }
 5898            .parent()?
 5899            .to_path_buf();
 5900            Some(parent)
 5901        }) {
 5902            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5903        }
 5904    }
 5905
 5906    fn gather_revert_changes(
 5907        &mut self,
 5908        selections: &[Selection<Anchor>],
 5909        cx: &mut ViewContext<'_, Editor>,
 5910    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 5911        let mut revert_changes = HashMap::default();
 5912        self.buffer.update(cx, |multi_buffer, cx| {
 5913            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 5914            for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 5915                Self::prepare_revert_change(&mut revert_changes, &multi_buffer, &hunk, cx);
 5916            }
 5917        });
 5918        revert_changes
 5919    }
 5920
 5921    fn prepare_revert_change(
 5922        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 5923        multi_buffer: &MultiBuffer,
 5924        hunk: &DiffHunk<MultiBufferRow>,
 5925        cx: &mut AppContext,
 5926    ) -> Option<()> {
 5927        let buffer = multi_buffer.buffer(hunk.buffer_id)?;
 5928        let buffer = buffer.read(cx);
 5929        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 5930        let buffer_snapshot = buffer.snapshot();
 5931        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5932        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5933            probe
 5934                .0
 5935                .start
 5936                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5937                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5938        }) {
 5939            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 5940            Some(())
 5941        } else {
 5942            None
 5943        }
 5944    }
 5945
 5946    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5947        self.manipulate_lines(cx, |lines| lines.reverse())
 5948    }
 5949
 5950    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5951        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5952    }
 5953
 5954    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5955    where
 5956        Fn: FnMut(&mut Vec<&str>),
 5957    {
 5958        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5959        let buffer = self.buffer.read(cx).snapshot(cx);
 5960
 5961        let mut edits = Vec::new();
 5962
 5963        let selections = self.selections.all::<Point>(cx);
 5964        let mut selections = selections.iter().peekable();
 5965        let mut contiguous_row_selections = Vec::new();
 5966        let mut new_selections = Vec::new();
 5967        let mut added_lines = 0;
 5968        let mut removed_lines = 0;
 5969
 5970        while let Some(selection) = selections.next() {
 5971            let (start_row, end_row) = consume_contiguous_rows(
 5972                &mut contiguous_row_selections,
 5973                selection,
 5974                &display_map,
 5975                &mut selections,
 5976            );
 5977
 5978            let start_point = Point::new(start_row.0, 0);
 5979            let end_point = Point::new(
 5980                end_row.previous_row().0,
 5981                buffer.line_len(end_row.previous_row()),
 5982            );
 5983            let text = buffer
 5984                .text_for_range(start_point..end_point)
 5985                .collect::<String>();
 5986
 5987            let mut lines = text.split('\n').collect_vec();
 5988
 5989            let lines_before = lines.len();
 5990            callback(&mut lines);
 5991            let lines_after = lines.len();
 5992
 5993            edits.push((start_point..end_point, lines.join("\n")));
 5994
 5995            // Selections must change based on added and removed line count
 5996            let start_row =
 5997                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 5998            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 5999            new_selections.push(Selection {
 6000                id: selection.id,
 6001                start: start_row,
 6002                end: end_row,
 6003                goal: SelectionGoal::None,
 6004                reversed: selection.reversed,
 6005            });
 6006
 6007            if lines_after > lines_before {
 6008                added_lines += lines_after - lines_before;
 6009            } else if lines_before > lines_after {
 6010                removed_lines += lines_before - lines_after;
 6011            }
 6012        }
 6013
 6014        self.transact(cx, |this, cx| {
 6015            let buffer = this.buffer.update(cx, |buffer, cx| {
 6016                buffer.edit(edits, None, cx);
 6017                buffer.snapshot(cx)
 6018            });
 6019
 6020            // Recalculate offsets on newly edited buffer
 6021            let new_selections = new_selections
 6022                .iter()
 6023                .map(|s| {
 6024                    let start_point = Point::new(s.start.0, 0);
 6025                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6026                    Selection {
 6027                        id: s.id,
 6028                        start: buffer.point_to_offset(start_point),
 6029                        end: buffer.point_to_offset(end_point),
 6030                        goal: s.goal,
 6031                        reversed: s.reversed,
 6032                    }
 6033                })
 6034                .collect();
 6035
 6036            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6037                s.select(new_selections);
 6038            });
 6039
 6040            this.request_autoscroll(Autoscroll::fit(), cx);
 6041        });
 6042    }
 6043
 6044    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6045        self.manipulate_text(cx, |text| text.to_uppercase())
 6046    }
 6047
 6048    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6049        self.manipulate_text(cx, |text| text.to_lowercase())
 6050    }
 6051
 6052    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6053        self.manipulate_text(cx, |text| {
 6054            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6055            // https://github.com/rutrum/convert-case/issues/16
 6056            text.split('\n')
 6057                .map(|line| line.to_case(Case::Title))
 6058                .join("\n")
 6059        })
 6060    }
 6061
 6062    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6063        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6064    }
 6065
 6066    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6067        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6068    }
 6069
 6070    pub fn convert_to_upper_camel_case(
 6071        &mut self,
 6072        _: &ConvertToUpperCamelCase,
 6073        cx: &mut ViewContext<Self>,
 6074    ) {
 6075        self.manipulate_text(cx, |text| {
 6076            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6077            // https://github.com/rutrum/convert-case/issues/16
 6078            text.split('\n')
 6079                .map(|line| line.to_case(Case::UpperCamel))
 6080                .join("\n")
 6081        })
 6082    }
 6083
 6084    pub fn convert_to_lower_camel_case(
 6085        &mut self,
 6086        _: &ConvertToLowerCamelCase,
 6087        cx: &mut ViewContext<Self>,
 6088    ) {
 6089        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6090    }
 6091
 6092    pub fn convert_to_opposite_case(
 6093        &mut self,
 6094        _: &ConvertToOppositeCase,
 6095        cx: &mut ViewContext<Self>,
 6096    ) {
 6097        self.manipulate_text(cx, |text| {
 6098            text.chars()
 6099                .fold(String::with_capacity(text.len()), |mut t, c| {
 6100                    if c.is_uppercase() {
 6101                        t.extend(c.to_lowercase());
 6102                    } else {
 6103                        t.extend(c.to_uppercase());
 6104                    }
 6105                    t
 6106                })
 6107        })
 6108    }
 6109
 6110    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6111    where
 6112        Fn: FnMut(&str) -> String,
 6113    {
 6114        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6115        let buffer = self.buffer.read(cx).snapshot(cx);
 6116
 6117        let mut new_selections = Vec::new();
 6118        let mut edits = Vec::new();
 6119        let mut selection_adjustment = 0i32;
 6120
 6121        for selection in self.selections.all::<usize>(cx) {
 6122            let selection_is_empty = selection.is_empty();
 6123
 6124            let (start, end) = if selection_is_empty {
 6125                let word_range = movement::surrounding_word(
 6126                    &display_map,
 6127                    selection.start.to_display_point(&display_map),
 6128                );
 6129                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6130                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6131                (start, end)
 6132            } else {
 6133                (selection.start, selection.end)
 6134            };
 6135
 6136            let text = buffer.text_for_range(start..end).collect::<String>();
 6137            let old_length = text.len() as i32;
 6138            let text = callback(&text);
 6139
 6140            new_selections.push(Selection {
 6141                start: (start as i32 - selection_adjustment) as usize,
 6142                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6143                goal: SelectionGoal::None,
 6144                ..selection
 6145            });
 6146
 6147            selection_adjustment += old_length - text.len() as i32;
 6148
 6149            edits.push((start..end, text));
 6150        }
 6151
 6152        self.transact(cx, |this, cx| {
 6153            this.buffer.update(cx, |buffer, cx| {
 6154                buffer.edit(edits, None, cx);
 6155            });
 6156
 6157            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6158                s.select(new_selections);
 6159            });
 6160
 6161            this.request_autoscroll(Autoscroll::fit(), cx);
 6162        });
 6163    }
 6164
 6165    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6166        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6167        let buffer = &display_map.buffer_snapshot;
 6168        let selections = self.selections.all::<Point>(cx);
 6169
 6170        let mut edits = Vec::new();
 6171        let mut selections_iter = selections.iter().peekable();
 6172        while let Some(selection) = selections_iter.next() {
 6173            // Avoid duplicating the same lines twice.
 6174            let mut rows = selection.spanned_rows(false, &display_map);
 6175
 6176            while let Some(next_selection) = selections_iter.peek() {
 6177                let next_rows = next_selection.spanned_rows(false, &display_map);
 6178                if next_rows.start < rows.end {
 6179                    rows.end = next_rows.end;
 6180                    selections_iter.next().unwrap();
 6181                } else {
 6182                    break;
 6183                }
 6184            }
 6185
 6186            // Copy the text from the selected row region and splice it either at the start
 6187            // or end of the region.
 6188            let start = Point::new(rows.start.0, 0);
 6189            let end = Point::new(
 6190                rows.end.previous_row().0,
 6191                buffer.line_len(rows.end.previous_row()),
 6192            );
 6193            let text = buffer
 6194                .text_for_range(start..end)
 6195                .chain(Some("\n"))
 6196                .collect::<String>();
 6197            let insert_location = if upwards {
 6198                Point::new(rows.end.0, 0)
 6199            } else {
 6200                start
 6201            };
 6202            edits.push((insert_location..insert_location, text));
 6203        }
 6204
 6205        self.transact(cx, |this, cx| {
 6206            this.buffer.update(cx, |buffer, cx| {
 6207                buffer.edit(edits, None, cx);
 6208            });
 6209
 6210            this.request_autoscroll(Autoscroll::fit(), cx);
 6211        });
 6212    }
 6213
 6214    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6215        self.duplicate_line(true, cx);
 6216    }
 6217
 6218    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6219        self.duplicate_line(false, cx);
 6220    }
 6221
 6222    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6223        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6224        let buffer = self.buffer.read(cx).snapshot(cx);
 6225
 6226        let mut edits = Vec::new();
 6227        let mut unfold_ranges = Vec::new();
 6228        let mut refold_ranges = Vec::new();
 6229
 6230        let selections = self.selections.all::<Point>(cx);
 6231        let mut selections = selections.iter().peekable();
 6232        let mut contiguous_row_selections = Vec::new();
 6233        let mut new_selections = Vec::new();
 6234
 6235        while let Some(selection) = selections.next() {
 6236            // Find all the selections that span a contiguous row range
 6237            let (start_row, end_row) = consume_contiguous_rows(
 6238                &mut contiguous_row_selections,
 6239                selection,
 6240                &display_map,
 6241                &mut selections,
 6242            );
 6243
 6244            // Move the text spanned by the row range to be before the line preceding the row range
 6245            if start_row.0 > 0 {
 6246                let range_to_move = Point::new(
 6247                    start_row.previous_row().0,
 6248                    buffer.line_len(start_row.previous_row()),
 6249                )
 6250                    ..Point::new(
 6251                        end_row.previous_row().0,
 6252                        buffer.line_len(end_row.previous_row()),
 6253                    );
 6254                let insertion_point = display_map
 6255                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6256                    .0;
 6257
 6258                // Don't move lines across excerpts
 6259                if buffer
 6260                    .excerpt_boundaries_in_range((
 6261                        Bound::Excluded(insertion_point),
 6262                        Bound::Included(range_to_move.end),
 6263                    ))
 6264                    .next()
 6265                    .is_none()
 6266                {
 6267                    let text = buffer
 6268                        .text_for_range(range_to_move.clone())
 6269                        .flat_map(|s| s.chars())
 6270                        .skip(1)
 6271                        .chain(['\n'])
 6272                        .collect::<String>();
 6273
 6274                    edits.push((
 6275                        buffer.anchor_after(range_to_move.start)
 6276                            ..buffer.anchor_before(range_to_move.end),
 6277                        String::new(),
 6278                    ));
 6279                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6280                    edits.push((insertion_anchor..insertion_anchor, text));
 6281
 6282                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6283
 6284                    // Move selections up
 6285                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6286                        |mut selection| {
 6287                            selection.start.row -= row_delta;
 6288                            selection.end.row -= row_delta;
 6289                            selection
 6290                        },
 6291                    ));
 6292
 6293                    // Move folds up
 6294                    unfold_ranges.push(range_to_move.clone());
 6295                    for fold in display_map.folds_in_range(
 6296                        buffer.anchor_before(range_to_move.start)
 6297                            ..buffer.anchor_after(range_to_move.end),
 6298                    ) {
 6299                        let mut start = fold.range.start.to_point(&buffer);
 6300                        let mut end = fold.range.end.to_point(&buffer);
 6301                        start.row -= row_delta;
 6302                        end.row -= row_delta;
 6303                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6304                    }
 6305                }
 6306            }
 6307
 6308            // If we didn't move line(s), preserve the existing selections
 6309            new_selections.append(&mut contiguous_row_selections);
 6310        }
 6311
 6312        self.transact(cx, |this, cx| {
 6313            this.unfold_ranges(unfold_ranges, true, true, cx);
 6314            this.buffer.update(cx, |buffer, cx| {
 6315                for (range, text) in edits {
 6316                    buffer.edit([(range, text)], None, cx);
 6317                }
 6318            });
 6319            this.fold_ranges(refold_ranges, true, cx);
 6320            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6321                s.select(new_selections);
 6322            })
 6323        });
 6324    }
 6325
 6326    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6327        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6328        let buffer = self.buffer.read(cx).snapshot(cx);
 6329
 6330        let mut edits = Vec::new();
 6331        let mut unfold_ranges = Vec::new();
 6332        let mut refold_ranges = Vec::new();
 6333
 6334        let selections = self.selections.all::<Point>(cx);
 6335        let mut selections = selections.iter().peekable();
 6336        let mut contiguous_row_selections = Vec::new();
 6337        let mut new_selections = Vec::new();
 6338
 6339        while let Some(selection) = selections.next() {
 6340            // Find all the selections that span a contiguous row range
 6341            let (start_row, end_row) = consume_contiguous_rows(
 6342                &mut contiguous_row_selections,
 6343                selection,
 6344                &display_map,
 6345                &mut selections,
 6346            );
 6347
 6348            // Move the text spanned by the row range to be after the last line of the row range
 6349            if end_row.0 <= buffer.max_point().row {
 6350                let range_to_move =
 6351                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6352                let insertion_point = display_map
 6353                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6354                    .0;
 6355
 6356                // Don't move lines across excerpt boundaries
 6357                if buffer
 6358                    .excerpt_boundaries_in_range((
 6359                        Bound::Excluded(range_to_move.start),
 6360                        Bound::Included(insertion_point),
 6361                    ))
 6362                    .next()
 6363                    .is_none()
 6364                {
 6365                    let mut text = String::from("\n");
 6366                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6367                    text.pop(); // Drop trailing newline
 6368                    edits.push((
 6369                        buffer.anchor_after(range_to_move.start)
 6370                            ..buffer.anchor_before(range_to_move.end),
 6371                        String::new(),
 6372                    ));
 6373                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6374                    edits.push((insertion_anchor..insertion_anchor, text));
 6375
 6376                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6377
 6378                    // Move selections down
 6379                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6380                        |mut selection| {
 6381                            selection.start.row += row_delta;
 6382                            selection.end.row += row_delta;
 6383                            selection
 6384                        },
 6385                    ));
 6386
 6387                    // Move folds down
 6388                    unfold_ranges.push(range_to_move.clone());
 6389                    for fold in display_map.folds_in_range(
 6390                        buffer.anchor_before(range_to_move.start)
 6391                            ..buffer.anchor_after(range_to_move.end),
 6392                    ) {
 6393                        let mut start = fold.range.start.to_point(&buffer);
 6394                        let mut end = fold.range.end.to_point(&buffer);
 6395                        start.row += row_delta;
 6396                        end.row += row_delta;
 6397                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6398                    }
 6399                }
 6400            }
 6401
 6402            // If we didn't move line(s), preserve the existing selections
 6403            new_selections.append(&mut contiguous_row_selections);
 6404        }
 6405
 6406        self.transact(cx, |this, cx| {
 6407            this.unfold_ranges(unfold_ranges, true, true, cx);
 6408            this.buffer.update(cx, |buffer, cx| {
 6409                for (range, text) in edits {
 6410                    buffer.edit([(range, text)], None, cx);
 6411                }
 6412            });
 6413            this.fold_ranges(refold_ranges, true, cx);
 6414            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6415        });
 6416    }
 6417
 6418    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6419        let text_layout_details = &self.text_layout_details(cx);
 6420        self.transact(cx, |this, cx| {
 6421            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6422                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6423                let line_mode = s.line_mode;
 6424                s.move_with(|display_map, selection| {
 6425                    if !selection.is_empty() || line_mode {
 6426                        return;
 6427                    }
 6428
 6429                    let mut head = selection.head();
 6430                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6431                    if head.column() == display_map.line_len(head.row()) {
 6432                        transpose_offset = display_map
 6433                            .buffer_snapshot
 6434                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6435                    }
 6436
 6437                    if transpose_offset == 0 {
 6438                        return;
 6439                    }
 6440
 6441                    *head.column_mut() += 1;
 6442                    head = display_map.clip_point(head, Bias::Right);
 6443                    let goal = SelectionGoal::HorizontalPosition(
 6444                        display_map
 6445                            .x_for_display_point(head, &text_layout_details)
 6446                            .into(),
 6447                    );
 6448                    selection.collapse_to(head, goal);
 6449
 6450                    let transpose_start = display_map
 6451                        .buffer_snapshot
 6452                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6453                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6454                        let transpose_end = display_map
 6455                            .buffer_snapshot
 6456                            .clip_offset(transpose_offset + 1, Bias::Right);
 6457                        if let Some(ch) =
 6458                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6459                        {
 6460                            edits.push((transpose_start..transpose_offset, String::new()));
 6461                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6462                        }
 6463                    }
 6464                });
 6465                edits
 6466            });
 6467            this.buffer
 6468                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6469            let selections = this.selections.all::<usize>(cx);
 6470            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6471                s.select(selections);
 6472            });
 6473        });
 6474    }
 6475
 6476    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6477        let mut text = String::new();
 6478        let buffer = self.buffer.read(cx).snapshot(cx);
 6479        let mut selections = self.selections.all::<Point>(cx);
 6480        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6481        {
 6482            let max_point = buffer.max_point();
 6483            let mut is_first = true;
 6484            for selection in &mut selections {
 6485                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6486                if is_entire_line {
 6487                    selection.start = Point::new(selection.start.row, 0);
 6488                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6489                    selection.goal = SelectionGoal::None;
 6490                }
 6491                if is_first {
 6492                    is_first = false;
 6493                } else {
 6494                    text += "\n";
 6495                }
 6496                let mut len = 0;
 6497                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6498                    text.push_str(chunk);
 6499                    len += chunk.len();
 6500                }
 6501                clipboard_selections.push(ClipboardSelection {
 6502                    len,
 6503                    is_entire_line,
 6504                    first_line_indent: buffer
 6505                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6506                        .len,
 6507                });
 6508            }
 6509        }
 6510
 6511        self.transact(cx, |this, cx| {
 6512            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6513                s.select(selections);
 6514            });
 6515            this.insert("", cx);
 6516            cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6517        });
 6518    }
 6519
 6520    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6521        let selections = self.selections.all::<Point>(cx);
 6522        let buffer = self.buffer.read(cx).read(cx);
 6523        let mut text = String::new();
 6524
 6525        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6526        {
 6527            let max_point = buffer.max_point();
 6528            let mut is_first = true;
 6529            for selection in selections.iter() {
 6530                let mut start = selection.start;
 6531                let mut end = selection.end;
 6532                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6533                if is_entire_line {
 6534                    start = Point::new(start.row, 0);
 6535                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6536                }
 6537                if is_first {
 6538                    is_first = false;
 6539                } else {
 6540                    text += "\n";
 6541                }
 6542                let mut len = 0;
 6543                for chunk in buffer.text_for_range(start..end) {
 6544                    text.push_str(chunk);
 6545                    len += chunk.len();
 6546                }
 6547                clipboard_selections.push(ClipboardSelection {
 6548                    len,
 6549                    is_entire_line,
 6550                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6551                });
 6552            }
 6553        }
 6554
 6555        cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6556    }
 6557
 6558    pub fn do_paste(
 6559        &mut self,
 6560        text: &String,
 6561        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6562        handle_entire_lines: bool,
 6563        cx: &mut ViewContext<Self>,
 6564    ) {
 6565        if self.read_only(cx) {
 6566            return;
 6567        }
 6568
 6569        let clipboard_text = Cow::Borrowed(text);
 6570
 6571        self.transact(cx, |this, cx| {
 6572            if let Some(mut clipboard_selections) = clipboard_selections {
 6573                let old_selections = this.selections.all::<usize>(cx);
 6574                let all_selections_were_entire_line =
 6575                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6576                let first_selection_indent_column =
 6577                    clipboard_selections.first().map(|s| s.first_line_indent);
 6578                if clipboard_selections.len() != old_selections.len() {
 6579                    clipboard_selections.drain(..);
 6580                }
 6581
 6582                this.buffer.update(cx, |buffer, cx| {
 6583                    let snapshot = buffer.read(cx);
 6584                    let mut start_offset = 0;
 6585                    let mut edits = Vec::new();
 6586                    let mut original_indent_columns = Vec::new();
 6587                    for (ix, selection) in old_selections.iter().enumerate() {
 6588                        let to_insert;
 6589                        let entire_line;
 6590                        let original_indent_column;
 6591                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6592                            let end_offset = start_offset + clipboard_selection.len;
 6593                            to_insert = &clipboard_text[start_offset..end_offset];
 6594                            entire_line = clipboard_selection.is_entire_line;
 6595                            start_offset = end_offset + 1;
 6596                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6597                        } else {
 6598                            to_insert = clipboard_text.as_str();
 6599                            entire_line = all_selections_were_entire_line;
 6600                            original_indent_column = first_selection_indent_column
 6601                        }
 6602
 6603                        // If the corresponding selection was empty when this slice of the
 6604                        // clipboard text was written, then the entire line containing the
 6605                        // selection was copied. If this selection is also currently empty,
 6606                        // then paste the line before the current line of the buffer.
 6607                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6608                            let column = selection.start.to_point(&snapshot).column as usize;
 6609                            let line_start = selection.start - column;
 6610                            line_start..line_start
 6611                        } else {
 6612                            selection.range()
 6613                        };
 6614
 6615                        edits.push((range, to_insert));
 6616                        original_indent_columns.extend(original_indent_column);
 6617                    }
 6618                    drop(snapshot);
 6619
 6620                    buffer.edit(
 6621                        edits,
 6622                        Some(AutoindentMode::Block {
 6623                            original_indent_columns,
 6624                        }),
 6625                        cx,
 6626                    );
 6627                });
 6628
 6629                let selections = this.selections.all::<usize>(cx);
 6630                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6631            } else {
 6632                this.insert(&clipboard_text, cx);
 6633            }
 6634        });
 6635    }
 6636
 6637    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6638        if let Some(item) = cx.read_from_clipboard() {
 6639            self.do_paste(
 6640                item.text(),
 6641                item.metadata::<Vec<ClipboardSelection>>(),
 6642                true,
 6643                cx,
 6644            )
 6645        };
 6646    }
 6647
 6648    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6649        if self.read_only(cx) {
 6650            return;
 6651        }
 6652
 6653        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6654            if let Some((selections, _)) =
 6655                self.selection_history.transaction(transaction_id).cloned()
 6656            {
 6657                self.change_selections(None, cx, |s| {
 6658                    s.select_anchors(selections.to_vec());
 6659                });
 6660            }
 6661            self.request_autoscroll(Autoscroll::fit(), cx);
 6662            self.unmark_text(cx);
 6663            self.refresh_inline_completion(true, cx);
 6664            cx.emit(EditorEvent::Edited { transaction_id });
 6665            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 6666        }
 6667    }
 6668
 6669    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 6670        if self.read_only(cx) {
 6671            return;
 6672        }
 6673
 6674        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 6675            if let Some((_, Some(selections))) =
 6676                self.selection_history.transaction(transaction_id).cloned()
 6677            {
 6678                self.change_selections(None, cx, |s| {
 6679                    s.select_anchors(selections.to_vec());
 6680                });
 6681            }
 6682            self.request_autoscroll(Autoscroll::fit(), cx);
 6683            self.unmark_text(cx);
 6684            self.refresh_inline_completion(true, cx);
 6685            cx.emit(EditorEvent::Edited { transaction_id });
 6686        }
 6687    }
 6688
 6689    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 6690        self.buffer
 6691            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 6692    }
 6693
 6694    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 6695        self.buffer
 6696            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 6697    }
 6698
 6699    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 6700        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6701            let line_mode = s.line_mode;
 6702            s.move_with(|map, selection| {
 6703                let cursor = if selection.is_empty() && !line_mode {
 6704                    movement::left(map, selection.start)
 6705                } else {
 6706                    selection.start
 6707                };
 6708                selection.collapse_to(cursor, SelectionGoal::None);
 6709            });
 6710        })
 6711    }
 6712
 6713    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 6714        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6715            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 6716        })
 6717    }
 6718
 6719    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 6720        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6721            let line_mode = s.line_mode;
 6722            s.move_with(|map, selection| {
 6723                let cursor = if selection.is_empty() && !line_mode {
 6724                    movement::right(map, selection.end)
 6725                } else {
 6726                    selection.end
 6727                };
 6728                selection.collapse_to(cursor, SelectionGoal::None)
 6729            });
 6730        })
 6731    }
 6732
 6733    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 6734        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6735            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 6736        })
 6737    }
 6738
 6739    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 6740        if self.take_rename(true, cx).is_some() {
 6741            return;
 6742        }
 6743
 6744        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6745            cx.propagate();
 6746            return;
 6747        }
 6748
 6749        let text_layout_details = &self.text_layout_details(cx);
 6750        let selection_count = self.selections.count();
 6751        let first_selection = self.selections.first_anchor();
 6752
 6753        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6754            let line_mode = s.line_mode;
 6755            s.move_with(|map, selection| {
 6756                if !selection.is_empty() && !line_mode {
 6757                    selection.goal = SelectionGoal::None;
 6758                }
 6759                let (cursor, goal) = movement::up(
 6760                    map,
 6761                    selection.start,
 6762                    selection.goal,
 6763                    false,
 6764                    &text_layout_details,
 6765                );
 6766                selection.collapse_to(cursor, goal);
 6767            });
 6768        });
 6769
 6770        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6771        {
 6772            cx.propagate();
 6773        }
 6774    }
 6775
 6776    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 6777        if self.take_rename(true, cx).is_some() {
 6778            return;
 6779        }
 6780
 6781        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6782            cx.propagate();
 6783            return;
 6784        }
 6785
 6786        let text_layout_details = &self.text_layout_details(cx);
 6787
 6788        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6789            let line_mode = s.line_mode;
 6790            s.move_with(|map, selection| {
 6791                if !selection.is_empty() && !line_mode {
 6792                    selection.goal = SelectionGoal::None;
 6793                }
 6794                let (cursor, goal) = movement::up_by_rows(
 6795                    map,
 6796                    selection.start,
 6797                    action.lines,
 6798                    selection.goal,
 6799                    false,
 6800                    &text_layout_details,
 6801                );
 6802                selection.collapse_to(cursor, goal);
 6803            });
 6804        })
 6805    }
 6806
 6807    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 6808        if self.take_rename(true, cx).is_some() {
 6809            return;
 6810        }
 6811
 6812        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6813            cx.propagate();
 6814            return;
 6815        }
 6816
 6817        let text_layout_details = &self.text_layout_details(cx);
 6818
 6819        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6820            let line_mode = s.line_mode;
 6821            s.move_with(|map, selection| {
 6822                if !selection.is_empty() && !line_mode {
 6823                    selection.goal = SelectionGoal::None;
 6824                }
 6825                let (cursor, goal) = movement::down_by_rows(
 6826                    map,
 6827                    selection.start,
 6828                    action.lines,
 6829                    selection.goal,
 6830                    false,
 6831                    &text_layout_details,
 6832                );
 6833                selection.collapse_to(cursor, goal);
 6834            });
 6835        })
 6836    }
 6837
 6838    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 6839        let text_layout_details = &self.text_layout_details(cx);
 6840        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6841            s.move_heads_with(|map, head, goal| {
 6842                movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6843            })
 6844        })
 6845    }
 6846
 6847    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 6848        let text_layout_details = &self.text_layout_details(cx);
 6849        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6850            s.move_heads_with(|map, head, goal| {
 6851                movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6852            })
 6853        })
 6854    }
 6855
 6856    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 6857        let Some(row_count) = self.visible_row_count() else {
 6858            return;
 6859        };
 6860
 6861        let text_layout_details = &self.text_layout_details(cx);
 6862
 6863        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6864            s.move_heads_with(|map, head, goal| {
 6865                movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
 6866            })
 6867        })
 6868    }
 6869
 6870    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 6871        if self.take_rename(true, cx).is_some() {
 6872            return;
 6873        }
 6874
 6875        if self
 6876            .context_menu
 6877            .write()
 6878            .as_mut()
 6879            .map(|menu| menu.select_first(self.project.as_ref(), cx))
 6880            .unwrap_or(false)
 6881        {
 6882            return;
 6883        }
 6884
 6885        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6886            cx.propagate();
 6887            return;
 6888        }
 6889
 6890        let Some(row_count) = self.visible_row_count() else {
 6891            return;
 6892        };
 6893
 6894        let autoscroll = if action.center_cursor {
 6895            Autoscroll::center()
 6896        } else {
 6897            Autoscroll::fit()
 6898        };
 6899
 6900        let text_layout_details = &self.text_layout_details(cx);
 6901
 6902        self.change_selections(Some(autoscroll), cx, |s| {
 6903            let line_mode = s.line_mode;
 6904            s.move_with(|map, selection| {
 6905                if !selection.is_empty() && !line_mode {
 6906                    selection.goal = SelectionGoal::None;
 6907                }
 6908                let (cursor, goal) = movement::up_by_rows(
 6909                    map,
 6910                    selection.end,
 6911                    row_count,
 6912                    selection.goal,
 6913                    false,
 6914                    &text_layout_details,
 6915                );
 6916                selection.collapse_to(cursor, goal);
 6917            });
 6918        });
 6919    }
 6920
 6921    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 6922        let text_layout_details = &self.text_layout_details(cx);
 6923        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6924            s.move_heads_with(|map, head, goal| {
 6925                movement::up(map, head, goal, false, &text_layout_details)
 6926            })
 6927        })
 6928    }
 6929
 6930    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 6931        self.take_rename(true, cx);
 6932
 6933        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6934            cx.propagate();
 6935            return;
 6936        }
 6937
 6938        let text_layout_details = &self.text_layout_details(cx);
 6939        let selection_count = self.selections.count();
 6940        let first_selection = self.selections.first_anchor();
 6941
 6942        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6943            let line_mode = s.line_mode;
 6944            s.move_with(|map, selection| {
 6945                if !selection.is_empty() && !line_mode {
 6946                    selection.goal = SelectionGoal::None;
 6947                }
 6948                let (cursor, goal) = movement::down(
 6949                    map,
 6950                    selection.end,
 6951                    selection.goal,
 6952                    false,
 6953                    &text_layout_details,
 6954                );
 6955                selection.collapse_to(cursor, goal);
 6956            });
 6957        });
 6958
 6959        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6960        {
 6961            cx.propagate();
 6962        }
 6963    }
 6964
 6965    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 6966        let Some(row_count) = self.visible_row_count() else {
 6967            return;
 6968        };
 6969
 6970        let text_layout_details = &self.text_layout_details(cx);
 6971
 6972        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6973            s.move_heads_with(|map, head, goal| {
 6974                movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
 6975            })
 6976        })
 6977    }
 6978
 6979    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 6980        if self.take_rename(true, cx).is_some() {
 6981            return;
 6982        }
 6983
 6984        if self
 6985            .context_menu
 6986            .write()
 6987            .as_mut()
 6988            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 6989            .unwrap_or(false)
 6990        {
 6991            return;
 6992        }
 6993
 6994        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6995            cx.propagate();
 6996            return;
 6997        }
 6998
 6999        let Some(row_count) = self.visible_row_count() else {
 7000            return;
 7001        };
 7002
 7003        let autoscroll = if action.center_cursor {
 7004            Autoscroll::center()
 7005        } else {
 7006            Autoscroll::fit()
 7007        };
 7008
 7009        let text_layout_details = &self.text_layout_details(cx);
 7010        self.change_selections(Some(autoscroll), cx, |s| {
 7011            let line_mode = s.line_mode;
 7012            s.move_with(|map, selection| {
 7013                if !selection.is_empty() && !line_mode {
 7014                    selection.goal = SelectionGoal::None;
 7015                }
 7016                let (cursor, goal) = movement::down_by_rows(
 7017                    map,
 7018                    selection.end,
 7019                    row_count,
 7020                    selection.goal,
 7021                    false,
 7022                    &text_layout_details,
 7023                );
 7024                selection.collapse_to(cursor, goal);
 7025            });
 7026        });
 7027    }
 7028
 7029    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7030        let text_layout_details = &self.text_layout_details(cx);
 7031        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7032            s.move_heads_with(|map, head, goal| {
 7033                movement::down(map, head, goal, false, &text_layout_details)
 7034            })
 7035        });
 7036    }
 7037
 7038    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7039        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7040            context_menu.select_first(self.project.as_ref(), cx);
 7041        }
 7042    }
 7043
 7044    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7045        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7046            context_menu.select_prev(self.project.as_ref(), cx);
 7047        }
 7048    }
 7049
 7050    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7051        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7052            context_menu.select_next(self.project.as_ref(), cx);
 7053        }
 7054    }
 7055
 7056    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7057        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7058            context_menu.select_last(self.project.as_ref(), cx);
 7059        }
 7060    }
 7061
 7062    pub fn move_to_previous_word_start(
 7063        &mut self,
 7064        _: &MoveToPreviousWordStart,
 7065        cx: &mut ViewContext<Self>,
 7066    ) {
 7067        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7068            s.move_cursors_with(|map, head, _| {
 7069                (
 7070                    movement::previous_word_start(map, head),
 7071                    SelectionGoal::None,
 7072                )
 7073            });
 7074        })
 7075    }
 7076
 7077    pub fn move_to_previous_subword_start(
 7078        &mut self,
 7079        _: &MoveToPreviousSubwordStart,
 7080        cx: &mut ViewContext<Self>,
 7081    ) {
 7082        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7083            s.move_cursors_with(|map, head, _| {
 7084                (
 7085                    movement::previous_subword_start(map, head),
 7086                    SelectionGoal::None,
 7087                )
 7088            });
 7089        })
 7090    }
 7091
 7092    pub fn select_to_previous_word_start(
 7093        &mut self,
 7094        _: &SelectToPreviousWordStart,
 7095        cx: &mut ViewContext<Self>,
 7096    ) {
 7097        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7098            s.move_heads_with(|map, head, _| {
 7099                (
 7100                    movement::previous_word_start(map, head),
 7101                    SelectionGoal::None,
 7102                )
 7103            });
 7104        })
 7105    }
 7106
 7107    pub fn select_to_previous_subword_start(
 7108        &mut self,
 7109        _: &SelectToPreviousSubwordStart,
 7110        cx: &mut ViewContext<Self>,
 7111    ) {
 7112        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7113            s.move_heads_with(|map, head, _| {
 7114                (
 7115                    movement::previous_subword_start(map, head),
 7116                    SelectionGoal::None,
 7117                )
 7118            });
 7119        })
 7120    }
 7121
 7122    pub fn delete_to_previous_word_start(
 7123        &mut self,
 7124        _: &DeleteToPreviousWordStart,
 7125        cx: &mut ViewContext<Self>,
 7126    ) {
 7127        self.transact(cx, |this, cx| {
 7128            this.select_autoclose_pair(cx);
 7129            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7130                let line_mode = s.line_mode;
 7131                s.move_with(|map, selection| {
 7132                    if selection.is_empty() && !line_mode {
 7133                        let cursor = movement::previous_word_start(map, selection.head());
 7134                        selection.set_head(cursor, SelectionGoal::None);
 7135                    }
 7136                });
 7137            });
 7138            this.insert("", cx);
 7139        });
 7140    }
 7141
 7142    pub fn delete_to_previous_subword_start(
 7143        &mut self,
 7144        _: &DeleteToPreviousSubwordStart,
 7145        cx: &mut ViewContext<Self>,
 7146    ) {
 7147        self.transact(cx, |this, cx| {
 7148            this.select_autoclose_pair(cx);
 7149            this.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                        let cursor = movement::previous_subword_start(map, selection.head());
 7154                        selection.set_head(cursor, SelectionGoal::None);
 7155                    }
 7156                });
 7157            });
 7158            this.insert("", cx);
 7159        });
 7160    }
 7161
 7162    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7163        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7164            s.move_cursors_with(|map, head, _| {
 7165                (movement::next_word_end(map, head), SelectionGoal::None)
 7166            });
 7167        })
 7168    }
 7169
 7170    pub fn move_to_next_subword_end(
 7171        &mut self,
 7172        _: &MoveToNextSubwordEnd,
 7173        cx: &mut ViewContext<Self>,
 7174    ) {
 7175        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7176            s.move_cursors_with(|map, head, _| {
 7177                (movement::next_subword_end(map, head), SelectionGoal::None)
 7178            });
 7179        })
 7180    }
 7181
 7182    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7183        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7184            s.move_heads_with(|map, head, _| {
 7185                (movement::next_word_end(map, head), SelectionGoal::None)
 7186            });
 7187        })
 7188    }
 7189
 7190    pub fn select_to_next_subword_end(
 7191        &mut self,
 7192        _: &SelectToNextSubwordEnd,
 7193        cx: &mut ViewContext<Self>,
 7194    ) {
 7195        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7196            s.move_heads_with(|map, head, _| {
 7197                (movement::next_subword_end(map, head), SelectionGoal::None)
 7198            });
 7199        })
 7200    }
 7201
 7202    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
 7203        self.transact(cx, |this, cx| {
 7204            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7205                let line_mode = s.line_mode;
 7206                s.move_with(|map, selection| {
 7207                    if selection.is_empty() && !line_mode {
 7208                        let cursor = movement::next_word_end(map, selection.head());
 7209                        selection.set_head(cursor, SelectionGoal::None);
 7210                    }
 7211                });
 7212            });
 7213            this.insert("", cx);
 7214        });
 7215    }
 7216
 7217    pub fn delete_to_next_subword_end(
 7218        &mut self,
 7219        _: &DeleteToNextSubwordEnd,
 7220        cx: &mut ViewContext<Self>,
 7221    ) {
 7222        self.transact(cx, |this, cx| {
 7223            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7224                s.move_with(|map, selection| {
 7225                    if selection.is_empty() {
 7226                        let cursor = movement::next_subword_end(map, selection.head());
 7227                        selection.set_head(cursor, SelectionGoal::None);
 7228                    }
 7229                });
 7230            });
 7231            this.insert("", cx);
 7232        });
 7233    }
 7234
 7235    pub fn move_to_beginning_of_line(
 7236        &mut self,
 7237        action: &MoveToBeginningOfLine,
 7238        cx: &mut ViewContext<Self>,
 7239    ) {
 7240        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7241            s.move_cursors_with(|map, head, _| {
 7242                (
 7243                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7244                    SelectionGoal::None,
 7245                )
 7246            });
 7247        })
 7248    }
 7249
 7250    pub fn select_to_beginning_of_line(
 7251        &mut self,
 7252        action: &SelectToBeginningOfLine,
 7253        cx: &mut ViewContext<Self>,
 7254    ) {
 7255        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7256            s.move_heads_with(|map, head, _| {
 7257                (
 7258                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7259                    SelectionGoal::None,
 7260                )
 7261            });
 7262        });
 7263    }
 7264
 7265    pub fn delete_to_beginning_of_line(
 7266        &mut self,
 7267        _: &DeleteToBeginningOfLine,
 7268        cx: &mut ViewContext<Self>,
 7269    ) {
 7270        self.transact(cx, |this, cx| {
 7271            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7272                s.move_with(|_, selection| {
 7273                    selection.reversed = true;
 7274                });
 7275            });
 7276
 7277            this.select_to_beginning_of_line(
 7278                &SelectToBeginningOfLine {
 7279                    stop_at_soft_wraps: false,
 7280                },
 7281                cx,
 7282            );
 7283            this.backspace(&Backspace, cx);
 7284        });
 7285    }
 7286
 7287    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7288        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7289            s.move_cursors_with(|map, head, _| {
 7290                (
 7291                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7292                    SelectionGoal::None,
 7293                )
 7294            });
 7295        })
 7296    }
 7297
 7298    pub fn select_to_end_of_line(
 7299        &mut self,
 7300        action: &SelectToEndOfLine,
 7301        cx: &mut ViewContext<Self>,
 7302    ) {
 7303        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7304            s.move_heads_with(|map, head, _| {
 7305                (
 7306                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7307                    SelectionGoal::None,
 7308                )
 7309            });
 7310        })
 7311    }
 7312
 7313    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7314        self.transact(cx, |this, cx| {
 7315            this.select_to_end_of_line(
 7316                &SelectToEndOfLine {
 7317                    stop_at_soft_wraps: false,
 7318                },
 7319                cx,
 7320            );
 7321            this.delete(&Delete, cx);
 7322        });
 7323    }
 7324
 7325    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7326        self.transact(cx, |this, cx| {
 7327            this.select_to_end_of_line(
 7328                &SelectToEndOfLine {
 7329                    stop_at_soft_wraps: false,
 7330                },
 7331                cx,
 7332            );
 7333            this.cut(&Cut, cx);
 7334        });
 7335    }
 7336
 7337    pub fn move_to_start_of_paragraph(
 7338        &mut self,
 7339        _: &MoveToStartOfParagraph,
 7340        cx: &mut ViewContext<Self>,
 7341    ) {
 7342        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7343            cx.propagate();
 7344            return;
 7345        }
 7346
 7347        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7348            s.move_with(|map, selection| {
 7349                selection.collapse_to(
 7350                    movement::start_of_paragraph(map, selection.head(), 1),
 7351                    SelectionGoal::None,
 7352                )
 7353            });
 7354        })
 7355    }
 7356
 7357    pub fn move_to_end_of_paragraph(
 7358        &mut self,
 7359        _: &MoveToEndOfParagraph,
 7360        cx: &mut ViewContext<Self>,
 7361    ) {
 7362        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7363            cx.propagate();
 7364            return;
 7365        }
 7366
 7367        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7368            s.move_with(|map, selection| {
 7369                selection.collapse_to(
 7370                    movement::end_of_paragraph(map, selection.head(), 1),
 7371                    SelectionGoal::None,
 7372                )
 7373            });
 7374        })
 7375    }
 7376
 7377    pub fn select_to_start_of_paragraph(
 7378        &mut self,
 7379        _: &SelectToStartOfParagraph,
 7380        cx: &mut ViewContext<Self>,
 7381    ) {
 7382        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7383            cx.propagate();
 7384            return;
 7385        }
 7386
 7387        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7388            s.move_heads_with(|map, head, _| {
 7389                (
 7390                    movement::start_of_paragraph(map, head, 1),
 7391                    SelectionGoal::None,
 7392                )
 7393            });
 7394        })
 7395    }
 7396
 7397    pub fn select_to_end_of_paragraph(
 7398        &mut self,
 7399        _: &SelectToEndOfParagraph,
 7400        cx: &mut ViewContext<Self>,
 7401    ) {
 7402        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7403            cx.propagate();
 7404            return;
 7405        }
 7406
 7407        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7408            s.move_heads_with(|map, head, _| {
 7409                (
 7410                    movement::end_of_paragraph(map, head, 1),
 7411                    SelectionGoal::None,
 7412                )
 7413            });
 7414        })
 7415    }
 7416
 7417    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7418        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7419            cx.propagate();
 7420            return;
 7421        }
 7422
 7423        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7424            s.select_ranges(vec![0..0]);
 7425        });
 7426    }
 7427
 7428    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7429        let mut selection = self.selections.last::<Point>(cx);
 7430        selection.set_head(Point::zero(), SelectionGoal::None);
 7431
 7432        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7433            s.select(vec![selection]);
 7434        });
 7435    }
 7436
 7437    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7438        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7439            cx.propagate();
 7440            return;
 7441        }
 7442
 7443        let cursor = self.buffer.read(cx).read(cx).len();
 7444        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7445            s.select_ranges(vec![cursor..cursor])
 7446        });
 7447    }
 7448
 7449    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7450        self.nav_history = nav_history;
 7451    }
 7452
 7453    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7454        self.nav_history.as_ref()
 7455    }
 7456
 7457    fn push_to_nav_history(
 7458        &mut self,
 7459        cursor_anchor: Anchor,
 7460        new_position: Option<Point>,
 7461        cx: &mut ViewContext<Self>,
 7462    ) {
 7463        if let Some(nav_history) = self.nav_history.as_mut() {
 7464            let buffer = self.buffer.read(cx).read(cx);
 7465            let cursor_position = cursor_anchor.to_point(&buffer);
 7466            let scroll_state = self.scroll_manager.anchor();
 7467            let scroll_top_row = scroll_state.top_row(&buffer);
 7468            drop(buffer);
 7469
 7470            if let Some(new_position) = new_position {
 7471                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7472                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7473                    return;
 7474                }
 7475            }
 7476
 7477            nav_history.push(
 7478                Some(NavigationData {
 7479                    cursor_anchor,
 7480                    cursor_position,
 7481                    scroll_anchor: scroll_state,
 7482                    scroll_top_row,
 7483                }),
 7484                cx,
 7485            );
 7486        }
 7487    }
 7488
 7489    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7490        let buffer = self.buffer.read(cx).snapshot(cx);
 7491        let mut selection = self.selections.first::<usize>(cx);
 7492        selection.set_head(buffer.len(), SelectionGoal::None);
 7493        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7494            s.select(vec![selection]);
 7495        });
 7496    }
 7497
 7498    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7499        let end = self.buffer.read(cx).read(cx).len();
 7500        self.change_selections(None, cx, |s| {
 7501            s.select_ranges(vec![0..end]);
 7502        });
 7503    }
 7504
 7505    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7506        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7507        let mut selections = self.selections.all::<Point>(cx);
 7508        let max_point = display_map.buffer_snapshot.max_point();
 7509        for selection in &mut selections {
 7510            let rows = selection.spanned_rows(true, &display_map);
 7511            selection.start = Point::new(rows.start.0, 0);
 7512            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7513            selection.reversed = false;
 7514        }
 7515        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7516            s.select(selections);
 7517        });
 7518    }
 7519
 7520    pub fn split_selection_into_lines(
 7521        &mut self,
 7522        _: &SplitSelectionIntoLines,
 7523        cx: &mut ViewContext<Self>,
 7524    ) {
 7525        let mut to_unfold = Vec::new();
 7526        let mut new_selection_ranges = Vec::new();
 7527        {
 7528            let selections = self.selections.all::<Point>(cx);
 7529            let buffer = self.buffer.read(cx).read(cx);
 7530            for selection in selections {
 7531                for row in selection.start.row..selection.end.row {
 7532                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7533                    new_selection_ranges.push(cursor..cursor);
 7534                }
 7535                new_selection_ranges.push(selection.end..selection.end);
 7536                to_unfold.push(selection.start..selection.end);
 7537            }
 7538        }
 7539        self.unfold_ranges(to_unfold, true, true, cx);
 7540        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7541            s.select_ranges(new_selection_ranges);
 7542        });
 7543    }
 7544
 7545    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7546        self.add_selection(true, cx);
 7547    }
 7548
 7549    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7550        self.add_selection(false, cx);
 7551    }
 7552
 7553    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7554        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7555        let mut selections = self.selections.all::<Point>(cx);
 7556        let text_layout_details = self.text_layout_details(cx);
 7557        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7558            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7559            let range = oldest_selection.display_range(&display_map).sorted();
 7560
 7561            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7562            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7563            let positions = start_x.min(end_x)..start_x.max(end_x);
 7564
 7565            selections.clear();
 7566            let mut stack = Vec::new();
 7567            for row in range.start.row().0..=range.end.row().0 {
 7568                if let Some(selection) = self.selections.build_columnar_selection(
 7569                    &display_map,
 7570                    DisplayRow(row),
 7571                    &positions,
 7572                    oldest_selection.reversed,
 7573                    &text_layout_details,
 7574                ) {
 7575                    stack.push(selection.id);
 7576                    selections.push(selection);
 7577                }
 7578            }
 7579
 7580            if above {
 7581                stack.reverse();
 7582            }
 7583
 7584            AddSelectionsState { above, stack }
 7585        });
 7586
 7587        let last_added_selection = *state.stack.last().unwrap();
 7588        let mut new_selections = Vec::new();
 7589        if above == state.above {
 7590            let end_row = if above {
 7591                DisplayRow(0)
 7592            } else {
 7593                display_map.max_point().row()
 7594            };
 7595
 7596            'outer: for selection in selections {
 7597                if selection.id == last_added_selection {
 7598                    let range = selection.display_range(&display_map).sorted();
 7599                    debug_assert_eq!(range.start.row(), range.end.row());
 7600                    let mut row = range.start.row();
 7601                    let positions =
 7602                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7603                            px(start)..px(end)
 7604                        } else {
 7605                            let start_x =
 7606                                display_map.x_for_display_point(range.start, &text_layout_details);
 7607                            let end_x =
 7608                                display_map.x_for_display_point(range.end, &text_layout_details);
 7609                            start_x.min(end_x)..start_x.max(end_x)
 7610                        };
 7611
 7612                    while row != end_row {
 7613                        if above {
 7614                            row.0 -= 1;
 7615                        } else {
 7616                            row.0 += 1;
 7617                        }
 7618
 7619                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7620                            &display_map,
 7621                            row,
 7622                            &positions,
 7623                            selection.reversed,
 7624                            &text_layout_details,
 7625                        ) {
 7626                            state.stack.push(new_selection.id);
 7627                            if above {
 7628                                new_selections.push(new_selection);
 7629                                new_selections.push(selection);
 7630                            } else {
 7631                                new_selections.push(selection);
 7632                                new_selections.push(new_selection);
 7633                            }
 7634
 7635                            continue 'outer;
 7636                        }
 7637                    }
 7638                }
 7639
 7640                new_selections.push(selection);
 7641            }
 7642        } else {
 7643            new_selections = selections;
 7644            new_selections.retain(|s| s.id != last_added_selection);
 7645            state.stack.pop();
 7646        }
 7647
 7648        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7649            s.select(new_selections);
 7650        });
 7651        if state.stack.len() > 1 {
 7652            self.add_selections_state = Some(state);
 7653        }
 7654    }
 7655
 7656    pub fn select_next_match_internal(
 7657        &mut self,
 7658        display_map: &DisplaySnapshot,
 7659        replace_newest: bool,
 7660        autoscroll: Option<Autoscroll>,
 7661        cx: &mut ViewContext<Self>,
 7662    ) -> Result<()> {
 7663        fn select_next_match_ranges(
 7664            this: &mut Editor,
 7665            range: Range<usize>,
 7666            replace_newest: bool,
 7667            auto_scroll: Option<Autoscroll>,
 7668            cx: &mut ViewContext<Editor>,
 7669        ) {
 7670            this.unfold_ranges([range.clone()], false, true, cx);
 7671            this.change_selections(auto_scroll, cx, |s| {
 7672                if replace_newest {
 7673                    s.delete(s.newest_anchor().id);
 7674                }
 7675                s.insert_range(range.clone());
 7676            });
 7677        }
 7678
 7679        let buffer = &display_map.buffer_snapshot;
 7680        let mut selections = self.selections.all::<usize>(cx);
 7681        if let Some(mut select_next_state) = self.select_next_state.take() {
 7682            let query = &select_next_state.query;
 7683            if !select_next_state.done {
 7684                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7685                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7686                let mut next_selected_range = None;
 7687
 7688                let bytes_after_last_selection =
 7689                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7690                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7691                let query_matches = query
 7692                    .stream_find_iter(bytes_after_last_selection)
 7693                    .map(|result| (last_selection.end, result))
 7694                    .chain(
 7695                        query
 7696                            .stream_find_iter(bytes_before_first_selection)
 7697                            .map(|result| (0, result)),
 7698                    );
 7699
 7700                for (start_offset, query_match) in query_matches {
 7701                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7702                    let offset_range =
 7703                        start_offset + query_match.start()..start_offset + query_match.end();
 7704                    let display_range = offset_range.start.to_display_point(&display_map)
 7705                        ..offset_range.end.to_display_point(&display_map);
 7706
 7707                    if !select_next_state.wordwise
 7708                        || (!movement::is_inside_word(&display_map, display_range.start)
 7709                            && !movement::is_inside_word(&display_map, display_range.end))
 7710                    {
 7711                        // TODO: This is n^2, because we might check all the selections
 7712                        if !selections
 7713                            .iter()
 7714                            .any(|selection| selection.range().overlaps(&offset_range))
 7715                        {
 7716                            next_selected_range = Some(offset_range);
 7717                            break;
 7718                        }
 7719                    }
 7720                }
 7721
 7722                if let Some(next_selected_range) = next_selected_range {
 7723                    select_next_match_ranges(
 7724                        self,
 7725                        next_selected_range,
 7726                        replace_newest,
 7727                        autoscroll,
 7728                        cx,
 7729                    );
 7730                } else {
 7731                    select_next_state.done = true;
 7732                }
 7733            }
 7734
 7735            self.select_next_state = Some(select_next_state);
 7736        } else {
 7737            let mut only_carets = true;
 7738            let mut same_text_selected = true;
 7739            let mut selected_text = None;
 7740
 7741            let mut selections_iter = selections.iter().peekable();
 7742            while let Some(selection) = selections_iter.next() {
 7743                if selection.start != selection.end {
 7744                    only_carets = false;
 7745                }
 7746
 7747                if same_text_selected {
 7748                    if selected_text.is_none() {
 7749                        selected_text =
 7750                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7751                    }
 7752
 7753                    if let Some(next_selection) = selections_iter.peek() {
 7754                        if next_selection.range().len() == selection.range().len() {
 7755                            let next_selected_text = buffer
 7756                                .text_for_range(next_selection.range())
 7757                                .collect::<String>();
 7758                            if Some(next_selected_text) != selected_text {
 7759                                same_text_selected = false;
 7760                                selected_text = None;
 7761                            }
 7762                        } else {
 7763                            same_text_selected = false;
 7764                            selected_text = None;
 7765                        }
 7766                    }
 7767                }
 7768            }
 7769
 7770            if only_carets {
 7771                for selection in &mut selections {
 7772                    let word_range = movement::surrounding_word(
 7773                        &display_map,
 7774                        selection.start.to_display_point(&display_map),
 7775                    );
 7776                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7777                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7778                    selection.goal = SelectionGoal::None;
 7779                    selection.reversed = false;
 7780                    select_next_match_ranges(
 7781                        self,
 7782                        selection.start..selection.end,
 7783                        replace_newest,
 7784                        autoscroll,
 7785                        cx,
 7786                    );
 7787                }
 7788
 7789                if selections.len() == 1 {
 7790                    let selection = selections
 7791                        .last()
 7792                        .expect("ensured that there's only one selection");
 7793                    let query = buffer
 7794                        .text_for_range(selection.start..selection.end)
 7795                        .collect::<String>();
 7796                    let is_empty = query.is_empty();
 7797                    let select_state = SelectNextState {
 7798                        query: AhoCorasick::new(&[query])?,
 7799                        wordwise: true,
 7800                        done: is_empty,
 7801                    };
 7802                    self.select_next_state = Some(select_state);
 7803                } else {
 7804                    self.select_next_state = None;
 7805                }
 7806            } else if let Some(selected_text) = selected_text {
 7807                self.select_next_state = Some(SelectNextState {
 7808                    query: AhoCorasick::new(&[selected_text])?,
 7809                    wordwise: false,
 7810                    done: false,
 7811                });
 7812                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 7813            }
 7814        }
 7815        Ok(())
 7816    }
 7817
 7818    pub fn select_all_matches(
 7819        &mut self,
 7820        _action: &SelectAllMatches,
 7821        cx: &mut ViewContext<Self>,
 7822    ) -> Result<()> {
 7823        self.push_to_selection_history();
 7824        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7825
 7826        self.select_next_match_internal(&display_map, false, None, cx)?;
 7827        let Some(select_next_state) = self.select_next_state.as_mut() else {
 7828            return Ok(());
 7829        };
 7830        if select_next_state.done {
 7831            return Ok(());
 7832        }
 7833
 7834        let mut new_selections = self.selections.all::<usize>(cx);
 7835
 7836        let buffer = &display_map.buffer_snapshot;
 7837        let query_matches = select_next_state
 7838            .query
 7839            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 7840
 7841        for query_match in query_matches {
 7842            let query_match = query_match.unwrap(); // can only fail due to I/O
 7843            let offset_range = query_match.start()..query_match.end();
 7844            let display_range = offset_range.start.to_display_point(&display_map)
 7845                ..offset_range.end.to_display_point(&display_map);
 7846
 7847            if !select_next_state.wordwise
 7848                || (!movement::is_inside_word(&display_map, display_range.start)
 7849                    && !movement::is_inside_word(&display_map, display_range.end))
 7850            {
 7851                self.selections.change_with(cx, |selections| {
 7852                    new_selections.push(Selection {
 7853                        id: selections.new_selection_id(),
 7854                        start: offset_range.start,
 7855                        end: offset_range.end,
 7856                        reversed: false,
 7857                        goal: SelectionGoal::None,
 7858                    });
 7859                });
 7860            }
 7861        }
 7862
 7863        new_selections.sort_by_key(|selection| selection.start);
 7864        let mut ix = 0;
 7865        while ix + 1 < new_selections.len() {
 7866            let current_selection = &new_selections[ix];
 7867            let next_selection = &new_selections[ix + 1];
 7868            if current_selection.range().overlaps(&next_selection.range()) {
 7869                if current_selection.id < next_selection.id {
 7870                    new_selections.remove(ix + 1);
 7871                } else {
 7872                    new_selections.remove(ix);
 7873                }
 7874            } else {
 7875                ix += 1;
 7876            }
 7877        }
 7878
 7879        select_next_state.done = true;
 7880        self.unfold_ranges(
 7881            new_selections.iter().map(|selection| selection.range()),
 7882            false,
 7883            false,
 7884            cx,
 7885        );
 7886        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 7887            selections.select(new_selections)
 7888        });
 7889
 7890        Ok(())
 7891    }
 7892
 7893    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 7894        self.push_to_selection_history();
 7895        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7896        self.select_next_match_internal(
 7897            &display_map,
 7898            action.replace_newest,
 7899            Some(Autoscroll::newest()),
 7900            cx,
 7901        )?;
 7902        Ok(())
 7903    }
 7904
 7905    pub fn select_previous(
 7906        &mut self,
 7907        action: &SelectPrevious,
 7908        cx: &mut ViewContext<Self>,
 7909    ) -> Result<()> {
 7910        self.push_to_selection_history();
 7911        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7912        let buffer = &display_map.buffer_snapshot;
 7913        let mut selections = self.selections.all::<usize>(cx);
 7914        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 7915            let query = &select_prev_state.query;
 7916            if !select_prev_state.done {
 7917                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7918                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7919                let mut next_selected_range = None;
 7920                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 7921                let bytes_before_last_selection =
 7922                    buffer.reversed_bytes_in_range(0..last_selection.start);
 7923                let bytes_after_first_selection =
 7924                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 7925                let query_matches = query
 7926                    .stream_find_iter(bytes_before_last_selection)
 7927                    .map(|result| (last_selection.start, result))
 7928                    .chain(
 7929                        query
 7930                            .stream_find_iter(bytes_after_first_selection)
 7931                            .map(|result| (buffer.len(), result)),
 7932                    );
 7933                for (end_offset, query_match) in query_matches {
 7934                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7935                    let offset_range =
 7936                        end_offset - query_match.end()..end_offset - query_match.start();
 7937                    let display_range = offset_range.start.to_display_point(&display_map)
 7938                        ..offset_range.end.to_display_point(&display_map);
 7939
 7940                    if !select_prev_state.wordwise
 7941                        || (!movement::is_inside_word(&display_map, display_range.start)
 7942                            && !movement::is_inside_word(&display_map, display_range.end))
 7943                    {
 7944                        next_selected_range = Some(offset_range);
 7945                        break;
 7946                    }
 7947                }
 7948
 7949                if let Some(next_selected_range) = next_selected_range {
 7950                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 7951                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7952                        if action.replace_newest {
 7953                            s.delete(s.newest_anchor().id);
 7954                        }
 7955                        s.insert_range(next_selected_range);
 7956                    });
 7957                } else {
 7958                    select_prev_state.done = true;
 7959                }
 7960            }
 7961
 7962            self.select_prev_state = Some(select_prev_state);
 7963        } else {
 7964            let mut only_carets = true;
 7965            let mut same_text_selected = true;
 7966            let mut selected_text = None;
 7967
 7968            let mut selections_iter = selections.iter().peekable();
 7969            while let Some(selection) = selections_iter.next() {
 7970                if selection.start != selection.end {
 7971                    only_carets = false;
 7972                }
 7973
 7974                if same_text_selected {
 7975                    if selected_text.is_none() {
 7976                        selected_text =
 7977                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7978                    }
 7979
 7980                    if let Some(next_selection) = selections_iter.peek() {
 7981                        if next_selection.range().len() == selection.range().len() {
 7982                            let next_selected_text = buffer
 7983                                .text_for_range(next_selection.range())
 7984                                .collect::<String>();
 7985                            if Some(next_selected_text) != selected_text {
 7986                                same_text_selected = false;
 7987                                selected_text = None;
 7988                            }
 7989                        } else {
 7990                            same_text_selected = false;
 7991                            selected_text = None;
 7992                        }
 7993                    }
 7994                }
 7995            }
 7996
 7997            if only_carets {
 7998                for selection in &mut selections {
 7999                    let word_range = movement::surrounding_word(
 8000                        &display_map,
 8001                        selection.start.to_display_point(&display_map),
 8002                    );
 8003                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8004                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8005                    selection.goal = SelectionGoal::None;
 8006                    selection.reversed = false;
 8007                }
 8008                if selections.len() == 1 {
 8009                    let selection = selections
 8010                        .last()
 8011                        .expect("ensured that there's only one selection");
 8012                    let query = buffer
 8013                        .text_for_range(selection.start..selection.end)
 8014                        .collect::<String>();
 8015                    let is_empty = query.is_empty();
 8016                    let select_state = SelectNextState {
 8017                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8018                        wordwise: true,
 8019                        done: is_empty,
 8020                    };
 8021                    self.select_prev_state = Some(select_state);
 8022                } else {
 8023                    self.select_prev_state = None;
 8024                }
 8025
 8026                self.unfold_ranges(
 8027                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8028                    false,
 8029                    true,
 8030                    cx,
 8031                );
 8032                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8033                    s.select(selections);
 8034                });
 8035            } else if let Some(selected_text) = selected_text {
 8036                self.select_prev_state = Some(SelectNextState {
 8037                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8038                    wordwise: false,
 8039                    done: false,
 8040                });
 8041                self.select_previous(action, cx)?;
 8042            }
 8043        }
 8044        Ok(())
 8045    }
 8046
 8047    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8048        let text_layout_details = &self.text_layout_details(cx);
 8049        self.transact(cx, |this, cx| {
 8050            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8051            let mut edits = Vec::new();
 8052            let mut selection_edit_ranges = Vec::new();
 8053            let mut last_toggled_row = None;
 8054            let snapshot = this.buffer.read(cx).read(cx);
 8055            let empty_str: Arc<str> = "".into();
 8056            let mut suffixes_inserted = Vec::new();
 8057
 8058            fn comment_prefix_range(
 8059                snapshot: &MultiBufferSnapshot,
 8060                row: MultiBufferRow,
 8061                comment_prefix: &str,
 8062                comment_prefix_whitespace: &str,
 8063            ) -> Range<Point> {
 8064                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8065
 8066                let mut line_bytes = snapshot
 8067                    .bytes_in_range(start..snapshot.max_point())
 8068                    .flatten()
 8069                    .copied();
 8070
 8071                // If this line currently begins with the line comment prefix, then record
 8072                // the range containing the prefix.
 8073                if line_bytes
 8074                    .by_ref()
 8075                    .take(comment_prefix.len())
 8076                    .eq(comment_prefix.bytes())
 8077                {
 8078                    // Include any whitespace that matches the comment prefix.
 8079                    let matching_whitespace_len = line_bytes
 8080                        .zip(comment_prefix_whitespace.bytes())
 8081                        .take_while(|(a, b)| a == b)
 8082                        .count() as u32;
 8083                    let end = Point::new(
 8084                        start.row,
 8085                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8086                    );
 8087                    start..end
 8088                } else {
 8089                    start..start
 8090                }
 8091            }
 8092
 8093            fn comment_suffix_range(
 8094                snapshot: &MultiBufferSnapshot,
 8095                row: MultiBufferRow,
 8096                comment_suffix: &str,
 8097                comment_suffix_has_leading_space: bool,
 8098            ) -> Range<Point> {
 8099                let end = Point::new(row.0, snapshot.line_len(row));
 8100                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8101
 8102                let mut line_end_bytes = snapshot
 8103                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8104                    .flatten()
 8105                    .copied();
 8106
 8107                let leading_space_len = if suffix_start_column > 0
 8108                    && line_end_bytes.next() == Some(b' ')
 8109                    && comment_suffix_has_leading_space
 8110                {
 8111                    1
 8112                } else {
 8113                    0
 8114                };
 8115
 8116                // If this line currently begins with the line comment prefix, then record
 8117                // the range containing the prefix.
 8118                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8119                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8120                    start..end
 8121                } else {
 8122                    end..end
 8123                }
 8124            }
 8125
 8126            // TODO: Handle selections that cross excerpts
 8127            for selection in &mut selections {
 8128                let start_column = snapshot
 8129                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8130                    .len;
 8131                let language = if let Some(language) =
 8132                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8133                {
 8134                    language
 8135                } else {
 8136                    continue;
 8137                };
 8138
 8139                selection_edit_ranges.clear();
 8140
 8141                // If multiple selections contain a given row, avoid processing that
 8142                // row more than once.
 8143                let mut start_row = MultiBufferRow(selection.start.row);
 8144                if last_toggled_row == Some(start_row) {
 8145                    start_row = start_row.next_row();
 8146                }
 8147                let end_row =
 8148                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8149                        MultiBufferRow(selection.end.row - 1)
 8150                    } else {
 8151                        MultiBufferRow(selection.end.row)
 8152                    };
 8153                last_toggled_row = Some(end_row);
 8154
 8155                if start_row > end_row {
 8156                    continue;
 8157                }
 8158
 8159                // If the language has line comments, toggle those.
 8160                let full_comment_prefixes = language.line_comment_prefixes();
 8161                if !full_comment_prefixes.is_empty() {
 8162                    let first_prefix = full_comment_prefixes
 8163                        .first()
 8164                        .expect("prefixes is non-empty");
 8165                    let prefix_trimmed_lengths = full_comment_prefixes
 8166                        .iter()
 8167                        .map(|p| p.trim_end_matches(' ').len())
 8168                        .collect::<SmallVec<[usize; 4]>>();
 8169
 8170                    let mut all_selection_lines_are_comments = true;
 8171
 8172                    for row in start_row.0..=end_row.0 {
 8173                        let row = MultiBufferRow(row);
 8174                        if start_row < end_row && snapshot.is_line_blank(row) {
 8175                            continue;
 8176                        }
 8177
 8178                        let prefix_range = full_comment_prefixes
 8179                            .iter()
 8180                            .zip(prefix_trimmed_lengths.iter().copied())
 8181                            .map(|(prefix, trimmed_prefix_len)| {
 8182                                comment_prefix_range(
 8183                                    snapshot.deref(),
 8184                                    row,
 8185                                    &prefix[..trimmed_prefix_len],
 8186                                    &prefix[trimmed_prefix_len..],
 8187                                )
 8188                            })
 8189                            .max_by_key(|range| range.end.column - range.start.column)
 8190                            .expect("prefixes is non-empty");
 8191
 8192                        if prefix_range.is_empty() {
 8193                            all_selection_lines_are_comments = false;
 8194                        }
 8195
 8196                        selection_edit_ranges.push(prefix_range);
 8197                    }
 8198
 8199                    if all_selection_lines_are_comments {
 8200                        edits.extend(
 8201                            selection_edit_ranges
 8202                                .iter()
 8203                                .cloned()
 8204                                .map(|range| (range, empty_str.clone())),
 8205                        );
 8206                    } else {
 8207                        let min_column = selection_edit_ranges
 8208                            .iter()
 8209                            .map(|range| range.start.column)
 8210                            .min()
 8211                            .unwrap_or(0);
 8212                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8213                            let position = Point::new(range.start.row, min_column);
 8214                            (position..position, first_prefix.clone())
 8215                        }));
 8216                    }
 8217                } else if let Some((full_comment_prefix, comment_suffix)) =
 8218                    language.block_comment_delimiters()
 8219                {
 8220                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8221                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8222                    let prefix_range = comment_prefix_range(
 8223                        snapshot.deref(),
 8224                        start_row,
 8225                        comment_prefix,
 8226                        comment_prefix_whitespace,
 8227                    );
 8228                    let suffix_range = comment_suffix_range(
 8229                        snapshot.deref(),
 8230                        end_row,
 8231                        comment_suffix.trim_start_matches(' '),
 8232                        comment_suffix.starts_with(' '),
 8233                    );
 8234
 8235                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8236                        edits.push((
 8237                            prefix_range.start..prefix_range.start,
 8238                            full_comment_prefix.clone(),
 8239                        ));
 8240                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8241                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8242                    } else {
 8243                        edits.push((prefix_range, empty_str.clone()));
 8244                        edits.push((suffix_range, empty_str.clone()));
 8245                    }
 8246                } else {
 8247                    continue;
 8248                }
 8249            }
 8250
 8251            drop(snapshot);
 8252            this.buffer.update(cx, |buffer, cx| {
 8253                buffer.edit(edits, None, cx);
 8254            });
 8255
 8256            // Adjust selections so that they end before any comment suffixes that
 8257            // were inserted.
 8258            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8259            let mut selections = this.selections.all::<Point>(cx);
 8260            let snapshot = this.buffer.read(cx).read(cx);
 8261            for selection in &mut selections {
 8262                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8263                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8264                        Ordering::Less => {
 8265                            suffixes_inserted.next();
 8266                            continue;
 8267                        }
 8268                        Ordering::Greater => break,
 8269                        Ordering::Equal => {
 8270                            if selection.end.column == snapshot.line_len(row) {
 8271                                if selection.is_empty() {
 8272                                    selection.start.column -= suffix_len as u32;
 8273                                }
 8274                                selection.end.column -= suffix_len as u32;
 8275                            }
 8276                            break;
 8277                        }
 8278                    }
 8279                }
 8280            }
 8281
 8282            drop(snapshot);
 8283            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8284
 8285            let selections = this.selections.all::<Point>(cx);
 8286            let selections_on_single_row = selections.windows(2).all(|selections| {
 8287                selections[0].start.row == selections[1].start.row
 8288                    && selections[0].end.row == selections[1].end.row
 8289                    && selections[0].start.row == selections[0].end.row
 8290            });
 8291            let selections_selecting = selections
 8292                .iter()
 8293                .any(|selection| selection.start != selection.end);
 8294            let advance_downwards = action.advance_downwards
 8295                && selections_on_single_row
 8296                && !selections_selecting
 8297                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8298
 8299            if advance_downwards {
 8300                let snapshot = this.buffer.read(cx).snapshot(cx);
 8301
 8302                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8303                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8304                        let mut point = display_point.to_point(display_snapshot);
 8305                        point.row += 1;
 8306                        point = snapshot.clip_point(point, Bias::Left);
 8307                        let display_point = point.to_display_point(display_snapshot);
 8308                        let goal = SelectionGoal::HorizontalPosition(
 8309                            display_snapshot
 8310                                .x_for_display_point(display_point, &text_layout_details)
 8311                                .into(),
 8312                        );
 8313                        (display_point, goal)
 8314                    })
 8315                });
 8316            }
 8317        });
 8318    }
 8319
 8320    pub fn select_enclosing_symbol(
 8321        &mut self,
 8322        _: &SelectEnclosingSymbol,
 8323        cx: &mut ViewContext<Self>,
 8324    ) {
 8325        let buffer = self.buffer.read(cx).snapshot(cx);
 8326        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8327
 8328        fn update_selection(
 8329            selection: &Selection<usize>,
 8330            buffer_snap: &MultiBufferSnapshot,
 8331        ) -> Option<Selection<usize>> {
 8332            let cursor = selection.head();
 8333            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8334            for symbol in symbols.iter().rev() {
 8335                let start = symbol.range.start.to_offset(&buffer_snap);
 8336                let end = symbol.range.end.to_offset(&buffer_snap);
 8337                let new_range = start..end;
 8338                if start < selection.start || end > selection.end {
 8339                    return Some(Selection {
 8340                        id: selection.id,
 8341                        start: new_range.start,
 8342                        end: new_range.end,
 8343                        goal: SelectionGoal::None,
 8344                        reversed: selection.reversed,
 8345                    });
 8346                }
 8347            }
 8348            None
 8349        }
 8350
 8351        let mut selected_larger_symbol = false;
 8352        let new_selections = old_selections
 8353            .iter()
 8354            .map(|selection| match update_selection(selection, &buffer) {
 8355                Some(new_selection) => {
 8356                    if new_selection.range() != selection.range() {
 8357                        selected_larger_symbol = true;
 8358                    }
 8359                    new_selection
 8360                }
 8361                None => selection.clone(),
 8362            })
 8363            .collect::<Vec<_>>();
 8364
 8365        if selected_larger_symbol {
 8366            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8367                s.select(new_selections);
 8368            });
 8369        }
 8370    }
 8371
 8372    pub fn select_larger_syntax_node(
 8373        &mut self,
 8374        _: &SelectLargerSyntaxNode,
 8375        cx: &mut ViewContext<Self>,
 8376    ) {
 8377        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8378        let buffer = self.buffer.read(cx).snapshot(cx);
 8379        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8380
 8381        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8382        let mut selected_larger_node = false;
 8383        let new_selections = old_selections
 8384            .iter()
 8385            .map(|selection| {
 8386                let old_range = selection.start..selection.end;
 8387                let mut new_range = old_range.clone();
 8388                while let Some(containing_range) =
 8389                    buffer.range_for_syntax_ancestor(new_range.clone())
 8390                {
 8391                    new_range = containing_range;
 8392                    if !display_map.intersects_fold(new_range.start)
 8393                        && !display_map.intersects_fold(new_range.end)
 8394                    {
 8395                        break;
 8396                    }
 8397                }
 8398
 8399                selected_larger_node |= new_range != old_range;
 8400                Selection {
 8401                    id: selection.id,
 8402                    start: new_range.start,
 8403                    end: new_range.end,
 8404                    goal: SelectionGoal::None,
 8405                    reversed: selection.reversed,
 8406                }
 8407            })
 8408            .collect::<Vec<_>>();
 8409
 8410        if selected_larger_node {
 8411            stack.push(old_selections);
 8412            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8413                s.select(new_selections);
 8414            });
 8415        }
 8416        self.select_larger_syntax_node_stack = stack;
 8417    }
 8418
 8419    pub fn select_smaller_syntax_node(
 8420        &mut self,
 8421        _: &SelectSmallerSyntaxNode,
 8422        cx: &mut ViewContext<Self>,
 8423    ) {
 8424        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8425        if let Some(selections) = stack.pop() {
 8426            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8427                s.select(selections.to_vec());
 8428            });
 8429        }
 8430        self.select_larger_syntax_node_stack = stack;
 8431    }
 8432
 8433    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8434        if !EditorSettings::get_global(cx).gutter.runnables {
 8435            self.clear_tasks();
 8436            return Task::ready(());
 8437        }
 8438        let project = self.project.clone();
 8439        cx.spawn(|this, mut cx| async move {
 8440            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8441                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8442            }) else {
 8443                return;
 8444            };
 8445
 8446            let Some(project) = project else {
 8447                return;
 8448            };
 8449
 8450            let hide_runnables = project
 8451                .update(&mut cx, |project, cx| {
 8452                    // Do not display any test indicators in non-dev server remote projects.
 8453                    project.is_remote() && project.ssh_connection_string(cx).is_none()
 8454                })
 8455                .unwrap_or(true);
 8456            if hide_runnables {
 8457                return;
 8458            }
 8459            let new_rows =
 8460                cx.background_executor()
 8461                    .spawn({
 8462                        let snapshot = display_snapshot.clone();
 8463                        async move {
 8464                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8465                        }
 8466                    })
 8467                    .await;
 8468            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8469
 8470            this.update(&mut cx, |this, _| {
 8471                this.clear_tasks();
 8472                for (key, value) in rows {
 8473                    this.insert_tasks(key, value);
 8474                }
 8475            })
 8476            .ok();
 8477        })
 8478    }
 8479    fn fetch_runnable_ranges(
 8480        snapshot: &DisplaySnapshot,
 8481        range: Range<Anchor>,
 8482    ) -> Vec<language::RunnableRange> {
 8483        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8484    }
 8485
 8486    fn runnable_rows(
 8487        project: Model<Project>,
 8488        snapshot: DisplaySnapshot,
 8489        runnable_ranges: Vec<RunnableRange>,
 8490        mut cx: AsyncWindowContext,
 8491    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8492        runnable_ranges
 8493            .into_iter()
 8494            .filter_map(|mut runnable| {
 8495                let tasks = cx
 8496                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8497                    .ok()?;
 8498                if tasks.is_empty() {
 8499                    return None;
 8500                }
 8501
 8502                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8503
 8504                let row = snapshot
 8505                    .buffer_snapshot
 8506                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8507                    .1
 8508                    .start
 8509                    .row;
 8510
 8511                let context_range =
 8512                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8513                Some((
 8514                    (runnable.buffer_id, row),
 8515                    RunnableTasks {
 8516                        templates: tasks,
 8517                        offset: MultiBufferOffset(runnable.run_range.start),
 8518                        context_range,
 8519                        column: point.column,
 8520                        extra_variables: runnable.extra_captures,
 8521                    },
 8522                ))
 8523            })
 8524            .collect()
 8525    }
 8526
 8527    fn templates_with_tags(
 8528        project: &Model<Project>,
 8529        runnable: &mut Runnable,
 8530        cx: &WindowContext<'_>,
 8531    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8532        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8533            let (worktree_id, file) = project
 8534                .buffer_for_id(runnable.buffer, cx)
 8535                .and_then(|buffer| buffer.read(cx).file())
 8536                .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
 8537                .unzip();
 8538
 8539            (project.task_inventory().clone(), worktree_id, file)
 8540        });
 8541
 8542        let inventory = inventory.read(cx);
 8543        let tags = mem::take(&mut runnable.tags);
 8544        let mut tags: Vec<_> = tags
 8545            .into_iter()
 8546            .flat_map(|tag| {
 8547                let tag = tag.0.clone();
 8548                inventory
 8549                    .list_tasks(
 8550                        file.clone(),
 8551                        Some(runnable.language.clone()),
 8552                        worktree_id,
 8553                        cx,
 8554                    )
 8555                    .into_iter()
 8556                    .filter(move |(_, template)| {
 8557                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8558                    })
 8559            })
 8560            .sorted_by_key(|(kind, _)| kind.to_owned())
 8561            .collect();
 8562        if let Some((leading_tag_source, _)) = tags.first() {
 8563            // Strongest source wins; if we have worktree tag binding, prefer that to
 8564            // global and language bindings;
 8565            // if we have a global binding, prefer that to language binding.
 8566            let first_mismatch = tags
 8567                .iter()
 8568                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8569            if let Some(index) = first_mismatch {
 8570                tags.truncate(index);
 8571            }
 8572        }
 8573
 8574        tags
 8575    }
 8576
 8577    pub fn move_to_enclosing_bracket(
 8578        &mut self,
 8579        _: &MoveToEnclosingBracket,
 8580        cx: &mut ViewContext<Self>,
 8581    ) {
 8582        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8583            s.move_offsets_with(|snapshot, selection| {
 8584                let Some(enclosing_bracket_ranges) =
 8585                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8586                else {
 8587                    return;
 8588                };
 8589
 8590                let mut best_length = usize::MAX;
 8591                let mut best_inside = false;
 8592                let mut best_in_bracket_range = false;
 8593                let mut best_destination = None;
 8594                for (open, close) in enclosing_bracket_ranges {
 8595                    let close = close.to_inclusive();
 8596                    let length = close.end() - open.start;
 8597                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8598                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8599                        || close.contains(&selection.head());
 8600
 8601                    // If best is next to a bracket and current isn't, skip
 8602                    if !in_bracket_range && best_in_bracket_range {
 8603                        continue;
 8604                    }
 8605
 8606                    // Prefer smaller lengths unless best is inside and current isn't
 8607                    if length > best_length && (best_inside || !inside) {
 8608                        continue;
 8609                    }
 8610
 8611                    best_length = length;
 8612                    best_inside = inside;
 8613                    best_in_bracket_range = in_bracket_range;
 8614                    best_destination = Some(
 8615                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8616                            if inside {
 8617                                open.end
 8618                            } else {
 8619                                open.start
 8620                            }
 8621                        } else {
 8622                            if inside {
 8623                                *close.start()
 8624                            } else {
 8625                                *close.end()
 8626                            }
 8627                        },
 8628                    );
 8629                }
 8630
 8631                if let Some(destination) = best_destination {
 8632                    selection.collapse_to(destination, SelectionGoal::None);
 8633                }
 8634            })
 8635        });
 8636    }
 8637
 8638    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 8639        self.end_selection(cx);
 8640        self.selection_history.mode = SelectionHistoryMode::Undoing;
 8641        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 8642            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8643            self.select_next_state = entry.select_next_state;
 8644            self.select_prev_state = entry.select_prev_state;
 8645            self.add_selections_state = entry.add_selections_state;
 8646            self.request_autoscroll(Autoscroll::newest(), cx);
 8647        }
 8648        self.selection_history.mode = SelectionHistoryMode::Normal;
 8649    }
 8650
 8651    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 8652        self.end_selection(cx);
 8653        self.selection_history.mode = SelectionHistoryMode::Redoing;
 8654        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 8655            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8656            self.select_next_state = entry.select_next_state;
 8657            self.select_prev_state = entry.select_prev_state;
 8658            self.add_selections_state = entry.add_selections_state;
 8659            self.request_autoscroll(Autoscroll::newest(), cx);
 8660        }
 8661        self.selection_history.mode = SelectionHistoryMode::Normal;
 8662    }
 8663
 8664    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 8665        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 8666    }
 8667
 8668    pub fn expand_excerpts_down(
 8669        &mut self,
 8670        action: &ExpandExcerptsDown,
 8671        cx: &mut ViewContext<Self>,
 8672    ) {
 8673        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 8674    }
 8675
 8676    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 8677        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 8678    }
 8679
 8680    pub fn expand_excerpts_for_direction(
 8681        &mut self,
 8682        lines: u32,
 8683        direction: ExpandExcerptDirection,
 8684        cx: &mut ViewContext<Self>,
 8685    ) {
 8686        let selections = self.selections.disjoint_anchors();
 8687
 8688        let lines = if lines == 0 {
 8689            EditorSettings::get_global(cx).expand_excerpt_lines
 8690        } else {
 8691            lines
 8692        };
 8693
 8694        self.buffer.update(cx, |buffer, cx| {
 8695            buffer.expand_excerpts(
 8696                selections
 8697                    .into_iter()
 8698                    .map(|selection| selection.head().excerpt_id)
 8699                    .dedup(),
 8700                lines,
 8701                direction,
 8702                cx,
 8703            )
 8704        })
 8705    }
 8706
 8707    pub fn expand_excerpt(
 8708        &mut self,
 8709        excerpt: ExcerptId,
 8710        direction: ExpandExcerptDirection,
 8711        cx: &mut ViewContext<Self>,
 8712    ) {
 8713        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 8714        self.buffer.update(cx, |buffer, cx| {
 8715            buffer.expand_excerpts([excerpt], lines, direction, cx)
 8716        })
 8717    }
 8718
 8719    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8720        self.go_to_diagnostic_impl(Direction::Next, cx)
 8721    }
 8722
 8723    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8724        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8725    }
 8726
 8727    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8728        let buffer = self.buffer.read(cx).snapshot(cx);
 8729        let selection = self.selections.newest::<usize>(cx);
 8730
 8731        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8732        if direction == Direction::Next {
 8733            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8734                let (group_id, jump_to) = popover.activation_info();
 8735                if self.activate_diagnostics(group_id, cx) {
 8736                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8737                        let mut new_selection = s.newest_anchor().clone();
 8738                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 8739                        s.select_anchors(vec![new_selection.clone()]);
 8740                    });
 8741                }
 8742                return;
 8743            }
 8744        }
 8745
 8746        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 8747            active_diagnostics
 8748                .primary_range
 8749                .to_offset(&buffer)
 8750                .to_inclusive()
 8751        });
 8752        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 8753            if active_primary_range.contains(&selection.head()) {
 8754                *active_primary_range.start()
 8755            } else {
 8756                selection.head()
 8757            }
 8758        } else {
 8759            selection.head()
 8760        };
 8761        let snapshot = self.snapshot(cx);
 8762        loop {
 8763            let diagnostics = if direction == Direction::Prev {
 8764                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 8765            } else {
 8766                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 8767            }
 8768            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 8769            let group = diagnostics
 8770                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 8771                // be sorted in a stable way
 8772                // skip until we are at current active diagnostic, if it exists
 8773                .skip_while(|entry| {
 8774                    (match direction {
 8775                        Direction::Prev => entry.range.start >= search_start,
 8776                        Direction::Next => entry.range.start <= search_start,
 8777                    }) && self
 8778                        .active_diagnostics
 8779                        .as_ref()
 8780                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 8781                })
 8782                .find_map(|entry| {
 8783                    if entry.diagnostic.is_primary
 8784                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 8785                        && !entry.range.is_empty()
 8786                        // if we match with the active diagnostic, skip it
 8787                        && Some(entry.diagnostic.group_id)
 8788                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 8789                    {
 8790                        Some((entry.range, entry.diagnostic.group_id))
 8791                    } else {
 8792                        None
 8793                    }
 8794                });
 8795
 8796            if let Some((primary_range, group_id)) = group {
 8797                if self.activate_diagnostics(group_id, cx) {
 8798                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8799                        s.select(vec![Selection {
 8800                            id: selection.id,
 8801                            start: primary_range.start,
 8802                            end: primary_range.start,
 8803                            reversed: false,
 8804                            goal: SelectionGoal::None,
 8805                        }]);
 8806                    });
 8807                }
 8808                break;
 8809            } else {
 8810                // Cycle around to the start of the buffer, potentially moving back to the start of
 8811                // the currently active diagnostic.
 8812                active_primary_range.take();
 8813                if direction == Direction::Prev {
 8814                    if search_start == buffer.len() {
 8815                        break;
 8816                    } else {
 8817                        search_start = buffer.len();
 8818                    }
 8819                } else if search_start == 0 {
 8820                    break;
 8821                } else {
 8822                    search_start = 0;
 8823                }
 8824            }
 8825        }
 8826    }
 8827
 8828    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 8829        let snapshot = self
 8830            .display_map
 8831            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8832        let selection = self.selections.newest::<Point>(cx);
 8833
 8834        if !self.seek_in_direction(
 8835            &snapshot,
 8836            selection.head(),
 8837            false,
 8838            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8839                MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
 8840            ),
 8841            cx,
 8842        ) {
 8843            let wrapped_point = Point::zero();
 8844            self.seek_in_direction(
 8845                &snapshot,
 8846                wrapped_point,
 8847                true,
 8848                snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8849                    MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 8850                ),
 8851                cx,
 8852            );
 8853        }
 8854    }
 8855
 8856    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 8857        let snapshot = self
 8858            .display_map
 8859            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8860        let selection = self.selections.newest::<Point>(cx);
 8861
 8862        if !self.seek_in_direction(
 8863            &snapshot,
 8864            selection.head(),
 8865            false,
 8866            snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8867                MultiBufferRow(0)..MultiBufferRow(selection.head().row),
 8868            ),
 8869            cx,
 8870        ) {
 8871            let wrapped_point = snapshot.buffer_snapshot.max_point();
 8872            self.seek_in_direction(
 8873                &snapshot,
 8874                wrapped_point,
 8875                true,
 8876                snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8877                    MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
 8878                ),
 8879                cx,
 8880            );
 8881        }
 8882    }
 8883
 8884    fn seek_in_direction(
 8885        &mut self,
 8886        snapshot: &DisplaySnapshot,
 8887        initial_point: Point,
 8888        is_wrapped: bool,
 8889        hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
 8890        cx: &mut ViewContext<Editor>,
 8891    ) -> bool {
 8892        let display_point = initial_point.to_display_point(snapshot);
 8893        let mut hunks = hunks
 8894            .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
 8895            .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
 8896            .dedup();
 8897
 8898        if let Some(hunk) = hunks.next() {
 8899            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8900                let row = hunk.start_display_row();
 8901                let point = DisplayPoint::new(row, 0);
 8902                s.select_display_ranges([point..point]);
 8903            });
 8904
 8905            true
 8906        } else {
 8907            false
 8908        }
 8909    }
 8910
 8911    pub fn go_to_definition(
 8912        &mut self,
 8913        _: &GoToDefinition,
 8914        cx: &mut ViewContext<Self>,
 8915    ) -> Task<Result<bool>> {
 8916        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
 8917    }
 8918
 8919    pub fn go_to_implementation(
 8920        &mut self,
 8921        _: &GoToImplementation,
 8922        cx: &mut ViewContext<Self>,
 8923    ) -> Task<Result<bool>> {
 8924        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 8925    }
 8926
 8927    pub fn go_to_implementation_split(
 8928        &mut self,
 8929        _: &GoToImplementationSplit,
 8930        cx: &mut ViewContext<Self>,
 8931    ) -> Task<Result<bool>> {
 8932        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 8933    }
 8934
 8935    pub fn go_to_type_definition(
 8936        &mut self,
 8937        _: &GoToTypeDefinition,
 8938        cx: &mut ViewContext<Self>,
 8939    ) -> Task<Result<bool>> {
 8940        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 8941    }
 8942
 8943    pub fn go_to_definition_split(
 8944        &mut self,
 8945        _: &GoToDefinitionSplit,
 8946        cx: &mut ViewContext<Self>,
 8947    ) -> Task<Result<bool>> {
 8948        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 8949    }
 8950
 8951    pub fn go_to_type_definition_split(
 8952        &mut self,
 8953        _: &GoToTypeDefinitionSplit,
 8954        cx: &mut ViewContext<Self>,
 8955    ) -> Task<Result<bool>> {
 8956        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 8957    }
 8958
 8959    fn go_to_definition_of_kind(
 8960        &mut self,
 8961        kind: GotoDefinitionKind,
 8962        split: bool,
 8963        cx: &mut ViewContext<Self>,
 8964    ) -> Task<Result<bool>> {
 8965        let Some(workspace) = self.workspace() else {
 8966            return Task::ready(Ok(false));
 8967        };
 8968        let buffer = self.buffer.read(cx);
 8969        let head = self.selections.newest::<usize>(cx).head();
 8970        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 8971            text_anchor
 8972        } else {
 8973            return Task::ready(Ok(false));
 8974        };
 8975
 8976        let project = workspace.read(cx).project().clone();
 8977        let definitions = project.update(cx, |project, cx| match kind {
 8978            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 8979            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 8980            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 8981        });
 8982
 8983        cx.spawn(|editor, mut cx| async move {
 8984            let definitions = definitions.await?;
 8985            let navigated = editor
 8986                .update(&mut cx, |editor, cx| {
 8987                    editor.navigate_to_hover_links(
 8988                        Some(kind),
 8989                        definitions
 8990                            .into_iter()
 8991                            .filter(|location| {
 8992                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 8993                            })
 8994                            .map(HoverLink::Text)
 8995                            .collect::<Vec<_>>(),
 8996                        split,
 8997                        cx,
 8998                    )
 8999                })?
 9000                .await?;
 9001            anyhow::Ok(navigated)
 9002        })
 9003    }
 9004
 9005    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9006        let position = self.selections.newest_anchor().head();
 9007        let Some((buffer, buffer_position)) =
 9008            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9009        else {
 9010            return;
 9011        };
 9012
 9013        cx.spawn(|editor, mut cx| async move {
 9014            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9015                editor.update(&mut cx, |_, cx| {
 9016                    cx.open_url(&url);
 9017                })
 9018            } else {
 9019                Ok(())
 9020            }
 9021        })
 9022        .detach();
 9023    }
 9024
 9025    pub(crate) fn navigate_to_hover_links(
 9026        &mut self,
 9027        kind: Option<GotoDefinitionKind>,
 9028        mut definitions: Vec<HoverLink>,
 9029        split: bool,
 9030        cx: &mut ViewContext<Editor>,
 9031    ) -> Task<Result<bool>> {
 9032        // If there is one definition, just open it directly
 9033        if definitions.len() == 1 {
 9034            let definition = definitions.pop().unwrap();
 9035            let target_task = match definition {
 9036                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9037                HoverLink::InlayHint(lsp_location, server_id) => {
 9038                    self.compute_target_location(lsp_location, server_id, cx)
 9039                }
 9040                HoverLink::Url(url) => {
 9041                    cx.open_url(&url);
 9042                    Task::ready(Ok(None))
 9043                }
 9044            };
 9045            cx.spawn(|editor, mut cx| async move {
 9046                let target = target_task.await.context("target resolution task")?;
 9047                if let Some(target) = target {
 9048                    editor.update(&mut cx, |editor, cx| {
 9049                        let Some(workspace) = editor.workspace() else {
 9050                            return false;
 9051                        };
 9052                        let pane = workspace.read(cx).active_pane().clone();
 9053
 9054                        let range = target.range.to_offset(target.buffer.read(cx));
 9055                        let range = editor.range_for_match(&range);
 9056
 9057                        /// If select range has more than one line, we
 9058                        /// just point the cursor to range.start.
 9059                        fn check_multiline_range(
 9060                            buffer: &Buffer,
 9061                            range: Range<usize>,
 9062                        ) -> Range<usize> {
 9063                            if buffer.offset_to_point(range.start).row
 9064                                == buffer.offset_to_point(range.end).row
 9065                            {
 9066                                range
 9067                            } else {
 9068                                range.start..range.start
 9069                            }
 9070                        }
 9071
 9072                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9073                            let buffer = target.buffer.read(cx);
 9074                            let range = check_multiline_range(buffer, range);
 9075                            editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 9076                                s.select_ranges([range]);
 9077                            });
 9078                        } else {
 9079                            cx.window_context().defer(move |cx| {
 9080                                let target_editor: View<Self> =
 9081                                    workspace.update(cx, |workspace, cx| {
 9082                                        let pane = if split {
 9083                                            workspace.adjacent_pane(cx)
 9084                                        } else {
 9085                                            workspace.active_pane().clone()
 9086                                        };
 9087
 9088                                        workspace.open_project_item(pane, target.buffer.clone(), cx)
 9089                                    });
 9090                                target_editor.update(cx, |target_editor, cx| {
 9091                                    // When selecting a definition in a different buffer, disable the nav history
 9092                                    // to avoid creating a history entry at the previous cursor location.
 9093                                    pane.update(cx, |pane, _| pane.disable_history());
 9094                                    let buffer = target.buffer.read(cx);
 9095                                    let range = check_multiline_range(buffer, range);
 9096                                    target_editor.change_selections(
 9097                                        Some(Autoscroll::focused()),
 9098                                        cx,
 9099                                        |s| {
 9100                                            s.select_ranges([range]);
 9101                                        },
 9102                                    );
 9103                                    pane.update(cx, |pane, _| pane.enable_history());
 9104                                });
 9105                            });
 9106                        }
 9107                        true
 9108                    })
 9109                } else {
 9110                    Ok(false)
 9111                }
 9112            })
 9113        } else if !definitions.is_empty() {
 9114            let replica_id = self.replica_id(cx);
 9115            cx.spawn(|editor, mut cx| async move {
 9116                let (title, location_tasks, workspace) = editor
 9117                    .update(&mut cx, |editor, cx| {
 9118                        let tab_kind = match kind {
 9119                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9120                            _ => "Definitions",
 9121                        };
 9122                        let title = definitions
 9123                            .iter()
 9124                            .find_map(|definition| match definition {
 9125                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9126                                    let buffer = origin.buffer.read(cx);
 9127                                    format!(
 9128                                        "{} for {}",
 9129                                        tab_kind,
 9130                                        buffer
 9131                                            .text_for_range(origin.range.clone())
 9132                                            .collect::<String>()
 9133                                    )
 9134                                }),
 9135                                HoverLink::InlayHint(_, _) => None,
 9136                                HoverLink::Url(_) => None,
 9137                            })
 9138                            .unwrap_or(tab_kind.to_string());
 9139                        let location_tasks = definitions
 9140                            .into_iter()
 9141                            .map(|definition| match definition {
 9142                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9143                                HoverLink::InlayHint(lsp_location, server_id) => {
 9144                                    editor.compute_target_location(lsp_location, server_id, cx)
 9145                                }
 9146                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9147                            })
 9148                            .collect::<Vec<_>>();
 9149                        (title, location_tasks, editor.workspace().clone())
 9150                    })
 9151                    .context("location tasks preparation")?;
 9152
 9153                let locations = futures::future::join_all(location_tasks)
 9154                    .await
 9155                    .into_iter()
 9156                    .filter_map(|location| location.transpose())
 9157                    .collect::<Result<_>>()
 9158                    .context("location tasks")?;
 9159
 9160                let Some(workspace) = workspace else {
 9161                    return Ok(false);
 9162                };
 9163                let opened = workspace
 9164                    .update(&mut cx, |workspace, cx| {
 9165                        Self::open_locations_in_multibuffer(
 9166                            workspace, locations, replica_id, title, split, cx,
 9167                        )
 9168                    })
 9169                    .ok();
 9170
 9171                anyhow::Ok(opened.is_some())
 9172            })
 9173        } else {
 9174            Task::ready(Ok(false))
 9175        }
 9176    }
 9177
 9178    fn compute_target_location(
 9179        &self,
 9180        lsp_location: lsp::Location,
 9181        server_id: LanguageServerId,
 9182        cx: &mut ViewContext<Editor>,
 9183    ) -> Task<anyhow::Result<Option<Location>>> {
 9184        let Some(project) = self.project.clone() else {
 9185            return Task::Ready(Some(Ok(None)));
 9186        };
 9187
 9188        cx.spawn(move |editor, mut cx| async move {
 9189            let location_task = editor.update(&mut cx, |editor, cx| {
 9190                project.update(cx, |project, cx| {
 9191                    let language_server_name =
 9192                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 9193                            project
 9194                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 9195                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 9196                        });
 9197                    language_server_name.map(|language_server_name| {
 9198                        project.open_local_buffer_via_lsp(
 9199                            lsp_location.uri.clone(),
 9200                            server_id,
 9201                            language_server_name,
 9202                            cx,
 9203                        )
 9204                    })
 9205                })
 9206            })?;
 9207            let location = match location_task {
 9208                Some(task) => Some({
 9209                    let target_buffer_handle = task.await.context("open local buffer")?;
 9210                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9211                        let target_start = target_buffer
 9212                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9213                        let target_end = target_buffer
 9214                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9215                        target_buffer.anchor_after(target_start)
 9216                            ..target_buffer.anchor_before(target_end)
 9217                    })?;
 9218                    Location {
 9219                        buffer: target_buffer_handle,
 9220                        range,
 9221                    }
 9222                }),
 9223                None => None,
 9224            };
 9225            Ok(location)
 9226        })
 9227    }
 9228
 9229    pub fn find_all_references(
 9230        &mut self,
 9231        _: &FindAllReferences,
 9232        cx: &mut ViewContext<Self>,
 9233    ) -> Option<Task<Result<()>>> {
 9234        let multi_buffer = self.buffer.read(cx);
 9235        let selection = self.selections.newest::<usize>(cx);
 9236        let head = selection.head();
 9237
 9238        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9239        let head_anchor = multi_buffer_snapshot.anchor_at(
 9240            head,
 9241            if head < selection.tail() {
 9242                Bias::Right
 9243            } else {
 9244                Bias::Left
 9245            },
 9246        );
 9247
 9248        match self
 9249            .find_all_references_task_sources
 9250            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9251        {
 9252            Ok(_) => {
 9253                log::info!(
 9254                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9255                );
 9256                return None;
 9257            }
 9258            Err(i) => {
 9259                self.find_all_references_task_sources.insert(i, head_anchor);
 9260            }
 9261        }
 9262
 9263        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9264        let replica_id = self.replica_id(cx);
 9265        let workspace = self.workspace()?;
 9266        let project = workspace.read(cx).project().clone();
 9267        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9268        Some(cx.spawn(|editor, mut cx| async move {
 9269            let _cleanup = defer({
 9270                let mut cx = cx.clone();
 9271                move || {
 9272                    let _ = editor.update(&mut cx, |editor, _| {
 9273                        if let Ok(i) =
 9274                            editor
 9275                                .find_all_references_task_sources
 9276                                .binary_search_by(|anchor| {
 9277                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9278                                })
 9279                        {
 9280                            editor.find_all_references_task_sources.remove(i);
 9281                        }
 9282                    });
 9283                }
 9284            });
 9285
 9286            let locations = references.await?;
 9287            if locations.is_empty() {
 9288                return anyhow::Ok(());
 9289            }
 9290
 9291            workspace.update(&mut cx, |workspace, cx| {
 9292                let title = locations
 9293                    .first()
 9294                    .as_ref()
 9295                    .map(|location| {
 9296                        let buffer = location.buffer.read(cx);
 9297                        format!(
 9298                            "References to `{}`",
 9299                            buffer
 9300                                .text_for_range(location.range.clone())
 9301                                .collect::<String>()
 9302                        )
 9303                    })
 9304                    .unwrap();
 9305                Self::open_locations_in_multibuffer(
 9306                    workspace, locations, replica_id, title, false, cx,
 9307                );
 9308            })
 9309        }))
 9310    }
 9311
 9312    /// Opens a multibuffer with the given project locations in it
 9313    pub fn open_locations_in_multibuffer(
 9314        workspace: &mut Workspace,
 9315        mut locations: Vec<Location>,
 9316        replica_id: ReplicaId,
 9317        title: String,
 9318        split: bool,
 9319        cx: &mut ViewContext<Workspace>,
 9320    ) {
 9321        // If there are multiple definitions, open them in a multibuffer
 9322        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9323        let mut locations = locations.into_iter().peekable();
 9324        let mut ranges_to_highlight = Vec::new();
 9325        let capability = workspace.project().read(cx).capability();
 9326
 9327        let excerpt_buffer = cx.new_model(|cx| {
 9328            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 9329            while let Some(location) = locations.next() {
 9330                let buffer = location.buffer.read(cx);
 9331                let mut ranges_for_buffer = Vec::new();
 9332                let range = location.range.to_offset(buffer);
 9333                ranges_for_buffer.push(range.clone());
 9334
 9335                while let Some(next_location) = locations.peek() {
 9336                    if next_location.buffer == location.buffer {
 9337                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9338                        locations.next();
 9339                    } else {
 9340                        break;
 9341                    }
 9342                }
 9343
 9344                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9345                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9346                    location.buffer.clone(),
 9347                    ranges_for_buffer,
 9348                    DEFAULT_MULTIBUFFER_CONTEXT,
 9349                    cx,
 9350                ))
 9351            }
 9352
 9353            multibuffer.with_title(title)
 9354        });
 9355
 9356        let editor = cx.new_view(|cx| {
 9357            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9358        });
 9359        editor.update(cx, |editor, cx| {
 9360            if let Some(first_range) = ranges_to_highlight.first() {
 9361                editor.change_selections(None, cx, |selections| {
 9362                    selections.clear_disjoint();
 9363                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9364                });
 9365            }
 9366            editor.highlight_background::<Self>(
 9367                &ranges_to_highlight,
 9368                |theme| theme.editor_highlighted_line_background,
 9369                cx,
 9370            );
 9371        });
 9372
 9373        let item = Box::new(editor);
 9374        let item_id = item.item_id();
 9375
 9376        if split {
 9377            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9378        } else {
 9379            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9380                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9381                    pane.close_current_preview_item(cx)
 9382                } else {
 9383                    None
 9384                }
 9385            });
 9386            workspace.add_item_to_active_pane(item.clone(), destination_index, cx);
 9387        }
 9388        workspace.active_pane().update(cx, |pane, cx| {
 9389            pane.set_preview_item_id(Some(item_id), cx);
 9390        });
 9391    }
 9392
 9393    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9394        use language::ToOffset as _;
 9395
 9396        let project = self.project.clone()?;
 9397        let selection = self.selections.newest_anchor().clone();
 9398        let (cursor_buffer, cursor_buffer_position) = self
 9399            .buffer
 9400            .read(cx)
 9401            .text_anchor_for_position(selection.head(), cx)?;
 9402        let (tail_buffer, cursor_buffer_position_end) = self
 9403            .buffer
 9404            .read(cx)
 9405            .text_anchor_for_position(selection.tail(), cx)?;
 9406        if tail_buffer != cursor_buffer {
 9407            return None;
 9408        }
 9409
 9410        let snapshot = cursor_buffer.read(cx).snapshot();
 9411        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9412        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9413        let prepare_rename = project.update(cx, |project, cx| {
 9414            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 9415        });
 9416        drop(snapshot);
 9417
 9418        Some(cx.spawn(|this, mut cx| async move {
 9419            let rename_range = if let Some(range) = prepare_rename.await? {
 9420                Some(range)
 9421            } else {
 9422                this.update(&mut cx, |this, cx| {
 9423                    let buffer = this.buffer.read(cx).snapshot(cx);
 9424                    let mut buffer_highlights = this
 9425                        .document_highlights_for_position(selection.head(), &buffer)
 9426                        .filter(|highlight| {
 9427                            highlight.start.excerpt_id == selection.head().excerpt_id
 9428                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9429                        });
 9430                    buffer_highlights
 9431                        .next()
 9432                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9433                })?
 9434            };
 9435            if let Some(rename_range) = rename_range {
 9436                this.update(&mut cx, |this, cx| {
 9437                    let snapshot = cursor_buffer.read(cx).snapshot();
 9438                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9439                    let cursor_offset_in_rename_range =
 9440                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9441                    let cursor_offset_in_rename_range_end =
 9442                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9443
 9444                    this.take_rename(false, cx);
 9445                    let buffer = this.buffer.read(cx).read(cx);
 9446                    let cursor_offset = selection.head().to_offset(&buffer);
 9447                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9448                    let rename_end = rename_start + rename_buffer_range.len();
 9449                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9450                    let mut old_highlight_id = None;
 9451                    let old_name: Arc<str> = buffer
 9452                        .chunks(rename_start..rename_end, true)
 9453                        .map(|chunk| {
 9454                            if old_highlight_id.is_none() {
 9455                                old_highlight_id = chunk.syntax_highlight_id;
 9456                            }
 9457                            chunk.text
 9458                        })
 9459                        .collect::<String>()
 9460                        .into();
 9461
 9462                    drop(buffer);
 9463
 9464                    // Position the selection in the rename editor so that it matches the current selection.
 9465                    this.show_local_selections = false;
 9466                    let rename_editor = cx.new_view(|cx| {
 9467                        let mut editor = Editor::single_line(cx);
 9468                        editor.buffer.update(cx, |buffer, cx| {
 9469                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9470                        });
 9471                        let rename_selection_range = match cursor_offset_in_rename_range
 9472                            .cmp(&cursor_offset_in_rename_range_end)
 9473                        {
 9474                            Ordering::Equal => {
 9475                                editor.select_all(&SelectAll, cx);
 9476                                return editor;
 9477                            }
 9478                            Ordering::Less => {
 9479                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9480                            }
 9481                            Ordering::Greater => {
 9482                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9483                            }
 9484                        };
 9485                        if rename_selection_range.end > old_name.len() {
 9486                            editor.select_all(&SelectAll, cx);
 9487                        } else {
 9488                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9489                                s.select_ranges([rename_selection_range]);
 9490                            });
 9491                        }
 9492                        editor
 9493                    });
 9494
 9495                    let write_highlights =
 9496                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9497                    let read_highlights =
 9498                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9499                    let ranges = write_highlights
 9500                        .iter()
 9501                        .flat_map(|(_, ranges)| ranges.iter())
 9502                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9503                        .cloned()
 9504                        .collect();
 9505
 9506                    this.highlight_text::<Rename>(
 9507                        ranges,
 9508                        HighlightStyle {
 9509                            fade_out: Some(0.6),
 9510                            ..Default::default()
 9511                        },
 9512                        cx,
 9513                    );
 9514                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9515                    cx.focus(&rename_focus_handle);
 9516                    let block_id = this.insert_blocks(
 9517                        [BlockProperties {
 9518                            style: BlockStyle::Flex,
 9519                            position: range.start,
 9520                            height: 1,
 9521                            render: Box::new({
 9522                                let rename_editor = rename_editor.clone();
 9523                                move |cx: &mut BlockContext| {
 9524                                    let mut text_style = cx.editor_style.text.clone();
 9525                                    if let Some(highlight_style) = old_highlight_id
 9526                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 9527                                    {
 9528                                        text_style = text_style.highlight(highlight_style);
 9529                                    }
 9530                                    div()
 9531                                        .pl(cx.anchor_x)
 9532                                        .child(EditorElement::new(
 9533                                            &rename_editor,
 9534                                            EditorStyle {
 9535                                                background: cx.theme().system().transparent,
 9536                                                local_player: cx.editor_style.local_player,
 9537                                                text: text_style,
 9538                                                scrollbar_width: cx.editor_style.scrollbar_width,
 9539                                                syntax: cx.editor_style.syntax.clone(),
 9540                                                status: cx.editor_style.status.clone(),
 9541                                                inlay_hints_style: HighlightStyle {
 9542                                                    color: Some(cx.theme().status().hint),
 9543                                                    font_weight: Some(FontWeight::BOLD),
 9544                                                    ..HighlightStyle::default()
 9545                                                },
 9546                                                suggestions_style: HighlightStyle {
 9547                                                    color: Some(cx.theme().status().predictive),
 9548                                                    ..HighlightStyle::default()
 9549                                                },
 9550                                            },
 9551                                        ))
 9552                                        .into_any_element()
 9553                                }
 9554                            }),
 9555                            disposition: BlockDisposition::Below,
 9556                        }],
 9557                        Some(Autoscroll::fit()),
 9558                        cx,
 9559                    )[0];
 9560                    this.pending_rename = Some(RenameState {
 9561                        range,
 9562                        old_name,
 9563                        editor: rename_editor,
 9564                        block_id,
 9565                    });
 9566                })?;
 9567            }
 9568
 9569            Ok(())
 9570        }))
 9571    }
 9572
 9573    pub fn confirm_rename(
 9574        &mut self,
 9575        _: &ConfirmRename,
 9576        cx: &mut ViewContext<Self>,
 9577    ) -> Option<Task<Result<()>>> {
 9578        let rename = self.take_rename(false, cx)?;
 9579        let workspace = self.workspace()?;
 9580        let (start_buffer, start) = self
 9581            .buffer
 9582            .read(cx)
 9583            .text_anchor_for_position(rename.range.start, cx)?;
 9584        let (end_buffer, end) = self
 9585            .buffer
 9586            .read(cx)
 9587            .text_anchor_for_position(rename.range.end, cx)?;
 9588        if start_buffer != end_buffer {
 9589            return None;
 9590        }
 9591
 9592        let buffer = start_buffer;
 9593        let range = start..end;
 9594        let old_name = rename.old_name;
 9595        let new_name = rename.editor.read(cx).text(cx);
 9596
 9597        let rename = workspace
 9598            .read(cx)
 9599            .project()
 9600            .clone()
 9601            .update(cx, |project, cx| {
 9602                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 9603            });
 9604        let workspace = workspace.downgrade();
 9605
 9606        Some(cx.spawn(|editor, mut cx| async move {
 9607            let project_transaction = rename.await?;
 9608            Self::open_project_transaction(
 9609                &editor,
 9610                workspace,
 9611                project_transaction,
 9612                format!("Rename: {}{}", old_name, new_name),
 9613                cx.clone(),
 9614            )
 9615            .await?;
 9616
 9617            editor.update(&mut cx, |editor, cx| {
 9618                editor.refresh_document_highlights(cx);
 9619            })?;
 9620            Ok(())
 9621        }))
 9622    }
 9623
 9624    fn take_rename(
 9625        &mut self,
 9626        moving_cursor: bool,
 9627        cx: &mut ViewContext<Self>,
 9628    ) -> Option<RenameState> {
 9629        let rename = self.pending_rename.take()?;
 9630        if rename.editor.focus_handle(cx).is_focused(cx) {
 9631            cx.focus(&self.focus_handle);
 9632        }
 9633
 9634        self.remove_blocks(
 9635            [rename.block_id].into_iter().collect(),
 9636            Some(Autoscroll::fit()),
 9637            cx,
 9638        );
 9639        self.clear_highlights::<Rename>(cx);
 9640        self.show_local_selections = true;
 9641
 9642        if moving_cursor {
 9643            let rename_editor = rename.editor.read(cx);
 9644            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 9645
 9646            // Update the selection to match the position of the selection inside
 9647            // the rename editor.
 9648            let snapshot = self.buffer.read(cx).read(cx);
 9649            let rename_range = rename.range.to_offset(&snapshot);
 9650            let cursor_in_editor = snapshot
 9651                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 9652                .min(rename_range.end);
 9653            drop(snapshot);
 9654
 9655            self.change_selections(None, cx, |s| {
 9656                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 9657            });
 9658        } else {
 9659            self.refresh_document_highlights(cx);
 9660        }
 9661
 9662        Some(rename)
 9663    }
 9664
 9665    pub fn pending_rename(&self) -> Option<&RenameState> {
 9666        self.pending_rename.as_ref()
 9667    }
 9668
 9669    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9670        let project = match &self.project {
 9671            Some(project) => project.clone(),
 9672            None => return None,
 9673        };
 9674
 9675        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 9676    }
 9677
 9678    fn perform_format(
 9679        &mut self,
 9680        project: Model<Project>,
 9681        trigger: FormatTrigger,
 9682        cx: &mut ViewContext<Self>,
 9683    ) -> Task<Result<()>> {
 9684        let buffer = self.buffer().clone();
 9685        let mut buffers = buffer.read(cx).all_buffers();
 9686        if trigger == FormatTrigger::Save {
 9687            buffers.retain(|buffer| buffer.read(cx).is_dirty());
 9688        }
 9689
 9690        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 9691        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 9692
 9693        cx.spawn(|_, mut cx| async move {
 9694            let transaction = futures::select_biased! {
 9695                () = timeout => {
 9696                    log::warn!("timed out waiting for formatting");
 9697                    None
 9698                }
 9699                transaction = format.log_err().fuse() => transaction,
 9700            };
 9701
 9702            buffer
 9703                .update(&mut cx, |buffer, cx| {
 9704                    if let Some(transaction) = transaction {
 9705                        if !buffer.is_singleton() {
 9706                            buffer.push_transaction(&transaction.0, cx);
 9707                        }
 9708                    }
 9709
 9710                    cx.notify();
 9711                })
 9712                .ok();
 9713
 9714            Ok(())
 9715        })
 9716    }
 9717
 9718    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
 9719        if let Some(project) = self.project.clone() {
 9720            self.buffer.update(cx, |multi_buffer, cx| {
 9721                project.update(cx, |project, cx| {
 9722                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
 9723                });
 9724            })
 9725        }
 9726    }
 9727
 9728    fn cancel_language_server_work(
 9729        &mut self,
 9730        _: &CancelLanguageServerWork,
 9731        cx: &mut ViewContext<Self>,
 9732    ) {
 9733        if let Some(project) = self.project.clone() {
 9734            self.buffer.update(cx, |multi_buffer, cx| {
 9735                project.update(cx, |project, cx| {
 9736                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
 9737                });
 9738            })
 9739        }
 9740    }
 9741
 9742    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 9743        cx.show_character_palette();
 9744    }
 9745
 9746    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
 9747        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
 9748            let buffer = self.buffer.read(cx).snapshot(cx);
 9749            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
 9750            let is_valid = buffer
 9751                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
 9752                .any(|entry| {
 9753                    entry.diagnostic.is_primary
 9754                        && !entry.range.is_empty()
 9755                        && entry.range.start == primary_range_start
 9756                        && entry.diagnostic.message == active_diagnostics.primary_message
 9757                });
 9758
 9759            if is_valid != active_diagnostics.is_valid {
 9760                active_diagnostics.is_valid = is_valid;
 9761                let mut new_styles = HashMap::default();
 9762                for (block_id, diagnostic) in &active_diagnostics.blocks {
 9763                    new_styles.insert(
 9764                        *block_id,
 9765                        (
 9766                            None,
 9767                            diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
 9768                        ),
 9769                    );
 9770                }
 9771                self.display_map.update(cx, |display_map, cx| {
 9772                    display_map.replace_blocks(new_styles, cx)
 9773                });
 9774            }
 9775        }
 9776    }
 9777
 9778    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
 9779        self.dismiss_diagnostics(cx);
 9780        let snapshot = self.snapshot(cx);
 9781        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
 9782            let buffer = self.buffer.read(cx).snapshot(cx);
 9783
 9784            let mut primary_range = None;
 9785            let mut primary_message = None;
 9786            let mut group_end = Point::zero();
 9787            let diagnostic_group = buffer
 9788                .diagnostic_group::<MultiBufferPoint>(group_id)
 9789                .filter_map(|entry| {
 9790                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
 9791                        && (entry.range.start.row == entry.range.end.row
 9792                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
 9793                    {
 9794                        return None;
 9795                    }
 9796                    if entry.range.end > group_end {
 9797                        group_end = entry.range.end;
 9798                    }
 9799                    if entry.diagnostic.is_primary {
 9800                        primary_range = Some(entry.range.clone());
 9801                        primary_message = Some(entry.diagnostic.message.clone());
 9802                    }
 9803                    Some(entry)
 9804                })
 9805                .collect::<Vec<_>>();
 9806            let primary_range = primary_range?;
 9807            let primary_message = primary_message?;
 9808            let primary_range =
 9809                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
 9810
 9811            let blocks = display_map
 9812                .insert_blocks(
 9813                    diagnostic_group.iter().map(|entry| {
 9814                        let diagnostic = entry.diagnostic.clone();
 9815                        let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
 9816                        BlockProperties {
 9817                            style: BlockStyle::Fixed,
 9818                            position: buffer.anchor_after(entry.range.start),
 9819                            height: message_height,
 9820                            render: diagnostic_block_renderer(diagnostic, None, true, true),
 9821                            disposition: BlockDisposition::Below,
 9822                        }
 9823                    }),
 9824                    cx,
 9825                )
 9826                .into_iter()
 9827                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
 9828                .collect();
 9829
 9830            Some(ActiveDiagnosticGroup {
 9831                primary_range,
 9832                primary_message,
 9833                group_id,
 9834                blocks,
 9835                is_valid: true,
 9836            })
 9837        });
 9838        self.active_diagnostics.is_some()
 9839    }
 9840
 9841    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
 9842        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
 9843            self.display_map.update(cx, |display_map, cx| {
 9844                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
 9845            });
 9846            cx.notify();
 9847        }
 9848    }
 9849
 9850    pub fn set_selections_from_remote(
 9851        &mut self,
 9852        selections: Vec<Selection<Anchor>>,
 9853        pending_selection: Option<Selection<Anchor>>,
 9854        cx: &mut ViewContext<Self>,
 9855    ) {
 9856        let old_cursor_position = self.selections.newest_anchor().head();
 9857        self.selections.change_with(cx, |s| {
 9858            s.select_anchors(selections);
 9859            if let Some(pending_selection) = pending_selection {
 9860                s.set_pending(pending_selection, SelectMode::Character);
 9861            } else {
 9862                s.clear_pending();
 9863            }
 9864        });
 9865        self.selections_did_change(false, &old_cursor_position, true, cx);
 9866    }
 9867
 9868    fn push_to_selection_history(&mut self) {
 9869        self.selection_history.push(SelectionHistoryEntry {
 9870            selections: self.selections.disjoint_anchors(),
 9871            select_next_state: self.select_next_state.clone(),
 9872            select_prev_state: self.select_prev_state.clone(),
 9873            add_selections_state: self.add_selections_state.clone(),
 9874        });
 9875    }
 9876
 9877    pub fn transact(
 9878        &mut self,
 9879        cx: &mut ViewContext<Self>,
 9880        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
 9881    ) -> Option<TransactionId> {
 9882        self.start_transaction_at(Instant::now(), cx);
 9883        update(self, cx);
 9884        self.end_transaction_at(Instant::now(), cx)
 9885    }
 9886
 9887    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
 9888        self.end_selection(cx);
 9889        if let Some(tx_id) = self
 9890            .buffer
 9891            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
 9892        {
 9893            self.selection_history
 9894                .insert_transaction(tx_id, self.selections.disjoint_anchors());
 9895            cx.emit(EditorEvent::TransactionBegun {
 9896                transaction_id: tx_id,
 9897            })
 9898        }
 9899    }
 9900
 9901    fn end_transaction_at(
 9902        &mut self,
 9903        now: Instant,
 9904        cx: &mut ViewContext<Self>,
 9905    ) -> Option<TransactionId> {
 9906        if let Some(transaction_id) = self
 9907            .buffer
 9908            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 9909        {
 9910            if let Some((_, end_selections)) =
 9911                self.selection_history.transaction_mut(transaction_id)
 9912            {
 9913                *end_selections = Some(self.selections.disjoint_anchors());
 9914            } else {
 9915                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
 9916            }
 9917
 9918            cx.emit(EditorEvent::Edited { transaction_id });
 9919            Some(transaction_id)
 9920        } else {
 9921            None
 9922        }
 9923    }
 9924
 9925    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
 9926        let mut fold_ranges = Vec::new();
 9927
 9928        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9929
 9930        let selections = self.selections.all_adjusted(cx);
 9931        for selection in selections {
 9932            let range = selection.range().sorted();
 9933            let buffer_start_row = range.start.row;
 9934
 9935            for row in (0..=range.end.row).rev() {
 9936                if let Some((foldable_range, fold_text)) =
 9937                    display_map.foldable_range(MultiBufferRow(row))
 9938                {
 9939                    if foldable_range.end.row >= buffer_start_row {
 9940                        fold_ranges.push((foldable_range, fold_text));
 9941                        if row <= range.start.row {
 9942                            break;
 9943                        }
 9944                    }
 9945                }
 9946            }
 9947        }
 9948
 9949        self.fold_ranges(fold_ranges, true, cx);
 9950    }
 9951
 9952    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
 9953        let buffer_row = fold_at.buffer_row;
 9954        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9955
 9956        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
 9957            let autoscroll = self
 9958                .selections
 9959                .all::<Point>(cx)
 9960                .iter()
 9961                .any(|selection| fold_range.overlaps(&selection.range()));
 9962
 9963            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
 9964        }
 9965    }
 9966
 9967    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
 9968        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9969        let buffer = &display_map.buffer_snapshot;
 9970        let selections = self.selections.all::<Point>(cx);
 9971        let ranges = selections
 9972            .iter()
 9973            .map(|s| {
 9974                let range = s.display_range(&display_map).sorted();
 9975                let mut start = range.start.to_point(&display_map);
 9976                let mut end = range.end.to_point(&display_map);
 9977                start.column = 0;
 9978                end.column = buffer.line_len(MultiBufferRow(end.row));
 9979                start..end
 9980            })
 9981            .collect::<Vec<_>>();
 9982
 9983        self.unfold_ranges(ranges, true, true, cx);
 9984    }
 9985
 9986    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
 9987        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9988
 9989        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
 9990            ..Point::new(
 9991                unfold_at.buffer_row.0,
 9992                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
 9993            );
 9994
 9995        let autoscroll = self
 9996            .selections
 9997            .all::<Point>(cx)
 9998            .iter()
 9999            .any(|selection| selection.range().overlaps(&intersection_range));
10000
10001        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10002    }
10003
10004    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10005        let selections = self.selections.all::<Point>(cx);
10006        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10007        let line_mode = self.selections.line_mode;
10008        let ranges = selections.into_iter().map(|s| {
10009            if line_mode {
10010                let start = Point::new(s.start.row, 0);
10011                let end = Point::new(
10012                    s.end.row,
10013                    display_map
10014                        .buffer_snapshot
10015                        .line_len(MultiBufferRow(s.end.row)),
10016                );
10017                (start..end, display_map.fold_placeholder.clone())
10018            } else {
10019                (s.start..s.end, display_map.fold_placeholder.clone())
10020            }
10021        });
10022        self.fold_ranges(ranges, true, cx);
10023    }
10024
10025    pub fn fold_ranges<T: ToOffset + Clone>(
10026        &mut self,
10027        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10028        auto_scroll: bool,
10029        cx: &mut ViewContext<Self>,
10030    ) {
10031        let mut fold_ranges = Vec::new();
10032        let mut buffers_affected = HashMap::default();
10033        let multi_buffer = self.buffer().read(cx);
10034        for (fold_range, fold_text) in ranges {
10035            if let Some((_, buffer, _)) =
10036                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10037            {
10038                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10039            };
10040            fold_ranges.push((fold_range, fold_text));
10041        }
10042
10043        let mut ranges = fold_ranges.into_iter().peekable();
10044        if ranges.peek().is_some() {
10045            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10046
10047            if auto_scroll {
10048                self.request_autoscroll(Autoscroll::fit(), cx);
10049            }
10050
10051            for buffer in buffers_affected.into_values() {
10052                self.sync_expanded_diff_hunks(buffer, cx);
10053            }
10054
10055            cx.notify();
10056
10057            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10058                // Clear diagnostics block when folding a range that contains it.
10059                let snapshot = self.snapshot(cx);
10060                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10061                    drop(snapshot);
10062                    self.active_diagnostics = Some(active_diagnostics);
10063                    self.dismiss_diagnostics(cx);
10064                } else {
10065                    self.active_diagnostics = Some(active_diagnostics);
10066                }
10067            }
10068
10069            self.scrollbar_marker_state.dirty = true;
10070        }
10071    }
10072
10073    pub fn unfold_ranges<T: ToOffset + Clone>(
10074        &mut self,
10075        ranges: impl IntoIterator<Item = Range<T>>,
10076        inclusive: bool,
10077        auto_scroll: bool,
10078        cx: &mut ViewContext<Self>,
10079    ) {
10080        let mut unfold_ranges = Vec::new();
10081        let mut buffers_affected = HashMap::default();
10082        let multi_buffer = self.buffer().read(cx);
10083        for range in ranges {
10084            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10085                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10086            };
10087            unfold_ranges.push(range);
10088        }
10089
10090        let mut ranges = unfold_ranges.into_iter().peekable();
10091        if ranges.peek().is_some() {
10092            self.display_map
10093                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10094            if auto_scroll {
10095                self.request_autoscroll(Autoscroll::fit(), cx);
10096            }
10097
10098            for buffer in buffers_affected.into_values() {
10099                self.sync_expanded_diff_hunks(buffer, cx);
10100            }
10101
10102            cx.notify();
10103            self.scrollbar_marker_state.dirty = true;
10104            self.active_indent_guides_state.dirty = true;
10105        }
10106    }
10107
10108    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10109        if hovered != self.gutter_hovered {
10110            self.gutter_hovered = hovered;
10111            cx.notify();
10112        }
10113    }
10114
10115    pub fn insert_blocks(
10116        &mut self,
10117        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10118        autoscroll: Option<Autoscroll>,
10119        cx: &mut ViewContext<Self>,
10120    ) -> Vec<BlockId> {
10121        let blocks = self
10122            .display_map
10123            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10124        if let Some(autoscroll) = autoscroll {
10125            self.request_autoscroll(autoscroll, cx);
10126        }
10127        blocks
10128    }
10129
10130    pub fn replace_blocks(
10131        &mut self,
10132        blocks: HashMap<BlockId, (Option<u8>, RenderBlock)>,
10133        autoscroll: Option<Autoscroll>,
10134        cx: &mut ViewContext<Self>,
10135    ) {
10136        self.display_map
10137            .update(cx, |display_map, cx| display_map.replace_blocks(blocks, cx));
10138        if let Some(autoscroll) = autoscroll {
10139            self.request_autoscroll(autoscroll, cx);
10140        }
10141    }
10142
10143    pub fn remove_blocks(
10144        &mut self,
10145        block_ids: HashSet<BlockId>,
10146        autoscroll: Option<Autoscroll>,
10147        cx: &mut ViewContext<Self>,
10148    ) {
10149        self.display_map.update(cx, |display_map, cx| {
10150            display_map.remove_blocks(block_ids, cx)
10151        });
10152        if let Some(autoscroll) = autoscroll {
10153            self.request_autoscroll(autoscroll, cx);
10154        }
10155    }
10156
10157    pub fn row_for_block(
10158        &self,
10159        block_id: BlockId,
10160        cx: &mut ViewContext<Self>,
10161    ) -> Option<DisplayRow> {
10162        self.display_map
10163            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10164    }
10165
10166    pub fn insert_creases(
10167        &mut self,
10168        creases: impl IntoIterator<Item = Crease>,
10169        cx: &mut ViewContext<Self>,
10170    ) -> Vec<CreaseId> {
10171        self.display_map
10172            .update(cx, |map, cx| map.insert_creases(creases, cx))
10173    }
10174
10175    pub fn remove_creases(
10176        &mut self,
10177        ids: impl IntoIterator<Item = CreaseId>,
10178        cx: &mut ViewContext<Self>,
10179    ) {
10180        self.display_map
10181            .update(cx, |map, cx| map.remove_creases(ids, cx));
10182    }
10183
10184    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10185        self.display_map
10186            .update(cx, |map, cx| map.snapshot(cx))
10187            .longest_row()
10188    }
10189
10190    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10191        self.display_map
10192            .update(cx, |map, cx| map.snapshot(cx))
10193            .max_point()
10194    }
10195
10196    pub fn text(&self, cx: &AppContext) -> String {
10197        self.buffer.read(cx).read(cx).text()
10198    }
10199
10200    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10201        let text = self.text(cx);
10202        let text = text.trim();
10203
10204        if text.is_empty() {
10205            return None;
10206        }
10207
10208        Some(text.to_string())
10209    }
10210
10211    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10212        self.transact(cx, |this, cx| {
10213            this.buffer
10214                .read(cx)
10215                .as_singleton()
10216                .expect("you can only call set_text on editors for singleton buffers")
10217                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10218        });
10219    }
10220
10221    pub fn display_text(&self, cx: &mut AppContext) -> String {
10222        self.display_map
10223            .update(cx, |map, cx| map.snapshot(cx))
10224            .text()
10225    }
10226
10227    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10228        let mut wrap_guides = smallvec::smallvec![];
10229
10230        if self.show_wrap_guides == Some(false) {
10231            return wrap_guides;
10232        }
10233
10234        let settings = self.buffer.read(cx).settings_at(0, cx);
10235        if settings.show_wrap_guides {
10236            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10237                wrap_guides.push((soft_wrap as usize, true));
10238            }
10239            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10240        }
10241
10242        wrap_guides
10243    }
10244
10245    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10246        let settings = self.buffer.read(cx).settings_at(0, cx);
10247        let mode = self
10248            .soft_wrap_mode_override
10249            .unwrap_or_else(|| settings.soft_wrap);
10250        match mode {
10251            language_settings::SoftWrap::None => SoftWrap::None,
10252            language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10253            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10254            language_settings::SoftWrap::PreferredLineLength => {
10255                SoftWrap::Column(settings.preferred_line_length)
10256            }
10257        }
10258    }
10259
10260    pub fn set_soft_wrap_mode(
10261        &mut self,
10262        mode: language_settings::SoftWrap,
10263        cx: &mut ViewContext<Self>,
10264    ) {
10265        self.soft_wrap_mode_override = Some(mode);
10266        cx.notify();
10267    }
10268
10269    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10270        let rem_size = cx.rem_size();
10271        self.display_map.update(cx, |map, cx| {
10272            map.set_font(
10273                style.text.font(),
10274                style.text.font_size.to_pixels(rem_size),
10275                cx,
10276            )
10277        });
10278        self.style = Some(style);
10279    }
10280
10281    pub fn style(&self) -> Option<&EditorStyle> {
10282        self.style.as_ref()
10283    }
10284
10285    // Called by the element. This method is not designed to be called outside of the editor
10286    // element's layout code because it does not notify when rewrapping is computed synchronously.
10287    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10288        self.display_map
10289            .update(cx, |map, cx| map.set_wrap_width(width, cx))
10290    }
10291
10292    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10293        if self.soft_wrap_mode_override.is_some() {
10294            self.soft_wrap_mode_override.take();
10295        } else {
10296            let soft_wrap = match self.soft_wrap_mode(cx) {
10297                SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10298                SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10299                    language_settings::SoftWrap::PreferLine
10300                }
10301            };
10302            self.soft_wrap_mode_override = Some(soft_wrap);
10303        }
10304        cx.notify();
10305    }
10306
10307    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10308        let Some(workspace) = self.workspace() else {
10309            return;
10310        };
10311        let fs = workspace.read(cx).app_state().fs.clone();
10312        let current_show = TabBarSettings::get_global(cx).show;
10313        update_settings_file::<TabBarSettings>(fs, cx, move |setting| {
10314            setting.show = Some(!current_show);
10315        });
10316    }
10317
10318    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10319        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10320            self.buffer
10321                .read(cx)
10322                .settings_at(0, cx)
10323                .indent_guides
10324                .enabled
10325        });
10326        self.show_indent_guides = Some(!currently_enabled);
10327        cx.notify();
10328    }
10329
10330    fn should_show_indent_guides(&self) -> Option<bool> {
10331        self.show_indent_guides
10332    }
10333
10334    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10335        let mut editor_settings = EditorSettings::get_global(cx).clone();
10336        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10337        EditorSettings::override_global(editor_settings, cx);
10338    }
10339
10340    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10341        self.show_gutter = show_gutter;
10342        cx.notify();
10343    }
10344
10345    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10346        self.show_line_numbers = Some(show_line_numbers);
10347        cx.notify();
10348    }
10349
10350    pub fn set_show_git_diff_gutter(
10351        &mut self,
10352        show_git_diff_gutter: bool,
10353        cx: &mut ViewContext<Self>,
10354    ) {
10355        self.show_git_diff_gutter = Some(show_git_diff_gutter);
10356        cx.notify();
10357    }
10358
10359    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10360        self.show_code_actions = Some(show_code_actions);
10361        cx.notify();
10362    }
10363
10364    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10365        self.show_runnables = Some(show_runnables);
10366        cx.notify();
10367    }
10368
10369    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10370        self.show_wrap_guides = Some(show_wrap_guides);
10371        cx.notify();
10372    }
10373
10374    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10375        self.show_indent_guides = Some(show_indent_guides);
10376        cx.notify();
10377    }
10378
10379    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10380        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10381            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10382                cx.reveal_path(&file.abs_path(cx));
10383            }
10384        }
10385    }
10386
10387    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10388        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10389            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10390                if let Some(path) = file.abs_path(cx).to_str() {
10391                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10392                }
10393            }
10394        }
10395    }
10396
10397    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10398        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10399            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10400                if let Some(path) = file.path().to_str() {
10401                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10402                }
10403            }
10404        }
10405    }
10406
10407    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10408        self.show_git_blame_gutter = !self.show_git_blame_gutter;
10409
10410        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10411            self.start_git_blame(true, cx);
10412        }
10413
10414        cx.notify();
10415    }
10416
10417    pub fn toggle_git_blame_inline(
10418        &mut self,
10419        _: &ToggleGitBlameInline,
10420        cx: &mut ViewContext<Self>,
10421    ) {
10422        self.toggle_git_blame_inline_internal(true, cx);
10423        cx.notify();
10424    }
10425
10426    pub fn git_blame_inline_enabled(&self) -> bool {
10427        self.git_blame_inline_enabled
10428    }
10429
10430    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10431        self.show_selection_menu = self
10432            .show_selection_menu
10433            .map(|show_selections_menu| !show_selections_menu)
10434            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10435
10436        cx.notify();
10437    }
10438
10439    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10440        self.show_selection_menu
10441            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10442    }
10443
10444    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10445        if let Some(project) = self.project.as_ref() {
10446            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10447                return;
10448            };
10449
10450            if buffer.read(cx).file().is_none() {
10451                return;
10452            }
10453
10454            let focused = self.focus_handle(cx).contains_focused(cx);
10455
10456            let project = project.clone();
10457            let blame =
10458                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10459            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10460            self.blame = Some(blame);
10461        }
10462    }
10463
10464    fn toggle_git_blame_inline_internal(
10465        &mut self,
10466        user_triggered: bool,
10467        cx: &mut ViewContext<Self>,
10468    ) {
10469        if self.git_blame_inline_enabled {
10470            self.git_blame_inline_enabled = false;
10471            self.show_git_blame_inline = false;
10472            self.show_git_blame_inline_delay_task.take();
10473        } else {
10474            self.git_blame_inline_enabled = true;
10475            self.start_git_blame_inline(user_triggered, cx);
10476        }
10477
10478        cx.notify();
10479    }
10480
10481    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10482        self.start_git_blame(user_triggered, cx);
10483
10484        if ProjectSettings::get_global(cx)
10485            .git
10486            .inline_blame_delay()
10487            .is_some()
10488        {
10489            self.start_inline_blame_timer(cx);
10490        } else {
10491            self.show_git_blame_inline = true
10492        }
10493    }
10494
10495    pub fn blame(&self) -> Option<&Model<GitBlame>> {
10496        self.blame.as_ref()
10497    }
10498
10499    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10500        self.show_git_blame_gutter && self.has_blame_entries(cx)
10501    }
10502
10503    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10504        self.show_git_blame_inline
10505            && self.focus_handle.is_focused(cx)
10506            && !self.newest_selection_head_on_empty_line(cx)
10507            && self.has_blame_entries(cx)
10508    }
10509
10510    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10511        self.blame()
10512            .map_or(false, |blame| blame.read(cx).has_generated_entries())
10513    }
10514
10515    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10516        let cursor_anchor = self.selections.newest_anchor().head();
10517
10518        let snapshot = self.buffer.read(cx).snapshot(cx);
10519        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10520
10521        snapshot.line_len(buffer_row) == 0
10522    }
10523
10524    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10525        let (path, selection, repo) = maybe!({
10526            let project_handle = self.project.as_ref()?.clone();
10527            let project = project_handle.read(cx);
10528
10529            let selection = self.selections.newest::<Point>(cx);
10530            let selection_range = selection.range();
10531
10532            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10533                (buffer, selection_range.start.row..selection_range.end.row)
10534            } else {
10535                let buffer_ranges = self
10536                    .buffer()
10537                    .read(cx)
10538                    .range_to_buffer_ranges(selection_range, cx);
10539
10540                let (buffer, range, _) = if selection.reversed {
10541                    buffer_ranges.first()
10542                } else {
10543                    buffer_ranges.last()
10544                }?;
10545
10546                let snapshot = buffer.read(cx).snapshot();
10547                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10548                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
10549                (buffer.clone(), selection)
10550            };
10551
10552            let path = buffer
10553                .read(cx)
10554                .file()?
10555                .as_local()?
10556                .path()
10557                .to_str()?
10558                .to_string();
10559            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10560            Some((path, selection, repo))
10561        })
10562        .ok_or_else(|| anyhow!("unable to open git repository"))?;
10563
10564        const REMOTE_NAME: &str = "origin";
10565        let origin_url = repo
10566            .remote_url(REMOTE_NAME)
10567            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10568        let sha = repo
10569            .head_sha()
10570            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10571
10572        let (provider, remote) =
10573            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10574                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10575
10576        Ok(provider.build_permalink(
10577            remote,
10578            BuildPermalinkParams {
10579                sha: &sha,
10580                path: &path,
10581                selection: Some(selection),
10582            },
10583        ))
10584    }
10585
10586    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10587        let permalink = self.get_permalink_to_line(cx);
10588
10589        match permalink {
10590            Ok(permalink) => {
10591                cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
10592            }
10593            Err(err) => {
10594                let message = format!("Failed to copy permalink: {err}");
10595
10596                Err::<(), anyhow::Error>(err).log_err();
10597
10598                if let Some(workspace) = self.workspace() {
10599                    workspace.update(cx, |workspace, cx| {
10600                        struct CopyPermalinkToLine;
10601
10602                        workspace.show_toast(
10603                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10604                            cx,
10605                        )
10606                    })
10607                }
10608            }
10609        }
10610    }
10611
10612    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10613        let permalink = self.get_permalink_to_line(cx);
10614
10615        match permalink {
10616            Ok(permalink) => {
10617                cx.open_url(permalink.as_ref());
10618            }
10619            Err(err) => {
10620                let message = format!("Failed to open permalink: {err}");
10621
10622                Err::<(), anyhow::Error>(err).log_err();
10623
10624                if let Some(workspace) = self.workspace() {
10625                    workspace.update(cx, |workspace, cx| {
10626                        struct OpenPermalinkToLine;
10627
10628                        workspace.show_toast(
10629                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10630                            cx,
10631                        )
10632                    })
10633                }
10634            }
10635        }
10636    }
10637
10638    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10639    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10640    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10641    pub fn highlight_rows<T: 'static>(
10642        &mut self,
10643        rows: RangeInclusive<Anchor>,
10644        color: Option<Hsla>,
10645        should_autoscroll: bool,
10646        cx: &mut ViewContext<Self>,
10647    ) {
10648        let snapshot = self.buffer().read(cx).snapshot(cx);
10649        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10650        let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10651            highlight
10652                .range
10653                .start()
10654                .cmp(&rows.start(), &snapshot)
10655                .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10656        });
10657        match (color, existing_highlight_index) {
10658            (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10659                ix,
10660                RowHighlight {
10661                    index: post_inc(&mut self.highlight_order),
10662                    range: rows,
10663                    should_autoscroll,
10664                    color,
10665                },
10666            ),
10667            (None, Ok(i)) => {
10668                row_highlights.remove(i);
10669            }
10670        }
10671    }
10672
10673    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10674    pub fn clear_row_highlights<T: 'static>(&mut self) {
10675        self.highlighted_rows.remove(&TypeId::of::<T>());
10676    }
10677
10678    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10679    pub fn highlighted_rows<T: 'static>(
10680        &self,
10681    ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10682        Some(
10683            self.highlighted_rows
10684                .get(&TypeId::of::<T>())?
10685                .iter()
10686                .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10687        )
10688    }
10689
10690    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10691    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10692    /// Allows to ignore certain kinds of highlights.
10693    pub fn highlighted_display_rows(
10694        &mut self,
10695        cx: &mut WindowContext,
10696    ) -> BTreeMap<DisplayRow, Hsla> {
10697        let snapshot = self.snapshot(cx);
10698        let mut used_highlight_orders = HashMap::default();
10699        self.highlighted_rows
10700            .iter()
10701            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10702            .fold(
10703                BTreeMap::<DisplayRow, Hsla>::new(),
10704                |mut unique_rows, highlight| {
10705                    let start_row = highlight.range.start().to_display_point(&snapshot).row();
10706                    let end_row = highlight.range.end().to_display_point(&snapshot).row();
10707                    for row in start_row.0..=end_row.0 {
10708                        let used_index =
10709                            used_highlight_orders.entry(row).or_insert(highlight.index);
10710                        if highlight.index >= *used_index {
10711                            *used_index = highlight.index;
10712                            match highlight.color {
10713                                Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10714                                None => unique_rows.remove(&DisplayRow(row)),
10715                            };
10716                        }
10717                    }
10718                    unique_rows
10719                },
10720            )
10721    }
10722
10723    pub fn highlighted_display_row_for_autoscroll(
10724        &self,
10725        snapshot: &DisplaySnapshot,
10726    ) -> Option<DisplayRow> {
10727        self.highlighted_rows
10728            .values()
10729            .flat_map(|highlighted_rows| highlighted_rows.iter())
10730            .filter_map(|highlight| {
10731                if highlight.color.is_none() || !highlight.should_autoscroll {
10732                    return None;
10733                }
10734                Some(highlight.range.start().to_display_point(&snapshot).row())
10735            })
10736            .min()
10737    }
10738
10739    pub fn set_search_within_ranges(
10740        &mut self,
10741        ranges: &[Range<Anchor>],
10742        cx: &mut ViewContext<Self>,
10743    ) {
10744        self.highlight_background::<SearchWithinRange>(
10745            ranges,
10746            |colors| colors.editor_document_highlight_read_background,
10747            cx,
10748        )
10749    }
10750
10751    pub fn set_breadcrumb_header(&mut self, new_header: String) {
10752        self.breadcrumb_header = Some(new_header);
10753    }
10754
10755    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10756        self.clear_background_highlights::<SearchWithinRange>(cx);
10757    }
10758
10759    pub fn highlight_background<T: 'static>(
10760        &mut self,
10761        ranges: &[Range<Anchor>],
10762        color_fetcher: fn(&ThemeColors) -> Hsla,
10763        cx: &mut ViewContext<Self>,
10764    ) {
10765        let snapshot = self.snapshot(cx);
10766        // this is to try and catch a panic sooner
10767        for range in ranges {
10768            snapshot
10769                .buffer_snapshot
10770                .summary_for_anchor::<usize>(&range.start);
10771            snapshot
10772                .buffer_snapshot
10773                .summary_for_anchor::<usize>(&range.end);
10774        }
10775
10776        self.background_highlights
10777            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10778        self.scrollbar_marker_state.dirty = true;
10779        cx.notify();
10780    }
10781
10782    pub fn clear_background_highlights<T: 'static>(
10783        &mut self,
10784        cx: &mut ViewContext<Self>,
10785    ) -> Option<BackgroundHighlight> {
10786        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10787        if !text_highlights.1.is_empty() {
10788            self.scrollbar_marker_state.dirty = true;
10789            cx.notify();
10790        }
10791        Some(text_highlights)
10792    }
10793
10794    pub fn highlight_gutter<T: 'static>(
10795        &mut self,
10796        ranges: &[Range<Anchor>],
10797        color_fetcher: fn(&AppContext) -> Hsla,
10798        cx: &mut ViewContext<Self>,
10799    ) {
10800        self.gutter_highlights
10801            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10802        cx.notify();
10803    }
10804
10805    pub fn clear_gutter_highlights<T: 'static>(
10806        &mut self,
10807        cx: &mut ViewContext<Self>,
10808    ) -> Option<GutterHighlight> {
10809        cx.notify();
10810        self.gutter_highlights.remove(&TypeId::of::<T>())
10811    }
10812
10813    #[cfg(feature = "test-support")]
10814    pub fn all_text_background_highlights(
10815        &mut self,
10816        cx: &mut ViewContext<Self>,
10817    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10818        let snapshot = self.snapshot(cx);
10819        let buffer = &snapshot.buffer_snapshot;
10820        let start = buffer.anchor_before(0);
10821        let end = buffer.anchor_after(buffer.len());
10822        let theme = cx.theme().colors();
10823        self.background_highlights_in_range(start..end, &snapshot, theme)
10824    }
10825
10826    #[cfg(feature = "test-support")]
10827    pub fn search_background_highlights(
10828        &mut self,
10829        cx: &mut ViewContext<Self>,
10830    ) -> Vec<Range<Point>> {
10831        let snapshot = self.buffer().read(cx).snapshot(cx);
10832
10833        let highlights = self
10834            .background_highlights
10835            .get(&TypeId::of::<items::BufferSearchHighlights>());
10836
10837        if let Some((_color, ranges)) = highlights {
10838            ranges
10839                .iter()
10840                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
10841                .collect_vec()
10842        } else {
10843            vec![]
10844        }
10845    }
10846
10847    fn document_highlights_for_position<'a>(
10848        &'a self,
10849        position: Anchor,
10850        buffer: &'a MultiBufferSnapshot,
10851    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
10852        let read_highlights = self
10853            .background_highlights
10854            .get(&TypeId::of::<DocumentHighlightRead>())
10855            .map(|h| &h.1);
10856        let write_highlights = self
10857            .background_highlights
10858            .get(&TypeId::of::<DocumentHighlightWrite>())
10859            .map(|h| &h.1);
10860        let left_position = position.bias_left(buffer);
10861        let right_position = position.bias_right(buffer);
10862        read_highlights
10863            .into_iter()
10864            .chain(write_highlights)
10865            .flat_map(move |ranges| {
10866                let start_ix = match ranges.binary_search_by(|probe| {
10867                    let cmp = probe.end.cmp(&left_position, buffer);
10868                    if cmp.is_ge() {
10869                        Ordering::Greater
10870                    } else {
10871                        Ordering::Less
10872                    }
10873                }) {
10874                    Ok(i) | Err(i) => i,
10875                };
10876
10877                ranges[start_ix..]
10878                    .iter()
10879                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
10880            })
10881    }
10882
10883    pub fn has_background_highlights<T: 'static>(&self) -> bool {
10884        self.background_highlights
10885            .get(&TypeId::of::<T>())
10886            .map_or(false, |(_, highlights)| !highlights.is_empty())
10887    }
10888
10889    pub fn background_highlights_in_range(
10890        &self,
10891        search_range: Range<Anchor>,
10892        display_snapshot: &DisplaySnapshot,
10893        theme: &ThemeColors,
10894    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10895        let mut results = Vec::new();
10896        for (color_fetcher, ranges) in self.background_highlights.values() {
10897            let color = color_fetcher(theme);
10898            let start_ix = match ranges.binary_search_by(|probe| {
10899                let cmp = probe
10900                    .end
10901                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10902                if cmp.is_gt() {
10903                    Ordering::Greater
10904                } else {
10905                    Ordering::Less
10906                }
10907            }) {
10908                Ok(i) | Err(i) => i,
10909            };
10910            for range in &ranges[start_ix..] {
10911                if range
10912                    .start
10913                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10914                    .is_ge()
10915                {
10916                    break;
10917                }
10918
10919                let start = range.start.to_display_point(&display_snapshot);
10920                let end = range.end.to_display_point(&display_snapshot);
10921                results.push((start..end, color))
10922            }
10923        }
10924        results
10925    }
10926
10927    pub fn background_highlight_row_ranges<T: 'static>(
10928        &self,
10929        search_range: Range<Anchor>,
10930        display_snapshot: &DisplaySnapshot,
10931        count: usize,
10932    ) -> Vec<RangeInclusive<DisplayPoint>> {
10933        let mut results = Vec::new();
10934        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
10935            return vec![];
10936        };
10937
10938        let start_ix = match ranges.binary_search_by(|probe| {
10939            let cmp = probe
10940                .end
10941                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10942            if cmp.is_gt() {
10943                Ordering::Greater
10944            } else {
10945                Ordering::Less
10946            }
10947        }) {
10948            Ok(i) | Err(i) => i,
10949        };
10950        let mut push_region = |start: Option<Point>, end: Option<Point>| {
10951            if let (Some(start_display), Some(end_display)) = (start, end) {
10952                results.push(
10953                    start_display.to_display_point(display_snapshot)
10954                        ..=end_display.to_display_point(display_snapshot),
10955                );
10956            }
10957        };
10958        let mut start_row: Option<Point> = None;
10959        let mut end_row: Option<Point> = None;
10960        if ranges.len() > count {
10961            return Vec::new();
10962        }
10963        for range in &ranges[start_ix..] {
10964            if range
10965                .start
10966                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10967                .is_ge()
10968            {
10969                break;
10970            }
10971            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
10972            if let Some(current_row) = &end_row {
10973                if end.row == current_row.row {
10974                    continue;
10975                }
10976            }
10977            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
10978            if start_row.is_none() {
10979                assert_eq!(end_row, None);
10980                start_row = Some(start);
10981                end_row = Some(end);
10982                continue;
10983            }
10984            if let Some(current_end) = end_row.as_mut() {
10985                if start.row > current_end.row + 1 {
10986                    push_region(start_row, end_row);
10987                    start_row = Some(start);
10988                    end_row = Some(end);
10989                } else {
10990                    // Merge two hunks.
10991                    *current_end = end;
10992                }
10993            } else {
10994                unreachable!();
10995            }
10996        }
10997        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
10998        push_region(start_row, end_row);
10999        results
11000    }
11001
11002    pub fn gutter_highlights_in_range(
11003        &self,
11004        search_range: Range<Anchor>,
11005        display_snapshot: &DisplaySnapshot,
11006        cx: &AppContext,
11007    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11008        let mut results = Vec::new();
11009        for (color_fetcher, ranges) in self.gutter_highlights.values() {
11010            let color = color_fetcher(cx);
11011            let start_ix = match ranges.binary_search_by(|probe| {
11012                let cmp = probe
11013                    .end
11014                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11015                if cmp.is_gt() {
11016                    Ordering::Greater
11017                } else {
11018                    Ordering::Less
11019                }
11020            }) {
11021                Ok(i) | Err(i) => i,
11022            };
11023            for range in &ranges[start_ix..] {
11024                if range
11025                    .start
11026                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11027                    .is_ge()
11028                {
11029                    break;
11030                }
11031
11032                let start = range.start.to_display_point(&display_snapshot);
11033                let end = range.end.to_display_point(&display_snapshot);
11034                results.push((start..end, color))
11035            }
11036        }
11037        results
11038    }
11039
11040    /// Get the text ranges corresponding to the redaction query
11041    pub fn redacted_ranges(
11042        &self,
11043        search_range: Range<Anchor>,
11044        display_snapshot: &DisplaySnapshot,
11045        cx: &WindowContext,
11046    ) -> Vec<Range<DisplayPoint>> {
11047        display_snapshot
11048            .buffer_snapshot
11049            .redacted_ranges(search_range, |file| {
11050                if let Some(file) = file {
11051                    file.is_private()
11052                        && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11053                } else {
11054                    false
11055                }
11056            })
11057            .map(|range| {
11058                range.start.to_display_point(display_snapshot)
11059                    ..range.end.to_display_point(display_snapshot)
11060            })
11061            .collect()
11062    }
11063
11064    pub fn highlight_text<T: 'static>(
11065        &mut self,
11066        ranges: Vec<Range<Anchor>>,
11067        style: HighlightStyle,
11068        cx: &mut ViewContext<Self>,
11069    ) {
11070        self.display_map.update(cx, |map, _| {
11071            map.highlight_text(TypeId::of::<T>(), ranges, style)
11072        });
11073        cx.notify();
11074    }
11075
11076    pub(crate) fn highlight_inlays<T: 'static>(
11077        &mut self,
11078        highlights: Vec<InlayHighlight>,
11079        style: HighlightStyle,
11080        cx: &mut ViewContext<Self>,
11081    ) {
11082        self.display_map.update(cx, |map, _| {
11083            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11084        });
11085        cx.notify();
11086    }
11087
11088    pub fn text_highlights<'a, T: 'static>(
11089        &'a self,
11090        cx: &'a AppContext,
11091    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11092        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11093    }
11094
11095    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11096        let cleared = self
11097            .display_map
11098            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11099        if cleared {
11100            cx.notify();
11101        }
11102    }
11103
11104    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11105        (self.read_only(cx) || self.blink_manager.read(cx).visible())
11106            && self.focus_handle.is_focused(cx)
11107    }
11108
11109    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11110        self.show_cursor_when_unfocused = is_enabled;
11111        cx.notify();
11112    }
11113
11114    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11115        cx.notify();
11116    }
11117
11118    fn on_buffer_event(
11119        &mut self,
11120        multibuffer: Model<MultiBuffer>,
11121        event: &multi_buffer::Event,
11122        cx: &mut ViewContext<Self>,
11123    ) {
11124        match event {
11125            multi_buffer::Event::Edited {
11126                singleton_buffer_edited,
11127            } => {
11128                self.scrollbar_marker_state.dirty = true;
11129                self.active_indent_guides_state.dirty = true;
11130                self.refresh_active_diagnostics(cx);
11131                self.refresh_code_actions(cx);
11132                if self.has_active_inline_completion(cx) {
11133                    self.update_visible_inline_completion(cx);
11134                }
11135                cx.emit(EditorEvent::BufferEdited);
11136                cx.emit(SearchEvent::MatchesInvalidated);
11137                if *singleton_buffer_edited {
11138                    if let Some(project) = &self.project {
11139                        let project = project.read(cx);
11140                        #[allow(clippy::mutable_key_type)]
11141                        let languages_affected = multibuffer
11142                            .read(cx)
11143                            .all_buffers()
11144                            .into_iter()
11145                            .filter_map(|buffer| {
11146                                let buffer = buffer.read(cx);
11147                                let language = buffer.language()?;
11148                                if project.is_local()
11149                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
11150                                {
11151                                    None
11152                                } else {
11153                                    Some(language)
11154                                }
11155                            })
11156                            .cloned()
11157                            .collect::<HashSet<_>>();
11158                        if !languages_affected.is_empty() {
11159                            self.refresh_inlay_hints(
11160                                InlayHintRefreshReason::BufferEdited(languages_affected),
11161                                cx,
11162                            );
11163                        }
11164                    }
11165                }
11166
11167                let Some(project) = &self.project else { return };
11168                let telemetry = project.read(cx).client().telemetry().clone();
11169                refresh_linked_ranges(self, cx);
11170                telemetry.log_edit_event("editor");
11171            }
11172            multi_buffer::Event::ExcerptsAdded {
11173                buffer,
11174                predecessor,
11175                excerpts,
11176            } => {
11177                self.tasks_update_task = Some(self.refresh_runnables(cx));
11178                cx.emit(EditorEvent::ExcerptsAdded {
11179                    buffer: buffer.clone(),
11180                    predecessor: *predecessor,
11181                    excerpts: excerpts.clone(),
11182                });
11183                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11184            }
11185            multi_buffer::Event::ExcerptsRemoved { ids } => {
11186                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11187                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11188            }
11189            multi_buffer::Event::ExcerptsEdited { ids } => {
11190                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11191            }
11192            multi_buffer::Event::ExcerptsExpanded { ids } => {
11193                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11194            }
11195            multi_buffer::Event::Reparsed(buffer_id) => {
11196                self.tasks_update_task = Some(self.refresh_runnables(cx));
11197
11198                cx.emit(EditorEvent::Reparsed(*buffer_id));
11199            }
11200            multi_buffer::Event::LanguageChanged(buffer_id) => {
11201                linked_editing_ranges::refresh_linked_ranges(self, cx);
11202                cx.emit(EditorEvent::Reparsed(*buffer_id));
11203                cx.notify();
11204            }
11205            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11206            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11207            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11208                cx.emit(EditorEvent::TitleChanged)
11209            }
11210            multi_buffer::Event::DiffBaseChanged => {
11211                self.scrollbar_marker_state.dirty = true;
11212                cx.emit(EditorEvent::DiffBaseChanged);
11213                cx.notify();
11214            }
11215            multi_buffer::Event::DiffUpdated { buffer } => {
11216                self.sync_expanded_diff_hunks(buffer.clone(), cx);
11217                cx.notify();
11218            }
11219            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11220            multi_buffer::Event::DiagnosticsUpdated => {
11221                self.refresh_active_diagnostics(cx);
11222                self.scrollbar_marker_state.dirty = true;
11223                cx.notify();
11224            }
11225            _ => {}
11226        };
11227    }
11228
11229    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11230        cx.notify();
11231    }
11232
11233    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11234        self.tasks_update_task = Some(self.refresh_runnables(cx));
11235        self.refresh_inline_completion(true, cx);
11236        self.refresh_inlay_hints(
11237            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11238                self.selections.newest_anchor().head(),
11239                &self.buffer.read(cx).snapshot(cx),
11240                cx,
11241            )),
11242            cx,
11243        );
11244        let editor_settings = EditorSettings::get_global(cx);
11245        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11246        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11247
11248        if self.mode == EditorMode::Full {
11249            let inline_blame_enabled = ProjectSettings::get_global(cx).git.inline_blame_enabled();
11250            if self.git_blame_inline_enabled != inline_blame_enabled {
11251                self.toggle_git_blame_inline_internal(false, cx);
11252            }
11253        }
11254
11255        cx.notify();
11256    }
11257
11258    pub fn set_searchable(&mut self, searchable: bool) {
11259        self.searchable = searchable;
11260    }
11261
11262    pub fn searchable(&self) -> bool {
11263        self.searchable
11264    }
11265
11266    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11267        self.open_excerpts_common(true, cx)
11268    }
11269
11270    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11271        self.open_excerpts_common(false, cx)
11272    }
11273
11274    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11275        let buffer = self.buffer.read(cx);
11276        if buffer.is_singleton() {
11277            cx.propagate();
11278            return;
11279        }
11280
11281        let Some(workspace) = self.workspace() else {
11282            cx.propagate();
11283            return;
11284        };
11285
11286        let mut new_selections_by_buffer = HashMap::default();
11287        for selection in self.selections.all::<usize>(cx) {
11288            for (buffer, mut range, _) in
11289                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11290            {
11291                if selection.reversed {
11292                    mem::swap(&mut range.start, &mut range.end);
11293                }
11294                new_selections_by_buffer
11295                    .entry(buffer)
11296                    .or_insert(Vec::new())
11297                    .push(range)
11298            }
11299        }
11300
11301        // We defer the pane interaction because we ourselves are a workspace item
11302        // and activating a new item causes the pane to call a method on us reentrantly,
11303        // which panics if we're on the stack.
11304        cx.window_context().defer(move |cx| {
11305            workspace.update(cx, |workspace, cx| {
11306                let pane = if split {
11307                    workspace.adjacent_pane(cx)
11308                } else {
11309                    workspace.active_pane().clone()
11310                };
11311
11312                for (buffer, ranges) in new_selections_by_buffer {
11313                    let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
11314                    editor.update(cx, |editor, cx| {
11315                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11316                            s.select_ranges(ranges);
11317                        });
11318                    });
11319                }
11320            })
11321        });
11322    }
11323
11324    fn jump(
11325        &mut self,
11326        path: ProjectPath,
11327        position: Point,
11328        anchor: language::Anchor,
11329        offset_from_top: u32,
11330        cx: &mut ViewContext<Self>,
11331    ) {
11332        let workspace = self.workspace();
11333        cx.spawn(|_, mut cx| async move {
11334            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11335            let editor = workspace.update(&mut cx, |workspace, cx| {
11336                // Reset the preview item id before opening the new item
11337                workspace.active_pane().update(cx, |pane, cx| {
11338                    pane.set_preview_item_id(None, cx);
11339                });
11340                workspace.open_path_preview(path, None, true, true, cx)
11341            })?;
11342            let editor = editor
11343                .await?
11344                .downcast::<Editor>()
11345                .ok_or_else(|| anyhow!("opened item was not an editor"))?
11346                .downgrade();
11347            editor.update(&mut cx, |editor, cx| {
11348                let buffer = editor
11349                    .buffer()
11350                    .read(cx)
11351                    .as_singleton()
11352                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11353                let buffer = buffer.read(cx);
11354                let cursor = if buffer.can_resolve(&anchor) {
11355                    language::ToPoint::to_point(&anchor, buffer)
11356                } else {
11357                    buffer.clip_point(position, Bias::Left)
11358                };
11359
11360                let nav_history = editor.nav_history.take();
11361                editor.change_selections(
11362                    Some(Autoscroll::top_relative(offset_from_top as usize)),
11363                    cx,
11364                    |s| {
11365                        s.select_ranges([cursor..cursor]);
11366                    },
11367                );
11368                editor.nav_history = nav_history;
11369
11370                anyhow::Ok(())
11371            })??;
11372
11373            anyhow::Ok(())
11374        })
11375        .detach_and_log_err(cx);
11376    }
11377
11378    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11379        let snapshot = self.buffer.read(cx).read(cx);
11380        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11381        Some(
11382            ranges
11383                .iter()
11384                .map(move |range| {
11385                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11386                })
11387                .collect(),
11388        )
11389    }
11390
11391    fn selection_replacement_ranges(
11392        &self,
11393        range: Range<OffsetUtf16>,
11394        cx: &AppContext,
11395    ) -> Vec<Range<OffsetUtf16>> {
11396        let selections = self.selections.all::<OffsetUtf16>(cx);
11397        let newest_selection = selections
11398            .iter()
11399            .max_by_key(|selection| selection.id)
11400            .unwrap();
11401        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11402        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11403        let snapshot = self.buffer.read(cx).read(cx);
11404        selections
11405            .into_iter()
11406            .map(|mut selection| {
11407                selection.start.0 =
11408                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
11409                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11410                snapshot.clip_offset_utf16(selection.start, Bias::Left)
11411                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11412            })
11413            .collect()
11414    }
11415
11416    fn report_editor_event(
11417        &self,
11418        operation: &'static str,
11419        file_extension: Option<String>,
11420        cx: &AppContext,
11421    ) {
11422        if cfg!(any(test, feature = "test-support")) {
11423            return;
11424        }
11425
11426        let Some(project) = &self.project else { return };
11427
11428        // If None, we are in a file without an extension
11429        let file = self
11430            .buffer
11431            .read(cx)
11432            .as_singleton()
11433            .and_then(|b| b.read(cx).file());
11434        let file_extension = file_extension.or(file
11435            .as_ref()
11436            .and_then(|file| Path::new(file.file_name(cx)).extension())
11437            .and_then(|e| e.to_str())
11438            .map(|a| a.to_string()));
11439
11440        let vim_mode = cx
11441            .global::<SettingsStore>()
11442            .raw_user_settings()
11443            .get("vim_mode")
11444            == Some(&serde_json::Value::Bool(true));
11445
11446        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11447            == language::language_settings::InlineCompletionProvider::Copilot;
11448        let copilot_enabled_for_language = self
11449            .buffer
11450            .read(cx)
11451            .settings_at(0, cx)
11452            .show_inline_completions;
11453
11454        let telemetry = project.read(cx).client().telemetry().clone();
11455        telemetry.report_editor_event(
11456            file_extension,
11457            vim_mode,
11458            operation,
11459            copilot_enabled,
11460            copilot_enabled_for_language,
11461        )
11462    }
11463
11464    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11465    /// with each line being an array of {text, highlight} objects.
11466    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11467        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11468            return;
11469        };
11470
11471        #[derive(Serialize)]
11472        struct Chunk<'a> {
11473            text: String,
11474            highlight: Option<&'a str>,
11475        }
11476
11477        let snapshot = buffer.read(cx).snapshot();
11478        let range = self
11479            .selected_text_range(cx)
11480            .and_then(|selected_range| {
11481                if selected_range.is_empty() {
11482                    None
11483                } else {
11484                    Some(selected_range)
11485                }
11486            })
11487            .unwrap_or_else(|| 0..snapshot.len());
11488
11489        let chunks = snapshot.chunks(range, true);
11490        let mut lines = Vec::new();
11491        let mut line: VecDeque<Chunk> = VecDeque::new();
11492
11493        let Some(style) = self.style.as_ref() else {
11494            return;
11495        };
11496
11497        for chunk in chunks {
11498            let highlight = chunk
11499                .syntax_highlight_id
11500                .and_then(|id| id.name(&style.syntax));
11501            let mut chunk_lines = chunk.text.split('\n').peekable();
11502            while let Some(text) = chunk_lines.next() {
11503                let mut merged_with_last_token = false;
11504                if let Some(last_token) = line.back_mut() {
11505                    if last_token.highlight == highlight {
11506                        last_token.text.push_str(text);
11507                        merged_with_last_token = true;
11508                    }
11509                }
11510
11511                if !merged_with_last_token {
11512                    line.push_back(Chunk {
11513                        text: text.into(),
11514                        highlight,
11515                    });
11516                }
11517
11518                if chunk_lines.peek().is_some() {
11519                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
11520                        line.pop_front();
11521                    }
11522                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
11523                        line.pop_back();
11524                    }
11525
11526                    lines.push(mem::take(&mut line));
11527                }
11528            }
11529        }
11530
11531        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11532            return;
11533        };
11534        cx.write_to_clipboard(ClipboardItem::new(lines));
11535    }
11536
11537    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11538        &self.inlay_hint_cache
11539    }
11540
11541    pub fn replay_insert_event(
11542        &mut self,
11543        text: &str,
11544        relative_utf16_range: Option<Range<isize>>,
11545        cx: &mut ViewContext<Self>,
11546    ) {
11547        if !self.input_enabled {
11548            cx.emit(EditorEvent::InputIgnored { text: text.into() });
11549            return;
11550        }
11551        if let Some(relative_utf16_range) = relative_utf16_range {
11552            let selections = self.selections.all::<OffsetUtf16>(cx);
11553            self.change_selections(None, cx, |s| {
11554                let new_ranges = selections.into_iter().map(|range| {
11555                    let start = OffsetUtf16(
11556                        range
11557                            .head()
11558                            .0
11559                            .saturating_add_signed(relative_utf16_range.start),
11560                    );
11561                    let end = OffsetUtf16(
11562                        range
11563                            .head()
11564                            .0
11565                            .saturating_add_signed(relative_utf16_range.end),
11566                    );
11567                    start..end
11568                });
11569                s.select_ranges(new_ranges);
11570            });
11571        }
11572
11573        self.handle_input(text, cx);
11574    }
11575
11576    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11577        let Some(project) = self.project.as_ref() else {
11578            return false;
11579        };
11580        let project = project.read(cx);
11581
11582        let mut supports = false;
11583        self.buffer().read(cx).for_each_buffer(|buffer| {
11584            if !supports {
11585                supports = project
11586                    .language_servers_for_buffer(buffer.read(cx), cx)
11587                    .any(
11588                        |(_, server)| match server.capabilities().inlay_hint_provider {
11589                            Some(lsp::OneOf::Left(enabled)) => enabled,
11590                            Some(lsp::OneOf::Right(_)) => true,
11591                            None => false,
11592                        },
11593                    )
11594            }
11595        });
11596        supports
11597    }
11598
11599    pub fn focus(&self, cx: &mut WindowContext) {
11600        cx.focus(&self.focus_handle)
11601    }
11602
11603    pub fn is_focused(&self, cx: &WindowContext) -> bool {
11604        self.focus_handle.is_focused(cx)
11605    }
11606
11607    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11608        cx.emit(EditorEvent::Focused);
11609
11610        if let Some(descendant) = self
11611            .last_focused_descendant
11612            .take()
11613            .and_then(|descendant| descendant.upgrade())
11614        {
11615            cx.focus(&descendant);
11616        } else {
11617            if let Some(blame) = self.blame.as_ref() {
11618                blame.update(cx, GitBlame::focus)
11619            }
11620
11621            self.blink_manager.update(cx, BlinkManager::enable);
11622            self.show_cursor_names(cx);
11623            self.buffer.update(cx, |buffer, cx| {
11624                buffer.finalize_last_transaction(cx);
11625                if self.leader_peer_id.is_none() {
11626                    buffer.set_active_selections(
11627                        &self.selections.disjoint_anchors(),
11628                        self.selections.line_mode,
11629                        self.cursor_shape,
11630                        cx,
11631                    );
11632                }
11633            });
11634        }
11635    }
11636
11637    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
11638        cx.emit(EditorEvent::FocusedIn)
11639    }
11640
11641    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11642        if event.blurred != self.focus_handle {
11643            self.last_focused_descendant = Some(event.blurred);
11644        }
11645    }
11646
11647    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11648        self.blink_manager.update(cx, BlinkManager::disable);
11649        self.buffer
11650            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11651
11652        if let Some(blame) = self.blame.as_ref() {
11653            blame.update(cx, GitBlame::blur)
11654        }
11655        if !self.hover_state.focused(cx) {
11656            hide_hover(self, cx);
11657        }
11658
11659        self.hide_context_menu(cx);
11660        cx.emit(EditorEvent::Blurred);
11661        cx.notify();
11662    }
11663
11664    pub fn register_action<A: Action>(
11665        &mut self,
11666        listener: impl Fn(&A, &mut WindowContext) + 'static,
11667    ) -> Subscription {
11668        let id = self.next_editor_action_id.post_inc();
11669        let listener = Arc::new(listener);
11670        self.editor_actions.borrow_mut().insert(
11671            id,
11672            Box::new(move |cx| {
11673                let _view = cx.view().clone();
11674                let cx = cx.window_context();
11675                let listener = listener.clone();
11676                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11677                    let action = action.downcast_ref().unwrap();
11678                    if phase == DispatchPhase::Bubble {
11679                        listener(action, cx)
11680                    }
11681                })
11682            }),
11683        );
11684
11685        let editor_actions = self.editor_actions.clone();
11686        Subscription::new(move || {
11687            editor_actions.borrow_mut().remove(&id);
11688        })
11689    }
11690
11691    pub fn file_header_size(&self) -> u8 {
11692        self.file_header_size
11693    }
11694}
11695
11696fn hunks_for_selections(
11697    multi_buffer_snapshot: &MultiBufferSnapshot,
11698    selections: &[Selection<Anchor>],
11699) -> Vec<DiffHunk<MultiBufferRow>> {
11700    let mut hunks = Vec::with_capacity(selections.len());
11701    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11702        HashMap::default();
11703    let buffer_rows_for_selections = selections.iter().map(|selection| {
11704        let head = selection.head();
11705        let tail = selection.tail();
11706        let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11707        let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11708        if start > end {
11709            end..start
11710        } else {
11711            start..end
11712        }
11713    });
11714
11715    for selected_multi_buffer_rows in buffer_rows_for_selections {
11716        let query_rows =
11717            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11718        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11719            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11720            // when the caret is just above or just below the deleted hunk.
11721            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11722            let related_to_selection = if allow_adjacent {
11723                hunk.associated_range.overlaps(&query_rows)
11724                    || hunk.associated_range.start == query_rows.end
11725                    || hunk.associated_range.end == query_rows.start
11726            } else {
11727                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11728                // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11729                hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11730                    || selected_multi_buffer_rows.end == hunk.associated_range.start
11731            };
11732            if related_to_selection {
11733                if !processed_buffer_rows
11734                    .entry(hunk.buffer_id)
11735                    .or_default()
11736                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
11737                {
11738                    continue;
11739                }
11740                hunks.push(hunk);
11741            }
11742        }
11743    }
11744
11745    hunks
11746}
11747
11748pub trait CollaborationHub {
11749    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
11750    fn user_participant_indices<'a>(
11751        &self,
11752        cx: &'a AppContext,
11753    ) -> &'a HashMap<u64, ParticipantIndex>;
11754    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
11755}
11756
11757impl CollaborationHub for Model<Project> {
11758    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
11759        self.read(cx).collaborators()
11760    }
11761
11762    fn user_participant_indices<'a>(
11763        &self,
11764        cx: &'a AppContext,
11765    ) -> &'a HashMap<u64, ParticipantIndex> {
11766        self.read(cx).user_store().read(cx).participant_indices()
11767    }
11768
11769    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
11770        let this = self.read(cx);
11771        let user_ids = this.collaborators().values().map(|c| c.user_id);
11772        this.user_store().read_with(cx, |user_store, cx| {
11773            user_store.participant_names(user_ids, cx)
11774        })
11775    }
11776}
11777
11778pub trait CompletionProvider {
11779    fn completions(
11780        &self,
11781        buffer: &Model<Buffer>,
11782        buffer_position: text::Anchor,
11783        trigger: CompletionContext,
11784        cx: &mut ViewContext<Editor>,
11785    ) -> Task<Result<Vec<Completion>>>;
11786
11787    fn resolve_completions(
11788        &self,
11789        buffer: Model<Buffer>,
11790        completion_indices: Vec<usize>,
11791        completions: Arc<RwLock<Box<[Completion]>>>,
11792        cx: &mut ViewContext<Editor>,
11793    ) -> Task<Result<bool>>;
11794
11795    fn apply_additional_edits_for_completion(
11796        &self,
11797        buffer: Model<Buffer>,
11798        completion: Completion,
11799        push_to_history: bool,
11800        cx: &mut ViewContext<Editor>,
11801    ) -> Task<Result<Option<language::Transaction>>>;
11802
11803    fn is_completion_trigger(
11804        &self,
11805        buffer: &Model<Buffer>,
11806        position: language::Anchor,
11807        text: &str,
11808        trigger_in_words: bool,
11809        cx: &mut ViewContext<Editor>,
11810    ) -> bool;
11811}
11812
11813fn snippet_completions(
11814    project: &Project,
11815    buffer: &Model<Buffer>,
11816    buffer_position: text::Anchor,
11817    cx: &mut AppContext,
11818) -> Vec<Completion> {
11819    let language = buffer.read(cx).language_at(buffer_position);
11820    let language_name = language.as_ref().map(|language| language.lsp_id());
11821    let snippet_store = project.snippets().read(cx);
11822    let snippets = snippet_store.snippets_for(language_name, cx);
11823
11824    if snippets.is_empty() {
11825        return vec![];
11826    }
11827    let snapshot = buffer.read(cx).text_snapshot();
11828    let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
11829
11830    let mut lines = chunks.lines();
11831    let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
11832        return vec![];
11833    };
11834
11835    let scope = language.map(|language| language.default_scope());
11836    let mut last_word = line_at
11837        .chars()
11838        .rev()
11839        .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
11840        .collect::<String>();
11841    last_word = last_word.chars().rev().collect();
11842    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
11843    let to_lsp = |point: &text::Anchor| {
11844        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
11845        point_to_lsp(end)
11846    };
11847    let lsp_end = to_lsp(&buffer_position);
11848    snippets
11849        .into_iter()
11850        .filter_map(|snippet| {
11851            let matching_prefix = snippet
11852                .prefix
11853                .iter()
11854                .find(|prefix| prefix.starts_with(&last_word))?;
11855            let start = as_offset - last_word.len();
11856            let start = snapshot.anchor_before(start);
11857            let range = start..buffer_position;
11858            let lsp_start = to_lsp(&start);
11859            let lsp_range = lsp::Range {
11860                start: lsp_start,
11861                end: lsp_end,
11862            };
11863            Some(Completion {
11864                old_range: range,
11865                new_text: snippet.body.clone(),
11866                label: CodeLabel {
11867                    text: matching_prefix.clone(),
11868                    runs: vec![],
11869                    filter_range: 0..matching_prefix.len(),
11870                },
11871                server_id: LanguageServerId(usize::MAX),
11872                documentation: snippet
11873                    .description
11874                    .clone()
11875                    .map(|description| Documentation::SingleLine(description)),
11876                lsp_completion: lsp::CompletionItem {
11877                    label: snippet.prefix.first().unwrap().clone(),
11878                    kind: Some(CompletionItemKind::SNIPPET),
11879                    label_details: snippet.description.as_ref().map(|description| {
11880                        lsp::CompletionItemLabelDetails {
11881                            detail: Some(description.clone()),
11882                            description: None,
11883                        }
11884                    }),
11885                    insert_text_format: Some(InsertTextFormat::SNIPPET),
11886                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
11887                        lsp::InsertReplaceEdit {
11888                            new_text: snippet.body.clone(),
11889                            insert: lsp_range,
11890                            replace: lsp_range,
11891                        },
11892                    )),
11893                    filter_text: Some(snippet.body.clone()),
11894                    sort_text: Some(char::MAX.to_string()),
11895                    ..Default::default()
11896                },
11897                confirm: None,
11898                show_new_completions_on_confirm: false,
11899            })
11900        })
11901        .collect()
11902}
11903
11904impl CompletionProvider for Model<Project> {
11905    fn completions(
11906        &self,
11907        buffer: &Model<Buffer>,
11908        buffer_position: text::Anchor,
11909        options: CompletionContext,
11910        cx: &mut ViewContext<Editor>,
11911    ) -> Task<Result<Vec<Completion>>> {
11912        self.update(cx, |project, cx| {
11913            let snippets = snippet_completions(project, buffer, buffer_position, cx);
11914            let project_completions = project.completions(&buffer, buffer_position, options, cx);
11915            cx.background_executor().spawn(async move {
11916                let mut completions = project_completions.await?;
11917                //let snippets = snippets.into_iter().;
11918                completions.extend(snippets);
11919                Ok(completions)
11920            })
11921        })
11922    }
11923
11924    fn resolve_completions(
11925        &self,
11926        buffer: Model<Buffer>,
11927        completion_indices: Vec<usize>,
11928        completions: Arc<RwLock<Box<[Completion]>>>,
11929        cx: &mut ViewContext<Editor>,
11930    ) -> Task<Result<bool>> {
11931        self.update(cx, |project, cx| {
11932            project.resolve_completions(buffer, completion_indices, completions, cx)
11933        })
11934    }
11935
11936    fn apply_additional_edits_for_completion(
11937        &self,
11938        buffer: Model<Buffer>,
11939        completion: Completion,
11940        push_to_history: bool,
11941        cx: &mut ViewContext<Editor>,
11942    ) -> Task<Result<Option<language::Transaction>>> {
11943        self.update(cx, |project, cx| {
11944            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
11945        })
11946    }
11947
11948    fn is_completion_trigger(
11949        &self,
11950        buffer: &Model<Buffer>,
11951        position: language::Anchor,
11952        text: &str,
11953        trigger_in_words: bool,
11954        cx: &mut ViewContext<Editor>,
11955    ) -> bool {
11956        if !EditorSettings::get_global(cx).show_completions_on_input {
11957            return false;
11958        }
11959
11960        let mut chars = text.chars();
11961        let char = if let Some(char) = chars.next() {
11962            char
11963        } else {
11964            return false;
11965        };
11966        if chars.next().is_some() {
11967            return false;
11968        }
11969
11970        let buffer = buffer.read(cx);
11971        let scope = buffer.snapshot().language_scope_at(position);
11972        if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
11973            return true;
11974        }
11975
11976        buffer
11977            .completion_triggers()
11978            .iter()
11979            .any(|string| string == text)
11980    }
11981}
11982
11983fn inlay_hint_settings(
11984    location: Anchor,
11985    snapshot: &MultiBufferSnapshot,
11986    cx: &mut ViewContext<'_, Editor>,
11987) -> InlayHintSettings {
11988    let file = snapshot.file_at(location);
11989    let language = snapshot.language_at(location);
11990    let settings = all_language_settings(file, cx);
11991    settings
11992        .language(language.map(|l| l.name()).as_deref())
11993        .inlay_hints
11994}
11995
11996fn consume_contiguous_rows(
11997    contiguous_row_selections: &mut Vec<Selection<Point>>,
11998    selection: &Selection<Point>,
11999    display_map: &DisplaySnapshot,
12000    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12001) -> (MultiBufferRow, MultiBufferRow) {
12002    contiguous_row_selections.push(selection.clone());
12003    let start_row = MultiBufferRow(selection.start.row);
12004    let mut end_row = ending_row(selection, display_map);
12005
12006    while let Some(next_selection) = selections.peek() {
12007        if next_selection.start.row <= end_row.0 {
12008            end_row = ending_row(next_selection, display_map);
12009            contiguous_row_selections.push(selections.next().unwrap().clone());
12010        } else {
12011            break;
12012        }
12013    }
12014    (start_row, end_row)
12015}
12016
12017fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12018    if next_selection.end.column > 0 || next_selection.is_empty() {
12019        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12020    } else {
12021        MultiBufferRow(next_selection.end.row)
12022    }
12023}
12024
12025impl EditorSnapshot {
12026    pub fn remote_selections_in_range<'a>(
12027        &'a self,
12028        range: &'a Range<Anchor>,
12029        collaboration_hub: &dyn CollaborationHub,
12030        cx: &'a AppContext,
12031    ) -> impl 'a + Iterator<Item = RemoteSelection> {
12032        let participant_names = collaboration_hub.user_names(cx);
12033        let participant_indices = collaboration_hub.user_participant_indices(cx);
12034        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12035        let collaborators_by_replica_id = collaborators_by_peer_id
12036            .iter()
12037            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12038            .collect::<HashMap<_, _>>();
12039        self.buffer_snapshot
12040            .selections_in_range(range, false)
12041            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12042                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12043                let participant_index = participant_indices.get(&collaborator.user_id).copied();
12044                let user_name = participant_names.get(&collaborator.user_id).cloned();
12045                Some(RemoteSelection {
12046                    replica_id,
12047                    selection,
12048                    cursor_shape,
12049                    line_mode,
12050                    participant_index,
12051                    peer_id: collaborator.peer_id,
12052                    user_name,
12053                })
12054            })
12055    }
12056
12057    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12058        self.display_snapshot.buffer_snapshot.language_at(position)
12059    }
12060
12061    pub fn is_focused(&self) -> bool {
12062        self.is_focused
12063    }
12064
12065    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12066        self.placeholder_text.as_ref()
12067    }
12068
12069    pub fn scroll_position(&self) -> gpui::Point<f32> {
12070        self.scroll_anchor.scroll_position(&self.display_snapshot)
12071    }
12072
12073    pub fn gutter_dimensions(
12074        &self,
12075        font_id: FontId,
12076        font_size: Pixels,
12077        em_width: Pixels,
12078        max_line_number_width: Pixels,
12079        cx: &AppContext,
12080    ) -> GutterDimensions {
12081        if !self.show_gutter {
12082            return GutterDimensions::default();
12083        }
12084        let descent = cx.text_system().descent(font_id, font_size);
12085
12086        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12087            matches!(
12088                ProjectSettings::get_global(cx).git.git_gutter,
12089                Some(GitGutterSetting::TrackedFiles)
12090            )
12091        });
12092        let gutter_settings = EditorSettings::get_global(cx).gutter;
12093        let show_line_numbers = self
12094            .show_line_numbers
12095            .unwrap_or(gutter_settings.line_numbers);
12096        let line_gutter_width = if show_line_numbers {
12097            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12098            let min_width_for_number_on_gutter = em_width * 4.0;
12099            max_line_number_width.max(min_width_for_number_on_gutter)
12100        } else {
12101            0.0.into()
12102        };
12103
12104        let show_code_actions = self
12105            .show_code_actions
12106            .unwrap_or(gutter_settings.code_actions);
12107
12108        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12109
12110        let git_blame_entries_width = self
12111            .render_git_blame_gutter
12112            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12113
12114        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12115        left_padding += if show_code_actions || show_runnables {
12116            em_width * 3.0
12117        } else if show_git_gutter && show_line_numbers {
12118            em_width * 2.0
12119        } else if show_git_gutter || show_line_numbers {
12120            em_width
12121        } else {
12122            px(0.)
12123        };
12124
12125        let right_padding = if gutter_settings.folds && show_line_numbers {
12126            em_width * 4.0
12127        } else if gutter_settings.folds {
12128            em_width * 3.0
12129        } else if show_line_numbers {
12130            em_width
12131        } else {
12132            px(0.)
12133        };
12134
12135        GutterDimensions {
12136            left_padding,
12137            right_padding,
12138            width: line_gutter_width + left_padding + right_padding,
12139            margin: -descent,
12140            git_blame_entries_width,
12141        }
12142    }
12143
12144    pub fn render_fold_toggle(
12145        &self,
12146        buffer_row: MultiBufferRow,
12147        row_contains_cursor: bool,
12148        editor: View<Editor>,
12149        cx: &mut WindowContext,
12150    ) -> Option<AnyElement> {
12151        let folded = self.is_line_folded(buffer_row);
12152
12153        if let Some(crease) = self
12154            .crease_snapshot
12155            .query_row(buffer_row, &self.buffer_snapshot)
12156        {
12157            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12158                if folded {
12159                    editor.update(cx, |editor, cx| {
12160                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12161                    });
12162                } else {
12163                    editor.update(cx, |editor, cx| {
12164                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12165                    });
12166                }
12167            });
12168
12169            Some((crease.render_toggle)(
12170                buffer_row,
12171                folded,
12172                toggle_callback,
12173                cx,
12174            ))
12175        } else if folded
12176            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12177        {
12178            Some(
12179                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12180                    .selected(folded)
12181                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12182                        if folded {
12183                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
12184                        } else {
12185                            this.fold_at(&FoldAt { buffer_row }, cx);
12186                        }
12187                    }))
12188                    .into_any_element(),
12189            )
12190        } else {
12191            None
12192        }
12193    }
12194
12195    pub fn render_crease_trailer(
12196        &self,
12197        buffer_row: MultiBufferRow,
12198        cx: &mut WindowContext,
12199    ) -> Option<AnyElement> {
12200        let folded = self.is_line_folded(buffer_row);
12201        let crease = self
12202            .crease_snapshot
12203            .query_row(buffer_row, &self.buffer_snapshot)?;
12204        Some((crease.render_trailer)(buffer_row, folded, cx))
12205    }
12206}
12207
12208impl Deref for EditorSnapshot {
12209    type Target = DisplaySnapshot;
12210
12211    fn deref(&self) -> &Self::Target {
12212        &self.display_snapshot
12213    }
12214}
12215
12216#[derive(Clone, Debug, PartialEq, Eq)]
12217pub enum EditorEvent {
12218    InputIgnored {
12219        text: Arc<str>,
12220    },
12221    InputHandled {
12222        utf16_range_to_replace: Option<Range<isize>>,
12223        text: Arc<str>,
12224    },
12225    ExcerptsAdded {
12226        buffer: Model<Buffer>,
12227        predecessor: ExcerptId,
12228        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12229    },
12230    ExcerptsRemoved {
12231        ids: Vec<ExcerptId>,
12232    },
12233    ExcerptsEdited {
12234        ids: Vec<ExcerptId>,
12235    },
12236    ExcerptsExpanded {
12237        ids: Vec<ExcerptId>,
12238    },
12239    BufferEdited,
12240    Edited {
12241        transaction_id: clock::Lamport,
12242    },
12243    Reparsed(BufferId),
12244    Focused,
12245    FocusedIn,
12246    Blurred,
12247    DirtyChanged,
12248    Saved,
12249    TitleChanged,
12250    DiffBaseChanged,
12251    SelectionsChanged {
12252        local: bool,
12253    },
12254    ScrollPositionChanged {
12255        local: bool,
12256        autoscroll: bool,
12257    },
12258    Closed,
12259    TransactionUndone {
12260        transaction_id: clock::Lamport,
12261    },
12262    TransactionBegun {
12263        transaction_id: clock::Lamport,
12264    },
12265}
12266
12267impl EventEmitter<EditorEvent> for Editor {}
12268
12269impl FocusableView for Editor {
12270    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12271        self.focus_handle.clone()
12272    }
12273}
12274
12275impl Render for Editor {
12276    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12277        let settings = ThemeSettings::get_global(cx);
12278
12279        let text_style = match self.mode {
12280            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12281                color: cx.theme().colors().editor_foreground,
12282                font_family: settings.ui_font.family.clone(),
12283                font_features: settings.ui_font.features.clone(),
12284                font_size: rems(0.875).into(),
12285                font_weight: settings.ui_font.weight,
12286                font_style: FontStyle::Normal,
12287                line_height: relative(settings.buffer_line_height.value()),
12288                background_color: None,
12289                underline: None,
12290                strikethrough: None,
12291                white_space: WhiteSpace::Normal,
12292            },
12293            EditorMode::Full => TextStyle {
12294                color: cx.theme().colors().editor_foreground,
12295                font_family: settings.buffer_font.family.clone(),
12296                font_features: settings.buffer_font.features.clone(),
12297                font_size: settings.buffer_font_size(cx).into(),
12298                font_weight: settings.buffer_font.weight,
12299                font_style: FontStyle::Normal,
12300                line_height: relative(settings.buffer_line_height.value()),
12301                background_color: None,
12302                underline: None,
12303                strikethrough: None,
12304                white_space: WhiteSpace::Normal,
12305            },
12306        };
12307
12308        let background = match self.mode {
12309            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12310            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12311            EditorMode::Full => cx.theme().colors().editor_background,
12312        };
12313
12314        EditorElement::new(
12315            cx.view(),
12316            EditorStyle {
12317                background,
12318                local_player: cx.theme().players().local(),
12319                text: text_style,
12320                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12321                syntax: cx.theme().syntax().clone(),
12322                status: cx.theme().status().clone(),
12323                inlay_hints_style: HighlightStyle {
12324                    color: Some(cx.theme().status().hint),
12325                    ..HighlightStyle::default()
12326                },
12327                suggestions_style: HighlightStyle {
12328                    color: Some(cx.theme().status().predictive),
12329                    ..HighlightStyle::default()
12330                },
12331            },
12332        )
12333    }
12334}
12335
12336impl ViewInputHandler for Editor {
12337    fn text_for_range(
12338        &mut self,
12339        range_utf16: Range<usize>,
12340        cx: &mut ViewContext<Self>,
12341    ) -> Option<String> {
12342        Some(
12343            self.buffer
12344                .read(cx)
12345                .read(cx)
12346                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12347                .collect(),
12348        )
12349    }
12350
12351    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12352        // Prevent the IME menu from appearing when holding down an alphabetic key
12353        // while input is disabled.
12354        if !self.input_enabled {
12355            return None;
12356        }
12357
12358        let range = self.selections.newest::<OffsetUtf16>(cx).range();
12359        Some(range.start.0..range.end.0)
12360    }
12361
12362    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12363        let snapshot = self.buffer.read(cx).read(cx);
12364        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12365        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12366    }
12367
12368    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12369        self.clear_highlights::<InputComposition>(cx);
12370        self.ime_transaction.take();
12371    }
12372
12373    fn replace_text_in_range(
12374        &mut self,
12375        range_utf16: Option<Range<usize>>,
12376        text: &str,
12377        cx: &mut ViewContext<Self>,
12378    ) {
12379        if !self.input_enabled {
12380            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12381            return;
12382        }
12383
12384        self.transact(cx, |this, cx| {
12385            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12386                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12387                Some(this.selection_replacement_ranges(range_utf16, cx))
12388            } else {
12389                this.marked_text_ranges(cx)
12390            };
12391
12392            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12393                let newest_selection_id = this.selections.newest_anchor().id;
12394                this.selections
12395                    .all::<OffsetUtf16>(cx)
12396                    .iter()
12397                    .zip(ranges_to_replace.iter())
12398                    .find_map(|(selection, range)| {
12399                        if selection.id == newest_selection_id {
12400                            Some(
12401                                (range.start.0 as isize - selection.head().0 as isize)
12402                                    ..(range.end.0 as isize - selection.head().0 as isize),
12403                            )
12404                        } else {
12405                            None
12406                        }
12407                    })
12408            });
12409
12410            cx.emit(EditorEvent::InputHandled {
12411                utf16_range_to_replace: range_to_replace,
12412                text: text.into(),
12413            });
12414
12415            if let Some(new_selected_ranges) = new_selected_ranges {
12416                this.change_selections(None, cx, |selections| {
12417                    selections.select_ranges(new_selected_ranges)
12418                });
12419                this.backspace(&Default::default(), cx);
12420            }
12421
12422            this.handle_input(text, cx);
12423        });
12424
12425        if let Some(transaction) = self.ime_transaction {
12426            self.buffer.update(cx, |buffer, cx| {
12427                buffer.group_until_transaction(transaction, cx);
12428            });
12429        }
12430
12431        self.unmark_text(cx);
12432    }
12433
12434    fn replace_and_mark_text_in_range(
12435        &mut self,
12436        range_utf16: Option<Range<usize>>,
12437        text: &str,
12438        new_selected_range_utf16: Option<Range<usize>>,
12439        cx: &mut ViewContext<Self>,
12440    ) {
12441        if !self.input_enabled {
12442            return;
12443        }
12444
12445        let transaction = self.transact(cx, |this, cx| {
12446            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12447                let snapshot = this.buffer.read(cx).read(cx);
12448                if let Some(relative_range_utf16) = range_utf16.as_ref() {
12449                    for marked_range in &mut marked_ranges {
12450                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12451                        marked_range.start.0 += relative_range_utf16.start;
12452                        marked_range.start =
12453                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12454                        marked_range.end =
12455                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12456                    }
12457                }
12458                Some(marked_ranges)
12459            } else if let Some(range_utf16) = range_utf16 {
12460                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12461                Some(this.selection_replacement_ranges(range_utf16, cx))
12462            } else {
12463                None
12464            };
12465
12466            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12467                let newest_selection_id = this.selections.newest_anchor().id;
12468                this.selections
12469                    .all::<OffsetUtf16>(cx)
12470                    .iter()
12471                    .zip(ranges_to_replace.iter())
12472                    .find_map(|(selection, range)| {
12473                        if selection.id == newest_selection_id {
12474                            Some(
12475                                (range.start.0 as isize - selection.head().0 as isize)
12476                                    ..(range.end.0 as isize - selection.head().0 as isize),
12477                            )
12478                        } else {
12479                            None
12480                        }
12481                    })
12482            });
12483
12484            cx.emit(EditorEvent::InputHandled {
12485                utf16_range_to_replace: range_to_replace,
12486                text: text.into(),
12487            });
12488
12489            if let Some(ranges) = ranges_to_replace {
12490                this.change_selections(None, cx, |s| s.select_ranges(ranges));
12491            }
12492
12493            let marked_ranges = {
12494                let snapshot = this.buffer.read(cx).read(cx);
12495                this.selections
12496                    .disjoint_anchors()
12497                    .iter()
12498                    .map(|selection| {
12499                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12500                    })
12501                    .collect::<Vec<_>>()
12502            };
12503
12504            if text.is_empty() {
12505                this.unmark_text(cx);
12506            } else {
12507                this.highlight_text::<InputComposition>(
12508                    marked_ranges.clone(),
12509                    HighlightStyle {
12510                        underline: Some(UnderlineStyle {
12511                            thickness: px(1.),
12512                            color: None,
12513                            wavy: false,
12514                        }),
12515                        ..Default::default()
12516                    },
12517                    cx,
12518                );
12519            }
12520
12521            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12522            let use_autoclose = this.use_autoclose;
12523            let use_auto_surround = this.use_auto_surround;
12524            this.set_use_autoclose(false);
12525            this.set_use_auto_surround(false);
12526            this.handle_input(text, cx);
12527            this.set_use_autoclose(use_autoclose);
12528            this.set_use_auto_surround(use_auto_surround);
12529
12530            if let Some(new_selected_range) = new_selected_range_utf16 {
12531                let snapshot = this.buffer.read(cx).read(cx);
12532                let new_selected_ranges = marked_ranges
12533                    .into_iter()
12534                    .map(|marked_range| {
12535                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12536                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12537                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12538                        snapshot.clip_offset_utf16(new_start, Bias::Left)
12539                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12540                    })
12541                    .collect::<Vec<_>>();
12542
12543                drop(snapshot);
12544                this.change_selections(None, cx, |selections| {
12545                    selections.select_ranges(new_selected_ranges)
12546                });
12547            }
12548        });
12549
12550        self.ime_transaction = self.ime_transaction.or(transaction);
12551        if let Some(transaction) = self.ime_transaction {
12552            self.buffer.update(cx, |buffer, cx| {
12553                buffer.group_until_transaction(transaction, cx);
12554            });
12555        }
12556
12557        if self.text_highlights::<InputComposition>(cx).is_none() {
12558            self.ime_transaction.take();
12559        }
12560    }
12561
12562    fn bounds_for_range(
12563        &mut self,
12564        range_utf16: Range<usize>,
12565        element_bounds: gpui::Bounds<Pixels>,
12566        cx: &mut ViewContext<Self>,
12567    ) -> Option<gpui::Bounds<Pixels>> {
12568        let text_layout_details = self.text_layout_details(cx);
12569        let style = &text_layout_details.editor_style;
12570        let font_id = cx.text_system().resolve_font(&style.text.font());
12571        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12572        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12573
12574        let em_width = cx
12575            .text_system()
12576            .typographic_bounds(font_id, font_size, 'm')
12577            .unwrap()
12578            .size
12579            .width;
12580
12581        let snapshot = self.snapshot(cx);
12582        let scroll_position = snapshot.scroll_position();
12583        let scroll_left = scroll_position.x * em_width;
12584
12585        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12586        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12587            + self.gutter_dimensions.width;
12588        let y = line_height * (start.row().as_f32() - scroll_position.y);
12589
12590        Some(Bounds {
12591            origin: element_bounds.origin + point(x, y),
12592            size: size(em_width, line_height),
12593        })
12594    }
12595}
12596
12597trait SelectionExt {
12598    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12599    fn spanned_rows(
12600        &self,
12601        include_end_if_at_line_start: bool,
12602        map: &DisplaySnapshot,
12603    ) -> Range<MultiBufferRow>;
12604}
12605
12606impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12607    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12608        let start = self
12609            .start
12610            .to_point(&map.buffer_snapshot)
12611            .to_display_point(map);
12612        let end = self
12613            .end
12614            .to_point(&map.buffer_snapshot)
12615            .to_display_point(map);
12616        if self.reversed {
12617            end..start
12618        } else {
12619            start..end
12620        }
12621    }
12622
12623    fn spanned_rows(
12624        &self,
12625        include_end_if_at_line_start: bool,
12626        map: &DisplaySnapshot,
12627    ) -> Range<MultiBufferRow> {
12628        let start = self.start.to_point(&map.buffer_snapshot);
12629        let mut end = self.end.to_point(&map.buffer_snapshot);
12630        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12631            end.row -= 1;
12632        }
12633
12634        let buffer_start = map.prev_line_boundary(start).0;
12635        let buffer_end = map.next_line_boundary(end).0;
12636        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12637    }
12638}
12639
12640impl<T: InvalidationRegion> InvalidationStack<T> {
12641    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12642    where
12643        S: Clone + ToOffset,
12644    {
12645        while let Some(region) = self.last() {
12646            let all_selections_inside_invalidation_ranges =
12647                if selections.len() == region.ranges().len() {
12648                    selections
12649                        .iter()
12650                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12651                        .all(|(selection, invalidation_range)| {
12652                            let head = selection.head().to_offset(buffer);
12653                            invalidation_range.start <= head && invalidation_range.end >= head
12654                        })
12655                } else {
12656                    false
12657                };
12658
12659            if all_selections_inside_invalidation_ranges {
12660                break;
12661            } else {
12662                self.pop();
12663            }
12664        }
12665    }
12666}
12667
12668impl<T> Default for InvalidationStack<T> {
12669    fn default() -> Self {
12670        Self(Default::default())
12671    }
12672}
12673
12674impl<T> Deref for InvalidationStack<T> {
12675    type Target = Vec<T>;
12676
12677    fn deref(&self) -> &Self::Target {
12678        &self.0
12679    }
12680}
12681
12682impl<T> DerefMut for InvalidationStack<T> {
12683    fn deref_mut(&mut self) -> &mut Self::Target {
12684        &mut self.0
12685    }
12686}
12687
12688impl InvalidationRegion for SnippetState {
12689    fn ranges(&self) -> &[Range<Anchor>] {
12690        &self.ranges[self.active_index]
12691    }
12692}
12693
12694pub fn diagnostic_block_renderer(
12695    diagnostic: Diagnostic,
12696    max_message_rows: Option<u8>,
12697    allow_closing: bool,
12698    _is_valid: bool,
12699) -> RenderBlock {
12700    let (text_without_backticks, code_ranges) =
12701        highlight_diagnostic_message(&diagnostic, max_message_rows);
12702
12703    Box::new(move |cx: &mut BlockContext| {
12704        let group_id: SharedString = cx.transform_block_id.to_string().into();
12705
12706        let mut text_style = cx.text_style().clone();
12707        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
12708        let theme_settings = ThemeSettings::get_global(cx);
12709        text_style.font_family = theme_settings.buffer_font.family.clone();
12710        text_style.font_style = theme_settings.buffer_font.style;
12711        text_style.font_features = theme_settings.buffer_font.features.clone();
12712        text_style.font_weight = theme_settings.buffer_font.weight;
12713
12714        let multi_line_diagnostic = diagnostic.message.contains('\n');
12715
12716        let buttons = |diagnostic: &Diagnostic, block_id: TransformBlockId| {
12717            if multi_line_diagnostic {
12718                v_flex()
12719            } else {
12720                h_flex()
12721            }
12722            .when(allow_closing, |div| {
12723                div.children(diagnostic.is_primary.then(|| {
12724                    IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
12725                        .icon_color(Color::Muted)
12726                        .size(ButtonSize::Compact)
12727                        .style(ButtonStyle::Transparent)
12728                        .visible_on_hover(group_id.clone())
12729                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
12730                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
12731                }))
12732            })
12733            .child(
12734                IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
12735                    .icon_color(Color::Muted)
12736                    .size(ButtonSize::Compact)
12737                    .style(ButtonStyle::Transparent)
12738                    .visible_on_hover(group_id.clone())
12739                    .on_click({
12740                        let message = diagnostic.message.clone();
12741                        move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
12742                    })
12743                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
12744            )
12745        };
12746
12747        let icon_size = buttons(&diagnostic, cx.transform_block_id)
12748            .into_any_element()
12749            .layout_as_root(AvailableSpace::min_size(), cx);
12750
12751        h_flex()
12752            .id(cx.transform_block_id)
12753            .group(group_id.clone())
12754            .relative()
12755            .size_full()
12756            .pl(cx.gutter_dimensions.width)
12757            .w(cx.max_width + cx.gutter_dimensions.width)
12758            .child(
12759                div()
12760                    .flex()
12761                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
12762                    .flex_shrink(),
12763            )
12764            .child(buttons(&diagnostic, cx.transform_block_id))
12765            .child(div().flex().flex_shrink_0().child(
12766                StyledText::new(text_without_backticks.clone()).with_highlights(
12767                    &text_style,
12768                    code_ranges.iter().map(|range| {
12769                        (
12770                            range.clone(),
12771                            HighlightStyle {
12772                                font_weight: Some(FontWeight::BOLD),
12773                                ..Default::default()
12774                            },
12775                        )
12776                    }),
12777                ),
12778            ))
12779            .into_any_element()
12780    })
12781}
12782
12783pub fn highlight_diagnostic_message(
12784    diagnostic: &Diagnostic,
12785    mut max_message_rows: Option<u8>,
12786) -> (SharedString, Vec<Range<usize>>) {
12787    let mut text_without_backticks = String::new();
12788    let mut code_ranges = Vec::new();
12789
12790    if let Some(source) = &diagnostic.source {
12791        text_without_backticks.push_str(&source);
12792        code_ranges.push(0..source.len());
12793        text_without_backticks.push_str(": ");
12794    }
12795
12796    let mut prev_offset = 0;
12797    let mut in_code_block = false;
12798    let mut newline_indices = diagnostic
12799        .message
12800        .match_indices('\n')
12801        .map(|(ix, _)| ix)
12802        .fuse()
12803        .peekable();
12804    for (ix, _) in diagnostic
12805        .message
12806        .match_indices('`')
12807        .chain([(diagnostic.message.len(), "")])
12808    {
12809        let mut trimmed_ix = ix;
12810        while let Some(newline_index) = newline_indices.peek() {
12811            if *newline_index < ix {
12812                if let Some(rows_left) = &mut max_message_rows {
12813                    if *rows_left == 0 {
12814                        trimmed_ix = newline_index.saturating_sub(1);
12815                        break;
12816                    } else {
12817                        *rows_left -= 1;
12818                    }
12819                }
12820                let _ = newline_indices.next();
12821            } else {
12822                break;
12823            }
12824        }
12825        let prev_len = text_without_backticks.len();
12826        let new_text = &diagnostic.message[prev_offset..trimmed_ix];
12827        text_without_backticks.push_str(new_text);
12828        if in_code_block {
12829            code_ranges.push(prev_len..text_without_backticks.len());
12830        }
12831        prev_offset = trimmed_ix + 1;
12832        in_code_block = !in_code_block;
12833        if trimmed_ix != ix {
12834            text_without_backticks.push_str("...");
12835            break;
12836        }
12837    }
12838
12839    (text_without_backticks.into(), code_ranges)
12840}
12841
12842fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
12843    match severity {
12844        DiagnosticSeverity::ERROR => colors.error,
12845        DiagnosticSeverity::WARNING => colors.warning,
12846        DiagnosticSeverity::INFORMATION => colors.info,
12847        DiagnosticSeverity::HINT => colors.info,
12848        _ => colors.ignored,
12849    }
12850}
12851
12852pub fn styled_runs_for_code_label<'a>(
12853    label: &'a CodeLabel,
12854    syntax_theme: &'a theme::SyntaxTheme,
12855) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
12856    let fade_out = HighlightStyle {
12857        fade_out: Some(0.35),
12858        ..Default::default()
12859    };
12860
12861    let mut prev_end = label.filter_range.end;
12862    label
12863        .runs
12864        .iter()
12865        .enumerate()
12866        .flat_map(move |(ix, (range, highlight_id))| {
12867            let style = if let Some(style) = highlight_id.style(syntax_theme) {
12868                style
12869            } else {
12870                return Default::default();
12871            };
12872            let mut muted_style = style;
12873            muted_style.highlight(fade_out);
12874
12875            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
12876            if range.start >= label.filter_range.end {
12877                if range.start > prev_end {
12878                    runs.push((prev_end..range.start, fade_out));
12879                }
12880                runs.push((range.clone(), muted_style));
12881            } else if range.end <= label.filter_range.end {
12882                runs.push((range.clone(), style));
12883            } else {
12884                runs.push((range.start..label.filter_range.end, style));
12885                runs.push((label.filter_range.end..range.end, muted_style));
12886            }
12887            prev_end = cmp::max(prev_end, range.end);
12888
12889            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
12890                runs.push((prev_end..label.text.len(), fade_out));
12891            }
12892
12893            runs
12894        })
12895}
12896
12897pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
12898    let mut prev_index = 0;
12899    let mut prev_codepoint: Option<char> = None;
12900    text.char_indices()
12901        .chain([(text.len(), '\0')])
12902        .filter_map(move |(index, codepoint)| {
12903            let prev_codepoint = prev_codepoint.replace(codepoint)?;
12904            let is_boundary = index == text.len()
12905                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
12906                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
12907            if is_boundary {
12908                let chunk = &text[prev_index..index];
12909                prev_index = index;
12910                Some(chunk)
12911            } else {
12912                None
12913            }
12914        })
12915}
12916
12917pub trait RangeToAnchorExt {
12918    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
12919}
12920
12921impl<T: ToOffset> RangeToAnchorExt for Range<T> {
12922    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
12923        let start_offset = self.start.to_offset(snapshot);
12924        let end_offset = self.end.to_offset(snapshot);
12925        if start_offset == end_offset {
12926            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
12927        } else {
12928            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
12929        }
12930    }
12931}
12932
12933pub trait RowExt {
12934    fn as_f32(&self) -> f32;
12935
12936    fn next_row(&self) -> Self;
12937
12938    fn previous_row(&self) -> Self;
12939
12940    fn minus(&self, other: Self) -> u32;
12941}
12942
12943impl RowExt for DisplayRow {
12944    fn as_f32(&self) -> f32 {
12945        self.0 as f32
12946    }
12947
12948    fn next_row(&self) -> Self {
12949        Self(self.0 + 1)
12950    }
12951
12952    fn previous_row(&self) -> Self {
12953        Self(self.0.saturating_sub(1))
12954    }
12955
12956    fn minus(&self, other: Self) -> u32 {
12957        self.0 - other.0
12958    }
12959}
12960
12961impl RowExt for MultiBufferRow {
12962    fn as_f32(&self) -> f32 {
12963        self.0 as f32
12964    }
12965
12966    fn next_row(&self) -> Self {
12967        Self(self.0 + 1)
12968    }
12969
12970    fn previous_row(&self) -> Self {
12971        Self(self.0.saturating_sub(1))
12972    }
12973
12974    fn minus(&self, other: Self) -> u32 {
12975        self.0 - other.0
12976    }
12977}
12978
12979trait RowRangeExt {
12980    type Row;
12981
12982    fn len(&self) -> usize;
12983
12984    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
12985}
12986
12987impl RowRangeExt for Range<MultiBufferRow> {
12988    type Row = MultiBufferRow;
12989
12990    fn len(&self) -> usize {
12991        (self.end.0 - self.start.0) as usize
12992    }
12993
12994    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
12995        (self.start.0..self.end.0).map(MultiBufferRow)
12996    }
12997}
12998
12999impl RowRangeExt for Range<DisplayRow> {
13000    type Row = DisplayRow;
13001
13002    fn len(&self) -> usize {
13003        (self.end.0 - self.start.0) as usize
13004    }
13005
13006    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13007        (self.start.0..self.end.0).map(DisplayRow)
13008    }
13009}
13010
13011fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13012    if hunk.diff_base_byte_range.is_empty() {
13013        DiffHunkStatus::Added
13014    } else if hunk.associated_range.is_empty() {
13015        DiffHunkStatus::Removed
13016    } else {
13017        DiffHunkStatus::Modified
13018    }
13019}