editor.rs

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