editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behaviour.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod debounced_delay;
   19pub mod display_map;
   20mod editor_settings;
   21mod element;
   22mod git;
   23mod highlight_matching_bracket;
   24mod hover_links;
   25mod hover_popover;
   26mod hunk_diff;
   27mod indent_guides;
   28mod inlay_hint_cache;
   29mod inline_completion_provider;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod mouse_context_menu;
   33pub mod movement;
   34mod persistence;
   35mod rust_analyzer_ext;
   36pub mod scroll;
   37mod selections_collection;
   38pub mod tasks;
   39
   40#[cfg(test)]
   41mod editor_tests;
   42#[cfg(any(test, feature = "test-support"))]
   43pub mod test;
   44use ::git::diff::{DiffHunk, DiffHunkStatus};
   45use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
   46pub(crate) use actions::*;
   47use aho_corasick::AhoCorasick;
   48use anyhow::{anyhow, Context as _, Result};
   49use blink_manager::BlinkManager;
   50use client::{Collaborator, ParticipantIndex};
   51use clock::ReplicaId;
   52use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   53use convert_case::{Case, Casing};
   54use debounced_delay::DebouncedDelay;
   55use display_map::*;
   56pub use display_map::{DisplayPoint, FoldPlaceholder};
   57pub use editor_settings::{CurrentLineHighlight, EditorSettings};
   58use element::LineWithInvisibles;
   59pub use element::{
   60    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   61};
   62use futures::FutureExt;
   63use fuzzy::{StringMatch, StringMatchCandidate};
   64use git::blame::GitBlame;
   65use git::diff_hunk_to_display;
   66use gpui::{
   67    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   68    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardItem,
   69    Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView,
   70    FontId, FontStyle, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext,
   71    ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString,
   72    Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle, UnderlineStyle,
   73    UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
   74    WeakView, WhiteSpace, WindowContext,
   75};
   76use highlight_matching_bracket::refresh_matching_bracket_highlights;
   77use hover_popover::{hide_hover, HoverState};
   78use hunk_diff::ExpandedHunks;
   79pub(crate) use hunk_diff::HunkToExpand;
   80use indent_guides::ActiveIndentGuidesState;
   81use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   82pub use inline_completion_provider::*;
   83pub use items::MAX_TAB_TITLE_LEN;
   84use itertools::Itertools;
   85use language::{
   86    char_kind,
   87    language_settings::{self, all_language_settings, InlayHintSettings},
   88    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   89    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   90    Point, Selection, SelectionGoal, TransactionId,
   91};
   92use language::{point_to_lsp, BufferRow, Runnable, RunnableRange};
   93use linked_editing_ranges::refresh_linked_ranges;
   94use task::{ResolvedTask, TaskTemplate, TaskVariables};
   95
   96use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
   97pub use lsp::CompletionContext;
   98use lsp::{
   99    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  100    LanguageServerId,
  101};
  102use mouse_context_menu::MouseContextMenu;
  103use movement::TextLayoutDetails;
  104pub use multi_buffer::{
  105    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  106    ToPoint,
  107};
  108use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
  109use ordered_float::OrderedFloat;
  110use parking_lot::{Mutex, RwLock};
  111use project::project_settings::{GitGutterSetting, ProjectSettings};
  112use project::{
  113    CodeAction, Completion, FormatTrigger, Item, Location, Project, ProjectPath,
  114    ProjectTransaction, TaskSourceKind, WorktreeId,
  115};
  116use rand::prelude::*;
  117use rpc::{proto::*, ErrorExt};
  118use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  119use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  120use serde::{Deserialize, Serialize};
  121use settings::{update_settings_file, Settings, SettingsStore};
  122use smallvec::SmallVec;
  123use snippet::Snippet;
  124use std::{
  125    any::TypeId,
  126    borrow::Cow,
  127    cell::RefCell,
  128    cmp::{self, Ordering, Reverse},
  129    mem,
  130    num::NonZeroU32,
  131    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  132    path::Path,
  133    rc::Rc,
  134    sync::Arc,
  135    time::{Duration, Instant},
  136};
  137pub use sum_tree::Bias;
  138use sum_tree::TreeMap;
  139use text::{BufferId, OffsetUtf16, Rope};
  140use theme::{
  141    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  142    ThemeColors, ThemeSettings,
  143};
  144use ui::{
  145    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  146    ListItem, Popover, Tooltip,
  147};
  148use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  149use workspace::item::{ItemHandle, PreviewTabsSettings};
  150use workspace::notifications::{DetachAndPromptErr, NotificationId};
  151use workspace::{
  152    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  153};
  154use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  155
  156use crate::hover_links::find_url;
  157
  158pub const FILE_HEADER_HEIGHT: u8 = 1;
  159pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u8 = 1;
  160pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u8 = 1;
  161pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  162const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  163const MAX_LINE_LEN: usize = 1024;
  164const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  165const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  166pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  167#[doc(hidden)]
  168pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  169#[doc(hidden)]
  170pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  171
  172pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  173
  174pub fn render_parsed_markdown(
  175    element_id: impl Into<ElementId>,
  176    parsed: &language::ParsedMarkdown,
  177    editor_style: &EditorStyle,
  178    workspace: Option<WeakView<Workspace>>,
  179    cx: &mut WindowContext,
  180) -> InteractiveText {
  181    let code_span_background_color = cx
  182        .theme()
  183        .colors()
  184        .editor_document_highlight_read_background;
  185
  186    let highlights = gpui::combine_highlights(
  187        parsed.highlights.iter().filter_map(|(range, highlight)| {
  188            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  189            Some((range.clone(), highlight))
  190        }),
  191        parsed
  192            .regions
  193            .iter()
  194            .zip(&parsed.region_ranges)
  195            .filter_map(|(region, range)| {
  196                if region.code {
  197                    Some((
  198                        range.clone(),
  199                        HighlightStyle {
  200                            background_color: Some(code_span_background_color),
  201                            ..Default::default()
  202                        },
  203                    ))
  204                } else {
  205                    None
  206                }
  207            }),
  208    );
  209
  210    let mut links = Vec::new();
  211    let mut link_ranges = Vec::new();
  212    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  213        if let Some(link) = region.link.clone() {
  214            links.push(link);
  215            link_ranges.push(range.clone());
  216        }
  217    }
  218
  219    InteractiveText::new(
  220        element_id,
  221        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  222    )
  223    .on_click(link_ranges, move |clicked_range_ix, cx| {
  224        match &links[clicked_range_ix] {
  225            markdown::Link::Web { url } => cx.open_url(url),
  226            markdown::Link::Path { path } => {
  227                if let Some(workspace) = &workspace {
  228                    _ = workspace.update(cx, |workspace, cx| {
  229                        workspace.open_abs_path(path.clone(), false, cx).detach();
  230                    });
  231                }
  232            }
  233        }
  234    })
  235}
  236
  237#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  238pub(crate) enum InlayId {
  239    Suggestion(usize),
  240    Hint(usize),
  241}
  242
  243impl InlayId {
  244    fn id(&self) -> usize {
  245        match self {
  246            Self::Suggestion(id) => *id,
  247            Self::Hint(id) => *id,
  248        }
  249    }
  250}
  251
  252enum DiffRowHighlight {}
  253enum DocumentHighlightRead {}
  254enum DocumentHighlightWrite {}
  255enum InputComposition {}
  256
  257#[derive(Copy, Clone, PartialEq, Eq)]
  258pub enum Direction {
  259    Prev,
  260    Next,
  261}
  262
  263pub fn init_settings(cx: &mut AppContext) {
  264    EditorSettings::register(cx);
  265}
  266
  267pub fn init(cx: &mut AppContext) {
  268    init_settings(cx);
  269
  270    workspace::register_project_item::<Editor>(cx);
  271    workspace::register_followable_item::<Editor>(cx);
  272    workspace::register_deserializable_item::<Editor>(cx);
  273    cx.observe_new_views(
  274        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  275            workspace.register_action(Editor::new_file);
  276            workspace.register_action(Editor::new_file_in_direction);
  277        },
  278    )
  279    .detach();
  280
  281    cx.on_action(move |_: &workspace::NewFile, cx| {
  282        let app_state = workspace::AppState::global(cx);
  283        if let Some(app_state) = app_state.upgrade() {
  284            workspace::open_new(app_state, cx, |workspace, cx| {
  285                Editor::new_file(workspace, &Default::default(), cx)
  286            })
  287            .detach();
  288        }
  289    });
  290    cx.on_action(move |_: &workspace::NewWindow, cx| {
  291        let app_state = workspace::AppState::global(cx);
  292        if let Some(app_state) = app_state.upgrade() {
  293            workspace::open_new(app_state, cx, |workspace, cx| {
  294                Editor::new_file(workspace, &Default::default(), cx)
  295            })
  296            .detach();
  297        }
  298    });
  299}
  300
  301pub struct SearchWithinRange;
  302
  303trait InvalidationRegion {
  304    fn ranges(&self) -> &[Range<Anchor>];
  305}
  306
  307#[derive(Clone, Debug, PartialEq)]
  308pub enum SelectPhase {
  309    Begin {
  310        position: DisplayPoint,
  311        add: bool,
  312        click_count: usize,
  313    },
  314    BeginColumnar {
  315        position: DisplayPoint,
  316        reset: bool,
  317        goal_column: u32,
  318    },
  319    Extend {
  320        position: DisplayPoint,
  321        click_count: usize,
  322    },
  323    Update {
  324        position: DisplayPoint,
  325        goal_column: u32,
  326        scroll_delta: gpui::Point<f32>,
  327    },
  328    End,
  329}
  330
  331#[derive(Clone, Debug)]
  332pub enum SelectMode {
  333    Character,
  334    Word(Range<Anchor>),
  335    Line(Range<Anchor>),
  336    All,
  337}
  338
  339#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  340pub enum EditorMode {
  341    SingleLine { auto_width: bool },
  342    AutoHeight { max_lines: usize },
  343    Full,
  344}
  345
  346#[derive(Clone, Debug)]
  347pub enum SoftWrap {
  348    None,
  349    PreferLine,
  350    EditorWidth,
  351    Column(u32),
  352}
  353
  354#[derive(Clone)]
  355pub struct EditorStyle {
  356    pub background: Hsla,
  357    pub local_player: PlayerColor,
  358    pub text: TextStyle,
  359    pub scrollbar_width: Pixels,
  360    pub syntax: Arc<SyntaxTheme>,
  361    pub status: StatusColors,
  362    pub inlay_hints_style: HighlightStyle,
  363    pub suggestions_style: HighlightStyle,
  364}
  365
  366impl Default for EditorStyle {
  367    fn default() -> Self {
  368        Self {
  369            background: Hsla::default(),
  370            local_player: PlayerColor::default(),
  371            text: TextStyle::default(),
  372            scrollbar_width: Pixels::default(),
  373            syntax: Default::default(),
  374            // HACK: Status colors don't have a real default.
  375            // We should look into removing the status colors from the editor
  376            // style and retrieve them directly from the theme.
  377            status: StatusColors::dark(),
  378            inlay_hints_style: HighlightStyle::default(),
  379            suggestions_style: HighlightStyle::default(),
  380        }
  381    }
  382}
  383
  384type CompletionId = usize;
  385
  386#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  387struct EditorActionId(usize);
  388
  389impl EditorActionId {
  390    pub fn post_inc(&mut self) -> Self {
  391        let answer = self.0;
  392
  393        *self = Self(answer + 1);
  394
  395        Self(answer)
  396    }
  397}
  398
  399// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  400// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  401
  402type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  403type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  404
  405struct ScrollbarMarkerState {
  406    scrollbar_size: Size<Pixels>,
  407    dirty: bool,
  408    markers: Arc<[PaintQuad]>,
  409    pending_refresh: Option<Task<Result<()>>>,
  410}
  411
  412impl ScrollbarMarkerState {
  413    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  414        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  415    }
  416}
  417
  418impl Default for ScrollbarMarkerState {
  419    fn default() -> Self {
  420        Self {
  421            scrollbar_size: Size::default(),
  422            dirty: false,
  423            markers: Arc::from([]),
  424            pending_refresh: None,
  425        }
  426    }
  427}
  428
  429#[derive(Clone, Debug)]
  430struct RunnableTasks {
  431    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  432    offset: MultiBufferOffset,
  433    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  434    column: u32,
  435    // Values of all named captures, including those starting with '_'
  436    extra_variables: HashMap<String, String>,
  437    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  438    context_range: Range<BufferOffset>,
  439}
  440
  441#[derive(Clone)]
  442struct ResolvedTasks {
  443    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  444    position: Anchor,
  445}
  446#[derive(Copy, Clone, Debug)]
  447struct MultiBufferOffset(usize);
  448#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  449struct BufferOffset(usize);
  450/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  451///
  452/// See the [module level documentation](self) for more information.
  453pub struct Editor {
  454    focus_handle: FocusHandle,
  455    last_focused_descendant: Option<WeakFocusHandle>,
  456    /// The text buffer being edited
  457    buffer: Model<MultiBuffer>,
  458    /// Map of how text in the buffer should be displayed.
  459    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  460    pub display_map: Model<DisplayMap>,
  461    pub selections: SelectionsCollection,
  462    pub scroll_manager: ScrollManager,
  463    /// When inline assist editors are linked, they all render cursors because
  464    /// typing enters text into each of them, even the ones that aren't focused.
  465    pub(crate) show_cursor_when_unfocused: bool,
  466    columnar_selection_tail: Option<Anchor>,
  467    add_selections_state: Option<AddSelectionsState>,
  468    select_next_state: Option<SelectNextState>,
  469    select_prev_state: Option<SelectNextState>,
  470    selection_history: SelectionHistory,
  471    autoclose_regions: Vec<AutocloseRegion>,
  472    snippet_stack: InvalidationStack<SnippetState>,
  473    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  474    ime_transaction: Option<TransactionId>,
  475    active_diagnostics: Option<ActiveDiagnosticGroup>,
  476    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  477    project: Option<Model<Project>>,
  478    completion_provider: Option<Box<dyn CompletionProvider>>,
  479    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  480    blink_manager: Model<BlinkManager>,
  481    show_cursor_names: bool,
  482    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  483    pub show_local_selections: bool,
  484    mode: EditorMode,
  485    show_breadcrumbs: bool,
  486    show_gutter: bool,
  487    show_line_numbers: Option<bool>,
  488    show_git_diff_gutter: Option<bool>,
  489    show_code_actions: Option<bool>,
  490    show_runnables: Option<bool>,
  491    show_wrap_guides: Option<bool>,
  492    show_indent_guides: Option<bool>,
  493    placeholder_text: Option<Arc<str>>,
  494    highlight_order: usize,
  495    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  496    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  497    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  498    scrollbar_marker_state: ScrollbarMarkerState,
  499    active_indent_guides_state: ActiveIndentGuidesState,
  500    nav_history: Option<ItemNavHistory>,
  501    context_menu: RwLock<Option<ContextMenu>>,
  502    mouse_context_menu: Option<MouseContextMenu>,
  503    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  504    find_all_references_task_sources: Vec<Anchor>,
  505    next_completion_id: CompletionId,
  506    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  507    available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
  508    code_actions_task: Option<Task<()>>,
  509    document_highlights_task: Option<Task<()>>,
  510    linked_editing_range_task: Option<Task<Option<()>>>,
  511    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  512    pending_rename: Option<RenameState>,
  513    searchable: bool,
  514    cursor_shape: CursorShape,
  515    current_line_highlight: Option<CurrentLineHighlight>,
  516    collapse_matches: bool,
  517    autoindent_mode: Option<AutoindentMode>,
  518    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  519    keymap_context_layers: BTreeMap<TypeId, KeyContext>,
  520    input_enabled: bool,
  521    use_modal_editing: bool,
  522    read_only: bool,
  523    leader_peer_id: Option<PeerId>,
  524    remote_id: Option<ViewId>,
  525    hover_state: HoverState,
  526    gutter_hovered: bool,
  527    hovered_link_state: Option<HoveredLinkState>,
  528    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  529    active_inline_completion: Option<Inlay>,
  530    show_inline_completions: bool,
  531    inlay_hint_cache: InlayHintCache,
  532    expanded_hunks: ExpandedHunks,
  533    next_inlay_id: usize,
  534    _subscriptions: Vec<Subscription>,
  535    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  536    gutter_dimensions: GutterDimensions,
  537    pub vim_replace_map: HashMap<Range<usize>, String>,
  538    style: Option<EditorStyle>,
  539    next_editor_action_id: EditorActionId,
  540    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  541    use_autoclose: bool,
  542    use_auto_surround: bool,
  543    auto_replace_emoji_shortcode: bool,
  544    show_git_blame_gutter: bool,
  545    show_git_blame_inline: bool,
  546    show_git_blame_inline_delay_task: Option<Task<()>>,
  547    git_blame_inline_enabled: bool,
  548    show_selection_menu: Option<bool>,
  549    blame: Option<Model<GitBlame>>,
  550    blame_subscription: Option<Subscription>,
  551    custom_context_menu: Option<
  552        Box<
  553            dyn 'static
  554                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  555        >,
  556    >,
  557    last_bounds: Option<Bounds<Pixels>>,
  558    expect_bounds_change: Option<Bounds<Pixels>>,
  559    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  560    tasks_update_task: Option<Task<()>>,
  561    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  562    file_header_size: u8,
  563    breadcrumb_header: Option<String>,
  564}
  565
  566#[derive(Clone)]
  567pub struct EditorSnapshot {
  568    pub mode: EditorMode,
  569    show_gutter: bool,
  570    show_line_numbers: Option<bool>,
  571    show_git_diff_gutter: Option<bool>,
  572    show_code_actions: Option<bool>,
  573    show_runnables: Option<bool>,
  574    render_git_blame_gutter: bool,
  575    pub display_snapshot: DisplaySnapshot,
  576    pub placeholder_text: Option<Arc<str>>,
  577    is_focused: bool,
  578    scroll_anchor: ScrollAnchor,
  579    ongoing_scroll: OngoingScroll,
  580    current_line_highlight: CurrentLineHighlight,
  581    gutter_hovered: bool,
  582}
  583
  584const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
  585
  586#[derive(Debug, Clone, Copy)]
  587pub struct GutterDimensions {
  588    pub left_padding: Pixels,
  589    pub right_padding: Pixels,
  590    pub width: Pixels,
  591    pub margin: Pixels,
  592    pub git_blame_entries_width: Option<Pixels>,
  593}
  594
  595impl GutterDimensions {
  596    /// The full width of the space taken up by the gutter.
  597    pub fn full_width(&self) -> Pixels {
  598        self.margin + self.width
  599    }
  600
  601    /// The width of the space reserved for the fold indicators,
  602    /// use alongside 'justify_end' and `gutter_width` to
  603    /// right align content with the line numbers
  604    pub fn fold_area_width(&self) -> Pixels {
  605        self.margin + self.right_padding
  606    }
  607}
  608
  609impl Default for GutterDimensions {
  610    fn default() -> Self {
  611        Self {
  612            left_padding: Pixels::ZERO,
  613            right_padding: Pixels::ZERO,
  614            width: Pixels::ZERO,
  615            margin: Pixels::ZERO,
  616            git_blame_entries_width: None,
  617        }
  618    }
  619}
  620
  621#[derive(Debug)]
  622pub struct RemoteSelection {
  623    pub replica_id: ReplicaId,
  624    pub selection: Selection<Anchor>,
  625    pub cursor_shape: CursorShape,
  626    pub peer_id: PeerId,
  627    pub line_mode: bool,
  628    pub participant_index: Option<ParticipantIndex>,
  629    pub user_name: Option<SharedString>,
  630}
  631
  632#[derive(Clone, Debug)]
  633struct SelectionHistoryEntry {
  634    selections: Arc<[Selection<Anchor>]>,
  635    select_next_state: Option<SelectNextState>,
  636    select_prev_state: Option<SelectNextState>,
  637    add_selections_state: Option<AddSelectionsState>,
  638}
  639
  640enum SelectionHistoryMode {
  641    Normal,
  642    Undoing,
  643    Redoing,
  644}
  645
  646#[derive(Clone, PartialEq, Eq, Hash)]
  647struct HoveredCursor {
  648    replica_id: u16,
  649    selection_id: usize,
  650}
  651
  652impl Default for SelectionHistoryMode {
  653    fn default() -> Self {
  654        Self::Normal
  655    }
  656}
  657
  658#[derive(Default)]
  659struct SelectionHistory {
  660    #[allow(clippy::type_complexity)]
  661    selections_by_transaction:
  662        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  663    mode: SelectionHistoryMode,
  664    undo_stack: VecDeque<SelectionHistoryEntry>,
  665    redo_stack: VecDeque<SelectionHistoryEntry>,
  666}
  667
  668impl SelectionHistory {
  669    fn insert_transaction(
  670        &mut self,
  671        transaction_id: TransactionId,
  672        selections: Arc<[Selection<Anchor>]>,
  673    ) {
  674        self.selections_by_transaction
  675            .insert(transaction_id, (selections, None));
  676    }
  677
  678    #[allow(clippy::type_complexity)]
  679    fn transaction(
  680        &self,
  681        transaction_id: TransactionId,
  682    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  683        self.selections_by_transaction.get(&transaction_id)
  684    }
  685
  686    #[allow(clippy::type_complexity)]
  687    fn transaction_mut(
  688        &mut self,
  689        transaction_id: TransactionId,
  690    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  691        self.selections_by_transaction.get_mut(&transaction_id)
  692    }
  693
  694    fn push(&mut self, entry: SelectionHistoryEntry) {
  695        if !entry.selections.is_empty() {
  696            match self.mode {
  697                SelectionHistoryMode::Normal => {
  698                    self.push_undo(entry);
  699                    self.redo_stack.clear();
  700                }
  701                SelectionHistoryMode::Undoing => self.push_redo(entry),
  702                SelectionHistoryMode::Redoing => self.push_undo(entry),
  703            }
  704        }
  705    }
  706
  707    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  708        if self
  709            .undo_stack
  710            .back()
  711            .map_or(true, |e| e.selections != entry.selections)
  712        {
  713            self.undo_stack.push_back(entry);
  714            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  715                self.undo_stack.pop_front();
  716            }
  717        }
  718    }
  719
  720    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  721        if self
  722            .redo_stack
  723            .back()
  724            .map_or(true, |e| e.selections != entry.selections)
  725        {
  726            self.redo_stack.push_back(entry);
  727            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  728                self.redo_stack.pop_front();
  729            }
  730        }
  731    }
  732}
  733
  734struct RowHighlight {
  735    index: usize,
  736    range: RangeInclusive<Anchor>,
  737    color: Option<Hsla>,
  738    should_autoscroll: bool,
  739}
  740
  741#[derive(Clone, Debug)]
  742struct AddSelectionsState {
  743    above: bool,
  744    stack: Vec<usize>,
  745}
  746
  747#[derive(Clone)]
  748struct SelectNextState {
  749    query: AhoCorasick,
  750    wordwise: bool,
  751    done: bool,
  752}
  753
  754impl std::fmt::Debug for SelectNextState {
  755    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  756        f.debug_struct(std::any::type_name::<Self>())
  757            .field("wordwise", &self.wordwise)
  758            .field("done", &self.done)
  759            .finish()
  760    }
  761}
  762
  763#[derive(Debug)]
  764struct AutocloseRegion {
  765    selection_id: usize,
  766    range: Range<Anchor>,
  767    pair: BracketPair,
  768}
  769
  770#[derive(Debug)]
  771struct SnippetState {
  772    ranges: Vec<Vec<Range<Anchor>>>,
  773    active_index: usize,
  774}
  775
  776#[doc(hidden)]
  777pub struct RenameState {
  778    pub range: Range<Anchor>,
  779    pub old_name: Arc<str>,
  780    pub editor: View<Editor>,
  781    block_id: BlockId,
  782}
  783
  784struct InvalidationStack<T>(Vec<T>);
  785
  786struct RegisteredInlineCompletionProvider {
  787    provider: Arc<dyn InlineCompletionProviderHandle>,
  788    _subscription: Subscription,
  789}
  790
  791enum ContextMenu {
  792    Completions(CompletionsMenu),
  793    CodeActions(CodeActionsMenu),
  794}
  795
  796impl ContextMenu {
  797    fn select_first(
  798        &mut self,
  799        project: Option<&Model<Project>>,
  800        cx: &mut ViewContext<Editor>,
  801    ) -> bool {
  802        if self.visible() {
  803            match self {
  804                ContextMenu::Completions(menu) => menu.select_first(project, cx),
  805                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  806            }
  807            true
  808        } else {
  809            false
  810        }
  811    }
  812
  813    fn select_prev(
  814        &mut self,
  815        project: Option<&Model<Project>>,
  816        cx: &mut ViewContext<Editor>,
  817    ) -> bool {
  818        if self.visible() {
  819            match self {
  820                ContextMenu::Completions(menu) => menu.select_prev(project, cx),
  821                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  822            }
  823            true
  824        } else {
  825            false
  826        }
  827    }
  828
  829    fn select_next(
  830        &mut self,
  831        project: Option<&Model<Project>>,
  832        cx: &mut ViewContext<Editor>,
  833    ) -> bool {
  834        if self.visible() {
  835            match self {
  836                ContextMenu::Completions(menu) => menu.select_next(project, cx),
  837                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  838            }
  839            true
  840        } else {
  841            false
  842        }
  843    }
  844
  845    fn select_last(
  846        &mut self,
  847        project: Option<&Model<Project>>,
  848        cx: &mut ViewContext<Editor>,
  849    ) -> bool {
  850        if self.visible() {
  851            match self {
  852                ContextMenu::Completions(menu) => menu.select_last(project, cx),
  853                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  854            }
  855            true
  856        } else {
  857            false
  858        }
  859    }
  860
  861    fn visible(&self) -> bool {
  862        match self {
  863            ContextMenu::Completions(menu) => menu.visible(),
  864            ContextMenu::CodeActions(menu) => menu.visible(),
  865        }
  866    }
  867
  868    fn render(
  869        &self,
  870        cursor_position: DisplayPoint,
  871        style: &EditorStyle,
  872        max_height: Pixels,
  873        workspace: Option<WeakView<Workspace>>,
  874        cx: &mut ViewContext<Editor>,
  875    ) -> (ContextMenuOrigin, AnyElement) {
  876        match self {
  877            ContextMenu::Completions(menu) => (
  878                ContextMenuOrigin::EditorPoint(cursor_position),
  879                menu.render(style, max_height, workspace, cx),
  880            ),
  881            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  882        }
  883    }
  884}
  885
  886enum ContextMenuOrigin {
  887    EditorPoint(DisplayPoint),
  888    GutterIndicator(DisplayRow),
  889}
  890
  891#[derive(Clone)]
  892struct CompletionsMenu {
  893    id: CompletionId,
  894    initial_position: Anchor,
  895    buffer: Model<Buffer>,
  896    completions: Arc<RwLock<Box<[Completion]>>>,
  897    match_candidates: Arc<[StringMatchCandidate]>,
  898    matches: Arc<[StringMatch]>,
  899    selected_item: usize,
  900    scroll_handle: UniformListScrollHandle,
  901    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  902}
  903
  904impl CompletionsMenu {
  905    fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  906        self.selected_item = 0;
  907        self.scroll_handle.scroll_to_item(self.selected_item);
  908        self.attempt_resolve_selected_completion_documentation(project, cx);
  909        cx.notify();
  910    }
  911
  912    fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  913        if self.selected_item > 0 {
  914            self.selected_item -= 1;
  915        } else {
  916            self.selected_item = self.matches.len() - 1;
  917        }
  918        self.scroll_handle.scroll_to_item(self.selected_item);
  919        self.attempt_resolve_selected_completion_documentation(project, cx);
  920        cx.notify();
  921    }
  922
  923    fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  924        if self.selected_item + 1 < self.matches.len() {
  925            self.selected_item += 1;
  926        } else {
  927            self.selected_item = 0;
  928        }
  929        self.scroll_handle.scroll_to_item(self.selected_item);
  930        self.attempt_resolve_selected_completion_documentation(project, cx);
  931        cx.notify();
  932    }
  933
  934    fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  935        self.selected_item = self.matches.len() - 1;
  936        self.scroll_handle.scroll_to_item(self.selected_item);
  937        self.attempt_resolve_selected_completion_documentation(project, cx);
  938        cx.notify();
  939    }
  940
  941    fn pre_resolve_completion_documentation(
  942        buffer: Model<Buffer>,
  943        completions: Arc<RwLock<Box<[Completion]>>>,
  944        matches: Arc<[StringMatch]>,
  945        editor: &Editor,
  946        cx: &mut ViewContext<Editor>,
  947    ) -> Task<()> {
  948        let settings = EditorSettings::get_global(cx);
  949        if !settings.show_completion_documentation {
  950            return Task::ready(());
  951        }
  952
  953        let Some(provider) = editor.completion_provider.as_ref() else {
  954            return Task::ready(());
  955        };
  956
  957        let resolve_task = provider.resolve_completions(
  958            buffer,
  959            matches.iter().map(|m| m.candidate_id).collect(),
  960            completions.clone(),
  961            cx,
  962        );
  963
  964        return cx.spawn(move |this, mut cx| async move {
  965            if let Some(true) = resolve_task.await.log_err() {
  966                this.update(&mut cx, |_, cx| cx.notify()).ok();
  967            }
  968        });
  969    }
  970
  971    fn attempt_resolve_selected_completion_documentation(
  972        &mut self,
  973        project: Option<&Model<Project>>,
  974        cx: &mut ViewContext<Editor>,
  975    ) {
  976        let settings = EditorSettings::get_global(cx);
  977        if !settings.show_completion_documentation {
  978            return;
  979        }
  980
  981        let completion_index = self.matches[self.selected_item].candidate_id;
  982        let Some(project) = project else {
  983            return;
  984        };
  985
  986        let resolve_task = project.update(cx, |project, cx| {
  987            project.resolve_completions(
  988                self.buffer.clone(),
  989                vec![completion_index],
  990                self.completions.clone(),
  991                cx,
  992            )
  993        });
  994
  995        let delay_ms =
  996            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
  997        let delay = Duration::from_millis(delay_ms);
  998
  999        self.selected_completion_documentation_resolve_debounce
 1000            .lock()
 1001            .fire_new(delay, cx, |_, cx| {
 1002                cx.spawn(move |this, mut cx| async move {
 1003                    if let Some(true) = resolve_task.await.log_err() {
 1004                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1005                    }
 1006                })
 1007            });
 1008    }
 1009
 1010    fn visible(&self) -> bool {
 1011        !self.matches.is_empty()
 1012    }
 1013
 1014    fn render(
 1015        &self,
 1016        style: &EditorStyle,
 1017        max_height: Pixels,
 1018        workspace: Option<WeakView<Workspace>>,
 1019        cx: &mut ViewContext<Editor>,
 1020    ) -> AnyElement {
 1021        let settings = EditorSettings::get_global(cx);
 1022        let show_completion_documentation = settings.show_completion_documentation;
 1023
 1024        let widest_completion_ix = self
 1025            .matches
 1026            .iter()
 1027            .enumerate()
 1028            .max_by_key(|(_, mat)| {
 1029                let completions = self.completions.read();
 1030                let completion = &completions[mat.candidate_id];
 1031                let documentation = &completion.documentation;
 1032
 1033                let mut len = completion.label.text.chars().count();
 1034                if let Some(Documentation::SingleLine(text)) = documentation {
 1035                    if show_completion_documentation {
 1036                        len += text.chars().count();
 1037                    }
 1038                }
 1039
 1040                len
 1041            })
 1042            .map(|(ix, _)| ix);
 1043
 1044        let completions = self.completions.clone();
 1045        let matches = self.matches.clone();
 1046        let selected_item = self.selected_item;
 1047        let style = style.clone();
 1048
 1049        let multiline_docs = if show_completion_documentation {
 1050            let mat = &self.matches[selected_item];
 1051            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1052                Some(Documentation::MultiLinePlainText(text)) => {
 1053                    Some(div().child(SharedString::from(text.clone())))
 1054                }
 1055                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1056                    Some(div().child(render_parsed_markdown(
 1057                        "completions_markdown",
 1058                        parsed,
 1059                        &style,
 1060                        workspace,
 1061                        cx,
 1062                    )))
 1063                }
 1064                _ => None,
 1065            };
 1066            multiline_docs.map(|div| {
 1067                div.id("multiline_docs")
 1068                    .max_h(max_height)
 1069                    .flex_1()
 1070                    .px_1p5()
 1071                    .py_1()
 1072                    .min_w(px(260.))
 1073                    .max_w(px(640.))
 1074                    .w(px(500.))
 1075                    .overflow_y_scroll()
 1076                    .occlude()
 1077            })
 1078        } else {
 1079            None
 1080        };
 1081
 1082        let list = uniform_list(
 1083            cx.view().clone(),
 1084            "completions",
 1085            matches.len(),
 1086            move |_editor, range, cx| {
 1087                let start_ix = range.start;
 1088                let completions_guard = completions.read();
 1089
 1090                matches[range]
 1091                    .iter()
 1092                    .enumerate()
 1093                    .map(|(ix, mat)| {
 1094                        let item_ix = start_ix + ix;
 1095                        let candidate_id = mat.candidate_id;
 1096                        let completion = &completions_guard[candidate_id];
 1097
 1098                        let documentation = if show_completion_documentation {
 1099                            &completion.documentation
 1100                        } else {
 1101                            &None
 1102                        };
 1103
 1104                        let highlights = gpui::combine_highlights(
 1105                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1106                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1107                                |(range, mut highlight)| {
 1108                                    // Ignore font weight for syntax highlighting, as we'll use it
 1109                                    // for fuzzy matches.
 1110                                    highlight.font_weight = None;
 1111
 1112                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1113                                        highlight.strikethrough = Some(StrikethroughStyle {
 1114                                            thickness: 1.0.into(),
 1115                                            ..Default::default()
 1116                                        });
 1117                                        highlight.color = Some(cx.theme().colors().text_muted);
 1118                                    }
 1119
 1120                                    (range, highlight)
 1121                                },
 1122                            ),
 1123                        );
 1124                        let completion_label = StyledText::new(completion.label.text.clone())
 1125                            .with_highlights(&style.text, highlights);
 1126                        let documentation_label =
 1127                            if let Some(Documentation::SingleLine(text)) = documentation {
 1128                                if text.trim().is_empty() {
 1129                                    None
 1130                                } else {
 1131                                    Some(
 1132                                        Label::new(text.clone())
 1133                                            .ml_4()
 1134                                            .size(LabelSize::Small)
 1135                                            .color(Color::Muted),
 1136                                    )
 1137                                }
 1138                            } else {
 1139                                None
 1140                            };
 1141
 1142                        div().min_w(px(220.)).max_w(px(540.)).child(
 1143                            ListItem::new(mat.candidate_id)
 1144                                .inset(true)
 1145                                .selected(item_ix == selected_item)
 1146                                .on_click(cx.listener(move |editor, _event, cx| {
 1147                                    cx.stop_propagation();
 1148                                    if let Some(task) = editor.confirm_completion(
 1149                                        &ConfirmCompletion {
 1150                                            item_ix: Some(item_ix),
 1151                                        },
 1152                                        cx,
 1153                                    ) {
 1154                                        task.detach_and_log_err(cx)
 1155                                    }
 1156                                }))
 1157                                .child(h_flex().overflow_hidden().child(completion_label))
 1158                                .end_slot::<Label>(documentation_label),
 1159                        )
 1160                    })
 1161                    .collect()
 1162            },
 1163        )
 1164        .occlude()
 1165        .max_h(max_height)
 1166        .track_scroll(self.scroll_handle.clone())
 1167        .with_width_from_item(widest_completion_ix)
 1168        .with_sizing_behavior(ListSizingBehavior::Infer);
 1169
 1170        Popover::new()
 1171            .child(list)
 1172            .when_some(multiline_docs, |popover, multiline_docs| {
 1173                popover.aside(multiline_docs)
 1174            })
 1175            .into_any_element()
 1176    }
 1177
 1178    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1179        let mut matches = if let Some(query) = query {
 1180            fuzzy::match_strings(
 1181                &self.match_candidates,
 1182                query,
 1183                query.chars().any(|c| c.is_uppercase()),
 1184                100,
 1185                &Default::default(),
 1186                executor,
 1187            )
 1188            .await
 1189        } else {
 1190            self.match_candidates
 1191                .iter()
 1192                .enumerate()
 1193                .map(|(candidate_id, candidate)| StringMatch {
 1194                    candidate_id,
 1195                    score: Default::default(),
 1196                    positions: Default::default(),
 1197                    string: candidate.string.clone(),
 1198                })
 1199                .collect()
 1200        };
 1201
 1202        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1203        if let Some(query) = query {
 1204            if let Some(query_start) = query.chars().next() {
 1205                matches.retain(|string_match| {
 1206                    split_words(&string_match.string).any(|word| {
 1207                        // Check that the first codepoint of the word as lowercase matches the first
 1208                        // codepoint of the query as lowercase
 1209                        word.chars()
 1210                            .flat_map(|codepoint| codepoint.to_lowercase())
 1211                            .zip(query_start.to_lowercase())
 1212                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1213                    })
 1214                });
 1215            }
 1216        }
 1217
 1218        let completions = self.completions.read();
 1219        matches.sort_unstable_by_key(|mat| {
 1220            // We do want to strike a balance here between what the language server tells us
 1221            // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1222            // `Creat` and there is a local variable called `CreateComponent`).
 1223            // So what we do is: we bucket all matches into two buckets
 1224            // - Strong matches
 1225            // - Weak matches
 1226            // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1227            // and the Weak matches are the rest.
 1228            //
 1229            // For the strong matches, we sort by the language-servers score first and for the weak
 1230            // matches, we prefer our fuzzy finder first.
 1231            //
 1232            // The thinking behind that: it's useless to take the sort_text the language-server gives
 1233            // us into account when it's obviously a bad match.
 1234
 1235            #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1236            enum MatchScore<'a> {
 1237                Strong {
 1238                    sort_text: Option<&'a str>,
 1239                    score: Reverse<OrderedFloat<f64>>,
 1240                    sort_key: (usize, &'a str),
 1241                },
 1242                Weak {
 1243                    score: Reverse<OrderedFloat<f64>>,
 1244                    sort_text: Option<&'a str>,
 1245                    sort_key: (usize, &'a str),
 1246                },
 1247            }
 1248
 1249            let completion = &completions[mat.candidate_id];
 1250            let sort_key = completion.sort_key();
 1251            let sort_text = completion.lsp_completion.sort_text.as_deref();
 1252            let score = Reverse(OrderedFloat(mat.score));
 1253
 1254            if mat.score >= 0.2 {
 1255                MatchScore::Strong {
 1256                    sort_text,
 1257                    score,
 1258                    sort_key,
 1259                }
 1260            } else {
 1261                MatchScore::Weak {
 1262                    score,
 1263                    sort_text,
 1264                    sort_key,
 1265                }
 1266            }
 1267        });
 1268
 1269        for mat in &mut matches {
 1270            let completion = &completions[mat.candidate_id];
 1271            mat.string.clone_from(&completion.label.text);
 1272            for position in &mut mat.positions {
 1273                *position += completion.label.filter_range.start;
 1274            }
 1275        }
 1276        drop(completions);
 1277
 1278        self.matches = matches.into();
 1279        self.selected_item = 0;
 1280    }
 1281}
 1282
 1283#[derive(Clone)]
 1284struct CodeActionContents {
 1285    tasks: Option<Arc<ResolvedTasks>>,
 1286    actions: Option<Arc<[CodeAction]>>,
 1287}
 1288
 1289impl CodeActionContents {
 1290    fn len(&self) -> usize {
 1291        match (&self.tasks, &self.actions) {
 1292            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1293            (Some(tasks), None) => tasks.templates.len(),
 1294            (None, Some(actions)) => actions.len(),
 1295            (None, None) => 0,
 1296        }
 1297    }
 1298
 1299    fn is_empty(&self) -> bool {
 1300        match (&self.tasks, &self.actions) {
 1301            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1302            (Some(tasks), None) => tasks.templates.is_empty(),
 1303            (None, Some(actions)) => actions.is_empty(),
 1304            (None, None) => true,
 1305        }
 1306    }
 1307
 1308    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1309        self.tasks
 1310            .iter()
 1311            .flat_map(|tasks| {
 1312                tasks
 1313                    .templates
 1314                    .iter()
 1315                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1316            })
 1317            .chain(self.actions.iter().flat_map(|actions| {
 1318                actions
 1319                    .iter()
 1320                    .map(|action| CodeActionsItem::CodeAction(action.clone()))
 1321            }))
 1322    }
 1323    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1324        match (&self.tasks, &self.actions) {
 1325            (Some(tasks), Some(actions)) => {
 1326                if index < tasks.templates.len() {
 1327                    tasks
 1328                        .templates
 1329                        .get(index)
 1330                        .cloned()
 1331                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1332                } else {
 1333                    actions
 1334                        .get(index - tasks.templates.len())
 1335                        .cloned()
 1336                        .map(CodeActionsItem::CodeAction)
 1337                }
 1338            }
 1339            (Some(tasks), None) => tasks
 1340                .templates
 1341                .get(index)
 1342                .cloned()
 1343                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1344            (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
 1345            (None, None) => None,
 1346        }
 1347    }
 1348}
 1349
 1350#[allow(clippy::large_enum_variant)]
 1351#[derive(Clone)]
 1352enum CodeActionsItem {
 1353    Task(TaskSourceKind, ResolvedTask),
 1354    CodeAction(CodeAction),
 1355}
 1356
 1357impl CodeActionsItem {
 1358    fn as_task(&self) -> Option<&ResolvedTask> {
 1359        let Self::Task(_, task) = self else {
 1360            return None;
 1361        };
 1362        Some(task)
 1363    }
 1364    fn as_code_action(&self) -> Option<&CodeAction> {
 1365        let Self::CodeAction(action) = self else {
 1366            return None;
 1367        };
 1368        Some(action)
 1369    }
 1370    fn label(&self) -> String {
 1371        match self {
 1372            Self::CodeAction(action) => action.lsp_action.title.clone(),
 1373            Self::Task(_, task) => task.resolved_label.clone(),
 1374        }
 1375    }
 1376}
 1377
 1378struct CodeActionsMenu {
 1379    actions: CodeActionContents,
 1380    buffer: Model<Buffer>,
 1381    selected_item: usize,
 1382    scroll_handle: UniformListScrollHandle,
 1383    deployed_from_indicator: Option<DisplayRow>,
 1384}
 1385
 1386impl CodeActionsMenu {
 1387    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1388        self.selected_item = 0;
 1389        self.scroll_handle.scroll_to_item(self.selected_item);
 1390        cx.notify()
 1391    }
 1392
 1393    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1394        if self.selected_item > 0 {
 1395            self.selected_item -= 1;
 1396        } else {
 1397            self.selected_item = self.actions.len() - 1;
 1398        }
 1399        self.scroll_handle.scroll_to_item(self.selected_item);
 1400        cx.notify();
 1401    }
 1402
 1403    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1404        if self.selected_item + 1 < self.actions.len() {
 1405            self.selected_item += 1;
 1406        } else {
 1407            self.selected_item = 0;
 1408        }
 1409        self.scroll_handle.scroll_to_item(self.selected_item);
 1410        cx.notify();
 1411    }
 1412
 1413    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1414        self.selected_item = self.actions.len() - 1;
 1415        self.scroll_handle.scroll_to_item(self.selected_item);
 1416        cx.notify()
 1417    }
 1418
 1419    fn visible(&self) -> bool {
 1420        !self.actions.is_empty()
 1421    }
 1422
 1423    fn render(
 1424        &self,
 1425        cursor_position: DisplayPoint,
 1426        _style: &EditorStyle,
 1427        max_height: Pixels,
 1428        cx: &mut ViewContext<Editor>,
 1429    ) -> (ContextMenuOrigin, AnyElement) {
 1430        let actions = self.actions.clone();
 1431        let selected_item = self.selected_item;
 1432        let element = uniform_list(
 1433            cx.view().clone(),
 1434            "code_actions_menu",
 1435            self.actions.len(),
 1436            move |_this, range, cx| {
 1437                actions
 1438                    .iter()
 1439                    .skip(range.start)
 1440                    .take(range.end - range.start)
 1441                    .enumerate()
 1442                    .map(|(ix, action)| {
 1443                        let item_ix = range.start + ix;
 1444                        let selected = selected_item == item_ix;
 1445                        let colors = cx.theme().colors();
 1446                        div()
 1447                            .px_2()
 1448                            .text_color(colors.text)
 1449                            .when(selected, |style| {
 1450                                style
 1451                                    .bg(colors.element_active)
 1452                                    .text_color(colors.text_accent)
 1453                            })
 1454                            .hover(|style| {
 1455                                style
 1456                                    .bg(colors.element_hover)
 1457                                    .text_color(colors.text_accent)
 1458                            })
 1459                            .whitespace_nowrap()
 1460                            .when_some(action.as_code_action(), |this, action| {
 1461                                this.on_mouse_down(
 1462                                    MouseButton::Left,
 1463                                    cx.listener(move |editor, _, cx| {
 1464                                        cx.stop_propagation();
 1465                                        if let Some(task) = editor.confirm_code_action(
 1466                                            &ConfirmCodeAction {
 1467                                                item_ix: Some(item_ix),
 1468                                            },
 1469                                            cx,
 1470                                        ) {
 1471                                            task.detach_and_log_err(cx)
 1472                                        }
 1473                                    }),
 1474                                )
 1475                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1476                                .child(SharedString::from(action.lsp_action.title.clone()))
 1477                            })
 1478                            .when_some(action.as_task(), |this, task| {
 1479                                this.on_mouse_down(
 1480                                    MouseButton::Left,
 1481                                    cx.listener(move |editor, _, cx| {
 1482                                        cx.stop_propagation();
 1483                                        if let Some(task) = editor.confirm_code_action(
 1484                                            &ConfirmCodeAction {
 1485                                                item_ix: Some(item_ix),
 1486                                            },
 1487                                            cx,
 1488                                        ) {
 1489                                            task.detach_and_log_err(cx)
 1490                                        }
 1491                                    }),
 1492                                )
 1493                                .child(SharedString::from(task.resolved_label.clone()))
 1494                            })
 1495                    })
 1496                    .collect()
 1497            },
 1498        )
 1499        .elevation_1(cx)
 1500        .px_2()
 1501        .py_1()
 1502        .max_h(max_height)
 1503        .occlude()
 1504        .track_scroll(self.scroll_handle.clone())
 1505        .with_width_from_item(
 1506            self.actions
 1507                .iter()
 1508                .enumerate()
 1509                .max_by_key(|(_, action)| match action {
 1510                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1511                    CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
 1512                })
 1513                .map(|(ix, _)| ix),
 1514        )
 1515        .with_sizing_behavior(ListSizingBehavior::Infer)
 1516        .into_any_element();
 1517
 1518        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1519            ContextMenuOrigin::GutterIndicator(row)
 1520        } else {
 1521            ContextMenuOrigin::EditorPoint(cursor_position)
 1522        };
 1523
 1524        (cursor_position, element)
 1525    }
 1526}
 1527
 1528#[derive(Debug)]
 1529struct ActiveDiagnosticGroup {
 1530    primary_range: Range<Anchor>,
 1531    primary_message: String,
 1532    group_id: usize,
 1533    blocks: HashMap<BlockId, Diagnostic>,
 1534    is_valid: bool,
 1535}
 1536
 1537#[derive(Serialize, Deserialize, Clone, Debug)]
 1538pub struct ClipboardSelection {
 1539    pub len: usize,
 1540    pub is_entire_line: bool,
 1541    pub first_line_indent: u32,
 1542}
 1543
 1544#[derive(Debug)]
 1545pub(crate) struct NavigationData {
 1546    cursor_anchor: Anchor,
 1547    cursor_position: Point,
 1548    scroll_anchor: ScrollAnchor,
 1549    scroll_top_row: u32,
 1550}
 1551
 1552enum GotoDefinitionKind {
 1553    Symbol,
 1554    Type,
 1555    Implementation,
 1556}
 1557
 1558#[derive(Debug, Clone)]
 1559enum InlayHintRefreshReason {
 1560    Toggle(bool),
 1561    SettingsChange(InlayHintSettings),
 1562    NewLinesShown,
 1563    BufferEdited(HashSet<Arc<Language>>),
 1564    RefreshRequested,
 1565    ExcerptsRemoved(Vec<ExcerptId>),
 1566}
 1567
 1568impl InlayHintRefreshReason {
 1569    fn description(&self) -> &'static str {
 1570        match self {
 1571            Self::Toggle(_) => "toggle",
 1572            Self::SettingsChange(_) => "settings change",
 1573            Self::NewLinesShown => "new lines shown",
 1574            Self::BufferEdited(_) => "buffer edited",
 1575            Self::RefreshRequested => "refresh requested",
 1576            Self::ExcerptsRemoved(_) => "excerpts removed",
 1577        }
 1578    }
 1579}
 1580
 1581impl Editor {
 1582    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1583        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1584        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1585        Self::new(
 1586            EditorMode::SingleLine { auto_width: false },
 1587            buffer,
 1588            None,
 1589            false,
 1590            cx,
 1591        )
 1592    }
 1593
 1594    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1595        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1596        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1597        Self::new(EditorMode::Full, buffer, None, false, cx)
 1598    }
 1599
 1600    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1601        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1602        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1603        Self::new(
 1604            EditorMode::SingleLine { auto_width: true },
 1605            buffer,
 1606            None,
 1607            false,
 1608            cx,
 1609        )
 1610    }
 1611
 1612    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1613        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1614        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1615        Self::new(
 1616            EditorMode::AutoHeight { max_lines },
 1617            buffer,
 1618            None,
 1619            false,
 1620            cx,
 1621        )
 1622    }
 1623
 1624    pub fn for_buffer(
 1625        buffer: Model<Buffer>,
 1626        project: Option<Model<Project>>,
 1627        cx: &mut ViewContext<Self>,
 1628    ) -> Self {
 1629        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1630        Self::new(EditorMode::Full, buffer, project, false, cx)
 1631    }
 1632
 1633    pub fn for_multibuffer(
 1634        buffer: Model<MultiBuffer>,
 1635        project: Option<Model<Project>>,
 1636        show_excerpt_controls: bool,
 1637        cx: &mut ViewContext<Self>,
 1638    ) -> Self {
 1639        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1640    }
 1641
 1642    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1643        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1644        let mut clone = Self::new(
 1645            self.mode,
 1646            self.buffer.clone(),
 1647            self.project.clone(),
 1648            show_excerpt_controls,
 1649            cx,
 1650        );
 1651        self.display_map.update(cx, |display_map, cx| {
 1652            let snapshot = display_map.snapshot(cx);
 1653            clone.display_map.update(cx, |display_map, cx| {
 1654                display_map.set_state(&snapshot, cx);
 1655            });
 1656        });
 1657        clone.selections.clone_state(&self.selections);
 1658        clone.scroll_manager.clone_state(&self.scroll_manager);
 1659        clone.searchable = self.searchable;
 1660        clone
 1661    }
 1662
 1663    pub fn new(
 1664        mode: EditorMode,
 1665        buffer: Model<MultiBuffer>,
 1666        project: Option<Model<Project>>,
 1667        show_excerpt_controls: bool,
 1668        cx: &mut ViewContext<Self>,
 1669    ) -> Self {
 1670        let style = cx.text_style();
 1671        let font_size = style.font_size.to_pixels(cx.rem_size());
 1672        let editor = cx.view().downgrade();
 1673        let fold_placeholder = FoldPlaceholder {
 1674            constrain_width: true,
 1675            render: Arc::new(move |fold_id, fold_range, cx| {
 1676                let editor = editor.clone();
 1677                div()
 1678                    .id(fold_id)
 1679                    .bg(cx.theme().colors().ghost_element_background)
 1680                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1681                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1682                    .rounded_sm()
 1683                    .size_full()
 1684                    .cursor_pointer()
 1685                    .child("")
 1686                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1687                    .on_click(move |_, cx| {
 1688                        editor
 1689                            .update(cx, |editor, cx| {
 1690                                editor.unfold_ranges(
 1691                                    [fold_range.start..fold_range.end],
 1692                                    true,
 1693                                    false,
 1694                                    cx,
 1695                                );
 1696                                cx.stop_propagation();
 1697                            })
 1698                            .ok();
 1699                    })
 1700                    .into_any()
 1701            }),
 1702            merge_adjacent: true,
 1703        };
 1704        let file_header_size = if show_excerpt_controls { 3 } else { 2 };
 1705        let display_map = cx.new_model(|cx| {
 1706            DisplayMap::new(
 1707                buffer.clone(),
 1708                style.font(),
 1709                font_size,
 1710                None,
 1711                show_excerpt_controls,
 1712                file_header_size,
 1713                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1714                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1715                fold_placeholder,
 1716                cx,
 1717            )
 1718        });
 1719
 1720        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1721
 1722        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1723
 1724        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1725            .then(|| language_settings::SoftWrap::PreferLine);
 1726
 1727        let mut project_subscriptions = Vec::new();
 1728        if mode == EditorMode::Full {
 1729            if let Some(project) = project.as_ref() {
 1730                if buffer.read(cx).is_singleton() {
 1731                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1732                        cx.emit(EditorEvent::TitleChanged);
 1733                    }));
 1734                }
 1735                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1736                    if let project::Event::RefreshInlayHints = event {
 1737                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1738                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1739                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1740                            let focus_handle = editor.focus_handle(cx);
 1741                            if focus_handle.is_focused(cx) {
 1742                                let snapshot = buffer.read(cx).snapshot();
 1743                                for (range, snippet) in snippet_edits {
 1744                                    let editor_range =
 1745                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1746                                    editor
 1747                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1748                                        .ok();
 1749                                }
 1750                            }
 1751                        }
 1752                    }
 1753                }));
 1754                let task_inventory = project.read(cx).task_inventory().clone();
 1755                project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1756                    editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1757                }));
 1758            }
 1759        }
 1760
 1761        let inlay_hint_settings = inlay_hint_settings(
 1762            selections.newest_anchor().head(),
 1763            &buffer.read(cx).snapshot(cx),
 1764            cx,
 1765        );
 1766        let focus_handle = cx.focus_handle();
 1767        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1768        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1769            .detach();
 1770        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1771
 1772        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1773            Some(false)
 1774        } else {
 1775            None
 1776        };
 1777
 1778        let mut this = Self {
 1779            focus_handle,
 1780            show_cursor_when_unfocused: false,
 1781            last_focused_descendant: None,
 1782            buffer: buffer.clone(),
 1783            display_map: display_map.clone(),
 1784            selections,
 1785            scroll_manager: ScrollManager::new(cx),
 1786            columnar_selection_tail: None,
 1787            add_selections_state: None,
 1788            select_next_state: None,
 1789            select_prev_state: None,
 1790            selection_history: Default::default(),
 1791            autoclose_regions: Default::default(),
 1792            snippet_stack: Default::default(),
 1793            select_larger_syntax_node_stack: Vec::new(),
 1794            ime_transaction: Default::default(),
 1795            active_diagnostics: None,
 1796            soft_wrap_mode_override,
 1797            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1798            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1799            project,
 1800            blink_manager: blink_manager.clone(),
 1801            show_local_selections: true,
 1802            mode,
 1803            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1804            show_gutter: mode == EditorMode::Full,
 1805            show_line_numbers: None,
 1806            show_git_diff_gutter: None,
 1807            show_code_actions: None,
 1808            show_runnables: None,
 1809            show_wrap_guides: None,
 1810            show_indent_guides,
 1811            placeholder_text: None,
 1812            highlight_order: 0,
 1813            highlighted_rows: HashMap::default(),
 1814            background_highlights: Default::default(),
 1815            gutter_highlights: TreeMap::default(),
 1816            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1817            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1818            nav_history: None,
 1819            context_menu: RwLock::new(None),
 1820            mouse_context_menu: None,
 1821            completion_tasks: Default::default(),
 1822            find_all_references_task_sources: Vec::new(),
 1823            next_completion_id: 0,
 1824            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1825            next_inlay_id: 0,
 1826            available_code_actions: Default::default(),
 1827            code_actions_task: Default::default(),
 1828            document_highlights_task: Default::default(),
 1829            linked_editing_range_task: Default::default(),
 1830            pending_rename: Default::default(),
 1831            searchable: true,
 1832            cursor_shape: Default::default(),
 1833            current_line_highlight: None,
 1834            autoindent_mode: Some(AutoindentMode::EachLine),
 1835            collapse_matches: false,
 1836            workspace: None,
 1837            keymap_context_layers: Default::default(),
 1838            input_enabled: true,
 1839            use_modal_editing: mode == EditorMode::Full,
 1840            read_only: false,
 1841            use_autoclose: true,
 1842            use_auto_surround: true,
 1843            auto_replace_emoji_shortcode: false,
 1844            leader_peer_id: None,
 1845            remote_id: None,
 1846            hover_state: Default::default(),
 1847            hovered_link_state: Default::default(),
 1848            inline_completion_provider: None,
 1849            active_inline_completion: None,
 1850            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1851            expanded_hunks: ExpandedHunks::default(),
 1852            gutter_hovered: false,
 1853            pixel_position_of_newest_cursor: None,
 1854            last_bounds: None,
 1855            expect_bounds_change: None,
 1856            gutter_dimensions: GutterDimensions::default(),
 1857            style: None,
 1858            show_cursor_names: false,
 1859            hovered_cursors: Default::default(),
 1860            next_editor_action_id: EditorActionId::default(),
 1861            editor_actions: Rc::default(),
 1862            vim_replace_map: Default::default(),
 1863            show_inline_completions: mode == EditorMode::Full,
 1864            custom_context_menu: None,
 1865            show_git_blame_gutter: false,
 1866            show_git_blame_inline: false,
 1867            show_selection_menu: None,
 1868            show_git_blame_inline_delay_task: None,
 1869            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1870            blame: None,
 1871            blame_subscription: None,
 1872            file_header_size,
 1873            tasks: Default::default(),
 1874            _subscriptions: vec![
 1875                cx.observe(&buffer, Self::on_buffer_changed),
 1876                cx.subscribe(&buffer, Self::on_buffer_event),
 1877                cx.observe(&display_map, Self::on_display_map_changed),
 1878                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1879                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1880                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1881                cx.observe_window_activation(|editor, cx| {
 1882                    let active = cx.is_window_active();
 1883                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1884                        if active {
 1885                            blink_manager.enable(cx);
 1886                        } else {
 1887                            blink_manager.show_cursor(cx);
 1888                            blink_manager.disable(cx);
 1889                        }
 1890                    });
 1891                }),
 1892            ],
 1893            tasks_update_task: None,
 1894            linked_edit_ranges: Default::default(),
 1895            previous_search_ranges: None,
 1896            breadcrumb_header: None,
 1897        };
 1898        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1899        this._subscriptions.extend(project_subscriptions);
 1900
 1901        this.end_selection(cx);
 1902        this.scroll_manager.show_scrollbar(cx);
 1903
 1904        if mode == EditorMode::Full {
 1905            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1906            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1907
 1908            if this.git_blame_inline_enabled {
 1909                this.git_blame_inline_enabled = true;
 1910                this.start_git_blame_inline(false, cx);
 1911            }
 1912        }
 1913
 1914        this.report_editor_event("open", None, cx);
 1915        this
 1916    }
 1917
 1918    pub fn mouse_menu_is_focused(&self, cx: &mut WindowContext) -> bool {
 1919        self.mouse_context_menu
 1920            .as_ref()
 1921            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1922    }
 1923
 1924    fn key_context(&self, cx: &AppContext) -> KeyContext {
 1925        let mut key_context = KeyContext::new_with_defaults();
 1926        key_context.add("Editor");
 1927        let mode = match self.mode {
 1928            EditorMode::SingleLine { .. } => "single_line",
 1929            EditorMode::AutoHeight { .. } => "auto_height",
 1930            EditorMode::Full => "full",
 1931        };
 1932
 1933        if EditorSettings::get_global(cx).jupyter.enabled {
 1934            key_context.add("jupyter");
 1935        }
 1936
 1937        key_context.set("mode", mode);
 1938        if self.pending_rename.is_some() {
 1939            key_context.add("renaming");
 1940        }
 1941        if self.context_menu_visible() {
 1942            match self.context_menu.read().as_ref() {
 1943                Some(ContextMenu::Completions(_)) => {
 1944                    key_context.add("menu");
 1945                    key_context.add("showing_completions")
 1946                }
 1947                Some(ContextMenu::CodeActions(_)) => {
 1948                    key_context.add("menu");
 1949                    key_context.add("showing_code_actions")
 1950                }
 1951                None => {}
 1952            }
 1953        }
 1954
 1955        for layer in self.keymap_context_layers.values() {
 1956            key_context.extend(layer);
 1957        }
 1958
 1959        if let Some(extension) = self
 1960            .buffer
 1961            .read(cx)
 1962            .as_singleton()
 1963            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1964        {
 1965            key_context.set("extension", extension.to_string());
 1966        }
 1967
 1968        if self.has_active_inline_completion(cx) {
 1969            key_context.add("copilot_suggestion");
 1970            key_context.add("inline_completion");
 1971        }
 1972
 1973        key_context
 1974    }
 1975
 1976    pub fn new_file(
 1977        workspace: &mut Workspace,
 1978        _: &workspace::NewFile,
 1979        cx: &mut ViewContext<Workspace>,
 1980    ) {
 1981        let project = workspace.project().clone();
 1982        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1983
 1984        cx.spawn(|workspace, mut cx| async move {
 1985            let buffer = create.await?;
 1986            workspace.update(&mut cx, |workspace, cx| {
 1987                workspace.add_item_to_active_pane(
 1988                    Box::new(
 1989                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1990                    ),
 1991                    None,
 1992                    cx,
 1993                )
 1994            })
 1995        })
 1996        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1997            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1998                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1999                e.error_tag("required").unwrap_or("the latest version")
 2000            )),
 2001            _ => None,
 2002        });
 2003    }
 2004
 2005    pub fn new_file_in_direction(
 2006        workspace: &mut Workspace,
 2007        action: &workspace::NewFileInDirection,
 2008        cx: &mut ViewContext<Workspace>,
 2009    ) {
 2010        let project = workspace.project().clone();
 2011        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2012        let direction = action.0;
 2013
 2014        cx.spawn(|workspace, mut cx| async move {
 2015            let buffer = create.await?;
 2016            workspace.update(&mut cx, move |workspace, cx| {
 2017                workspace.split_item(
 2018                    direction,
 2019                    Box::new(
 2020                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2021                    ),
 2022                    cx,
 2023                )
 2024            })?;
 2025            anyhow::Ok(())
 2026        })
 2027        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2028            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2029                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2030                e.error_tag("required").unwrap_or("the latest version")
 2031            )),
 2032            _ => None,
 2033        });
 2034    }
 2035
 2036    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
 2037        self.buffer.read(cx).replica_id()
 2038    }
 2039
 2040    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2041        self.leader_peer_id
 2042    }
 2043
 2044    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2045        &self.buffer
 2046    }
 2047
 2048    pub fn workspace(&self) -> Option<View<Workspace>> {
 2049        self.workspace.as_ref()?.0.upgrade()
 2050    }
 2051
 2052    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2053        self.buffer().read(cx).title(cx)
 2054    }
 2055
 2056    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2057        EditorSnapshot {
 2058            mode: self.mode,
 2059            show_gutter: self.show_gutter,
 2060            show_line_numbers: self.show_line_numbers,
 2061            show_git_diff_gutter: self.show_git_diff_gutter,
 2062            show_code_actions: self.show_code_actions,
 2063            show_runnables: self.show_runnables,
 2064            render_git_blame_gutter: self.render_git_blame_gutter(cx),
 2065            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2066            scroll_anchor: self.scroll_manager.anchor(),
 2067            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2068            placeholder_text: self.placeholder_text.clone(),
 2069            is_focused: self.focus_handle.is_focused(cx),
 2070            current_line_highlight: self
 2071                .current_line_highlight
 2072                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2073            gutter_hovered: self.gutter_hovered,
 2074        }
 2075    }
 2076
 2077    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2078        self.buffer.read(cx).language_at(point, cx)
 2079    }
 2080
 2081    pub fn file_at<T: ToOffset>(
 2082        &self,
 2083        point: T,
 2084        cx: &AppContext,
 2085    ) -> Option<Arc<dyn language::File>> {
 2086        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2087    }
 2088
 2089    pub fn active_excerpt(
 2090        &self,
 2091        cx: &AppContext,
 2092    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2093        self.buffer
 2094            .read(cx)
 2095            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2096    }
 2097
 2098    pub fn mode(&self) -> EditorMode {
 2099        self.mode
 2100    }
 2101
 2102    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2103        self.collaboration_hub.as_deref()
 2104    }
 2105
 2106    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2107        self.collaboration_hub = Some(hub);
 2108    }
 2109
 2110    pub fn set_custom_context_menu(
 2111        &mut self,
 2112        f: impl 'static
 2113            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2114    ) {
 2115        self.custom_context_menu = Some(Box::new(f))
 2116    }
 2117
 2118    pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
 2119        self.completion_provider = Some(provider);
 2120    }
 2121
 2122    pub fn set_inline_completion_provider<T>(
 2123        &mut self,
 2124        provider: Option<Model<T>>,
 2125        cx: &mut ViewContext<Self>,
 2126    ) where
 2127        T: InlineCompletionProvider,
 2128    {
 2129        self.inline_completion_provider =
 2130            provider.map(|provider| RegisteredInlineCompletionProvider {
 2131                _subscription: cx.observe(&provider, |this, _, cx| {
 2132                    if this.focus_handle.is_focused(cx) {
 2133                        this.update_visible_inline_completion(cx);
 2134                    }
 2135                }),
 2136                provider: Arc::new(provider),
 2137            });
 2138        self.refresh_inline_completion(false, cx);
 2139    }
 2140
 2141    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2142        self.placeholder_text.as_deref()
 2143    }
 2144
 2145    pub fn set_placeholder_text(
 2146        &mut self,
 2147        placeholder_text: impl Into<Arc<str>>,
 2148        cx: &mut ViewContext<Self>,
 2149    ) {
 2150        let placeholder_text = Some(placeholder_text.into());
 2151        if self.placeholder_text != placeholder_text {
 2152            self.placeholder_text = placeholder_text;
 2153            cx.notify();
 2154        }
 2155    }
 2156
 2157    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2158        self.cursor_shape = cursor_shape;
 2159        cx.notify();
 2160    }
 2161
 2162    pub fn set_current_line_highlight(
 2163        &mut self,
 2164        current_line_highlight: Option<CurrentLineHighlight>,
 2165    ) {
 2166        self.current_line_highlight = current_line_highlight;
 2167    }
 2168
 2169    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2170        self.collapse_matches = collapse_matches;
 2171    }
 2172
 2173    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2174        if self.collapse_matches {
 2175            return range.start..range.start;
 2176        }
 2177        range.clone()
 2178    }
 2179
 2180    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2181        if self.display_map.read(cx).clip_at_line_ends != clip {
 2182            self.display_map
 2183                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2184        }
 2185    }
 2186
 2187    pub fn set_keymap_context_layer<Tag: 'static>(
 2188        &mut self,
 2189        context: KeyContext,
 2190        cx: &mut ViewContext<Self>,
 2191    ) {
 2192        self.keymap_context_layers
 2193            .insert(TypeId::of::<Tag>(), context);
 2194        cx.notify();
 2195    }
 2196
 2197    pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
 2198        self.keymap_context_layers.remove(&TypeId::of::<Tag>());
 2199        cx.notify();
 2200    }
 2201
 2202    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2203        self.input_enabled = input_enabled;
 2204    }
 2205
 2206    pub fn set_autoindent(&mut self, autoindent: bool) {
 2207        if autoindent {
 2208            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2209        } else {
 2210            self.autoindent_mode = None;
 2211        }
 2212    }
 2213
 2214    pub fn read_only(&self, cx: &AppContext) -> bool {
 2215        self.read_only || self.buffer.read(cx).read_only()
 2216    }
 2217
 2218    pub fn set_read_only(&mut self, read_only: bool) {
 2219        self.read_only = read_only;
 2220    }
 2221
 2222    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2223        self.use_autoclose = autoclose;
 2224    }
 2225
 2226    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2227        self.use_auto_surround = auto_surround;
 2228    }
 2229
 2230    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2231        self.auto_replace_emoji_shortcode = auto_replace;
 2232    }
 2233
 2234    pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
 2235        self.show_inline_completions = show_inline_completions;
 2236    }
 2237
 2238    pub fn set_use_modal_editing(&mut self, to: bool) {
 2239        self.use_modal_editing = to;
 2240    }
 2241
 2242    pub fn use_modal_editing(&self) -> bool {
 2243        self.use_modal_editing
 2244    }
 2245
 2246    fn selections_did_change(
 2247        &mut self,
 2248        local: bool,
 2249        old_cursor_position: &Anchor,
 2250        show_completions: bool,
 2251        cx: &mut ViewContext<Self>,
 2252    ) {
 2253        // Copy selections to primary selection buffer
 2254        #[cfg(target_os = "linux")]
 2255        if local {
 2256            let selections = self.selections.all::<usize>(cx);
 2257            let buffer_handle = self.buffer.read(cx).read(cx);
 2258
 2259            let mut text = String::new();
 2260            for (index, selection) in selections.iter().enumerate() {
 2261                let text_for_selection = buffer_handle
 2262                    .text_for_range(selection.start..selection.end)
 2263                    .collect::<String>();
 2264
 2265                text.push_str(&text_for_selection);
 2266                if index != selections.len() - 1 {
 2267                    text.push('\n');
 2268                }
 2269            }
 2270
 2271            if !text.is_empty() {
 2272                cx.write_to_primary(ClipboardItem::new(text));
 2273            }
 2274        }
 2275
 2276        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2277            self.buffer.update(cx, |buffer, cx| {
 2278                buffer.set_active_selections(
 2279                    &self.selections.disjoint_anchors(),
 2280                    self.selections.line_mode,
 2281                    self.cursor_shape,
 2282                    cx,
 2283                )
 2284            });
 2285        }
 2286        let display_map = self
 2287            .display_map
 2288            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2289        let buffer = &display_map.buffer_snapshot;
 2290        self.add_selections_state = None;
 2291        self.select_next_state = None;
 2292        self.select_prev_state = None;
 2293        self.select_larger_syntax_node_stack.clear();
 2294        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2295        self.snippet_stack
 2296            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2297        self.take_rename(false, cx);
 2298
 2299        let new_cursor_position = self.selections.newest_anchor().head();
 2300
 2301        self.push_to_nav_history(
 2302            *old_cursor_position,
 2303            Some(new_cursor_position.to_point(buffer)),
 2304            cx,
 2305        );
 2306
 2307        if local {
 2308            let new_cursor_position = self.selections.newest_anchor().head();
 2309            let mut context_menu = self.context_menu.write();
 2310            let completion_menu = match context_menu.as_ref() {
 2311                Some(ContextMenu::Completions(menu)) => Some(menu),
 2312
 2313                _ => {
 2314                    *context_menu = None;
 2315                    None
 2316                }
 2317            };
 2318
 2319            if let Some(completion_menu) = completion_menu {
 2320                let cursor_position = new_cursor_position.to_offset(buffer);
 2321                let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
 2322                if kind == Some(CharKind::Word)
 2323                    && word_range.to_inclusive().contains(&cursor_position)
 2324                {
 2325                    let mut completion_menu = completion_menu.clone();
 2326                    drop(context_menu);
 2327
 2328                    let query = Self::completion_query(buffer, cursor_position);
 2329                    cx.spawn(move |this, mut cx| async move {
 2330                        completion_menu
 2331                            .filter(query.as_deref(), cx.background_executor().clone())
 2332                            .await;
 2333
 2334                        this.update(&mut cx, |this, cx| {
 2335                            let mut context_menu = this.context_menu.write();
 2336                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2337                                return;
 2338                            };
 2339
 2340                            if menu.id > completion_menu.id {
 2341                                return;
 2342                            }
 2343
 2344                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2345                            drop(context_menu);
 2346                            cx.notify();
 2347                        })
 2348                    })
 2349                    .detach();
 2350
 2351                    if show_completions {
 2352                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2353                    }
 2354                } else {
 2355                    drop(context_menu);
 2356                    self.hide_context_menu(cx);
 2357                }
 2358            } else {
 2359                drop(context_menu);
 2360            }
 2361
 2362            hide_hover(self, cx);
 2363
 2364            if old_cursor_position.to_display_point(&display_map).row()
 2365                != new_cursor_position.to_display_point(&display_map).row()
 2366            {
 2367                self.available_code_actions.take();
 2368            }
 2369            self.refresh_code_actions(cx);
 2370            self.refresh_document_highlights(cx);
 2371            refresh_matching_bracket_highlights(self, cx);
 2372            self.discard_inline_completion(false, cx);
 2373            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2374            if self.git_blame_inline_enabled {
 2375                self.start_inline_blame_timer(cx);
 2376            }
 2377        }
 2378
 2379        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2380        cx.emit(EditorEvent::SelectionsChanged { local });
 2381
 2382        if self.selections.disjoint_anchors().len() == 1 {
 2383            cx.emit(SearchEvent::ActiveMatchChanged)
 2384        }
 2385        cx.notify();
 2386    }
 2387
 2388    pub fn change_selections<R>(
 2389        &mut self,
 2390        autoscroll: Option<Autoscroll>,
 2391        cx: &mut ViewContext<Self>,
 2392        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2393    ) -> R {
 2394        self.change_selections_inner(autoscroll, true, cx, change)
 2395    }
 2396
 2397    pub fn change_selections_inner<R>(
 2398        &mut self,
 2399        autoscroll: Option<Autoscroll>,
 2400        request_completions: bool,
 2401        cx: &mut ViewContext<Self>,
 2402        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2403    ) -> R {
 2404        let old_cursor_position = self.selections.newest_anchor().head();
 2405        self.push_to_selection_history();
 2406
 2407        let (changed, result) = self.selections.change_with(cx, change);
 2408
 2409        if changed {
 2410            if let Some(autoscroll) = autoscroll {
 2411                self.request_autoscroll(autoscroll, cx);
 2412            }
 2413            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2414        }
 2415
 2416        result
 2417    }
 2418
 2419    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2420    where
 2421        I: IntoIterator<Item = (Range<S>, T)>,
 2422        S: ToOffset,
 2423        T: Into<Arc<str>>,
 2424    {
 2425        if self.read_only(cx) {
 2426            return;
 2427        }
 2428
 2429        self.buffer
 2430            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2431    }
 2432
 2433    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2434    where
 2435        I: IntoIterator<Item = (Range<S>, T)>,
 2436        S: ToOffset,
 2437        T: Into<Arc<str>>,
 2438    {
 2439        if self.read_only(cx) {
 2440            return;
 2441        }
 2442
 2443        self.buffer.update(cx, |buffer, cx| {
 2444            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2445        });
 2446    }
 2447
 2448    pub fn edit_with_block_indent<I, S, T>(
 2449        &mut self,
 2450        edits: I,
 2451        original_indent_columns: Vec<u32>,
 2452        cx: &mut ViewContext<Self>,
 2453    ) where
 2454        I: IntoIterator<Item = (Range<S>, T)>,
 2455        S: ToOffset,
 2456        T: Into<Arc<str>>,
 2457    {
 2458        if self.read_only(cx) {
 2459            return;
 2460        }
 2461
 2462        self.buffer.update(cx, |buffer, cx| {
 2463            buffer.edit(
 2464                edits,
 2465                Some(AutoindentMode::Block {
 2466                    original_indent_columns,
 2467                }),
 2468                cx,
 2469            )
 2470        });
 2471    }
 2472
 2473    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2474        self.hide_context_menu(cx);
 2475
 2476        match phase {
 2477            SelectPhase::Begin {
 2478                position,
 2479                add,
 2480                click_count,
 2481            } => self.begin_selection(position, add, click_count, cx),
 2482            SelectPhase::BeginColumnar {
 2483                position,
 2484                goal_column,
 2485                reset,
 2486            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2487            SelectPhase::Extend {
 2488                position,
 2489                click_count,
 2490            } => self.extend_selection(position, click_count, cx),
 2491            SelectPhase::Update {
 2492                position,
 2493                goal_column,
 2494                scroll_delta,
 2495            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2496            SelectPhase::End => self.end_selection(cx),
 2497        }
 2498    }
 2499
 2500    fn extend_selection(
 2501        &mut self,
 2502        position: DisplayPoint,
 2503        click_count: usize,
 2504        cx: &mut ViewContext<Self>,
 2505    ) {
 2506        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2507        let tail = self.selections.newest::<usize>(cx).tail();
 2508        self.begin_selection(position, false, click_count, cx);
 2509
 2510        let position = position.to_offset(&display_map, Bias::Left);
 2511        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2512
 2513        let mut pending_selection = self
 2514            .selections
 2515            .pending_anchor()
 2516            .expect("extend_selection not called with pending selection");
 2517        if position >= tail {
 2518            pending_selection.start = tail_anchor;
 2519        } else {
 2520            pending_selection.end = tail_anchor;
 2521            pending_selection.reversed = true;
 2522        }
 2523
 2524        let mut pending_mode = self.selections.pending_mode().unwrap();
 2525        match &mut pending_mode {
 2526            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2527            _ => {}
 2528        }
 2529
 2530        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2531            s.set_pending(pending_selection, pending_mode)
 2532        });
 2533    }
 2534
 2535    fn begin_selection(
 2536        &mut self,
 2537        position: DisplayPoint,
 2538        add: bool,
 2539        click_count: usize,
 2540        cx: &mut ViewContext<Self>,
 2541    ) {
 2542        if !self.focus_handle.is_focused(cx) {
 2543            self.last_focused_descendant = None;
 2544            cx.focus(&self.focus_handle);
 2545        }
 2546
 2547        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2548        let buffer = &display_map.buffer_snapshot;
 2549        let newest_selection = self.selections.newest_anchor().clone();
 2550        let position = display_map.clip_point(position, Bias::Left);
 2551
 2552        let start;
 2553        let end;
 2554        let mode;
 2555        let auto_scroll;
 2556        match click_count {
 2557            1 => {
 2558                start = buffer.anchor_before(position.to_point(&display_map));
 2559                end = start;
 2560                mode = SelectMode::Character;
 2561                auto_scroll = true;
 2562            }
 2563            2 => {
 2564                let range = movement::surrounding_word(&display_map, position);
 2565                start = buffer.anchor_before(range.start.to_point(&display_map));
 2566                end = buffer.anchor_before(range.end.to_point(&display_map));
 2567                mode = SelectMode::Word(start..end);
 2568                auto_scroll = true;
 2569            }
 2570            3 => {
 2571                let position = display_map
 2572                    .clip_point(position, Bias::Left)
 2573                    .to_point(&display_map);
 2574                let line_start = display_map.prev_line_boundary(position).0;
 2575                let next_line_start = buffer.clip_point(
 2576                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2577                    Bias::Left,
 2578                );
 2579                start = buffer.anchor_before(line_start);
 2580                end = buffer.anchor_before(next_line_start);
 2581                mode = SelectMode::Line(start..end);
 2582                auto_scroll = true;
 2583            }
 2584            _ => {
 2585                start = buffer.anchor_before(0);
 2586                end = buffer.anchor_before(buffer.len());
 2587                mode = SelectMode::All;
 2588                auto_scroll = false;
 2589            }
 2590        }
 2591
 2592        let point_to_delete: Option<usize> = {
 2593            let selected_points: Vec<Selection<Point>> =
 2594                self.selections.disjoint_in_range(start..end, cx);
 2595
 2596            if !add || click_count > 1 {
 2597                None
 2598            } else if selected_points.len() > 0 {
 2599                Some(selected_points[0].id)
 2600            } else {
 2601                let clicked_point_already_selected =
 2602                    self.selections.disjoint.iter().find(|selection| {
 2603                        selection.start.to_point(buffer) == start.to_point(buffer)
 2604                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2605                    });
 2606
 2607                if let Some(selection) = clicked_point_already_selected {
 2608                    Some(selection.id)
 2609                } else {
 2610                    None
 2611                }
 2612            }
 2613        };
 2614
 2615        let selections_count = self.selections.count();
 2616
 2617        self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
 2618            if let Some(point_to_delete) = point_to_delete {
 2619                s.delete(point_to_delete);
 2620
 2621                if selections_count == 1 {
 2622                    s.set_pending_anchor_range(start..end, mode);
 2623                }
 2624            } else {
 2625                if !add {
 2626                    s.clear_disjoint();
 2627                } else if click_count > 1 {
 2628                    s.delete(newest_selection.id)
 2629                }
 2630
 2631                s.set_pending_anchor_range(start..end, mode);
 2632            }
 2633        });
 2634    }
 2635
 2636    fn begin_columnar_selection(
 2637        &mut self,
 2638        position: DisplayPoint,
 2639        goal_column: u32,
 2640        reset: bool,
 2641        cx: &mut ViewContext<Self>,
 2642    ) {
 2643        if !self.focus_handle.is_focused(cx) {
 2644            self.last_focused_descendant = None;
 2645            cx.focus(&self.focus_handle);
 2646        }
 2647
 2648        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2649
 2650        if reset {
 2651            let pointer_position = display_map
 2652                .buffer_snapshot
 2653                .anchor_before(position.to_point(&display_map));
 2654
 2655            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2656                s.clear_disjoint();
 2657                s.set_pending_anchor_range(
 2658                    pointer_position..pointer_position,
 2659                    SelectMode::Character,
 2660                );
 2661            });
 2662        }
 2663
 2664        let tail = self.selections.newest::<Point>(cx).tail();
 2665        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2666
 2667        if !reset {
 2668            self.select_columns(
 2669                tail.to_display_point(&display_map),
 2670                position,
 2671                goal_column,
 2672                &display_map,
 2673                cx,
 2674            );
 2675        }
 2676    }
 2677
 2678    fn update_selection(
 2679        &mut self,
 2680        position: DisplayPoint,
 2681        goal_column: u32,
 2682        scroll_delta: gpui::Point<f32>,
 2683        cx: &mut ViewContext<Self>,
 2684    ) {
 2685        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2686
 2687        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2688            let tail = tail.to_display_point(&display_map);
 2689            self.select_columns(tail, position, goal_column, &display_map, cx);
 2690        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2691            let buffer = self.buffer.read(cx).snapshot(cx);
 2692            let head;
 2693            let tail;
 2694            let mode = self.selections.pending_mode().unwrap();
 2695            match &mode {
 2696                SelectMode::Character => {
 2697                    head = position.to_point(&display_map);
 2698                    tail = pending.tail().to_point(&buffer);
 2699                }
 2700                SelectMode::Word(original_range) => {
 2701                    let original_display_range = original_range.start.to_display_point(&display_map)
 2702                        ..original_range.end.to_display_point(&display_map);
 2703                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2704                        ..original_display_range.end.to_point(&display_map);
 2705                    if movement::is_inside_word(&display_map, position)
 2706                        || original_display_range.contains(&position)
 2707                    {
 2708                        let word_range = movement::surrounding_word(&display_map, position);
 2709                        if word_range.start < original_display_range.start {
 2710                            head = word_range.start.to_point(&display_map);
 2711                        } else {
 2712                            head = word_range.end.to_point(&display_map);
 2713                        }
 2714                    } else {
 2715                        head = position.to_point(&display_map);
 2716                    }
 2717
 2718                    if head <= original_buffer_range.start {
 2719                        tail = original_buffer_range.end;
 2720                    } else {
 2721                        tail = original_buffer_range.start;
 2722                    }
 2723                }
 2724                SelectMode::Line(original_range) => {
 2725                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2726
 2727                    let position = display_map
 2728                        .clip_point(position, Bias::Left)
 2729                        .to_point(&display_map);
 2730                    let line_start = display_map.prev_line_boundary(position).0;
 2731                    let next_line_start = buffer.clip_point(
 2732                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2733                        Bias::Left,
 2734                    );
 2735
 2736                    if line_start < original_range.start {
 2737                        head = line_start
 2738                    } else {
 2739                        head = next_line_start
 2740                    }
 2741
 2742                    if head <= original_range.start {
 2743                        tail = original_range.end;
 2744                    } else {
 2745                        tail = original_range.start;
 2746                    }
 2747                }
 2748                SelectMode::All => {
 2749                    return;
 2750                }
 2751            };
 2752
 2753            if head < tail {
 2754                pending.start = buffer.anchor_before(head);
 2755                pending.end = buffer.anchor_before(tail);
 2756                pending.reversed = true;
 2757            } else {
 2758                pending.start = buffer.anchor_before(tail);
 2759                pending.end = buffer.anchor_before(head);
 2760                pending.reversed = false;
 2761            }
 2762
 2763            self.change_selections(None, cx, |s| {
 2764                s.set_pending(pending, mode);
 2765            });
 2766        } else {
 2767            log::error!("update_selection dispatched with no pending selection");
 2768            return;
 2769        }
 2770
 2771        self.apply_scroll_delta(scroll_delta, cx);
 2772        cx.notify();
 2773    }
 2774
 2775    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2776        self.columnar_selection_tail.take();
 2777        if self.selections.pending_anchor().is_some() {
 2778            let selections = self.selections.all::<usize>(cx);
 2779            self.change_selections(None, cx, |s| {
 2780                s.select(selections);
 2781                s.clear_pending();
 2782            });
 2783        }
 2784    }
 2785
 2786    fn select_columns(
 2787        &mut self,
 2788        tail: DisplayPoint,
 2789        head: DisplayPoint,
 2790        goal_column: u32,
 2791        display_map: &DisplaySnapshot,
 2792        cx: &mut ViewContext<Self>,
 2793    ) {
 2794        let start_row = cmp::min(tail.row(), head.row());
 2795        let end_row = cmp::max(tail.row(), head.row());
 2796        let start_column = cmp::min(tail.column(), goal_column);
 2797        let end_column = cmp::max(tail.column(), goal_column);
 2798        let reversed = start_column < tail.column();
 2799
 2800        let selection_ranges = (start_row.0..=end_row.0)
 2801            .map(DisplayRow)
 2802            .filter_map(|row| {
 2803                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2804                    let start = display_map
 2805                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2806                        .to_point(display_map);
 2807                    let end = display_map
 2808                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2809                        .to_point(display_map);
 2810                    if reversed {
 2811                        Some(end..start)
 2812                    } else {
 2813                        Some(start..end)
 2814                    }
 2815                } else {
 2816                    None
 2817                }
 2818            })
 2819            .collect::<Vec<_>>();
 2820
 2821        self.change_selections(None, cx, |s| {
 2822            s.select_ranges(selection_ranges);
 2823        });
 2824        cx.notify();
 2825    }
 2826
 2827    pub fn has_pending_nonempty_selection(&self) -> bool {
 2828        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2829            Some(Selection { start, end, .. }) => start != end,
 2830            None => false,
 2831        };
 2832
 2833        pending_nonempty_selection
 2834            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2835    }
 2836
 2837    pub fn has_pending_selection(&self) -> bool {
 2838        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2839    }
 2840
 2841    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2842        self.clear_expanded_diff_hunks(cx);
 2843        if self.dismiss_menus_and_popups(true, cx) {
 2844            return;
 2845        }
 2846
 2847        if self.mode == EditorMode::Full {
 2848            if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
 2849                return;
 2850            }
 2851        }
 2852
 2853        cx.propagate();
 2854    }
 2855
 2856    pub fn dismiss_menus_and_popups(
 2857        &mut self,
 2858        should_report_inline_completion_event: bool,
 2859        cx: &mut ViewContext<Self>,
 2860    ) -> bool {
 2861        if self.take_rename(false, cx).is_some() {
 2862            return true;
 2863        }
 2864
 2865        if hide_hover(self, cx) {
 2866            return true;
 2867        }
 2868
 2869        if self.hide_context_menu(cx).is_some() {
 2870            return true;
 2871        }
 2872
 2873        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2874            return true;
 2875        }
 2876
 2877        if self.snippet_stack.pop().is_some() {
 2878            return true;
 2879        }
 2880
 2881        if self.mode == EditorMode::Full {
 2882            if self.active_diagnostics.is_some() {
 2883                self.dismiss_diagnostics(cx);
 2884                return true;
 2885            }
 2886        }
 2887
 2888        false
 2889    }
 2890
 2891    fn linked_editing_ranges_for(
 2892        &self,
 2893        selection: Range<text::Anchor>,
 2894        cx: &AppContext,
 2895    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2896        if self.linked_edit_ranges.is_empty() {
 2897            return None;
 2898        }
 2899        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2900            selection.end.buffer_id.and_then(|end_buffer_id| {
 2901                if selection.start.buffer_id != Some(end_buffer_id) {
 2902                    return None;
 2903                }
 2904                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2905                let snapshot = buffer.read(cx).snapshot();
 2906                self.linked_edit_ranges
 2907                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2908                    .map(|ranges| (ranges, snapshot, buffer))
 2909            })?;
 2910        use text::ToOffset as TO;
 2911        // find offset from the start of current range to current cursor position
 2912        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2913
 2914        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2915        let start_difference = start_offset - start_byte_offset;
 2916        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2917        let end_difference = end_offset - start_byte_offset;
 2918        // Current range has associated linked ranges.
 2919        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2920        for range in linked_ranges.iter() {
 2921            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2922            let end_offset = start_offset + end_difference;
 2923            let start_offset = start_offset + start_difference;
 2924            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2925                continue;
 2926            }
 2927            let start = buffer_snapshot.anchor_after(start_offset);
 2928            let end = buffer_snapshot.anchor_after(end_offset);
 2929            linked_edits
 2930                .entry(buffer.clone())
 2931                .or_default()
 2932                .push(start..end);
 2933        }
 2934        Some(linked_edits)
 2935    }
 2936
 2937    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2938        let text: Arc<str> = text.into();
 2939
 2940        if self.read_only(cx) {
 2941            return;
 2942        }
 2943
 2944        let selections = self.selections.all_adjusted(cx);
 2945        let mut brace_inserted = false;
 2946        let mut edits = Vec::new();
 2947        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2948        let mut new_selections = Vec::with_capacity(selections.len());
 2949        let mut new_autoclose_regions = Vec::new();
 2950        let snapshot = self.buffer.read(cx).read(cx);
 2951
 2952        for (selection, autoclose_region) in
 2953            self.selections_with_autoclose_regions(selections, &snapshot)
 2954        {
 2955            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2956                // Determine if the inserted text matches the opening or closing
 2957                // bracket of any of this language's bracket pairs.
 2958                let mut bracket_pair = None;
 2959                let mut is_bracket_pair_start = false;
 2960                let mut is_bracket_pair_end = false;
 2961                if !text.is_empty() {
 2962                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2963                    //  and they are removing the character that triggered IME popup.
 2964                    for (pair, enabled) in scope.brackets() {
 2965                        if !pair.close && !pair.surround {
 2966                            continue;
 2967                        }
 2968
 2969                        if enabled && pair.start.ends_with(text.as_ref()) {
 2970                            bracket_pair = Some(pair.clone());
 2971                            is_bracket_pair_start = true;
 2972                            break;
 2973                        }
 2974                        if pair.end.as_str() == text.as_ref() {
 2975                            bracket_pair = Some(pair.clone());
 2976                            is_bracket_pair_end = true;
 2977                            break;
 2978                        }
 2979                    }
 2980                }
 2981
 2982                if let Some(bracket_pair) = bracket_pair {
 2983                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2984                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2985                    let auto_surround =
 2986                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2987                    if selection.is_empty() {
 2988                        if is_bracket_pair_start {
 2989                            let prefix_len = bracket_pair.start.len() - text.len();
 2990
 2991                            // If the inserted text is a suffix of an opening bracket and the
 2992                            // selection is preceded by the rest of the opening bracket, then
 2993                            // insert the closing bracket.
 2994                            let following_text_allows_autoclose = snapshot
 2995                                .chars_at(selection.start)
 2996                                .next()
 2997                                .map_or(true, |c| scope.should_autoclose_before(c));
 2998                            let preceding_text_matches_prefix = prefix_len == 0
 2999                                || (selection.start.column >= (prefix_len as u32)
 3000                                    && snapshot.contains_str_at(
 3001                                        Point::new(
 3002                                            selection.start.row,
 3003                                            selection.start.column - (prefix_len as u32),
 3004                                        ),
 3005                                        &bracket_pair.start[..prefix_len],
 3006                                    ));
 3007                            if autoclose
 3008                                && bracket_pair.close
 3009                                && following_text_allows_autoclose
 3010                                && preceding_text_matches_prefix
 3011                            {
 3012                                let anchor = snapshot.anchor_before(selection.end);
 3013                                new_selections.push((selection.map(|_| anchor), text.len()));
 3014                                new_autoclose_regions.push((
 3015                                    anchor,
 3016                                    text.len(),
 3017                                    selection.id,
 3018                                    bracket_pair.clone(),
 3019                                ));
 3020                                edits.push((
 3021                                    selection.range(),
 3022                                    format!("{}{}", text, bracket_pair.end).into(),
 3023                                ));
 3024                                brace_inserted = true;
 3025                                continue;
 3026                            }
 3027                        }
 3028
 3029                        if let Some(region) = autoclose_region {
 3030                            // If the selection is followed by an auto-inserted closing bracket,
 3031                            // then don't insert that closing bracket again; just move the selection
 3032                            // past the closing bracket.
 3033                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3034                                && text.as_ref() == region.pair.end.as_str();
 3035                            if should_skip {
 3036                                let anchor = snapshot.anchor_after(selection.end);
 3037                                new_selections
 3038                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3039                                continue;
 3040                            }
 3041                        }
 3042
 3043                        let always_treat_brackets_as_autoclosed = snapshot
 3044                            .settings_at(selection.start, cx)
 3045                            .always_treat_brackets_as_autoclosed;
 3046                        if always_treat_brackets_as_autoclosed
 3047                            && is_bracket_pair_end
 3048                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3049                        {
 3050                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3051                            // and the inserted text is a closing bracket and the selection is followed
 3052                            // by the closing bracket then move the selection past the closing bracket.
 3053                            let anchor = snapshot.anchor_after(selection.end);
 3054                            new_selections.push((selection.map(|_| anchor), text.len()));
 3055                            continue;
 3056                        }
 3057                    }
 3058                    // If an opening bracket is 1 character long and is typed while
 3059                    // text is selected, then surround that text with the bracket pair.
 3060                    else if auto_surround
 3061                        && bracket_pair.surround
 3062                        && is_bracket_pair_start
 3063                        && bracket_pair.start.chars().count() == 1
 3064                    {
 3065                        edits.push((selection.start..selection.start, text.clone()));
 3066                        edits.push((
 3067                            selection.end..selection.end,
 3068                            bracket_pair.end.as_str().into(),
 3069                        ));
 3070                        brace_inserted = true;
 3071                        new_selections.push((
 3072                            Selection {
 3073                                id: selection.id,
 3074                                start: snapshot.anchor_after(selection.start),
 3075                                end: snapshot.anchor_before(selection.end),
 3076                                reversed: selection.reversed,
 3077                                goal: selection.goal,
 3078                            },
 3079                            0,
 3080                        ));
 3081                        continue;
 3082                    }
 3083                }
 3084            }
 3085
 3086            if self.auto_replace_emoji_shortcode
 3087                && selection.is_empty()
 3088                && text.as_ref().ends_with(':')
 3089            {
 3090                if let Some(possible_emoji_short_code) =
 3091                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3092                {
 3093                    if !possible_emoji_short_code.is_empty() {
 3094                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3095                            let emoji_shortcode_start = Point::new(
 3096                                selection.start.row,
 3097                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3098                            );
 3099
 3100                            // Remove shortcode from buffer
 3101                            edits.push((
 3102                                emoji_shortcode_start..selection.start,
 3103                                "".to_string().into(),
 3104                            ));
 3105                            new_selections.push((
 3106                                Selection {
 3107                                    id: selection.id,
 3108                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3109                                    end: snapshot.anchor_before(selection.start),
 3110                                    reversed: selection.reversed,
 3111                                    goal: selection.goal,
 3112                                },
 3113                                0,
 3114                            ));
 3115
 3116                            // Insert emoji
 3117                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3118                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3119                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3120
 3121                            continue;
 3122                        }
 3123                    }
 3124                }
 3125            }
 3126
 3127            // If not handling any auto-close operation, then just replace the selected
 3128            // text with the given input and move the selection to the end of the
 3129            // newly inserted text.
 3130            let anchor = snapshot.anchor_after(selection.end);
 3131            if !self.linked_edit_ranges.is_empty() {
 3132                let start_anchor = snapshot.anchor_before(selection.start);
 3133
 3134                let is_word_char = text.chars().next().map_or(true, |char| {
 3135                    let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
 3136                    let kind = char_kind(&scope, char);
 3137
 3138                    kind == CharKind::Word
 3139                });
 3140
 3141                if is_word_char {
 3142                    if let Some(ranges) = self
 3143                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3144                    {
 3145                        for (buffer, edits) in ranges {
 3146                            linked_edits
 3147                                .entry(buffer.clone())
 3148                                .or_default()
 3149                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3150                        }
 3151                    }
 3152                }
 3153            }
 3154
 3155            new_selections.push((selection.map(|_| anchor), 0));
 3156            edits.push((selection.start..selection.end, text.clone()));
 3157        }
 3158
 3159        drop(snapshot);
 3160
 3161        self.transact(cx, |this, cx| {
 3162            this.buffer.update(cx, |buffer, cx| {
 3163                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3164            });
 3165            for (buffer, edits) in linked_edits {
 3166                buffer.update(cx, |buffer, cx| {
 3167                    let snapshot = buffer.snapshot();
 3168                    let edits = edits
 3169                        .into_iter()
 3170                        .map(|(range, text)| {
 3171                            use text::ToPoint as TP;
 3172                            let end_point = TP::to_point(&range.end, &snapshot);
 3173                            let start_point = TP::to_point(&range.start, &snapshot);
 3174                            (start_point..end_point, text)
 3175                        })
 3176                        .sorted_by_key(|(range, _)| range.start)
 3177                        .collect::<Vec<_>>();
 3178                    buffer.edit(edits, None, cx);
 3179                })
 3180            }
 3181            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3182            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3183            let snapshot = this.buffer.read(cx).read(cx);
 3184            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3185                .zip(new_selection_deltas)
 3186                .map(|(selection, delta)| Selection {
 3187                    id: selection.id,
 3188                    start: selection.start + delta,
 3189                    end: selection.end + delta,
 3190                    reversed: selection.reversed,
 3191                    goal: SelectionGoal::None,
 3192                })
 3193                .collect::<Vec<_>>();
 3194
 3195            let mut i = 0;
 3196            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3197                let position = position.to_offset(&snapshot) + delta;
 3198                let start = snapshot.anchor_before(position);
 3199                let end = snapshot.anchor_after(position);
 3200                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3201                    match existing_state.range.start.cmp(&start, &snapshot) {
 3202                        Ordering::Less => i += 1,
 3203                        Ordering::Greater => break,
 3204                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3205                            Ordering::Less => i += 1,
 3206                            Ordering::Equal => break,
 3207                            Ordering::Greater => break,
 3208                        },
 3209                    }
 3210                }
 3211                this.autoclose_regions.insert(
 3212                    i,
 3213                    AutocloseRegion {
 3214                        selection_id,
 3215                        range: start..end,
 3216                        pair,
 3217                    },
 3218                );
 3219            }
 3220
 3221            drop(snapshot);
 3222            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3223            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3224                s.select(new_selections)
 3225            });
 3226
 3227            if !brace_inserted && EditorSettings::get_global(cx).use_on_type_format {
 3228                if let Some(on_type_format_task) =
 3229                    this.trigger_on_type_formatting(text.to_string(), cx)
 3230                {
 3231                    on_type_format_task.detach_and_log_err(cx);
 3232                }
 3233            }
 3234
 3235            let trigger_in_words = !had_active_inline_completion;
 3236            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3237            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3238            this.refresh_inline_completion(true, cx);
 3239        });
 3240    }
 3241
 3242    fn find_possible_emoji_shortcode_at_position(
 3243        snapshot: &MultiBufferSnapshot,
 3244        position: Point,
 3245    ) -> Option<String> {
 3246        let mut chars = Vec::new();
 3247        let mut found_colon = false;
 3248        for char in snapshot.reversed_chars_at(position).take(100) {
 3249            // Found a possible emoji shortcode in the middle of the buffer
 3250            if found_colon {
 3251                if char.is_whitespace() {
 3252                    chars.reverse();
 3253                    return Some(chars.iter().collect());
 3254                }
 3255                // If the previous character is not a whitespace, we are in the middle of a word
 3256                // and we only want to complete the shortcode if the word is made up of other emojis
 3257                let mut containing_word = String::new();
 3258                for ch in snapshot
 3259                    .reversed_chars_at(position)
 3260                    .skip(chars.len() + 1)
 3261                    .take(100)
 3262                {
 3263                    if ch.is_whitespace() {
 3264                        break;
 3265                    }
 3266                    containing_word.push(ch);
 3267                }
 3268                let containing_word = containing_word.chars().rev().collect::<String>();
 3269                if util::word_consists_of_emojis(containing_word.as_str()) {
 3270                    chars.reverse();
 3271                    return Some(chars.iter().collect());
 3272                }
 3273            }
 3274
 3275            if char.is_whitespace() || !char.is_ascii() {
 3276                return None;
 3277            }
 3278            if char == ':' {
 3279                found_colon = true;
 3280            } else {
 3281                chars.push(char);
 3282            }
 3283        }
 3284        // Found a possible emoji shortcode at the beginning of the buffer
 3285        chars.reverse();
 3286        Some(chars.iter().collect())
 3287    }
 3288
 3289    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3290        self.transact(cx, |this, cx| {
 3291            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3292                let selections = this.selections.all::<usize>(cx);
 3293                let multi_buffer = this.buffer.read(cx);
 3294                let buffer = multi_buffer.snapshot(cx);
 3295                selections
 3296                    .iter()
 3297                    .map(|selection| {
 3298                        let start_point = selection.start.to_point(&buffer);
 3299                        let mut indent =
 3300                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3301                        indent.len = cmp::min(indent.len, start_point.column);
 3302                        let start = selection.start;
 3303                        let end = selection.end;
 3304                        let selection_is_empty = start == end;
 3305                        let language_scope = buffer.language_scope_at(start);
 3306                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3307                            &language_scope
 3308                        {
 3309                            let leading_whitespace_len = buffer
 3310                                .reversed_chars_at(start)
 3311                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3312                                .map(|c| c.len_utf8())
 3313                                .sum::<usize>();
 3314
 3315                            let trailing_whitespace_len = buffer
 3316                                .chars_at(end)
 3317                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3318                                .map(|c| c.len_utf8())
 3319                                .sum::<usize>();
 3320
 3321                            let insert_extra_newline =
 3322                                language.brackets().any(|(pair, enabled)| {
 3323                                    let pair_start = pair.start.trim_end();
 3324                                    let pair_end = pair.end.trim_start();
 3325
 3326                                    enabled
 3327                                        && pair.newline
 3328                                        && buffer.contains_str_at(
 3329                                            end + trailing_whitespace_len,
 3330                                            pair_end,
 3331                                        )
 3332                                        && buffer.contains_str_at(
 3333                                            (start - leading_whitespace_len)
 3334                                                .saturating_sub(pair_start.len()),
 3335                                            pair_start,
 3336                                        )
 3337                                });
 3338
 3339                            // Comment extension on newline is allowed only for cursor selections
 3340                            let comment_delimiter = maybe!({
 3341                                if !selection_is_empty {
 3342                                    return None;
 3343                                }
 3344
 3345                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3346                                    return None;
 3347                                }
 3348
 3349                                let delimiters = language.line_comment_prefixes();
 3350                                let max_len_of_delimiter =
 3351                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3352                                let (snapshot, range) =
 3353                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3354
 3355                                let mut index_of_first_non_whitespace = 0;
 3356                                let comment_candidate = snapshot
 3357                                    .chars_for_range(range)
 3358                                    .skip_while(|c| {
 3359                                        let should_skip = c.is_whitespace();
 3360                                        if should_skip {
 3361                                            index_of_first_non_whitespace += 1;
 3362                                        }
 3363                                        should_skip
 3364                                    })
 3365                                    .take(max_len_of_delimiter)
 3366                                    .collect::<String>();
 3367                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3368                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3369                                })?;
 3370                                let cursor_is_placed_after_comment_marker =
 3371                                    index_of_first_non_whitespace + comment_prefix.len()
 3372                                        <= start_point.column as usize;
 3373                                if cursor_is_placed_after_comment_marker {
 3374                                    Some(comment_prefix.clone())
 3375                                } else {
 3376                                    None
 3377                                }
 3378                            });
 3379                            (comment_delimiter, insert_extra_newline)
 3380                        } else {
 3381                            (None, false)
 3382                        };
 3383
 3384                        let capacity_for_delimiter = comment_delimiter
 3385                            .as_deref()
 3386                            .map(str::len)
 3387                            .unwrap_or_default();
 3388                        let mut new_text =
 3389                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3390                        new_text.push_str("\n");
 3391                        new_text.extend(indent.chars());
 3392                        if let Some(delimiter) = &comment_delimiter {
 3393                            new_text.push_str(&delimiter);
 3394                        }
 3395                        if insert_extra_newline {
 3396                            new_text = new_text.repeat(2);
 3397                        }
 3398
 3399                        let anchor = buffer.anchor_after(end);
 3400                        let new_selection = selection.map(|_| anchor);
 3401                        (
 3402                            (start..end, new_text),
 3403                            (insert_extra_newline, new_selection),
 3404                        )
 3405                    })
 3406                    .unzip()
 3407            };
 3408
 3409            this.edit_with_autoindent(edits, cx);
 3410            let buffer = this.buffer.read(cx).snapshot(cx);
 3411            let new_selections = selection_fixup_info
 3412                .into_iter()
 3413                .map(|(extra_newline_inserted, new_selection)| {
 3414                    let mut cursor = new_selection.end.to_point(&buffer);
 3415                    if extra_newline_inserted {
 3416                        cursor.row -= 1;
 3417                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3418                    }
 3419                    new_selection.map(|_| cursor)
 3420                })
 3421                .collect();
 3422
 3423            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3424            this.refresh_inline_completion(true, cx);
 3425        });
 3426    }
 3427
 3428    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3429        let buffer = self.buffer.read(cx);
 3430        let snapshot = buffer.snapshot(cx);
 3431
 3432        let mut edits = Vec::new();
 3433        let mut rows = Vec::new();
 3434
 3435        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3436            let cursor = selection.head();
 3437            let row = cursor.row;
 3438
 3439            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3440
 3441            let newline = "\n".to_string();
 3442            edits.push((start_of_line..start_of_line, newline));
 3443
 3444            rows.push(row + rows_inserted as u32);
 3445        }
 3446
 3447        self.transact(cx, |editor, cx| {
 3448            editor.edit(edits, cx);
 3449
 3450            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3451                let mut index = 0;
 3452                s.move_cursors_with(|map, _, _| {
 3453                    let row = rows[index];
 3454                    index += 1;
 3455
 3456                    let point = Point::new(row, 0);
 3457                    let boundary = map.next_line_boundary(point).1;
 3458                    let clipped = map.clip_point(boundary, Bias::Left);
 3459
 3460                    (clipped, SelectionGoal::None)
 3461                });
 3462            });
 3463
 3464            let mut indent_edits = Vec::new();
 3465            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3466            for row in rows {
 3467                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3468                for (row, indent) in indents {
 3469                    if indent.len == 0 {
 3470                        continue;
 3471                    }
 3472
 3473                    let text = match indent.kind {
 3474                        IndentKind::Space => " ".repeat(indent.len as usize),
 3475                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3476                    };
 3477                    let point = Point::new(row.0, 0);
 3478                    indent_edits.push((point..point, text));
 3479                }
 3480            }
 3481            editor.edit(indent_edits, cx);
 3482        });
 3483    }
 3484
 3485    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3486        let buffer = self.buffer.read(cx);
 3487        let snapshot = buffer.snapshot(cx);
 3488
 3489        let mut edits = Vec::new();
 3490        let mut rows = Vec::new();
 3491        let mut rows_inserted = 0;
 3492
 3493        for selection in self.selections.all_adjusted(cx) {
 3494            let cursor = selection.head();
 3495            let row = cursor.row;
 3496
 3497            let point = Point::new(row + 1, 0);
 3498            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3499
 3500            let newline = "\n".to_string();
 3501            edits.push((start_of_line..start_of_line, newline));
 3502
 3503            rows_inserted += 1;
 3504            rows.push(row + rows_inserted);
 3505        }
 3506
 3507        self.transact(cx, |editor, cx| {
 3508            editor.edit(edits, cx);
 3509
 3510            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3511                let mut index = 0;
 3512                s.move_cursors_with(|map, _, _| {
 3513                    let row = rows[index];
 3514                    index += 1;
 3515
 3516                    let point = Point::new(row, 0);
 3517                    let boundary = map.next_line_boundary(point).1;
 3518                    let clipped = map.clip_point(boundary, Bias::Left);
 3519
 3520                    (clipped, SelectionGoal::None)
 3521                });
 3522            });
 3523
 3524            let mut indent_edits = Vec::new();
 3525            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3526            for row in rows {
 3527                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3528                for (row, indent) in indents {
 3529                    if indent.len == 0 {
 3530                        continue;
 3531                    }
 3532
 3533                    let text = match indent.kind {
 3534                        IndentKind::Space => " ".repeat(indent.len as usize),
 3535                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3536                    };
 3537                    let point = Point::new(row.0, 0);
 3538                    indent_edits.push((point..point, text));
 3539                }
 3540            }
 3541            editor.edit(indent_edits, cx);
 3542        });
 3543    }
 3544
 3545    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3546        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3547            original_indent_columns: Vec::new(),
 3548        });
 3549        self.insert_with_autoindent_mode(text, autoindent, cx);
 3550    }
 3551
 3552    fn insert_with_autoindent_mode(
 3553        &mut self,
 3554        text: &str,
 3555        autoindent_mode: Option<AutoindentMode>,
 3556        cx: &mut ViewContext<Self>,
 3557    ) {
 3558        if self.read_only(cx) {
 3559            return;
 3560        }
 3561
 3562        let text: Arc<str> = text.into();
 3563        self.transact(cx, |this, cx| {
 3564            let old_selections = this.selections.all_adjusted(cx);
 3565            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3566                let anchors = {
 3567                    let snapshot = buffer.read(cx);
 3568                    old_selections
 3569                        .iter()
 3570                        .map(|s| {
 3571                            let anchor = snapshot.anchor_after(s.head());
 3572                            s.map(|_| anchor)
 3573                        })
 3574                        .collect::<Vec<_>>()
 3575                };
 3576                buffer.edit(
 3577                    old_selections
 3578                        .iter()
 3579                        .map(|s| (s.start..s.end, text.clone())),
 3580                    autoindent_mode,
 3581                    cx,
 3582                );
 3583                anchors
 3584            });
 3585
 3586            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3587                s.select_anchors(selection_anchors);
 3588            })
 3589        });
 3590    }
 3591
 3592    fn trigger_completion_on_input(
 3593        &mut self,
 3594        text: &str,
 3595        trigger_in_words: bool,
 3596        cx: &mut ViewContext<Self>,
 3597    ) {
 3598        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3599            self.show_completions(
 3600                &ShowCompletions {
 3601                    trigger: text.chars().last(),
 3602                },
 3603                cx,
 3604            );
 3605        } else {
 3606            self.hide_context_menu(cx);
 3607        }
 3608    }
 3609
 3610    fn is_completion_trigger(
 3611        &self,
 3612        text: &str,
 3613        trigger_in_words: bool,
 3614        cx: &mut ViewContext<Self>,
 3615    ) -> bool {
 3616        let position = self.selections.newest_anchor().head();
 3617        let multibuffer = self.buffer.read(cx);
 3618        let Some(buffer) = position
 3619            .buffer_id
 3620            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3621        else {
 3622            return false;
 3623        };
 3624
 3625        if let Some(completion_provider) = &self.completion_provider {
 3626            completion_provider.is_completion_trigger(
 3627                &buffer,
 3628                position.text_anchor,
 3629                text,
 3630                trigger_in_words,
 3631                cx,
 3632            )
 3633        } else {
 3634            false
 3635        }
 3636    }
 3637
 3638    /// If any empty selections is touching the start of its innermost containing autoclose
 3639    /// region, expand it to select the brackets.
 3640    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3641        let selections = self.selections.all::<usize>(cx);
 3642        let buffer = self.buffer.read(cx).read(cx);
 3643        let new_selections = self
 3644            .selections_with_autoclose_regions(selections, &buffer)
 3645            .map(|(mut selection, region)| {
 3646                if !selection.is_empty() {
 3647                    return selection;
 3648                }
 3649
 3650                if let Some(region) = region {
 3651                    let mut range = region.range.to_offset(&buffer);
 3652                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3653                        range.start -= region.pair.start.len();
 3654                        if buffer.contains_str_at(range.start, &region.pair.start)
 3655                            && buffer.contains_str_at(range.end, &region.pair.end)
 3656                        {
 3657                            range.end += region.pair.end.len();
 3658                            selection.start = range.start;
 3659                            selection.end = range.end;
 3660
 3661                            return selection;
 3662                        }
 3663                    }
 3664                }
 3665
 3666                let always_treat_brackets_as_autoclosed = buffer
 3667                    .settings_at(selection.start, cx)
 3668                    .always_treat_brackets_as_autoclosed;
 3669
 3670                if !always_treat_brackets_as_autoclosed {
 3671                    return selection;
 3672                }
 3673
 3674                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3675                    for (pair, enabled) in scope.brackets() {
 3676                        if !enabled || !pair.close {
 3677                            continue;
 3678                        }
 3679
 3680                        if buffer.contains_str_at(selection.start, &pair.end) {
 3681                            let pair_start_len = pair.start.len();
 3682                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3683                            {
 3684                                selection.start -= pair_start_len;
 3685                                selection.end += pair.end.len();
 3686
 3687                                return selection;
 3688                            }
 3689                        }
 3690                    }
 3691                }
 3692
 3693                selection
 3694            })
 3695            .collect();
 3696
 3697        drop(buffer);
 3698        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3699    }
 3700
 3701    /// Iterate the given selections, and for each one, find the smallest surrounding
 3702    /// autoclose region. This uses the ordering of the selections and the autoclose
 3703    /// regions to avoid repeated comparisons.
 3704    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3705        &'a self,
 3706        selections: impl IntoIterator<Item = Selection<D>>,
 3707        buffer: &'a MultiBufferSnapshot,
 3708    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3709        let mut i = 0;
 3710        let mut regions = self.autoclose_regions.as_slice();
 3711        selections.into_iter().map(move |selection| {
 3712            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3713
 3714            let mut enclosing = None;
 3715            while let Some(pair_state) = regions.get(i) {
 3716                if pair_state.range.end.to_offset(buffer) < range.start {
 3717                    regions = &regions[i + 1..];
 3718                    i = 0;
 3719                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3720                    break;
 3721                } else {
 3722                    if pair_state.selection_id == selection.id {
 3723                        enclosing = Some(pair_state);
 3724                    }
 3725                    i += 1;
 3726                }
 3727            }
 3728
 3729            (selection.clone(), enclosing)
 3730        })
 3731    }
 3732
 3733    /// Remove any autoclose regions that no longer contain their selection.
 3734    fn invalidate_autoclose_regions(
 3735        &mut self,
 3736        mut selections: &[Selection<Anchor>],
 3737        buffer: &MultiBufferSnapshot,
 3738    ) {
 3739        self.autoclose_regions.retain(|state| {
 3740            let mut i = 0;
 3741            while let Some(selection) = selections.get(i) {
 3742                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3743                    selections = &selections[1..];
 3744                    continue;
 3745                }
 3746                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3747                    break;
 3748                }
 3749                if selection.id == state.selection_id {
 3750                    return true;
 3751                } else {
 3752                    i += 1;
 3753                }
 3754            }
 3755            false
 3756        });
 3757    }
 3758
 3759    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3760        let offset = position.to_offset(buffer);
 3761        let (word_range, kind) = buffer.surrounding_word(offset);
 3762        if offset > word_range.start && kind == Some(CharKind::Word) {
 3763            Some(
 3764                buffer
 3765                    .text_for_range(word_range.start..offset)
 3766                    .collect::<String>(),
 3767            )
 3768        } else {
 3769            None
 3770        }
 3771    }
 3772
 3773    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3774        self.refresh_inlay_hints(
 3775            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3776            cx,
 3777        );
 3778    }
 3779
 3780    pub fn inlay_hints_enabled(&self) -> bool {
 3781        self.inlay_hint_cache.enabled
 3782    }
 3783
 3784    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3785        if self.project.is_none() || self.mode != EditorMode::Full {
 3786            return;
 3787        }
 3788
 3789        let reason_description = reason.description();
 3790        let ignore_debounce = matches!(
 3791            reason,
 3792            InlayHintRefreshReason::SettingsChange(_)
 3793                | InlayHintRefreshReason::Toggle(_)
 3794                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3795        );
 3796        let (invalidate_cache, required_languages) = match reason {
 3797            InlayHintRefreshReason::Toggle(enabled) => {
 3798                self.inlay_hint_cache.enabled = enabled;
 3799                if enabled {
 3800                    (InvalidationStrategy::RefreshRequested, None)
 3801                } else {
 3802                    self.inlay_hint_cache.clear();
 3803                    self.splice_inlays(
 3804                        self.visible_inlay_hints(cx)
 3805                            .iter()
 3806                            .map(|inlay| inlay.id)
 3807                            .collect(),
 3808                        Vec::new(),
 3809                        cx,
 3810                    );
 3811                    return;
 3812                }
 3813            }
 3814            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3815                match self.inlay_hint_cache.update_settings(
 3816                    &self.buffer,
 3817                    new_settings,
 3818                    self.visible_inlay_hints(cx),
 3819                    cx,
 3820                ) {
 3821                    ControlFlow::Break(Some(InlaySplice {
 3822                        to_remove,
 3823                        to_insert,
 3824                    })) => {
 3825                        self.splice_inlays(to_remove, to_insert, cx);
 3826                        return;
 3827                    }
 3828                    ControlFlow::Break(None) => return,
 3829                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3830                }
 3831            }
 3832            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3833                if let Some(InlaySplice {
 3834                    to_remove,
 3835                    to_insert,
 3836                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3837                {
 3838                    self.splice_inlays(to_remove, to_insert, cx);
 3839                }
 3840                return;
 3841            }
 3842            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3843            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3844                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3845            }
 3846            InlayHintRefreshReason::RefreshRequested => {
 3847                (InvalidationStrategy::RefreshRequested, None)
 3848            }
 3849        };
 3850
 3851        if let Some(InlaySplice {
 3852            to_remove,
 3853            to_insert,
 3854        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3855            reason_description,
 3856            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3857            invalidate_cache,
 3858            ignore_debounce,
 3859            cx,
 3860        ) {
 3861            self.splice_inlays(to_remove, to_insert, cx);
 3862        }
 3863    }
 3864
 3865    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3866        self.display_map
 3867            .read(cx)
 3868            .current_inlays()
 3869            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3870            .cloned()
 3871            .collect()
 3872    }
 3873
 3874    pub fn excerpts_for_inlay_hints_query(
 3875        &self,
 3876        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3877        cx: &mut ViewContext<Editor>,
 3878    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3879        let Some(project) = self.project.as_ref() else {
 3880            return HashMap::default();
 3881        };
 3882        let project = project.read(cx);
 3883        let multi_buffer = self.buffer().read(cx);
 3884        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3885        let multi_buffer_visible_start = self
 3886            .scroll_manager
 3887            .anchor()
 3888            .anchor
 3889            .to_point(&multi_buffer_snapshot);
 3890        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3891            multi_buffer_visible_start
 3892                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3893            Bias::Left,
 3894        );
 3895        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3896        multi_buffer
 3897            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3898            .into_iter()
 3899            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3900            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3901                let buffer = buffer_handle.read(cx);
 3902                let buffer_file = project::File::from_dyn(buffer.file())?;
 3903                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3904                let worktree_entry = buffer_worktree
 3905                    .read(cx)
 3906                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3907                if worktree_entry.is_ignored {
 3908                    return None;
 3909                }
 3910
 3911                let language = buffer.language()?;
 3912                if let Some(restrict_to_languages) = restrict_to_languages {
 3913                    if !restrict_to_languages.contains(language) {
 3914                        return None;
 3915                    }
 3916                }
 3917                Some((
 3918                    excerpt_id,
 3919                    (
 3920                        buffer_handle,
 3921                        buffer.version().clone(),
 3922                        excerpt_visible_range,
 3923                    ),
 3924                ))
 3925            })
 3926            .collect()
 3927    }
 3928
 3929    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3930        TextLayoutDetails {
 3931            text_system: cx.text_system().clone(),
 3932            editor_style: self.style.clone().unwrap(),
 3933            rem_size: cx.rem_size(),
 3934            scroll_anchor: self.scroll_manager.anchor(),
 3935            visible_rows: self.visible_line_count(),
 3936            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3937        }
 3938    }
 3939
 3940    fn splice_inlays(
 3941        &self,
 3942        to_remove: Vec<InlayId>,
 3943        to_insert: Vec<Inlay>,
 3944        cx: &mut ViewContext<Self>,
 3945    ) {
 3946        self.display_map.update(cx, |display_map, cx| {
 3947            display_map.splice_inlays(to_remove, to_insert, cx);
 3948        });
 3949        cx.notify();
 3950    }
 3951
 3952    fn trigger_on_type_formatting(
 3953        &self,
 3954        input: String,
 3955        cx: &mut ViewContext<Self>,
 3956    ) -> Option<Task<Result<()>>> {
 3957        if input.len() != 1 {
 3958            return None;
 3959        }
 3960
 3961        let project = self.project.as_ref()?;
 3962        let position = self.selections.newest_anchor().head();
 3963        let (buffer, buffer_position) = self
 3964            .buffer
 3965            .read(cx)
 3966            .text_anchor_for_position(position, cx)?;
 3967
 3968        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3969        // hence we do LSP request & edit on host side only — add formats to host's history.
 3970        let push_to_lsp_host_history = true;
 3971        // If this is not the host, append its history with new edits.
 3972        let push_to_client_history = project.read(cx).is_remote();
 3973
 3974        let on_type_formatting = project.update(cx, |project, cx| {
 3975            project.on_type_format(
 3976                buffer.clone(),
 3977                buffer_position,
 3978                input,
 3979                push_to_lsp_host_history,
 3980                cx,
 3981            )
 3982        });
 3983        Some(cx.spawn(|editor, mut cx| async move {
 3984            if let Some(transaction) = on_type_formatting.await? {
 3985                if push_to_client_history {
 3986                    buffer
 3987                        .update(&mut cx, |buffer, _| {
 3988                            buffer.push_transaction(transaction, Instant::now());
 3989                        })
 3990                        .ok();
 3991                }
 3992                editor.update(&mut cx, |editor, cx| {
 3993                    editor.refresh_document_highlights(cx);
 3994                })?;
 3995            }
 3996            Ok(())
 3997        }))
 3998    }
 3999
 4000    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4001        if self.pending_rename.is_some() {
 4002            return;
 4003        }
 4004
 4005        let Some(provider) = self.completion_provider.as_ref() else {
 4006            return;
 4007        };
 4008
 4009        let position = self.selections.newest_anchor().head();
 4010        let (buffer, buffer_position) =
 4011            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4012                output
 4013            } else {
 4014                return;
 4015            };
 4016
 4017        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4018        let is_followup_invoke = {
 4019            let context_menu_state = self.context_menu.read();
 4020            matches!(
 4021                context_menu_state.deref(),
 4022                Some(ContextMenu::Completions(_))
 4023            )
 4024        };
 4025        let trigger_kind = match (options.trigger, is_followup_invoke) {
 4026            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4027            (Some(_), _) => CompletionTriggerKind::TRIGGER_CHARACTER,
 4028            _ => CompletionTriggerKind::INVOKED,
 4029        };
 4030        let completion_context = CompletionContext {
 4031            trigger_character: options.trigger.and_then(|c| {
 4032                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4033                    Some(String::from(c))
 4034                } else {
 4035                    None
 4036                }
 4037            }),
 4038            trigger_kind,
 4039        };
 4040        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4041
 4042        let id = post_inc(&mut self.next_completion_id);
 4043        let task = cx.spawn(|this, mut cx| {
 4044            async move {
 4045                this.update(&mut cx, |this, _| {
 4046                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4047                })?;
 4048                let completions = completions.await.log_err();
 4049                let menu = if let Some(completions) = completions {
 4050                    let mut menu = CompletionsMenu {
 4051                        id,
 4052                        initial_position: position,
 4053                        match_candidates: completions
 4054                            .iter()
 4055                            .enumerate()
 4056                            .map(|(id, completion)| {
 4057                                StringMatchCandidate::new(
 4058                                    id,
 4059                                    completion.label.text[completion.label.filter_range.clone()]
 4060                                        .into(),
 4061                                )
 4062                            })
 4063                            .collect(),
 4064                        buffer: buffer.clone(),
 4065                        completions: Arc::new(RwLock::new(completions.into())),
 4066                        matches: Vec::new().into(),
 4067                        selected_item: 0,
 4068                        scroll_handle: UniformListScrollHandle::new(),
 4069                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4070                            DebouncedDelay::new(),
 4071                        )),
 4072                    };
 4073                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4074                        .await;
 4075
 4076                    if menu.matches.is_empty() {
 4077                        None
 4078                    } else {
 4079                        this.update(&mut cx, |editor, cx| {
 4080                            let completions = menu.completions.clone();
 4081                            let matches = menu.matches.clone();
 4082
 4083                            let delay_ms = EditorSettings::get_global(cx)
 4084                                .completion_documentation_secondary_query_debounce;
 4085                            let delay = Duration::from_millis(delay_ms);
 4086                            editor
 4087                                .completion_documentation_pre_resolve_debounce
 4088                                .fire_new(delay, cx, |editor, cx| {
 4089                                    CompletionsMenu::pre_resolve_completion_documentation(
 4090                                        buffer,
 4091                                        completions,
 4092                                        matches,
 4093                                        editor,
 4094                                        cx,
 4095                                    )
 4096                                });
 4097                        })
 4098                        .ok();
 4099                        Some(menu)
 4100                    }
 4101                } else {
 4102                    None
 4103                };
 4104
 4105                this.update(&mut cx, |this, cx| {
 4106                    let mut context_menu = this.context_menu.write();
 4107                    match context_menu.as_ref() {
 4108                        None => {}
 4109
 4110                        Some(ContextMenu::Completions(prev_menu)) => {
 4111                            if prev_menu.id > id {
 4112                                return;
 4113                            }
 4114                        }
 4115
 4116                        _ => return,
 4117                    }
 4118
 4119                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4120                        let menu = menu.unwrap();
 4121                        *context_menu = Some(ContextMenu::Completions(menu));
 4122                        drop(context_menu);
 4123                        this.discard_inline_completion(false, cx);
 4124                        cx.notify();
 4125                    } else if this.completion_tasks.len() <= 1 {
 4126                        // If there are no more completion tasks and the last menu was
 4127                        // empty, we should hide it. If it was already hidden, we should
 4128                        // also show the copilot completion when available.
 4129                        drop(context_menu);
 4130                        if this.hide_context_menu(cx).is_none() {
 4131                            this.update_visible_inline_completion(cx);
 4132                        }
 4133                    }
 4134                })?;
 4135
 4136                Ok::<_, anyhow::Error>(())
 4137            }
 4138            .log_err()
 4139        });
 4140
 4141        self.completion_tasks.push((id, task));
 4142    }
 4143
 4144    pub fn confirm_completion(
 4145        &mut self,
 4146        action: &ConfirmCompletion,
 4147        cx: &mut ViewContext<Self>,
 4148    ) -> Option<Task<Result<()>>> {
 4149        use language::ToOffset as _;
 4150
 4151        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4152            menu
 4153        } else {
 4154            return None;
 4155        };
 4156
 4157        let mat = completions_menu
 4158            .matches
 4159            .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
 4160        let buffer_handle = completions_menu.buffer;
 4161        let completions = completions_menu.completions.read();
 4162        let completion = completions.get(mat.candidate_id)?;
 4163        cx.stop_propagation();
 4164
 4165        let snippet;
 4166        let text;
 4167
 4168        if completion.is_snippet() {
 4169            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4170            text = snippet.as_ref().unwrap().text.clone();
 4171        } else {
 4172            snippet = None;
 4173            text = completion.new_text.clone();
 4174        };
 4175        let selections = self.selections.all::<usize>(cx);
 4176        let buffer = buffer_handle.read(cx);
 4177        let old_range = completion.old_range.to_offset(buffer);
 4178        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4179
 4180        let newest_selection = self.selections.newest_anchor();
 4181        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4182            return None;
 4183        }
 4184
 4185        let lookbehind = newest_selection
 4186            .start
 4187            .text_anchor
 4188            .to_offset(buffer)
 4189            .saturating_sub(old_range.start);
 4190        let lookahead = old_range
 4191            .end
 4192            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4193        let mut common_prefix_len = old_text
 4194            .bytes()
 4195            .zip(text.bytes())
 4196            .take_while(|(a, b)| a == b)
 4197            .count();
 4198
 4199        let snapshot = self.buffer.read(cx).snapshot(cx);
 4200        let mut range_to_replace: Option<Range<isize>> = None;
 4201        let mut ranges = Vec::new();
 4202        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4203        for selection in &selections {
 4204            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4205                let start = selection.start.saturating_sub(lookbehind);
 4206                let end = selection.end + lookahead;
 4207                if selection.id == newest_selection.id {
 4208                    range_to_replace = Some(
 4209                        ((start + common_prefix_len) as isize - selection.start as isize)
 4210                            ..(end as isize - selection.start as isize),
 4211                    );
 4212                }
 4213                ranges.push(start + common_prefix_len..end);
 4214            } else {
 4215                common_prefix_len = 0;
 4216                ranges.clear();
 4217                ranges.extend(selections.iter().map(|s| {
 4218                    if s.id == newest_selection.id {
 4219                        range_to_replace = Some(
 4220                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4221                                - selection.start as isize
 4222                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4223                                    - selection.start as isize,
 4224                        );
 4225                        old_range.clone()
 4226                    } else {
 4227                        s.start..s.end
 4228                    }
 4229                }));
 4230                break;
 4231            }
 4232            if !self.linked_edit_ranges.is_empty() {
 4233                let start_anchor = snapshot.anchor_before(selection.head());
 4234                let end_anchor = snapshot.anchor_after(selection.tail());
 4235                if let Some(ranges) = self
 4236                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4237                {
 4238                    for (buffer, edits) in ranges {
 4239                        linked_edits.entry(buffer.clone()).or_default().extend(
 4240                            edits
 4241                                .into_iter()
 4242                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4243                        );
 4244                    }
 4245                }
 4246            }
 4247        }
 4248        let text = &text[common_prefix_len..];
 4249
 4250        cx.emit(EditorEvent::InputHandled {
 4251            utf16_range_to_replace: range_to_replace,
 4252            text: text.into(),
 4253        });
 4254
 4255        self.transact(cx, |this, cx| {
 4256            if let Some(mut snippet) = snippet {
 4257                snippet.text = text.to_string();
 4258                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4259                    tabstop.start -= common_prefix_len as isize;
 4260                    tabstop.end -= common_prefix_len as isize;
 4261                }
 4262
 4263                this.insert_snippet(&ranges, snippet, cx).log_err();
 4264            } else {
 4265                this.buffer.update(cx, |buffer, cx| {
 4266                    buffer.edit(
 4267                        ranges.iter().map(|range| (range.clone(), text)),
 4268                        this.autoindent_mode.clone(),
 4269                        cx,
 4270                    );
 4271                });
 4272            }
 4273            for (buffer, edits) in linked_edits {
 4274                buffer.update(cx, |buffer, cx| {
 4275                    let snapshot = buffer.snapshot();
 4276                    let edits = edits
 4277                        .into_iter()
 4278                        .map(|(range, text)| {
 4279                            use text::ToPoint as TP;
 4280                            let end_point = TP::to_point(&range.end, &snapshot);
 4281                            let start_point = TP::to_point(&range.start, &snapshot);
 4282                            (start_point..end_point, text)
 4283                        })
 4284                        .sorted_by_key(|(range, _)| range.start)
 4285                        .collect::<Vec<_>>();
 4286                    buffer.edit(edits, None, cx);
 4287                })
 4288            }
 4289
 4290            this.refresh_inline_completion(true, cx);
 4291        });
 4292
 4293        if let Some(confirm) = completion.confirm.as_ref() {
 4294            (confirm)(cx);
 4295        }
 4296
 4297        if completion.show_new_completions_on_confirm {
 4298            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4299        }
 4300
 4301        let provider = self.completion_provider.as_ref()?;
 4302        let apply_edits = provider.apply_additional_edits_for_completion(
 4303            buffer_handle,
 4304            completion.clone(),
 4305            true,
 4306            cx,
 4307        );
 4308        Some(cx.foreground_executor().spawn(async move {
 4309            apply_edits.await?;
 4310            Ok(())
 4311        }))
 4312    }
 4313
 4314    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4315        let mut context_menu = self.context_menu.write();
 4316        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4317            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4318                // Toggle if we're selecting the same one
 4319                *context_menu = None;
 4320                cx.notify();
 4321                return;
 4322            } else {
 4323                // Otherwise, clear it and start a new one
 4324                *context_menu = None;
 4325                cx.notify();
 4326            }
 4327        }
 4328        drop(context_menu);
 4329        let snapshot = self.snapshot(cx);
 4330        let deployed_from_indicator = action.deployed_from_indicator;
 4331        let mut task = self.code_actions_task.take();
 4332        let action = action.clone();
 4333        cx.spawn(|editor, mut cx| async move {
 4334            while let Some(prev_task) = task {
 4335                prev_task.await;
 4336                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4337            }
 4338
 4339            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4340                if editor.focus_handle.is_focused(cx) {
 4341                    let multibuffer_point = action
 4342                        .deployed_from_indicator
 4343                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4344                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4345                    let (buffer, buffer_row) = snapshot
 4346                        .buffer_snapshot
 4347                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4348                        .and_then(|(buffer_snapshot, range)| {
 4349                            editor
 4350                                .buffer
 4351                                .read(cx)
 4352                                .buffer(buffer_snapshot.remote_id())
 4353                                .map(|buffer| (buffer, range.start.row))
 4354                        })?;
 4355                    let (_, code_actions) = editor
 4356                        .available_code_actions
 4357                        .clone()
 4358                        .and_then(|(location, code_actions)| {
 4359                            let snapshot = location.buffer.read(cx).snapshot();
 4360                            let point_range = location.range.to_point(&snapshot);
 4361                            let point_range = point_range.start.row..=point_range.end.row;
 4362                            if point_range.contains(&buffer_row) {
 4363                                Some((location, code_actions))
 4364                            } else {
 4365                                None
 4366                            }
 4367                        })
 4368                        .unzip();
 4369                    let buffer_id = buffer.read(cx).remote_id();
 4370                    let tasks = editor
 4371                        .tasks
 4372                        .get(&(buffer_id, buffer_row))
 4373                        .map(|t| Arc::new(t.to_owned()));
 4374                    if tasks.is_none() && code_actions.is_none() {
 4375                        return None;
 4376                    }
 4377
 4378                    editor.completion_tasks.clear();
 4379                    editor.discard_inline_completion(false, cx);
 4380                    let task_context =
 4381                        tasks
 4382                            .as_ref()
 4383                            .zip(editor.project.clone())
 4384                            .map(|(tasks, project)| {
 4385                                let position = Point::new(buffer_row, tasks.column);
 4386                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4387                                let location = Location {
 4388                                    buffer: buffer.clone(),
 4389                                    range: range_start..range_start,
 4390                                };
 4391                                // Fill in the environmental variables from the tree-sitter captures
 4392                                let mut captured_task_variables = TaskVariables::default();
 4393                                for (capture_name, value) in tasks.extra_variables.clone() {
 4394                                    captured_task_variables.insert(
 4395                                        task::VariableName::Custom(capture_name.into()),
 4396                                        value.clone(),
 4397                                    );
 4398                                }
 4399                                project.update(cx, |project, cx| {
 4400                                    project.task_context_for_location(
 4401                                        captured_task_variables,
 4402                                        location,
 4403                                        cx,
 4404                                    )
 4405                                })
 4406                            });
 4407
 4408                    Some(cx.spawn(|editor, mut cx| async move {
 4409                        let task_context = match task_context {
 4410                            Some(task_context) => task_context.await,
 4411                            None => None,
 4412                        };
 4413                        let resolved_tasks =
 4414                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4415                                Arc::new(ResolvedTasks {
 4416                                    templates: tasks
 4417                                        .templates
 4418                                        .iter()
 4419                                        .filter_map(|(kind, template)| {
 4420                                            template
 4421                                                .resolve_task(&kind.to_id_base(), &task_context)
 4422                                                .map(|task| (kind.clone(), task))
 4423                                        })
 4424                                        .collect(),
 4425                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4426                                        multibuffer_point.row,
 4427                                        tasks.column,
 4428                                    )),
 4429                                })
 4430                            });
 4431                        let spawn_straight_away = resolved_tasks
 4432                            .as_ref()
 4433                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4434                            && code_actions
 4435                                .as_ref()
 4436                                .map_or(true, |actions| actions.is_empty());
 4437                        if let Some(task) = editor
 4438                            .update(&mut cx, |editor, cx| {
 4439                                *editor.context_menu.write() =
 4440                                    Some(ContextMenu::CodeActions(CodeActionsMenu {
 4441                                        buffer,
 4442                                        actions: CodeActionContents {
 4443                                            tasks: resolved_tasks,
 4444                                            actions: code_actions,
 4445                                        },
 4446                                        selected_item: Default::default(),
 4447                                        scroll_handle: UniformListScrollHandle::default(),
 4448                                        deployed_from_indicator,
 4449                                    }));
 4450                                if spawn_straight_away {
 4451                                    if let Some(task) = editor.confirm_code_action(
 4452                                        &ConfirmCodeAction { item_ix: Some(0) },
 4453                                        cx,
 4454                                    ) {
 4455                                        cx.notify();
 4456                                        return task;
 4457                                    }
 4458                                }
 4459                                cx.notify();
 4460                                Task::ready(Ok(()))
 4461                            })
 4462                            .ok()
 4463                        {
 4464                            task.await
 4465                        } else {
 4466                            Ok(())
 4467                        }
 4468                    }))
 4469                } else {
 4470                    Some(Task::ready(Ok(())))
 4471                }
 4472            })?;
 4473            if let Some(task) = spawned_test_task {
 4474                task.await?;
 4475            }
 4476
 4477            Ok::<_, anyhow::Error>(())
 4478        })
 4479        .detach_and_log_err(cx);
 4480    }
 4481
 4482    pub fn confirm_code_action(
 4483        &mut self,
 4484        action: &ConfirmCodeAction,
 4485        cx: &mut ViewContext<Self>,
 4486    ) -> Option<Task<Result<()>>> {
 4487        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4488            menu
 4489        } else {
 4490            return None;
 4491        };
 4492        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4493        let action = actions_menu.actions.get(action_ix)?;
 4494        let title = action.label();
 4495        let buffer = actions_menu.buffer;
 4496        let workspace = self.workspace()?;
 4497
 4498        match action {
 4499            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4500                workspace.update(cx, |workspace, cx| {
 4501                    workspace::tasks::schedule_resolved_task(
 4502                        workspace,
 4503                        task_source_kind,
 4504                        resolved_task,
 4505                        false,
 4506                        cx,
 4507                    );
 4508
 4509                    Some(Task::ready(Ok(())))
 4510                })
 4511            }
 4512            CodeActionsItem::CodeAction(action) => {
 4513                let apply_code_actions = workspace
 4514                    .read(cx)
 4515                    .project()
 4516                    .clone()
 4517                    .update(cx, |project, cx| {
 4518                        project.apply_code_action(buffer, action, true, cx)
 4519                    });
 4520                let workspace = workspace.downgrade();
 4521                Some(cx.spawn(|editor, cx| async move {
 4522                    let project_transaction = apply_code_actions.await?;
 4523                    Self::open_project_transaction(
 4524                        &editor,
 4525                        workspace,
 4526                        project_transaction,
 4527                        title,
 4528                        cx,
 4529                    )
 4530                    .await
 4531                }))
 4532            }
 4533        }
 4534    }
 4535
 4536    pub async fn open_project_transaction(
 4537        this: &WeakView<Editor>,
 4538        workspace: WeakView<Workspace>,
 4539        transaction: ProjectTransaction,
 4540        title: String,
 4541        mut cx: AsyncWindowContext,
 4542    ) -> Result<()> {
 4543        let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
 4544
 4545        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4546        cx.update(|cx| {
 4547            entries.sort_unstable_by_key(|(buffer, _)| {
 4548                buffer.read(cx).file().map(|f| f.path().clone())
 4549            });
 4550        })?;
 4551
 4552        // If the project transaction's edits are all contained within this editor, then
 4553        // avoid opening a new editor to display them.
 4554
 4555        if let Some((buffer, transaction)) = entries.first() {
 4556            if entries.len() == 1 {
 4557                let excerpt = this.update(&mut cx, |editor, cx| {
 4558                    editor
 4559                        .buffer()
 4560                        .read(cx)
 4561                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4562                })?;
 4563                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4564                    if excerpted_buffer == *buffer {
 4565                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4566                            let excerpt_range = excerpt_range.to_offset(buffer);
 4567                            buffer
 4568                                .edited_ranges_for_transaction::<usize>(transaction)
 4569                                .all(|range| {
 4570                                    excerpt_range.start <= range.start
 4571                                        && excerpt_range.end >= range.end
 4572                                })
 4573                        })?;
 4574
 4575                        if all_edits_within_excerpt {
 4576                            return Ok(());
 4577                        }
 4578                    }
 4579                }
 4580            }
 4581        } else {
 4582            return Ok(());
 4583        }
 4584
 4585        let mut ranges_to_highlight = Vec::new();
 4586        let excerpt_buffer = cx.new_model(|cx| {
 4587            let mut multibuffer =
 4588                MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
 4589            for (buffer_handle, transaction) in &entries {
 4590                let buffer = buffer_handle.read(cx);
 4591                ranges_to_highlight.extend(
 4592                    multibuffer.push_excerpts_with_context_lines(
 4593                        buffer_handle.clone(),
 4594                        buffer
 4595                            .edited_ranges_for_transaction::<usize>(transaction)
 4596                            .collect(),
 4597                        DEFAULT_MULTIBUFFER_CONTEXT,
 4598                        cx,
 4599                    ),
 4600                );
 4601            }
 4602            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4603            multibuffer
 4604        })?;
 4605
 4606        workspace.update(&mut cx, |workspace, cx| {
 4607            let project = workspace.project().clone();
 4608            let editor =
 4609                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4610            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, cx);
 4611            editor.update(cx, |editor, cx| {
 4612                editor.highlight_background::<Self>(
 4613                    &ranges_to_highlight,
 4614                    |theme| theme.editor_highlighted_line_background,
 4615                    cx,
 4616                );
 4617            });
 4618        })?;
 4619
 4620        Ok(())
 4621    }
 4622
 4623    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4624        let project = self.project.clone()?;
 4625        let buffer = self.buffer.read(cx);
 4626        let newest_selection = self.selections.newest_anchor().clone();
 4627        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4628        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4629        if start_buffer != end_buffer {
 4630            return None;
 4631        }
 4632
 4633        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4634            cx.background_executor()
 4635                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4636                .await;
 4637
 4638            let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
 4639                project.code_actions(&start_buffer, start..end, cx)
 4640            }) {
 4641                code_actions.await
 4642            } else {
 4643                Vec::new()
 4644            };
 4645
 4646            this.update(&mut cx, |this, cx| {
 4647                this.available_code_actions = if actions.is_empty() {
 4648                    None
 4649                } else {
 4650                    Some((
 4651                        Location {
 4652                            buffer: start_buffer,
 4653                            range: start..end,
 4654                        },
 4655                        actions.into(),
 4656                    ))
 4657                };
 4658                cx.notify();
 4659            })
 4660            .log_err();
 4661        }));
 4662        None
 4663    }
 4664
 4665    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4666        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4667            self.show_git_blame_inline = false;
 4668
 4669            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4670                cx.background_executor().timer(delay).await;
 4671
 4672                this.update(&mut cx, |this, cx| {
 4673                    this.show_git_blame_inline = true;
 4674                    cx.notify();
 4675                })
 4676                .log_err();
 4677            }));
 4678        }
 4679    }
 4680
 4681    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4682        if self.pending_rename.is_some() {
 4683            return None;
 4684        }
 4685
 4686        let project = self.project.clone()?;
 4687        let buffer = self.buffer.read(cx);
 4688        let newest_selection = self.selections.newest_anchor().clone();
 4689        let cursor_position = newest_selection.head();
 4690        let (cursor_buffer, cursor_buffer_position) =
 4691            buffer.text_anchor_for_position(cursor_position, cx)?;
 4692        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4693        if cursor_buffer != tail_buffer {
 4694            return None;
 4695        }
 4696
 4697        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4698            cx.background_executor()
 4699                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 4700                .await;
 4701
 4702            let highlights = if let Some(highlights) = project
 4703                .update(&mut cx, |project, cx| {
 4704                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4705                })
 4706                .log_err()
 4707            {
 4708                highlights.await.log_err()
 4709            } else {
 4710                None
 4711            };
 4712
 4713            if let Some(highlights) = highlights {
 4714                this.update(&mut cx, |this, cx| {
 4715                    if this.pending_rename.is_some() {
 4716                        return;
 4717                    }
 4718
 4719                    let buffer_id = cursor_position.buffer_id;
 4720                    let buffer = this.buffer.read(cx);
 4721                    if !buffer
 4722                        .text_anchor_for_position(cursor_position, cx)
 4723                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4724                    {
 4725                        return;
 4726                    }
 4727
 4728                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4729                    let mut write_ranges = Vec::new();
 4730                    let mut read_ranges = Vec::new();
 4731                    for highlight in highlights {
 4732                        for (excerpt_id, excerpt_range) in
 4733                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4734                        {
 4735                            let start = highlight
 4736                                .range
 4737                                .start
 4738                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4739                            let end = highlight
 4740                                .range
 4741                                .end
 4742                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4743                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4744                                continue;
 4745                            }
 4746
 4747                            let range = Anchor {
 4748                                buffer_id,
 4749                                excerpt_id: excerpt_id,
 4750                                text_anchor: start,
 4751                            }..Anchor {
 4752                                buffer_id,
 4753                                excerpt_id,
 4754                                text_anchor: end,
 4755                            };
 4756                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4757                                write_ranges.push(range);
 4758                            } else {
 4759                                read_ranges.push(range);
 4760                            }
 4761                        }
 4762                    }
 4763
 4764                    this.highlight_background::<DocumentHighlightRead>(
 4765                        &read_ranges,
 4766                        |theme| theme.editor_document_highlight_read_background,
 4767                        cx,
 4768                    );
 4769                    this.highlight_background::<DocumentHighlightWrite>(
 4770                        &write_ranges,
 4771                        |theme| theme.editor_document_highlight_write_background,
 4772                        cx,
 4773                    );
 4774                    cx.notify();
 4775                })
 4776                .log_err();
 4777            }
 4778        }));
 4779        None
 4780    }
 4781
 4782    fn refresh_inline_completion(
 4783        &mut self,
 4784        debounce: bool,
 4785        cx: &mut ViewContext<Self>,
 4786    ) -> Option<()> {
 4787        let provider = self.inline_completion_provider()?;
 4788        let cursor = self.selections.newest_anchor().head();
 4789        let (buffer, cursor_buffer_position) =
 4790            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4791        if !self.show_inline_completions
 4792            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4793        {
 4794            self.discard_inline_completion(false, cx);
 4795            return None;
 4796        }
 4797
 4798        self.update_visible_inline_completion(cx);
 4799        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4800        Some(())
 4801    }
 4802
 4803    fn cycle_inline_completion(
 4804        &mut self,
 4805        direction: Direction,
 4806        cx: &mut ViewContext<Self>,
 4807    ) -> Option<()> {
 4808        let provider = self.inline_completion_provider()?;
 4809        let cursor = self.selections.newest_anchor().head();
 4810        let (buffer, cursor_buffer_position) =
 4811            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4812        if !self.show_inline_completions
 4813            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4814        {
 4815            return None;
 4816        }
 4817
 4818        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4819        self.update_visible_inline_completion(cx);
 4820
 4821        Some(())
 4822    }
 4823
 4824    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4825        if !self.has_active_inline_completion(cx) {
 4826            self.refresh_inline_completion(false, cx);
 4827            return;
 4828        }
 4829
 4830        self.update_visible_inline_completion(cx);
 4831    }
 4832
 4833    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4834        self.show_cursor_names(cx);
 4835    }
 4836
 4837    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4838        self.show_cursor_names = true;
 4839        cx.notify();
 4840        cx.spawn(|this, mut cx| async move {
 4841            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4842            this.update(&mut cx, |this, cx| {
 4843                this.show_cursor_names = false;
 4844                cx.notify()
 4845            })
 4846            .ok()
 4847        })
 4848        .detach();
 4849    }
 4850
 4851    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4852        if self.has_active_inline_completion(cx) {
 4853            self.cycle_inline_completion(Direction::Next, cx);
 4854        } else {
 4855            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4856            if is_copilot_disabled {
 4857                cx.propagate();
 4858            }
 4859        }
 4860    }
 4861
 4862    pub fn previous_inline_completion(
 4863        &mut self,
 4864        _: &PreviousInlineCompletion,
 4865        cx: &mut ViewContext<Self>,
 4866    ) {
 4867        if self.has_active_inline_completion(cx) {
 4868            self.cycle_inline_completion(Direction::Prev, cx);
 4869        } else {
 4870            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4871            if is_copilot_disabled {
 4872                cx.propagate();
 4873            }
 4874        }
 4875    }
 4876
 4877    pub fn accept_inline_completion(
 4878        &mut self,
 4879        _: &AcceptInlineCompletion,
 4880        cx: &mut ViewContext<Self>,
 4881    ) {
 4882        let Some(completion) = self.take_active_inline_completion(cx) else {
 4883            return;
 4884        };
 4885        if let Some(provider) = self.inline_completion_provider() {
 4886            provider.accept(cx);
 4887        }
 4888
 4889        cx.emit(EditorEvent::InputHandled {
 4890            utf16_range_to_replace: None,
 4891            text: completion.text.to_string().into(),
 4892        });
 4893        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 4894        self.refresh_inline_completion(true, cx);
 4895        cx.notify();
 4896    }
 4897
 4898    pub fn accept_partial_inline_completion(
 4899        &mut self,
 4900        _: &AcceptPartialInlineCompletion,
 4901        cx: &mut ViewContext<Self>,
 4902    ) {
 4903        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 4904            if let Some(completion) = self.take_active_inline_completion(cx) {
 4905                let mut partial_completion = completion
 4906                    .text
 4907                    .chars()
 4908                    .by_ref()
 4909                    .take_while(|c| c.is_alphabetic())
 4910                    .collect::<String>();
 4911                if partial_completion.is_empty() {
 4912                    partial_completion = completion
 4913                        .text
 4914                        .chars()
 4915                        .by_ref()
 4916                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4917                        .collect::<String>();
 4918                }
 4919
 4920                cx.emit(EditorEvent::InputHandled {
 4921                    utf16_range_to_replace: None,
 4922                    text: partial_completion.clone().into(),
 4923                });
 4924                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4925                self.refresh_inline_completion(true, cx);
 4926                cx.notify();
 4927            }
 4928        }
 4929    }
 4930
 4931    fn discard_inline_completion(
 4932        &mut self,
 4933        should_report_inline_completion_event: bool,
 4934        cx: &mut ViewContext<Self>,
 4935    ) -> bool {
 4936        if let Some(provider) = self.inline_completion_provider() {
 4937            provider.discard(should_report_inline_completion_event, cx);
 4938        }
 4939
 4940        self.take_active_inline_completion(cx).is_some()
 4941    }
 4942
 4943    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 4944        if let Some(completion) = self.active_inline_completion.as_ref() {
 4945            let buffer = self.buffer.read(cx).read(cx);
 4946            completion.position.is_valid(&buffer)
 4947        } else {
 4948            false
 4949        }
 4950    }
 4951
 4952    fn take_active_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
 4953        let completion = self.active_inline_completion.take()?;
 4954        self.display_map.update(cx, |map, cx| {
 4955            map.splice_inlays(vec![completion.id], Default::default(), cx);
 4956        });
 4957        let buffer = self.buffer.read(cx).read(cx);
 4958
 4959        if completion.position.is_valid(&buffer) {
 4960            Some(completion)
 4961        } else {
 4962            None
 4963        }
 4964    }
 4965
 4966    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 4967        let selection = self.selections.newest_anchor();
 4968        let cursor = selection.head();
 4969
 4970        if self.context_menu.read().is_none()
 4971            && self.completion_tasks.is_empty()
 4972            && selection.start == selection.end
 4973        {
 4974            if let Some(provider) = self.inline_completion_provider() {
 4975                if let Some((buffer, cursor_buffer_position)) =
 4976                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4977                {
 4978                    if let Some(text) =
 4979                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 4980                    {
 4981                        let text = Rope::from(text);
 4982                        let mut to_remove = Vec::new();
 4983                        if let Some(completion) = self.active_inline_completion.take() {
 4984                            to_remove.push(completion.id);
 4985                        }
 4986
 4987                        let completion_inlay =
 4988                            Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
 4989                        self.active_inline_completion = Some(completion_inlay.clone());
 4990                        self.display_map.update(cx, move |map, cx| {
 4991                            map.splice_inlays(to_remove, vec![completion_inlay], cx)
 4992                        });
 4993                        cx.notify();
 4994                        return;
 4995                    }
 4996                }
 4997            }
 4998        }
 4999
 5000        self.discard_inline_completion(false, cx);
 5001    }
 5002
 5003    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5004        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5005    }
 5006
 5007    fn render_code_actions_indicator(
 5008        &self,
 5009        _style: &EditorStyle,
 5010        row: DisplayRow,
 5011        is_active: bool,
 5012        cx: &mut ViewContext<Self>,
 5013    ) -> Option<IconButton> {
 5014        if self.available_code_actions.is_some() {
 5015            Some(
 5016                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5017                    .shape(ui::IconButtonShape::Square)
 5018                    .icon_size(IconSize::XSmall)
 5019                    .icon_color(Color::Muted)
 5020                    .selected(is_active)
 5021                    .on_click(cx.listener(move |editor, _e, cx| {
 5022                        editor.focus(cx);
 5023                        editor.toggle_code_actions(
 5024                            &ToggleCodeActions {
 5025                                deployed_from_indicator: Some(row),
 5026                            },
 5027                            cx,
 5028                        );
 5029                    })),
 5030            )
 5031        } else {
 5032            None
 5033        }
 5034    }
 5035
 5036    fn clear_tasks(&mut self) {
 5037        self.tasks.clear()
 5038    }
 5039
 5040    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5041        if let Some(_) = self.tasks.insert(key, value) {
 5042            // This case should hopefully be rare, but just in case...
 5043            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5044        }
 5045    }
 5046
 5047    fn render_run_indicator(
 5048        &self,
 5049        _style: &EditorStyle,
 5050        is_active: bool,
 5051        row: DisplayRow,
 5052        cx: &mut ViewContext<Self>,
 5053    ) -> IconButton {
 5054        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5055            .shape(ui::IconButtonShape::Square)
 5056            .icon_size(IconSize::XSmall)
 5057            .icon_color(Color::Muted)
 5058            .selected(is_active)
 5059            .on_click(cx.listener(move |editor, _e, cx| {
 5060                editor.focus(cx);
 5061                editor.toggle_code_actions(
 5062                    &ToggleCodeActions {
 5063                        deployed_from_indicator: Some(row),
 5064                    },
 5065                    cx,
 5066                );
 5067            }))
 5068    }
 5069
 5070    pub fn context_menu_visible(&self) -> bool {
 5071        self.context_menu
 5072            .read()
 5073            .as_ref()
 5074            .map_or(false, |menu| menu.visible())
 5075    }
 5076
 5077    fn render_context_menu(
 5078        &self,
 5079        cursor_position: DisplayPoint,
 5080        style: &EditorStyle,
 5081        max_height: Pixels,
 5082        cx: &mut ViewContext<Editor>,
 5083    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5084        self.context_menu.read().as_ref().map(|menu| {
 5085            menu.render(
 5086                cursor_position,
 5087                style,
 5088                max_height,
 5089                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5090                cx,
 5091            )
 5092        })
 5093    }
 5094
 5095    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5096        cx.notify();
 5097        self.completion_tasks.clear();
 5098        let context_menu = self.context_menu.write().take();
 5099        if context_menu.is_some() {
 5100            self.update_visible_inline_completion(cx);
 5101        }
 5102        context_menu
 5103    }
 5104
 5105    pub fn insert_snippet(
 5106        &mut self,
 5107        insertion_ranges: &[Range<usize>],
 5108        snippet: Snippet,
 5109        cx: &mut ViewContext<Self>,
 5110    ) -> Result<()> {
 5111        struct Tabstop<T> {
 5112            is_end_tabstop: bool,
 5113            ranges: Vec<Range<T>>,
 5114        }
 5115
 5116        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5117            let snippet_text: Arc<str> = snippet.text.clone().into();
 5118            buffer.edit(
 5119                insertion_ranges
 5120                    .iter()
 5121                    .cloned()
 5122                    .map(|range| (range, snippet_text.clone())),
 5123                Some(AutoindentMode::EachLine),
 5124                cx,
 5125            );
 5126
 5127            let snapshot = &*buffer.read(cx);
 5128            let snippet = &snippet;
 5129            snippet
 5130                .tabstops
 5131                .iter()
 5132                .map(|tabstop| {
 5133                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5134                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5135                    });
 5136                    let mut tabstop_ranges = tabstop
 5137                        .iter()
 5138                        .flat_map(|tabstop_range| {
 5139                            let mut delta = 0_isize;
 5140                            insertion_ranges.iter().map(move |insertion_range| {
 5141                                let insertion_start = insertion_range.start as isize + delta;
 5142                                delta +=
 5143                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5144
 5145                                let start = ((insertion_start + tabstop_range.start) as usize)
 5146                                    .min(snapshot.len());
 5147                                let end = ((insertion_start + tabstop_range.end) as usize)
 5148                                    .min(snapshot.len());
 5149                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5150                            })
 5151                        })
 5152                        .collect::<Vec<_>>();
 5153                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5154
 5155                    Tabstop {
 5156                        is_end_tabstop,
 5157                        ranges: tabstop_ranges,
 5158                    }
 5159                })
 5160                .collect::<Vec<_>>()
 5161        });
 5162        if let Some(tabstop) = tabstops.first() {
 5163            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5164                s.select_ranges(tabstop.ranges.iter().cloned());
 5165            });
 5166
 5167            // If we're already at the last tabstop and it's at the end of the snippet,
 5168            // we're done, we don't need to keep the state around.
 5169            if !tabstop.is_end_tabstop {
 5170                let ranges = tabstops
 5171                    .into_iter()
 5172                    .map(|tabstop| tabstop.ranges)
 5173                    .collect::<Vec<_>>();
 5174                self.snippet_stack.push(SnippetState {
 5175                    active_index: 0,
 5176                    ranges,
 5177                });
 5178            }
 5179
 5180            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5181            if self.autoclose_regions.is_empty() {
 5182                let snapshot = self.buffer.read(cx).snapshot(cx);
 5183                for selection in &mut self.selections.all::<Point>(cx) {
 5184                    let selection_head = selection.head();
 5185                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5186                        continue;
 5187                    };
 5188
 5189                    let mut bracket_pair = None;
 5190                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5191                    let prev_chars = snapshot
 5192                        .reversed_chars_at(selection_head)
 5193                        .collect::<String>();
 5194                    for (pair, enabled) in scope.brackets() {
 5195                        if enabled
 5196                            && pair.close
 5197                            && prev_chars.starts_with(pair.start.as_str())
 5198                            && next_chars.starts_with(pair.end.as_str())
 5199                        {
 5200                            bracket_pair = Some(pair.clone());
 5201                            break;
 5202                        }
 5203                    }
 5204                    if let Some(pair) = bracket_pair {
 5205                        let start = snapshot.anchor_after(selection_head);
 5206                        let end = snapshot.anchor_after(selection_head);
 5207                        self.autoclose_regions.push(AutocloseRegion {
 5208                            selection_id: selection.id,
 5209                            range: start..end,
 5210                            pair,
 5211                        });
 5212                    }
 5213                }
 5214            }
 5215        }
 5216        Ok(())
 5217    }
 5218
 5219    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5220        self.move_to_snippet_tabstop(Bias::Right, cx)
 5221    }
 5222
 5223    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5224        self.move_to_snippet_tabstop(Bias::Left, cx)
 5225    }
 5226
 5227    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5228        if let Some(mut snippet) = self.snippet_stack.pop() {
 5229            match bias {
 5230                Bias::Left => {
 5231                    if snippet.active_index > 0 {
 5232                        snippet.active_index -= 1;
 5233                    } else {
 5234                        self.snippet_stack.push(snippet);
 5235                        return false;
 5236                    }
 5237                }
 5238                Bias::Right => {
 5239                    if snippet.active_index + 1 < snippet.ranges.len() {
 5240                        snippet.active_index += 1;
 5241                    } else {
 5242                        self.snippet_stack.push(snippet);
 5243                        return false;
 5244                    }
 5245                }
 5246            }
 5247            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5248                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5249                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5250                });
 5251                // If snippet state is not at the last tabstop, push it back on the stack
 5252                if snippet.active_index + 1 < snippet.ranges.len() {
 5253                    self.snippet_stack.push(snippet);
 5254                }
 5255                return true;
 5256            }
 5257        }
 5258
 5259        false
 5260    }
 5261
 5262    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5263        self.transact(cx, |this, cx| {
 5264            this.select_all(&SelectAll, cx);
 5265            this.insert("", cx);
 5266        });
 5267    }
 5268
 5269    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5270        self.transact(cx, |this, cx| {
 5271            this.select_autoclose_pair(cx);
 5272            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5273            if !this.linked_edit_ranges.is_empty() {
 5274                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5275                let snapshot = this.buffer.read(cx).snapshot(cx);
 5276
 5277                for selection in selections.iter() {
 5278                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5279                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5280                    if selection_start.buffer_id != selection_end.buffer_id {
 5281                        continue;
 5282                    }
 5283                    if let Some(ranges) =
 5284                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5285                    {
 5286                        for (buffer, entries) in ranges {
 5287                            linked_ranges.entry(buffer).or_default().extend(entries);
 5288                        }
 5289                    }
 5290                }
 5291            }
 5292
 5293            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5294            if !this.selections.line_mode {
 5295                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5296                for selection in &mut selections {
 5297                    if selection.is_empty() {
 5298                        let old_head = selection.head();
 5299                        let mut new_head =
 5300                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5301                                .to_point(&display_map);
 5302                        if let Some((buffer, line_buffer_range)) = display_map
 5303                            .buffer_snapshot
 5304                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5305                        {
 5306                            let indent_size =
 5307                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5308                            let indent_len = match indent_size.kind {
 5309                                IndentKind::Space => {
 5310                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5311                                }
 5312                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5313                            };
 5314                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5315                                let indent_len = indent_len.get();
 5316                                new_head = cmp::min(
 5317                                    new_head,
 5318                                    MultiBufferPoint::new(
 5319                                        old_head.row,
 5320                                        ((old_head.column - 1) / indent_len) * indent_len,
 5321                                    ),
 5322                                );
 5323                            }
 5324                        }
 5325
 5326                        selection.set_head(new_head, SelectionGoal::None);
 5327                    }
 5328                }
 5329            }
 5330
 5331            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5332            this.insert("", cx);
 5333            let empty_str: Arc<str> = Arc::from("");
 5334            for (buffer, edits) in linked_ranges {
 5335                let snapshot = buffer.read(cx).snapshot();
 5336                use text::ToPoint as TP;
 5337
 5338                let edits = edits
 5339                    .into_iter()
 5340                    .map(|range| {
 5341                        let end_point = TP::to_point(&range.end, &snapshot);
 5342                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5343
 5344                        if end_point == start_point {
 5345                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5346                                .saturating_sub(1);
 5347                            start_point = TP::to_point(&offset, &snapshot);
 5348                        };
 5349
 5350                        (start_point..end_point, empty_str.clone())
 5351                    })
 5352                    .sorted_by_key(|(range, _)| range.start)
 5353                    .collect::<Vec<_>>();
 5354                buffer.update(cx, |this, cx| {
 5355                    this.edit(edits, None, cx);
 5356                })
 5357            }
 5358            this.refresh_inline_completion(true, cx);
 5359            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5360        });
 5361    }
 5362
 5363    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5364        self.transact(cx, |this, cx| {
 5365            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5366                let line_mode = s.line_mode;
 5367                s.move_with(|map, selection| {
 5368                    if selection.is_empty() && !line_mode {
 5369                        let cursor = movement::right(map, selection.head());
 5370                        selection.end = cursor;
 5371                        selection.reversed = true;
 5372                        selection.goal = SelectionGoal::None;
 5373                    }
 5374                })
 5375            });
 5376            this.insert("", cx);
 5377            this.refresh_inline_completion(true, cx);
 5378        });
 5379    }
 5380
 5381    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5382        if self.move_to_prev_snippet_tabstop(cx) {
 5383            return;
 5384        }
 5385
 5386        self.outdent(&Outdent, cx);
 5387    }
 5388
 5389    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5390        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5391            return;
 5392        }
 5393
 5394        let mut selections = self.selections.all_adjusted(cx);
 5395        let buffer = self.buffer.read(cx);
 5396        let snapshot = buffer.snapshot(cx);
 5397        let rows_iter = selections.iter().map(|s| s.head().row);
 5398        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5399
 5400        let mut edits = Vec::new();
 5401        let mut prev_edited_row = 0;
 5402        let mut row_delta = 0;
 5403        for selection in &mut selections {
 5404            if selection.start.row != prev_edited_row {
 5405                row_delta = 0;
 5406            }
 5407            prev_edited_row = selection.end.row;
 5408
 5409            // If the selection is non-empty, then increase the indentation of the selected lines.
 5410            if !selection.is_empty() {
 5411                row_delta =
 5412                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5413                continue;
 5414            }
 5415
 5416            // If the selection is empty and the cursor is in the leading whitespace before the
 5417            // suggested indentation, then auto-indent the line.
 5418            let cursor = selection.head();
 5419            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5420            if let Some(suggested_indent) =
 5421                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5422            {
 5423                if cursor.column < suggested_indent.len
 5424                    && cursor.column <= current_indent.len
 5425                    && current_indent.len <= suggested_indent.len
 5426                {
 5427                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5428                    selection.end = selection.start;
 5429                    if row_delta == 0 {
 5430                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5431                            cursor.row,
 5432                            current_indent,
 5433                            suggested_indent,
 5434                        ));
 5435                        row_delta = suggested_indent.len - current_indent.len;
 5436                    }
 5437                    continue;
 5438                }
 5439            }
 5440
 5441            // Otherwise, insert a hard or soft tab.
 5442            let settings = buffer.settings_at(cursor, cx);
 5443            let tab_size = if settings.hard_tabs {
 5444                IndentSize::tab()
 5445            } else {
 5446                let tab_size = settings.tab_size.get();
 5447                let char_column = snapshot
 5448                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5449                    .flat_map(str::chars)
 5450                    .count()
 5451                    + row_delta as usize;
 5452                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5453                IndentSize::spaces(chars_to_next_tab_stop)
 5454            };
 5455            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5456            selection.end = selection.start;
 5457            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5458            row_delta += tab_size.len;
 5459        }
 5460
 5461        self.transact(cx, |this, cx| {
 5462            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5463            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5464            this.refresh_inline_completion(true, cx);
 5465        });
 5466    }
 5467
 5468    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5469        if self.read_only(cx) {
 5470            return;
 5471        }
 5472        let mut selections = self.selections.all::<Point>(cx);
 5473        let mut prev_edited_row = 0;
 5474        let mut row_delta = 0;
 5475        let mut edits = Vec::new();
 5476        let buffer = self.buffer.read(cx);
 5477        let snapshot = buffer.snapshot(cx);
 5478        for selection in &mut selections {
 5479            if selection.start.row != prev_edited_row {
 5480                row_delta = 0;
 5481            }
 5482            prev_edited_row = selection.end.row;
 5483
 5484            row_delta =
 5485                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5486        }
 5487
 5488        self.transact(cx, |this, cx| {
 5489            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5490            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5491        });
 5492    }
 5493
 5494    fn indent_selection(
 5495        buffer: &MultiBuffer,
 5496        snapshot: &MultiBufferSnapshot,
 5497        selection: &mut Selection<Point>,
 5498        edits: &mut Vec<(Range<Point>, String)>,
 5499        delta_for_start_row: u32,
 5500        cx: &AppContext,
 5501    ) -> u32 {
 5502        let settings = buffer.settings_at(selection.start, cx);
 5503        let tab_size = settings.tab_size.get();
 5504        let indent_kind = if settings.hard_tabs {
 5505            IndentKind::Tab
 5506        } else {
 5507            IndentKind::Space
 5508        };
 5509        let mut start_row = selection.start.row;
 5510        let mut end_row = selection.end.row + 1;
 5511
 5512        // If a selection ends at the beginning of a line, don't indent
 5513        // that last line.
 5514        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5515            end_row -= 1;
 5516        }
 5517
 5518        // Avoid re-indenting a row that has already been indented by a
 5519        // previous selection, but still update this selection's column
 5520        // to reflect that indentation.
 5521        if delta_for_start_row > 0 {
 5522            start_row += 1;
 5523            selection.start.column += delta_for_start_row;
 5524            if selection.end.row == selection.start.row {
 5525                selection.end.column += delta_for_start_row;
 5526            }
 5527        }
 5528
 5529        let mut delta_for_end_row = 0;
 5530        let has_multiple_rows = start_row + 1 != end_row;
 5531        for row in start_row..end_row {
 5532            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5533            let indent_delta = match (current_indent.kind, indent_kind) {
 5534                (IndentKind::Space, IndentKind::Space) => {
 5535                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5536                    IndentSize::spaces(columns_to_next_tab_stop)
 5537                }
 5538                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5539                (_, IndentKind::Tab) => IndentSize::tab(),
 5540            };
 5541
 5542            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5543                0
 5544            } else {
 5545                selection.start.column
 5546            };
 5547            let row_start = Point::new(row, start);
 5548            edits.push((
 5549                row_start..row_start,
 5550                indent_delta.chars().collect::<String>(),
 5551            ));
 5552
 5553            // Update this selection's endpoints to reflect the indentation.
 5554            if row == selection.start.row {
 5555                selection.start.column += indent_delta.len;
 5556            }
 5557            if row == selection.end.row {
 5558                selection.end.column += indent_delta.len;
 5559                delta_for_end_row = indent_delta.len;
 5560            }
 5561        }
 5562
 5563        if selection.start.row == selection.end.row {
 5564            delta_for_start_row + delta_for_end_row
 5565        } else {
 5566            delta_for_end_row
 5567        }
 5568    }
 5569
 5570    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5571        if self.read_only(cx) {
 5572            return;
 5573        }
 5574        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5575        let selections = self.selections.all::<Point>(cx);
 5576        let mut deletion_ranges = Vec::new();
 5577        let mut last_outdent = None;
 5578        {
 5579            let buffer = self.buffer.read(cx);
 5580            let snapshot = buffer.snapshot(cx);
 5581            for selection in &selections {
 5582                let settings = buffer.settings_at(selection.start, cx);
 5583                let tab_size = settings.tab_size.get();
 5584                let mut rows = selection.spanned_rows(false, &display_map);
 5585
 5586                // Avoid re-outdenting a row that has already been outdented by a
 5587                // previous selection.
 5588                if let Some(last_row) = last_outdent {
 5589                    if last_row == rows.start {
 5590                        rows.start = rows.start.next_row();
 5591                    }
 5592                }
 5593                let has_multiple_rows = rows.len() > 1;
 5594                for row in rows.iter_rows() {
 5595                    let indent_size = snapshot.indent_size_for_line(row);
 5596                    if indent_size.len > 0 {
 5597                        let deletion_len = match indent_size.kind {
 5598                            IndentKind::Space => {
 5599                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5600                                if columns_to_prev_tab_stop == 0 {
 5601                                    tab_size
 5602                                } else {
 5603                                    columns_to_prev_tab_stop
 5604                                }
 5605                            }
 5606                            IndentKind::Tab => 1,
 5607                        };
 5608                        let start = if has_multiple_rows
 5609                            || deletion_len > selection.start.column
 5610                            || indent_size.len < selection.start.column
 5611                        {
 5612                            0
 5613                        } else {
 5614                            selection.start.column - deletion_len
 5615                        };
 5616                        deletion_ranges.push(
 5617                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5618                        );
 5619                        last_outdent = Some(row);
 5620                    }
 5621                }
 5622            }
 5623        }
 5624
 5625        self.transact(cx, |this, cx| {
 5626            this.buffer.update(cx, |buffer, cx| {
 5627                let empty_str: Arc<str> = "".into();
 5628                buffer.edit(
 5629                    deletion_ranges
 5630                        .into_iter()
 5631                        .map(|range| (range, empty_str.clone())),
 5632                    None,
 5633                    cx,
 5634                );
 5635            });
 5636            let selections = this.selections.all::<usize>(cx);
 5637            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5638        });
 5639    }
 5640
 5641    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5642        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5643        let selections = self.selections.all::<Point>(cx);
 5644
 5645        let mut new_cursors = Vec::new();
 5646        let mut edit_ranges = Vec::new();
 5647        let mut selections = selections.iter().peekable();
 5648        while let Some(selection) = selections.next() {
 5649            let mut rows = selection.spanned_rows(false, &display_map);
 5650            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5651
 5652            // Accumulate contiguous regions of rows that we want to delete.
 5653            while let Some(next_selection) = selections.peek() {
 5654                let next_rows = next_selection.spanned_rows(false, &display_map);
 5655                if next_rows.start <= rows.end {
 5656                    rows.end = next_rows.end;
 5657                    selections.next().unwrap();
 5658                } else {
 5659                    break;
 5660                }
 5661            }
 5662
 5663            let buffer = &display_map.buffer_snapshot;
 5664            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5665            let edit_end;
 5666            let cursor_buffer_row;
 5667            if buffer.max_point().row >= rows.end.0 {
 5668                // If there's a line after the range, delete the \n from the end of the row range
 5669                // and position the cursor on the next line.
 5670                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5671                cursor_buffer_row = rows.end;
 5672            } else {
 5673                // If there isn't a line after the range, delete the \n from the line before the
 5674                // start of the row range and position the cursor there.
 5675                edit_start = edit_start.saturating_sub(1);
 5676                edit_end = buffer.len();
 5677                cursor_buffer_row = rows.start.previous_row();
 5678            }
 5679
 5680            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5681            *cursor.column_mut() =
 5682                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5683
 5684            new_cursors.push((
 5685                selection.id,
 5686                buffer.anchor_after(cursor.to_point(&display_map)),
 5687            ));
 5688            edit_ranges.push(edit_start..edit_end);
 5689        }
 5690
 5691        self.transact(cx, |this, cx| {
 5692            let buffer = this.buffer.update(cx, |buffer, cx| {
 5693                let empty_str: Arc<str> = "".into();
 5694                buffer.edit(
 5695                    edit_ranges
 5696                        .into_iter()
 5697                        .map(|range| (range, empty_str.clone())),
 5698                    None,
 5699                    cx,
 5700                );
 5701                buffer.snapshot(cx)
 5702            });
 5703            let new_selections = new_cursors
 5704                .into_iter()
 5705                .map(|(id, cursor)| {
 5706                    let cursor = cursor.to_point(&buffer);
 5707                    Selection {
 5708                        id,
 5709                        start: cursor,
 5710                        end: cursor,
 5711                        reversed: false,
 5712                        goal: SelectionGoal::None,
 5713                    }
 5714                })
 5715                .collect();
 5716
 5717            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5718                s.select(new_selections);
 5719            });
 5720        });
 5721    }
 5722
 5723    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5724        if self.read_only(cx) {
 5725            return;
 5726        }
 5727        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5728        for selection in self.selections.all::<Point>(cx) {
 5729            let start = MultiBufferRow(selection.start.row);
 5730            let end = if selection.start.row == selection.end.row {
 5731                MultiBufferRow(selection.start.row + 1)
 5732            } else {
 5733                MultiBufferRow(selection.end.row)
 5734            };
 5735
 5736            if let Some(last_row_range) = row_ranges.last_mut() {
 5737                if start <= last_row_range.end {
 5738                    last_row_range.end = end;
 5739                    continue;
 5740                }
 5741            }
 5742            row_ranges.push(start..end);
 5743        }
 5744
 5745        let snapshot = self.buffer.read(cx).snapshot(cx);
 5746        let mut cursor_positions = Vec::new();
 5747        for row_range in &row_ranges {
 5748            let anchor = snapshot.anchor_before(Point::new(
 5749                row_range.end.previous_row().0,
 5750                snapshot.line_len(row_range.end.previous_row()),
 5751            ));
 5752            cursor_positions.push(anchor..anchor);
 5753        }
 5754
 5755        self.transact(cx, |this, cx| {
 5756            for row_range in row_ranges.into_iter().rev() {
 5757                for row in row_range.iter_rows().rev() {
 5758                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5759                    let next_line_row = row.next_row();
 5760                    let indent = snapshot.indent_size_for_line(next_line_row);
 5761                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5762
 5763                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5764                        " "
 5765                    } else {
 5766                        ""
 5767                    };
 5768
 5769                    this.buffer.update(cx, |buffer, cx| {
 5770                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5771                    });
 5772                }
 5773            }
 5774
 5775            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5776                s.select_anchor_ranges(cursor_positions)
 5777            });
 5778        });
 5779    }
 5780
 5781    pub fn sort_lines_case_sensitive(
 5782        &mut self,
 5783        _: &SortLinesCaseSensitive,
 5784        cx: &mut ViewContext<Self>,
 5785    ) {
 5786        self.manipulate_lines(cx, |lines| lines.sort())
 5787    }
 5788
 5789    pub fn sort_lines_case_insensitive(
 5790        &mut self,
 5791        _: &SortLinesCaseInsensitive,
 5792        cx: &mut ViewContext<Self>,
 5793    ) {
 5794        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5795    }
 5796
 5797    pub fn unique_lines_case_insensitive(
 5798        &mut self,
 5799        _: &UniqueLinesCaseInsensitive,
 5800        cx: &mut ViewContext<Self>,
 5801    ) {
 5802        self.manipulate_lines(cx, |lines| {
 5803            let mut seen = HashSet::default();
 5804            lines.retain(|line| seen.insert(line.to_lowercase()));
 5805        })
 5806    }
 5807
 5808    pub fn unique_lines_case_sensitive(
 5809        &mut self,
 5810        _: &UniqueLinesCaseSensitive,
 5811        cx: &mut ViewContext<Self>,
 5812    ) {
 5813        self.manipulate_lines(cx, |lines| {
 5814            let mut seen = HashSet::default();
 5815            lines.retain(|line| seen.insert(*line));
 5816        })
 5817    }
 5818
 5819    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5820        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 5821        if !revert_changes.is_empty() {
 5822            self.transact(cx, |editor, cx| {
 5823                editor.buffer().update(cx, |multi_buffer, cx| {
 5824                    for (buffer_id, changes) in revert_changes {
 5825                        if let Some(buffer) = multi_buffer.buffer(buffer_id) {
 5826                            buffer.update(cx, |buffer, cx| {
 5827                                buffer.edit(
 5828                                    changes.into_iter().map(|(range, text)| {
 5829                                        (range, text.to_string().map(Arc::<str>::from))
 5830                                    }),
 5831                                    None,
 5832                                    cx,
 5833                                );
 5834                            });
 5835                        }
 5836                    }
 5837                });
 5838                editor.change_selections(None, cx, |selections| selections.refresh());
 5839            });
 5840        }
 5841    }
 5842
 5843    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5844        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5845            let project_path = buffer.read(cx).project_path(cx)?;
 5846            let project = self.project.as_ref()?.read(cx);
 5847            let entry = project.entry_for_path(&project_path, cx)?;
 5848            let abs_path = project.absolute_path(&project_path, cx)?;
 5849            let parent = if entry.is_symlink {
 5850                abs_path.canonicalize().ok()?
 5851            } else {
 5852                abs_path
 5853            }
 5854            .parent()?
 5855            .to_path_buf();
 5856            Some(parent)
 5857        }) {
 5858            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5859        }
 5860    }
 5861
 5862    fn gather_revert_changes(
 5863        &mut self,
 5864        selections: &[Selection<Anchor>],
 5865        cx: &mut ViewContext<'_, Editor>,
 5866    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 5867        let mut revert_changes = HashMap::default();
 5868        self.buffer.update(cx, |multi_buffer, cx| {
 5869            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 5870            for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 5871                Self::prepare_revert_change(&mut revert_changes, &multi_buffer, &hunk, cx);
 5872            }
 5873        });
 5874        revert_changes
 5875    }
 5876
 5877    fn prepare_revert_change(
 5878        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 5879        multi_buffer: &MultiBuffer,
 5880        hunk: &DiffHunk<MultiBufferRow>,
 5881        cx: &mut AppContext,
 5882    ) -> Option<()> {
 5883        let buffer = multi_buffer.buffer(hunk.buffer_id)?;
 5884        let buffer = buffer.read(cx);
 5885        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 5886        let buffer_snapshot = buffer.snapshot();
 5887        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5888        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5889            probe
 5890                .0
 5891                .start
 5892                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5893                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5894        }) {
 5895            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 5896            Some(())
 5897        } else {
 5898            None
 5899        }
 5900    }
 5901
 5902    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5903        self.manipulate_lines(cx, |lines| lines.reverse())
 5904    }
 5905
 5906    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5907        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5908    }
 5909
 5910    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5911    where
 5912        Fn: FnMut(&mut Vec<&str>),
 5913    {
 5914        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5915        let buffer = self.buffer.read(cx).snapshot(cx);
 5916
 5917        let mut edits = Vec::new();
 5918
 5919        let selections = self.selections.all::<Point>(cx);
 5920        let mut selections = selections.iter().peekable();
 5921        let mut contiguous_row_selections = Vec::new();
 5922        let mut new_selections = Vec::new();
 5923        let mut added_lines = 0;
 5924        let mut removed_lines = 0;
 5925
 5926        while let Some(selection) = selections.next() {
 5927            let (start_row, end_row) = consume_contiguous_rows(
 5928                &mut contiguous_row_selections,
 5929                selection,
 5930                &display_map,
 5931                &mut selections,
 5932            );
 5933
 5934            let start_point = Point::new(start_row.0, 0);
 5935            let end_point = Point::new(
 5936                end_row.previous_row().0,
 5937                buffer.line_len(end_row.previous_row()),
 5938            );
 5939            let text = buffer
 5940                .text_for_range(start_point..end_point)
 5941                .collect::<String>();
 5942
 5943            let mut lines = text.split('\n').collect_vec();
 5944
 5945            let lines_before = lines.len();
 5946            callback(&mut lines);
 5947            let lines_after = lines.len();
 5948
 5949            edits.push((start_point..end_point, lines.join("\n")));
 5950
 5951            // Selections must change based on added and removed line count
 5952            let start_row =
 5953                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 5954            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 5955            new_selections.push(Selection {
 5956                id: selection.id,
 5957                start: start_row,
 5958                end: end_row,
 5959                goal: SelectionGoal::None,
 5960                reversed: selection.reversed,
 5961            });
 5962
 5963            if lines_after > lines_before {
 5964                added_lines += lines_after - lines_before;
 5965            } else if lines_before > lines_after {
 5966                removed_lines += lines_before - lines_after;
 5967            }
 5968        }
 5969
 5970        self.transact(cx, |this, cx| {
 5971            let buffer = this.buffer.update(cx, |buffer, cx| {
 5972                buffer.edit(edits, None, cx);
 5973                buffer.snapshot(cx)
 5974            });
 5975
 5976            // Recalculate offsets on newly edited buffer
 5977            let new_selections = new_selections
 5978                .iter()
 5979                .map(|s| {
 5980                    let start_point = Point::new(s.start.0, 0);
 5981                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 5982                    Selection {
 5983                        id: s.id,
 5984                        start: buffer.point_to_offset(start_point),
 5985                        end: buffer.point_to_offset(end_point),
 5986                        goal: s.goal,
 5987                        reversed: s.reversed,
 5988                    }
 5989                })
 5990                .collect();
 5991
 5992            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5993                s.select(new_selections);
 5994            });
 5995
 5996            this.request_autoscroll(Autoscroll::fit(), cx);
 5997        });
 5998    }
 5999
 6000    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6001        self.manipulate_text(cx, |text| text.to_uppercase())
 6002    }
 6003
 6004    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6005        self.manipulate_text(cx, |text| text.to_lowercase())
 6006    }
 6007
 6008    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6009        self.manipulate_text(cx, |text| {
 6010            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6011            // https://github.com/rutrum/convert-case/issues/16
 6012            text.split('\n')
 6013                .map(|line| line.to_case(Case::Title))
 6014                .join("\n")
 6015        })
 6016    }
 6017
 6018    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6019        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6020    }
 6021
 6022    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6023        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6024    }
 6025
 6026    pub fn convert_to_upper_camel_case(
 6027        &mut self,
 6028        _: &ConvertToUpperCamelCase,
 6029        cx: &mut ViewContext<Self>,
 6030    ) {
 6031        self.manipulate_text(cx, |text| {
 6032            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6033            // https://github.com/rutrum/convert-case/issues/16
 6034            text.split('\n')
 6035                .map(|line| line.to_case(Case::UpperCamel))
 6036                .join("\n")
 6037        })
 6038    }
 6039
 6040    pub fn convert_to_lower_camel_case(
 6041        &mut self,
 6042        _: &ConvertToLowerCamelCase,
 6043        cx: &mut ViewContext<Self>,
 6044    ) {
 6045        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6046    }
 6047
 6048    pub fn convert_to_opposite_case(
 6049        &mut self,
 6050        _: &ConvertToOppositeCase,
 6051        cx: &mut ViewContext<Self>,
 6052    ) {
 6053        self.manipulate_text(cx, |text| {
 6054            text.chars()
 6055                .fold(String::with_capacity(text.len()), |mut t, c| {
 6056                    if c.is_uppercase() {
 6057                        t.extend(c.to_lowercase());
 6058                    } else {
 6059                        t.extend(c.to_uppercase());
 6060                    }
 6061                    t
 6062                })
 6063        })
 6064    }
 6065
 6066    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6067    where
 6068        Fn: FnMut(&str) -> String,
 6069    {
 6070        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6071        let buffer = self.buffer.read(cx).snapshot(cx);
 6072
 6073        let mut new_selections = Vec::new();
 6074        let mut edits = Vec::new();
 6075        let mut selection_adjustment = 0i32;
 6076
 6077        for selection in self.selections.all::<usize>(cx) {
 6078            let selection_is_empty = selection.is_empty();
 6079
 6080            let (start, end) = if selection_is_empty {
 6081                let word_range = movement::surrounding_word(
 6082                    &display_map,
 6083                    selection.start.to_display_point(&display_map),
 6084                );
 6085                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6086                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6087                (start, end)
 6088            } else {
 6089                (selection.start, selection.end)
 6090            };
 6091
 6092            let text = buffer.text_for_range(start..end).collect::<String>();
 6093            let old_length = text.len() as i32;
 6094            let text = callback(&text);
 6095
 6096            new_selections.push(Selection {
 6097                start: (start as i32 - selection_adjustment) as usize,
 6098                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6099                goal: SelectionGoal::None,
 6100                ..selection
 6101            });
 6102
 6103            selection_adjustment += old_length - text.len() as i32;
 6104
 6105            edits.push((start..end, text));
 6106        }
 6107
 6108        self.transact(cx, |this, cx| {
 6109            this.buffer.update(cx, |buffer, cx| {
 6110                buffer.edit(edits, None, cx);
 6111            });
 6112
 6113            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6114                s.select(new_selections);
 6115            });
 6116
 6117            this.request_autoscroll(Autoscroll::fit(), cx);
 6118        });
 6119    }
 6120
 6121    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6122        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6123        let buffer = &display_map.buffer_snapshot;
 6124        let selections = self.selections.all::<Point>(cx);
 6125
 6126        let mut edits = Vec::new();
 6127        let mut selections_iter = selections.iter().peekable();
 6128        while let Some(selection) = selections_iter.next() {
 6129            // Avoid duplicating the same lines twice.
 6130            let mut rows = selection.spanned_rows(false, &display_map);
 6131
 6132            while let Some(next_selection) = selections_iter.peek() {
 6133                let next_rows = next_selection.spanned_rows(false, &display_map);
 6134                if next_rows.start < rows.end {
 6135                    rows.end = next_rows.end;
 6136                    selections_iter.next().unwrap();
 6137                } else {
 6138                    break;
 6139                }
 6140            }
 6141
 6142            // Copy the text from the selected row region and splice it either at the start
 6143            // or end of the region.
 6144            let start = Point::new(rows.start.0, 0);
 6145            let end = Point::new(
 6146                rows.end.previous_row().0,
 6147                buffer.line_len(rows.end.previous_row()),
 6148            );
 6149            let text = buffer
 6150                .text_for_range(start..end)
 6151                .chain(Some("\n"))
 6152                .collect::<String>();
 6153            let insert_location = if upwards {
 6154                Point::new(rows.end.0, 0)
 6155            } else {
 6156                start
 6157            };
 6158            edits.push((insert_location..insert_location, text));
 6159        }
 6160
 6161        self.transact(cx, |this, cx| {
 6162            this.buffer.update(cx, |buffer, cx| {
 6163                buffer.edit(edits, None, cx);
 6164            });
 6165
 6166            this.request_autoscroll(Autoscroll::fit(), cx);
 6167        });
 6168    }
 6169
 6170    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6171        self.duplicate_line(true, cx);
 6172    }
 6173
 6174    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6175        self.duplicate_line(false, cx);
 6176    }
 6177
 6178    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6179        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6180        let buffer = self.buffer.read(cx).snapshot(cx);
 6181
 6182        let mut edits = Vec::new();
 6183        let mut unfold_ranges = Vec::new();
 6184        let mut refold_ranges = Vec::new();
 6185
 6186        let selections = self.selections.all::<Point>(cx);
 6187        let mut selections = selections.iter().peekable();
 6188        let mut contiguous_row_selections = Vec::new();
 6189        let mut new_selections = Vec::new();
 6190
 6191        while let Some(selection) = selections.next() {
 6192            // Find all the selections that span a contiguous row range
 6193            let (start_row, end_row) = consume_contiguous_rows(
 6194                &mut contiguous_row_selections,
 6195                selection,
 6196                &display_map,
 6197                &mut selections,
 6198            );
 6199
 6200            // Move the text spanned by the row range to be before the line preceding the row range
 6201            if start_row.0 > 0 {
 6202                let range_to_move = Point::new(
 6203                    start_row.previous_row().0,
 6204                    buffer.line_len(start_row.previous_row()),
 6205                )
 6206                    ..Point::new(
 6207                        end_row.previous_row().0,
 6208                        buffer.line_len(end_row.previous_row()),
 6209                    );
 6210                let insertion_point = display_map
 6211                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6212                    .0;
 6213
 6214                // Don't move lines across excerpts
 6215                if buffer
 6216                    .excerpt_boundaries_in_range((
 6217                        Bound::Excluded(insertion_point),
 6218                        Bound::Included(range_to_move.end),
 6219                    ))
 6220                    .next()
 6221                    .is_none()
 6222                {
 6223                    let text = buffer
 6224                        .text_for_range(range_to_move.clone())
 6225                        .flat_map(|s| s.chars())
 6226                        .skip(1)
 6227                        .chain(['\n'])
 6228                        .collect::<String>();
 6229
 6230                    edits.push((
 6231                        buffer.anchor_after(range_to_move.start)
 6232                            ..buffer.anchor_before(range_to_move.end),
 6233                        String::new(),
 6234                    ));
 6235                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6236                    edits.push((insertion_anchor..insertion_anchor, text));
 6237
 6238                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6239
 6240                    // Move selections up
 6241                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6242                        |mut selection| {
 6243                            selection.start.row -= row_delta;
 6244                            selection.end.row -= row_delta;
 6245                            selection
 6246                        },
 6247                    ));
 6248
 6249                    // Move folds up
 6250                    unfold_ranges.push(range_to_move.clone());
 6251                    for fold in display_map.folds_in_range(
 6252                        buffer.anchor_before(range_to_move.start)
 6253                            ..buffer.anchor_after(range_to_move.end),
 6254                    ) {
 6255                        let mut start = fold.range.start.to_point(&buffer);
 6256                        let mut end = fold.range.end.to_point(&buffer);
 6257                        start.row -= row_delta;
 6258                        end.row -= row_delta;
 6259                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6260                    }
 6261                }
 6262            }
 6263
 6264            // If we didn't move line(s), preserve the existing selections
 6265            new_selections.append(&mut contiguous_row_selections);
 6266        }
 6267
 6268        self.transact(cx, |this, cx| {
 6269            this.unfold_ranges(unfold_ranges, true, true, cx);
 6270            this.buffer.update(cx, |buffer, cx| {
 6271                for (range, text) in edits {
 6272                    buffer.edit([(range, text)], None, cx);
 6273                }
 6274            });
 6275            this.fold_ranges(refold_ranges, true, cx);
 6276            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6277                s.select(new_selections);
 6278            })
 6279        });
 6280    }
 6281
 6282    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6283        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6284        let buffer = self.buffer.read(cx).snapshot(cx);
 6285
 6286        let mut edits = Vec::new();
 6287        let mut unfold_ranges = Vec::new();
 6288        let mut refold_ranges = Vec::new();
 6289
 6290        let selections = self.selections.all::<Point>(cx);
 6291        let mut selections = selections.iter().peekable();
 6292        let mut contiguous_row_selections = Vec::new();
 6293        let mut new_selections = Vec::new();
 6294
 6295        while let Some(selection) = selections.next() {
 6296            // Find all the selections that span a contiguous row range
 6297            let (start_row, end_row) = consume_contiguous_rows(
 6298                &mut contiguous_row_selections,
 6299                selection,
 6300                &display_map,
 6301                &mut selections,
 6302            );
 6303
 6304            // Move the text spanned by the row range to be after the last line of the row range
 6305            if end_row.0 <= buffer.max_point().row {
 6306                let range_to_move =
 6307                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6308                let insertion_point = display_map
 6309                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6310                    .0;
 6311
 6312                // Don't move lines across excerpt boundaries
 6313                if buffer
 6314                    .excerpt_boundaries_in_range((
 6315                        Bound::Excluded(range_to_move.start),
 6316                        Bound::Included(insertion_point),
 6317                    ))
 6318                    .next()
 6319                    .is_none()
 6320                {
 6321                    let mut text = String::from("\n");
 6322                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6323                    text.pop(); // Drop trailing newline
 6324                    edits.push((
 6325                        buffer.anchor_after(range_to_move.start)
 6326                            ..buffer.anchor_before(range_to_move.end),
 6327                        String::new(),
 6328                    ));
 6329                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6330                    edits.push((insertion_anchor..insertion_anchor, text));
 6331
 6332                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6333
 6334                    // Move selections down
 6335                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6336                        |mut selection| {
 6337                            selection.start.row += row_delta;
 6338                            selection.end.row += row_delta;
 6339                            selection
 6340                        },
 6341                    ));
 6342
 6343                    // Move folds down
 6344                    unfold_ranges.push(range_to_move.clone());
 6345                    for fold in display_map.folds_in_range(
 6346                        buffer.anchor_before(range_to_move.start)
 6347                            ..buffer.anchor_after(range_to_move.end),
 6348                    ) {
 6349                        let mut start = fold.range.start.to_point(&buffer);
 6350                        let mut end = fold.range.end.to_point(&buffer);
 6351                        start.row += row_delta;
 6352                        end.row += row_delta;
 6353                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6354                    }
 6355                }
 6356            }
 6357
 6358            // If we didn't move line(s), preserve the existing selections
 6359            new_selections.append(&mut contiguous_row_selections);
 6360        }
 6361
 6362        self.transact(cx, |this, cx| {
 6363            this.unfold_ranges(unfold_ranges, true, true, cx);
 6364            this.buffer.update(cx, |buffer, cx| {
 6365                for (range, text) in edits {
 6366                    buffer.edit([(range, text)], None, cx);
 6367                }
 6368            });
 6369            this.fold_ranges(refold_ranges, true, cx);
 6370            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6371        });
 6372    }
 6373
 6374    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6375        let text_layout_details = &self.text_layout_details(cx);
 6376        self.transact(cx, |this, cx| {
 6377            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6378                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6379                let line_mode = s.line_mode;
 6380                s.move_with(|display_map, selection| {
 6381                    if !selection.is_empty() || line_mode {
 6382                        return;
 6383                    }
 6384
 6385                    let mut head = selection.head();
 6386                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6387                    if head.column() == display_map.line_len(head.row()) {
 6388                        transpose_offset = display_map
 6389                            .buffer_snapshot
 6390                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6391                    }
 6392
 6393                    if transpose_offset == 0 {
 6394                        return;
 6395                    }
 6396
 6397                    *head.column_mut() += 1;
 6398                    head = display_map.clip_point(head, Bias::Right);
 6399                    let goal = SelectionGoal::HorizontalPosition(
 6400                        display_map
 6401                            .x_for_display_point(head, &text_layout_details)
 6402                            .into(),
 6403                    );
 6404                    selection.collapse_to(head, goal);
 6405
 6406                    let transpose_start = display_map
 6407                        .buffer_snapshot
 6408                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6409                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6410                        let transpose_end = display_map
 6411                            .buffer_snapshot
 6412                            .clip_offset(transpose_offset + 1, Bias::Right);
 6413                        if let Some(ch) =
 6414                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6415                        {
 6416                            edits.push((transpose_start..transpose_offset, String::new()));
 6417                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6418                        }
 6419                    }
 6420                });
 6421                edits
 6422            });
 6423            this.buffer
 6424                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6425            let selections = this.selections.all::<usize>(cx);
 6426            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6427                s.select(selections);
 6428            });
 6429        });
 6430    }
 6431
 6432    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6433        let mut text = String::new();
 6434        let buffer = self.buffer.read(cx).snapshot(cx);
 6435        let mut selections = self.selections.all::<Point>(cx);
 6436        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6437        {
 6438            let max_point = buffer.max_point();
 6439            let mut is_first = true;
 6440            for selection in &mut selections {
 6441                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6442                if is_entire_line {
 6443                    selection.start = Point::new(selection.start.row, 0);
 6444                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6445                    selection.goal = SelectionGoal::None;
 6446                }
 6447                if is_first {
 6448                    is_first = false;
 6449                } else {
 6450                    text += "\n";
 6451                }
 6452                let mut len = 0;
 6453                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6454                    text.push_str(chunk);
 6455                    len += chunk.len();
 6456                }
 6457                clipboard_selections.push(ClipboardSelection {
 6458                    len,
 6459                    is_entire_line,
 6460                    first_line_indent: buffer
 6461                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6462                        .len,
 6463                });
 6464            }
 6465        }
 6466
 6467        self.transact(cx, |this, cx| {
 6468            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6469                s.select(selections);
 6470            });
 6471            this.insert("", cx);
 6472            cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6473        });
 6474    }
 6475
 6476    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6477        let selections = self.selections.all::<Point>(cx);
 6478        let buffer = self.buffer.read(cx).read(cx);
 6479        let mut text = String::new();
 6480
 6481        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6482        {
 6483            let max_point = buffer.max_point();
 6484            let mut is_first = true;
 6485            for selection in selections.iter() {
 6486                let mut start = selection.start;
 6487                let mut end = selection.end;
 6488                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6489                if is_entire_line {
 6490                    start = Point::new(start.row, 0);
 6491                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6492                }
 6493                if is_first {
 6494                    is_first = false;
 6495                } else {
 6496                    text += "\n";
 6497                }
 6498                let mut len = 0;
 6499                for chunk in buffer.text_for_range(start..end) {
 6500                    text.push_str(chunk);
 6501                    len += chunk.len();
 6502                }
 6503                clipboard_selections.push(ClipboardSelection {
 6504                    len,
 6505                    is_entire_line,
 6506                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6507                });
 6508            }
 6509        }
 6510
 6511        cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6512    }
 6513
 6514    pub fn do_paste(
 6515        &mut self,
 6516        text: &String,
 6517        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6518        handle_entire_lines: bool,
 6519        cx: &mut ViewContext<Self>,
 6520    ) {
 6521        if self.read_only(cx) {
 6522            return;
 6523        }
 6524
 6525        let clipboard_text = Cow::Borrowed(text);
 6526
 6527        self.transact(cx, |this, cx| {
 6528            if let Some(mut clipboard_selections) = clipboard_selections {
 6529                let old_selections = this.selections.all::<usize>(cx);
 6530                let all_selections_were_entire_line =
 6531                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6532                let first_selection_indent_column =
 6533                    clipboard_selections.first().map(|s| s.first_line_indent);
 6534                if clipboard_selections.len() != old_selections.len() {
 6535                    clipboard_selections.drain(..);
 6536                }
 6537
 6538                this.buffer.update(cx, |buffer, cx| {
 6539                    let snapshot = buffer.read(cx);
 6540                    let mut start_offset = 0;
 6541                    let mut edits = Vec::new();
 6542                    let mut original_indent_columns = Vec::new();
 6543                    for (ix, selection) in old_selections.iter().enumerate() {
 6544                        let to_insert;
 6545                        let entire_line;
 6546                        let original_indent_column;
 6547                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6548                            let end_offset = start_offset + clipboard_selection.len;
 6549                            to_insert = &clipboard_text[start_offset..end_offset];
 6550                            entire_line = clipboard_selection.is_entire_line;
 6551                            start_offset = end_offset + 1;
 6552                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6553                        } else {
 6554                            to_insert = clipboard_text.as_str();
 6555                            entire_line = all_selections_were_entire_line;
 6556                            original_indent_column = first_selection_indent_column
 6557                        }
 6558
 6559                        // If the corresponding selection was empty when this slice of the
 6560                        // clipboard text was written, then the entire line containing the
 6561                        // selection was copied. If this selection is also currently empty,
 6562                        // then paste the line before the current line of the buffer.
 6563                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6564                            let column = selection.start.to_point(&snapshot).column as usize;
 6565                            let line_start = selection.start - column;
 6566                            line_start..line_start
 6567                        } else {
 6568                            selection.range()
 6569                        };
 6570
 6571                        edits.push((range, to_insert));
 6572                        original_indent_columns.extend(original_indent_column);
 6573                    }
 6574                    drop(snapshot);
 6575
 6576                    buffer.edit(
 6577                        edits,
 6578                        Some(AutoindentMode::Block {
 6579                            original_indent_columns,
 6580                        }),
 6581                        cx,
 6582                    );
 6583                });
 6584
 6585                let selections = this.selections.all::<usize>(cx);
 6586                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6587            } else {
 6588                this.insert(&clipboard_text, cx);
 6589            }
 6590        });
 6591    }
 6592
 6593    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6594        if let Some(item) = cx.read_from_clipboard() {
 6595            self.do_paste(
 6596                item.text(),
 6597                item.metadata::<Vec<ClipboardSelection>>(),
 6598                true,
 6599                cx,
 6600            )
 6601        };
 6602    }
 6603
 6604    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6605        if self.read_only(cx) {
 6606            return;
 6607        }
 6608
 6609        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6610            if let Some((selections, _)) =
 6611                self.selection_history.transaction(transaction_id).cloned()
 6612            {
 6613                self.change_selections(None, cx, |s| {
 6614                    s.select_anchors(selections.to_vec());
 6615                });
 6616            }
 6617            self.request_autoscroll(Autoscroll::fit(), cx);
 6618            self.unmark_text(cx);
 6619            self.refresh_inline_completion(true, cx);
 6620            cx.emit(EditorEvent::Edited { transaction_id });
 6621            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 6622        }
 6623    }
 6624
 6625    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 6626        if self.read_only(cx) {
 6627            return;
 6628        }
 6629
 6630        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 6631            if let Some((_, Some(selections))) =
 6632                self.selection_history.transaction(transaction_id).cloned()
 6633            {
 6634                self.change_selections(None, cx, |s| {
 6635                    s.select_anchors(selections.to_vec());
 6636                });
 6637            }
 6638            self.request_autoscroll(Autoscroll::fit(), cx);
 6639            self.unmark_text(cx);
 6640            self.refresh_inline_completion(true, cx);
 6641            cx.emit(EditorEvent::Edited { transaction_id });
 6642        }
 6643    }
 6644
 6645    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 6646        self.buffer
 6647            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 6648    }
 6649
 6650    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 6651        self.buffer
 6652            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 6653    }
 6654
 6655    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 6656        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6657            let line_mode = s.line_mode;
 6658            s.move_with(|map, selection| {
 6659                let cursor = if selection.is_empty() && !line_mode {
 6660                    movement::left(map, selection.start)
 6661                } else {
 6662                    selection.start
 6663                };
 6664                selection.collapse_to(cursor, SelectionGoal::None);
 6665            });
 6666        })
 6667    }
 6668
 6669    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 6670        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6671            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 6672        })
 6673    }
 6674
 6675    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 6676        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6677            let line_mode = s.line_mode;
 6678            s.move_with(|map, selection| {
 6679                let cursor = if selection.is_empty() && !line_mode {
 6680                    movement::right(map, selection.end)
 6681                } else {
 6682                    selection.end
 6683                };
 6684                selection.collapse_to(cursor, SelectionGoal::None)
 6685            });
 6686        })
 6687    }
 6688
 6689    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 6690        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6691            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 6692        })
 6693    }
 6694
 6695    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 6696        if self.take_rename(true, cx).is_some() {
 6697            return;
 6698        }
 6699
 6700        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6701            cx.propagate();
 6702            return;
 6703        }
 6704
 6705        let text_layout_details = &self.text_layout_details(cx);
 6706        let selection_count = self.selections.count();
 6707        let first_selection = self.selections.first_anchor();
 6708
 6709        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6710            let line_mode = s.line_mode;
 6711            s.move_with(|map, selection| {
 6712                if !selection.is_empty() && !line_mode {
 6713                    selection.goal = SelectionGoal::None;
 6714                }
 6715                let (cursor, goal) = movement::up(
 6716                    map,
 6717                    selection.start,
 6718                    selection.goal,
 6719                    false,
 6720                    &text_layout_details,
 6721                );
 6722                selection.collapse_to(cursor, goal);
 6723            });
 6724        });
 6725
 6726        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6727        {
 6728            cx.propagate();
 6729        }
 6730    }
 6731
 6732    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 6733        if self.take_rename(true, cx).is_some() {
 6734            return;
 6735        }
 6736
 6737        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6738            cx.propagate();
 6739            return;
 6740        }
 6741
 6742        let text_layout_details = &self.text_layout_details(cx);
 6743
 6744        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6745            let line_mode = s.line_mode;
 6746            s.move_with(|map, selection| {
 6747                if !selection.is_empty() && !line_mode {
 6748                    selection.goal = SelectionGoal::None;
 6749                }
 6750                let (cursor, goal) = movement::up_by_rows(
 6751                    map,
 6752                    selection.start,
 6753                    action.lines,
 6754                    selection.goal,
 6755                    false,
 6756                    &text_layout_details,
 6757                );
 6758                selection.collapse_to(cursor, goal);
 6759            });
 6760        })
 6761    }
 6762
 6763    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 6764        if self.take_rename(true, cx).is_some() {
 6765            return;
 6766        }
 6767
 6768        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6769            cx.propagate();
 6770            return;
 6771        }
 6772
 6773        let text_layout_details = &self.text_layout_details(cx);
 6774
 6775        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6776            let line_mode = s.line_mode;
 6777            s.move_with(|map, selection| {
 6778                if !selection.is_empty() && !line_mode {
 6779                    selection.goal = SelectionGoal::None;
 6780                }
 6781                let (cursor, goal) = movement::down_by_rows(
 6782                    map,
 6783                    selection.start,
 6784                    action.lines,
 6785                    selection.goal,
 6786                    false,
 6787                    &text_layout_details,
 6788                );
 6789                selection.collapse_to(cursor, goal);
 6790            });
 6791        })
 6792    }
 6793
 6794    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 6795        let text_layout_details = &self.text_layout_details(cx);
 6796        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6797            s.move_heads_with(|map, head, goal| {
 6798                movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6799            })
 6800        })
 6801    }
 6802
 6803    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 6804        let text_layout_details = &self.text_layout_details(cx);
 6805        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6806            s.move_heads_with(|map, head, goal| {
 6807                movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6808            })
 6809        })
 6810    }
 6811
 6812    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 6813        let Some(row_count) = self.visible_row_count() else {
 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            s.move_heads_with(|map, head, goal| {
 6821                movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
 6822            })
 6823        })
 6824    }
 6825
 6826    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 6827        if self.take_rename(true, cx).is_some() {
 6828            return;
 6829        }
 6830
 6831        if self
 6832            .context_menu
 6833            .write()
 6834            .as_mut()
 6835            .map(|menu| menu.select_first(self.project.as_ref(), cx))
 6836            .unwrap_or(false)
 6837        {
 6838            return;
 6839        }
 6840
 6841        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6842            cx.propagate();
 6843            return;
 6844        }
 6845
 6846        let Some(row_count) = self.visible_row_count() else {
 6847            return;
 6848        };
 6849
 6850        let autoscroll = if action.center_cursor {
 6851            Autoscroll::center()
 6852        } else {
 6853            Autoscroll::fit()
 6854        };
 6855
 6856        let text_layout_details = &self.text_layout_details(cx);
 6857
 6858        self.change_selections(Some(autoscroll), cx, |s| {
 6859            let line_mode = s.line_mode;
 6860            s.move_with(|map, selection| {
 6861                if !selection.is_empty() && !line_mode {
 6862                    selection.goal = SelectionGoal::None;
 6863                }
 6864                let (cursor, goal) = movement::up_by_rows(
 6865                    map,
 6866                    selection.end,
 6867                    row_count,
 6868                    selection.goal,
 6869                    false,
 6870                    &text_layout_details,
 6871                );
 6872                selection.collapse_to(cursor, goal);
 6873            });
 6874        });
 6875    }
 6876
 6877    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 6878        let text_layout_details = &self.text_layout_details(cx);
 6879        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6880            s.move_heads_with(|map, head, goal| {
 6881                movement::up(map, head, goal, false, &text_layout_details)
 6882            })
 6883        })
 6884    }
 6885
 6886    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 6887        self.take_rename(true, cx);
 6888
 6889        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6890            cx.propagate();
 6891            return;
 6892        }
 6893
 6894        let text_layout_details = &self.text_layout_details(cx);
 6895        let selection_count = self.selections.count();
 6896        let first_selection = self.selections.first_anchor();
 6897
 6898        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6899            let line_mode = s.line_mode;
 6900            s.move_with(|map, selection| {
 6901                if !selection.is_empty() && !line_mode {
 6902                    selection.goal = SelectionGoal::None;
 6903                }
 6904                let (cursor, goal) = movement::down(
 6905                    map,
 6906                    selection.end,
 6907                    selection.goal,
 6908                    false,
 6909                    &text_layout_details,
 6910                );
 6911                selection.collapse_to(cursor, goal);
 6912            });
 6913        });
 6914
 6915        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6916        {
 6917            cx.propagate();
 6918        }
 6919    }
 6920
 6921    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 6922        let Some(row_count) = self.visible_row_count() else {
 6923            return;
 6924        };
 6925
 6926        let text_layout_details = &self.text_layout_details(cx);
 6927
 6928        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6929            s.move_heads_with(|map, head, goal| {
 6930                movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
 6931            })
 6932        })
 6933    }
 6934
 6935    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 6936        if self.take_rename(true, cx).is_some() {
 6937            return;
 6938        }
 6939
 6940        if self
 6941            .context_menu
 6942            .write()
 6943            .as_mut()
 6944            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 6945            .unwrap_or(false)
 6946        {
 6947            return;
 6948        }
 6949
 6950        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6951            cx.propagate();
 6952            return;
 6953        }
 6954
 6955        let Some(row_count) = self.visible_row_count() else {
 6956            return;
 6957        };
 6958
 6959        let autoscroll = if action.center_cursor {
 6960            Autoscroll::center()
 6961        } else {
 6962            Autoscroll::fit()
 6963        };
 6964
 6965        let text_layout_details = &self.text_layout_details(cx);
 6966        self.change_selections(Some(autoscroll), cx, |s| {
 6967            let line_mode = s.line_mode;
 6968            s.move_with(|map, selection| {
 6969                if !selection.is_empty() && !line_mode {
 6970                    selection.goal = SelectionGoal::None;
 6971                }
 6972                let (cursor, goal) = movement::down_by_rows(
 6973                    map,
 6974                    selection.end,
 6975                    row_count,
 6976                    selection.goal,
 6977                    false,
 6978                    &text_layout_details,
 6979                );
 6980                selection.collapse_to(cursor, goal);
 6981            });
 6982        });
 6983    }
 6984
 6985    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 6986        let text_layout_details = &self.text_layout_details(cx);
 6987        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6988            s.move_heads_with(|map, head, goal| {
 6989                movement::down(map, head, goal, false, &text_layout_details)
 6990            })
 6991        });
 6992    }
 6993
 6994    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 6995        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6996            context_menu.select_first(self.project.as_ref(), cx);
 6997        }
 6998    }
 6999
 7000    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7001        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7002            context_menu.select_prev(self.project.as_ref(), cx);
 7003        }
 7004    }
 7005
 7006    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7007        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7008            context_menu.select_next(self.project.as_ref(), cx);
 7009        }
 7010    }
 7011
 7012    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7013        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7014            context_menu.select_last(self.project.as_ref(), cx);
 7015        }
 7016    }
 7017
 7018    pub fn move_to_previous_word_start(
 7019        &mut self,
 7020        _: &MoveToPreviousWordStart,
 7021        cx: &mut ViewContext<Self>,
 7022    ) {
 7023        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7024            s.move_cursors_with(|map, head, _| {
 7025                (
 7026                    movement::previous_word_start(map, head),
 7027                    SelectionGoal::None,
 7028                )
 7029            });
 7030        })
 7031    }
 7032
 7033    pub fn move_to_previous_subword_start(
 7034        &mut self,
 7035        _: &MoveToPreviousSubwordStart,
 7036        cx: &mut ViewContext<Self>,
 7037    ) {
 7038        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7039            s.move_cursors_with(|map, head, _| {
 7040                (
 7041                    movement::previous_subword_start(map, head),
 7042                    SelectionGoal::None,
 7043                )
 7044            });
 7045        })
 7046    }
 7047
 7048    pub fn select_to_previous_word_start(
 7049        &mut self,
 7050        _: &SelectToPreviousWordStart,
 7051        cx: &mut ViewContext<Self>,
 7052    ) {
 7053        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7054            s.move_heads_with(|map, head, _| {
 7055                (
 7056                    movement::previous_word_start(map, head),
 7057                    SelectionGoal::None,
 7058                )
 7059            });
 7060        })
 7061    }
 7062
 7063    pub fn select_to_previous_subword_start(
 7064        &mut self,
 7065        _: &SelectToPreviousSubwordStart,
 7066        cx: &mut ViewContext<Self>,
 7067    ) {
 7068        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7069            s.move_heads_with(|map, head, _| {
 7070                (
 7071                    movement::previous_subword_start(map, head),
 7072                    SelectionGoal::None,
 7073                )
 7074            });
 7075        })
 7076    }
 7077
 7078    pub fn delete_to_previous_word_start(
 7079        &mut self,
 7080        _: &DeleteToPreviousWordStart,
 7081        cx: &mut ViewContext<Self>,
 7082    ) {
 7083        self.transact(cx, |this, cx| {
 7084            this.select_autoclose_pair(cx);
 7085            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7086                let line_mode = s.line_mode;
 7087                s.move_with(|map, selection| {
 7088                    if selection.is_empty() && !line_mode {
 7089                        let cursor = movement::previous_word_start(map, selection.head());
 7090                        selection.set_head(cursor, SelectionGoal::None);
 7091                    }
 7092                });
 7093            });
 7094            this.insert("", cx);
 7095        });
 7096    }
 7097
 7098    pub fn delete_to_previous_subword_start(
 7099        &mut self,
 7100        _: &DeleteToPreviousSubwordStart,
 7101        cx: &mut ViewContext<Self>,
 7102    ) {
 7103        self.transact(cx, |this, cx| {
 7104            this.select_autoclose_pair(cx);
 7105            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7106                let line_mode = s.line_mode;
 7107                s.move_with(|map, selection| {
 7108                    if selection.is_empty() && !line_mode {
 7109                        let cursor = movement::previous_subword_start(map, selection.head());
 7110                        selection.set_head(cursor, SelectionGoal::None);
 7111                    }
 7112                });
 7113            });
 7114            this.insert("", cx);
 7115        });
 7116    }
 7117
 7118    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7119        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7120            s.move_cursors_with(|map, head, _| {
 7121                (movement::next_word_end(map, head), SelectionGoal::None)
 7122            });
 7123        })
 7124    }
 7125
 7126    pub fn move_to_next_subword_end(
 7127        &mut self,
 7128        _: &MoveToNextSubwordEnd,
 7129        cx: &mut ViewContext<Self>,
 7130    ) {
 7131        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7132            s.move_cursors_with(|map, head, _| {
 7133                (movement::next_subword_end(map, head), SelectionGoal::None)
 7134            });
 7135        })
 7136    }
 7137
 7138    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7139        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7140            s.move_heads_with(|map, head, _| {
 7141                (movement::next_word_end(map, head), SelectionGoal::None)
 7142            });
 7143        })
 7144    }
 7145
 7146    pub fn select_to_next_subword_end(
 7147        &mut self,
 7148        _: &SelectToNextSubwordEnd,
 7149        cx: &mut ViewContext<Self>,
 7150    ) {
 7151        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7152            s.move_heads_with(|map, head, _| {
 7153                (movement::next_subword_end(map, head), SelectionGoal::None)
 7154            });
 7155        })
 7156    }
 7157
 7158    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
 7159        self.transact(cx, |this, cx| {
 7160            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7161                let line_mode = s.line_mode;
 7162                s.move_with(|map, selection| {
 7163                    if selection.is_empty() && !line_mode {
 7164                        let cursor = movement::next_word_end(map, selection.head());
 7165                        selection.set_head(cursor, SelectionGoal::None);
 7166                    }
 7167                });
 7168            });
 7169            this.insert("", cx);
 7170        });
 7171    }
 7172
 7173    pub fn delete_to_next_subword_end(
 7174        &mut self,
 7175        _: &DeleteToNextSubwordEnd,
 7176        cx: &mut ViewContext<Self>,
 7177    ) {
 7178        self.transact(cx, |this, cx| {
 7179            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7180                s.move_with(|map, selection| {
 7181                    if selection.is_empty() {
 7182                        let cursor = movement::next_subword_end(map, selection.head());
 7183                        selection.set_head(cursor, SelectionGoal::None);
 7184                    }
 7185                });
 7186            });
 7187            this.insert("", cx);
 7188        });
 7189    }
 7190
 7191    pub fn move_to_beginning_of_line(
 7192        &mut self,
 7193        action: &MoveToBeginningOfLine,
 7194        cx: &mut ViewContext<Self>,
 7195    ) {
 7196        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7197            s.move_cursors_with(|map, head, _| {
 7198                (
 7199                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7200                    SelectionGoal::None,
 7201                )
 7202            });
 7203        })
 7204    }
 7205
 7206    pub fn select_to_beginning_of_line(
 7207        &mut self,
 7208        action: &SelectToBeginningOfLine,
 7209        cx: &mut ViewContext<Self>,
 7210    ) {
 7211        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7212            s.move_heads_with(|map, head, _| {
 7213                (
 7214                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7215                    SelectionGoal::None,
 7216                )
 7217            });
 7218        });
 7219    }
 7220
 7221    pub fn delete_to_beginning_of_line(
 7222        &mut self,
 7223        _: &DeleteToBeginningOfLine,
 7224        cx: &mut ViewContext<Self>,
 7225    ) {
 7226        self.transact(cx, |this, cx| {
 7227            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7228                s.move_with(|_, selection| {
 7229                    selection.reversed = true;
 7230                });
 7231            });
 7232
 7233            this.select_to_beginning_of_line(
 7234                &SelectToBeginningOfLine {
 7235                    stop_at_soft_wraps: false,
 7236                },
 7237                cx,
 7238            );
 7239            this.backspace(&Backspace, cx);
 7240        });
 7241    }
 7242
 7243    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7244        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7245            s.move_cursors_with(|map, head, _| {
 7246                (
 7247                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7248                    SelectionGoal::None,
 7249                )
 7250            });
 7251        })
 7252    }
 7253
 7254    pub fn select_to_end_of_line(
 7255        &mut self,
 7256        action: &SelectToEndOfLine,
 7257        cx: &mut ViewContext<Self>,
 7258    ) {
 7259        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7260            s.move_heads_with(|map, head, _| {
 7261                (
 7262                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7263                    SelectionGoal::None,
 7264                )
 7265            });
 7266        })
 7267    }
 7268
 7269    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7270        self.transact(cx, |this, cx| {
 7271            this.select_to_end_of_line(
 7272                &SelectToEndOfLine {
 7273                    stop_at_soft_wraps: false,
 7274                },
 7275                cx,
 7276            );
 7277            this.delete(&Delete, cx);
 7278        });
 7279    }
 7280
 7281    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7282        self.transact(cx, |this, cx| {
 7283            this.select_to_end_of_line(
 7284                &SelectToEndOfLine {
 7285                    stop_at_soft_wraps: false,
 7286                },
 7287                cx,
 7288            );
 7289            this.cut(&Cut, cx);
 7290        });
 7291    }
 7292
 7293    pub fn move_to_start_of_paragraph(
 7294        &mut self,
 7295        _: &MoveToStartOfParagraph,
 7296        cx: &mut ViewContext<Self>,
 7297    ) {
 7298        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7299            cx.propagate();
 7300            return;
 7301        }
 7302
 7303        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7304            s.move_with(|map, selection| {
 7305                selection.collapse_to(
 7306                    movement::start_of_paragraph(map, selection.head(), 1),
 7307                    SelectionGoal::None,
 7308                )
 7309            });
 7310        })
 7311    }
 7312
 7313    pub fn move_to_end_of_paragraph(
 7314        &mut self,
 7315        _: &MoveToEndOfParagraph,
 7316        cx: &mut ViewContext<Self>,
 7317    ) {
 7318        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7319            cx.propagate();
 7320            return;
 7321        }
 7322
 7323        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7324            s.move_with(|map, selection| {
 7325                selection.collapse_to(
 7326                    movement::end_of_paragraph(map, selection.head(), 1),
 7327                    SelectionGoal::None,
 7328                )
 7329            });
 7330        })
 7331    }
 7332
 7333    pub fn select_to_start_of_paragraph(
 7334        &mut self,
 7335        _: &SelectToStartOfParagraph,
 7336        cx: &mut ViewContext<Self>,
 7337    ) {
 7338        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7339            cx.propagate();
 7340            return;
 7341        }
 7342
 7343        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7344            s.move_heads_with(|map, head, _| {
 7345                (
 7346                    movement::start_of_paragraph(map, head, 1),
 7347                    SelectionGoal::None,
 7348                )
 7349            });
 7350        })
 7351    }
 7352
 7353    pub fn select_to_end_of_paragraph(
 7354        &mut self,
 7355        _: &SelectToEndOfParagraph,
 7356        cx: &mut ViewContext<Self>,
 7357    ) {
 7358        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7359            cx.propagate();
 7360            return;
 7361        }
 7362
 7363        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7364            s.move_heads_with(|map, head, _| {
 7365                (
 7366                    movement::end_of_paragraph(map, head, 1),
 7367                    SelectionGoal::None,
 7368                )
 7369            });
 7370        })
 7371    }
 7372
 7373    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7374        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7375            cx.propagate();
 7376            return;
 7377        }
 7378
 7379        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7380            s.select_ranges(vec![0..0]);
 7381        });
 7382    }
 7383
 7384    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7385        let mut selection = self.selections.last::<Point>(cx);
 7386        selection.set_head(Point::zero(), SelectionGoal::None);
 7387
 7388        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7389            s.select(vec![selection]);
 7390        });
 7391    }
 7392
 7393    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7394        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7395            cx.propagate();
 7396            return;
 7397        }
 7398
 7399        let cursor = self.buffer.read(cx).read(cx).len();
 7400        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7401            s.select_ranges(vec![cursor..cursor])
 7402        });
 7403    }
 7404
 7405    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7406        self.nav_history = nav_history;
 7407    }
 7408
 7409    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7410        self.nav_history.as_ref()
 7411    }
 7412
 7413    fn push_to_nav_history(
 7414        &mut self,
 7415        cursor_anchor: Anchor,
 7416        new_position: Option<Point>,
 7417        cx: &mut ViewContext<Self>,
 7418    ) {
 7419        if let Some(nav_history) = self.nav_history.as_mut() {
 7420            let buffer = self.buffer.read(cx).read(cx);
 7421            let cursor_position = cursor_anchor.to_point(&buffer);
 7422            let scroll_state = self.scroll_manager.anchor();
 7423            let scroll_top_row = scroll_state.top_row(&buffer);
 7424            drop(buffer);
 7425
 7426            if let Some(new_position) = new_position {
 7427                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7428                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7429                    return;
 7430                }
 7431            }
 7432
 7433            nav_history.push(
 7434                Some(NavigationData {
 7435                    cursor_anchor,
 7436                    cursor_position,
 7437                    scroll_anchor: scroll_state,
 7438                    scroll_top_row,
 7439                }),
 7440                cx,
 7441            );
 7442        }
 7443    }
 7444
 7445    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7446        let buffer = self.buffer.read(cx).snapshot(cx);
 7447        let mut selection = self.selections.first::<usize>(cx);
 7448        selection.set_head(buffer.len(), SelectionGoal::None);
 7449        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7450            s.select(vec![selection]);
 7451        });
 7452    }
 7453
 7454    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7455        let end = self.buffer.read(cx).read(cx).len();
 7456        self.change_selections(None, cx, |s| {
 7457            s.select_ranges(vec![0..end]);
 7458        });
 7459    }
 7460
 7461    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7462        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7463        let mut selections = self.selections.all::<Point>(cx);
 7464        let max_point = display_map.buffer_snapshot.max_point();
 7465        for selection in &mut selections {
 7466            let rows = selection.spanned_rows(true, &display_map);
 7467            selection.start = Point::new(rows.start.0, 0);
 7468            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7469            selection.reversed = false;
 7470        }
 7471        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7472            s.select(selections);
 7473        });
 7474    }
 7475
 7476    pub fn split_selection_into_lines(
 7477        &mut self,
 7478        _: &SplitSelectionIntoLines,
 7479        cx: &mut ViewContext<Self>,
 7480    ) {
 7481        let mut to_unfold = Vec::new();
 7482        let mut new_selection_ranges = Vec::new();
 7483        {
 7484            let selections = self.selections.all::<Point>(cx);
 7485            let buffer = self.buffer.read(cx).read(cx);
 7486            for selection in selections {
 7487                for row in selection.start.row..selection.end.row {
 7488                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7489                    new_selection_ranges.push(cursor..cursor);
 7490                }
 7491                new_selection_ranges.push(selection.end..selection.end);
 7492                to_unfold.push(selection.start..selection.end);
 7493            }
 7494        }
 7495        self.unfold_ranges(to_unfold, true, true, cx);
 7496        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7497            s.select_ranges(new_selection_ranges);
 7498        });
 7499    }
 7500
 7501    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7502        self.add_selection(true, cx);
 7503    }
 7504
 7505    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7506        self.add_selection(false, cx);
 7507    }
 7508
 7509    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7510        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7511        let mut selections = self.selections.all::<Point>(cx);
 7512        let text_layout_details = self.text_layout_details(cx);
 7513        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7514            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7515            let range = oldest_selection.display_range(&display_map).sorted();
 7516
 7517            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7518            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7519            let positions = start_x.min(end_x)..start_x.max(end_x);
 7520
 7521            selections.clear();
 7522            let mut stack = Vec::new();
 7523            for row in range.start.row().0..=range.end.row().0 {
 7524                if let Some(selection) = self.selections.build_columnar_selection(
 7525                    &display_map,
 7526                    DisplayRow(row),
 7527                    &positions,
 7528                    oldest_selection.reversed,
 7529                    &text_layout_details,
 7530                ) {
 7531                    stack.push(selection.id);
 7532                    selections.push(selection);
 7533                }
 7534            }
 7535
 7536            if above {
 7537                stack.reverse();
 7538            }
 7539
 7540            AddSelectionsState { above, stack }
 7541        });
 7542
 7543        let last_added_selection = *state.stack.last().unwrap();
 7544        let mut new_selections = Vec::new();
 7545        if above == state.above {
 7546            let end_row = if above {
 7547                DisplayRow(0)
 7548            } else {
 7549                display_map.max_point().row()
 7550            };
 7551
 7552            'outer: for selection in selections {
 7553                if selection.id == last_added_selection {
 7554                    let range = selection.display_range(&display_map).sorted();
 7555                    debug_assert_eq!(range.start.row(), range.end.row());
 7556                    let mut row = range.start.row();
 7557                    let positions =
 7558                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7559                            px(start)..px(end)
 7560                        } else {
 7561                            let start_x =
 7562                                display_map.x_for_display_point(range.start, &text_layout_details);
 7563                            let end_x =
 7564                                display_map.x_for_display_point(range.end, &text_layout_details);
 7565                            start_x.min(end_x)..start_x.max(end_x)
 7566                        };
 7567
 7568                    while row != end_row {
 7569                        if above {
 7570                            row.0 -= 1;
 7571                        } else {
 7572                            row.0 += 1;
 7573                        }
 7574
 7575                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7576                            &display_map,
 7577                            row,
 7578                            &positions,
 7579                            selection.reversed,
 7580                            &text_layout_details,
 7581                        ) {
 7582                            state.stack.push(new_selection.id);
 7583                            if above {
 7584                                new_selections.push(new_selection);
 7585                                new_selections.push(selection);
 7586                            } else {
 7587                                new_selections.push(selection);
 7588                                new_selections.push(new_selection);
 7589                            }
 7590
 7591                            continue 'outer;
 7592                        }
 7593                    }
 7594                }
 7595
 7596                new_selections.push(selection);
 7597            }
 7598        } else {
 7599            new_selections = selections;
 7600            new_selections.retain(|s| s.id != last_added_selection);
 7601            state.stack.pop();
 7602        }
 7603
 7604        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7605            s.select(new_selections);
 7606        });
 7607        if state.stack.len() > 1 {
 7608            self.add_selections_state = Some(state);
 7609        }
 7610    }
 7611
 7612    pub fn select_next_match_internal(
 7613        &mut self,
 7614        display_map: &DisplaySnapshot,
 7615        replace_newest: bool,
 7616        autoscroll: Option<Autoscroll>,
 7617        cx: &mut ViewContext<Self>,
 7618    ) -> Result<()> {
 7619        fn select_next_match_ranges(
 7620            this: &mut Editor,
 7621            range: Range<usize>,
 7622            replace_newest: bool,
 7623            auto_scroll: Option<Autoscroll>,
 7624            cx: &mut ViewContext<Editor>,
 7625        ) {
 7626            this.unfold_ranges([range.clone()], false, true, cx);
 7627            this.change_selections(auto_scroll, cx, |s| {
 7628                if replace_newest {
 7629                    s.delete(s.newest_anchor().id);
 7630                }
 7631                s.insert_range(range.clone());
 7632            });
 7633        }
 7634
 7635        let buffer = &display_map.buffer_snapshot;
 7636        let mut selections = self.selections.all::<usize>(cx);
 7637        if let Some(mut select_next_state) = self.select_next_state.take() {
 7638            let query = &select_next_state.query;
 7639            if !select_next_state.done {
 7640                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7641                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7642                let mut next_selected_range = None;
 7643
 7644                let bytes_after_last_selection =
 7645                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7646                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7647                let query_matches = query
 7648                    .stream_find_iter(bytes_after_last_selection)
 7649                    .map(|result| (last_selection.end, result))
 7650                    .chain(
 7651                        query
 7652                            .stream_find_iter(bytes_before_first_selection)
 7653                            .map(|result| (0, result)),
 7654                    );
 7655
 7656                for (start_offset, query_match) in query_matches {
 7657                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7658                    let offset_range =
 7659                        start_offset + query_match.start()..start_offset + query_match.end();
 7660                    let display_range = offset_range.start.to_display_point(&display_map)
 7661                        ..offset_range.end.to_display_point(&display_map);
 7662
 7663                    if !select_next_state.wordwise
 7664                        || (!movement::is_inside_word(&display_map, display_range.start)
 7665                            && !movement::is_inside_word(&display_map, display_range.end))
 7666                    {
 7667                        // TODO: This is n^2, because we might check all the selections
 7668                        if !selections
 7669                            .iter()
 7670                            .any(|selection| selection.range().overlaps(&offset_range))
 7671                        {
 7672                            next_selected_range = Some(offset_range);
 7673                            break;
 7674                        }
 7675                    }
 7676                }
 7677
 7678                if let Some(next_selected_range) = next_selected_range {
 7679                    select_next_match_ranges(
 7680                        self,
 7681                        next_selected_range,
 7682                        replace_newest,
 7683                        autoscroll,
 7684                        cx,
 7685                    );
 7686                } else {
 7687                    select_next_state.done = true;
 7688                }
 7689            }
 7690
 7691            self.select_next_state = Some(select_next_state);
 7692        } else {
 7693            let mut only_carets = true;
 7694            let mut same_text_selected = true;
 7695            let mut selected_text = None;
 7696
 7697            let mut selections_iter = selections.iter().peekable();
 7698            while let Some(selection) = selections_iter.next() {
 7699                if selection.start != selection.end {
 7700                    only_carets = false;
 7701                }
 7702
 7703                if same_text_selected {
 7704                    if selected_text.is_none() {
 7705                        selected_text =
 7706                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7707                    }
 7708
 7709                    if let Some(next_selection) = selections_iter.peek() {
 7710                        if next_selection.range().len() == selection.range().len() {
 7711                            let next_selected_text = buffer
 7712                                .text_for_range(next_selection.range())
 7713                                .collect::<String>();
 7714                            if Some(next_selected_text) != selected_text {
 7715                                same_text_selected = false;
 7716                                selected_text = None;
 7717                            }
 7718                        } else {
 7719                            same_text_selected = false;
 7720                            selected_text = None;
 7721                        }
 7722                    }
 7723                }
 7724            }
 7725
 7726            if only_carets {
 7727                for selection in &mut selections {
 7728                    let word_range = movement::surrounding_word(
 7729                        &display_map,
 7730                        selection.start.to_display_point(&display_map),
 7731                    );
 7732                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7733                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7734                    selection.goal = SelectionGoal::None;
 7735                    selection.reversed = false;
 7736                    select_next_match_ranges(
 7737                        self,
 7738                        selection.start..selection.end,
 7739                        replace_newest,
 7740                        autoscroll,
 7741                        cx,
 7742                    );
 7743                }
 7744
 7745                if selections.len() == 1 {
 7746                    let selection = selections
 7747                        .last()
 7748                        .expect("ensured that there's only one selection");
 7749                    let query = buffer
 7750                        .text_for_range(selection.start..selection.end)
 7751                        .collect::<String>();
 7752                    let is_empty = query.is_empty();
 7753                    let select_state = SelectNextState {
 7754                        query: AhoCorasick::new(&[query])?,
 7755                        wordwise: true,
 7756                        done: is_empty,
 7757                    };
 7758                    self.select_next_state = Some(select_state);
 7759                } else {
 7760                    self.select_next_state = None;
 7761                }
 7762            } else if let Some(selected_text) = selected_text {
 7763                self.select_next_state = Some(SelectNextState {
 7764                    query: AhoCorasick::new(&[selected_text])?,
 7765                    wordwise: false,
 7766                    done: false,
 7767                });
 7768                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 7769            }
 7770        }
 7771        Ok(())
 7772    }
 7773
 7774    pub fn select_all_matches(
 7775        &mut self,
 7776        _action: &SelectAllMatches,
 7777        cx: &mut ViewContext<Self>,
 7778    ) -> Result<()> {
 7779        self.push_to_selection_history();
 7780        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7781
 7782        self.select_next_match_internal(&display_map, false, None, cx)?;
 7783        let Some(select_next_state) = self.select_next_state.as_mut() else {
 7784            return Ok(());
 7785        };
 7786        if select_next_state.done {
 7787            return Ok(());
 7788        }
 7789
 7790        let mut new_selections = self.selections.all::<usize>(cx);
 7791
 7792        let buffer = &display_map.buffer_snapshot;
 7793        let query_matches = select_next_state
 7794            .query
 7795            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 7796
 7797        for query_match in query_matches {
 7798            let query_match = query_match.unwrap(); // can only fail due to I/O
 7799            let offset_range = query_match.start()..query_match.end();
 7800            let display_range = offset_range.start.to_display_point(&display_map)
 7801                ..offset_range.end.to_display_point(&display_map);
 7802
 7803            if !select_next_state.wordwise
 7804                || (!movement::is_inside_word(&display_map, display_range.start)
 7805                    && !movement::is_inside_word(&display_map, display_range.end))
 7806            {
 7807                self.selections.change_with(cx, |selections| {
 7808                    new_selections.push(Selection {
 7809                        id: selections.new_selection_id(),
 7810                        start: offset_range.start,
 7811                        end: offset_range.end,
 7812                        reversed: false,
 7813                        goal: SelectionGoal::None,
 7814                    });
 7815                });
 7816            }
 7817        }
 7818
 7819        new_selections.sort_by_key(|selection| selection.start);
 7820        let mut ix = 0;
 7821        while ix + 1 < new_selections.len() {
 7822            let current_selection = &new_selections[ix];
 7823            let next_selection = &new_selections[ix + 1];
 7824            if current_selection.range().overlaps(&next_selection.range()) {
 7825                if current_selection.id < next_selection.id {
 7826                    new_selections.remove(ix + 1);
 7827                } else {
 7828                    new_selections.remove(ix);
 7829                }
 7830            } else {
 7831                ix += 1;
 7832            }
 7833        }
 7834
 7835        select_next_state.done = true;
 7836        self.unfold_ranges(
 7837            new_selections.iter().map(|selection| selection.range()),
 7838            false,
 7839            false,
 7840            cx,
 7841        );
 7842        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 7843            selections.select(new_selections)
 7844        });
 7845
 7846        Ok(())
 7847    }
 7848
 7849    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 7850        self.push_to_selection_history();
 7851        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7852        self.select_next_match_internal(
 7853            &display_map,
 7854            action.replace_newest,
 7855            Some(Autoscroll::newest()),
 7856            cx,
 7857        )?;
 7858        Ok(())
 7859    }
 7860
 7861    pub fn select_previous(
 7862        &mut self,
 7863        action: &SelectPrevious,
 7864        cx: &mut ViewContext<Self>,
 7865    ) -> Result<()> {
 7866        self.push_to_selection_history();
 7867        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7868        let buffer = &display_map.buffer_snapshot;
 7869        let mut selections = self.selections.all::<usize>(cx);
 7870        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 7871            let query = &select_prev_state.query;
 7872            if !select_prev_state.done {
 7873                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7874                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7875                let mut next_selected_range = None;
 7876                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 7877                let bytes_before_last_selection =
 7878                    buffer.reversed_bytes_in_range(0..last_selection.start);
 7879                let bytes_after_first_selection =
 7880                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 7881                let query_matches = query
 7882                    .stream_find_iter(bytes_before_last_selection)
 7883                    .map(|result| (last_selection.start, result))
 7884                    .chain(
 7885                        query
 7886                            .stream_find_iter(bytes_after_first_selection)
 7887                            .map(|result| (buffer.len(), result)),
 7888                    );
 7889                for (end_offset, query_match) in query_matches {
 7890                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7891                    let offset_range =
 7892                        end_offset - query_match.end()..end_offset - query_match.start();
 7893                    let display_range = offset_range.start.to_display_point(&display_map)
 7894                        ..offset_range.end.to_display_point(&display_map);
 7895
 7896                    if !select_prev_state.wordwise
 7897                        || (!movement::is_inside_word(&display_map, display_range.start)
 7898                            && !movement::is_inside_word(&display_map, display_range.end))
 7899                    {
 7900                        next_selected_range = Some(offset_range);
 7901                        break;
 7902                    }
 7903                }
 7904
 7905                if let Some(next_selected_range) = next_selected_range {
 7906                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 7907                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7908                        if action.replace_newest {
 7909                            s.delete(s.newest_anchor().id);
 7910                        }
 7911                        s.insert_range(next_selected_range);
 7912                    });
 7913                } else {
 7914                    select_prev_state.done = true;
 7915                }
 7916            }
 7917
 7918            self.select_prev_state = Some(select_prev_state);
 7919        } else {
 7920            let mut only_carets = true;
 7921            let mut same_text_selected = true;
 7922            let mut selected_text = None;
 7923
 7924            let mut selections_iter = selections.iter().peekable();
 7925            while let Some(selection) = selections_iter.next() {
 7926                if selection.start != selection.end {
 7927                    only_carets = false;
 7928                }
 7929
 7930                if same_text_selected {
 7931                    if selected_text.is_none() {
 7932                        selected_text =
 7933                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7934                    }
 7935
 7936                    if let Some(next_selection) = selections_iter.peek() {
 7937                        if next_selection.range().len() == selection.range().len() {
 7938                            let next_selected_text = buffer
 7939                                .text_for_range(next_selection.range())
 7940                                .collect::<String>();
 7941                            if Some(next_selected_text) != selected_text {
 7942                                same_text_selected = false;
 7943                                selected_text = None;
 7944                            }
 7945                        } else {
 7946                            same_text_selected = false;
 7947                            selected_text = None;
 7948                        }
 7949                    }
 7950                }
 7951            }
 7952
 7953            if only_carets {
 7954                for selection in &mut selections {
 7955                    let word_range = movement::surrounding_word(
 7956                        &display_map,
 7957                        selection.start.to_display_point(&display_map),
 7958                    );
 7959                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7960                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7961                    selection.goal = SelectionGoal::None;
 7962                    selection.reversed = false;
 7963                }
 7964                if selections.len() == 1 {
 7965                    let selection = selections
 7966                        .last()
 7967                        .expect("ensured that there's only one selection");
 7968                    let query = buffer
 7969                        .text_for_range(selection.start..selection.end)
 7970                        .collect::<String>();
 7971                    let is_empty = query.is_empty();
 7972                    let select_state = SelectNextState {
 7973                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 7974                        wordwise: true,
 7975                        done: is_empty,
 7976                    };
 7977                    self.select_prev_state = Some(select_state);
 7978                } else {
 7979                    self.select_prev_state = None;
 7980                }
 7981
 7982                self.unfold_ranges(
 7983                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 7984                    false,
 7985                    true,
 7986                    cx,
 7987                );
 7988                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7989                    s.select(selections);
 7990                });
 7991            } else if let Some(selected_text) = selected_text {
 7992                self.select_prev_state = Some(SelectNextState {
 7993                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 7994                    wordwise: false,
 7995                    done: false,
 7996                });
 7997                self.select_previous(action, cx)?;
 7998            }
 7999        }
 8000        Ok(())
 8001    }
 8002
 8003    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8004        let text_layout_details = &self.text_layout_details(cx);
 8005        self.transact(cx, |this, cx| {
 8006            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8007            let mut edits = Vec::new();
 8008            let mut selection_edit_ranges = Vec::new();
 8009            let mut last_toggled_row = None;
 8010            let snapshot = this.buffer.read(cx).read(cx);
 8011            let empty_str: Arc<str> = "".into();
 8012            let mut suffixes_inserted = Vec::new();
 8013
 8014            fn comment_prefix_range(
 8015                snapshot: &MultiBufferSnapshot,
 8016                row: MultiBufferRow,
 8017                comment_prefix: &str,
 8018                comment_prefix_whitespace: &str,
 8019            ) -> Range<Point> {
 8020                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8021
 8022                let mut line_bytes = snapshot
 8023                    .bytes_in_range(start..snapshot.max_point())
 8024                    .flatten()
 8025                    .copied();
 8026
 8027                // If this line currently begins with the line comment prefix, then record
 8028                // the range containing the prefix.
 8029                if line_bytes
 8030                    .by_ref()
 8031                    .take(comment_prefix.len())
 8032                    .eq(comment_prefix.bytes())
 8033                {
 8034                    // Include any whitespace that matches the comment prefix.
 8035                    let matching_whitespace_len = line_bytes
 8036                        .zip(comment_prefix_whitespace.bytes())
 8037                        .take_while(|(a, b)| a == b)
 8038                        .count() as u32;
 8039                    let end = Point::new(
 8040                        start.row,
 8041                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8042                    );
 8043                    start..end
 8044                } else {
 8045                    start..start
 8046                }
 8047            }
 8048
 8049            fn comment_suffix_range(
 8050                snapshot: &MultiBufferSnapshot,
 8051                row: MultiBufferRow,
 8052                comment_suffix: &str,
 8053                comment_suffix_has_leading_space: bool,
 8054            ) -> Range<Point> {
 8055                let end = Point::new(row.0, snapshot.line_len(row));
 8056                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8057
 8058                let mut line_end_bytes = snapshot
 8059                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8060                    .flatten()
 8061                    .copied();
 8062
 8063                let leading_space_len = if suffix_start_column > 0
 8064                    && line_end_bytes.next() == Some(b' ')
 8065                    && comment_suffix_has_leading_space
 8066                {
 8067                    1
 8068                } else {
 8069                    0
 8070                };
 8071
 8072                // If this line currently begins with the line comment prefix, then record
 8073                // the range containing the prefix.
 8074                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8075                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8076                    start..end
 8077                } else {
 8078                    end..end
 8079                }
 8080            }
 8081
 8082            // TODO: Handle selections that cross excerpts
 8083            for selection in &mut selections {
 8084                let start_column = snapshot
 8085                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8086                    .len;
 8087                let language = if let Some(language) =
 8088                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8089                {
 8090                    language
 8091                } else {
 8092                    continue;
 8093                };
 8094
 8095                selection_edit_ranges.clear();
 8096
 8097                // If multiple selections contain a given row, avoid processing that
 8098                // row more than once.
 8099                let mut start_row = MultiBufferRow(selection.start.row);
 8100                if last_toggled_row == Some(start_row) {
 8101                    start_row = start_row.next_row();
 8102                }
 8103                let end_row =
 8104                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8105                        MultiBufferRow(selection.end.row - 1)
 8106                    } else {
 8107                        MultiBufferRow(selection.end.row)
 8108                    };
 8109                last_toggled_row = Some(end_row);
 8110
 8111                if start_row > end_row {
 8112                    continue;
 8113                }
 8114
 8115                // If the language has line comments, toggle those.
 8116                let full_comment_prefixes = language.line_comment_prefixes();
 8117                if !full_comment_prefixes.is_empty() {
 8118                    let first_prefix = full_comment_prefixes
 8119                        .first()
 8120                        .expect("prefixes is non-empty");
 8121                    let prefix_trimmed_lengths = full_comment_prefixes
 8122                        .iter()
 8123                        .map(|p| p.trim_end_matches(' ').len())
 8124                        .collect::<SmallVec<[usize; 4]>>();
 8125
 8126                    let mut all_selection_lines_are_comments = true;
 8127
 8128                    for row in start_row.0..=end_row.0 {
 8129                        let row = MultiBufferRow(row);
 8130                        if start_row < end_row && snapshot.is_line_blank(row) {
 8131                            continue;
 8132                        }
 8133
 8134                        let prefix_range = full_comment_prefixes
 8135                            .iter()
 8136                            .zip(prefix_trimmed_lengths.iter().copied())
 8137                            .map(|(prefix, trimmed_prefix_len)| {
 8138                                comment_prefix_range(
 8139                                    snapshot.deref(),
 8140                                    row,
 8141                                    &prefix[..trimmed_prefix_len],
 8142                                    &prefix[trimmed_prefix_len..],
 8143                                )
 8144                            })
 8145                            .max_by_key(|range| range.end.column - range.start.column)
 8146                            .expect("prefixes is non-empty");
 8147
 8148                        if prefix_range.is_empty() {
 8149                            all_selection_lines_are_comments = false;
 8150                        }
 8151
 8152                        selection_edit_ranges.push(prefix_range);
 8153                    }
 8154
 8155                    if all_selection_lines_are_comments {
 8156                        edits.extend(
 8157                            selection_edit_ranges
 8158                                .iter()
 8159                                .cloned()
 8160                                .map(|range| (range, empty_str.clone())),
 8161                        );
 8162                    } else {
 8163                        let min_column = selection_edit_ranges
 8164                            .iter()
 8165                            .map(|range| range.start.column)
 8166                            .min()
 8167                            .unwrap_or(0);
 8168                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8169                            let position = Point::new(range.start.row, min_column);
 8170                            (position..position, first_prefix.clone())
 8171                        }));
 8172                    }
 8173                } else if let Some((full_comment_prefix, comment_suffix)) =
 8174                    language.block_comment_delimiters()
 8175                {
 8176                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8177                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8178                    let prefix_range = comment_prefix_range(
 8179                        snapshot.deref(),
 8180                        start_row,
 8181                        comment_prefix,
 8182                        comment_prefix_whitespace,
 8183                    );
 8184                    let suffix_range = comment_suffix_range(
 8185                        snapshot.deref(),
 8186                        end_row,
 8187                        comment_suffix.trim_start_matches(' '),
 8188                        comment_suffix.starts_with(' '),
 8189                    );
 8190
 8191                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8192                        edits.push((
 8193                            prefix_range.start..prefix_range.start,
 8194                            full_comment_prefix.clone(),
 8195                        ));
 8196                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8197                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8198                    } else {
 8199                        edits.push((prefix_range, empty_str.clone()));
 8200                        edits.push((suffix_range, empty_str.clone()));
 8201                    }
 8202                } else {
 8203                    continue;
 8204                }
 8205            }
 8206
 8207            drop(snapshot);
 8208            this.buffer.update(cx, |buffer, cx| {
 8209                buffer.edit(edits, None, cx);
 8210            });
 8211
 8212            // Adjust selections so that they end before any comment suffixes that
 8213            // were inserted.
 8214            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8215            let mut selections = this.selections.all::<Point>(cx);
 8216            let snapshot = this.buffer.read(cx).read(cx);
 8217            for selection in &mut selections {
 8218                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8219                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8220                        Ordering::Less => {
 8221                            suffixes_inserted.next();
 8222                            continue;
 8223                        }
 8224                        Ordering::Greater => break,
 8225                        Ordering::Equal => {
 8226                            if selection.end.column == snapshot.line_len(row) {
 8227                                if selection.is_empty() {
 8228                                    selection.start.column -= suffix_len as u32;
 8229                                }
 8230                                selection.end.column -= suffix_len as u32;
 8231                            }
 8232                            break;
 8233                        }
 8234                    }
 8235                }
 8236            }
 8237
 8238            drop(snapshot);
 8239            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8240
 8241            let selections = this.selections.all::<Point>(cx);
 8242            let selections_on_single_row = selections.windows(2).all(|selections| {
 8243                selections[0].start.row == selections[1].start.row
 8244                    && selections[0].end.row == selections[1].end.row
 8245                    && selections[0].start.row == selections[0].end.row
 8246            });
 8247            let selections_selecting = selections
 8248                .iter()
 8249                .any(|selection| selection.start != selection.end);
 8250            let advance_downwards = action.advance_downwards
 8251                && selections_on_single_row
 8252                && !selections_selecting
 8253                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8254
 8255            if advance_downwards {
 8256                let snapshot = this.buffer.read(cx).snapshot(cx);
 8257
 8258                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8259                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8260                        let mut point = display_point.to_point(display_snapshot);
 8261                        point.row += 1;
 8262                        point = snapshot.clip_point(point, Bias::Left);
 8263                        let display_point = point.to_display_point(display_snapshot);
 8264                        let goal = SelectionGoal::HorizontalPosition(
 8265                            display_snapshot
 8266                                .x_for_display_point(display_point, &text_layout_details)
 8267                                .into(),
 8268                        );
 8269                        (display_point, goal)
 8270                    })
 8271                });
 8272            }
 8273        });
 8274    }
 8275
 8276    pub fn select_enclosing_symbol(
 8277        &mut self,
 8278        _: &SelectEnclosingSymbol,
 8279        cx: &mut ViewContext<Self>,
 8280    ) {
 8281        let buffer = self.buffer.read(cx).snapshot(cx);
 8282        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8283
 8284        fn update_selection(
 8285            selection: &Selection<usize>,
 8286            buffer_snap: &MultiBufferSnapshot,
 8287        ) -> Option<Selection<usize>> {
 8288            let cursor = selection.head();
 8289            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8290            for symbol in symbols.iter().rev() {
 8291                let start = symbol.range.start.to_offset(&buffer_snap);
 8292                let end = symbol.range.end.to_offset(&buffer_snap);
 8293                let new_range = start..end;
 8294                if start < selection.start || end > selection.end {
 8295                    return Some(Selection {
 8296                        id: selection.id,
 8297                        start: new_range.start,
 8298                        end: new_range.end,
 8299                        goal: SelectionGoal::None,
 8300                        reversed: selection.reversed,
 8301                    });
 8302                }
 8303            }
 8304            None
 8305        }
 8306
 8307        let mut selected_larger_symbol = false;
 8308        let new_selections = old_selections
 8309            .iter()
 8310            .map(|selection| match update_selection(selection, &buffer) {
 8311                Some(new_selection) => {
 8312                    if new_selection.range() != selection.range() {
 8313                        selected_larger_symbol = true;
 8314                    }
 8315                    new_selection
 8316                }
 8317                None => selection.clone(),
 8318            })
 8319            .collect::<Vec<_>>();
 8320
 8321        if selected_larger_symbol {
 8322            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8323                s.select(new_selections);
 8324            });
 8325        }
 8326    }
 8327
 8328    pub fn select_larger_syntax_node(
 8329        &mut self,
 8330        _: &SelectLargerSyntaxNode,
 8331        cx: &mut ViewContext<Self>,
 8332    ) {
 8333        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8334        let buffer = self.buffer.read(cx).snapshot(cx);
 8335        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8336
 8337        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8338        let mut selected_larger_node = false;
 8339        let new_selections = old_selections
 8340            .iter()
 8341            .map(|selection| {
 8342                let old_range = selection.start..selection.end;
 8343                let mut new_range = old_range.clone();
 8344                while let Some(containing_range) =
 8345                    buffer.range_for_syntax_ancestor(new_range.clone())
 8346                {
 8347                    new_range = containing_range;
 8348                    if !display_map.intersects_fold(new_range.start)
 8349                        && !display_map.intersects_fold(new_range.end)
 8350                    {
 8351                        break;
 8352                    }
 8353                }
 8354
 8355                selected_larger_node |= new_range != old_range;
 8356                Selection {
 8357                    id: selection.id,
 8358                    start: new_range.start,
 8359                    end: new_range.end,
 8360                    goal: SelectionGoal::None,
 8361                    reversed: selection.reversed,
 8362                }
 8363            })
 8364            .collect::<Vec<_>>();
 8365
 8366        if selected_larger_node {
 8367            stack.push(old_selections);
 8368            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8369                s.select(new_selections);
 8370            });
 8371        }
 8372        self.select_larger_syntax_node_stack = stack;
 8373    }
 8374
 8375    pub fn select_smaller_syntax_node(
 8376        &mut self,
 8377        _: &SelectSmallerSyntaxNode,
 8378        cx: &mut ViewContext<Self>,
 8379    ) {
 8380        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8381        if let Some(selections) = stack.pop() {
 8382            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8383                s.select(selections.to_vec());
 8384            });
 8385        }
 8386        self.select_larger_syntax_node_stack = stack;
 8387    }
 8388
 8389    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8390        if !EditorSettings::get_global(cx).gutter.runnables {
 8391            self.clear_tasks();
 8392            return Task::ready(());
 8393        }
 8394        let project = self.project.clone();
 8395        cx.spawn(|this, mut cx| async move {
 8396            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8397                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8398            }) else {
 8399                return;
 8400            };
 8401
 8402            let Some(project) = project else {
 8403                return;
 8404            };
 8405
 8406            let hide_runnables = project
 8407                .update(&mut cx, |project, cx| {
 8408                    // Do not display any test indicators in non-dev server remote projects.
 8409                    project.is_remote() && project.ssh_connection_string(cx).is_none()
 8410                })
 8411                .unwrap_or(true);
 8412            if hide_runnables {
 8413                return;
 8414            }
 8415            let new_rows =
 8416                cx.background_executor()
 8417                    .spawn({
 8418                        let snapshot = display_snapshot.clone();
 8419                        async move {
 8420                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8421                        }
 8422                    })
 8423                    .await;
 8424            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8425
 8426            this.update(&mut cx, |this, _| {
 8427                this.clear_tasks();
 8428                for (key, value) in rows {
 8429                    this.insert_tasks(key, value);
 8430                }
 8431            })
 8432            .ok();
 8433        })
 8434    }
 8435    fn fetch_runnable_ranges(
 8436        snapshot: &DisplaySnapshot,
 8437        range: Range<Anchor>,
 8438    ) -> Vec<language::RunnableRange> {
 8439        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8440    }
 8441
 8442    fn runnable_rows(
 8443        project: Model<Project>,
 8444        snapshot: DisplaySnapshot,
 8445        runnable_ranges: Vec<RunnableRange>,
 8446        mut cx: AsyncWindowContext,
 8447    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8448        runnable_ranges
 8449            .into_iter()
 8450            .filter_map(|mut runnable| {
 8451                let tasks = cx
 8452                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8453                    .ok()?;
 8454                if tasks.is_empty() {
 8455                    return None;
 8456                }
 8457
 8458                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8459
 8460                let row = snapshot
 8461                    .buffer_snapshot
 8462                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8463                    .1
 8464                    .start
 8465                    .row;
 8466
 8467                let context_range =
 8468                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8469                Some((
 8470                    (runnable.buffer_id, row),
 8471                    RunnableTasks {
 8472                        templates: tasks,
 8473                        offset: MultiBufferOffset(runnable.run_range.start),
 8474                        context_range,
 8475                        column: point.column,
 8476                        extra_variables: runnable.extra_captures,
 8477                    },
 8478                ))
 8479            })
 8480            .collect()
 8481    }
 8482
 8483    fn templates_with_tags(
 8484        project: &Model<Project>,
 8485        runnable: &mut Runnable,
 8486        cx: &WindowContext<'_>,
 8487    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8488        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8489            let (worktree_id, file) = project
 8490                .buffer_for_id(runnable.buffer)
 8491                .and_then(|buffer| buffer.read(cx).file())
 8492                .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
 8493                .unzip();
 8494
 8495            (project.task_inventory().clone(), worktree_id, file)
 8496        });
 8497
 8498        let inventory = inventory.read(cx);
 8499        let tags = mem::take(&mut runnable.tags);
 8500        let mut tags: Vec<_> = tags
 8501            .into_iter()
 8502            .flat_map(|tag| {
 8503                let tag = tag.0.clone();
 8504                inventory
 8505                    .list_tasks(
 8506                        file.clone(),
 8507                        Some(runnable.language.clone()),
 8508                        worktree_id,
 8509                        cx,
 8510                    )
 8511                    .into_iter()
 8512                    .filter(move |(_, template)| {
 8513                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8514                    })
 8515            })
 8516            .sorted_by_key(|(kind, _)| kind.to_owned())
 8517            .collect();
 8518        if let Some((leading_tag_source, _)) = tags.first() {
 8519            // Strongest source wins; if we have worktree tag binding, prefer that to
 8520            // global and language bindings;
 8521            // if we have a global binding, prefer that to language binding.
 8522            let first_mismatch = tags
 8523                .iter()
 8524                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8525            if let Some(index) = first_mismatch {
 8526                tags.truncate(index);
 8527            }
 8528        }
 8529
 8530        tags
 8531    }
 8532
 8533    pub fn move_to_enclosing_bracket(
 8534        &mut self,
 8535        _: &MoveToEnclosingBracket,
 8536        cx: &mut ViewContext<Self>,
 8537    ) {
 8538        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8539            s.move_offsets_with(|snapshot, selection| {
 8540                let Some(enclosing_bracket_ranges) =
 8541                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8542                else {
 8543                    return;
 8544                };
 8545
 8546                let mut best_length = usize::MAX;
 8547                let mut best_inside = false;
 8548                let mut best_in_bracket_range = false;
 8549                let mut best_destination = None;
 8550                for (open, close) in enclosing_bracket_ranges {
 8551                    let close = close.to_inclusive();
 8552                    let length = close.end() - open.start;
 8553                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8554                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8555                        || close.contains(&selection.head());
 8556
 8557                    // If best is next to a bracket and current isn't, skip
 8558                    if !in_bracket_range && best_in_bracket_range {
 8559                        continue;
 8560                    }
 8561
 8562                    // Prefer smaller lengths unless best is inside and current isn't
 8563                    if length > best_length && (best_inside || !inside) {
 8564                        continue;
 8565                    }
 8566
 8567                    best_length = length;
 8568                    best_inside = inside;
 8569                    best_in_bracket_range = in_bracket_range;
 8570                    best_destination = Some(
 8571                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8572                            if inside {
 8573                                open.end
 8574                            } else {
 8575                                open.start
 8576                            }
 8577                        } else {
 8578                            if inside {
 8579                                *close.start()
 8580                            } else {
 8581                                *close.end()
 8582                            }
 8583                        },
 8584                    );
 8585                }
 8586
 8587                if let Some(destination) = best_destination {
 8588                    selection.collapse_to(destination, SelectionGoal::None);
 8589                }
 8590            })
 8591        });
 8592    }
 8593
 8594    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 8595        self.end_selection(cx);
 8596        self.selection_history.mode = SelectionHistoryMode::Undoing;
 8597        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 8598            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8599            self.select_next_state = entry.select_next_state;
 8600            self.select_prev_state = entry.select_prev_state;
 8601            self.add_selections_state = entry.add_selections_state;
 8602            self.request_autoscroll(Autoscroll::newest(), cx);
 8603        }
 8604        self.selection_history.mode = SelectionHistoryMode::Normal;
 8605    }
 8606
 8607    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 8608        self.end_selection(cx);
 8609        self.selection_history.mode = SelectionHistoryMode::Redoing;
 8610        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 8611            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8612            self.select_next_state = entry.select_next_state;
 8613            self.select_prev_state = entry.select_prev_state;
 8614            self.add_selections_state = entry.add_selections_state;
 8615            self.request_autoscroll(Autoscroll::newest(), cx);
 8616        }
 8617        self.selection_history.mode = SelectionHistoryMode::Normal;
 8618    }
 8619
 8620    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 8621        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 8622    }
 8623
 8624    pub fn expand_excerpts_down(
 8625        &mut self,
 8626        action: &ExpandExcerptsDown,
 8627        cx: &mut ViewContext<Self>,
 8628    ) {
 8629        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 8630    }
 8631
 8632    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 8633        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 8634    }
 8635
 8636    pub fn expand_excerpts_for_direction(
 8637        &mut self,
 8638        lines: u32,
 8639        direction: ExpandExcerptDirection,
 8640        cx: &mut ViewContext<Self>,
 8641    ) {
 8642        let selections = self.selections.disjoint_anchors();
 8643
 8644        let lines = if lines == 0 {
 8645            EditorSettings::get_global(cx).expand_excerpt_lines
 8646        } else {
 8647            lines
 8648        };
 8649
 8650        self.buffer.update(cx, |buffer, cx| {
 8651            buffer.expand_excerpts(
 8652                selections
 8653                    .into_iter()
 8654                    .map(|selection| selection.head().excerpt_id)
 8655                    .dedup(),
 8656                lines,
 8657                direction,
 8658                cx,
 8659            )
 8660        })
 8661    }
 8662
 8663    pub fn expand_excerpt(
 8664        &mut self,
 8665        excerpt: ExcerptId,
 8666        direction: ExpandExcerptDirection,
 8667        cx: &mut ViewContext<Self>,
 8668    ) {
 8669        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 8670        self.buffer.update(cx, |buffer, cx| {
 8671            buffer.expand_excerpts([excerpt], lines, direction, cx)
 8672        })
 8673    }
 8674
 8675    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8676        self.go_to_diagnostic_impl(Direction::Next, cx)
 8677    }
 8678
 8679    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8680        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8681    }
 8682
 8683    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8684        let buffer = self.buffer.read(cx).snapshot(cx);
 8685        let selection = self.selections.newest::<usize>(cx);
 8686
 8687        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8688        if direction == Direction::Next {
 8689            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8690                let (group_id, jump_to) = popover.activation_info();
 8691                if self.activate_diagnostics(group_id, cx) {
 8692                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8693                        let mut new_selection = s.newest_anchor().clone();
 8694                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 8695                        s.select_anchors(vec![new_selection.clone()]);
 8696                    });
 8697                }
 8698                return;
 8699            }
 8700        }
 8701
 8702        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 8703            active_diagnostics
 8704                .primary_range
 8705                .to_offset(&buffer)
 8706                .to_inclusive()
 8707        });
 8708        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 8709            if active_primary_range.contains(&selection.head()) {
 8710                *active_primary_range.start()
 8711            } else {
 8712                selection.head()
 8713            }
 8714        } else {
 8715            selection.head()
 8716        };
 8717        let snapshot = self.snapshot(cx);
 8718        loop {
 8719            let diagnostics = if direction == Direction::Prev {
 8720                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 8721            } else {
 8722                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 8723            }
 8724            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 8725            let group = diagnostics
 8726                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 8727                // be sorted in a stable way
 8728                // skip until we are at current active diagnostic, if it exists
 8729                .skip_while(|entry| {
 8730                    (match direction {
 8731                        Direction::Prev => entry.range.start >= search_start,
 8732                        Direction::Next => entry.range.start <= search_start,
 8733                    }) && self
 8734                        .active_diagnostics
 8735                        .as_ref()
 8736                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 8737                })
 8738                .find_map(|entry| {
 8739                    if entry.diagnostic.is_primary
 8740                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 8741                        && !entry.range.is_empty()
 8742                        // if we match with the active diagnostic, skip it
 8743                        && Some(entry.diagnostic.group_id)
 8744                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 8745                    {
 8746                        Some((entry.range, entry.diagnostic.group_id))
 8747                    } else {
 8748                        None
 8749                    }
 8750                });
 8751
 8752            if let Some((primary_range, group_id)) = group {
 8753                if self.activate_diagnostics(group_id, cx) {
 8754                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8755                        s.select(vec![Selection {
 8756                            id: selection.id,
 8757                            start: primary_range.start,
 8758                            end: primary_range.start,
 8759                            reversed: false,
 8760                            goal: SelectionGoal::None,
 8761                        }]);
 8762                    });
 8763                }
 8764                break;
 8765            } else {
 8766                // Cycle around to the start of the buffer, potentially moving back to the start of
 8767                // the currently active diagnostic.
 8768                active_primary_range.take();
 8769                if direction == Direction::Prev {
 8770                    if search_start == buffer.len() {
 8771                        break;
 8772                    } else {
 8773                        search_start = buffer.len();
 8774                    }
 8775                } else if search_start == 0 {
 8776                    break;
 8777                } else {
 8778                    search_start = 0;
 8779                }
 8780            }
 8781        }
 8782    }
 8783
 8784    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 8785        let snapshot = self
 8786            .display_map
 8787            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8788        let selection = self.selections.newest::<Point>(cx);
 8789
 8790        if !self.seek_in_direction(
 8791            &snapshot,
 8792            selection.head(),
 8793            false,
 8794            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8795                MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
 8796            ),
 8797            cx,
 8798        ) {
 8799            let wrapped_point = Point::zero();
 8800            self.seek_in_direction(
 8801                &snapshot,
 8802                wrapped_point,
 8803                true,
 8804                snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8805                    MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 8806                ),
 8807                cx,
 8808            );
 8809        }
 8810    }
 8811
 8812    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 8813        let snapshot = self
 8814            .display_map
 8815            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8816        let selection = self.selections.newest::<Point>(cx);
 8817
 8818        if !self.seek_in_direction(
 8819            &snapshot,
 8820            selection.head(),
 8821            false,
 8822            snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8823                MultiBufferRow(0)..MultiBufferRow(selection.head().row),
 8824            ),
 8825            cx,
 8826        ) {
 8827            let wrapped_point = snapshot.buffer_snapshot.max_point();
 8828            self.seek_in_direction(
 8829                &snapshot,
 8830                wrapped_point,
 8831                true,
 8832                snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8833                    MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
 8834                ),
 8835                cx,
 8836            );
 8837        }
 8838    }
 8839
 8840    fn seek_in_direction(
 8841        &mut self,
 8842        snapshot: &DisplaySnapshot,
 8843        initial_point: Point,
 8844        is_wrapped: bool,
 8845        hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
 8846        cx: &mut ViewContext<Editor>,
 8847    ) -> bool {
 8848        let display_point = initial_point.to_display_point(snapshot);
 8849        let mut hunks = hunks
 8850            .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
 8851            .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
 8852            .dedup();
 8853
 8854        if let Some(hunk) = hunks.next() {
 8855            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8856                let row = hunk.start_display_row();
 8857                let point = DisplayPoint::new(row, 0);
 8858                s.select_display_ranges([point..point]);
 8859            });
 8860
 8861            true
 8862        } else {
 8863            false
 8864        }
 8865    }
 8866
 8867    pub fn go_to_definition(
 8868        &mut self,
 8869        _: &GoToDefinition,
 8870        cx: &mut ViewContext<Self>,
 8871    ) -> Task<Result<bool>> {
 8872        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
 8873    }
 8874
 8875    pub fn go_to_implementation(
 8876        &mut self,
 8877        _: &GoToImplementation,
 8878        cx: &mut ViewContext<Self>,
 8879    ) -> Task<Result<bool>> {
 8880        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 8881    }
 8882
 8883    pub fn go_to_implementation_split(
 8884        &mut self,
 8885        _: &GoToImplementationSplit,
 8886        cx: &mut ViewContext<Self>,
 8887    ) -> Task<Result<bool>> {
 8888        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 8889    }
 8890
 8891    pub fn go_to_type_definition(
 8892        &mut self,
 8893        _: &GoToTypeDefinition,
 8894        cx: &mut ViewContext<Self>,
 8895    ) -> Task<Result<bool>> {
 8896        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 8897    }
 8898
 8899    pub fn go_to_definition_split(
 8900        &mut self,
 8901        _: &GoToDefinitionSplit,
 8902        cx: &mut ViewContext<Self>,
 8903    ) -> Task<Result<bool>> {
 8904        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 8905    }
 8906
 8907    pub fn go_to_type_definition_split(
 8908        &mut self,
 8909        _: &GoToTypeDefinitionSplit,
 8910        cx: &mut ViewContext<Self>,
 8911    ) -> Task<Result<bool>> {
 8912        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 8913    }
 8914
 8915    fn go_to_definition_of_kind(
 8916        &mut self,
 8917        kind: GotoDefinitionKind,
 8918        split: bool,
 8919        cx: &mut ViewContext<Self>,
 8920    ) -> Task<Result<bool>> {
 8921        let Some(workspace) = self.workspace() else {
 8922            return Task::ready(Ok(false));
 8923        };
 8924        let buffer = self.buffer.read(cx);
 8925        let head = self.selections.newest::<usize>(cx).head();
 8926        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 8927            text_anchor
 8928        } else {
 8929            return Task::ready(Ok(false));
 8930        };
 8931
 8932        let project = workspace.read(cx).project().clone();
 8933        let definitions = project.update(cx, |project, cx| match kind {
 8934            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 8935            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 8936            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 8937        });
 8938
 8939        cx.spawn(|editor, mut cx| async move {
 8940            let definitions = definitions.await?;
 8941            let navigated = editor
 8942                .update(&mut cx, |editor, cx| {
 8943                    editor.navigate_to_hover_links(
 8944                        Some(kind),
 8945                        definitions
 8946                            .into_iter()
 8947                            .filter(|location| {
 8948                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 8949                            })
 8950                            .map(HoverLink::Text)
 8951                            .collect::<Vec<_>>(),
 8952                        split,
 8953                        cx,
 8954                    )
 8955                })?
 8956                .await?;
 8957            anyhow::Ok(navigated)
 8958        })
 8959    }
 8960
 8961    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 8962        let position = self.selections.newest_anchor().head();
 8963        let Some((buffer, buffer_position)) =
 8964            self.buffer.read(cx).text_anchor_for_position(position, cx)
 8965        else {
 8966            return;
 8967        };
 8968
 8969        cx.spawn(|editor, mut cx| async move {
 8970            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 8971                editor.update(&mut cx, |_, cx| {
 8972                    cx.open_url(&url);
 8973                })
 8974            } else {
 8975                Ok(())
 8976            }
 8977        })
 8978        .detach();
 8979    }
 8980
 8981    pub(crate) fn navigate_to_hover_links(
 8982        &mut self,
 8983        kind: Option<GotoDefinitionKind>,
 8984        mut definitions: Vec<HoverLink>,
 8985        split: bool,
 8986        cx: &mut ViewContext<Editor>,
 8987    ) -> Task<Result<bool>> {
 8988        // If there is one definition, just open it directly
 8989        if definitions.len() == 1 {
 8990            let definition = definitions.pop().unwrap();
 8991            let target_task = match definition {
 8992                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 8993                HoverLink::InlayHint(lsp_location, server_id) => {
 8994                    self.compute_target_location(lsp_location, server_id, cx)
 8995                }
 8996                HoverLink::Url(url) => {
 8997                    cx.open_url(&url);
 8998                    Task::ready(Ok(None))
 8999                }
 9000            };
 9001            cx.spawn(|editor, mut cx| async move {
 9002                let target = target_task.await.context("target resolution task")?;
 9003                if let Some(target) = target {
 9004                    editor.update(&mut cx, |editor, cx| {
 9005                        let Some(workspace) = editor.workspace() else {
 9006                            return false;
 9007                        };
 9008                        let pane = workspace.read(cx).active_pane().clone();
 9009
 9010                        let range = target.range.to_offset(target.buffer.read(cx));
 9011                        let range = editor.range_for_match(&range);
 9012
 9013                        /// If select range has more than one line, we
 9014                        /// just point the cursor to range.start.
 9015                        fn check_multiline_range(
 9016                            buffer: &Buffer,
 9017                            range: Range<usize>,
 9018                        ) -> Range<usize> {
 9019                            if buffer.offset_to_point(range.start).row
 9020                                == buffer.offset_to_point(range.end).row
 9021                            {
 9022                                range
 9023                            } else {
 9024                                range.start..range.start
 9025                            }
 9026                        }
 9027
 9028                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9029                            let buffer = target.buffer.read(cx);
 9030                            let range = check_multiline_range(buffer, range);
 9031                            editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 9032                                s.select_ranges([range]);
 9033                            });
 9034                        } else {
 9035                            cx.window_context().defer(move |cx| {
 9036                                let target_editor: View<Self> =
 9037                                    workspace.update(cx, |workspace, cx| {
 9038                                        let pane = if split {
 9039                                            workspace.adjacent_pane(cx)
 9040                                        } else {
 9041                                            workspace.active_pane().clone()
 9042                                        };
 9043
 9044                                        workspace.open_project_item(pane, target.buffer.clone(), cx)
 9045                                    });
 9046                                target_editor.update(cx, |target_editor, cx| {
 9047                                    // When selecting a definition in a different buffer, disable the nav history
 9048                                    // to avoid creating a history entry at the previous cursor location.
 9049                                    pane.update(cx, |pane, _| pane.disable_history());
 9050                                    let buffer = target.buffer.read(cx);
 9051                                    let range = check_multiline_range(buffer, range);
 9052                                    target_editor.change_selections(
 9053                                        Some(Autoscroll::focused()),
 9054                                        cx,
 9055                                        |s| {
 9056                                            s.select_ranges([range]);
 9057                                        },
 9058                                    );
 9059                                    pane.update(cx, |pane, _| pane.enable_history());
 9060                                });
 9061                            });
 9062                        }
 9063                        true
 9064                    })
 9065                } else {
 9066                    Ok(false)
 9067                }
 9068            })
 9069        } else if !definitions.is_empty() {
 9070            let replica_id = self.replica_id(cx);
 9071            cx.spawn(|editor, mut cx| async move {
 9072                let (title, location_tasks, workspace) = editor
 9073                    .update(&mut cx, |editor, cx| {
 9074                        let tab_kind = match kind {
 9075                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9076                            _ => "Definitions",
 9077                        };
 9078                        let title = definitions
 9079                            .iter()
 9080                            .find_map(|definition| match definition {
 9081                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9082                                    let buffer = origin.buffer.read(cx);
 9083                                    format!(
 9084                                        "{} for {}",
 9085                                        tab_kind,
 9086                                        buffer
 9087                                            .text_for_range(origin.range.clone())
 9088                                            .collect::<String>()
 9089                                    )
 9090                                }),
 9091                                HoverLink::InlayHint(_, _) => None,
 9092                                HoverLink::Url(_) => None,
 9093                            })
 9094                            .unwrap_or(tab_kind.to_string());
 9095                        let location_tasks = definitions
 9096                            .into_iter()
 9097                            .map(|definition| match definition {
 9098                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9099                                HoverLink::InlayHint(lsp_location, server_id) => {
 9100                                    editor.compute_target_location(lsp_location, server_id, cx)
 9101                                }
 9102                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9103                            })
 9104                            .collect::<Vec<_>>();
 9105                        (title, location_tasks, editor.workspace().clone())
 9106                    })
 9107                    .context("location tasks preparation")?;
 9108
 9109                let locations = futures::future::join_all(location_tasks)
 9110                    .await
 9111                    .into_iter()
 9112                    .filter_map(|location| location.transpose())
 9113                    .collect::<Result<_>>()
 9114                    .context("location tasks")?;
 9115
 9116                let Some(workspace) = workspace else {
 9117                    return Ok(false);
 9118                };
 9119                let opened = workspace
 9120                    .update(&mut cx, |workspace, cx| {
 9121                        Self::open_locations_in_multibuffer(
 9122                            workspace, locations, replica_id, title, split, cx,
 9123                        )
 9124                    })
 9125                    .ok();
 9126
 9127                anyhow::Ok(opened.is_some())
 9128            })
 9129        } else {
 9130            Task::ready(Ok(false))
 9131        }
 9132    }
 9133
 9134    fn compute_target_location(
 9135        &self,
 9136        lsp_location: lsp::Location,
 9137        server_id: LanguageServerId,
 9138        cx: &mut ViewContext<Editor>,
 9139    ) -> Task<anyhow::Result<Option<Location>>> {
 9140        let Some(project) = self.project.clone() else {
 9141            return Task::Ready(Some(Ok(None)));
 9142        };
 9143
 9144        cx.spawn(move |editor, mut cx| async move {
 9145            let location_task = editor.update(&mut cx, |editor, cx| {
 9146                project.update(cx, |project, cx| {
 9147                    let language_server_name =
 9148                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 9149                            project
 9150                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 9151                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 9152                        });
 9153                    language_server_name.map(|language_server_name| {
 9154                        project.open_local_buffer_via_lsp(
 9155                            lsp_location.uri.clone(),
 9156                            server_id,
 9157                            language_server_name,
 9158                            cx,
 9159                        )
 9160                    })
 9161                })
 9162            })?;
 9163            let location = match location_task {
 9164                Some(task) => Some({
 9165                    let target_buffer_handle = task.await.context("open local buffer")?;
 9166                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9167                        let target_start = target_buffer
 9168                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9169                        let target_end = target_buffer
 9170                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9171                        target_buffer.anchor_after(target_start)
 9172                            ..target_buffer.anchor_before(target_end)
 9173                    })?;
 9174                    Location {
 9175                        buffer: target_buffer_handle,
 9176                        range,
 9177                    }
 9178                }),
 9179                None => None,
 9180            };
 9181            Ok(location)
 9182        })
 9183    }
 9184
 9185    pub fn find_all_references(
 9186        &mut self,
 9187        _: &FindAllReferences,
 9188        cx: &mut ViewContext<Self>,
 9189    ) -> Option<Task<Result<()>>> {
 9190        let multi_buffer = self.buffer.read(cx);
 9191        let selection = self.selections.newest::<usize>(cx);
 9192        let head = selection.head();
 9193
 9194        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9195        let head_anchor = multi_buffer_snapshot.anchor_at(
 9196            head,
 9197            if head < selection.tail() {
 9198                Bias::Right
 9199            } else {
 9200                Bias::Left
 9201            },
 9202        );
 9203
 9204        match self
 9205            .find_all_references_task_sources
 9206            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9207        {
 9208            Ok(_) => {
 9209                log::info!(
 9210                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9211                );
 9212                return None;
 9213            }
 9214            Err(i) => {
 9215                self.find_all_references_task_sources.insert(i, head_anchor);
 9216            }
 9217        }
 9218
 9219        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9220        let replica_id = self.replica_id(cx);
 9221        let workspace = self.workspace()?;
 9222        let project = workspace.read(cx).project().clone();
 9223        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9224        Some(cx.spawn(|editor, mut cx| async move {
 9225            let _cleanup = defer({
 9226                let mut cx = cx.clone();
 9227                move || {
 9228                    let _ = editor.update(&mut cx, |editor, _| {
 9229                        if let Ok(i) =
 9230                            editor
 9231                                .find_all_references_task_sources
 9232                                .binary_search_by(|anchor| {
 9233                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9234                                })
 9235                        {
 9236                            editor.find_all_references_task_sources.remove(i);
 9237                        }
 9238                    });
 9239                }
 9240            });
 9241
 9242            let locations = references.await?;
 9243            if locations.is_empty() {
 9244                return anyhow::Ok(());
 9245            }
 9246
 9247            workspace.update(&mut cx, |workspace, cx| {
 9248                let title = locations
 9249                    .first()
 9250                    .as_ref()
 9251                    .map(|location| {
 9252                        let buffer = location.buffer.read(cx);
 9253                        format!(
 9254                            "References to `{}`",
 9255                            buffer
 9256                                .text_for_range(location.range.clone())
 9257                                .collect::<String>()
 9258                        )
 9259                    })
 9260                    .unwrap();
 9261                Self::open_locations_in_multibuffer(
 9262                    workspace, locations, replica_id, title, false, cx,
 9263                );
 9264            })
 9265        }))
 9266    }
 9267
 9268    /// Opens a multibuffer with the given project locations in it
 9269    pub fn open_locations_in_multibuffer(
 9270        workspace: &mut Workspace,
 9271        mut locations: Vec<Location>,
 9272        replica_id: ReplicaId,
 9273        title: String,
 9274        split: bool,
 9275        cx: &mut ViewContext<Workspace>,
 9276    ) {
 9277        // If there are multiple definitions, open them in a multibuffer
 9278        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9279        let mut locations = locations.into_iter().peekable();
 9280        let mut ranges_to_highlight = Vec::new();
 9281        let capability = workspace.project().read(cx).capability();
 9282
 9283        let excerpt_buffer = cx.new_model(|cx| {
 9284            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 9285            while let Some(location) = locations.next() {
 9286                let buffer = location.buffer.read(cx);
 9287                let mut ranges_for_buffer = Vec::new();
 9288                let range = location.range.to_offset(buffer);
 9289                ranges_for_buffer.push(range.clone());
 9290
 9291                while let Some(next_location) = locations.peek() {
 9292                    if next_location.buffer == location.buffer {
 9293                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9294                        locations.next();
 9295                    } else {
 9296                        break;
 9297                    }
 9298                }
 9299
 9300                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9301                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9302                    location.buffer.clone(),
 9303                    ranges_for_buffer,
 9304                    DEFAULT_MULTIBUFFER_CONTEXT,
 9305                    cx,
 9306                ))
 9307            }
 9308
 9309            multibuffer.with_title(title)
 9310        });
 9311
 9312        let editor = cx.new_view(|cx| {
 9313            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9314        });
 9315        editor.update(cx, |editor, cx| {
 9316            if let Some(first_range) = ranges_to_highlight.first() {
 9317                editor.change_selections(None, cx, |selections| {
 9318                    selections.clear_disjoint();
 9319                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9320                });
 9321            }
 9322            editor.highlight_background::<Self>(
 9323                &ranges_to_highlight,
 9324                |theme| theme.editor_highlighted_line_background,
 9325                cx,
 9326            );
 9327        });
 9328
 9329        let item = Box::new(editor);
 9330        let item_id = item.item_id();
 9331
 9332        if split {
 9333            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9334        } else {
 9335            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9336                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9337                    pane.close_current_preview_item(cx)
 9338                } else {
 9339                    None
 9340                }
 9341            });
 9342            workspace.add_item_to_active_pane(item.clone(), destination_index, cx);
 9343        }
 9344        workspace.active_pane().update(cx, |pane, cx| {
 9345            pane.set_preview_item_id(Some(item_id), cx);
 9346        });
 9347    }
 9348
 9349    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9350        use language::ToOffset as _;
 9351
 9352        let project = self.project.clone()?;
 9353        let selection = self.selections.newest_anchor().clone();
 9354        let (cursor_buffer, cursor_buffer_position) = self
 9355            .buffer
 9356            .read(cx)
 9357            .text_anchor_for_position(selection.head(), cx)?;
 9358        let (tail_buffer, cursor_buffer_position_end) = self
 9359            .buffer
 9360            .read(cx)
 9361            .text_anchor_for_position(selection.tail(), cx)?;
 9362        if tail_buffer != cursor_buffer {
 9363            return None;
 9364        }
 9365
 9366        let snapshot = cursor_buffer.read(cx).snapshot();
 9367        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9368        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9369        let prepare_rename = project.update(cx, |project, cx| {
 9370            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 9371        });
 9372        drop(snapshot);
 9373
 9374        Some(cx.spawn(|this, mut cx| async move {
 9375            let rename_range = if let Some(range) = prepare_rename.await? {
 9376                Some(range)
 9377            } else {
 9378                this.update(&mut cx, |this, cx| {
 9379                    let buffer = this.buffer.read(cx).snapshot(cx);
 9380                    let mut buffer_highlights = this
 9381                        .document_highlights_for_position(selection.head(), &buffer)
 9382                        .filter(|highlight| {
 9383                            highlight.start.excerpt_id == selection.head().excerpt_id
 9384                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9385                        });
 9386                    buffer_highlights
 9387                        .next()
 9388                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9389                })?
 9390            };
 9391            if let Some(rename_range) = rename_range {
 9392                this.update(&mut cx, |this, cx| {
 9393                    let snapshot = cursor_buffer.read(cx).snapshot();
 9394                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9395                    let cursor_offset_in_rename_range =
 9396                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9397                    let cursor_offset_in_rename_range_end =
 9398                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9399
 9400                    this.take_rename(false, cx);
 9401                    let buffer = this.buffer.read(cx).read(cx);
 9402                    let cursor_offset = selection.head().to_offset(&buffer);
 9403                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9404                    let rename_end = rename_start + rename_buffer_range.len();
 9405                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9406                    let mut old_highlight_id = None;
 9407                    let old_name: Arc<str> = buffer
 9408                        .chunks(rename_start..rename_end, true)
 9409                        .map(|chunk| {
 9410                            if old_highlight_id.is_none() {
 9411                                old_highlight_id = chunk.syntax_highlight_id;
 9412                            }
 9413                            chunk.text
 9414                        })
 9415                        .collect::<String>()
 9416                        .into();
 9417
 9418                    drop(buffer);
 9419
 9420                    // Position the selection in the rename editor so that it matches the current selection.
 9421                    this.show_local_selections = false;
 9422                    let rename_editor = cx.new_view(|cx| {
 9423                        let mut editor = Editor::single_line(cx);
 9424                        editor.buffer.update(cx, |buffer, cx| {
 9425                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9426                        });
 9427                        let rename_selection_range = match cursor_offset_in_rename_range
 9428                            .cmp(&cursor_offset_in_rename_range_end)
 9429                        {
 9430                            Ordering::Equal => {
 9431                                editor.select_all(&SelectAll, cx);
 9432                                return editor;
 9433                            }
 9434                            Ordering::Less => {
 9435                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9436                            }
 9437                            Ordering::Greater => {
 9438                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9439                            }
 9440                        };
 9441                        if rename_selection_range.end > old_name.len() {
 9442                            editor.select_all(&SelectAll, cx);
 9443                        } else {
 9444                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9445                                s.select_ranges([rename_selection_range]);
 9446                            });
 9447                        }
 9448                        editor
 9449                    });
 9450
 9451                    let write_highlights =
 9452                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9453                    let read_highlights =
 9454                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9455                    let ranges = write_highlights
 9456                        .iter()
 9457                        .flat_map(|(_, ranges)| ranges.iter())
 9458                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9459                        .cloned()
 9460                        .collect();
 9461
 9462                    this.highlight_text::<Rename>(
 9463                        ranges,
 9464                        HighlightStyle {
 9465                            fade_out: Some(0.6),
 9466                            ..Default::default()
 9467                        },
 9468                        cx,
 9469                    );
 9470                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9471                    cx.focus(&rename_focus_handle);
 9472                    let block_id = this.insert_blocks(
 9473                        [BlockProperties {
 9474                            style: BlockStyle::Flex,
 9475                            position: range.start,
 9476                            height: 1,
 9477                            render: Box::new({
 9478                                let rename_editor = rename_editor.clone();
 9479                                move |cx: &mut BlockContext| {
 9480                                    let mut text_style = cx.editor_style.text.clone();
 9481                                    if let Some(highlight_style) = old_highlight_id
 9482                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 9483                                    {
 9484                                        text_style = text_style.highlight(highlight_style);
 9485                                    }
 9486                                    div()
 9487                                        .pl(cx.anchor_x)
 9488                                        .child(EditorElement::new(
 9489                                            &rename_editor,
 9490                                            EditorStyle {
 9491                                                background: cx.theme().system().transparent,
 9492                                                local_player: cx.editor_style.local_player,
 9493                                                text: text_style,
 9494                                                scrollbar_width: cx.editor_style.scrollbar_width,
 9495                                                syntax: cx.editor_style.syntax.clone(),
 9496                                                status: cx.editor_style.status.clone(),
 9497                                                inlay_hints_style: HighlightStyle {
 9498                                                    color: Some(cx.theme().status().hint),
 9499                                                    font_weight: Some(FontWeight::BOLD),
 9500                                                    ..HighlightStyle::default()
 9501                                                },
 9502                                                suggestions_style: HighlightStyle {
 9503                                                    color: Some(cx.theme().status().predictive),
 9504                                                    ..HighlightStyle::default()
 9505                                                },
 9506                                            },
 9507                                        ))
 9508                                        .into_any_element()
 9509                                }
 9510                            }),
 9511                            disposition: BlockDisposition::Below,
 9512                        }],
 9513                        Some(Autoscroll::fit()),
 9514                        cx,
 9515                    )[0];
 9516                    this.pending_rename = Some(RenameState {
 9517                        range,
 9518                        old_name,
 9519                        editor: rename_editor,
 9520                        block_id,
 9521                    });
 9522                })?;
 9523            }
 9524
 9525            Ok(())
 9526        }))
 9527    }
 9528
 9529    pub fn confirm_rename(
 9530        &mut self,
 9531        _: &ConfirmRename,
 9532        cx: &mut ViewContext<Self>,
 9533    ) -> Option<Task<Result<()>>> {
 9534        let rename = self.take_rename(false, cx)?;
 9535        let workspace = self.workspace()?;
 9536        let (start_buffer, start) = self
 9537            .buffer
 9538            .read(cx)
 9539            .text_anchor_for_position(rename.range.start, cx)?;
 9540        let (end_buffer, end) = self
 9541            .buffer
 9542            .read(cx)
 9543            .text_anchor_for_position(rename.range.end, cx)?;
 9544        if start_buffer != end_buffer {
 9545            return None;
 9546        }
 9547
 9548        let buffer = start_buffer;
 9549        let range = start..end;
 9550        let old_name = rename.old_name;
 9551        let new_name = rename.editor.read(cx).text(cx);
 9552
 9553        let rename = workspace
 9554            .read(cx)
 9555            .project()
 9556            .clone()
 9557            .update(cx, |project, cx| {
 9558                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 9559            });
 9560        let workspace = workspace.downgrade();
 9561
 9562        Some(cx.spawn(|editor, mut cx| async move {
 9563            let project_transaction = rename.await?;
 9564            Self::open_project_transaction(
 9565                &editor,
 9566                workspace,
 9567                project_transaction,
 9568                format!("Rename: {}{}", old_name, new_name),
 9569                cx.clone(),
 9570            )
 9571            .await?;
 9572
 9573            editor.update(&mut cx, |editor, cx| {
 9574                editor.refresh_document_highlights(cx);
 9575            })?;
 9576            Ok(())
 9577        }))
 9578    }
 9579
 9580    fn take_rename(
 9581        &mut self,
 9582        moving_cursor: bool,
 9583        cx: &mut ViewContext<Self>,
 9584    ) -> Option<RenameState> {
 9585        let rename = self.pending_rename.take()?;
 9586        if rename.editor.focus_handle(cx).is_focused(cx) {
 9587            cx.focus(&self.focus_handle);
 9588        }
 9589
 9590        self.remove_blocks(
 9591            [rename.block_id].into_iter().collect(),
 9592            Some(Autoscroll::fit()),
 9593            cx,
 9594        );
 9595        self.clear_highlights::<Rename>(cx);
 9596        self.show_local_selections = true;
 9597
 9598        if moving_cursor {
 9599            let rename_editor = rename.editor.read(cx);
 9600            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 9601
 9602            // Update the selection to match the position of the selection inside
 9603            // the rename editor.
 9604            let snapshot = self.buffer.read(cx).read(cx);
 9605            let rename_range = rename.range.to_offset(&snapshot);
 9606            let cursor_in_editor = snapshot
 9607                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 9608                .min(rename_range.end);
 9609            drop(snapshot);
 9610
 9611            self.change_selections(None, cx, |s| {
 9612                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 9613            });
 9614        } else {
 9615            self.refresh_document_highlights(cx);
 9616        }
 9617
 9618        Some(rename)
 9619    }
 9620
 9621    pub fn pending_rename(&self) -> Option<&RenameState> {
 9622        self.pending_rename.as_ref()
 9623    }
 9624
 9625    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9626        let project = match &self.project {
 9627            Some(project) => project.clone(),
 9628            None => return None,
 9629        };
 9630
 9631        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 9632    }
 9633
 9634    fn perform_format(
 9635        &mut self,
 9636        project: Model<Project>,
 9637        trigger: FormatTrigger,
 9638        cx: &mut ViewContext<Self>,
 9639    ) -> Task<Result<()>> {
 9640        let buffer = self.buffer().clone();
 9641        let mut buffers = buffer.read(cx).all_buffers();
 9642        if trigger == FormatTrigger::Save {
 9643            buffers.retain(|buffer| buffer.read(cx).is_dirty());
 9644        }
 9645
 9646        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 9647        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 9648
 9649        cx.spawn(|_, mut cx| async move {
 9650            let transaction = futures::select_biased! {
 9651                () = timeout => {
 9652                    log::warn!("timed out waiting for formatting");
 9653                    None
 9654                }
 9655                transaction = format.log_err().fuse() => transaction,
 9656            };
 9657
 9658            buffer
 9659                .update(&mut cx, |buffer, cx| {
 9660                    if let Some(transaction) = transaction {
 9661                        if !buffer.is_singleton() {
 9662                            buffer.push_transaction(&transaction.0, cx);
 9663                        }
 9664                    }
 9665
 9666                    cx.notify();
 9667                })
 9668                .ok();
 9669
 9670            Ok(())
 9671        })
 9672    }
 9673
 9674    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
 9675        if let Some(project) = self.project.clone() {
 9676            self.buffer.update(cx, |multi_buffer, cx| {
 9677                project.update(cx, |project, cx| {
 9678                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
 9679                });
 9680            })
 9681        }
 9682    }
 9683
 9684    fn cancel_language_server_work(
 9685        &mut self,
 9686        _: &CancelLanguageServerWork,
 9687        cx: &mut ViewContext<Self>,
 9688    ) {
 9689        if let Some(project) = self.project.clone() {
 9690            self.buffer.update(cx, |multi_buffer, cx| {
 9691                project.update(cx, |project, cx| {
 9692                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
 9693                });
 9694            })
 9695        }
 9696    }
 9697
 9698    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 9699        cx.show_character_palette();
 9700    }
 9701
 9702    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
 9703        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
 9704            let buffer = self.buffer.read(cx).snapshot(cx);
 9705            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
 9706            let is_valid = buffer
 9707                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
 9708                .any(|entry| {
 9709                    entry.diagnostic.is_primary
 9710                        && !entry.range.is_empty()
 9711                        && entry.range.start == primary_range_start
 9712                        && entry.diagnostic.message == active_diagnostics.primary_message
 9713                });
 9714
 9715            if is_valid != active_diagnostics.is_valid {
 9716                active_diagnostics.is_valid = is_valid;
 9717                let mut new_styles = HashMap::default();
 9718                for (block_id, diagnostic) in &active_diagnostics.blocks {
 9719                    new_styles.insert(
 9720                        *block_id,
 9721                        (
 9722                            None,
 9723                            diagnostic_block_renderer(diagnostic.clone(), is_valid),
 9724                        ),
 9725                    );
 9726                }
 9727                self.display_map.update(cx, |display_map, cx| {
 9728                    display_map.replace_blocks(new_styles, cx)
 9729                });
 9730            }
 9731        }
 9732    }
 9733
 9734    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
 9735        self.dismiss_diagnostics(cx);
 9736        let snapshot = self.snapshot(cx);
 9737        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
 9738            let buffer = self.buffer.read(cx).snapshot(cx);
 9739
 9740            let mut primary_range = None;
 9741            let mut primary_message = None;
 9742            let mut group_end = Point::zero();
 9743            let diagnostic_group = buffer
 9744                .diagnostic_group::<MultiBufferPoint>(group_id)
 9745                .filter_map(|entry| {
 9746                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
 9747                        && (entry.range.start.row == entry.range.end.row
 9748                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
 9749                    {
 9750                        return None;
 9751                    }
 9752                    if entry.range.end > group_end {
 9753                        group_end = entry.range.end;
 9754                    }
 9755                    if entry.diagnostic.is_primary {
 9756                        primary_range = Some(entry.range.clone());
 9757                        primary_message = Some(entry.diagnostic.message.clone());
 9758                    }
 9759                    Some(entry)
 9760                })
 9761                .collect::<Vec<_>>();
 9762            let primary_range = primary_range?;
 9763            let primary_message = primary_message?;
 9764            let primary_range =
 9765                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
 9766
 9767            let blocks = display_map
 9768                .insert_blocks(
 9769                    diagnostic_group.iter().map(|entry| {
 9770                        let diagnostic = entry.diagnostic.clone();
 9771                        let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
 9772                        BlockProperties {
 9773                            style: BlockStyle::Fixed,
 9774                            position: buffer.anchor_after(entry.range.start),
 9775                            height: message_height,
 9776                            render: diagnostic_block_renderer(diagnostic, true),
 9777                            disposition: BlockDisposition::Below,
 9778                        }
 9779                    }),
 9780                    cx,
 9781                )
 9782                .into_iter()
 9783                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
 9784                .collect();
 9785
 9786            Some(ActiveDiagnosticGroup {
 9787                primary_range,
 9788                primary_message,
 9789                group_id,
 9790                blocks,
 9791                is_valid: true,
 9792            })
 9793        });
 9794        self.active_diagnostics.is_some()
 9795    }
 9796
 9797    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
 9798        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
 9799            self.display_map.update(cx, |display_map, cx| {
 9800                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
 9801            });
 9802            cx.notify();
 9803        }
 9804    }
 9805
 9806    pub fn set_selections_from_remote(
 9807        &mut self,
 9808        selections: Vec<Selection<Anchor>>,
 9809        pending_selection: Option<Selection<Anchor>>,
 9810        cx: &mut ViewContext<Self>,
 9811    ) {
 9812        let old_cursor_position = self.selections.newest_anchor().head();
 9813        self.selections.change_with(cx, |s| {
 9814            s.select_anchors(selections);
 9815            if let Some(pending_selection) = pending_selection {
 9816                s.set_pending(pending_selection, SelectMode::Character);
 9817            } else {
 9818                s.clear_pending();
 9819            }
 9820        });
 9821        self.selections_did_change(false, &old_cursor_position, true, cx);
 9822    }
 9823
 9824    fn push_to_selection_history(&mut self) {
 9825        self.selection_history.push(SelectionHistoryEntry {
 9826            selections: self.selections.disjoint_anchors(),
 9827            select_next_state: self.select_next_state.clone(),
 9828            select_prev_state: self.select_prev_state.clone(),
 9829            add_selections_state: self.add_selections_state.clone(),
 9830        });
 9831    }
 9832
 9833    pub fn transact(
 9834        &mut self,
 9835        cx: &mut ViewContext<Self>,
 9836        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
 9837    ) -> Option<TransactionId> {
 9838        self.start_transaction_at(Instant::now(), cx);
 9839        update(self, cx);
 9840        self.end_transaction_at(Instant::now(), cx)
 9841    }
 9842
 9843    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
 9844        self.end_selection(cx);
 9845        if let Some(tx_id) = self
 9846            .buffer
 9847            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
 9848        {
 9849            self.selection_history
 9850                .insert_transaction(tx_id, self.selections.disjoint_anchors());
 9851            cx.emit(EditorEvent::TransactionBegun {
 9852                transaction_id: tx_id,
 9853            })
 9854        }
 9855    }
 9856
 9857    fn end_transaction_at(
 9858        &mut self,
 9859        now: Instant,
 9860        cx: &mut ViewContext<Self>,
 9861    ) -> Option<TransactionId> {
 9862        if let Some(transaction_id) = self
 9863            .buffer
 9864            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 9865        {
 9866            if let Some((_, end_selections)) =
 9867                self.selection_history.transaction_mut(transaction_id)
 9868            {
 9869                *end_selections = Some(self.selections.disjoint_anchors());
 9870            } else {
 9871                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
 9872            }
 9873
 9874            cx.emit(EditorEvent::Edited { transaction_id });
 9875            Some(transaction_id)
 9876        } else {
 9877            None
 9878        }
 9879    }
 9880
 9881    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
 9882        let mut fold_ranges = Vec::new();
 9883
 9884        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9885
 9886        let selections = self.selections.all_adjusted(cx);
 9887        for selection in selections {
 9888            let range = selection.range().sorted();
 9889            let buffer_start_row = range.start.row;
 9890
 9891            for row in (0..=range.end.row).rev() {
 9892                if let Some((foldable_range, fold_text)) =
 9893                    display_map.foldable_range(MultiBufferRow(row))
 9894                {
 9895                    if foldable_range.end.row >= buffer_start_row {
 9896                        fold_ranges.push((foldable_range, fold_text));
 9897                        if row <= range.start.row {
 9898                            break;
 9899                        }
 9900                    }
 9901                }
 9902            }
 9903        }
 9904
 9905        self.fold_ranges(fold_ranges, true, cx);
 9906    }
 9907
 9908    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
 9909        let buffer_row = fold_at.buffer_row;
 9910        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9911
 9912        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
 9913            let autoscroll = self
 9914                .selections
 9915                .all::<Point>(cx)
 9916                .iter()
 9917                .any(|selection| fold_range.overlaps(&selection.range()));
 9918
 9919            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
 9920        }
 9921    }
 9922
 9923    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
 9924        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9925        let buffer = &display_map.buffer_snapshot;
 9926        let selections = self.selections.all::<Point>(cx);
 9927        let ranges = selections
 9928            .iter()
 9929            .map(|s| {
 9930                let range = s.display_range(&display_map).sorted();
 9931                let mut start = range.start.to_point(&display_map);
 9932                let mut end = range.end.to_point(&display_map);
 9933                start.column = 0;
 9934                end.column = buffer.line_len(MultiBufferRow(end.row));
 9935                start..end
 9936            })
 9937            .collect::<Vec<_>>();
 9938
 9939        self.unfold_ranges(ranges, true, true, cx);
 9940    }
 9941
 9942    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
 9943        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9944
 9945        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
 9946            ..Point::new(
 9947                unfold_at.buffer_row.0,
 9948                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
 9949            );
 9950
 9951        let autoscroll = self
 9952            .selections
 9953            .all::<Point>(cx)
 9954            .iter()
 9955            .any(|selection| selection.range().overlaps(&intersection_range));
 9956
 9957        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
 9958    }
 9959
 9960    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
 9961        let selections = self.selections.all::<Point>(cx);
 9962        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9963        let line_mode = self.selections.line_mode;
 9964        let ranges = selections.into_iter().map(|s| {
 9965            if line_mode {
 9966                let start = Point::new(s.start.row, 0);
 9967                let end = Point::new(
 9968                    s.end.row,
 9969                    display_map
 9970                        .buffer_snapshot
 9971                        .line_len(MultiBufferRow(s.end.row)),
 9972                );
 9973                (start..end, display_map.fold_placeholder.clone())
 9974            } else {
 9975                (s.start..s.end, display_map.fold_placeholder.clone())
 9976            }
 9977        });
 9978        self.fold_ranges(ranges, true, cx);
 9979    }
 9980
 9981    pub fn fold_ranges<T: ToOffset + Clone>(
 9982        &mut self,
 9983        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
 9984        auto_scroll: bool,
 9985        cx: &mut ViewContext<Self>,
 9986    ) {
 9987        let mut fold_ranges = Vec::new();
 9988        let mut buffers_affected = HashMap::default();
 9989        let multi_buffer = self.buffer().read(cx);
 9990        for (fold_range, fold_text) in ranges {
 9991            if let Some((_, buffer, _)) =
 9992                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
 9993            {
 9994                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
 9995            };
 9996            fold_ranges.push((fold_range, fold_text));
 9997        }
 9998
 9999        let mut ranges = fold_ranges.into_iter().peekable();
10000        if ranges.peek().is_some() {
10001            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10002
10003            if auto_scroll {
10004                self.request_autoscroll(Autoscroll::fit(), cx);
10005            }
10006
10007            for buffer in buffers_affected.into_values() {
10008                self.sync_expanded_diff_hunks(buffer, cx);
10009            }
10010
10011            cx.notify();
10012
10013            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10014                // Clear diagnostics block when folding a range that contains it.
10015                let snapshot = self.snapshot(cx);
10016                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10017                    drop(snapshot);
10018                    self.active_diagnostics = Some(active_diagnostics);
10019                    self.dismiss_diagnostics(cx);
10020                } else {
10021                    self.active_diagnostics = Some(active_diagnostics);
10022                }
10023            }
10024
10025            self.scrollbar_marker_state.dirty = true;
10026        }
10027    }
10028
10029    pub fn unfold_ranges<T: ToOffset + Clone>(
10030        &mut self,
10031        ranges: impl IntoIterator<Item = Range<T>>,
10032        inclusive: bool,
10033        auto_scroll: bool,
10034        cx: &mut ViewContext<Self>,
10035    ) {
10036        let mut unfold_ranges = Vec::new();
10037        let mut buffers_affected = HashMap::default();
10038        let multi_buffer = self.buffer().read(cx);
10039        for range in ranges {
10040            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10041                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10042            };
10043            unfold_ranges.push(range);
10044        }
10045
10046        let mut ranges = unfold_ranges.into_iter().peekable();
10047        if ranges.peek().is_some() {
10048            self.display_map
10049                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10050            if auto_scroll {
10051                self.request_autoscroll(Autoscroll::fit(), cx);
10052            }
10053
10054            for buffer in buffers_affected.into_values() {
10055                self.sync_expanded_diff_hunks(buffer, cx);
10056            }
10057
10058            cx.notify();
10059            self.scrollbar_marker_state.dirty = true;
10060            self.active_indent_guides_state.dirty = true;
10061        }
10062    }
10063
10064    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10065        if hovered != self.gutter_hovered {
10066            self.gutter_hovered = hovered;
10067            cx.notify();
10068        }
10069    }
10070
10071    pub fn insert_blocks(
10072        &mut self,
10073        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10074        autoscroll: Option<Autoscroll>,
10075        cx: &mut ViewContext<Self>,
10076    ) -> Vec<BlockId> {
10077        let blocks = self
10078            .display_map
10079            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10080        if let Some(autoscroll) = autoscroll {
10081            self.request_autoscroll(autoscroll, cx);
10082        }
10083        blocks
10084    }
10085
10086    pub fn replace_blocks(
10087        &mut self,
10088        blocks: HashMap<BlockId, (Option<u8>, RenderBlock)>,
10089        autoscroll: Option<Autoscroll>,
10090        cx: &mut ViewContext<Self>,
10091    ) {
10092        self.display_map
10093            .update(cx, |display_map, cx| display_map.replace_blocks(blocks, cx));
10094        if let Some(autoscroll) = autoscroll {
10095            self.request_autoscroll(autoscroll, cx);
10096        }
10097    }
10098
10099    pub fn remove_blocks(
10100        &mut self,
10101        block_ids: HashSet<BlockId>,
10102        autoscroll: Option<Autoscroll>,
10103        cx: &mut ViewContext<Self>,
10104    ) {
10105        self.display_map.update(cx, |display_map, cx| {
10106            display_map.remove_blocks(block_ids, cx)
10107        });
10108        if let Some(autoscroll) = autoscroll {
10109            self.request_autoscroll(autoscroll, cx);
10110        }
10111    }
10112
10113    pub fn row_for_block(
10114        &self,
10115        block_id: BlockId,
10116        cx: &mut ViewContext<Self>,
10117    ) -> Option<DisplayRow> {
10118        self.display_map
10119            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10120    }
10121
10122    pub fn insert_creases(
10123        &mut self,
10124        creases: impl IntoIterator<Item = Crease>,
10125        cx: &mut ViewContext<Self>,
10126    ) -> Vec<CreaseId> {
10127        self.display_map
10128            .update(cx, |map, cx| map.insert_creases(creases, cx))
10129    }
10130
10131    pub fn remove_creases(
10132        &mut self,
10133        ids: impl IntoIterator<Item = CreaseId>,
10134        cx: &mut ViewContext<Self>,
10135    ) {
10136        self.display_map
10137            .update(cx, |map, cx| map.remove_creases(ids, cx));
10138    }
10139
10140    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10141        self.display_map
10142            .update(cx, |map, cx| map.snapshot(cx))
10143            .longest_row()
10144    }
10145
10146    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10147        self.display_map
10148            .update(cx, |map, cx| map.snapshot(cx))
10149            .max_point()
10150    }
10151
10152    pub fn text(&self, cx: &AppContext) -> String {
10153        self.buffer.read(cx).read(cx).text()
10154    }
10155
10156    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10157        let text = self.text(cx);
10158        let text = text.trim();
10159
10160        if text.is_empty() {
10161            return None;
10162        }
10163
10164        Some(text.to_string())
10165    }
10166
10167    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10168        self.transact(cx, |this, cx| {
10169            this.buffer
10170                .read(cx)
10171                .as_singleton()
10172                .expect("you can only call set_text on editors for singleton buffers")
10173                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10174        });
10175    }
10176
10177    pub fn display_text(&self, cx: &mut AppContext) -> String {
10178        self.display_map
10179            .update(cx, |map, cx| map.snapshot(cx))
10180            .text()
10181    }
10182
10183    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10184        let mut wrap_guides = smallvec::smallvec![];
10185
10186        if self.show_wrap_guides == Some(false) {
10187            return wrap_guides;
10188        }
10189
10190        let settings = self.buffer.read(cx).settings_at(0, cx);
10191        if settings.show_wrap_guides {
10192            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10193                wrap_guides.push((soft_wrap as usize, true));
10194            }
10195            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10196        }
10197
10198        wrap_guides
10199    }
10200
10201    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10202        let settings = self.buffer.read(cx).settings_at(0, cx);
10203        let mode = self
10204            .soft_wrap_mode_override
10205            .unwrap_or_else(|| settings.soft_wrap);
10206        match mode {
10207            language_settings::SoftWrap::None => SoftWrap::None,
10208            language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10209            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10210            language_settings::SoftWrap::PreferredLineLength => {
10211                SoftWrap::Column(settings.preferred_line_length)
10212            }
10213        }
10214    }
10215
10216    pub fn set_soft_wrap_mode(
10217        &mut self,
10218        mode: language_settings::SoftWrap,
10219        cx: &mut ViewContext<Self>,
10220    ) {
10221        self.soft_wrap_mode_override = Some(mode);
10222        cx.notify();
10223    }
10224
10225    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10226        let rem_size = cx.rem_size();
10227        self.display_map.update(cx, |map, cx| {
10228            map.set_font(
10229                style.text.font(),
10230                style.text.font_size.to_pixels(rem_size),
10231                cx,
10232            )
10233        });
10234        self.style = Some(style);
10235    }
10236
10237    pub fn style(&self) -> Option<&EditorStyle> {
10238        self.style.as_ref()
10239    }
10240
10241    // Called by the element. This method is not designed to be called outside of the editor
10242    // element's layout code because it does not notify when rewrapping is computed synchronously.
10243    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10244        self.display_map
10245            .update(cx, |map, cx| map.set_wrap_width(width, cx))
10246    }
10247
10248    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10249        if self.soft_wrap_mode_override.is_some() {
10250            self.soft_wrap_mode_override.take();
10251        } else {
10252            let soft_wrap = match self.soft_wrap_mode(cx) {
10253                SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10254                SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10255                    language_settings::SoftWrap::PreferLine
10256                }
10257            };
10258            self.soft_wrap_mode_override = Some(soft_wrap);
10259        }
10260        cx.notify();
10261    }
10262
10263    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10264        let Some(workspace) = self.workspace() else {
10265            return;
10266        };
10267        let fs = workspace.read(cx).app_state().fs.clone();
10268        let current_show = TabBarSettings::get_global(cx).show;
10269        update_settings_file::<TabBarSettings>(fs, cx, move |setting| {
10270            setting.show = Some(!current_show);
10271        });
10272    }
10273
10274    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10275        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10276            self.buffer
10277                .read(cx)
10278                .settings_at(0, cx)
10279                .indent_guides
10280                .enabled
10281        });
10282        self.show_indent_guides = Some(!currently_enabled);
10283        cx.notify();
10284    }
10285
10286    fn should_show_indent_guides(&self) -> Option<bool> {
10287        self.show_indent_guides
10288    }
10289
10290    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10291        let mut editor_settings = EditorSettings::get_global(cx).clone();
10292        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10293        EditorSettings::override_global(editor_settings, cx);
10294    }
10295
10296    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10297        self.show_gutter = show_gutter;
10298        cx.notify();
10299    }
10300
10301    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10302        self.show_line_numbers = Some(show_line_numbers);
10303        cx.notify();
10304    }
10305
10306    pub fn set_show_git_diff_gutter(
10307        &mut self,
10308        show_git_diff_gutter: bool,
10309        cx: &mut ViewContext<Self>,
10310    ) {
10311        self.show_git_diff_gutter = Some(show_git_diff_gutter);
10312        cx.notify();
10313    }
10314
10315    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10316        self.show_code_actions = Some(show_code_actions);
10317        cx.notify();
10318    }
10319
10320    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10321        self.show_runnables = Some(show_runnables);
10322        cx.notify();
10323    }
10324
10325    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10326        self.show_wrap_guides = Some(show_wrap_guides);
10327        cx.notify();
10328    }
10329
10330    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10331        self.show_indent_guides = Some(show_indent_guides);
10332        cx.notify();
10333    }
10334
10335    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10336        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10337            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10338                cx.reveal_path(&file.abs_path(cx));
10339            }
10340        }
10341    }
10342
10343    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10344        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10345            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10346                if let Some(path) = file.abs_path(cx).to_str() {
10347                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10348                }
10349            }
10350        }
10351    }
10352
10353    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10354        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10355            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10356                if let Some(path) = file.path().to_str() {
10357                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10358                }
10359            }
10360        }
10361    }
10362
10363    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10364        self.show_git_blame_gutter = !self.show_git_blame_gutter;
10365
10366        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10367            self.start_git_blame(true, cx);
10368        }
10369
10370        cx.notify();
10371    }
10372
10373    pub fn toggle_git_blame_inline(
10374        &mut self,
10375        _: &ToggleGitBlameInline,
10376        cx: &mut ViewContext<Self>,
10377    ) {
10378        self.toggle_git_blame_inline_internal(true, cx);
10379        cx.notify();
10380    }
10381
10382    pub fn git_blame_inline_enabled(&self) -> bool {
10383        self.git_blame_inline_enabled
10384    }
10385
10386    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10387        self.show_selection_menu = self
10388            .show_selection_menu
10389            .map(|show_selections_menu| !show_selections_menu)
10390            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10391
10392        cx.notify();
10393    }
10394
10395    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10396        self.show_selection_menu
10397            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10398    }
10399
10400    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10401        if let Some(project) = self.project.as_ref() {
10402            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10403                return;
10404            };
10405
10406            if buffer.read(cx).file().is_none() {
10407                return;
10408            }
10409
10410            let focused = self.focus_handle(cx).contains_focused(cx);
10411
10412            let project = project.clone();
10413            let blame =
10414                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10415            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10416            self.blame = Some(blame);
10417        }
10418    }
10419
10420    fn toggle_git_blame_inline_internal(
10421        &mut self,
10422        user_triggered: bool,
10423        cx: &mut ViewContext<Self>,
10424    ) {
10425        if self.git_blame_inline_enabled {
10426            self.git_blame_inline_enabled = false;
10427            self.show_git_blame_inline = false;
10428            self.show_git_blame_inline_delay_task.take();
10429        } else {
10430            self.git_blame_inline_enabled = true;
10431            self.start_git_blame_inline(user_triggered, cx);
10432        }
10433
10434        cx.notify();
10435    }
10436
10437    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10438        self.start_git_blame(user_triggered, cx);
10439
10440        if ProjectSettings::get_global(cx)
10441            .git
10442            .inline_blame_delay()
10443            .is_some()
10444        {
10445            self.start_inline_blame_timer(cx);
10446        } else {
10447            self.show_git_blame_inline = true
10448        }
10449    }
10450
10451    pub fn blame(&self) -> Option<&Model<GitBlame>> {
10452        self.blame.as_ref()
10453    }
10454
10455    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10456        self.show_git_blame_gutter && self.has_blame_entries(cx)
10457    }
10458
10459    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10460        self.show_git_blame_inline
10461            && self.focus_handle.is_focused(cx)
10462            && !self.newest_selection_head_on_empty_line(cx)
10463            && self.has_blame_entries(cx)
10464    }
10465
10466    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10467        self.blame()
10468            .map_or(false, |blame| blame.read(cx).has_generated_entries())
10469    }
10470
10471    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10472        let cursor_anchor = self.selections.newest_anchor().head();
10473
10474        let snapshot = self.buffer.read(cx).snapshot(cx);
10475        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10476
10477        snapshot.line_len(buffer_row) == 0
10478    }
10479
10480    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10481        let (path, selection, repo) = maybe!({
10482            let project_handle = self.project.as_ref()?.clone();
10483            let project = project_handle.read(cx);
10484
10485            let selection = self.selections.newest::<Point>(cx);
10486            let selection_range = selection.range();
10487
10488            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10489                (buffer, selection_range.start.row..selection_range.end.row)
10490            } else {
10491                let buffer_ranges = self
10492                    .buffer()
10493                    .read(cx)
10494                    .range_to_buffer_ranges(selection_range, cx);
10495
10496                let (buffer, range, _) = if selection.reversed {
10497                    buffer_ranges.first()
10498                } else {
10499                    buffer_ranges.last()
10500                }?;
10501
10502                let snapshot = buffer.read(cx).snapshot();
10503                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10504                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
10505                (buffer.clone(), selection)
10506            };
10507
10508            let path = buffer
10509                .read(cx)
10510                .file()?
10511                .as_local()?
10512                .path()
10513                .to_str()?
10514                .to_string();
10515            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10516            Some((path, selection, repo))
10517        })
10518        .ok_or_else(|| anyhow!("unable to open git repository"))?;
10519
10520        const REMOTE_NAME: &str = "origin";
10521        let origin_url = repo
10522            .remote_url(REMOTE_NAME)
10523            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10524        let sha = repo
10525            .head_sha()
10526            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10527
10528        let (provider, remote) =
10529            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10530                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10531
10532        Ok(provider.build_permalink(
10533            remote,
10534            BuildPermalinkParams {
10535                sha: &sha,
10536                path: &path,
10537                selection: Some(selection),
10538            },
10539        ))
10540    }
10541
10542    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10543        let permalink = self.get_permalink_to_line(cx);
10544
10545        match permalink {
10546            Ok(permalink) => {
10547                cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
10548            }
10549            Err(err) => {
10550                let message = format!("Failed to copy permalink: {err}");
10551
10552                Err::<(), anyhow::Error>(err).log_err();
10553
10554                if let Some(workspace) = self.workspace() {
10555                    workspace.update(cx, |workspace, cx| {
10556                        struct CopyPermalinkToLine;
10557
10558                        workspace.show_toast(
10559                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10560                            cx,
10561                        )
10562                    })
10563                }
10564            }
10565        }
10566    }
10567
10568    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10569        let permalink = self.get_permalink_to_line(cx);
10570
10571        match permalink {
10572            Ok(permalink) => {
10573                cx.open_url(permalink.as_ref());
10574            }
10575            Err(err) => {
10576                let message = format!("Failed to open permalink: {err}");
10577
10578                Err::<(), anyhow::Error>(err).log_err();
10579
10580                if let Some(workspace) = self.workspace() {
10581                    workspace.update(cx, |workspace, cx| {
10582                        struct OpenPermalinkToLine;
10583
10584                        workspace.show_toast(
10585                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10586                            cx,
10587                        )
10588                    })
10589                }
10590            }
10591        }
10592    }
10593
10594    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10595    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10596    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10597    pub fn highlight_rows<T: 'static>(
10598        &mut self,
10599        rows: RangeInclusive<Anchor>,
10600        color: Option<Hsla>,
10601        should_autoscroll: bool,
10602        cx: &mut ViewContext<Self>,
10603    ) {
10604        let snapshot = self.buffer().read(cx).snapshot(cx);
10605        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10606        let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10607            highlight
10608                .range
10609                .start()
10610                .cmp(&rows.start(), &snapshot)
10611                .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10612        });
10613        match (color, existing_highlight_index) {
10614            (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10615                ix,
10616                RowHighlight {
10617                    index: post_inc(&mut self.highlight_order),
10618                    range: rows,
10619                    should_autoscroll,
10620                    color,
10621                },
10622            ),
10623            (None, Ok(i)) => {
10624                row_highlights.remove(i);
10625            }
10626        }
10627    }
10628
10629    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10630    pub fn clear_row_highlights<T: 'static>(&mut self) {
10631        self.highlighted_rows.remove(&TypeId::of::<T>());
10632    }
10633
10634    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10635    pub fn highlighted_rows<T: 'static>(
10636        &self,
10637    ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10638        Some(
10639            self.highlighted_rows
10640                .get(&TypeId::of::<T>())?
10641                .iter()
10642                .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10643        )
10644    }
10645
10646    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10647    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10648    /// Allows to ignore certain kinds of highlights.
10649    pub fn highlighted_display_rows(
10650        &mut self,
10651        cx: &mut WindowContext,
10652    ) -> BTreeMap<DisplayRow, Hsla> {
10653        let snapshot = self.snapshot(cx);
10654        let mut used_highlight_orders = HashMap::default();
10655        self.highlighted_rows
10656            .iter()
10657            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10658            .fold(
10659                BTreeMap::<DisplayRow, Hsla>::new(),
10660                |mut unique_rows, highlight| {
10661                    let start_row = highlight.range.start().to_display_point(&snapshot).row();
10662                    let end_row = highlight.range.end().to_display_point(&snapshot).row();
10663                    for row in start_row.0..=end_row.0 {
10664                        let used_index =
10665                            used_highlight_orders.entry(row).or_insert(highlight.index);
10666                        if highlight.index >= *used_index {
10667                            *used_index = highlight.index;
10668                            match highlight.color {
10669                                Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10670                                None => unique_rows.remove(&DisplayRow(row)),
10671                            };
10672                        }
10673                    }
10674                    unique_rows
10675                },
10676            )
10677    }
10678
10679    pub fn highlighted_display_row_for_autoscroll(
10680        &self,
10681        snapshot: &DisplaySnapshot,
10682    ) -> Option<DisplayRow> {
10683        self.highlighted_rows
10684            .values()
10685            .flat_map(|highlighted_rows| highlighted_rows.iter())
10686            .filter_map(|highlight| {
10687                if highlight.color.is_none() || !highlight.should_autoscroll {
10688                    return None;
10689                }
10690                Some(highlight.range.start().to_display_point(&snapshot).row())
10691            })
10692            .min()
10693    }
10694
10695    pub fn set_search_within_ranges(
10696        &mut self,
10697        ranges: &[Range<Anchor>],
10698        cx: &mut ViewContext<Self>,
10699    ) {
10700        self.highlight_background::<SearchWithinRange>(
10701            ranges,
10702            |colors| colors.editor_document_highlight_read_background,
10703            cx,
10704        )
10705    }
10706
10707    pub fn set_breadcrumb_header(&mut self, new_header: String) {
10708        self.breadcrumb_header = Some(new_header);
10709    }
10710
10711    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10712        self.clear_background_highlights::<SearchWithinRange>(cx);
10713    }
10714
10715    pub fn highlight_background<T: 'static>(
10716        &mut self,
10717        ranges: &[Range<Anchor>],
10718        color_fetcher: fn(&ThemeColors) -> Hsla,
10719        cx: &mut ViewContext<Self>,
10720    ) {
10721        let snapshot = self.snapshot(cx);
10722        // this is to try and catch a panic sooner
10723        for range in ranges {
10724            snapshot
10725                .buffer_snapshot
10726                .summary_for_anchor::<usize>(&range.start);
10727            snapshot
10728                .buffer_snapshot
10729                .summary_for_anchor::<usize>(&range.end);
10730        }
10731
10732        self.background_highlights
10733            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10734        self.scrollbar_marker_state.dirty = true;
10735        cx.notify();
10736    }
10737
10738    pub fn clear_background_highlights<T: 'static>(
10739        &mut self,
10740        cx: &mut ViewContext<Self>,
10741    ) -> Option<BackgroundHighlight> {
10742        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10743        if !text_highlights.1.is_empty() {
10744            self.scrollbar_marker_state.dirty = true;
10745            cx.notify();
10746        }
10747        Some(text_highlights)
10748    }
10749
10750    pub fn highlight_gutter<T: 'static>(
10751        &mut self,
10752        ranges: &[Range<Anchor>],
10753        color_fetcher: fn(&AppContext) -> Hsla,
10754        cx: &mut ViewContext<Self>,
10755    ) {
10756        self.gutter_highlights
10757            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10758        cx.notify();
10759    }
10760
10761    pub fn clear_gutter_highlights<T: 'static>(
10762        &mut self,
10763        cx: &mut ViewContext<Self>,
10764    ) -> Option<GutterHighlight> {
10765        cx.notify();
10766        self.gutter_highlights.remove(&TypeId::of::<T>())
10767    }
10768
10769    #[cfg(feature = "test-support")]
10770    pub fn all_text_background_highlights(
10771        &mut self,
10772        cx: &mut ViewContext<Self>,
10773    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10774        let snapshot = self.snapshot(cx);
10775        let buffer = &snapshot.buffer_snapshot;
10776        let start = buffer.anchor_before(0);
10777        let end = buffer.anchor_after(buffer.len());
10778        let theme = cx.theme().colors();
10779        self.background_highlights_in_range(start..end, &snapshot, theme)
10780    }
10781
10782    #[cfg(feature = "test-support")]
10783    pub fn search_background_highlights(
10784        &mut self,
10785        cx: &mut ViewContext<Self>,
10786    ) -> Vec<Range<Point>> {
10787        let snapshot = self.buffer().read(cx).snapshot(cx);
10788
10789        let highlights = self
10790            .background_highlights
10791            .get(&TypeId::of::<items::BufferSearchHighlights>());
10792
10793        if let Some((_color, ranges)) = highlights {
10794            ranges
10795                .iter()
10796                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
10797                .collect_vec()
10798        } else {
10799            vec![]
10800        }
10801    }
10802
10803    fn document_highlights_for_position<'a>(
10804        &'a self,
10805        position: Anchor,
10806        buffer: &'a MultiBufferSnapshot,
10807    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
10808        let read_highlights = self
10809            .background_highlights
10810            .get(&TypeId::of::<DocumentHighlightRead>())
10811            .map(|h| &h.1);
10812        let write_highlights = self
10813            .background_highlights
10814            .get(&TypeId::of::<DocumentHighlightWrite>())
10815            .map(|h| &h.1);
10816        let left_position = position.bias_left(buffer);
10817        let right_position = position.bias_right(buffer);
10818        read_highlights
10819            .into_iter()
10820            .chain(write_highlights)
10821            .flat_map(move |ranges| {
10822                let start_ix = match ranges.binary_search_by(|probe| {
10823                    let cmp = probe.end.cmp(&left_position, buffer);
10824                    if cmp.is_ge() {
10825                        Ordering::Greater
10826                    } else {
10827                        Ordering::Less
10828                    }
10829                }) {
10830                    Ok(i) | Err(i) => i,
10831                };
10832
10833                ranges[start_ix..]
10834                    .iter()
10835                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
10836            })
10837    }
10838
10839    pub fn has_background_highlights<T: 'static>(&self) -> bool {
10840        self.background_highlights
10841            .get(&TypeId::of::<T>())
10842            .map_or(false, |(_, highlights)| !highlights.is_empty())
10843    }
10844
10845    pub fn background_highlights_in_range(
10846        &self,
10847        search_range: Range<Anchor>,
10848        display_snapshot: &DisplaySnapshot,
10849        theme: &ThemeColors,
10850    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10851        let mut results = Vec::new();
10852        for (color_fetcher, ranges) in self.background_highlights.values() {
10853            let color = color_fetcher(theme);
10854            let start_ix = match ranges.binary_search_by(|probe| {
10855                let cmp = probe
10856                    .end
10857                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10858                if cmp.is_gt() {
10859                    Ordering::Greater
10860                } else {
10861                    Ordering::Less
10862                }
10863            }) {
10864                Ok(i) | Err(i) => i,
10865            };
10866            for range in &ranges[start_ix..] {
10867                if range
10868                    .start
10869                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10870                    .is_ge()
10871                {
10872                    break;
10873                }
10874
10875                let start = range.start.to_display_point(&display_snapshot);
10876                let end = range.end.to_display_point(&display_snapshot);
10877                results.push((start..end, color))
10878            }
10879        }
10880        results
10881    }
10882
10883    pub fn background_highlight_row_ranges<T: 'static>(
10884        &self,
10885        search_range: Range<Anchor>,
10886        display_snapshot: &DisplaySnapshot,
10887        count: usize,
10888    ) -> Vec<RangeInclusive<DisplayPoint>> {
10889        let mut results = Vec::new();
10890        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
10891            return vec![];
10892        };
10893
10894        let start_ix = match ranges.binary_search_by(|probe| {
10895            let cmp = probe
10896                .end
10897                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10898            if cmp.is_gt() {
10899                Ordering::Greater
10900            } else {
10901                Ordering::Less
10902            }
10903        }) {
10904            Ok(i) | Err(i) => i,
10905        };
10906        let mut push_region = |start: Option<Point>, end: Option<Point>| {
10907            if let (Some(start_display), Some(end_display)) = (start, end) {
10908                results.push(
10909                    start_display.to_display_point(display_snapshot)
10910                        ..=end_display.to_display_point(display_snapshot),
10911                );
10912            }
10913        };
10914        let mut start_row: Option<Point> = None;
10915        let mut end_row: Option<Point> = None;
10916        if ranges.len() > count {
10917            return Vec::new();
10918        }
10919        for range in &ranges[start_ix..] {
10920            if range
10921                .start
10922                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10923                .is_ge()
10924            {
10925                break;
10926            }
10927            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
10928            if let Some(current_row) = &end_row {
10929                if end.row == current_row.row {
10930                    continue;
10931                }
10932            }
10933            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
10934            if start_row.is_none() {
10935                assert_eq!(end_row, None);
10936                start_row = Some(start);
10937                end_row = Some(end);
10938                continue;
10939            }
10940            if let Some(current_end) = end_row.as_mut() {
10941                if start.row > current_end.row + 1 {
10942                    push_region(start_row, end_row);
10943                    start_row = Some(start);
10944                    end_row = Some(end);
10945                } else {
10946                    // Merge two hunks.
10947                    *current_end = end;
10948                }
10949            } else {
10950                unreachable!();
10951            }
10952        }
10953        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
10954        push_region(start_row, end_row);
10955        results
10956    }
10957
10958    pub fn gutter_highlights_in_range(
10959        &self,
10960        search_range: Range<Anchor>,
10961        display_snapshot: &DisplaySnapshot,
10962        cx: &AppContext,
10963    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10964        let mut results = Vec::new();
10965        for (color_fetcher, ranges) in self.gutter_highlights.values() {
10966            let color = color_fetcher(cx);
10967            let start_ix = match ranges.binary_search_by(|probe| {
10968                let cmp = probe
10969                    .end
10970                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10971                if cmp.is_gt() {
10972                    Ordering::Greater
10973                } else {
10974                    Ordering::Less
10975                }
10976            }) {
10977                Ok(i) | Err(i) => i,
10978            };
10979            for range in &ranges[start_ix..] {
10980                if range
10981                    .start
10982                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10983                    .is_ge()
10984                {
10985                    break;
10986                }
10987
10988                let start = range.start.to_display_point(&display_snapshot);
10989                let end = range.end.to_display_point(&display_snapshot);
10990                results.push((start..end, color))
10991            }
10992        }
10993        results
10994    }
10995
10996    /// Get the text ranges corresponding to the redaction query
10997    pub fn redacted_ranges(
10998        &self,
10999        search_range: Range<Anchor>,
11000        display_snapshot: &DisplaySnapshot,
11001        cx: &WindowContext,
11002    ) -> Vec<Range<DisplayPoint>> {
11003        display_snapshot
11004            .buffer_snapshot
11005            .redacted_ranges(search_range, |file| {
11006                if let Some(file) = file {
11007                    file.is_private()
11008                        && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11009                } else {
11010                    false
11011                }
11012            })
11013            .map(|range| {
11014                range.start.to_display_point(display_snapshot)
11015                    ..range.end.to_display_point(display_snapshot)
11016            })
11017            .collect()
11018    }
11019
11020    pub fn highlight_text<T: 'static>(
11021        &mut self,
11022        ranges: Vec<Range<Anchor>>,
11023        style: HighlightStyle,
11024        cx: &mut ViewContext<Self>,
11025    ) {
11026        self.display_map.update(cx, |map, _| {
11027            map.highlight_text(TypeId::of::<T>(), ranges, style)
11028        });
11029        cx.notify();
11030    }
11031
11032    pub(crate) fn highlight_inlays<T: 'static>(
11033        &mut self,
11034        highlights: Vec<InlayHighlight>,
11035        style: HighlightStyle,
11036        cx: &mut ViewContext<Self>,
11037    ) {
11038        self.display_map.update(cx, |map, _| {
11039            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11040        });
11041        cx.notify();
11042    }
11043
11044    pub fn text_highlights<'a, T: 'static>(
11045        &'a self,
11046        cx: &'a AppContext,
11047    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11048        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11049    }
11050
11051    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11052        let cleared = self
11053            .display_map
11054            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11055        if cleared {
11056            cx.notify();
11057        }
11058    }
11059
11060    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11061        (self.read_only(cx) || self.blink_manager.read(cx).visible())
11062            && self.focus_handle.is_focused(cx)
11063    }
11064
11065    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11066        self.show_cursor_when_unfocused = is_enabled;
11067        cx.notify();
11068    }
11069
11070    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11071        cx.notify();
11072    }
11073
11074    fn on_buffer_event(
11075        &mut self,
11076        multibuffer: Model<MultiBuffer>,
11077        event: &multi_buffer::Event,
11078        cx: &mut ViewContext<Self>,
11079    ) {
11080        match event {
11081            multi_buffer::Event::Edited {
11082                singleton_buffer_edited,
11083            } => {
11084                self.scrollbar_marker_state.dirty = true;
11085                self.active_indent_guides_state.dirty = true;
11086                self.refresh_active_diagnostics(cx);
11087                self.refresh_code_actions(cx);
11088                if self.has_active_inline_completion(cx) {
11089                    self.update_visible_inline_completion(cx);
11090                }
11091                cx.emit(EditorEvent::BufferEdited);
11092                cx.emit(SearchEvent::MatchesInvalidated);
11093                if *singleton_buffer_edited {
11094                    if let Some(project) = &self.project {
11095                        let project = project.read(cx);
11096                        let languages_affected = multibuffer
11097                            .read(cx)
11098                            .all_buffers()
11099                            .into_iter()
11100                            .filter_map(|buffer| {
11101                                let buffer = buffer.read(cx);
11102                                let language = buffer.language()?;
11103                                if project.is_local()
11104                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
11105                                {
11106                                    None
11107                                } else {
11108                                    Some(language)
11109                                }
11110                            })
11111                            .cloned()
11112                            .collect::<HashSet<_>>();
11113                        if !languages_affected.is_empty() {
11114                            self.refresh_inlay_hints(
11115                                InlayHintRefreshReason::BufferEdited(languages_affected),
11116                                cx,
11117                            );
11118                        }
11119                    }
11120                }
11121
11122                let Some(project) = &self.project else { return };
11123                let telemetry = project.read(cx).client().telemetry().clone();
11124                refresh_linked_ranges(self, cx);
11125                telemetry.log_edit_event("editor");
11126            }
11127            multi_buffer::Event::ExcerptsAdded {
11128                buffer,
11129                predecessor,
11130                excerpts,
11131            } => {
11132                self.tasks_update_task = Some(self.refresh_runnables(cx));
11133                cx.emit(EditorEvent::ExcerptsAdded {
11134                    buffer: buffer.clone(),
11135                    predecessor: *predecessor,
11136                    excerpts: excerpts.clone(),
11137                });
11138                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11139            }
11140            multi_buffer::Event::ExcerptsRemoved { ids } => {
11141                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11142                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11143            }
11144            multi_buffer::Event::ExcerptsEdited { ids } => {
11145                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11146            }
11147            multi_buffer::Event::ExcerptsExpanded { ids } => {
11148                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11149            }
11150            multi_buffer::Event::Reparsed(buffer_id) => {
11151                self.tasks_update_task = Some(self.refresh_runnables(cx));
11152
11153                cx.emit(EditorEvent::Reparsed(*buffer_id));
11154            }
11155            multi_buffer::Event::LanguageChanged(buffer_id) => {
11156                linked_editing_ranges::refresh_linked_ranges(self, cx);
11157                cx.emit(EditorEvent::Reparsed(*buffer_id));
11158                cx.notify();
11159            }
11160            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11161            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11162            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11163                cx.emit(EditorEvent::TitleChanged)
11164            }
11165            multi_buffer::Event::DiffBaseChanged => {
11166                self.scrollbar_marker_state.dirty = true;
11167                cx.emit(EditorEvent::DiffBaseChanged);
11168                cx.notify();
11169            }
11170            multi_buffer::Event::DiffUpdated { buffer } => {
11171                self.sync_expanded_diff_hunks(buffer.clone(), cx);
11172                cx.notify();
11173            }
11174            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11175            multi_buffer::Event::DiagnosticsUpdated => {
11176                self.refresh_active_diagnostics(cx);
11177                self.scrollbar_marker_state.dirty = true;
11178                cx.notify();
11179            }
11180            _ => {}
11181        };
11182    }
11183
11184    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11185        cx.notify();
11186    }
11187
11188    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11189        self.tasks_update_task = Some(self.refresh_runnables(cx));
11190        self.refresh_inline_completion(true, cx);
11191        self.refresh_inlay_hints(
11192            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11193                self.selections.newest_anchor().head(),
11194                &self.buffer.read(cx).snapshot(cx),
11195                cx,
11196            )),
11197            cx,
11198        );
11199        let editor_settings = EditorSettings::get_global(cx);
11200        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11201        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11202
11203        if self.mode == EditorMode::Full {
11204            let inline_blame_enabled = ProjectSettings::get_global(cx).git.inline_blame_enabled();
11205            if self.git_blame_inline_enabled != inline_blame_enabled {
11206                self.toggle_git_blame_inline_internal(false, cx);
11207            }
11208        }
11209
11210        cx.notify();
11211    }
11212
11213    pub fn set_searchable(&mut self, searchable: bool) {
11214        self.searchable = searchable;
11215    }
11216
11217    pub fn searchable(&self) -> bool {
11218        self.searchable
11219    }
11220
11221    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11222        self.open_excerpts_common(true, cx)
11223    }
11224
11225    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11226        self.open_excerpts_common(false, cx)
11227    }
11228
11229    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11230        let buffer = self.buffer.read(cx);
11231        if buffer.is_singleton() {
11232            cx.propagate();
11233            return;
11234        }
11235
11236        let Some(workspace) = self.workspace() else {
11237            cx.propagate();
11238            return;
11239        };
11240
11241        let mut new_selections_by_buffer = HashMap::default();
11242        for selection in self.selections.all::<usize>(cx) {
11243            for (buffer, mut range, _) in
11244                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11245            {
11246                if selection.reversed {
11247                    mem::swap(&mut range.start, &mut range.end);
11248                }
11249                new_selections_by_buffer
11250                    .entry(buffer)
11251                    .or_insert(Vec::new())
11252                    .push(range)
11253            }
11254        }
11255
11256        // We defer the pane interaction because we ourselves are a workspace item
11257        // and activating a new item causes the pane to call a method on us reentrantly,
11258        // which panics if we're on the stack.
11259        cx.window_context().defer(move |cx| {
11260            workspace.update(cx, |workspace, cx| {
11261                let pane = if split {
11262                    workspace.adjacent_pane(cx)
11263                } else {
11264                    workspace.active_pane().clone()
11265                };
11266
11267                for (buffer, ranges) in new_selections_by_buffer {
11268                    let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
11269                    editor.update(cx, |editor, cx| {
11270                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11271                            s.select_ranges(ranges);
11272                        });
11273                    });
11274                }
11275            })
11276        });
11277    }
11278
11279    fn jump(
11280        &mut self,
11281        path: ProjectPath,
11282        position: Point,
11283        anchor: language::Anchor,
11284        offset_from_top: u32,
11285        cx: &mut ViewContext<Self>,
11286    ) {
11287        let workspace = self.workspace();
11288        cx.spawn(|_, mut cx| async move {
11289            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11290            let editor = workspace.update(&mut cx, |workspace, cx| {
11291                // Reset the preview item id before opening the new item
11292                workspace.active_pane().update(cx, |pane, cx| {
11293                    pane.set_preview_item_id(None, cx);
11294                });
11295                workspace.open_path_preview(path, None, true, true, cx)
11296            })?;
11297            let editor = editor
11298                .await?
11299                .downcast::<Editor>()
11300                .ok_or_else(|| anyhow!("opened item was not an editor"))?
11301                .downgrade();
11302            editor.update(&mut cx, |editor, cx| {
11303                let buffer = editor
11304                    .buffer()
11305                    .read(cx)
11306                    .as_singleton()
11307                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11308                let buffer = buffer.read(cx);
11309                let cursor = if buffer.can_resolve(&anchor) {
11310                    language::ToPoint::to_point(&anchor, buffer)
11311                } else {
11312                    buffer.clip_point(position, Bias::Left)
11313                };
11314
11315                let nav_history = editor.nav_history.take();
11316                editor.change_selections(
11317                    Some(Autoscroll::top_relative(offset_from_top as usize)),
11318                    cx,
11319                    |s| {
11320                        s.select_ranges([cursor..cursor]);
11321                    },
11322                );
11323                editor.nav_history = nav_history;
11324
11325                anyhow::Ok(())
11326            })??;
11327
11328            anyhow::Ok(())
11329        })
11330        .detach_and_log_err(cx);
11331    }
11332
11333    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11334        let snapshot = self.buffer.read(cx).read(cx);
11335        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11336        Some(
11337            ranges
11338                .iter()
11339                .map(move |range| {
11340                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11341                })
11342                .collect(),
11343        )
11344    }
11345
11346    fn selection_replacement_ranges(
11347        &self,
11348        range: Range<OffsetUtf16>,
11349        cx: &AppContext,
11350    ) -> Vec<Range<OffsetUtf16>> {
11351        let selections = self.selections.all::<OffsetUtf16>(cx);
11352        let newest_selection = selections
11353            .iter()
11354            .max_by_key(|selection| selection.id)
11355            .unwrap();
11356        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11357        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11358        let snapshot = self.buffer.read(cx).read(cx);
11359        selections
11360            .into_iter()
11361            .map(|mut selection| {
11362                selection.start.0 =
11363                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
11364                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11365                snapshot.clip_offset_utf16(selection.start, Bias::Left)
11366                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11367            })
11368            .collect()
11369    }
11370
11371    fn report_editor_event(
11372        &self,
11373        operation: &'static str,
11374        file_extension: Option<String>,
11375        cx: &AppContext,
11376    ) {
11377        if cfg!(any(test, feature = "test-support")) {
11378            return;
11379        }
11380
11381        let Some(project) = &self.project else { return };
11382
11383        // If None, we are in a file without an extension
11384        let file = self
11385            .buffer
11386            .read(cx)
11387            .as_singleton()
11388            .and_then(|b| b.read(cx).file());
11389        let file_extension = file_extension.or(file
11390            .as_ref()
11391            .and_then(|file| Path::new(file.file_name(cx)).extension())
11392            .and_then(|e| e.to_str())
11393            .map(|a| a.to_string()));
11394
11395        let vim_mode = cx
11396            .global::<SettingsStore>()
11397            .raw_user_settings()
11398            .get("vim_mode")
11399            == Some(&serde_json::Value::Bool(true));
11400
11401        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11402            == language::language_settings::InlineCompletionProvider::Copilot;
11403        let copilot_enabled_for_language = self
11404            .buffer
11405            .read(cx)
11406            .settings_at(0, cx)
11407            .show_inline_completions;
11408
11409        let telemetry = project.read(cx).client().telemetry().clone();
11410        telemetry.report_editor_event(
11411            file_extension,
11412            vim_mode,
11413            operation,
11414            copilot_enabled,
11415            copilot_enabled_for_language,
11416        )
11417    }
11418
11419    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11420    /// with each line being an array of {text, highlight} objects.
11421    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11422        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11423            return;
11424        };
11425
11426        #[derive(Serialize)]
11427        struct Chunk<'a> {
11428            text: String,
11429            highlight: Option<&'a str>,
11430        }
11431
11432        let snapshot = buffer.read(cx).snapshot();
11433        let range = self
11434            .selected_text_range(cx)
11435            .and_then(|selected_range| {
11436                if selected_range.is_empty() {
11437                    None
11438                } else {
11439                    Some(selected_range)
11440                }
11441            })
11442            .unwrap_or_else(|| 0..snapshot.len());
11443
11444        let chunks = snapshot.chunks(range, true);
11445        let mut lines = Vec::new();
11446        let mut line: VecDeque<Chunk> = VecDeque::new();
11447
11448        let Some(style) = self.style.as_ref() else {
11449            return;
11450        };
11451
11452        for chunk in chunks {
11453            let highlight = chunk
11454                .syntax_highlight_id
11455                .and_then(|id| id.name(&style.syntax));
11456            let mut chunk_lines = chunk.text.split('\n').peekable();
11457            while let Some(text) = chunk_lines.next() {
11458                let mut merged_with_last_token = false;
11459                if let Some(last_token) = line.back_mut() {
11460                    if last_token.highlight == highlight {
11461                        last_token.text.push_str(text);
11462                        merged_with_last_token = true;
11463                    }
11464                }
11465
11466                if !merged_with_last_token {
11467                    line.push_back(Chunk {
11468                        text: text.into(),
11469                        highlight,
11470                    });
11471                }
11472
11473                if chunk_lines.peek().is_some() {
11474                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
11475                        line.pop_front();
11476                    }
11477                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
11478                        line.pop_back();
11479                    }
11480
11481                    lines.push(mem::take(&mut line));
11482                }
11483            }
11484        }
11485
11486        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11487            return;
11488        };
11489        cx.write_to_clipboard(ClipboardItem::new(lines));
11490    }
11491
11492    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11493        &self.inlay_hint_cache
11494    }
11495
11496    pub fn replay_insert_event(
11497        &mut self,
11498        text: &str,
11499        relative_utf16_range: Option<Range<isize>>,
11500        cx: &mut ViewContext<Self>,
11501    ) {
11502        if !self.input_enabled {
11503            cx.emit(EditorEvent::InputIgnored { text: text.into() });
11504            return;
11505        }
11506        if let Some(relative_utf16_range) = relative_utf16_range {
11507            let selections = self.selections.all::<OffsetUtf16>(cx);
11508            self.change_selections(None, cx, |s| {
11509                let new_ranges = selections.into_iter().map(|range| {
11510                    let start = OffsetUtf16(
11511                        range
11512                            .head()
11513                            .0
11514                            .saturating_add_signed(relative_utf16_range.start),
11515                    );
11516                    let end = OffsetUtf16(
11517                        range
11518                            .head()
11519                            .0
11520                            .saturating_add_signed(relative_utf16_range.end),
11521                    );
11522                    start..end
11523                });
11524                s.select_ranges(new_ranges);
11525            });
11526        }
11527
11528        self.handle_input(text, cx);
11529    }
11530
11531    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11532        let Some(project) = self.project.as_ref() else {
11533            return false;
11534        };
11535        let project = project.read(cx);
11536
11537        let mut supports = false;
11538        self.buffer().read(cx).for_each_buffer(|buffer| {
11539            if !supports {
11540                supports = project
11541                    .language_servers_for_buffer(buffer.read(cx), cx)
11542                    .any(
11543                        |(_, server)| match server.capabilities().inlay_hint_provider {
11544                            Some(lsp::OneOf::Left(enabled)) => enabled,
11545                            Some(lsp::OneOf::Right(_)) => true,
11546                            None => false,
11547                        },
11548                    )
11549            }
11550        });
11551        supports
11552    }
11553
11554    pub fn focus(&self, cx: &mut WindowContext) {
11555        cx.focus(&self.focus_handle)
11556    }
11557
11558    pub fn is_focused(&self, cx: &WindowContext) -> bool {
11559        self.focus_handle.is_focused(cx)
11560    }
11561
11562    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11563        cx.emit(EditorEvent::Focused);
11564
11565        if let Some(descendant) = self
11566            .last_focused_descendant
11567            .take()
11568            .and_then(|descendant| descendant.upgrade())
11569        {
11570            cx.focus(&descendant);
11571        } else {
11572            if let Some(blame) = self.blame.as_ref() {
11573                blame.update(cx, GitBlame::focus)
11574            }
11575
11576            self.blink_manager.update(cx, BlinkManager::enable);
11577            self.show_cursor_names(cx);
11578            self.buffer.update(cx, |buffer, cx| {
11579                buffer.finalize_last_transaction(cx);
11580                if self.leader_peer_id.is_none() {
11581                    buffer.set_active_selections(
11582                        &self.selections.disjoint_anchors(),
11583                        self.selections.line_mode,
11584                        self.cursor_shape,
11585                        cx,
11586                    );
11587                }
11588            });
11589        }
11590    }
11591
11592    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11593        if event.blurred != self.focus_handle {
11594            self.last_focused_descendant = Some(event.blurred);
11595        }
11596    }
11597
11598    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11599        self.blink_manager.update(cx, BlinkManager::disable);
11600        self.buffer
11601            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11602
11603        if let Some(blame) = self.blame.as_ref() {
11604            blame.update(cx, GitBlame::blur)
11605        }
11606        self.hide_context_menu(cx);
11607        hide_hover(self, cx);
11608        cx.emit(EditorEvent::Blurred);
11609        cx.notify();
11610    }
11611
11612    pub fn register_action<A: Action>(
11613        &mut self,
11614        listener: impl Fn(&A, &mut WindowContext) + 'static,
11615    ) -> Subscription {
11616        let id = self.next_editor_action_id.post_inc();
11617        let listener = Arc::new(listener);
11618        self.editor_actions.borrow_mut().insert(
11619            id,
11620            Box::new(move |cx| {
11621                let _view = cx.view().clone();
11622                let cx = cx.window_context();
11623                let listener = listener.clone();
11624                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11625                    let action = action.downcast_ref().unwrap();
11626                    if phase == DispatchPhase::Bubble {
11627                        listener(action, cx)
11628                    }
11629                })
11630            }),
11631        );
11632
11633        let editor_actions = self.editor_actions.clone();
11634        Subscription::new(move || {
11635            editor_actions.borrow_mut().remove(&id);
11636        })
11637    }
11638
11639    pub fn file_header_size(&self) -> u8 {
11640        self.file_header_size
11641    }
11642}
11643
11644fn hunks_for_selections(
11645    multi_buffer_snapshot: &MultiBufferSnapshot,
11646    selections: &[Selection<Anchor>],
11647) -> Vec<DiffHunk<MultiBufferRow>> {
11648    let mut hunks = Vec::with_capacity(selections.len());
11649    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11650        HashMap::default();
11651    let buffer_rows_for_selections = selections.iter().map(|selection| {
11652        let head = selection.head();
11653        let tail = selection.tail();
11654        let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11655        let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11656        if start > end {
11657            end..start
11658        } else {
11659            start..end
11660        }
11661    });
11662
11663    for selected_multi_buffer_rows in buffer_rows_for_selections {
11664        let query_rows =
11665            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11666        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11667            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11668            // when the caret is just above or just below the deleted hunk.
11669            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11670            let related_to_selection = if allow_adjacent {
11671                hunk.associated_range.overlaps(&query_rows)
11672                    || hunk.associated_range.start == query_rows.end
11673                    || hunk.associated_range.end == query_rows.start
11674            } else {
11675                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11676                // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11677                hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11678                    || selected_multi_buffer_rows.end == hunk.associated_range.start
11679            };
11680            if related_to_selection {
11681                if !processed_buffer_rows
11682                    .entry(hunk.buffer_id)
11683                    .or_default()
11684                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
11685                {
11686                    continue;
11687                }
11688                hunks.push(hunk);
11689            }
11690        }
11691    }
11692
11693    hunks
11694}
11695
11696pub trait CollaborationHub {
11697    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
11698    fn user_participant_indices<'a>(
11699        &self,
11700        cx: &'a AppContext,
11701    ) -> &'a HashMap<u64, ParticipantIndex>;
11702    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
11703}
11704
11705impl CollaborationHub for Model<Project> {
11706    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
11707        self.read(cx).collaborators()
11708    }
11709
11710    fn user_participant_indices<'a>(
11711        &self,
11712        cx: &'a AppContext,
11713    ) -> &'a HashMap<u64, ParticipantIndex> {
11714        self.read(cx).user_store().read(cx).participant_indices()
11715    }
11716
11717    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
11718        let this = self.read(cx);
11719        let user_ids = this.collaborators().values().map(|c| c.user_id);
11720        this.user_store().read_with(cx, |user_store, cx| {
11721            user_store.participant_names(user_ids, cx)
11722        })
11723    }
11724}
11725
11726pub trait CompletionProvider {
11727    fn completions(
11728        &self,
11729        buffer: &Model<Buffer>,
11730        buffer_position: text::Anchor,
11731        trigger: CompletionContext,
11732        cx: &mut ViewContext<Editor>,
11733    ) -> Task<Result<Vec<Completion>>>;
11734
11735    fn resolve_completions(
11736        &self,
11737        buffer: Model<Buffer>,
11738        completion_indices: Vec<usize>,
11739        completions: Arc<RwLock<Box<[Completion]>>>,
11740        cx: &mut ViewContext<Editor>,
11741    ) -> Task<Result<bool>>;
11742
11743    fn apply_additional_edits_for_completion(
11744        &self,
11745        buffer: Model<Buffer>,
11746        completion: Completion,
11747        push_to_history: bool,
11748        cx: &mut ViewContext<Editor>,
11749    ) -> Task<Result<Option<language::Transaction>>>;
11750
11751    fn is_completion_trigger(
11752        &self,
11753        buffer: &Model<Buffer>,
11754        position: language::Anchor,
11755        text: &str,
11756        trigger_in_words: bool,
11757        cx: &mut ViewContext<Editor>,
11758    ) -> bool;
11759}
11760
11761fn snippet_completions(
11762    project: &Project,
11763    buffer: &Model<Buffer>,
11764    buffer_position: text::Anchor,
11765    cx: &mut AppContext,
11766) -> Vec<Completion> {
11767    let language = buffer.read(cx).language_at(buffer_position);
11768    let language_name = language.as_ref().map(|language| language.lsp_id());
11769    let snippet_store = project.snippets().read(cx);
11770    let snippets = snippet_store.snippets_for(language_name, cx);
11771
11772    if snippets.is_empty() {
11773        return vec![];
11774    }
11775    let snapshot = buffer.read(cx).text_snapshot();
11776    let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
11777
11778    let mut lines = chunks.lines();
11779    let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
11780        return vec![];
11781    };
11782
11783    let scope = language.map(|language| language.default_scope());
11784    let mut last_word = line_at
11785        .chars()
11786        .rev()
11787        .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
11788        .collect::<String>();
11789    last_word = last_word.chars().rev().collect();
11790    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
11791    let to_lsp = |point: &text::Anchor| {
11792        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
11793        point_to_lsp(end)
11794    };
11795    let lsp_end = to_lsp(&buffer_position);
11796    snippets
11797        .into_iter()
11798        .filter_map(|snippet| {
11799            let matching_prefix = snippet
11800                .prefix
11801                .iter()
11802                .find(|prefix| prefix.starts_with(&last_word))?;
11803            let start = as_offset - last_word.len();
11804            let start = snapshot.anchor_before(start);
11805            let range = start..buffer_position;
11806            let lsp_start = to_lsp(&start);
11807            let lsp_range = lsp::Range {
11808                start: lsp_start,
11809                end: lsp_end,
11810            };
11811            Some(Completion {
11812                old_range: range,
11813                new_text: snippet.body.clone(),
11814                label: CodeLabel {
11815                    text: matching_prefix.clone(),
11816                    runs: vec![],
11817                    filter_range: 0..matching_prefix.len(),
11818                },
11819                server_id: LanguageServerId(usize::MAX),
11820                documentation: snippet
11821                    .description
11822                    .clone()
11823                    .map(|description| Documentation::SingleLine(description)),
11824                lsp_completion: lsp::CompletionItem {
11825                    label: snippet.prefix.first().unwrap().clone(),
11826                    kind: Some(CompletionItemKind::SNIPPET),
11827                    label_details: snippet.description.as_ref().map(|description| {
11828                        lsp::CompletionItemLabelDetails {
11829                            detail: Some(description.clone()),
11830                            description: None,
11831                        }
11832                    }),
11833                    insert_text_format: Some(InsertTextFormat::SNIPPET),
11834                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
11835                        lsp::InsertReplaceEdit {
11836                            new_text: snippet.body.clone(),
11837                            insert: lsp_range,
11838                            replace: lsp_range,
11839                        },
11840                    )),
11841                    filter_text: Some(snippet.body.clone()),
11842                    sort_text: Some(char::MAX.to_string()),
11843                    ..Default::default()
11844                },
11845                confirm: None,
11846                show_new_completions_on_confirm: false,
11847            })
11848        })
11849        .collect()
11850}
11851
11852impl CompletionProvider for Model<Project> {
11853    fn completions(
11854        &self,
11855        buffer: &Model<Buffer>,
11856        buffer_position: text::Anchor,
11857        options: CompletionContext,
11858        cx: &mut ViewContext<Editor>,
11859    ) -> Task<Result<Vec<Completion>>> {
11860        self.update(cx, |project, cx| {
11861            let snippets = snippet_completions(project, buffer, buffer_position, cx);
11862            let project_completions = project.completions(&buffer, buffer_position, options, cx);
11863            cx.background_executor().spawn(async move {
11864                let mut completions = project_completions.await?;
11865                //let snippets = snippets.into_iter().;
11866                completions.extend(snippets);
11867                Ok(completions)
11868            })
11869        })
11870    }
11871
11872    fn resolve_completions(
11873        &self,
11874        buffer: Model<Buffer>,
11875        completion_indices: Vec<usize>,
11876        completions: Arc<RwLock<Box<[Completion]>>>,
11877        cx: &mut ViewContext<Editor>,
11878    ) -> Task<Result<bool>> {
11879        self.update(cx, |project, cx| {
11880            project.resolve_completions(buffer, completion_indices, completions, cx)
11881        })
11882    }
11883
11884    fn apply_additional_edits_for_completion(
11885        &self,
11886        buffer: Model<Buffer>,
11887        completion: Completion,
11888        push_to_history: bool,
11889        cx: &mut ViewContext<Editor>,
11890    ) -> Task<Result<Option<language::Transaction>>> {
11891        self.update(cx, |project, cx| {
11892            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
11893        })
11894    }
11895
11896    fn is_completion_trigger(
11897        &self,
11898        buffer: &Model<Buffer>,
11899        position: language::Anchor,
11900        text: &str,
11901        trigger_in_words: bool,
11902        cx: &mut ViewContext<Editor>,
11903    ) -> bool {
11904        if !EditorSettings::get_global(cx).show_completions_on_input {
11905            return false;
11906        }
11907
11908        let mut chars = text.chars();
11909        let char = if let Some(char) = chars.next() {
11910            char
11911        } else {
11912            return false;
11913        };
11914        if chars.next().is_some() {
11915            return false;
11916        }
11917
11918        let buffer = buffer.read(cx);
11919        let scope = buffer.snapshot().language_scope_at(position);
11920        if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
11921            return true;
11922        }
11923
11924        buffer
11925            .completion_triggers()
11926            .iter()
11927            .any(|string| string == text)
11928    }
11929}
11930
11931fn inlay_hint_settings(
11932    location: Anchor,
11933    snapshot: &MultiBufferSnapshot,
11934    cx: &mut ViewContext<'_, Editor>,
11935) -> InlayHintSettings {
11936    let file = snapshot.file_at(location);
11937    let language = snapshot.language_at(location);
11938    let settings = all_language_settings(file, cx);
11939    settings
11940        .language(language.map(|l| l.name()).as_deref())
11941        .inlay_hints
11942}
11943
11944fn consume_contiguous_rows(
11945    contiguous_row_selections: &mut Vec<Selection<Point>>,
11946    selection: &Selection<Point>,
11947    display_map: &DisplaySnapshot,
11948    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
11949) -> (MultiBufferRow, MultiBufferRow) {
11950    contiguous_row_selections.push(selection.clone());
11951    let start_row = MultiBufferRow(selection.start.row);
11952    let mut end_row = ending_row(selection, display_map);
11953
11954    while let Some(next_selection) = selections.peek() {
11955        if next_selection.start.row <= end_row.0 {
11956            end_row = ending_row(next_selection, display_map);
11957            contiguous_row_selections.push(selections.next().unwrap().clone());
11958        } else {
11959            break;
11960        }
11961    }
11962    (start_row, end_row)
11963}
11964
11965fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
11966    if next_selection.end.column > 0 || next_selection.is_empty() {
11967        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
11968    } else {
11969        MultiBufferRow(next_selection.end.row)
11970    }
11971}
11972
11973impl EditorSnapshot {
11974    pub fn remote_selections_in_range<'a>(
11975        &'a self,
11976        range: &'a Range<Anchor>,
11977        collaboration_hub: &dyn CollaborationHub,
11978        cx: &'a AppContext,
11979    ) -> impl 'a + Iterator<Item = RemoteSelection> {
11980        let participant_names = collaboration_hub.user_names(cx);
11981        let participant_indices = collaboration_hub.user_participant_indices(cx);
11982        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
11983        let collaborators_by_replica_id = collaborators_by_peer_id
11984            .iter()
11985            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
11986            .collect::<HashMap<_, _>>();
11987        self.buffer_snapshot
11988            .selections_in_range(range, false)
11989            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
11990                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
11991                let participant_index = participant_indices.get(&collaborator.user_id).copied();
11992                let user_name = participant_names.get(&collaborator.user_id).cloned();
11993                Some(RemoteSelection {
11994                    replica_id,
11995                    selection,
11996                    cursor_shape,
11997                    line_mode,
11998                    participant_index,
11999                    peer_id: collaborator.peer_id,
12000                    user_name,
12001                })
12002            })
12003    }
12004
12005    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12006        self.display_snapshot.buffer_snapshot.language_at(position)
12007    }
12008
12009    pub fn is_focused(&self) -> bool {
12010        self.is_focused
12011    }
12012
12013    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12014        self.placeholder_text.as_ref()
12015    }
12016
12017    pub fn scroll_position(&self) -> gpui::Point<f32> {
12018        self.scroll_anchor.scroll_position(&self.display_snapshot)
12019    }
12020
12021    pub fn gutter_dimensions(
12022        &self,
12023        font_id: FontId,
12024        font_size: Pixels,
12025        em_width: Pixels,
12026        max_line_number_width: Pixels,
12027        cx: &AppContext,
12028    ) -> GutterDimensions {
12029        if !self.show_gutter {
12030            return GutterDimensions::default();
12031        }
12032        let descent = cx.text_system().descent(font_id, font_size);
12033
12034        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12035            matches!(
12036                ProjectSettings::get_global(cx).git.git_gutter,
12037                Some(GitGutterSetting::TrackedFiles)
12038            )
12039        });
12040        let gutter_settings = EditorSettings::get_global(cx).gutter;
12041        let show_line_numbers = self
12042            .show_line_numbers
12043            .unwrap_or(gutter_settings.line_numbers);
12044        let line_gutter_width = if show_line_numbers {
12045            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12046            let min_width_for_number_on_gutter = em_width * 4.0;
12047            max_line_number_width.max(min_width_for_number_on_gutter)
12048        } else {
12049            0.0.into()
12050        };
12051
12052        let show_code_actions = self
12053            .show_code_actions
12054            .unwrap_or(gutter_settings.code_actions);
12055
12056        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12057
12058        let git_blame_entries_width = self
12059            .render_git_blame_gutter
12060            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12061
12062        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12063        left_padding += if show_code_actions || show_runnables {
12064            em_width * 3.0
12065        } else if show_git_gutter && show_line_numbers {
12066            em_width * 2.0
12067        } else if show_git_gutter || show_line_numbers {
12068            em_width
12069        } else {
12070            px(0.)
12071        };
12072
12073        let right_padding = if gutter_settings.folds && show_line_numbers {
12074            em_width * 4.0
12075        } else if gutter_settings.folds {
12076            em_width * 3.0
12077        } else if show_line_numbers {
12078            em_width
12079        } else {
12080            px(0.)
12081        };
12082
12083        GutterDimensions {
12084            left_padding,
12085            right_padding,
12086            width: line_gutter_width + left_padding + right_padding,
12087            margin: -descent,
12088            git_blame_entries_width,
12089        }
12090    }
12091
12092    pub fn render_fold_toggle(
12093        &self,
12094        buffer_row: MultiBufferRow,
12095        row_contains_cursor: bool,
12096        editor: View<Editor>,
12097        cx: &mut WindowContext,
12098    ) -> Option<AnyElement> {
12099        let folded = self.is_line_folded(buffer_row);
12100
12101        if let Some(crease) = self
12102            .crease_snapshot
12103            .query_row(buffer_row, &self.buffer_snapshot)
12104        {
12105            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12106                if folded {
12107                    editor.update(cx, |editor, cx| {
12108                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12109                    });
12110                } else {
12111                    editor.update(cx, |editor, cx| {
12112                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12113                    });
12114                }
12115            });
12116
12117            Some((crease.render_toggle)(
12118                buffer_row,
12119                folded,
12120                toggle_callback,
12121                cx,
12122            ))
12123        } else if folded
12124            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12125        {
12126            Some(
12127                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12128                    .selected(folded)
12129                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12130                        if folded {
12131                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
12132                        } else {
12133                            this.fold_at(&FoldAt { buffer_row }, cx);
12134                        }
12135                    }))
12136                    .into_any_element(),
12137            )
12138        } else {
12139            None
12140        }
12141    }
12142
12143    pub fn render_crease_trailer(
12144        &self,
12145        buffer_row: MultiBufferRow,
12146        cx: &mut WindowContext,
12147    ) -> Option<AnyElement> {
12148        let folded = self.is_line_folded(buffer_row);
12149        let crease = self
12150            .crease_snapshot
12151            .query_row(buffer_row, &self.buffer_snapshot)?;
12152        Some((crease.render_trailer)(buffer_row, folded, cx))
12153    }
12154}
12155
12156impl Deref for EditorSnapshot {
12157    type Target = DisplaySnapshot;
12158
12159    fn deref(&self) -> &Self::Target {
12160        &self.display_snapshot
12161    }
12162}
12163
12164#[derive(Clone, Debug, PartialEq, Eq)]
12165pub enum EditorEvent {
12166    InputIgnored {
12167        text: Arc<str>,
12168    },
12169    InputHandled {
12170        utf16_range_to_replace: Option<Range<isize>>,
12171        text: Arc<str>,
12172    },
12173    ExcerptsAdded {
12174        buffer: Model<Buffer>,
12175        predecessor: ExcerptId,
12176        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12177    },
12178    ExcerptsRemoved {
12179        ids: Vec<ExcerptId>,
12180    },
12181    ExcerptsEdited {
12182        ids: Vec<ExcerptId>,
12183    },
12184    ExcerptsExpanded {
12185        ids: Vec<ExcerptId>,
12186    },
12187    BufferEdited,
12188    Edited {
12189        transaction_id: clock::Lamport,
12190    },
12191    Reparsed(BufferId),
12192    Focused,
12193    Blurred,
12194    DirtyChanged,
12195    Saved,
12196    TitleChanged,
12197    DiffBaseChanged,
12198    SelectionsChanged {
12199        local: bool,
12200    },
12201    ScrollPositionChanged {
12202        local: bool,
12203        autoscroll: bool,
12204    },
12205    Closed,
12206    TransactionUndone {
12207        transaction_id: clock::Lamport,
12208    },
12209    TransactionBegun {
12210        transaction_id: clock::Lamport,
12211    },
12212}
12213
12214impl EventEmitter<EditorEvent> for Editor {}
12215
12216impl FocusableView for Editor {
12217    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12218        self.focus_handle.clone()
12219    }
12220}
12221
12222impl Render for Editor {
12223    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12224        let settings = ThemeSettings::get_global(cx);
12225
12226        let text_style = match self.mode {
12227            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12228                color: cx.theme().colors().editor_foreground,
12229                font_family: settings.ui_font.family.clone(),
12230                font_features: settings.ui_font.features.clone(),
12231                font_size: rems(0.875).into(),
12232                font_weight: settings.ui_font.weight,
12233                font_style: FontStyle::Normal,
12234                line_height: relative(settings.buffer_line_height.value()),
12235                background_color: None,
12236                underline: None,
12237                strikethrough: None,
12238                white_space: WhiteSpace::Normal,
12239            },
12240            EditorMode::Full => TextStyle {
12241                color: cx.theme().colors().editor_foreground,
12242                font_family: settings.buffer_font.family.clone(),
12243                font_features: settings.buffer_font.features.clone(),
12244                font_size: settings.buffer_font_size(cx).into(),
12245                font_weight: settings.buffer_font.weight,
12246                font_style: FontStyle::Normal,
12247                line_height: relative(settings.buffer_line_height.value()),
12248                background_color: None,
12249                underline: None,
12250                strikethrough: None,
12251                white_space: WhiteSpace::Normal,
12252            },
12253        };
12254
12255        let background = match self.mode {
12256            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12257            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12258            EditorMode::Full => cx.theme().colors().editor_background,
12259        };
12260
12261        EditorElement::new(
12262            cx.view(),
12263            EditorStyle {
12264                background,
12265                local_player: cx.theme().players().local(),
12266                text: text_style,
12267                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12268                syntax: cx.theme().syntax().clone(),
12269                status: cx.theme().status().clone(),
12270                inlay_hints_style: HighlightStyle {
12271                    color: Some(cx.theme().status().hint),
12272                    ..HighlightStyle::default()
12273                },
12274                suggestions_style: HighlightStyle {
12275                    color: Some(cx.theme().status().predictive),
12276                    ..HighlightStyle::default()
12277                },
12278            },
12279        )
12280    }
12281}
12282
12283impl ViewInputHandler for Editor {
12284    fn text_for_range(
12285        &mut self,
12286        range_utf16: Range<usize>,
12287        cx: &mut ViewContext<Self>,
12288    ) -> Option<String> {
12289        Some(
12290            self.buffer
12291                .read(cx)
12292                .read(cx)
12293                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12294                .collect(),
12295        )
12296    }
12297
12298    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12299        // Prevent the IME menu from appearing when holding down an alphabetic key
12300        // while input is disabled.
12301        if !self.input_enabled {
12302            return None;
12303        }
12304
12305        let range = self.selections.newest::<OffsetUtf16>(cx).range();
12306        Some(range.start.0..range.end.0)
12307    }
12308
12309    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12310        let snapshot = self.buffer.read(cx).read(cx);
12311        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12312        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12313    }
12314
12315    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12316        self.clear_highlights::<InputComposition>(cx);
12317        self.ime_transaction.take();
12318    }
12319
12320    fn replace_text_in_range(
12321        &mut self,
12322        range_utf16: Option<Range<usize>>,
12323        text: &str,
12324        cx: &mut ViewContext<Self>,
12325    ) {
12326        if !self.input_enabled {
12327            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12328            return;
12329        }
12330
12331        self.transact(cx, |this, cx| {
12332            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12333                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12334                Some(this.selection_replacement_ranges(range_utf16, cx))
12335            } else {
12336                this.marked_text_ranges(cx)
12337            };
12338
12339            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12340                let newest_selection_id = this.selections.newest_anchor().id;
12341                this.selections
12342                    .all::<OffsetUtf16>(cx)
12343                    .iter()
12344                    .zip(ranges_to_replace.iter())
12345                    .find_map(|(selection, range)| {
12346                        if selection.id == newest_selection_id {
12347                            Some(
12348                                (range.start.0 as isize - selection.head().0 as isize)
12349                                    ..(range.end.0 as isize - selection.head().0 as isize),
12350                            )
12351                        } else {
12352                            None
12353                        }
12354                    })
12355            });
12356
12357            cx.emit(EditorEvent::InputHandled {
12358                utf16_range_to_replace: range_to_replace,
12359                text: text.into(),
12360            });
12361
12362            if let Some(new_selected_ranges) = new_selected_ranges {
12363                this.change_selections(None, cx, |selections| {
12364                    selections.select_ranges(new_selected_ranges)
12365                });
12366                this.backspace(&Default::default(), cx);
12367            }
12368
12369            this.handle_input(text, cx);
12370        });
12371
12372        if let Some(transaction) = self.ime_transaction {
12373            self.buffer.update(cx, |buffer, cx| {
12374                buffer.group_until_transaction(transaction, cx);
12375            });
12376        }
12377
12378        self.unmark_text(cx);
12379    }
12380
12381    fn replace_and_mark_text_in_range(
12382        &mut self,
12383        range_utf16: Option<Range<usize>>,
12384        text: &str,
12385        new_selected_range_utf16: Option<Range<usize>>,
12386        cx: &mut ViewContext<Self>,
12387    ) {
12388        if !self.input_enabled {
12389            return;
12390        }
12391
12392        let transaction = self.transact(cx, |this, cx| {
12393            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12394                let snapshot = this.buffer.read(cx).read(cx);
12395                if let Some(relative_range_utf16) = range_utf16.as_ref() {
12396                    for marked_range in &mut marked_ranges {
12397                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12398                        marked_range.start.0 += relative_range_utf16.start;
12399                        marked_range.start =
12400                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12401                        marked_range.end =
12402                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12403                    }
12404                }
12405                Some(marked_ranges)
12406            } else if let Some(range_utf16) = range_utf16 {
12407                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12408                Some(this.selection_replacement_ranges(range_utf16, cx))
12409            } else {
12410                None
12411            };
12412
12413            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12414                let newest_selection_id = this.selections.newest_anchor().id;
12415                this.selections
12416                    .all::<OffsetUtf16>(cx)
12417                    .iter()
12418                    .zip(ranges_to_replace.iter())
12419                    .find_map(|(selection, range)| {
12420                        if selection.id == newest_selection_id {
12421                            Some(
12422                                (range.start.0 as isize - selection.head().0 as isize)
12423                                    ..(range.end.0 as isize - selection.head().0 as isize),
12424                            )
12425                        } else {
12426                            None
12427                        }
12428                    })
12429            });
12430
12431            cx.emit(EditorEvent::InputHandled {
12432                utf16_range_to_replace: range_to_replace,
12433                text: text.into(),
12434            });
12435
12436            if let Some(ranges) = ranges_to_replace {
12437                this.change_selections(None, cx, |s| s.select_ranges(ranges));
12438            }
12439
12440            let marked_ranges = {
12441                let snapshot = this.buffer.read(cx).read(cx);
12442                this.selections
12443                    .disjoint_anchors()
12444                    .iter()
12445                    .map(|selection| {
12446                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12447                    })
12448                    .collect::<Vec<_>>()
12449            };
12450
12451            if text.is_empty() {
12452                this.unmark_text(cx);
12453            } else {
12454                this.highlight_text::<InputComposition>(
12455                    marked_ranges.clone(),
12456                    HighlightStyle {
12457                        underline: Some(UnderlineStyle {
12458                            thickness: px(1.),
12459                            color: None,
12460                            wavy: false,
12461                        }),
12462                        ..Default::default()
12463                    },
12464                    cx,
12465                );
12466            }
12467
12468            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12469            let use_autoclose = this.use_autoclose;
12470            let use_auto_surround = this.use_auto_surround;
12471            this.set_use_autoclose(false);
12472            this.set_use_auto_surround(false);
12473            this.handle_input(text, cx);
12474            this.set_use_autoclose(use_autoclose);
12475            this.set_use_auto_surround(use_auto_surround);
12476
12477            if let Some(new_selected_range) = new_selected_range_utf16 {
12478                let snapshot = this.buffer.read(cx).read(cx);
12479                let new_selected_ranges = marked_ranges
12480                    .into_iter()
12481                    .map(|marked_range| {
12482                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12483                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12484                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12485                        snapshot.clip_offset_utf16(new_start, Bias::Left)
12486                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12487                    })
12488                    .collect::<Vec<_>>();
12489
12490                drop(snapshot);
12491                this.change_selections(None, cx, |selections| {
12492                    selections.select_ranges(new_selected_ranges)
12493                });
12494            }
12495        });
12496
12497        self.ime_transaction = self.ime_transaction.or(transaction);
12498        if let Some(transaction) = self.ime_transaction {
12499            self.buffer.update(cx, |buffer, cx| {
12500                buffer.group_until_transaction(transaction, cx);
12501            });
12502        }
12503
12504        if self.text_highlights::<InputComposition>(cx).is_none() {
12505            self.ime_transaction.take();
12506        }
12507    }
12508
12509    fn bounds_for_range(
12510        &mut self,
12511        range_utf16: Range<usize>,
12512        element_bounds: gpui::Bounds<Pixels>,
12513        cx: &mut ViewContext<Self>,
12514    ) -> Option<gpui::Bounds<Pixels>> {
12515        let text_layout_details = self.text_layout_details(cx);
12516        let style = &text_layout_details.editor_style;
12517        let font_id = cx.text_system().resolve_font(&style.text.font());
12518        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12519        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12520
12521        let em_width = cx
12522            .text_system()
12523            .typographic_bounds(font_id, font_size, 'm')
12524            .unwrap()
12525            .size
12526            .width;
12527
12528        let snapshot = self.snapshot(cx);
12529        let scroll_position = snapshot.scroll_position();
12530        let scroll_left = scroll_position.x * em_width;
12531
12532        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12533        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12534            + self.gutter_dimensions.width;
12535        let y = line_height * (start.row().as_f32() - scroll_position.y);
12536
12537        Some(Bounds {
12538            origin: element_bounds.origin + point(x, y),
12539            size: size(em_width, line_height),
12540        })
12541    }
12542}
12543
12544trait SelectionExt {
12545    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12546    fn spanned_rows(
12547        &self,
12548        include_end_if_at_line_start: bool,
12549        map: &DisplaySnapshot,
12550    ) -> Range<MultiBufferRow>;
12551}
12552
12553impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12554    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12555        let start = self
12556            .start
12557            .to_point(&map.buffer_snapshot)
12558            .to_display_point(map);
12559        let end = self
12560            .end
12561            .to_point(&map.buffer_snapshot)
12562            .to_display_point(map);
12563        if self.reversed {
12564            end..start
12565        } else {
12566            start..end
12567        }
12568    }
12569
12570    fn spanned_rows(
12571        &self,
12572        include_end_if_at_line_start: bool,
12573        map: &DisplaySnapshot,
12574    ) -> Range<MultiBufferRow> {
12575        let start = self.start.to_point(&map.buffer_snapshot);
12576        let mut end = self.end.to_point(&map.buffer_snapshot);
12577        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12578            end.row -= 1;
12579        }
12580
12581        let buffer_start = map.prev_line_boundary(start).0;
12582        let buffer_end = map.next_line_boundary(end).0;
12583        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12584    }
12585}
12586
12587impl<T: InvalidationRegion> InvalidationStack<T> {
12588    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12589    where
12590        S: Clone + ToOffset,
12591    {
12592        while let Some(region) = self.last() {
12593            let all_selections_inside_invalidation_ranges =
12594                if selections.len() == region.ranges().len() {
12595                    selections
12596                        .iter()
12597                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12598                        .all(|(selection, invalidation_range)| {
12599                            let head = selection.head().to_offset(buffer);
12600                            invalidation_range.start <= head && invalidation_range.end >= head
12601                        })
12602                } else {
12603                    false
12604                };
12605
12606            if all_selections_inside_invalidation_ranges {
12607                break;
12608            } else {
12609                self.pop();
12610            }
12611        }
12612    }
12613}
12614
12615impl<T> Default for InvalidationStack<T> {
12616    fn default() -> Self {
12617        Self(Default::default())
12618    }
12619}
12620
12621impl<T> Deref for InvalidationStack<T> {
12622    type Target = Vec<T>;
12623
12624    fn deref(&self) -> &Self::Target {
12625        &self.0
12626    }
12627}
12628
12629impl<T> DerefMut for InvalidationStack<T> {
12630    fn deref_mut(&mut self) -> &mut Self::Target {
12631        &mut self.0
12632    }
12633}
12634
12635impl InvalidationRegion for SnippetState {
12636    fn ranges(&self) -> &[Range<Anchor>] {
12637        &self.ranges[self.active_index]
12638    }
12639}
12640
12641pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
12642    let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
12643
12644    Box::new(move |cx: &mut BlockContext| {
12645        let group_id: SharedString = cx.block_id.to_string().into();
12646
12647        let mut text_style = cx.text_style().clone();
12648        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
12649        let theme_settings = ThemeSettings::get_global(cx);
12650        text_style.font_family = theme_settings.buffer_font.family.clone();
12651        text_style.font_style = theme_settings.buffer_font.style;
12652        text_style.font_features = theme_settings.buffer_font.features.clone();
12653        text_style.font_weight = theme_settings.buffer_font.weight;
12654
12655        let multi_line_diagnostic = diagnostic.message.contains('\n');
12656
12657        let buttons = |diagnostic: &Diagnostic, block_id: usize| {
12658            if multi_line_diagnostic {
12659                v_flex()
12660            } else {
12661                h_flex()
12662            }
12663            .children(diagnostic.is_primary.then(|| {
12664                IconButton::new(("close-block", block_id), IconName::XCircle)
12665                    .icon_color(Color::Muted)
12666                    .size(ButtonSize::Compact)
12667                    .style(ButtonStyle::Transparent)
12668                    .visible_on_hover(group_id.clone())
12669                    .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
12670                    .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
12671            }))
12672            .child(
12673                IconButton::new(("copy-block", block_id), IconName::Copy)
12674                    .icon_color(Color::Muted)
12675                    .size(ButtonSize::Compact)
12676                    .style(ButtonStyle::Transparent)
12677                    .visible_on_hover(group_id.clone())
12678                    .on_click({
12679                        let message = diagnostic.message.clone();
12680                        move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
12681                    })
12682                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
12683            )
12684        };
12685
12686        let icon_size = buttons(&diagnostic, cx.block_id)
12687            .into_any_element()
12688            .layout_as_root(AvailableSpace::min_size(), cx);
12689
12690        h_flex()
12691            .id(cx.block_id)
12692            .group(group_id.clone())
12693            .relative()
12694            .size_full()
12695            .pl(cx.gutter_dimensions.width)
12696            .w(cx.max_width + cx.gutter_dimensions.width)
12697            .child(
12698                div()
12699                    .flex()
12700                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
12701                    .flex_shrink(),
12702            )
12703            .child(buttons(&diagnostic, cx.block_id))
12704            .child(div().flex().flex_shrink_0().child(
12705                StyledText::new(text_without_backticks.clone()).with_highlights(
12706                    &text_style,
12707                    code_ranges.iter().map(|range| {
12708                        (
12709                            range.clone(),
12710                            HighlightStyle {
12711                                font_weight: Some(FontWeight::BOLD),
12712                                ..Default::default()
12713                            },
12714                        )
12715                    }),
12716                ),
12717            ))
12718            .into_any_element()
12719    })
12720}
12721
12722pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
12723    let mut text_without_backticks = String::new();
12724    let mut code_ranges = Vec::new();
12725
12726    if let Some(source) = &diagnostic.source {
12727        text_without_backticks.push_str(&source);
12728        code_ranges.push(0..source.len());
12729        text_without_backticks.push_str(": ");
12730    }
12731
12732    let mut prev_offset = 0;
12733    let mut in_code_block = false;
12734    for (ix, _) in diagnostic
12735        .message
12736        .match_indices('`')
12737        .chain([(diagnostic.message.len(), "")])
12738    {
12739        let prev_len = text_without_backticks.len();
12740        text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
12741        prev_offset = ix + 1;
12742        if in_code_block {
12743            code_ranges.push(prev_len..text_without_backticks.len());
12744        }
12745        in_code_block = !in_code_block;
12746    }
12747
12748    (text_without_backticks.into(), code_ranges)
12749}
12750
12751fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
12752    match severity {
12753        DiagnosticSeverity::ERROR => colors.error,
12754        DiagnosticSeverity::WARNING => colors.warning,
12755        DiagnosticSeverity::INFORMATION => colors.info,
12756        DiagnosticSeverity::HINT => colors.info,
12757        _ => colors.ignored,
12758    }
12759}
12760
12761pub fn styled_runs_for_code_label<'a>(
12762    label: &'a CodeLabel,
12763    syntax_theme: &'a theme::SyntaxTheme,
12764) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
12765    let fade_out = HighlightStyle {
12766        fade_out: Some(0.35),
12767        ..Default::default()
12768    };
12769
12770    let mut prev_end = label.filter_range.end;
12771    label
12772        .runs
12773        .iter()
12774        .enumerate()
12775        .flat_map(move |(ix, (range, highlight_id))| {
12776            let style = if let Some(style) = highlight_id.style(syntax_theme) {
12777                style
12778            } else {
12779                return Default::default();
12780            };
12781            let mut muted_style = style;
12782            muted_style.highlight(fade_out);
12783
12784            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
12785            if range.start >= label.filter_range.end {
12786                if range.start > prev_end {
12787                    runs.push((prev_end..range.start, fade_out));
12788                }
12789                runs.push((range.clone(), muted_style));
12790            } else if range.end <= label.filter_range.end {
12791                runs.push((range.clone(), style));
12792            } else {
12793                runs.push((range.start..label.filter_range.end, style));
12794                runs.push((label.filter_range.end..range.end, muted_style));
12795            }
12796            prev_end = cmp::max(prev_end, range.end);
12797
12798            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
12799                runs.push((prev_end..label.text.len(), fade_out));
12800            }
12801
12802            runs
12803        })
12804}
12805
12806pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
12807    let mut prev_index = 0;
12808    let mut prev_codepoint: Option<char> = None;
12809    text.char_indices()
12810        .chain([(text.len(), '\0')])
12811        .filter_map(move |(index, codepoint)| {
12812            let prev_codepoint = prev_codepoint.replace(codepoint)?;
12813            let is_boundary = index == text.len()
12814                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
12815                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
12816            if is_boundary {
12817                let chunk = &text[prev_index..index];
12818                prev_index = index;
12819                Some(chunk)
12820            } else {
12821                None
12822            }
12823        })
12824}
12825
12826pub trait RangeToAnchorExt {
12827    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
12828}
12829
12830impl<T: ToOffset> RangeToAnchorExt for Range<T> {
12831    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
12832        let start_offset = self.start.to_offset(snapshot);
12833        let end_offset = self.end.to_offset(snapshot);
12834        if start_offset == end_offset {
12835            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
12836        } else {
12837            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
12838        }
12839    }
12840}
12841
12842pub trait RowExt {
12843    fn as_f32(&self) -> f32;
12844
12845    fn next_row(&self) -> Self;
12846
12847    fn previous_row(&self) -> Self;
12848
12849    fn minus(&self, other: Self) -> u32;
12850}
12851
12852impl RowExt for DisplayRow {
12853    fn as_f32(&self) -> f32 {
12854        self.0 as f32
12855    }
12856
12857    fn next_row(&self) -> Self {
12858        Self(self.0 + 1)
12859    }
12860
12861    fn previous_row(&self) -> Self {
12862        Self(self.0.saturating_sub(1))
12863    }
12864
12865    fn minus(&self, other: Self) -> u32 {
12866        self.0 - other.0
12867    }
12868}
12869
12870impl RowExt for MultiBufferRow {
12871    fn as_f32(&self) -> f32 {
12872        self.0 as f32
12873    }
12874
12875    fn next_row(&self) -> Self {
12876        Self(self.0 + 1)
12877    }
12878
12879    fn previous_row(&self) -> Self {
12880        Self(self.0.saturating_sub(1))
12881    }
12882
12883    fn minus(&self, other: Self) -> u32 {
12884        self.0 - other.0
12885    }
12886}
12887
12888trait RowRangeExt {
12889    type Row;
12890
12891    fn len(&self) -> usize;
12892
12893    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
12894}
12895
12896impl RowRangeExt for Range<MultiBufferRow> {
12897    type Row = MultiBufferRow;
12898
12899    fn len(&self) -> usize {
12900        (self.end.0 - self.start.0) as usize
12901    }
12902
12903    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
12904        (self.start.0..self.end.0).map(MultiBufferRow)
12905    }
12906}
12907
12908impl RowRangeExt for Range<DisplayRow> {
12909    type Row = DisplayRow;
12910
12911    fn len(&self) -> usize {
12912        (self.end.0 - self.start.0) as usize
12913    }
12914
12915    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
12916        (self.start.0..self.end.0).map(DisplayRow)
12917    }
12918}
12919
12920fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
12921    if hunk.diff_base_byte_range.is_empty() {
12922        DiffHunkStatus::Added
12923    } else if hunk.associated_range.is_empty() {
12924        DiffHunkStatus::Removed
12925    } else {
12926        DiffHunkStatus::Modified
12927    }
12928}