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