editor.rs

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