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        let selection_count = self.selections.count();
 6544        let first_selection = self.selections.first_anchor();
 6545
 6546        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6547            let line_mode = s.line_mode;
 6548            s.move_with(|map, selection| {
 6549                if !selection.is_empty() && !line_mode {
 6550                    selection.goal = SelectionGoal::None;
 6551                }
 6552                let (cursor, goal) = movement::up(
 6553                    map,
 6554                    selection.start,
 6555                    selection.goal,
 6556                    false,
 6557                    &text_layout_details,
 6558                );
 6559                selection.collapse_to(cursor, goal);
 6560            });
 6561        });
 6562
 6563        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6564        {
 6565            cx.propagate();
 6566        }
 6567    }
 6568
 6569    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 6570        if self.take_rename(true, cx).is_some() {
 6571            return;
 6572        }
 6573
 6574        if matches!(self.mode, EditorMode::SingleLine) {
 6575            cx.propagate();
 6576            return;
 6577        }
 6578
 6579        let text_layout_details = &self.text_layout_details(cx);
 6580
 6581        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6582            let line_mode = s.line_mode;
 6583            s.move_with(|map, selection| {
 6584                if !selection.is_empty() && !line_mode {
 6585                    selection.goal = SelectionGoal::None;
 6586                }
 6587                let (cursor, goal) = movement::up_by_rows(
 6588                    map,
 6589                    selection.start,
 6590                    action.lines,
 6591                    selection.goal,
 6592                    false,
 6593                    &text_layout_details,
 6594                );
 6595                selection.collapse_to(cursor, goal);
 6596            });
 6597        })
 6598    }
 6599
 6600    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 6601        if self.take_rename(true, cx).is_some() {
 6602            return;
 6603        }
 6604
 6605        if matches!(self.mode, EditorMode::SingleLine) {
 6606            cx.propagate();
 6607            return;
 6608        }
 6609
 6610        let text_layout_details = &self.text_layout_details(cx);
 6611
 6612        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6613            let line_mode = s.line_mode;
 6614            s.move_with(|map, selection| {
 6615                if !selection.is_empty() && !line_mode {
 6616                    selection.goal = SelectionGoal::None;
 6617                }
 6618                let (cursor, goal) = movement::down_by_rows(
 6619                    map,
 6620                    selection.start,
 6621                    action.lines,
 6622                    selection.goal,
 6623                    false,
 6624                    &text_layout_details,
 6625                );
 6626                selection.collapse_to(cursor, goal);
 6627            });
 6628        })
 6629    }
 6630
 6631    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 6632        let text_layout_details = &self.text_layout_details(cx);
 6633        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6634            s.move_heads_with(|map, head, goal| {
 6635                movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6636            })
 6637        })
 6638    }
 6639
 6640    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 6641        let text_layout_details = &self.text_layout_details(cx);
 6642        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6643            s.move_heads_with(|map, head, goal| {
 6644                movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6645            })
 6646        })
 6647    }
 6648
 6649    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 6650        if self.take_rename(true, cx).is_some() {
 6651            return;
 6652        }
 6653
 6654        if matches!(self.mode, EditorMode::SingleLine) {
 6655            cx.propagate();
 6656            return;
 6657        }
 6658
 6659        let row_count = if let Some(row_count) = self.visible_line_count() {
 6660            row_count as u32 - 1
 6661        } else {
 6662            return;
 6663        };
 6664
 6665        let autoscroll = if action.center_cursor {
 6666            Autoscroll::center()
 6667        } else {
 6668            Autoscroll::fit()
 6669        };
 6670
 6671        let text_layout_details = &self.text_layout_details(cx);
 6672
 6673        self.change_selections(Some(autoscroll), cx, |s| {
 6674            let line_mode = s.line_mode;
 6675            s.move_with(|map, selection| {
 6676                if !selection.is_empty() && !line_mode {
 6677                    selection.goal = SelectionGoal::None;
 6678                }
 6679                let (cursor, goal) = movement::up_by_rows(
 6680                    map,
 6681                    selection.end,
 6682                    row_count,
 6683                    selection.goal,
 6684                    false,
 6685                    &text_layout_details,
 6686                );
 6687                selection.collapse_to(cursor, goal);
 6688            });
 6689        });
 6690    }
 6691
 6692    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 6693        let text_layout_details = &self.text_layout_details(cx);
 6694        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6695            s.move_heads_with(|map, head, goal| {
 6696                movement::up(map, head, goal, false, &text_layout_details)
 6697            })
 6698        })
 6699    }
 6700
 6701    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 6702        self.take_rename(true, cx);
 6703
 6704        if self.mode == EditorMode::SingleLine {
 6705            cx.propagate();
 6706            return;
 6707        }
 6708
 6709        let text_layout_details = &self.text_layout_details(cx);
 6710        let selection_count = self.selections.count();
 6711        let first_selection = self.selections.first_anchor();
 6712
 6713        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6714            let line_mode = s.line_mode;
 6715            s.move_with(|map, selection| {
 6716                if !selection.is_empty() && !line_mode {
 6717                    selection.goal = SelectionGoal::None;
 6718                }
 6719                let (cursor, goal) = movement::down(
 6720                    map,
 6721                    selection.end,
 6722                    selection.goal,
 6723                    false,
 6724                    &text_layout_details,
 6725                );
 6726                selection.collapse_to(cursor, goal);
 6727            });
 6728        });
 6729
 6730        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6731        {
 6732            cx.propagate();
 6733        }
 6734    }
 6735
 6736    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 6737        if self.take_rename(true, cx).is_some() {
 6738            return;
 6739        }
 6740
 6741        if self
 6742            .context_menu
 6743            .write()
 6744            .as_mut()
 6745            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 6746            .unwrap_or(false)
 6747        {
 6748            return;
 6749        }
 6750
 6751        if matches!(self.mode, EditorMode::SingleLine) {
 6752            cx.propagate();
 6753            return;
 6754        }
 6755
 6756        let row_count = if let Some(row_count) = self.visible_line_count() {
 6757            row_count as u32 - 1
 6758        } else {
 6759            return;
 6760        };
 6761
 6762        let autoscroll = if action.center_cursor {
 6763            Autoscroll::center()
 6764        } else {
 6765            Autoscroll::fit()
 6766        };
 6767
 6768        let text_layout_details = &self.text_layout_details(cx);
 6769        self.change_selections(Some(autoscroll), cx, |s| {
 6770            let line_mode = s.line_mode;
 6771            s.move_with(|map, selection| {
 6772                if !selection.is_empty() && !line_mode {
 6773                    selection.goal = SelectionGoal::None;
 6774                }
 6775                let (cursor, goal) = movement::down_by_rows(
 6776                    map,
 6777                    selection.end,
 6778                    row_count,
 6779                    selection.goal,
 6780                    false,
 6781                    &text_layout_details,
 6782                );
 6783                selection.collapse_to(cursor, goal);
 6784            });
 6785        });
 6786    }
 6787
 6788    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 6789        let text_layout_details = &self.text_layout_details(cx);
 6790        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6791            s.move_heads_with(|map, head, goal| {
 6792                movement::down(map, head, goal, false, &text_layout_details)
 6793            })
 6794        });
 6795    }
 6796
 6797    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 6798        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6799            context_menu.select_first(self.project.as_ref(), cx);
 6800        }
 6801    }
 6802
 6803    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 6804        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6805            context_menu.select_prev(self.project.as_ref(), cx);
 6806        }
 6807    }
 6808
 6809    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 6810        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6811            context_menu.select_next(self.project.as_ref(), cx);
 6812        }
 6813    }
 6814
 6815    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 6816        if let Some(context_menu) = self.context_menu.write().as_mut() {
 6817            context_menu.select_last(self.project.as_ref(), cx);
 6818        }
 6819    }
 6820
 6821    pub fn move_to_previous_word_start(
 6822        &mut self,
 6823        _: &MoveToPreviousWordStart,
 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_word_start(map, head),
 6830                    SelectionGoal::None,
 6831                )
 6832            });
 6833        })
 6834    }
 6835
 6836    pub fn move_to_previous_subword_start(
 6837        &mut self,
 6838        _: &MoveToPreviousSubwordStart,
 6839        cx: &mut ViewContext<Self>,
 6840    ) {
 6841        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6842            s.move_cursors_with(|map, head, _| {
 6843                (
 6844                    movement::previous_subword_start(map, head),
 6845                    SelectionGoal::None,
 6846                )
 6847            });
 6848        })
 6849    }
 6850
 6851    pub fn select_to_previous_word_start(
 6852        &mut self,
 6853        _: &SelectToPreviousWordStart,
 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_word_start(map, head),
 6860                    SelectionGoal::None,
 6861                )
 6862            });
 6863        })
 6864    }
 6865
 6866    pub fn select_to_previous_subword_start(
 6867        &mut self,
 6868        _: &SelectToPreviousSubwordStart,
 6869        cx: &mut ViewContext<Self>,
 6870    ) {
 6871        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6872            s.move_heads_with(|map, head, _| {
 6873                (
 6874                    movement::previous_subword_start(map, head),
 6875                    SelectionGoal::None,
 6876                )
 6877            });
 6878        })
 6879    }
 6880
 6881    pub fn delete_to_previous_word_start(
 6882        &mut self,
 6883        _: &DeleteToPreviousWordStart,
 6884        cx: &mut ViewContext<Self>,
 6885    ) {
 6886        self.transact(cx, |this, cx| {
 6887            this.select_autoclose_pair(cx);
 6888            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6889                let line_mode = s.line_mode;
 6890                s.move_with(|map, selection| {
 6891                    if selection.is_empty() && !line_mode {
 6892                        let cursor = movement::previous_word_start(map, selection.head());
 6893                        selection.set_head(cursor, SelectionGoal::None);
 6894                    }
 6895                });
 6896            });
 6897            this.insert("", cx);
 6898        });
 6899    }
 6900
 6901    pub fn delete_to_previous_subword_start(
 6902        &mut self,
 6903        _: &DeleteToPreviousSubwordStart,
 6904        cx: &mut ViewContext<Self>,
 6905    ) {
 6906        self.transact(cx, |this, cx| {
 6907            this.select_autoclose_pair(cx);
 6908            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6909                let line_mode = s.line_mode;
 6910                s.move_with(|map, selection| {
 6911                    if selection.is_empty() && !line_mode {
 6912                        let cursor = movement::previous_subword_start(map, selection.head());
 6913                        selection.set_head(cursor, SelectionGoal::None);
 6914                    }
 6915                });
 6916            });
 6917            this.insert("", cx);
 6918        });
 6919    }
 6920
 6921    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 6922        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6923            s.move_cursors_with(|map, head, _| {
 6924                (movement::next_word_end(map, head), SelectionGoal::None)
 6925            });
 6926        })
 6927    }
 6928
 6929    pub fn move_to_next_subword_end(
 6930        &mut self,
 6931        _: &MoveToNextSubwordEnd,
 6932        cx: &mut ViewContext<Self>,
 6933    ) {
 6934        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6935            s.move_cursors_with(|map, head, _| {
 6936                (movement::next_subword_end(map, head), SelectionGoal::None)
 6937            });
 6938        })
 6939    }
 6940
 6941    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 6942        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6943            s.move_heads_with(|map, head, _| {
 6944                (movement::next_word_end(map, head), SelectionGoal::None)
 6945            });
 6946        })
 6947    }
 6948
 6949    pub fn select_to_next_subword_end(
 6950        &mut self,
 6951        _: &SelectToNextSubwordEnd,
 6952        cx: &mut ViewContext<Self>,
 6953    ) {
 6954        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6955            s.move_heads_with(|map, head, _| {
 6956                (movement::next_subword_end(map, head), SelectionGoal::None)
 6957            });
 6958        })
 6959    }
 6960
 6961    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
 6962        self.transact(cx, |this, cx| {
 6963            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6964                let line_mode = s.line_mode;
 6965                s.move_with(|map, selection| {
 6966                    if selection.is_empty() && !line_mode {
 6967                        let cursor = movement::next_word_end(map, selection.head());
 6968                        selection.set_head(cursor, SelectionGoal::None);
 6969                    }
 6970                });
 6971            });
 6972            this.insert("", cx);
 6973        });
 6974    }
 6975
 6976    pub fn delete_to_next_subword_end(
 6977        &mut self,
 6978        _: &DeleteToNextSubwordEnd,
 6979        cx: &mut ViewContext<Self>,
 6980    ) {
 6981        self.transact(cx, |this, cx| {
 6982            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6983                s.move_with(|map, selection| {
 6984                    if selection.is_empty() {
 6985                        let cursor = movement::next_subword_end(map, selection.head());
 6986                        selection.set_head(cursor, SelectionGoal::None);
 6987                    }
 6988                });
 6989            });
 6990            this.insert("", cx);
 6991        });
 6992    }
 6993
 6994    pub fn move_to_beginning_of_line(
 6995        &mut self,
 6996        action: &MoveToBeginningOfLine,
 6997        cx: &mut ViewContext<Self>,
 6998    ) {
 6999        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7000            s.move_cursors_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 select_to_beginning_of_line(
 7010        &mut self,
 7011        action: &SelectToBeginningOfLine,
 7012        cx: &mut ViewContext<Self>,
 7013    ) {
 7014        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7015            s.move_heads_with(|map, head, _| {
 7016                (
 7017                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7018                    SelectionGoal::None,
 7019                )
 7020            });
 7021        });
 7022    }
 7023
 7024    pub fn delete_to_beginning_of_line(
 7025        &mut self,
 7026        _: &DeleteToBeginningOfLine,
 7027        cx: &mut ViewContext<Self>,
 7028    ) {
 7029        self.transact(cx, |this, cx| {
 7030            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7031                s.move_with(|_, selection| {
 7032                    selection.reversed = true;
 7033                });
 7034            });
 7035
 7036            this.select_to_beginning_of_line(
 7037                &SelectToBeginningOfLine {
 7038                    stop_at_soft_wraps: false,
 7039                },
 7040                cx,
 7041            );
 7042            this.backspace(&Backspace, cx);
 7043        });
 7044    }
 7045
 7046    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7047        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7048            s.move_cursors_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 select_to_end_of_line(
 7058        &mut self,
 7059        action: &SelectToEndOfLine,
 7060        cx: &mut ViewContext<Self>,
 7061    ) {
 7062        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7063            s.move_heads_with(|map, head, _| {
 7064                (
 7065                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7066                    SelectionGoal::None,
 7067                )
 7068            });
 7069        })
 7070    }
 7071
 7072    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7073        self.transact(cx, |this, cx| {
 7074            this.select_to_end_of_line(
 7075                &SelectToEndOfLine {
 7076                    stop_at_soft_wraps: false,
 7077                },
 7078                cx,
 7079            );
 7080            this.delete(&Delete, cx);
 7081        });
 7082    }
 7083
 7084    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7085        self.transact(cx, |this, cx| {
 7086            this.select_to_end_of_line(
 7087                &SelectToEndOfLine {
 7088                    stop_at_soft_wraps: false,
 7089                },
 7090                cx,
 7091            );
 7092            this.cut(&Cut, cx);
 7093        });
 7094    }
 7095
 7096    pub fn move_to_start_of_paragraph(
 7097        &mut self,
 7098        _: &MoveToStartOfParagraph,
 7099        cx: &mut ViewContext<Self>,
 7100    ) {
 7101        if matches!(self.mode, EditorMode::SingleLine) {
 7102            cx.propagate();
 7103            return;
 7104        }
 7105
 7106        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7107            s.move_with(|map, selection| {
 7108                selection.collapse_to(
 7109                    movement::start_of_paragraph(map, selection.head(), 1),
 7110                    SelectionGoal::None,
 7111                )
 7112            });
 7113        })
 7114    }
 7115
 7116    pub fn move_to_end_of_paragraph(
 7117        &mut self,
 7118        _: &MoveToEndOfParagraph,
 7119        cx: &mut ViewContext<Self>,
 7120    ) {
 7121        if matches!(self.mode, EditorMode::SingleLine) {
 7122            cx.propagate();
 7123            return;
 7124        }
 7125
 7126        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7127            s.move_with(|map, selection| {
 7128                selection.collapse_to(
 7129                    movement::end_of_paragraph(map, selection.head(), 1),
 7130                    SelectionGoal::None,
 7131                )
 7132            });
 7133        })
 7134    }
 7135
 7136    pub fn select_to_start_of_paragraph(
 7137        &mut self,
 7138        _: &SelectToStartOfParagraph,
 7139        cx: &mut ViewContext<Self>,
 7140    ) {
 7141        if matches!(self.mode, EditorMode::SingleLine) {
 7142            cx.propagate();
 7143            return;
 7144        }
 7145
 7146        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7147            s.move_heads_with(|map, head, _| {
 7148                (
 7149                    movement::start_of_paragraph(map, head, 1),
 7150                    SelectionGoal::None,
 7151                )
 7152            });
 7153        })
 7154    }
 7155
 7156    pub fn select_to_end_of_paragraph(
 7157        &mut self,
 7158        _: &SelectToEndOfParagraph,
 7159        cx: &mut ViewContext<Self>,
 7160    ) {
 7161        if matches!(self.mode, EditorMode::SingleLine) {
 7162            cx.propagate();
 7163            return;
 7164        }
 7165
 7166        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7167            s.move_heads_with(|map, head, _| {
 7168                (
 7169                    movement::end_of_paragraph(map, head, 1),
 7170                    SelectionGoal::None,
 7171                )
 7172            });
 7173        })
 7174    }
 7175
 7176    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7177        if matches!(self.mode, EditorMode::SingleLine) {
 7178            cx.propagate();
 7179            return;
 7180        }
 7181
 7182        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7183            s.select_ranges(vec![0..0]);
 7184        });
 7185    }
 7186
 7187    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7188        let mut selection = self.selections.last::<Point>(cx);
 7189        selection.set_head(Point::zero(), SelectionGoal::None);
 7190
 7191        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7192            s.select(vec![selection]);
 7193        });
 7194    }
 7195
 7196    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7197        if matches!(self.mode, EditorMode::SingleLine) {
 7198            cx.propagate();
 7199            return;
 7200        }
 7201
 7202        let cursor = self.buffer.read(cx).read(cx).len();
 7203        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7204            s.select_ranges(vec![cursor..cursor])
 7205        });
 7206    }
 7207
 7208    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7209        self.nav_history = nav_history;
 7210    }
 7211
 7212    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7213        self.nav_history.as_ref()
 7214    }
 7215
 7216    fn push_to_nav_history(
 7217        &mut self,
 7218        cursor_anchor: Anchor,
 7219        new_position: Option<Point>,
 7220        cx: &mut ViewContext<Self>,
 7221    ) {
 7222        if let Some(nav_history) = self.nav_history.as_mut() {
 7223            let buffer = self.buffer.read(cx).read(cx);
 7224            let cursor_position = cursor_anchor.to_point(&buffer);
 7225            let scroll_state = self.scroll_manager.anchor();
 7226            let scroll_top_row = scroll_state.top_row(&buffer);
 7227            drop(buffer);
 7228
 7229            if let Some(new_position) = new_position {
 7230                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7231                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7232                    return;
 7233                }
 7234            }
 7235
 7236            nav_history.push(
 7237                Some(NavigationData {
 7238                    cursor_anchor,
 7239                    cursor_position,
 7240                    scroll_anchor: scroll_state,
 7241                    scroll_top_row,
 7242                }),
 7243                cx,
 7244            );
 7245        }
 7246    }
 7247
 7248    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7249        let buffer = self.buffer.read(cx).snapshot(cx);
 7250        let mut selection = self.selections.first::<usize>(cx);
 7251        selection.set_head(buffer.len(), SelectionGoal::None);
 7252        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7253            s.select(vec![selection]);
 7254        });
 7255    }
 7256
 7257    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7258        let end = self.buffer.read(cx).read(cx).len();
 7259        self.change_selections(None, cx, |s| {
 7260            s.select_ranges(vec![0..end]);
 7261        });
 7262    }
 7263
 7264    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7265        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7266        let mut selections = self.selections.all::<Point>(cx);
 7267        let max_point = display_map.buffer_snapshot.max_point();
 7268        for selection in &mut selections {
 7269            let rows = selection.spanned_rows(true, &display_map);
 7270            selection.start = Point::new(rows.start.0, 0);
 7271            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7272            selection.reversed = false;
 7273        }
 7274        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7275            s.select(selections);
 7276        });
 7277    }
 7278
 7279    pub fn split_selection_into_lines(
 7280        &mut self,
 7281        _: &SplitSelectionIntoLines,
 7282        cx: &mut ViewContext<Self>,
 7283    ) {
 7284        let mut to_unfold = Vec::new();
 7285        let mut new_selection_ranges = Vec::new();
 7286        {
 7287            let selections = self.selections.all::<Point>(cx);
 7288            let buffer = self.buffer.read(cx).read(cx);
 7289            for selection in selections {
 7290                for row in selection.start.row..selection.end.row {
 7291                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7292                    new_selection_ranges.push(cursor..cursor);
 7293                }
 7294                new_selection_ranges.push(selection.end..selection.end);
 7295                to_unfold.push(selection.start..selection.end);
 7296            }
 7297        }
 7298        self.unfold_ranges(to_unfold, true, true, cx);
 7299        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7300            s.select_ranges(new_selection_ranges);
 7301        });
 7302    }
 7303
 7304    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7305        self.add_selection(true, cx);
 7306    }
 7307
 7308    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7309        self.add_selection(false, cx);
 7310    }
 7311
 7312    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7313        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7314        let mut selections = self.selections.all::<Point>(cx);
 7315        let text_layout_details = self.text_layout_details(cx);
 7316        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7317            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7318            let range = oldest_selection.display_range(&display_map).sorted();
 7319
 7320            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7321            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7322            let positions = start_x.min(end_x)..start_x.max(end_x);
 7323
 7324            selections.clear();
 7325            let mut stack = Vec::new();
 7326            for row in range.start.row().0..=range.end.row().0 {
 7327                if let Some(selection) = self.selections.build_columnar_selection(
 7328                    &display_map,
 7329                    DisplayRow(row),
 7330                    &positions,
 7331                    oldest_selection.reversed,
 7332                    &text_layout_details,
 7333                ) {
 7334                    stack.push(selection.id);
 7335                    selections.push(selection);
 7336                }
 7337            }
 7338
 7339            if above {
 7340                stack.reverse();
 7341            }
 7342
 7343            AddSelectionsState { above, stack }
 7344        });
 7345
 7346        let last_added_selection = *state.stack.last().unwrap();
 7347        let mut new_selections = Vec::new();
 7348        if above == state.above {
 7349            let end_row = if above {
 7350                DisplayRow(0)
 7351            } else {
 7352                display_map.max_point().row()
 7353            };
 7354
 7355            'outer: for selection in selections {
 7356                if selection.id == last_added_selection {
 7357                    let range = selection.display_range(&display_map).sorted();
 7358                    debug_assert_eq!(range.start.row(), range.end.row());
 7359                    let mut row = range.start.row();
 7360                    let positions =
 7361                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7362                            px(start)..px(end)
 7363                        } else {
 7364                            let start_x =
 7365                                display_map.x_for_display_point(range.start, &text_layout_details);
 7366                            let end_x =
 7367                                display_map.x_for_display_point(range.end, &text_layout_details);
 7368                            start_x.min(end_x)..start_x.max(end_x)
 7369                        };
 7370
 7371                    while row != end_row {
 7372                        if above {
 7373                            row.0 -= 1;
 7374                        } else {
 7375                            row.0 += 1;
 7376                        }
 7377
 7378                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7379                            &display_map,
 7380                            row,
 7381                            &positions,
 7382                            selection.reversed,
 7383                            &text_layout_details,
 7384                        ) {
 7385                            state.stack.push(new_selection.id);
 7386                            if above {
 7387                                new_selections.push(new_selection);
 7388                                new_selections.push(selection);
 7389                            } else {
 7390                                new_selections.push(selection);
 7391                                new_selections.push(new_selection);
 7392                            }
 7393
 7394                            continue 'outer;
 7395                        }
 7396                    }
 7397                }
 7398
 7399                new_selections.push(selection);
 7400            }
 7401        } else {
 7402            new_selections = selections;
 7403            new_selections.retain(|s| s.id != last_added_selection);
 7404            state.stack.pop();
 7405        }
 7406
 7407        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7408            s.select(new_selections);
 7409        });
 7410        if state.stack.len() > 1 {
 7411            self.add_selections_state = Some(state);
 7412        }
 7413    }
 7414
 7415    pub fn select_next_match_internal(
 7416        &mut self,
 7417        display_map: &DisplaySnapshot,
 7418        replace_newest: bool,
 7419        autoscroll: Option<Autoscroll>,
 7420        cx: &mut ViewContext<Self>,
 7421    ) -> Result<()> {
 7422        fn select_next_match_ranges(
 7423            this: &mut Editor,
 7424            range: Range<usize>,
 7425            replace_newest: bool,
 7426            auto_scroll: Option<Autoscroll>,
 7427            cx: &mut ViewContext<Editor>,
 7428        ) {
 7429            this.unfold_ranges([range.clone()], false, true, cx);
 7430            this.change_selections(auto_scroll, cx, |s| {
 7431                if replace_newest {
 7432                    s.delete(s.newest_anchor().id);
 7433                }
 7434                s.insert_range(range.clone());
 7435            });
 7436        }
 7437
 7438        let buffer = &display_map.buffer_snapshot;
 7439        let mut selections = self.selections.all::<usize>(cx);
 7440        if let Some(mut select_next_state) = self.select_next_state.take() {
 7441            let query = &select_next_state.query;
 7442            if !select_next_state.done {
 7443                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7444                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7445                let mut next_selected_range = None;
 7446
 7447                let bytes_after_last_selection =
 7448                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7449                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7450                let query_matches = query
 7451                    .stream_find_iter(bytes_after_last_selection)
 7452                    .map(|result| (last_selection.end, result))
 7453                    .chain(
 7454                        query
 7455                            .stream_find_iter(bytes_before_first_selection)
 7456                            .map(|result| (0, result)),
 7457                    );
 7458
 7459                for (start_offset, query_match) in query_matches {
 7460                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7461                    let offset_range =
 7462                        start_offset + query_match.start()..start_offset + query_match.end();
 7463                    let display_range = offset_range.start.to_display_point(&display_map)
 7464                        ..offset_range.end.to_display_point(&display_map);
 7465
 7466                    if !select_next_state.wordwise
 7467                        || (!movement::is_inside_word(&display_map, display_range.start)
 7468                            && !movement::is_inside_word(&display_map, display_range.end))
 7469                    {
 7470                        // TODO: This is n^2, because we might check all the selections
 7471                        if !selections
 7472                            .iter()
 7473                            .any(|selection| selection.range().overlaps(&offset_range))
 7474                        {
 7475                            next_selected_range = Some(offset_range);
 7476                            break;
 7477                        }
 7478                    }
 7479                }
 7480
 7481                if let Some(next_selected_range) = next_selected_range {
 7482                    select_next_match_ranges(
 7483                        self,
 7484                        next_selected_range,
 7485                        replace_newest,
 7486                        autoscroll,
 7487                        cx,
 7488                    );
 7489                } else {
 7490                    select_next_state.done = true;
 7491                }
 7492            }
 7493
 7494            self.select_next_state = Some(select_next_state);
 7495        } else {
 7496            let mut only_carets = true;
 7497            let mut same_text_selected = true;
 7498            let mut selected_text = None;
 7499
 7500            let mut selections_iter = selections.iter().peekable();
 7501            while let Some(selection) = selections_iter.next() {
 7502                if selection.start != selection.end {
 7503                    only_carets = false;
 7504                }
 7505
 7506                if same_text_selected {
 7507                    if selected_text.is_none() {
 7508                        selected_text =
 7509                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7510                    }
 7511
 7512                    if let Some(next_selection) = selections_iter.peek() {
 7513                        if next_selection.range().len() == selection.range().len() {
 7514                            let next_selected_text = buffer
 7515                                .text_for_range(next_selection.range())
 7516                                .collect::<String>();
 7517                            if Some(next_selected_text) != selected_text {
 7518                                same_text_selected = false;
 7519                                selected_text = None;
 7520                            }
 7521                        } else {
 7522                            same_text_selected = false;
 7523                            selected_text = None;
 7524                        }
 7525                    }
 7526                }
 7527            }
 7528
 7529            if only_carets {
 7530                for selection in &mut selections {
 7531                    let word_range = movement::surrounding_word(
 7532                        &display_map,
 7533                        selection.start.to_display_point(&display_map),
 7534                    );
 7535                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7536                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7537                    selection.goal = SelectionGoal::None;
 7538                    selection.reversed = false;
 7539                    select_next_match_ranges(
 7540                        self,
 7541                        selection.start..selection.end,
 7542                        replace_newest,
 7543                        autoscroll,
 7544                        cx,
 7545                    );
 7546                }
 7547
 7548                if selections.len() == 1 {
 7549                    let selection = selections
 7550                        .last()
 7551                        .expect("ensured that there's only one selection");
 7552                    let query = buffer
 7553                        .text_for_range(selection.start..selection.end)
 7554                        .collect::<String>();
 7555                    let is_empty = query.is_empty();
 7556                    let select_state = SelectNextState {
 7557                        query: AhoCorasick::new(&[query])?,
 7558                        wordwise: true,
 7559                        done: is_empty,
 7560                    };
 7561                    self.select_next_state = Some(select_state);
 7562                } else {
 7563                    self.select_next_state = None;
 7564                }
 7565            } else if let Some(selected_text) = selected_text {
 7566                self.select_next_state = Some(SelectNextState {
 7567                    query: AhoCorasick::new(&[selected_text])?,
 7568                    wordwise: false,
 7569                    done: false,
 7570                });
 7571                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 7572            }
 7573        }
 7574        Ok(())
 7575    }
 7576
 7577    pub fn select_all_matches(
 7578        &mut self,
 7579        _action: &SelectAllMatches,
 7580        cx: &mut ViewContext<Self>,
 7581    ) -> Result<()> {
 7582        self.push_to_selection_history();
 7583        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7584
 7585        self.select_next_match_internal(&display_map, false, None, cx)?;
 7586        let Some(select_next_state) = self.select_next_state.as_mut() else {
 7587            return Ok(());
 7588        };
 7589        if select_next_state.done {
 7590            return Ok(());
 7591        }
 7592
 7593        let mut new_selections = self.selections.all::<usize>(cx);
 7594
 7595        let buffer = &display_map.buffer_snapshot;
 7596        let query_matches = select_next_state
 7597            .query
 7598            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 7599
 7600        for query_match in query_matches {
 7601            let query_match = query_match.unwrap(); // can only fail due to I/O
 7602            let offset_range = query_match.start()..query_match.end();
 7603            let display_range = offset_range.start.to_display_point(&display_map)
 7604                ..offset_range.end.to_display_point(&display_map);
 7605
 7606            if !select_next_state.wordwise
 7607                || (!movement::is_inside_word(&display_map, display_range.start)
 7608                    && !movement::is_inside_word(&display_map, display_range.end))
 7609            {
 7610                self.selections.change_with(cx, |selections| {
 7611                    new_selections.push(Selection {
 7612                        id: selections.new_selection_id(),
 7613                        start: offset_range.start,
 7614                        end: offset_range.end,
 7615                        reversed: false,
 7616                        goal: SelectionGoal::None,
 7617                    });
 7618                });
 7619            }
 7620        }
 7621
 7622        new_selections.sort_by_key(|selection| selection.start);
 7623        let mut ix = 0;
 7624        while ix + 1 < new_selections.len() {
 7625            let current_selection = &new_selections[ix];
 7626            let next_selection = &new_selections[ix + 1];
 7627            if current_selection.range().overlaps(&next_selection.range()) {
 7628                if current_selection.id < next_selection.id {
 7629                    new_selections.remove(ix + 1);
 7630                } else {
 7631                    new_selections.remove(ix);
 7632                }
 7633            } else {
 7634                ix += 1;
 7635            }
 7636        }
 7637
 7638        select_next_state.done = true;
 7639        self.unfold_ranges(
 7640            new_selections.iter().map(|selection| selection.range()),
 7641            false,
 7642            false,
 7643            cx,
 7644        );
 7645        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 7646            selections.select(new_selections)
 7647        });
 7648
 7649        Ok(())
 7650    }
 7651
 7652    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 7653        self.push_to_selection_history();
 7654        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7655        self.select_next_match_internal(
 7656            &display_map,
 7657            action.replace_newest,
 7658            Some(Autoscroll::newest()),
 7659            cx,
 7660        )?;
 7661        Ok(())
 7662    }
 7663
 7664    pub fn select_previous(
 7665        &mut self,
 7666        action: &SelectPrevious,
 7667        cx: &mut ViewContext<Self>,
 7668    ) -> Result<()> {
 7669        self.push_to_selection_history();
 7670        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7671        let buffer = &display_map.buffer_snapshot;
 7672        let mut selections = self.selections.all::<usize>(cx);
 7673        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 7674            let query = &select_prev_state.query;
 7675            if !select_prev_state.done {
 7676                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7677                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7678                let mut next_selected_range = None;
 7679                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 7680                let bytes_before_last_selection =
 7681                    buffer.reversed_bytes_in_range(0..last_selection.start);
 7682                let bytes_after_first_selection =
 7683                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 7684                let query_matches = query
 7685                    .stream_find_iter(bytes_before_last_selection)
 7686                    .map(|result| (last_selection.start, result))
 7687                    .chain(
 7688                        query
 7689                            .stream_find_iter(bytes_after_first_selection)
 7690                            .map(|result| (buffer.len(), result)),
 7691                    );
 7692                for (end_offset, query_match) in query_matches {
 7693                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7694                    let offset_range =
 7695                        end_offset - query_match.end()..end_offset - query_match.start();
 7696                    let display_range = offset_range.start.to_display_point(&display_map)
 7697                        ..offset_range.end.to_display_point(&display_map);
 7698
 7699                    if !select_prev_state.wordwise
 7700                        || (!movement::is_inside_word(&display_map, display_range.start)
 7701                            && !movement::is_inside_word(&display_map, display_range.end))
 7702                    {
 7703                        next_selected_range = Some(offset_range);
 7704                        break;
 7705                    }
 7706                }
 7707
 7708                if let Some(next_selected_range) = next_selected_range {
 7709                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 7710                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7711                        if action.replace_newest {
 7712                            s.delete(s.newest_anchor().id);
 7713                        }
 7714                        s.insert_range(next_selected_range);
 7715                    });
 7716                } else {
 7717                    select_prev_state.done = true;
 7718                }
 7719            }
 7720
 7721            self.select_prev_state = Some(select_prev_state);
 7722        } else {
 7723            let mut only_carets = true;
 7724            let mut same_text_selected = true;
 7725            let mut selected_text = None;
 7726
 7727            let mut selections_iter = selections.iter().peekable();
 7728            while let Some(selection) = selections_iter.next() {
 7729                if selection.start != selection.end {
 7730                    only_carets = false;
 7731                }
 7732
 7733                if same_text_selected {
 7734                    if selected_text.is_none() {
 7735                        selected_text =
 7736                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7737                    }
 7738
 7739                    if let Some(next_selection) = selections_iter.peek() {
 7740                        if next_selection.range().len() == selection.range().len() {
 7741                            let next_selected_text = buffer
 7742                                .text_for_range(next_selection.range())
 7743                                .collect::<String>();
 7744                            if Some(next_selected_text) != selected_text {
 7745                                same_text_selected = false;
 7746                                selected_text = None;
 7747                            }
 7748                        } else {
 7749                            same_text_selected = false;
 7750                            selected_text = None;
 7751                        }
 7752                    }
 7753                }
 7754            }
 7755
 7756            if only_carets {
 7757                for selection in &mut selections {
 7758                    let word_range = movement::surrounding_word(
 7759                        &display_map,
 7760                        selection.start.to_display_point(&display_map),
 7761                    );
 7762                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7763                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7764                    selection.goal = SelectionGoal::None;
 7765                    selection.reversed = false;
 7766                }
 7767                if selections.len() == 1 {
 7768                    let selection = selections
 7769                        .last()
 7770                        .expect("ensured that there's only one selection");
 7771                    let query = buffer
 7772                        .text_for_range(selection.start..selection.end)
 7773                        .collect::<String>();
 7774                    let is_empty = query.is_empty();
 7775                    let select_state = SelectNextState {
 7776                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 7777                        wordwise: true,
 7778                        done: is_empty,
 7779                    };
 7780                    self.select_prev_state = Some(select_state);
 7781                } else {
 7782                    self.select_prev_state = None;
 7783                }
 7784
 7785                self.unfold_ranges(
 7786                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 7787                    false,
 7788                    true,
 7789                    cx,
 7790                );
 7791                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7792                    s.select(selections);
 7793                });
 7794            } else if let Some(selected_text) = selected_text {
 7795                self.select_prev_state = Some(SelectNextState {
 7796                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 7797                    wordwise: false,
 7798                    done: false,
 7799                });
 7800                self.select_previous(action, cx)?;
 7801            }
 7802        }
 7803        Ok(())
 7804    }
 7805
 7806    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 7807        let text_layout_details = &self.text_layout_details(cx);
 7808        self.transact(cx, |this, cx| {
 7809            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 7810            let mut edits = Vec::new();
 7811            let mut selection_edit_ranges = Vec::new();
 7812            let mut last_toggled_row = None;
 7813            let snapshot = this.buffer.read(cx).read(cx);
 7814            let empty_str: Arc<str> = "".into();
 7815            let mut suffixes_inserted = Vec::new();
 7816
 7817            fn comment_prefix_range(
 7818                snapshot: &MultiBufferSnapshot,
 7819                row: MultiBufferRow,
 7820                comment_prefix: &str,
 7821                comment_prefix_whitespace: &str,
 7822            ) -> Range<Point> {
 7823                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 7824
 7825                let mut line_bytes = snapshot
 7826                    .bytes_in_range(start..snapshot.max_point())
 7827                    .flatten()
 7828                    .copied();
 7829
 7830                // If this line currently begins with the line comment prefix, then record
 7831                // the range containing the prefix.
 7832                if line_bytes
 7833                    .by_ref()
 7834                    .take(comment_prefix.len())
 7835                    .eq(comment_prefix.bytes())
 7836                {
 7837                    // Include any whitespace that matches the comment prefix.
 7838                    let matching_whitespace_len = line_bytes
 7839                        .zip(comment_prefix_whitespace.bytes())
 7840                        .take_while(|(a, b)| a == b)
 7841                        .count() as u32;
 7842                    let end = Point::new(
 7843                        start.row,
 7844                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 7845                    );
 7846                    start..end
 7847                } else {
 7848                    start..start
 7849                }
 7850            }
 7851
 7852            fn comment_suffix_range(
 7853                snapshot: &MultiBufferSnapshot,
 7854                row: MultiBufferRow,
 7855                comment_suffix: &str,
 7856                comment_suffix_has_leading_space: bool,
 7857            ) -> Range<Point> {
 7858                let end = Point::new(row.0, snapshot.line_len(row));
 7859                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 7860
 7861                let mut line_end_bytes = snapshot
 7862                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 7863                    .flatten()
 7864                    .copied();
 7865
 7866                let leading_space_len = if suffix_start_column > 0
 7867                    && line_end_bytes.next() == Some(b' ')
 7868                    && comment_suffix_has_leading_space
 7869                {
 7870                    1
 7871                } else {
 7872                    0
 7873                };
 7874
 7875                // If this line currently begins with the line comment prefix, then record
 7876                // the range containing the prefix.
 7877                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 7878                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 7879                    start..end
 7880                } else {
 7881                    end..end
 7882                }
 7883            }
 7884
 7885            // TODO: Handle selections that cross excerpts
 7886            for selection in &mut selections {
 7887                let start_column = snapshot
 7888                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 7889                    .len;
 7890                let language = if let Some(language) =
 7891                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 7892                {
 7893                    language
 7894                } else {
 7895                    continue;
 7896                };
 7897
 7898                selection_edit_ranges.clear();
 7899
 7900                // If multiple selections contain a given row, avoid processing that
 7901                // row more than once.
 7902                let mut start_row = MultiBufferRow(selection.start.row);
 7903                if last_toggled_row == Some(start_row) {
 7904                    start_row = start_row.next_row();
 7905                }
 7906                let end_row =
 7907                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 7908                        MultiBufferRow(selection.end.row - 1)
 7909                    } else {
 7910                        MultiBufferRow(selection.end.row)
 7911                    };
 7912                last_toggled_row = Some(end_row);
 7913
 7914                if start_row > end_row {
 7915                    continue;
 7916                }
 7917
 7918                // If the language has line comments, toggle those.
 7919                let full_comment_prefixes = language.line_comment_prefixes();
 7920                if !full_comment_prefixes.is_empty() {
 7921                    let first_prefix = full_comment_prefixes
 7922                        .first()
 7923                        .expect("prefixes is non-empty");
 7924                    let prefix_trimmed_lengths = full_comment_prefixes
 7925                        .iter()
 7926                        .map(|p| p.trim_end_matches(' ').len())
 7927                        .collect::<SmallVec<[usize; 4]>>();
 7928
 7929                    let mut all_selection_lines_are_comments = true;
 7930
 7931                    for row in start_row.0..=end_row.0 {
 7932                        let row = MultiBufferRow(row);
 7933                        if start_row < end_row && snapshot.is_line_blank(row) {
 7934                            continue;
 7935                        }
 7936
 7937                        let prefix_range = full_comment_prefixes
 7938                            .iter()
 7939                            .zip(prefix_trimmed_lengths.iter().copied())
 7940                            .map(|(prefix, trimmed_prefix_len)| {
 7941                                comment_prefix_range(
 7942                                    snapshot.deref(),
 7943                                    row,
 7944                                    &prefix[..trimmed_prefix_len],
 7945                                    &prefix[trimmed_prefix_len..],
 7946                                )
 7947                            })
 7948                            .max_by_key(|range| range.end.column - range.start.column)
 7949                            .expect("prefixes is non-empty");
 7950
 7951                        if prefix_range.is_empty() {
 7952                            all_selection_lines_are_comments = false;
 7953                        }
 7954
 7955                        selection_edit_ranges.push(prefix_range);
 7956                    }
 7957
 7958                    if all_selection_lines_are_comments {
 7959                        edits.extend(
 7960                            selection_edit_ranges
 7961                                .iter()
 7962                                .cloned()
 7963                                .map(|range| (range, empty_str.clone())),
 7964                        );
 7965                    } else {
 7966                        let min_column = selection_edit_ranges
 7967                            .iter()
 7968                            .map(|range| range.start.column)
 7969                            .min()
 7970                            .unwrap_or(0);
 7971                        edits.extend(selection_edit_ranges.iter().map(|range| {
 7972                            let position = Point::new(range.start.row, min_column);
 7973                            (position..position, first_prefix.clone())
 7974                        }));
 7975                    }
 7976                } else if let Some((full_comment_prefix, comment_suffix)) =
 7977                    language.block_comment_delimiters()
 7978                {
 7979                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 7980                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 7981                    let prefix_range = comment_prefix_range(
 7982                        snapshot.deref(),
 7983                        start_row,
 7984                        comment_prefix,
 7985                        comment_prefix_whitespace,
 7986                    );
 7987                    let suffix_range = comment_suffix_range(
 7988                        snapshot.deref(),
 7989                        end_row,
 7990                        comment_suffix.trim_start_matches(' '),
 7991                        comment_suffix.starts_with(' '),
 7992                    );
 7993
 7994                    if prefix_range.is_empty() || suffix_range.is_empty() {
 7995                        edits.push((
 7996                            prefix_range.start..prefix_range.start,
 7997                            full_comment_prefix.clone(),
 7998                        ));
 7999                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8000                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8001                    } else {
 8002                        edits.push((prefix_range, empty_str.clone()));
 8003                        edits.push((suffix_range, empty_str.clone()));
 8004                    }
 8005                } else {
 8006                    continue;
 8007                }
 8008            }
 8009
 8010            drop(snapshot);
 8011            this.buffer.update(cx, |buffer, cx| {
 8012                buffer.edit(edits, None, cx);
 8013            });
 8014
 8015            // Adjust selections so that they end before any comment suffixes that
 8016            // were inserted.
 8017            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8018            let mut selections = this.selections.all::<Point>(cx);
 8019            let snapshot = this.buffer.read(cx).read(cx);
 8020            for selection in &mut selections {
 8021                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8022                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8023                        Ordering::Less => {
 8024                            suffixes_inserted.next();
 8025                            continue;
 8026                        }
 8027                        Ordering::Greater => break,
 8028                        Ordering::Equal => {
 8029                            if selection.end.column == snapshot.line_len(row) {
 8030                                if selection.is_empty() {
 8031                                    selection.start.column -= suffix_len as u32;
 8032                                }
 8033                                selection.end.column -= suffix_len as u32;
 8034                            }
 8035                            break;
 8036                        }
 8037                    }
 8038                }
 8039            }
 8040
 8041            drop(snapshot);
 8042            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8043
 8044            let selections = this.selections.all::<Point>(cx);
 8045            let selections_on_single_row = selections.windows(2).all(|selections| {
 8046                selections[0].start.row == selections[1].start.row
 8047                    && selections[0].end.row == selections[1].end.row
 8048                    && selections[0].start.row == selections[0].end.row
 8049            });
 8050            let selections_selecting = selections
 8051                .iter()
 8052                .any(|selection| selection.start != selection.end);
 8053            let advance_downwards = action.advance_downwards
 8054                && selections_on_single_row
 8055                && !selections_selecting
 8056                && this.mode != EditorMode::SingleLine;
 8057
 8058            if advance_downwards {
 8059                let snapshot = this.buffer.read(cx).snapshot(cx);
 8060
 8061                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8062                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8063                        let mut point = display_point.to_point(display_snapshot);
 8064                        point.row += 1;
 8065                        point = snapshot.clip_point(point, Bias::Left);
 8066                        let display_point = point.to_display_point(display_snapshot);
 8067                        let goal = SelectionGoal::HorizontalPosition(
 8068                            display_snapshot
 8069                                .x_for_display_point(display_point, &text_layout_details)
 8070                                .into(),
 8071                        );
 8072                        (display_point, goal)
 8073                    })
 8074                });
 8075            }
 8076        });
 8077    }
 8078
 8079    pub fn select_larger_syntax_node(
 8080        &mut self,
 8081        _: &SelectLargerSyntaxNode,
 8082        cx: &mut ViewContext<Self>,
 8083    ) {
 8084        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8085        let buffer = self.buffer.read(cx).snapshot(cx);
 8086        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8087
 8088        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8089        let mut selected_larger_node = false;
 8090        let new_selections = old_selections
 8091            .iter()
 8092            .map(|selection| {
 8093                let old_range = selection.start..selection.end;
 8094                let mut new_range = old_range.clone();
 8095                while let Some(containing_range) =
 8096                    buffer.range_for_syntax_ancestor(new_range.clone())
 8097                {
 8098                    new_range = containing_range;
 8099                    if !display_map.intersects_fold(new_range.start)
 8100                        && !display_map.intersects_fold(new_range.end)
 8101                    {
 8102                        break;
 8103                    }
 8104                }
 8105
 8106                selected_larger_node |= new_range != old_range;
 8107                Selection {
 8108                    id: selection.id,
 8109                    start: new_range.start,
 8110                    end: new_range.end,
 8111                    goal: SelectionGoal::None,
 8112                    reversed: selection.reversed,
 8113                }
 8114            })
 8115            .collect::<Vec<_>>();
 8116
 8117        if selected_larger_node {
 8118            stack.push(old_selections);
 8119            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8120                s.select(new_selections);
 8121            });
 8122        }
 8123        self.select_larger_syntax_node_stack = stack;
 8124    }
 8125
 8126    pub fn select_smaller_syntax_node(
 8127        &mut self,
 8128        _: &SelectSmallerSyntaxNode,
 8129        cx: &mut ViewContext<Self>,
 8130    ) {
 8131        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8132        if let Some(selections) = stack.pop() {
 8133            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8134                s.select(selections.to_vec());
 8135            });
 8136        }
 8137        self.select_larger_syntax_node_stack = stack;
 8138    }
 8139
 8140    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8141        let project = self.project.clone();
 8142        cx.spawn(|this, mut cx| async move {
 8143            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8144                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8145            }) else {
 8146                return;
 8147            };
 8148
 8149            let Some(project) = project else {
 8150                return;
 8151            };
 8152
 8153            let hide_runnables = project
 8154                .update(&mut cx, |project, cx| {
 8155                    // Do not display any test indicators in non-dev server remote projects.
 8156                    project.is_remote() && project.ssh_connection_string(cx).is_none()
 8157                })
 8158                .unwrap_or(true);
 8159            if hide_runnables {
 8160                return;
 8161            }
 8162            let new_rows =
 8163                cx.background_executor()
 8164                    .spawn({
 8165                        let snapshot = display_snapshot.clone();
 8166                        async move {
 8167                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8168                        }
 8169                    })
 8170                    .await;
 8171            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8172
 8173            this.update(&mut cx, |this, _| {
 8174                this.clear_tasks();
 8175                for (key, value) in rows {
 8176                    this.insert_tasks(key, value);
 8177                }
 8178            })
 8179            .ok();
 8180        })
 8181    }
 8182    fn fetch_runnable_ranges(
 8183        snapshot: &DisplaySnapshot,
 8184        range: Range<Anchor>,
 8185    ) -> Vec<language::RunnableRange> {
 8186        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8187    }
 8188
 8189    fn runnable_rows(
 8190        project: Model<Project>,
 8191        snapshot: DisplaySnapshot,
 8192        runnable_ranges: Vec<RunnableRange>,
 8193        mut cx: AsyncWindowContext,
 8194    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8195        runnable_ranges
 8196            .into_iter()
 8197            .filter_map(|mut runnable| {
 8198                let tasks = cx
 8199                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8200                    .ok()?;
 8201                if tasks.is_empty() {
 8202                    return None;
 8203                }
 8204
 8205                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8206
 8207                let row = snapshot
 8208                    .buffer_snapshot
 8209                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8210                    .1
 8211                    .start
 8212                    .row;
 8213
 8214                let context_range =
 8215                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8216                Some((
 8217                    (runnable.buffer_id, row),
 8218                    RunnableTasks {
 8219                        templates: tasks,
 8220                        offset: MultiBufferOffset(runnable.run_range.start),
 8221                        context_range,
 8222                        column: point.column,
 8223                        extra_variables: runnable.extra_captures,
 8224                    },
 8225                ))
 8226            })
 8227            .collect()
 8228    }
 8229
 8230    fn templates_with_tags(
 8231        project: &Model<Project>,
 8232        runnable: &mut Runnable,
 8233        cx: &WindowContext<'_>,
 8234    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8235        let (inventory, worktree_id) = project.read_with(cx, |project, cx| {
 8236            let worktree_id = project
 8237                .buffer_for_id(runnable.buffer)
 8238                .and_then(|buffer| buffer.read(cx).file())
 8239                .map(|file| WorktreeId::from_usize(file.worktree_id()));
 8240
 8241            (project.task_inventory().clone(), worktree_id)
 8242        });
 8243
 8244        let inventory = inventory.read(cx);
 8245        let tags = mem::take(&mut runnable.tags);
 8246        let mut tags: Vec<_> = tags
 8247            .into_iter()
 8248            .flat_map(|tag| {
 8249                let tag = tag.0.clone();
 8250                inventory
 8251                    .list_tasks(Some(runnable.language.clone()), worktree_id)
 8252                    .into_iter()
 8253                    .filter(move |(_, template)| {
 8254                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8255                    })
 8256            })
 8257            .sorted_by_key(|(kind, _)| kind.to_owned())
 8258            .collect();
 8259        if let Some((leading_tag_source, _)) = tags.first() {
 8260            // Strongest source wins; if we have worktree tag binding, prefer that to
 8261            // global and language bindings;
 8262            // if we have a global binding, prefer that to language binding.
 8263            let first_mismatch = tags
 8264                .iter()
 8265                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8266            if let Some(index) = first_mismatch {
 8267                tags.truncate(index);
 8268            }
 8269        }
 8270
 8271        tags
 8272    }
 8273
 8274    pub fn move_to_enclosing_bracket(
 8275        &mut self,
 8276        _: &MoveToEnclosingBracket,
 8277        cx: &mut ViewContext<Self>,
 8278    ) {
 8279        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8280            s.move_offsets_with(|snapshot, selection| {
 8281                let Some(enclosing_bracket_ranges) =
 8282                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8283                else {
 8284                    return;
 8285                };
 8286
 8287                let mut best_length = usize::MAX;
 8288                let mut best_inside = false;
 8289                let mut best_in_bracket_range = false;
 8290                let mut best_destination = None;
 8291                for (open, close) in enclosing_bracket_ranges {
 8292                    let close = close.to_inclusive();
 8293                    let length = close.end() - open.start;
 8294                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8295                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8296                        || close.contains(&selection.head());
 8297
 8298                    // If best is next to a bracket and current isn't, skip
 8299                    if !in_bracket_range && best_in_bracket_range {
 8300                        continue;
 8301                    }
 8302
 8303                    // Prefer smaller lengths unless best is inside and current isn't
 8304                    if length > best_length && (best_inside || !inside) {
 8305                        continue;
 8306                    }
 8307
 8308                    best_length = length;
 8309                    best_inside = inside;
 8310                    best_in_bracket_range = in_bracket_range;
 8311                    best_destination = Some(
 8312                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8313                            if inside {
 8314                                open.end
 8315                            } else {
 8316                                open.start
 8317                            }
 8318                        } else {
 8319                            if inside {
 8320                                *close.start()
 8321                            } else {
 8322                                *close.end()
 8323                            }
 8324                        },
 8325                    );
 8326                }
 8327
 8328                if let Some(destination) = best_destination {
 8329                    selection.collapse_to(destination, SelectionGoal::None);
 8330                }
 8331            })
 8332        });
 8333    }
 8334
 8335    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 8336        self.end_selection(cx);
 8337        self.selection_history.mode = SelectionHistoryMode::Undoing;
 8338        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 8339            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8340            self.select_next_state = entry.select_next_state;
 8341            self.select_prev_state = entry.select_prev_state;
 8342            self.add_selections_state = entry.add_selections_state;
 8343            self.request_autoscroll(Autoscroll::newest(), cx);
 8344        }
 8345        self.selection_history.mode = SelectionHistoryMode::Normal;
 8346    }
 8347
 8348    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 8349        self.end_selection(cx);
 8350        self.selection_history.mode = SelectionHistoryMode::Redoing;
 8351        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 8352            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8353            self.select_next_state = entry.select_next_state;
 8354            self.select_prev_state = entry.select_prev_state;
 8355            self.add_selections_state = entry.add_selections_state;
 8356            self.request_autoscroll(Autoscroll::newest(), cx);
 8357        }
 8358        self.selection_history.mode = SelectionHistoryMode::Normal;
 8359    }
 8360
 8361    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 8362        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 8363    }
 8364
 8365    pub fn expand_excerpts_down(
 8366        &mut self,
 8367        action: &ExpandExcerptsDown,
 8368        cx: &mut ViewContext<Self>,
 8369    ) {
 8370        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 8371    }
 8372
 8373    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 8374        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 8375    }
 8376
 8377    pub fn expand_excerpts_for_direction(
 8378        &mut self,
 8379        lines: u32,
 8380        direction: ExpandExcerptDirection,
 8381        cx: &mut ViewContext<Self>,
 8382    ) {
 8383        let selections = self.selections.disjoint_anchors();
 8384
 8385        let lines = if lines == 0 {
 8386            EditorSettings::get_global(cx).expand_excerpt_lines
 8387        } else {
 8388            lines
 8389        };
 8390
 8391        self.buffer.update(cx, |buffer, cx| {
 8392            buffer.expand_excerpts(
 8393                selections
 8394                    .into_iter()
 8395                    .map(|selection| selection.head().excerpt_id)
 8396                    .dedup(),
 8397                lines,
 8398                direction,
 8399                cx,
 8400            )
 8401        })
 8402    }
 8403
 8404    pub fn expand_excerpt(
 8405        &mut self,
 8406        excerpt: ExcerptId,
 8407        direction: ExpandExcerptDirection,
 8408        cx: &mut ViewContext<Self>,
 8409    ) {
 8410        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 8411        self.buffer.update(cx, |buffer, cx| {
 8412            buffer.expand_excerpts([excerpt], lines, direction, cx)
 8413        })
 8414    }
 8415
 8416    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8417        self.go_to_diagnostic_impl(Direction::Next, cx)
 8418    }
 8419
 8420    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8421        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8422    }
 8423
 8424    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8425        let buffer = self.buffer.read(cx).snapshot(cx);
 8426        let selection = self.selections.newest::<usize>(cx);
 8427
 8428        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8429        if direction == Direction::Next {
 8430            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8431                let (group_id, jump_to) = popover.activation_info();
 8432                if self.activate_diagnostics(group_id, cx) {
 8433                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8434                        let mut new_selection = s.newest_anchor().clone();
 8435                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 8436                        s.select_anchors(vec![new_selection.clone()]);
 8437                    });
 8438                }
 8439                return;
 8440            }
 8441        }
 8442
 8443        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 8444            active_diagnostics
 8445                .primary_range
 8446                .to_offset(&buffer)
 8447                .to_inclusive()
 8448        });
 8449        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 8450            if active_primary_range.contains(&selection.head()) {
 8451                *active_primary_range.start()
 8452            } else {
 8453                selection.head()
 8454            }
 8455        } else {
 8456            selection.head()
 8457        };
 8458        let snapshot = self.snapshot(cx);
 8459        loop {
 8460            let diagnostics = if direction == Direction::Prev {
 8461                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 8462            } else {
 8463                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 8464            }
 8465            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 8466            let group = diagnostics
 8467                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 8468                // be sorted in a stable way
 8469                // skip until we are at current active diagnostic, if it exists
 8470                .skip_while(|entry| {
 8471                    (match direction {
 8472                        Direction::Prev => entry.range.start >= search_start,
 8473                        Direction::Next => entry.range.start <= search_start,
 8474                    }) && self
 8475                        .active_diagnostics
 8476                        .as_ref()
 8477                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 8478                })
 8479                .find_map(|entry| {
 8480                    if entry.diagnostic.is_primary
 8481                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 8482                        && !entry.range.is_empty()
 8483                        // if we match with the active diagnostic, skip it
 8484                        && Some(entry.diagnostic.group_id)
 8485                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 8486                    {
 8487                        Some((entry.range, entry.diagnostic.group_id))
 8488                    } else {
 8489                        None
 8490                    }
 8491                });
 8492
 8493            if let Some((primary_range, group_id)) = group {
 8494                if self.activate_diagnostics(group_id, cx) {
 8495                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8496                        s.select(vec![Selection {
 8497                            id: selection.id,
 8498                            start: primary_range.start,
 8499                            end: primary_range.start,
 8500                            reversed: false,
 8501                            goal: SelectionGoal::None,
 8502                        }]);
 8503                    });
 8504                }
 8505                break;
 8506            } else {
 8507                // Cycle around to the start of the buffer, potentially moving back to the start of
 8508                // the currently active diagnostic.
 8509                active_primary_range.take();
 8510                if direction == Direction::Prev {
 8511                    if search_start == buffer.len() {
 8512                        break;
 8513                    } else {
 8514                        search_start = buffer.len();
 8515                    }
 8516                } else if search_start == 0 {
 8517                    break;
 8518                } else {
 8519                    search_start = 0;
 8520                }
 8521            }
 8522        }
 8523    }
 8524
 8525    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 8526        let snapshot = self
 8527            .display_map
 8528            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8529        let selection = self.selections.newest::<Point>(cx);
 8530
 8531        if !self.seek_in_direction(
 8532            &snapshot,
 8533            selection.head(),
 8534            false,
 8535            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8536                MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
 8537            ),
 8538            cx,
 8539        ) {
 8540            let wrapped_point = Point::zero();
 8541            self.seek_in_direction(
 8542                &snapshot,
 8543                wrapped_point,
 8544                true,
 8545                snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8546                    MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 8547                ),
 8548                cx,
 8549            );
 8550        }
 8551    }
 8552
 8553    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 8554        let snapshot = self
 8555            .display_map
 8556            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8557        let selection = self.selections.newest::<Point>(cx);
 8558
 8559        if !self.seek_in_direction(
 8560            &snapshot,
 8561            selection.head(),
 8562            false,
 8563            snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8564                MultiBufferRow(0)..MultiBufferRow(selection.head().row),
 8565            ),
 8566            cx,
 8567        ) {
 8568            let wrapped_point = snapshot.buffer_snapshot.max_point();
 8569            self.seek_in_direction(
 8570                &snapshot,
 8571                wrapped_point,
 8572                true,
 8573                snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8574                    MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
 8575                ),
 8576                cx,
 8577            );
 8578        }
 8579    }
 8580
 8581    fn seek_in_direction(
 8582        &mut self,
 8583        snapshot: &DisplaySnapshot,
 8584        initial_point: Point,
 8585        is_wrapped: bool,
 8586        hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
 8587        cx: &mut ViewContext<Editor>,
 8588    ) -> bool {
 8589        let display_point = initial_point.to_display_point(snapshot);
 8590        let mut hunks = hunks
 8591            .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
 8592            .filter(|hunk| {
 8593                if is_wrapped {
 8594                    true
 8595                } else {
 8596                    !hunk.contains_display_row(display_point.row())
 8597                }
 8598            })
 8599            .dedup();
 8600
 8601        if let Some(hunk) = hunks.next() {
 8602            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8603                let row = hunk.start_display_row();
 8604                let point = DisplayPoint::new(row, 0);
 8605                s.select_display_ranges([point..point]);
 8606            });
 8607
 8608            true
 8609        } else {
 8610            false
 8611        }
 8612    }
 8613
 8614    pub fn go_to_definition(
 8615        &mut self,
 8616        _: &GoToDefinition,
 8617        cx: &mut ViewContext<Self>,
 8618    ) -> Task<Result<bool>> {
 8619        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
 8620    }
 8621
 8622    pub fn go_to_implementation(
 8623        &mut self,
 8624        _: &GoToImplementation,
 8625        cx: &mut ViewContext<Self>,
 8626    ) -> Task<Result<bool>> {
 8627        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 8628    }
 8629
 8630    pub fn go_to_implementation_split(
 8631        &mut self,
 8632        _: &GoToImplementationSplit,
 8633        cx: &mut ViewContext<Self>,
 8634    ) -> Task<Result<bool>> {
 8635        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 8636    }
 8637
 8638    pub fn go_to_type_definition(
 8639        &mut self,
 8640        _: &GoToTypeDefinition,
 8641        cx: &mut ViewContext<Self>,
 8642    ) -> Task<Result<bool>> {
 8643        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 8644    }
 8645
 8646    pub fn go_to_definition_split(
 8647        &mut self,
 8648        _: &GoToDefinitionSplit,
 8649        cx: &mut ViewContext<Self>,
 8650    ) -> Task<Result<bool>> {
 8651        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 8652    }
 8653
 8654    pub fn go_to_type_definition_split(
 8655        &mut self,
 8656        _: &GoToTypeDefinitionSplit,
 8657        cx: &mut ViewContext<Self>,
 8658    ) -> Task<Result<bool>> {
 8659        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 8660    }
 8661
 8662    fn go_to_definition_of_kind(
 8663        &mut self,
 8664        kind: GotoDefinitionKind,
 8665        split: bool,
 8666        cx: &mut ViewContext<Self>,
 8667    ) -> Task<Result<bool>> {
 8668        let Some(workspace) = self.workspace() else {
 8669            return Task::ready(Ok(false));
 8670        };
 8671        let buffer = self.buffer.read(cx);
 8672        let head = self.selections.newest::<usize>(cx).head();
 8673        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 8674            text_anchor
 8675        } else {
 8676            return Task::ready(Ok(false));
 8677        };
 8678
 8679        let project = workspace.read(cx).project().clone();
 8680        let definitions = project.update(cx, |project, cx| match kind {
 8681            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 8682            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 8683            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 8684        });
 8685
 8686        cx.spawn(|editor, mut cx| async move {
 8687            let definitions = definitions.await?;
 8688            let navigated = editor
 8689                .update(&mut cx, |editor, cx| {
 8690                    editor.navigate_to_hover_links(
 8691                        Some(kind),
 8692                        definitions
 8693                            .into_iter()
 8694                            .filter(|location| {
 8695                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 8696                            })
 8697                            .map(HoverLink::Text)
 8698                            .collect::<Vec<_>>(),
 8699                        split,
 8700                        cx,
 8701                    )
 8702                })?
 8703                .await?;
 8704            anyhow::Ok(navigated)
 8705        })
 8706    }
 8707
 8708    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 8709        let position = self.selections.newest_anchor().head();
 8710        let Some((buffer, buffer_position)) =
 8711            self.buffer.read(cx).text_anchor_for_position(position, cx)
 8712        else {
 8713            return;
 8714        };
 8715
 8716        cx.spawn(|editor, mut cx| async move {
 8717            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 8718                editor.update(&mut cx, |_, cx| {
 8719                    cx.open_url(&url);
 8720                })
 8721            } else {
 8722                Ok(())
 8723            }
 8724        })
 8725        .detach();
 8726    }
 8727
 8728    pub(crate) fn navigate_to_hover_links(
 8729        &mut self,
 8730        kind: Option<GotoDefinitionKind>,
 8731        mut definitions: Vec<HoverLink>,
 8732        split: bool,
 8733        cx: &mut ViewContext<Editor>,
 8734    ) -> Task<Result<bool>> {
 8735        // If there is one definition, just open it directly
 8736        if definitions.len() == 1 {
 8737            let definition = definitions.pop().unwrap();
 8738            let target_task = match definition {
 8739                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 8740                HoverLink::InlayHint(lsp_location, server_id) => {
 8741                    self.compute_target_location(lsp_location, server_id, cx)
 8742                }
 8743                HoverLink::Url(url) => {
 8744                    cx.open_url(&url);
 8745                    Task::ready(Ok(None))
 8746                }
 8747            };
 8748            cx.spawn(|editor, mut cx| async move {
 8749                let target = target_task.await.context("target resolution task")?;
 8750                if let Some(target) = target {
 8751                    editor.update(&mut cx, |editor, cx| {
 8752                        let Some(workspace) = editor.workspace() else {
 8753                            return false;
 8754                        };
 8755                        let pane = workspace.read(cx).active_pane().clone();
 8756
 8757                        let range = target.range.to_offset(target.buffer.read(cx));
 8758                        let range = editor.range_for_match(&range);
 8759
 8760                        /// If select range has more than one line, we
 8761                        /// just point the cursor to range.start.
 8762                        fn check_multiline_range(
 8763                            buffer: &Buffer,
 8764                            range: Range<usize>,
 8765                        ) -> Range<usize> {
 8766                            if buffer.offset_to_point(range.start).row
 8767                                == buffer.offset_to_point(range.end).row
 8768                            {
 8769                                range
 8770                            } else {
 8771                                range.start..range.start
 8772                            }
 8773                        }
 8774
 8775                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 8776                            let buffer = target.buffer.read(cx);
 8777                            let range = check_multiline_range(buffer, range);
 8778                            editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 8779                                s.select_ranges([range]);
 8780                            });
 8781                        } else {
 8782                            cx.window_context().defer(move |cx| {
 8783                                let target_editor: View<Self> =
 8784                                    workspace.update(cx, |workspace, cx| {
 8785                                        let pane = if split {
 8786                                            workspace.adjacent_pane(cx)
 8787                                        } else {
 8788                                            workspace.active_pane().clone()
 8789                                        };
 8790
 8791                                        workspace.open_project_item(pane, target.buffer.clone(), cx)
 8792                                    });
 8793                                target_editor.update(cx, |target_editor, cx| {
 8794                                    // When selecting a definition in a different buffer, disable the nav history
 8795                                    // to avoid creating a history entry at the previous cursor location.
 8796                                    pane.update(cx, |pane, _| pane.disable_history());
 8797                                    let buffer = target.buffer.read(cx);
 8798                                    let range = check_multiline_range(buffer, range);
 8799                                    target_editor.change_selections(
 8800                                        Some(Autoscroll::focused()),
 8801                                        cx,
 8802                                        |s| {
 8803                                            s.select_ranges([range]);
 8804                                        },
 8805                                    );
 8806                                    pane.update(cx, |pane, _| pane.enable_history());
 8807                                });
 8808                            });
 8809                        }
 8810                        true
 8811                    })
 8812                } else {
 8813                    Ok(false)
 8814                }
 8815            })
 8816        } else if !definitions.is_empty() {
 8817            let replica_id = self.replica_id(cx);
 8818            cx.spawn(|editor, mut cx| async move {
 8819                let (title, location_tasks, workspace) = editor
 8820                    .update(&mut cx, |editor, cx| {
 8821                        let tab_kind = match kind {
 8822                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 8823                            _ => "Definitions",
 8824                        };
 8825                        let title = definitions
 8826                            .iter()
 8827                            .find_map(|definition| match definition {
 8828                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 8829                                    let buffer = origin.buffer.read(cx);
 8830                                    format!(
 8831                                        "{} for {}",
 8832                                        tab_kind,
 8833                                        buffer
 8834                                            .text_for_range(origin.range.clone())
 8835                                            .collect::<String>()
 8836                                    )
 8837                                }),
 8838                                HoverLink::InlayHint(_, _) => None,
 8839                                HoverLink::Url(_) => None,
 8840                            })
 8841                            .unwrap_or(tab_kind.to_string());
 8842                        let location_tasks = definitions
 8843                            .into_iter()
 8844                            .map(|definition| match definition {
 8845                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 8846                                HoverLink::InlayHint(lsp_location, server_id) => {
 8847                                    editor.compute_target_location(lsp_location, server_id, cx)
 8848                                }
 8849                                HoverLink::Url(_) => Task::ready(Ok(None)),
 8850                            })
 8851                            .collect::<Vec<_>>();
 8852                        (title, location_tasks, editor.workspace().clone())
 8853                    })
 8854                    .context("location tasks preparation")?;
 8855
 8856                let locations = futures::future::join_all(location_tasks)
 8857                    .await
 8858                    .into_iter()
 8859                    .filter_map(|location| location.transpose())
 8860                    .collect::<Result<_>>()
 8861                    .context("location tasks")?;
 8862
 8863                let Some(workspace) = workspace else {
 8864                    return Ok(false);
 8865                };
 8866                let opened = workspace
 8867                    .update(&mut cx, |workspace, cx| {
 8868                        Self::open_locations_in_multibuffer(
 8869                            workspace, locations, replica_id, title, split, cx,
 8870                        )
 8871                    })
 8872                    .ok();
 8873
 8874                anyhow::Ok(opened.is_some())
 8875            })
 8876        } else {
 8877            Task::ready(Ok(false))
 8878        }
 8879    }
 8880
 8881    fn compute_target_location(
 8882        &self,
 8883        lsp_location: lsp::Location,
 8884        server_id: LanguageServerId,
 8885        cx: &mut ViewContext<Editor>,
 8886    ) -> Task<anyhow::Result<Option<Location>>> {
 8887        let Some(project) = self.project.clone() else {
 8888            return Task::Ready(Some(Ok(None)));
 8889        };
 8890
 8891        cx.spawn(move |editor, mut cx| async move {
 8892            let location_task = editor.update(&mut cx, |editor, cx| {
 8893                project.update(cx, |project, cx| {
 8894                    let language_server_name =
 8895                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 8896                            project
 8897                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 8898                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 8899                        });
 8900                    language_server_name.map(|language_server_name| {
 8901                        project.open_local_buffer_via_lsp(
 8902                            lsp_location.uri.clone(),
 8903                            server_id,
 8904                            language_server_name,
 8905                            cx,
 8906                        )
 8907                    })
 8908                })
 8909            })?;
 8910            let location = match location_task {
 8911                Some(task) => Some({
 8912                    let target_buffer_handle = task.await.context("open local buffer")?;
 8913                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 8914                        let target_start = target_buffer
 8915                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 8916                        let target_end = target_buffer
 8917                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 8918                        target_buffer.anchor_after(target_start)
 8919                            ..target_buffer.anchor_before(target_end)
 8920                    })?;
 8921                    Location {
 8922                        buffer: target_buffer_handle,
 8923                        range,
 8924                    }
 8925                }),
 8926                None => None,
 8927            };
 8928            Ok(location)
 8929        })
 8930    }
 8931
 8932    pub fn find_all_references(
 8933        &mut self,
 8934        _: &FindAllReferences,
 8935        cx: &mut ViewContext<Self>,
 8936    ) -> Option<Task<Result<()>>> {
 8937        let multi_buffer = self.buffer.read(cx);
 8938        let selection = self.selections.newest::<usize>(cx);
 8939        let head = selection.head();
 8940
 8941        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 8942        let head_anchor = multi_buffer_snapshot.anchor_at(
 8943            head,
 8944            if head < selection.tail() {
 8945                Bias::Right
 8946            } else {
 8947                Bias::Left
 8948            },
 8949        );
 8950
 8951        match self
 8952            .find_all_references_task_sources
 8953            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 8954        {
 8955            Ok(_) => {
 8956                log::info!(
 8957                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 8958                );
 8959                return None;
 8960            }
 8961            Err(i) => {
 8962                self.find_all_references_task_sources.insert(i, head_anchor);
 8963            }
 8964        }
 8965
 8966        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 8967        let replica_id = self.replica_id(cx);
 8968        let workspace = self.workspace()?;
 8969        let project = workspace.read(cx).project().clone();
 8970        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 8971        Some(cx.spawn(|editor, mut cx| async move {
 8972            let _cleanup = defer({
 8973                let mut cx = cx.clone();
 8974                move || {
 8975                    let _ = editor.update(&mut cx, |editor, _| {
 8976                        if let Ok(i) =
 8977                            editor
 8978                                .find_all_references_task_sources
 8979                                .binary_search_by(|anchor| {
 8980                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 8981                                })
 8982                        {
 8983                            editor.find_all_references_task_sources.remove(i);
 8984                        }
 8985                    });
 8986                }
 8987            });
 8988
 8989            let locations = references.await?;
 8990            if locations.is_empty() {
 8991                return anyhow::Ok(());
 8992            }
 8993
 8994            workspace.update(&mut cx, |workspace, cx| {
 8995                let title = locations
 8996                    .first()
 8997                    .as_ref()
 8998                    .map(|location| {
 8999                        let buffer = location.buffer.read(cx);
 9000                        format!(
 9001                            "References to `{}`",
 9002                            buffer
 9003                                .text_for_range(location.range.clone())
 9004                                .collect::<String>()
 9005                        )
 9006                    })
 9007                    .unwrap();
 9008                Self::open_locations_in_multibuffer(
 9009                    workspace, locations, replica_id, title, false, cx,
 9010                );
 9011            })
 9012        }))
 9013    }
 9014
 9015    /// Opens a multibuffer with the given project locations in it
 9016    pub fn open_locations_in_multibuffer(
 9017        workspace: &mut Workspace,
 9018        mut locations: Vec<Location>,
 9019        replica_id: ReplicaId,
 9020        title: String,
 9021        split: bool,
 9022        cx: &mut ViewContext<Workspace>,
 9023    ) {
 9024        // If there are multiple definitions, open them in a multibuffer
 9025        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9026        let mut locations = locations.into_iter().peekable();
 9027        let mut ranges_to_highlight = Vec::new();
 9028        let capability = workspace.project().read(cx).capability();
 9029
 9030        let excerpt_buffer = cx.new_model(|cx| {
 9031            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 9032            while let Some(location) = locations.next() {
 9033                let buffer = location.buffer.read(cx);
 9034                let mut ranges_for_buffer = Vec::new();
 9035                let range = location.range.to_offset(buffer);
 9036                ranges_for_buffer.push(range.clone());
 9037
 9038                while let Some(next_location) = locations.peek() {
 9039                    if next_location.buffer == location.buffer {
 9040                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9041                        locations.next();
 9042                    } else {
 9043                        break;
 9044                    }
 9045                }
 9046
 9047                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9048                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9049                    location.buffer.clone(),
 9050                    ranges_for_buffer,
 9051                    DEFAULT_MULTIBUFFER_CONTEXT,
 9052                    cx,
 9053                ))
 9054            }
 9055
 9056            multibuffer.with_title(title)
 9057        });
 9058
 9059        let editor = cx.new_view(|cx| {
 9060            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9061        });
 9062        editor.update(cx, |editor, cx| {
 9063            editor.highlight_background::<Self>(
 9064                &ranges_to_highlight,
 9065                |theme| theme.editor_highlighted_line_background,
 9066                cx,
 9067            );
 9068        });
 9069
 9070        let item = Box::new(editor);
 9071        let item_id = item.item_id();
 9072
 9073        if split {
 9074            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9075        } else {
 9076            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9077                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9078                    pane.close_current_preview_item(cx)
 9079                } else {
 9080                    None
 9081                }
 9082            });
 9083            workspace.add_item_to_active_pane(item.clone(), destination_index, cx);
 9084        }
 9085        workspace.active_pane().update(cx, |pane, cx| {
 9086            pane.set_preview_item_id(Some(item_id), cx);
 9087        });
 9088    }
 9089
 9090    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9091        use language::ToOffset as _;
 9092
 9093        let project = self.project.clone()?;
 9094        let selection = self.selections.newest_anchor().clone();
 9095        let (cursor_buffer, cursor_buffer_position) = self
 9096            .buffer
 9097            .read(cx)
 9098            .text_anchor_for_position(selection.head(), cx)?;
 9099        let (tail_buffer, cursor_buffer_position_end) = self
 9100            .buffer
 9101            .read(cx)
 9102            .text_anchor_for_position(selection.tail(), cx)?;
 9103        if tail_buffer != cursor_buffer {
 9104            return None;
 9105        }
 9106
 9107        let snapshot = cursor_buffer.read(cx).snapshot();
 9108        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9109        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9110        let prepare_rename = project.update(cx, |project, cx| {
 9111            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 9112        });
 9113        drop(snapshot);
 9114
 9115        Some(cx.spawn(|this, mut cx| async move {
 9116            let rename_range = if let Some(range) = prepare_rename.await? {
 9117                Some(range)
 9118            } else {
 9119                this.update(&mut cx, |this, cx| {
 9120                    let buffer = this.buffer.read(cx).snapshot(cx);
 9121                    let mut buffer_highlights = this
 9122                        .document_highlights_for_position(selection.head(), &buffer)
 9123                        .filter(|highlight| {
 9124                            highlight.start.excerpt_id == selection.head().excerpt_id
 9125                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9126                        });
 9127                    buffer_highlights
 9128                        .next()
 9129                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9130                })?
 9131            };
 9132            if let Some(rename_range) = rename_range {
 9133                this.update(&mut cx, |this, cx| {
 9134                    let snapshot = cursor_buffer.read(cx).snapshot();
 9135                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9136                    let cursor_offset_in_rename_range =
 9137                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9138                    let cursor_offset_in_rename_range_end =
 9139                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9140
 9141                    this.take_rename(false, cx);
 9142                    let buffer = this.buffer.read(cx).read(cx);
 9143                    let cursor_offset = selection.head().to_offset(&buffer);
 9144                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9145                    let rename_end = rename_start + rename_buffer_range.len();
 9146                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9147                    let mut old_highlight_id = None;
 9148                    let old_name: Arc<str> = buffer
 9149                        .chunks(rename_start..rename_end, true)
 9150                        .map(|chunk| {
 9151                            if old_highlight_id.is_none() {
 9152                                old_highlight_id = chunk.syntax_highlight_id;
 9153                            }
 9154                            chunk.text
 9155                        })
 9156                        .collect::<String>()
 9157                        .into();
 9158
 9159                    drop(buffer);
 9160
 9161                    // Position the selection in the rename editor so that it matches the current selection.
 9162                    this.show_local_selections = false;
 9163                    let rename_editor = cx.new_view(|cx| {
 9164                        let mut editor = Editor::single_line(cx);
 9165                        editor.buffer.update(cx, |buffer, cx| {
 9166                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9167                        });
 9168                        let rename_selection_range = match cursor_offset_in_rename_range
 9169                            .cmp(&cursor_offset_in_rename_range_end)
 9170                        {
 9171                            Ordering::Equal => {
 9172                                editor.select_all(&SelectAll, cx);
 9173                                return editor;
 9174                            }
 9175                            Ordering::Less => {
 9176                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9177                            }
 9178                            Ordering::Greater => {
 9179                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9180                            }
 9181                        };
 9182                        if rename_selection_range.end > old_name.len() {
 9183                            editor.select_all(&SelectAll, cx);
 9184                        } else {
 9185                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9186                                s.select_ranges([rename_selection_range]);
 9187                            });
 9188                        }
 9189                        editor
 9190                    });
 9191
 9192                    let write_highlights =
 9193                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9194                    let read_highlights =
 9195                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9196                    let ranges = write_highlights
 9197                        .iter()
 9198                        .flat_map(|(_, ranges)| ranges.iter())
 9199                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9200                        .cloned()
 9201                        .collect();
 9202
 9203                    this.highlight_text::<Rename>(
 9204                        ranges,
 9205                        HighlightStyle {
 9206                            fade_out: Some(0.6),
 9207                            ..Default::default()
 9208                        },
 9209                        cx,
 9210                    );
 9211                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9212                    cx.focus(&rename_focus_handle);
 9213                    let block_id = this.insert_blocks(
 9214                        [BlockProperties {
 9215                            style: BlockStyle::Flex,
 9216                            position: range.start,
 9217                            height: 1,
 9218                            render: Box::new({
 9219                                let rename_editor = rename_editor.clone();
 9220                                move |cx: &mut BlockContext| {
 9221                                    let mut text_style = cx.editor_style.text.clone();
 9222                                    if let Some(highlight_style) = old_highlight_id
 9223                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 9224                                    {
 9225                                        text_style = text_style.highlight(highlight_style);
 9226                                    }
 9227                                    div()
 9228                                        .pl(cx.anchor_x)
 9229                                        .child(EditorElement::new(
 9230                                            &rename_editor,
 9231                                            EditorStyle {
 9232                                                background: cx.theme().system().transparent,
 9233                                                local_player: cx.editor_style.local_player,
 9234                                                text: text_style,
 9235                                                scrollbar_width: cx.editor_style.scrollbar_width,
 9236                                                syntax: cx.editor_style.syntax.clone(),
 9237                                                status: cx.editor_style.status.clone(),
 9238                                                inlay_hints_style: HighlightStyle {
 9239                                                    color: Some(cx.theme().status().hint),
 9240                                                    font_weight: Some(FontWeight::BOLD),
 9241                                                    ..HighlightStyle::default()
 9242                                                },
 9243                                                suggestions_style: HighlightStyle {
 9244                                                    color: Some(cx.theme().status().predictive),
 9245                                                    ..HighlightStyle::default()
 9246                                                },
 9247                                            },
 9248                                        ))
 9249                                        .into_any_element()
 9250                                }
 9251                            }),
 9252                            disposition: BlockDisposition::Below,
 9253                        }],
 9254                        Some(Autoscroll::fit()),
 9255                        cx,
 9256                    )[0];
 9257                    this.pending_rename = Some(RenameState {
 9258                        range,
 9259                        old_name,
 9260                        editor: rename_editor,
 9261                        block_id,
 9262                    });
 9263                })?;
 9264            }
 9265
 9266            Ok(())
 9267        }))
 9268    }
 9269
 9270    pub fn confirm_rename(
 9271        &mut self,
 9272        _: &ConfirmRename,
 9273        cx: &mut ViewContext<Self>,
 9274    ) -> Option<Task<Result<()>>> {
 9275        let rename = self.take_rename(false, cx)?;
 9276        let workspace = self.workspace()?;
 9277        let (start_buffer, start) = self
 9278            .buffer
 9279            .read(cx)
 9280            .text_anchor_for_position(rename.range.start, cx)?;
 9281        let (end_buffer, end) = self
 9282            .buffer
 9283            .read(cx)
 9284            .text_anchor_for_position(rename.range.end, cx)?;
 9285        if start_buffer != end_buffer {
 9286            return None;
 9287        }
 9288
 9289        let buffer = start_buffer;
 9290        let range = start..end;
 9291        let old_name = rename.old_name;
 9292        let new_name = rename.editor.read(cx).text(cx);
 9293
 9294        let rename = workspace
 9295            .read(cx)
 9296            .project()
 9297            .clone()
 9298            .update(cx, |project, cx| {
 9299                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 9300            });
 9301        let workspace = workspace.downgrade();
 9302
 9303        Some(cx.spawn(|editor, mut cx| async move {
 9304            let project_transaction = rename.await?;
 9305            Self::open_project_transaction(
 9306                &editor,
 9307                workspace,
 9308                project_transaction,
 9309                format!("Rename: {}{}", old_name, new_name),
 9310                cx.clone(),
 9311            )
 9312            .await?;
 9313
 9314            editor.update(&mut cx, |editor, cx| {
 9315                editor.refresh_document_highlights(cx);
 9316            })?;
 9317            Ok(())
 9318        }))
 9319    }
 9320
 9321    fn take_rename(
 9322        &mut self,
 9323        moving_cursor: bool,
 9324        cx: &mut ViewContext<Self>,
 9325    ) -> Option<RenameState> {
 9326        let rename = self.pending_rename.take()?;
 9327        if rename.editor.focus_handle(cx).is_focused(cx) {
 9328            cx.focus(&self.focus_handle);
 9329        }
 9330
 9331        self.remove_blocks(
 9332            [rename.block_id].into_iter().collect(),
 9333            Some(Autoscroll::fit()),
 9334            cx,
 9335        );
 9336        self.clear_highlights::<Rename>(cx);
 9337        self.show_local_selections = true;
 9338
 9339        if moving_cursor {
 9340            let rename_editor = rename.editor.read(cx);
 9341            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 9342
 9343            // Update the selection to match the position of the selection inside
 9344            // the rename editor.
 9345            let snapshot = self.buffer.read(cx).read(cx);
 9346            let rename_range = rename.range.to_offset(&snapshot);
 9347            let cursor_in_editor = snapshot
 9348                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 9349                .min(rename_range.end);
 9350            drop(snapshot);
 9351
 9352            self.change_selections(None, cx, |s| {
 9353                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 9354            });
 9355        } else {
 9356            self.refresh_document_highlights(cx);
 9357        }
 9358
 9359        Some(rename)
 9360    }
 9361
 9362    pub fn pending_rename(&self) -> Option<&RenameState> {
 9363        self.pending_rename.as_ref()
 9364    }
 9365
 9366    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9367        let project = match &self.project {
 9368            Some(project) => project.clone(),
 9369            None => return None,
 9370        };
 9371
 9372        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 9373    }
 9374
 9375    fn perform_format(
 9376        &mut self,
 9377        project: Model<Project>,
 9378        trigger: FormatTrigger,
 9379        cx: &mut ViewContext<Self>,
 9380    ) -> Task<Result<()>> {
 9381        let buffer = self.buffer().clone();
 9382        let mut buffers = buffer.read(cx).all_buffers();
 9383        if trigger == FormatTrigger::Save {
 9384            buffers.retain(|buffer| buffer.read(cx).is_dirty());
 9385        }
 9386
 9387        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 9388        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 9389
 9390        cx.spawn(|_, mut cx| async move {
 9391            let transaction = futures::select_biased! {
 9392                () = timeout => {
 9393                    log::warn!("timed out waiting for formatting");
 9394                    None
 9395                }
 9396                transaction = format.log_err().fuse() => transaction,
 9397            };
 9398
 9399            buffer
 9400                .update(&mut cx, |buffer, cx| {
 9401                    if let Some(transaction) = transaction {
 9402                        if !buffer.is_singleton() {
 9403                            buffer.push_transaction(&transaction.0, cx);
 9404                        }
 9405                    }
 9406
 9407                    cx.notify();
 9408                })
 9409                .ok();
 9410
 9411            Ok(())
 9412        })
 9413    }
 9414
 9415    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
 9416        if let Some(project) = self.project.clone() {
 9417            self.buffer.update(cx, |multi_buffer, cx| {
 9418                project.update(cx, |project, cx| {
 9419                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
 9420                });
 9421            })
 9422        }
 9423    }
 9424
 9425    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 9426        cx.show_character_palette();
 9427    }
 9428
 9429    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
 9430        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
 9431            let buffer = self.buffer.read(cx).snapshot(cx);
 9432            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
 9433            let is_valid = buffer
 9434                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
 9435                .any(|entry| {
 9436                    entry.diagnostic.is_primary
 9437                        && !entry.range.is_empty()
 9438                        && entry.range.start == primary_range_start
 9439                        && entry.diagnostic.message == active_diagnostics.primary_message
 9440                });
 9441
 9442            if is_valid != active_diagnostics.is_valid {
 9443                active_diagnostics.is_valid = is_valid;
 9444                let mut new_styles = HashMap::default();
 9445                for (block_id, diagnostic) in &active_diagnostics.blocks {
 9446                    new_styles.insert(
 9447                        *block_id,
 9448                        (
 9449                            None,
 9450                            diagnostic_block_renderer(diagnostic.clone(), is_valid),
 9451                        ),
 9452                    );
 9453                }
 9454                self.display_map.update(cx, |display_map, cx| {
 9455                    display_map.replace_blocks(new_styles, cx)
 9456                });
 9457            }
 9458        }
 9459    }
 9460
 9461    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
 9462        self.dismiss_diagnostics(cx);
 9463        let snapshot = self.snapshot(cx);
 9464        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
 9465            let buffer = self.buffer.read(cx).snapshot(cx);
 9466
 9467            let mut primary_range = None;
 9468            let mut primary_message = None;
 9469            let mut group_end = Point::zero();
 9470            let diagnostic_group = buffer
 9471                .diagnostic_group::<MultiBufferPoint>(group_id)
 9472                .filter_map(|entry| {
 9473                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
 9474                        && (entry.range.start.row == entry.range.end.row
 9475                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
 9476                    {
 9477                        return None;
 9478                    }
 9479                    if entry.range.end > group_end {
 9480                        group_end = entry.range.end;
 9481                    }
 9482                    if entry.diagnostic.is_primary {
 9483                        primary_range = Some(entry.range.clone());
 9484                        primary_message = Some(entry.diagnostic.message.clone());
 9485                    }
 9486                    Some(entry)
 9487                })
 9488                .collect::<Vec<_>>();
 9489            let primary_range = primary_range?;
 9490            let primary_message = primary_message?;
 9491            let primary_range =
 9492                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
 9493
 9494            let blocks = display_map
 9495                .insert_blocks(
 9496                    diagnostic_group.iter().map(|entry| {
 9497                        let diagnostic = entry.diagnostic.clone();
 9498                        let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
 9499                        BlockProperties {
 9500                            style: BlockStyle::Fixed,
 9501                            position: buffer.anchor_after(entry.range.start),
 9502                            height: message_height,
 9503                            render: diagnostic_block_renderer(diagnostic, true),
 9504                            disposition: BlockDisposition::Below,
 9505                        }
 9506                    }),
 9507                    cx,
 9508                )
 9509                .into_iter()
 9510                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
 9511                .collect();
 9512
 9513            Some(ActiveDiagnosticGroup {
 9514                primary_range,
 9515                primary_message,
 9516                group_id,
 9517                blocks,
 9518                is_valid: true,
 9519            })
 9520        });
 9521        self.active_diagnostics.is_some()
 9522    }
 9523
 9524    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
 9525        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
 9526            self.display_map.update(cx, |display_map, cx| {
 9527                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
 9528            });
 9529            cx.notify();
 9530        }
 9531    }
 9532
 9533    pub fn set_selections_from_remote(
 9534        &mut self,
 9535        selections: Vec<Selection<Anchor>>,
 9536        pending_selection: Option<Selection<Anchor>>,
 9537        cx: &mut ViewContext<Self>,
 9538    ) {
 9539        let old_cursor_position = self.selections.newest_anchor().head();
 9540        self.selections.change_with(cx, |s| {
 9541            s.select_anchors(selections);
 9542            if let Some(pending_selection) = pending_selection {
 9543                s.set_pending(pending_selection, SelectMode::Character);
 9544            } else {
 9545                s.clear_pending();
 9546            }
 9547        });
 9548        self.selections_did_change(false, &old_cursor_position, true, cx);
 9549    }
 9550
 9551    fn push_to_selection_history(&mut self) {
 9552        self.selection_history.push(SelectionHistoryEntry {
 9553            selections: self.selections.disjoint_anchors(),
 9554            select_next_state: self.select_next_state.clone(),
 9555            select_prev_state: self.select_prev_state.clone(),
 9556            add_selections_state: self.add_selections_state.clone(),
 9557        });
 9558    }
 9559
 9560    pub fn transact(
 9561        &mut self,
 9562        cx: &mut ViewContext<Self>,
 9563        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
 9564    ) -> Option<TransactionId> {
 9565        self.start_transaction_at(Instant::now(), cx);
 9566        update(self, cx);
 9567        self.end_transaction_at(Instant::now(), cx)
 9568    }
 9569
 9570    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
 9571        self.end_selection(cx);
 9572        if let Some(tx_id) = self
 9573            .buffer
 9574            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
 9575        {
 9576            self.selection_history
 9577                .insert_transaction(tx_id, self.selections.disjoint_anchors());
 9578            cx.emit(EditorEvent::TransactionBegun {
 9579                transaction_id: tx_id,
 9580            })
 9581        }
 9582    }
 9583
 9584    fn end_transaction_at(
 9585        &mut self,
 9586        now: Instant,
 9587        cx: &mut ViewContext<Self>,
 9588    ) -> Option<TransactionId> {
 9589        if let Some(tx_id) = self
 9590            .buffer
 9591            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 9592        {
 9593            if let Some((_, end_selections)) = self.selection_history.transaction_mut(tx_id) {
 9594                *end_selections = Some(self.selections.disjoint_anchors());
 9595            } else {
 9596                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
 9597            }
 9598
 9599            cx.emit(EditorEvent::Edited);
 9600            Some(tx_id)
 9601        } else {
 9602            None
 9603        }
 9604    }
 9605
 9606    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
 9607        let mut fold_ranges = Vec::new();
 9608
 9609        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9610
 9611        let selections = self.selections.all_adjusted(cx);
 9612        for selection in selections {
 9613            let range = selection.range().sorted();
 9614            let buffer_start_row = range.start.row;
 9615
 9616            for row in (0..=range.end.row).rev() {
 9617                if let Some((foldable_range, fold_text)) =
 9618                    display_map.foldable_range(MultiBufferRow(row))
 9619                {
 9620                    if foldable_range.end.row >= buffer_start_row {
 9621                        fold_ranges.push((foldable_range, fold_text));
 9622                        if row <= range.start.row {
 9623                            break;
 9624                        }
 9625                    }
 9626                }
 9627            }
 9628        }
 9629
 9630        self.fold_ranges(fold_ranges, true, cx);
 9631    }
 9632
 9633    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
 9634        let buffer_row = fold_at.buffer_row;
 9635        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9636
 9637        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
 9638            let autoscroll = self
 9639                .selections
 9640                .all::<Point>(cx)
 9641                .iter()
 9642                .any(|selection| fold_range.overlaps(&selection.range()));
 9643
 9644            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
 9645        }
 9646    }
 9647
 9648    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
 9649        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9650        let buffer = &display_map.buffer_snapshot;
 9651        let selections = self.selections.all::<Point>(cx);
 9652        let ranges = selections
 9653            .iter()
 9654            .map(|s| {
 9655                let range = s.display_range(&display_map).sorted();
 9656                let mut start = range.start.to_point(&display_map);
 9657                let mut end = range.end.to_point(&display_map);
 9658                start.column = 0;
 9659                end.column = buffer.line_len(MultiBufferRow(end.row));
 9660                start..end
 9661            })
 9662            .collect::<Vec<_>>();
 9663
 9664        self.unfold_ranges(ranges, true, true, cx);
 9665    }
 9666
 9667    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
 9668        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9669
 9670        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
 9671            ..Point::new(
 9672                unfold_at.buffer_row.0,
 9673                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
 9674            );
 9675
 9676        let autoscroll = self
 9677            .selections
 9678            .all::<Point>(cx)
 9679            .iter()
 9680            .any(|selection| selection.range().overlaps(&intersection_range));
 9681
 9682        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
 9683    }
 9684
 9685    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
 9686        let selections = self.selections.all::<Point>(cx);
 9687        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9688        let line_mode = self.selections.line_mode;
 9689        let ranges = selections.into_iter().map(|s| {
 9690            if line_mode {
 9691                let start = Point::new(s.start.row, 0);
 9692                let end = Point::new(
 9693                    s.end.row,
 9694                    display_map
 9695                        .buffer_snapshot
 9696                        .line_len(MultiBufferRow(s.end.row)),
 9697                );
 9698                (start..end, display_map.fold_placeholder.clone())
 9699            } else {
 9700                (s.start..s.end, display_map.fold_placeholder.clone())
 9701            }
 9702        });
 9703        self.fold_ranges(ranges, true, cx);
 9704    }
 9705
 9706    pub fn fold_ranges<T: ToOffset + Clone>(
 9707        &mut self,
 9708        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
 9709        auto_scroll: bool,
 9710        cx: &mut ViewContext<Self>,
 9711    ) {
 9712        let mut fold_ranges = Vec::new();
 9713        let mut buffers_affected = HashMap::default();
 9714        let multi_buffer = self.buffer().read(cx);
 9715        for (fold_range, fold_text) in ranges {
 9716            if let Some((_, buffer, _)) =
 9717                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
 9718            {
 9719                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
 9720            };
 9721            fold_ranges.push((fold_range, fold_text));
 9722        }
 9723
 9724        let mut ranges = fold_ranges.into_iter().peekable();
 9725        if ranges.peek().is_some() {
 9726            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
 9727
 9728            if auto_scroll {
 9729                self.request_autoscroll(Autoscroll::fit(), cx);
 9730            }
 9731
 9732            for buffer in buffers_affected.into_values() {
 9733                self.sync_expanded_diff_hunks(buffer, cx);
 9734            }
 9735
 9736            cx.notify();
 9737
 9738            if let Some(active_diagnostics) = self.active_diagnostics.take() {
 9739                // Clear diagnostics block when folding a range that contains it.
 9740                let snapshot = self.snapshot(cx);
 9741                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
 9742                    drop(snapshot);
 9743                    self.active_diagnostics = Some(active_diagnostics);
 9744                    self.dismiss_diagnostics(cx);
 9745                } else {
 9746                    self.active_diagnostics = Some(active_diagnostics);
 9747                }
 9748            }
 9749
 9750            self.scrollbar_marker_state.dirty = true;
 9751        }
 9752    }
 9753
 9754    pub fn unfold_ranges<T: ToOffset + Clone>(
 9755        &mut self,
 9756        ranges: impl IntoIterator<Item = Range<T>>,
 9757        inclusive: bool,
 9758        auto_scroll: bool,
 9759        cx: &mut ViewContext<Self>,
 9760    ) {
 9761        let mut unfold_ranges = Vec::new();
 9762        let mut buffers_affected = HashMap::default();
 9763        let multi_buffer = self.buffer().read(cx);
 9764        for range in ranges {
 9765            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
 9766                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
 9767            };
 9768            unfold_ranges.push(range);
 9769        }
 9770
 9771        let mut ranges = unfold_ranges.into_iter().peekable();
 9772        if ranges.peek().is_some() {
 9773            self.display_map
 9774                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
 9775            if auto_scroll {
 9776                self.request_autoscroll(Autoscroll::fit(), cx);
 9777            }
 9778
 9779            for buffer in buffers_affected.into_values() {
 9780                self.sync_expanded_diff_hunks(buffer, cx);
 9781            }
 9782
 9783            cx.notify();
 9784            self.scrollbar_marker_state.dirty = true;
 9785            self.active_indent_guides_state.dirty = true;
 9786        }
 9787    }
 9788
 9789    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
 9790        if hovered != self.gutter_hovered {
 9791            self.gutter_hovered = hovered;
 9792            cx.notify();
 9793        }
 9794    }
 9795
 9796    pub fn insert_blocks(
 9797        &mut self,
 9798        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
 9799        autoscroll: Option<Autoscroll>,
 9800        cx: &mut ViewContext<Self>,
 9801    ) -> Vec<BlockId> {
 9802        let blocks = self
 9803            .display_map
 9804            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
 9805        if let Some(autoscroll) = autoscroll {
 9806            self.request_autoscroll(autoscroll, cx);
 9807        }
 9808        blocks
 9809    }
 9810
 9811    pub fn replace_blocks(
 9812        &mut self,
 9813        blocks: HashMap<BlockId, (Option<u8>, RenderBlock)>,
 9814        autoscroll: Option<Autoscroll>,
 9815        cx: &mut ViewContext<Self>,
 9816    ) {
 9817        self.display_map
 9818            .update(cx, |display_map, cx| display_map.replace_blocks(blocks, cx));
 9819        if let Some(autoscroll) = autoscroll {
 9820            self.request_autoscroll(autoscroll, cx);
 9821        }
 9822    }
 9823
 9824    pub fn remove_blocks(
 9825        &mut self,
 9826        block_ids: HashSet<BlockId>,
 9827        autoscroll: Option<Autoscroll>,
 9828        cx: &mut ViewContext<Self>,
 9829    ) {
 9830        self.display_map.update(cx, |display_map, cx| {
 9831            display_map.remove_blocks(block_ids, cx)
 9832        });
 9833        if let Some(autoscroll) = autoscroll {
 9834            self.request_autoscroll(autoscroll, cx);
 9835        }
 9836    }
 9837
 9838    pub fn insert_flaps(
 9839        &mut self,
 9840        flaps: impl IntoIterator<Item = Flap>,
 9841        cx: &mut ViewContext<Self>,
 9842    ) -> Vec<FlapId> {
 9843        self.display_map
 9844            .update(cx, |map, cx| map.insert_flaps(flaps, cx))
 9845    }
 9846
 9847    pub fn remove_flaps(
 9848        &mut self,
 9849        ids: impl IntoIterator<Item = FlapId>,
 9850        cx: &mut ViewContext<Self>,
 9851    ) {
 9852        self.display_map
 9853            .update(cx, |map, cx| map.remove_flaps(ids, cx));
 9854    }
 9855
 9856    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
 9857        self.display_map
 9858            .update(cx, |map, cx| map.snapshot(cx))
 9859            .longest_row()
 9860    }
 9861
 9862    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
 9863        self.display_map
 9864            .update(cx, |map, cx| map.snapshot(cx))
 9865            .max_point()
 9866    }
 9867
 9868    pub fn text(&self, cx: &AppContext) -> String {
 9869        self.buffer.read(cx).read(cx).text()
 9870    }
 9871
 9872    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
 9873        let text = self.text(cx);
 9874        let text = text.trim();
 9875
 9876        if text.is_empty() {
 9877            return None;
 9878        }
 9879
 9880        Some(text.to_string())
 9881    }
 9882
 9883    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
 9884        self.transact(cx, |this, cx| {
 9885            this.buffer
 9886                .read(cx)
 9887                .as_singleton()
 9888                .expect("you can only call set_text on editors for singleton buffers")
 9889                .update(cx, |buffer, cx| buffer.set_text(text, cx));
 9890        });
 9891    }
 9892
 9893    pub fn display_text(&self, cx: &mut AppContext) -> String {
 9894        self.display_map
 9895            .update(cx, |map, cx| map.snapshot(cx))
 9896            .text()
 9897    }
 9898
 9899    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
 9900        let mut wrap_guides = smallvec::smallvec![];
 9901
 9902        if self.show_wrap_guides == Some(false) {
 9903            return wrap_guides;
 9904        }
 9905
 9906        let settings = self.buffer.read(cx).settings_at(0, cx);
 9907        if settings.show_wrap_guides {
 9908            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
 9909                wrap_guides.push((soft_wrap as usize, true));
 9910            }
 9911            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
 9912        }
 9913
 9914        wrap_guides
 9915    }
 9916
 9917    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
 9918        let settings = self.buffer.read(cx).settings_at(0, cx);
 9919        let mode = self
 9920            .soft_wrap_mode_override
 9921            .unwrap_or_else(|| settings.soft_wrap);
 9922        match mode {
 9923            language_settings::SoftWrap::None => SoftWrap::None,
 9924            language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
 9925            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
 9926            language_settings::SoftWrap::PreferredLineLength => {
 9927                SoftWrap::Column(settings.preferred_line_length)
 9928            }
 9929        }
 9930    }
 9931
 9932    pub fn set_soft_wrap_mode(
 9933        &mut self,
 9934        mode: language_settings::SoftWrap,
 9935        cx: &mut ViewContext<Self>,
 9936    ) {
 9937        self.soft_wrap_mode_override = Some(mode);
 9938        cx.notify();
 9939    }
 9940
 9941    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
 9942        let rem_size = cx.rem_size();
 9943        self.display_map.update(cx, |map, cx| {
 9944            map.set_font(
 9945                style.text.font(),
 9946                style.text.font_size.to_pixels(rem_size),
 9947                cx,
 9948            )
 9949        });
 9950        self.style = Some(style);
 9951    }
 9952
 9953    pub fn style(&self) -> Option<&EditorStyle> {
 9954        self.style.as_ref()
 9955    }
 9956
 9957    // Called by the element. This method is not designed to be called outside of the editor
 9958    // element's layout code because it does not notify when rewrapping is computed synchronously.
 9959    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
 9960        self.display_map
 9961            .update(cx, |map, cx| map.set_wrap_width(width, cx))
 9962    }
 9963
 9964    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
 9965        if self.soft_wrap_mode_override.is_some() {
 9966            self.soft_wrap_mode_override.take();
 9967        } else {
 9968            let soft_wrap = match self.soft_wrap_mode(cx) {
 9969                SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
 9970                SoftWrap::EditorWidth | SoftWrap::Column(_) => {
 9971                    language_settings::SoftWrap::PreferLine
 9972                }
 9973            };
 9974            self.soft_wrap_mode_override = Some(soft_wrap);
 9975        }
 9976        cx.notify();
 9977    }
 9978
 9979    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
 9980        let Some(workspace) = self.workspace() else {
 9981            return;
 9982        };
 9983        let fs = workspace.read(cx).app_state().fs.clone();
 9984        let current_show = TabBarSettings::get_global(cx).show;
 9985        update_settings_file::<TabBarSettings>(fs, cx, move |setting| {
 9986            setting.show = Some(!current_show);
 9987        });
 9988    }
 9989
 9990    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
 9991        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
 9992            self.buffer
 9993                .read(cx)
 9994                .settings_at(0, cx)
 9995                .indent_guides
 9996                .enabled
 9997        });
 9998        self.show_indent_guides = Some(!currently_enabled);
 9999        cx.notify();
10000    }
10001
10002    fn should_show_indent_guides(&self) -> Option<bool> {
10003        self.show_indent_guides
10004    }
10005
10006    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10007        let mut editor_settings = EditorSettings::get_global(cx).clone();
10008        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10009        EditorSettings::override_global(editor_settings, cx);
10010    }
10011
10012    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10013        self.show_gutter = show_gutter;
10014        cx.notify();
10015    }
10016
10017    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10018        self.show_line_numbers = Some(show_line_numbers);
10019        cx.notify();
10020    }
10021
10022    pub fn set_show_git_diff_gutter(
10023        &mut self,
10024        show_git_diff_gutter: bool,
10025        cx: &mut ViewContext<Self>,
10026    ) {
10027        self.show_git_diff_gutter = Some(show_git_diff_gutter);
10028        cx.notify();
10029    }
10030
10031    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10032        self.show_code_actions = Some(show_code_actions);
10033        cx.notify();
10034    }
10035
10036    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10037        self.show_wrap_guides = Some(show_wrap_guides);
10038        cx.notify();
10039    }
10040
10041    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10042        self.show_indent_guides = Some(show_indent_guides);
10043        cx.notify();
10044    }
10045
10046    pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
10047        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10048            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10049                cx.reveal_path(&file.abs_path(cx));
10050            }
10051        }
10052    }
10053
10054    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10055        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10056            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10057                if let Some(path) = file.abs_path(cx).to_str() {
10058                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10059                }
10060            }
10061        }
10062    }
10063
10064    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10065        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10066            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10067                if let Some(path) = file.path().to_str() {
10068                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10069                }
10070            }
10071        }
10072    }
10073
10074    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10075        self.show_git_blame_gutter = !self.show_git_blame_gutter;
10076
10077        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10078            self.start_git_blame(true, cx);
10079        }
10080
10081        cx.notify();
10082    }
10083
10084    pub fn toggle_git_blame_inline(
10085        &mut self,
10086        _: &ToggleGitBlameInline,
10087        cx: &mut ViewContext<Self>,
10088    ) {
10089        self.toggle_git_blame_inline_internal(true, cx);
10090        cx.notify();
10091    }
10092
10093    pub fn git_blame_inline_enabled(&self) -> bool {
10094        self.git_blame_inline_enabled
10095    }
10096
10097    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10098        if let Some(project) = self.project.as_ref() {
10099            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10100                return;
10101            };
10102
10103            if buffer.read(cx).file().is_none() {
10104                return;
10105            }
10106
10107            let focused = self.focus_handle(cx).contains_focused(cx);
10108
10109            let project = project.clone();
10110            let blame =
10111                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10112            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10113            self.blame = Some(blame);
10114        }
10115    }
10116
10117    fn toggle_git_blame_inline_internal(
10118        &mut self,
10119        user_triggered: bool,
10120        cx: &mut ViewContext<Self>,
10121    ) {
10122        if self.git_blame_inline_enabled {
10123            self.git_blame_inline_enabled = false;
10124            self.show_git_blame_inline = false;
10125            self.show_git_blame_inline_delay_task.take();
10126        } else {
10127            self.git_blame_inline_enabled = true;
10128            self.start_git_blame_inline(user_triggered, cx);
10129        }
10130
10131        cx.notify();
10132    }
10133
10134    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10135        self.start_git_blame(user_triggered, cx);
10136
10137        if ProjectSettings::get_global(cx)
10138            .git
10139            .inline_blame_delay()
10140            .is_some()
10141        {
10142            self.start_inline_blame_timer(cx);
10143        } else {
10144            self.show_git_blame_inline = true
10145        }
10146    }
10147
10148    pub fn blame(&self) -> Option<&Model<GitBlame>> {
10149        self.blame.as_ref()
10150    }
10151
10152    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10153        self.show_git_blame_gutter && self.has_blame_entries(cx)
10154    }
10155
10156    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10157        self.show_git_blame_inline
10158            && self.focus_handle.is_focused(cx)
10159            && !self.newest_selection_head_on_empty_line(cx)
10160            && self.has_blame_entries(cx)
10161    }
10162
10163    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10164        self.blame()
10165            .map_or(false, |blame| blame.read(cx).has_generated_entries())
10166    }
10167
10168    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10169        let cursor_anchor = self.selections.newest_anchor().head();
10170
10171        let snapshot = self.buffer.read(cx).snapshot(cx);
10172        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10173
10174        snapshot.line_len(buffer_row) == 0
10175    }
10176
10177    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10178        let (path, selection, repo) = maybe!({
10179            let project_handle = self.project.as_ref()?.clone();
10180            let project = project_handle.read(cx);
10181
10182            let selection = self.selections.newest::<Point>(cx);
10183            let selection_range = selection.range();
10184
10185            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10186                (buffer, selection_range.start.row..selection_range.end.row)
10187            } else {
10188                let buffer_ranges = self
10189                    .buffer()
10190                    .read(cx)
10191                    .range_to_buffer_ranges(selection_range, cx);
10192
10193                let (buffer, range, _) = if selection.reversed {
10194                    buffer_ranges.first()
10195                } else {
10196                    buffer_ranges.last()
10197                }?;
10198
10199                let snapshot = buffer.read(cx).snapshot();
10200                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10201                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
10202                (buffer.clone(), selection)
10203            };
10204
10205            let path = buffer
10206                .read(cx)
10207                .file()?
10208                .as_local()?
10209                .path()
10210                .to_str()?
10211                .to_string();
10212            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10213            Some((path, selection, repo))
10214        })
10215        .ok_or_else(|| anyhow!("unable to open git repository"))?;
10216
10217        const REMOTE_NAME: &str = "origin";
10218        let origin_url = repo
10219            .remote_url(REMOTE_NAME)
10220            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10221        let sha = repo
10222            .head_sha()
10223            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10224
10225        let (provider, remote) =
10226            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10227                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10228
10229        Ok(provider.build_permalink(
10230            remote,
10231            BuildPermalinkParams {
10232                sha: &sha,
10233                path: &path,
10234                selection: Some(selection),
10235            },
10236        ))
10237    }
10238
10239    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10240        let permalink = self.get_permalink_to_line(cx);
10241
10242        match permalink {
10243            Ok(permalink) => {
10244                cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
10245            }
10246            Err(err) => {
10247                let message = format!("Failed to copy permalink: {err}");
10248
10249                Err::<(), anyhow::Error>(err).log_err();
10250
10251                if let Some(workspace) = self.workspace() {
10252                    workspace.update(cx, |workspace, cx| {
10253                        struct CopyPermalinkToLine;
10254
10255                        workspace.show_toast(
10256                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10257                            cx,
10258                        )
10259                    })
10260                }
10261            }
10262        }
10263    }
10264
10265    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10266        let permalink = self.get_permalink_to_line(cx);
10267
10268        match permalink {
10269            Ok(permalink) => {
10270                cx.open_url(permalink.as_ref());
10271            }
10272            Err(err) => {
10273                let message = format!("Failed to open permalink: {err}");
10274
10275                Err::<(), anyhow::Error>(err).log_err();
10276
10277                if let Some(workspace) = self.workspace() {
10278                    workspace.update(cx, |workspace, cx| {
10279                        struct OpenPermalinkToLine;
10280
10281                        workspace.show_toast(
10282                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10283                            cx,
10284                        )
10285                    })
10286                }
10287            }
10288        }
10289    }
10290
10291    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10292    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10293    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10294    pub fn highlight_rows<T: 'static>(
10295        &mut self,
10296        rows: RangeInclusive<Anchor>,
10297        color: Option<Hsla>,
10298        should_autoscroll: bool,
10299        cx: &mut ViewContext<Self>,
10300    ) {
10301        let snapshot = self.buffer().read(cx).snapshot(cx);
10302        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10303        let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10304            highlight
10305                .range
10306                .start()
10307                .cmp(&rows.start(), &snapshot)
10308                .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10309        });
10310        match (color, existing_highlight_index) {
10311            (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10312                ix,
10313                RowHighlight {
10314                    index: post_inc(&mut self.highlight_order),
10315                    range: rows,
10316                    should_autoscroll,
10317                    color,
10318                },
10319            ),
10320            (None, Ok(i)) => {
10321                row_highlights.remove(i);
10322            }
10323        }
10324    }
10325
10326    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10327    pub fn clear_row_highlights<T: 'static>(&mut self) {
10328        self.highlighted_rows.remove(&TypeId::of::<T>());
10329    }
10330
10331    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10332    pub fn highlighted_rows<T: 'static>(
10333        &self,
10334    ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10335        Some(
10336            self.highlighted_rows
10337                .get(&TypeId::of::<T>())?
10338                .iter()
10339                .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10340        )
10341    }
10342
10343    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10344    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10345    /// Allows to ignore certain kinds of highlights.
10346    pub fn highlighted_display_rows(
10347        &mut self,
10348        cx: &mut WindowContext,
10349    ) -> BTreeMap<DisplayRow, Hsla> {
10350        let snapshot = self.snapshot(cx);
10351        let mut used_highlight_orders = HashMap::default();
10352        self.highlighted_rows
10353            .iter()
10354            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10355            .fold(
10356                BTreeMap::<DisplayRow, Hsla>::new(),
10357                |mut unique_rows, highlight| {
10358                    let start_row = highlight.range.start().to_display_point(&snapshot).row();
10359                    let end_row = highlight.range.end().to_display_point(&snapshot).row();
10360                    for row in start_row.0..=end_row.0 {
10361                        let used_index =
10362                            used_highlight_orders.entry(row).or_insert(highlight.index);
10363                        if highlight.index >= *used_index {
10364                            *used_index = highlight.index;
10365                            match highlight.color {
10366                                Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10367                                None => unique_rows.remove(&DisplayRow(row)),
10368                            };
10369                        }
10370                    }
10371                    unique_rows
10372                },
10373            )
10374    }
10375
10376    pub fn highlighted_display_row_for_autoscroll(
10377        &self,
10378        snapshot: &DisplaySnapshot,
10379    ) -> Option<DisplayRow> {
10380        self.highlighted_rows
10381            .values()
10382            .flat_map(|highlighted_rows| highlighted_rows.iter())
10383            .filter_map(|highlight| {
10384                if highlight.color.is_none() || !highlight.should_autoscroll {
10385                    return None;
10386                }
10387                Some(highlight.range.start().to_display_point(&snapshot).row())
10388            })
10389            .min()
10390    }
10391
10392    pub fn set_search_within_ranges(
10393        &mut self,
10394        ranges: &[Range<Anchor>],
10395        cx: &mut ViewContext<Self>,
10396    ) {
10397        self.highlight_background::<SearchWithinRange>(
10398            ranges,
10399            |colors| colors.editor_document_highlight_read_background,
10400            cx,
10401        )
10402    }
10403
10404    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10405        self.clear_background_highlights::<SearchWithinRange>(cx);
10406    }
10407
10408    pub fn highlight_background<T: 'static>(
10409        &mut self,
10410        ranges: &[Range<Anchor>],
10411        color_fetcher: fn(&ThemeColors) -> Hsla,
10412        cx: &mut ViewContext<Self>,
10413    ) {
10414        let snapshot = self.snapshot(cx);
10415        // this is to try and catch a panic sooner
10416        for range in ranges {
10417            snapshot
10418                .buffer_snapshot
10419                .summary_for_anchor::<usize>(&range.start);
10420            snapshot
10421                .buffer_snapshot
10422                .summary_for_anchor::<usize>(&range.end);
10423        }
10424
10425        self.background_highlights
10426            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10427        self.scrollbar_marker_state.dirty = true;
10428        cx.notify();
10429    }
10430
10431    pub fn clear_background_highlights<T: 'static>(
10432        &mut self,
10433        cx: &mut ViewContext<Self>,
10434    ) -> Option<BackgroundHighlight> {
10435        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10436        if !text_highlights.1.is_empty() {
10437            self.scrollbar_marker_state.dirty = true;
10438            cx.notify();
10439        }
10440        Some(text_highlights)
10441    }
10442
10443    pub fn highlight_gutter<T: 'static>(
10444        &mut self,
10445        ranges: &[Range<Anchor>],
10446        color_fetcher: fn(&AppContext) -> Hsla,
10447        cx: &mut ViewContext<Self>,
10448    ) {
10449        self.gutter_highlights
10450            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10451        cx.notify();
10452    }
10453
10454    pub fn clear_gutter_highlights<T: 'static>(
10455        &mut self,
10456        cx: &mut ViewContext<Self>,
10457    ) -> Option<GutterHighlight> {
10458        cx.notify();
10459        self.gutter_highlights.remove(&TypeId::of::<T>())
10460    }
10461
10462    #[cfg(feature = "test-support")]
10463    pub fn all_text_background_highlights(
10464        &mut self,
10465        cx: &mut ViewContext<Self>,
10466    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10467        let snapshot = self.snapshot(cx);
10468        let buffer = &snapshot.buffer_snapshot;
10469        let start = buffer.anchor_before(0);
10470        let end = buffer.anchor_after(buffer.len());
10471        let theme = cx.theme().colors();
10472        self.background_highlights_in_range(start..end, &snapshot, theme)
10473    }
10474
10475    #[cfg(feature = "test-support")]
10476    pub fn search_background_highlights(
10477        &mut self,
10478        cx: &mut ViewContext<Self>,
10479    ) -> Vec<Range<Point>> {
10480        let snapshot = self.buffer().read(cx).snapshot(cx);
10481
10482        let highlights = self
10483            .background_highlights
10484            .get(&TypeId::of::<items::BufferSearchHighlights>());
10485
10486        if let Some((_color, ranges)) = highlights {
10487            ranges
10488                .iter()
10489                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
10490                .collect_vec()
10491        } else {
10492            vec![]
10493        }
10494    }
10495
10496    fn document_highlights_for_position<'a>(
10497        &'a self,
10498        position: Anchor,
10499        buffer: &'a MultiBufferSnapshot,
10500    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
10501        let read_highlights = self
10502            .background_highlights
10503            .get(&TypeId::of::<DocumentHighlightRead>())
10504            .map(|h| &h.1);
10505        let write_highlights = self
10506            .background_highlights
10507            .get(&TypeId::of::<DocumentHighlightWrite>())
10508            .map(|h| &h.1);
10509        let left_position = position.bias_left(buffer);
10510        let right_position = position.bias_right(buffer);
10511        read_highlights
10512            .into_iter()
10513            .chain(write_highlights)
10514            .flat_map(move |ranges| {
10515                let start_ix = match ranges.binary_search_by(|probe| {
10516                    let cmp = probe.end.cmp(&left_position, buffer);
10517                    if cmp.is_ge() {
10518                        Ordering::Greater
10519                    } else {
10520                        Ordering::Less
10521                    }
10522                }) {
10523                    Ok(i) | Err(i) => i,
10524                };
10525
10526                ranges[start_ix..]
10527                    .iter()
10528                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
10529            })
10530    }
10531
10532    pub fn has_background_highlights<T: 'static>(&self) -> bool {
10533        self.background_highlights
10534            .get(&TypeId::of::<T>())
10535            .map_or(false, |(_, highlights)| !highlights.is_empty())
10536    }
10537
10538    pub fn background_highlights_in_range(
10539        &self,
10540        search_range: Range<Anchor>,
10541        display_snapshot: &DisplaySnapshot,
10542        theme: &ThemeColors,
10543    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10544        let mut results = Vec::new();
10545        for (color_fetcher, ranges) in self.background_highlights.values() {
10546            let color = color_fetcher(theme);
10547            let start_ix = match ranges.binary_search_by(|probe| {
10548                let cmp = probe
10549                    .end
10550                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10551                if cmp.is_gt() {
10552                    Ordering::Greater
10553                } else {
10554                    Ordering::Less
10555                }
10556            }) {
10557                Ok(i) | Err(i) => i,
10558            };
10559            for range in &ranges[start_ix..] {
10560                if range
10561                    .start
10562                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10563                    .is_ge()
10564                {
10565                    break;
10566                }
10567
10568                let start = range.start.to_display_point(&display_snapshot);
10569                let end = range.end.to_display_point(&display_snapshot);
10570                results.push((start..end, color))
10571            }
10572        }
10573        results
10574    }
10575
10576    pub fn background_highlight_row_ranges<T: 'static>(
10577        &self,
10578        search_range: Range<Anchor>,
10579        display_snapshot: &DisplaySnapshot,
10580        count: usize,
10581    ) -> Vec<RangeInclusive<DisplayPoint>> {
10582        let mut results = Vec::new();
10583        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
10584            return vec![];
10585        };
10586
10587        let start_ix = match ranges.binary_search_by(|probe| {
10588            let cmp = probe
10589                .end
10590                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10591            if cmp.is_gt() {
10592                Ordering::Greater
10593            } else {
10594                Ordering::Less
10595            }
10596        }) {
10597            Ok(i) | Err(i) => i,
10598        };
10599        let mut push_region = |start: Option<Point>, end: Option<Point>| {
10600            if let (Some(start_display), Some(end_display)) = (start, end) {
10601                results.push(
10602                    start_display.to_display_point(display_snapshot)
10603                        ..=end_display.to_display_point(display_snapshot),
10604                );
10605            }
10606        };
10607        let mut start_row: Option<Point> = None;
10608        let mut end_row: Option<Point> = None;
10609        if ranges.len() > count {
10610            return Vec::new();
10611        }
10612        for range in &ranges[start_ix..] {
10613            if range
10614                .start
10615                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10616                .is_ge()
10617            {
10618                break;
10619            }
10620            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
10621            if let Some(current_row) = &end_row {
10622                if end.row == current_row.row {
10623                    continue;
10624                }
10625            }
10626            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
10627            if start_row.is_none() {
10628                assert_eq!(end_row, None);
10629                start_row = Some(start);
10630                end_row = Some(end);
10631                continue;
10632            }
10633            if let Some(current_end) = end_row.as_mut() {
10634                if start.row > current_end.row + 1 {
10635                    push_region(start_row, end_row);
10636                    start_row = Some(start);
10637                    end_row = Some(end);
10638                } else {
10639                    // Merge two hunks.
10640                    *current_end = end;
10641                }
10642            } else {
10643                unreachable!();
10644            }
10645        }
10646        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
10647        push_region(start_row, end_row);
10648        results
10649    }
10650
10651    pub fn gutter_highlights_in_range(
10652        &self,
10653        search_range: Range<Anchor>,
10654        display_snapshot: &DisplaySnapshot,
10655        cx: &AppContext,
10656    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10657        let mut results = Vec::new();
10658        for (color_fetcher, ranges) in self.gutter_highlights.values() {
10659            let color = color_fetcher(cx);
10660            let start_ix = match ranges.binary_search_by(|probe| {
10661                let cmp = probe
10662                    .end
10663                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10664                if cmp.is_gt() {
10665                    Ordering::Greater
10666                } else {
10667                    Ordering::Less
10668                }
10669            }) {
10670                Ok(i) | Err(i) => i,
10671            };
10672            for range in &ranges[start_ix..] {
10673                if range
10674                    .start
10675                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10676                    .is_ge()
10677                {
10678                    break;
10679                }
10680
10681                let start = range.start.to_display_point(&display_snapshot);
10682                let end = range.end.to_display_point(&display_snapshot);
10683                results.push((start..end, color))
10684            }
10685        }
10686        results
10687    }
10688
10689    /// Get the text ranges corresponding to the redaction query
10690    pub fn redacted_ranges(
10691        &self,
10692        search_range: Range<Anchor>,
10693        display_snapshot: &DisplaySnapshot,
10694        cx: &WindowContext,
10695    ) -> Vec<Range<DisplayPoint>> {
10696        display_snapshot
10697            .buffer_snapshot
10698            .redacted_ranges(search_range, |file| {
10699                if let Some(file) = file {
10700                    file.is_private()
10701                        && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
10702                } else {
10703                    false
10704                }
10705            })
10706            .map(|range| {
10707                range.start.to_display_point(display_snapshot)
10708                    ..range.end.to_display_point(display_snapshot)
10709            })
10710            .collect()
10711    }
10712
10713    pub fn highlight_text<T: 'static>(
10714        &mut self,
10715        ranges: Vec<Range<Anchor>>,
10716        style: HighlightStyle,
10717        cx: &mut ViewContext<Self>,
10718    ) {
10719        self.display_map.update(cx, |map, _| {
10720            map.highlight_text(TypeId::of::<T>(), ranges, style)
10721        });
10722        cx.notify();
10723    }
10724
10725    pub(crate) fn highlight_inlays<T: 'static>(
10726        &mut self,
10727        highlights: Vec<InlayHighlight>,
10728        style: HighlightStyle,
10729        cx: &mut ViewContext<Self>,
10730    ) {
10731        self.display_map.update(cx, |map, _| {
10732            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
10733        });
10734        cx.notify();
10735    }
10736
10737    pub fn text_highlights<'a, T: 'static>(
10738        &'a self,
10739        cx: &'a AppContext,
10740    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
10741        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
10742    }
10743
10744    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
10745        let cleared = self
10746            .display_map
10747            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
10748        if cleared {
10749            cx.notify();
10750        }
10751    }
10752
10753    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
10754        (self.read_only(cx) || self.blink_manager.read(cx).visible())
10755            && self.focus_handle.is_focused(cx)
10756    }
10757
10758    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
10759        cx.notify();
10760    }
10761
10762    fn on_buffer_event(
10763        &mut self,
10764        multibuffer: Model<MultiBuffer>,
10765        event: &multi_buffer::Event,
10766        cx: &mut ViewContext<Self>,
10767    ) {
10768        match event {
10769            multi_buffer::Event::Edited {
10770                singleton_buffer_edited,
10771            } => {
10772                self.scrollbar_marker_state.dirty = true;
10773                self.active_indent_guides_state.dirty = true;
10774                self.refresh_active_diagnostics(cx);
10775                self.refresh_code_actions(cx);
10776                if self.has_active_inline_completion(cx) {
10777                    self.update_visible_inline_completion(cx);
10778                }
10779                cx.emit(EditorEvent::BufferEdited);
10780                cx.emit(SearchEvent::MatchesInvalidated);
10781                if *singleton_buffer_edited {
10782                    if let Some(project) = &self.project {
10783                        let project = project.read(cx);
10784                        let languages_affected = multibuffer
10785                            .read(cx)
10786                            .all_buffers()
10787                            .into_iter()
10788                            .filter_map(|buffer| {
10789                                let buffer = buffer.read(cx);
10790                                let language = buffer.language()?;
10791                                if project.is_local()
10792                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
10793                                {
10794                                    None
10795                                } else {
10796                                    Some(language)
10797                                }
10798                            })
10799                            .cloned()
10800                            .collect::<HashSet<_>>();
10801                        if !languages_affected.is_empty() {
10802                            self.refresh_inlay_hints(
10803                                InlayHintRefreshReason::BufferEdited(languages_affected),
10804                                cx,
10805                            );
10806                        }
10807                    }
10808                }
10809
10810                let Some(project) = &self.project else { return };
10811                let telemetry = project.read(cx).client().telemetry().clone();
10812                refresh_linked_ranges(self, cx);
10813                telemetry.log_edit_event("editor");
10814            }
10815            multi_buffer::Event::ExcerptsAdded {
10816                buffer,
10817                predecessor,
10818                excerpts,
10819            } => {
10820                self.tasks_update_task = Some(self.refresh_runnables(cx));
10821                cx.emit(EditorEvent::ExcerptsAdded {
10822                    buffer: buffer.clone(),
10823                    predecessor: *predecessor,
10824                    excerpts: excerpts.clone(),
10825                });
10826                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
10827            }
10828            multi_buffer::Event::ExcerptsRemoved { ids } => {
10829                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
10830                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
10831            }
10832            multi_buffer::Event::Reparsed => {
10833                self.tasks_update_task = Some(self.refresh_runnables(cx));
10834
10835                cx.emit(EditorEvent::Reparsed);
10836            }
10837            multi_buffer::Event::LanguageChanged => {
10838                linked_editing_ranges::refresh_linked_ranges(self, cx);
10839                cx.emit(EditorEvent::Reparsed);
10840                cx.notify();
10841            }
10842            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
10843            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
10844            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
10845                cx.emit(EditorEvent::TitleChanged)
10846            }
10847            multi_buffer::Event::DiffBaseChanged => {
10848                self.scrollbar_marker_state.dirty = true;
10849                cx.emit(EditorEvent::DiffBaseChanged);
10850                cx.notify();
10851            }
10852            multi_buffer::Event::DiffUpdated { buffer } => {
10853                self.sync_expanded_diff_hunks(buffer.clone(), cx);
10854                cx.notify();
10855            }
10856            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
10857            multi_buffer::Event::DiagnosticsUpdated => {
10858                self.refresh_active_diagnostics(cx);
10859                self.scrollbar_marker_state.dirty = true;
10860                cx.notify();
10861            }
10862            _ => {}
10863        };
10864    }
10865
10866    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
10867        cx.notify();
10868    }
10869
10870    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
10871        self.refresh_inline_completion(true, cx);
10872        self.refresh_inlay_hints(
10873            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
10874                self.selections.newest_anchor().head(),
10875                &self.buffer.read(cx).snapshot(cx),
10876                cx,
10877            )),
10878            cx,
10879        );
10880        let editor_settings = EditorSettings::get_global(cx);
10881        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
10882        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
10883
10884        if self.mode == EditorMode::Full {
10885            let inline_blame_enabled = ProjectSettings::get_global(cx).git.inline_blame_enabled();
10886            if self.git_blame_inline_enabled != inline_blame_enabled {
10887                self.toggle_git_blame_inline_internal(false, cx);
10888            }
10889        }
10890
10891        cx.notify();
10892    }
10893
10894    pub fn set_searchable(&mut self, searchable: bool) {
10895        self.searchable = searchable;
10896    }
10897
10898    pub fn searchable(&self) -> bool {
10899        self.searchable
10900    }
10901
10902    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
10903        self.open_excerpts_common(true, cx)
10904    }
10905
10906    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
10907        self.open_excerpts_common(false, cx)
10908    }
10909
10910    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
10911        let buffer = self.buffer.read(cx);
10912        if buffer.is_singleton() {
10913            cx.propagate();
10914            return;
10915        }
10916
10917        let Some(workspace) = self.workspace() else {
10918            cx.propagate();
10919            return;
10920        };
10921
10922        let mut new_selections_by_buffer = HashMap::default();
10923        for selection in self.selections.all::<usize>(cx) {
10924            for (buffer, mut range, _) in
10925                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
10926            {
10927                if selection.reversed {
10928                    mem::swap(&mut range.start, &mut range.end);
10929                }
10930                new_selections_by_buffer
10931                    .entry(buffer)
10932                    .or_insert(Vec::new())
10933                    .push(range)
10934            }
10935        }
10936
10937        // We defer the pane interaction because we ourselves are a workspace item
10938        // and activating a new item causes the pane to call a method on us reentrantly,
10939        // which panics if we're on the stack.
10940        cx.window_context().defer(move |cx| {
10941            workspace.update(cx, |workspace, cx| {
10942                let pane = if split {
10943                    workspace.adjacent_pane(cx)
10944                } else {
10945                    workspace.active_pane().clone()
10946                };
10947
10948                for (buffer, ranges) in new_selections_by_buffer {
10949                    let editor = workspace.open_project_item::<Self>(pane.clone(), buffer, cx);
10950                    editor.update(cx, |editor, cx| {
10951                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
10952                            s.select_ranges(ranges);
10953                        });
10954                    });
10955                }
10956            })
10957        });
10958    }
10959
10960    fn jump(
10961        &mut self,
10962        path: ProjectPath,
10963        position: Point,
10964        anchor: language::Anchor,
10965        offset_from_top: u32,
10966        cx: &mut ViewContext<Self>,
10967    ) {
10968        let workspace = self.workspace();
10969        cx.spawn(|_, mut cx| async move {
10970            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
10971            let editor = workspace.update(&mut cx, |workspace, cx| {
10972                // Reset the preview item id before opening the new item
10973                workspace.active_pane().update(cx, |pane, cx| {
10974                    pane.set_preview_item_id(None, cx);
10975                });
10976                workspace.open_path_preview(path, None, true, true, cx)
10977            })?;
10978            let editor = editor
10979                .await?
10980                .downcast::<Editor>()
10981                .ok_or_else(|| anyhow!("opened item was not an editor"))?
10982                .downgrade();
10983            editor.update(&mut cx, |editor, cx| {
10984                let buffer = editor
10985                    .buffer()
10986                    .read(cx)
10987                    .as_singleton()
10988                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
10989                let buffer = buffer.read(cx);
10990                let cursor = if buffer.can_resolve(&anchor) {
10991                    language::ToPoint::to_point(&anchor, buffer)
10992                } else {
10993                    buffer.clip_point(position, Bias::Left)
10994                };
10995
10996                let nav_history = editor.nav_history.take();
10997                editor.change_selections(
10998                    Some(Autoscroll::top_relative(offset_from_top as usize)),
10999                    cx,
11000                    |s| {
11001                        s.select_ranges([cursor..cursor]);
11002                    },
11003                );
11004                editor.nav_history = nav_history;
11005
11006                anyhow::Ok(())
11007            })??;
11008
11009            anyhow::Ok(())
11010        })
11011        .detach_and_log_err(cx);
11012    }
11013
11014    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11015        let snapshot = self.buffer.read(cx).read(cx);
11016        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11017        Some(
11018            ranges
11019                .iter()
11020                .map(move |range| {
11021                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11022                })
11023                .collect(),
11024        )
11025    }
11026
11027    fn selection_replacement_ranges(
11028        &self,
11029        range: Range<OffsetUtf16>,
11030        cx: &AppContext,
11031    ) -> Vec<Range<OffsetUtf16>> {
11032        let selections = self.selections.all::<OffsetUtf16>(cx);
11033        let newest_selection = selections
11034            .iter()
11035            .max_by_key(|selection| selection.id)
11036            .unwrap();
11037        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11038        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11039        let snapshot = self.buffer.read(cx).read(cx);
11040        selections
11041            .into_iter()
11042            .map(|mut selection| {
11043                selection.start.0 =
11044                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
11045                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11046                snapshot.clip_offset_utf16(selection.start, Bias::Left)
11047                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11048            })
11049            .collect()
11050    }
11051
11052    fn report_editor_event(
11053        &self,
11054        operation: &'static str,
11055        file_extension: Option<String>,
11056        cx: &AppContext,
11057    ) {
11058        if cfg!(any(test, feature = "test-support")) {
11059            return;
11060        }
11061
11062        let Some(project) = &self.project else { return };
11063
11064        // If None, we are in a file without an extension
11065        let file = self
11066            .buffer
11067            .read(cx)
11068            .as_singleton()
11069            .and_then(|b| b.read(cx).file());
11070        let file_extension = file_extension.or(file
11071            .as_ref()
11072            .and_then(|file| Path::new(file.file_name(cx)).extension())
11073            .and_then(|e| e.to_str())
11074            .map(|a| a.to_string()));
11075
11076        let vim_mode = cx
11077            .global::<SettingsStore>()
11078            .raw_user_settings()
11079            .get("vim_mode")
11080            == Some(&serde_json::Value::Bool(true));
11081
11082        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11083            == language::language_settings::InlineCompletionProvider::Copilot;
11084        let copilot_enabled_for_language = self
11085            .buffer
11086            .read(cx)
11087            .settings_at(0, cx)
11088            .show_inline_completions;
11089
11090        let telemetry = project.read(cx).client().telemetry().clone();
11091        telemetry.report_editor_event(
11092            file_extension,
11093            vim_mode,
11094            operation,
11095            copilot_enabled,
11096            copilot_enabled_for_language,
11097        )
11098    }
11099
11100    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11101    /// with each line being an array of {text, highlight} objects.
11102    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11103        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11104            return;
11105        };
11106
11107        #[derive(Serialize)]
11108        struct Chunk<'a> {
11109            text: String,
11110            highlight: Option<&'a str>,
11111        }
11112
11113        let snapshot = buffer.read(cx).snapshot();
11114        let range = self
11115            .selected_text_range(cx)
11116            .and_then(|selected_range| {
11117                if selected_range.is_empty() {
11118                    None
11119                } else {
11120                    Some(selected_range)
11121                }
11122            })
11123            .unwrap_or_else(|| 0..snapshot.len());
11124
11125        let chunks = snapshot.chunks(range, true);
11126        let mut lines = Vec::new();
11127        let mut line: VecDeque<Chunk> = VecDeque::new();
11128
11129        let Some(style) = self.style.as_ref() else {
11130            return;
11131        };
11132
11133        for chunk in chunks {
11134            let highlight = chunk
11135                .syntax_highlight_id
11136                .and_then(|id| id.name(&style.syntax));
11137            let mut chunk_lines = chunk.text.split('\n').peekable();
11138            while let Some(text) = chunk_lines.next() {
11139                let mut merged_with_last_token = false;
11140                if let Some(last_token) = line.back_mut() {
11141                    if last_token.highlight == highlight {
11142                        last_token.text.push_str(text);
11143                        merged_with_last_token = true;
11144                    }
11145                }
11146
11147                if !merged_with_last_token {
11148                    line.push_back(Chunk {
11149                        text: text.into(),
11150                        highlight,
11151                    });
11152                }
11153
11154                if chunk_lines.peek().is_some() {
11155                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
11156                        line.pop_front();
11157                    }
11158                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
11159                        line.pop_back();
11160                    }
11161
11162                    lines.push(mem::take(&mut line));
11163                }
11164            }
11165        }
11166
11167        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11168            return;
11169        };
11170        cx.write_to_clipboard(ClipboardItem::new(lines));
11171    }
11172
11173    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11174        &self.inlay_hint_cache
11175    }
11176
11177    pub fn replay_insert_event(
11178        &mut self,
11179        text: &str,
11180        relative_utf16_range: Option<Range<isize>>,
11181        cx: &mut ViewContext<Self>,
11182    ) {
11183        if !self.input_enabled {
11184            cx.emit(EditorEvent::InputIgnored { text: text.into() });
11185            return;
11186        }
11187        if let Some(relative_utf16_range) = relative_utf16_range {
11188            let selections = self.selections.all::<OffsetUtf16>(cx);
11189            self.change_selections(None, cx, |s| {
11190                let new_ranges = selections.into_iter().map(|range| {
11191                    let start = OffsetUtf16(
11192                        range
11193                            .head()
11194                            .0
11195                            .saturating_add_signed(relative_utf16_range.start),
11196                    );
11197                    let end = OffsetUtf16(
11198                        range
11199                            .head()
11200                            .0
11201                            .saturating_add_signed(relative_utf16_range.end),
11202                    );
11203                    start..end
11204                });
11205                s.select_ranges(new_ranges);
11206            });
11207        }
11208
11209        self.handle_input(text, cx);
11210    }
11211
11212    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11213        let Some(project) = self.project.as_ref() else {
11214            return false;
11215        };
11216        let project = project.read(cx);
11217
11218        let mut supports = false;
11219        self.buffer().read(cx).for_each_buffer(|buffer| {
11220            if !supports {
11221                supports = project
11222                    .language_servers_for_buffer(buffer.read(cx), cx)
11223                    .any(
11224                        |(_, server)| match server.capabilities().inlay_hint_provider {
11225                            Some(lsp::OneOf::Left(enabled)) => enabled,
11226                            Some(lsp::OneOf::Right(_)) => true,
11227                            None => false,
11228                        },
11229                    )
11230            }
11231        });
11232        supports
11233    }
11234
11235    pub fn focus(&self, cx: &mut WindowContext) {
11236        cx.focus(&self.focus_handle)
11237    }
11238
11239    pub fn is_focused(&self, cx: &WindowContext) -> bool {
11240        self.focus_handle.is_focused(cx)
11241    }
11242
11243    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11244        cx.emit(EditorEvent::Focused);
11245        if let Some(rename) = self.pending_rename.as_ref() {
11246            let rename_editor_focus_handle = rename.editor.read(cx).focus_handle.clone();
11247            cx.focus(&rename_editor_focus_handle);
11248        } else {
11249            if let Some(blame) = self.blame.as_ref() {
11250                blame.update(cx, GitBlame::focus)
11251            }
11252
11253            self.blink_manager.update(cx, BlinkManager::enable);
11254            self.show_cursor_names(cx);
11255            self.buffer.update(cx, |buffer, cx| {
11256                buffer.finalize_last_transaction(cx);
11257                if self.leader_peer_id.is_none() {
11258                    buffer.set_active_selections(
11259                        &self.selections.disjoint_anchors(),
11260                        self.selections.line_mode,
11261                        self.cursor_shape,
11262                        cx,
11263                    );
11264                }
11265            });
11266        }
11267    }
11268
11269    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11270        self.blink_manager.update(cx, BlinkManager::disable);
11271        self.buffer
11272            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11273
11274        if let Some(blame) = self.blame.as_ref() {
11275            blame.update(cx, GitBlame::blur)
11276        }
11277        self.hide_context_menu(cx);
11278        hide_hover(self, cx);
11279        cx.emit(EditorEvent::Blurred);
11280        cx.notify();
11281    }
11282
11283    pub fn register_action<A: Action>(
11284        &mut self,
11285        listener: impl Fn(&A, &mut WindowContext) + 'static,
11286    ) -> &mut Self {
11287        let listener = Arc::new(listener);
11288
11289        self.editor_actions.push(Box::new(move |cx| {
11290            let _view = cx.view().clone();
11291            let cx = cx.window_context();
11292            let listener = listener.clone();
11293            cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11294                let action = action.downcast_ref().unwrap();
11295                if phase == DispatchPhase::Bubble {
11296                    listener(action, cx)
11297                }
11298            })
11299        }));
11300        self
11301    }
11302}
11303
11304fn hunks_for_selections(
11305    multi_buffer_snapshot: &MultiBufferSnapshot,
11306    selections: &[Selection<Anchor>],
11307) -> Vec<DiffHunk<MultiBufferRow>> {
11308    let mut hunks = Vec::with_capacity(selections.len());
11309    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11310        HashMap::default();
11311    let buffer_rows_for_selections = selections.iter().map(|selection| {
11312        let head = selection.head();
11313        let tail = selection.tail();
11314        let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11315        let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11316        if start > end {
11317            end..start
11318        } else {
11319            start..end
11320        }
11321    });
11322
11323    for selected_multi_buffer_rows in buffer_rows_for_selections {
11324        let query_rows =
11325            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11326        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11327            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11328            // when the caret is just above or just below the deleted hunk.
11329            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11330            let related_to_selection = if allow_adjacent {
11331                hunk.associated_range.overlaps(&query_rows)
11332                    || hunk.associated_range.start == query_rows.end
11333                    || hunk.associated_range.end == query_rows.start
11334            } else {
11335                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11336                // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11337                hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11338                    || selected_multi_buffer_rows.end == hunk.associated_range.start
11339            };
11340            if related_to_selection {
11341                if !processed_buffer_rows
11342                    .entry(hunk.buffer_id)
11343                    .or_default()
11344                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
11345                {
11346                    continue;
11347                }
11348                hunks.push(hunk);
11349            }
11350        }
11351    }
11352
11353    hunks
11354}
11355
11356pub trait CollaborationHub {
11357    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
11358    fn user_participant_indices<'a>(
11359        &self,
11360        cx: &'a AppContext,
11361    ) -> &'a HashMap<u64, ParticipantIndex>;
11362    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
11363}
11364
11365impl CollaborationHub for Model<Project> {
11366    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
11367        self.read(cx).collaborators()
11368    }
11369
11370    fn user_participant_indices<'a>(
11371        &self,
11372        cx: &'a AppContext,
11373    ) -> &'a HashMap<u64, ParticipantIndex> {
11374        self.read(cx).user_store().read(cx).participant_indices()
11375    }
11376
11377    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
11378        let this = self.read(cx);
11379        let user_ids = this.collaborators().values().map(|c| c.user_id);
11380        this.user_store().read_with(cx, |user_store, cx| {
11381            user_store.participant_names(user_ids, cx)
11382        })
11383    }
11384}
11385
11386pub trait CompletionProvider {
11387    fn completions(
11388        &self,
11389        buffer: &Model<Buffer>,
11390        buffer_position: text::Anchor,
11391        cx: &mut ViewContext<Editor>,
11392    ) -> Task<Result<Vec<Completion>>>;
11393
11394    fn resolve_completions(
11395        &self,
11396        buffer: Model<Buffer>,
11397        completion_indices: Vec<usize>,
11398        completions: Arc<RwLock<Box<[Completion]>>>,
11399        cx: &mut ViewContext<Editor>,
11400    ) -> Task<Result<bool>>;
11401
11402    fn apply_additional_edits_for_completion(
11403        &self,
11404        buffer: Model<Buffer>,
11405        completion: Completion,
11406        push_to_history: bool,
11407        cx: &mut ViewContext<Editor>,
11408    ) -> Task<Result<Option<language::Transaction>>>;
11409
11410    fn is_completion_trigger(
11411        &self,
11412        buffer: &Model<Buffer>,
11413        position: language::Anchor,
11414        text: &str,
11415        trigger_in_words: bool,
11416        cx: &mut ViewContext<Editor>,
11417    ) -> bool;
11418}
11419
11420impl CompletionProvider for Model<Project> {
11421    fn completions(
11422        &self,
11423        buffer: &Model<Buffer>,
11424        buffer_position: text::Anchor,
11425        cx: &mut ViewContext<Editor>,
11426    ) -> Task<Result<Vec<Completion>>> {
11427        self.update(cx, |project, cx| {
11428            project.completions(&buffer, buffer_position, cx)
11429        })
11430    }
11431
11432    fn resolve_completions(
11433        &self,
11434        buffer: Model<Buffer>,
11435        completion_indices: Vec<usize>,
11436        completions: Arc<RwLock<Box<[Completion]>>>,
11437        cx: &mut ViewContext<Editor>,
11438    ) -> Task<Result<bool>> {
11439        self.update(cx, |project, cx| {
11440            project.resolve_completions(buffer, completion_indices, completions, cx)
11441        })
11442    }
11443
11444    fn apply_additional_edits_for_completion(
11445        &self,
11446        buffer: Model<Buffer>,
11447        completion: Completion,
11448        push_to_history: bool,
11449        cx: &mut ViewContext<Editor>,
11450    ) -> Task<Result<Option<language::Transaction>>> {
11451        self.update(cx, |project, cx| {
11452            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
11453        })
11454    }
11455
11456    fn is_completion_trigger(
11457        &self,
11458        buffer: &Model<Buffer>,
11459        position: language::Anchor,
11460        text: &str,
11461        trigger_in_words: bool,
11462        cx: &mut ViewContext<Editor>,
11463    ) -> bool {
11464        if !EditorSettings::get_global(cx).show_completions_on_input {
11465            return false;
11466        }
11467
11468        let mut chars = text.chars();
11469        let char = if let Some(char) = chars.next() {
11470            char
11471        } else {
11472            return false;
11473        };
11474        if chars.next().is_some() {
11475            return false;
11476        }
11477
11478        let buffer = buffer.read(cx);
11479        let scope = buffer.snapshot().language_scope_at(position);
11480        if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
11481            return true;
11482        }
11483
11484        buffer
11485            .completion_triggers()
11486            .iter()
11487            .any(|string| string == text)
11488    }
11489}
11490
11491fn inlay_hint_settings(
11492    location: Anchor,
11493    snapshot: &MultiBufferSnapshot,
11494    cx: &mut ViewContext<'_, Editor>,
11495) -> InlayHintSettings {
11496    let file = snapshot.file_at(location);
11497    let language = snapshot.language_at(location);
11498    let settings = all_language_settings(file, cx);
11499    settings
11500        .language(language.map(|l| l.name()).as_deref())
11501        .inlay_hints
11502}
11503
11504fn consume_contiguous_rows(
11505    contiguous_row_selections: &mut Vec<Selection<Point>>,
11506    selection: &Selection<Point>,
11507    display_map: &DisplaySnapshot,
11508    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
11509) -> (MultiBufferRow, MultiBufferRow) {
11510    contiguous_row_selections.push(selection.clone());
11511    let start_row = MultiBufferRow(selection.start.row);
11512    let mut end_row = ending_row(selection, display_map);
11513
11514    while let Some(next_selection) = selections.peek() {
11515        if next_selection.start.row <= end_row.0 {
11516            end_row = ending_row(next_selection, display_map);
11517            contiguous_row_selections.push(selections.next().unwrap().clone());
11518        } else {
11519            break;
11520        }
11521    }
11522    (start_row, end_row)
11523}
11524
11525fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
11526    if next_selection.end.column > 0 || next_selection.is_empty() {
11527        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
11528    } else {
11529        MultiBufferRow(next_selection.end.row)
11530    }
11531}
11532
11533impl EditorSnapshot {
11534    pub fn remote_selections_in_range<'a>(
11535        &'a self,
11536        range: &'a Range<Anchor>,
11537        collaboration_hub: &dyn CollaborationHub,
11538        cx: &'a AppContext,
11539    ) -> impl 'a + Iterator<Item = RemoteSelection> {
11540        let participant_names = collaboration_hub.user_names(cx);
11541        let participant_indices = collaboration_hub.user_participant_indices(cx);
11542        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
11543        let collaborators_by_replica_id = collaborators_by_peer_id
11544            .iter()
11545            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
11546            .collect::<HashMap<_, _>>();
11547        self.buffer_snapshot
11548            .remote_selections_in_range(range)
11549            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
11550                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
11551                let participant_index = participant_indices.get(&collaborator.user_id).copied();
11552                let user_name = participant_names.get(&collaborator.user_id).cloned();
11553                Some(RemoteSelection {
11554                    replica_id,
11555                    selection,
11556                    cursor_shape,
11557                    line_mode,
11558                    participant_index,
11559                    peer_id: collaborator.peer_id,
11560                    user_name,
11561                })
11562            })
11563    }
11564
11565    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
11566        self.display_snapshot.buffer_snapshot.language_at(position)
11567    }
11568
11569    pub fn is_focused(&self) -> bool {
11570        self.is_focused
11571    }
11572
11573    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
11574        self.placeholder_text.as_ref()
11575    }
11576
11577    pub fn scroll_position(&self) -> gpui::Point<f32> {
11578        self.scroll_anchor.scroll_position(&self.display_snapshot)
11579    }
11580
11581    pub fn gutter_dimensions(
11582        &self,
11583        font_id: FontId,
11584        font_size: Pixels,
11585        em_width: Pixels,
11586        max_line_number_width: Pixels,
11587        cx: &AppContext,
11588    ) -> GutterDimensions {
11589        if !self.show_gutter {
11590            return GutterDimensions::default();
11591        }
11592        let descent = cx.text_system().descent(font_id, font_size);
11593
11594        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
11595            matches!(
11596                ProjectSettings::get_global(cx).git.git_gutter,
11597                Some(GitGutterSetting::TrackedFiles)
11598            )
11599        });
11600        let gutter_settings = EditorSettings::get_global(cx).gutter;
11601        let show_line_numbers = self
11602            .show_line_numbers
11603            .unwrap_or_else(|| gutter_settings.line_numbers);
11604        let line_gutter_width = if show_line_numbers {
11605            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
11606            let min_width_for_number_on_gutter = em_width * 4.0;
11607            max_line_number_width.max(min_width_for_number_on_gutter)
11608        } else {
11609            0.0.into()
11610        };
11611
11612        let show_code_actions = self
11613            .show_code_actions
11614            .unwrap_or_else(|| gutter_settings.code_actions);
11615
11616        let git_blame_entries_width = self
11617            .render_git_blame_gutter
11618            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
11619
11620        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
11621        left_padding += if show_code_actions {
11622            em_width * 3.0
11623        } else if show_git_gutter && show_line_numbers {
11624            em_width * 2.0
11625        } else if show_git_gutter || show_line_numbers {
11626            em_width
11627        } else {
11628            px(0.)
11629        };
11630
11631        let right_padding = if gutter_settings.folds && show_line_numbers {
11632            em_width * 4.0
11633        } else if gutter_settings.folds {
11634            em_width * 3.0
11635        } else if show_line_numbers {
11636            em_width
11637        } else {
11638            px(0.)
11639        };
11640
11641        GutterDimensions {
11642            left_padding,
11643            right_padding,
11644            width: line_gutter_width + left_padding + right_padding,
11645            margin: -descent,
11646            git_blame_entries_width,
11647        }
11648    }
11649
11650    pub fn render_fold_toggle(
11651        &self,
11652        buffer_row: MultiBufferRow,
11653        row_contains_cursor: bool,
11654        editor: View<Editor>,
11655        cx: &mut WindowContext,
11656    ) -> Option<AnyElement> {
11657        let folded = self.is_line_folded(buffer_row);
11658
11659        if let Some(flap) = self
11660            .flap_snapshot
11661            .query_row(buffer_row, &self.buffer_snapshot)
11662        {
11663            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
11664                if folded {
11665                    editor.update(cx, |editor, cx| {
11666                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
11667                    });
11668                } else {
11669                    editor.update(cx, |editor, cx| {
11670                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
11671                    });
11672                }
11673            });
11674
11675            Some((flap.render_toggle)(
11676                buffer_row,
11677                folded,
11678                toggle_callback,
11679                cx,
11680            ))
11681        } else if folded
11682            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
11683        {
11684            Some(
11685                IconButton::new(
11686                    ("indent-fold-indicator", buffer_row.0),
11687                    ui::IconName::ChevronDown,
11688                )
11689                .on_click(cx.listener_for(&editor, move |this, _e, cx| {
11690                    if folded {
11691                        this.unfold_at(&UnfoldAt { buffer_row }, cx);
11692                    } else {
11693                        this.fold_at(&FoldAt { buffer_row }, cx);
11694                    }
11695                }))
11696                .icon_color(ui::Color::Muted)
11697                .icon_size(ui::IconSize::Small)
11698                .selected(folded)
11699                .selected_icon(ui::IconName::ChevronRight)
11700                .size(ui::ButtonSize::None)
11701                .into_any_element(),
11702            )
11703        } else {
11704            None
11705        }
11706    }
11707
11708    pub fn render_flap_trailer(
11709        &self,
11710        buffer_row: MultiBufferRow,
11711        cx: &mut WindowContext,
11712    ) -> Option<AnyElement> {
11713        let folded = self.is_line_folded(buffer_row);
11714        let flap = self
11715            .flap_snapshot
11716            .query_row(buffer_row, &self.buffer_snapshot)?;
11717        Some((flap.render_trailer)(buffer_row, folded, cx))
11718    }
11719}
11720
11721impl Deref for EditorSnapshot {
11722    type Target = DisplaySnapshot;
11723
11724    fn deref(&self) -> &Self::Target {
11725        &self.display_snapshot
11726    }
11727}
11728
11729#[derive(Clone, Debug, PartialEq, Eq)]
11730pub enum EditorEvent {
11731    InputIgnored {
11732        text: Arc<str>,
11733    },
11734    InputHandled {
11735        utf16_range_to_replace: Option<Range<isize>>,
11736        text: Arc<str>,
11737    },
11738    ExcerptsAdded {
11739        buffer: Model<Buffer>,
11740        predecessor: ExcerptId,
11741        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
11742    },
11743    ExcerptsRemoved {
11744        ids: Vec<ExcerptId>,
11745    },
11746    BufferEdited,
11747    Edited,
11748    Reparsed,
11749    Focused,
11750    Blurred,
11751    DirtyChanged,
11752    Saved,
11753    TitleChanged,
11754    DiffBaseChanged,
11755    SelectionsChanged {
11756        local: bool,
11757    },
11758    ScrollPositionChanged {
11759        local: bool,
11760        autoscroll: bool,
11761    },
11762    Closed,
11763    TransactionUndone {
11764        transaction_id: clock::Lamport,
11765    },
11766    TransactionBegun {
11767        transaction_id: clock::Lamport,
11768    },
11769}
11770
11771impl EventEmitter<EditorEvent> for Editor {}
11772
11773impl FocusableView for Editor {
11774    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
11775        self.focus_handle.clone()
11776    }
11777}
11778
11779impl Render for Editor {
11780    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
11781        let settings = ThemeSettings::get_global(cx);
11782
11783        let text_style = match self.mode {
11784            EditorMode::SingleLine | EditorMode::AutoHeight { .. } => TextStyle {
11785                color: cx.theme().colors().editor_foreground,
11786                font_family: settings.ui_font.family.clone(),
11787                font_features: settings.ui_font.features.clone(),
11788                font_size: rems(0.875).into(),
11789                font_weight: settings.ui_font.weight,
11790                font_style: FontStyle::Normal,
11791                line_height: relative(settings.buffer_line_height.value()),
11792                background_color: None,
11793                underline: None,
11794                strikethrough: None,
11795                white_space: WhiteSpace::Normal,
11796            },
11797            EditorMode::Full => TextStyle {
11798                color: cx.theme().colors().editor_foreground,
11799                font_family: settings.buffer_font.family.clone(),
11800                font_features: settings.buffer_font.features.clone(),
11801                font_size: settings.buffer_font_size(cx).into(),
11802                font_weight: settings.buffer_font.weight,
11803                font_style: FontStyle::Normal,
11804                line_height: relative(settings.buffer_line_height.value()),
11805                background_color: None,
11806                underline: None,
11807                strikethrough: None,
11808                white_space: WhiteSpace::Normal,
11809            },
11810        };
11811
11812        let background = match self.mode {
11813            EditorMode::SingleLine => cx.theme().system().transparent,
11814            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
11815            EditorMode::Full => cx.theme().colors().editor_background,
11816        };
11817
11818        EditorElement::new(
11819            cx.view(),
11820            EditorStyle {
11821                background,
11822                local_player: cx.theme().players().local(),
11823                text: text_style,
11824                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
11825                syntax: cx.theme().syntax().clone(),
11826                status: cx.theme().status().clone(),
11827                inlay_hints_style: HighlightStyle {
11828                    color: Some(cx.theme().status().hint),
11829                    ..HighlightStyle::default()
11830                },
11831                suggestions_style: HighlightStyle {
11832                    color: Some(cx.theme().status().predictive),
11833                    ..HighlightStyle::default()
11834                },
11835            },
11836        )
11837    }
11838}
11839
11840impl ViewInputHandler for Editor {
11841    fn text_for_range(
11842        &mut self,
11843        range_utf16: Range<usize>,
11844        cx: &mut ViewContext<Self>,
11845    ) -> Option<String> {
11846        Some(
11847            self.buffer
11848                .read(cx)
11849                .read(cx)
11850                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
11851                .collect(),
11852        )
11853    }
11854
11855    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
11856        // Prevent the IME menu from appearing when holding down an alphabetic key
11857        // while input is disabled.
11858        if !self.input_enabled {
11859            return None;
11860        }
11861
11862        let range = self.selections.newest::<OffsetUtf16>(cx).range();
11863        Some(range.start.0..range.end.0)
11864    }
11865
11866    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
11867        let snapshot = self.buffer.read(cx).read(cx);
11868        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
11869        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
11870    }
11871
11872    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
11873        self.clear_highlights::<InputComposition>(cx);
11874        self.ime_transaction.take();
11875    }
11876
11877    fn replace_text_in_range(
11878        &mut self,
11879        range_utf16: Option<Range<usize>>,
11880        text: &str,
11881        cx: &mut ViewContext<Self>,
11882    ) {
11883        if !self.input_enabled {
11884            cx.emit(EditorEvent::InputIgnored { text: text.into() });
11885            return;
11886        }
11887
11888        self.transact(cx, |this, cx| {
11889            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
11890                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
11891                Some(this.selection_replacement_ranges(range_utf16, cx))
11892            } else {
11893                this.marked_text_ranges(cx)
11894            };
11895
11896            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
11897                let newest_selection_id = this.selections.newest_anchor().id;
11898                this.selections
11899                    .all::<OffsetUtf16>(cx)
11900                    .iter()
11901                    .zip(ranges_to_replace.iter())
11902                    .find_map(|(selection, range)| {
11903                        if selection.id == newest_selection_id {
11904                            Some(
11905                                (range.start.0 as isize - selection.head().0 as isize)
11906                                    ..(range.end.0 as isize - selection.head().0 as isize),
11907                            )
11908                        } else {
11909                            None
11910                        }
11911                    })
11912            });
11913
11914            cx.emit(EditorEvent::InputHandled {
11915                utf16_range_to_replace: range_to_replace,
11916                text: text.into(),
11917            });
11918
11919            if let Some(new_selected_ranges) = new_selected_ranges {
11920                this.change_selections(None, cx, |selections| {
11921                    selections.select_ranges(new_selected_ranges)
11922                });
11923                this.backspace(&Default::default(), cx);
11924            }
11925
11926            this.handle_input(text, cx);
11927        });
11928
11929        if let Some(transaction) = self.ime_transaction {
11930            self.buffer.update(cx, |buffer, cx| {
11931                buffer.group_until_transaction(transaction, cx);
11932            });
11933        }
11934
11935        self.unmark_text(cx);
11936    }
11937
11938    fn replace_and_mark_text_in_range(
11939        &mut self,
11940        range_utf16: Option<Range<usize>>,
11941        text: &str,
11942        new_selected_range_utf16: Option<Range<usize>>,
11943        cx: &mut ViewContext<Self>,
11944    ) {
11945        if !self.input_enabled {
11946            return;
11947        }
11948
11949        let transaction = self.transact(cx, |this, cx| {
11950            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
11951                let snapshot = this.buffer.read(cx).read(cx);
11952                if let Some(relative_range_utf16) = range_utf16.as_ref() {
11953                    for marked_range in &mut marked_ranges {
11954                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
11955                        marked_range.start.0 += relative_range_utf16.start;
11956                        marked_range.start =
11957                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
11958                        marked_range.end =
11959                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
11960                    }
11961                }
11962                Some(marked_ranges)
11963            } else if let Some(range_utf16) = range_utf16 {
11964                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
11965                Some(this.selection_replacement_ranges(range_utf16, cx))
11966            } else {
11967                None
11968            };
11969
11970            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
11971                let newest_selection_id = this.selections.newest_anchor().id;
11972                this.selections
11973                    .all::<OffsetUtf16>(cx)
11974                    .iter()
11975                    .zip(ranges_to_replace.iter())
11976                    .find_map(|(selection, range)| {
11977                        if selection.id == newest_selection_id {
11978                            Some(
11979                                (range.start.0 as isize - selection.head().0 as isize)
11980                                    ..(range.end.0 as isize - selection.head().0 as isize),
11981                            )
11982                        } else {
11983                            None
11984                        }
11985                    })
11986            });
11987
11988            cx.emit(EditorEvent::InputHandled {
11989                utf16_range_to_replace: range_to_replace,
11990                text: text.into(),
11991            });
11992
11993            if let Some(ranges) = ranges_to_replace {
11994                this.change_selections(None, cx, |s| s.select_ranges(ranges));
11995            }
11996
11997            let marked_ranges = {
11998                let snapshot = this.buffer.read(cx).read(cx);
11999                this.selections
12000                    .disjoint_anchors()
12001                    .iter()
12002                    .map(|selection| {
12003                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12004                    })
12005                    .collect::<Vec<_>>()
12006            };
12007
12008            if text.is_empty() {
12009                this.unmark_text(cx);
12010            } else {
12011                this.highlight_text::<InputComposition>(
12012                    marked_ranges.clone(),
12013                    HighlightStyle {
12014                        underline: Some(UnderlineStyle {
12015                            thickness: px(1.),
12016                            color: None,
12017                            wavy: false,
12018                        }),
12019                        ..Default::default()
12020                    },
12021                    cx,
12022                );
12023            }
12024
12025            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12026            let use_autoclose = this.use_autoclose;
12027            this.set_use_autoclose(false);
12028            this.handle_input(text, cx);
12029            this.set_use_autoclose(use_autoclose);
12030
12031            if let Some(new_selected_range) = new_selected_range_utf16 {
12032                let snapshot = this.buffer.read(cx).read(cx);
12033                let new_selected_ranges = marked_ranges
12034                    .into_iter()
12035                    .map(|marked_range| {
12036                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12037                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12038                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12039                        snapshot.clip_offset_utf16(new_start, Bias::Left)
12040                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12041                    })
12042                    .collect::<Vec<_>>();
12043
12044                drop(snapshot);
12045                this.change_selections(None, cx, |selections| {
12046                    selections.select_ranges(new_selected_ranges)
12047                });
12048            }
12049        });
12050
12051        self.ime_transaction = self.ime_transaction.or(transaction);
12052        if let Some(transaction) = self.ime_transaction {
12053            self.buffer.update(cx, |buffer, cx| {
12054                buffer.group_until_transaction(transaction, cx);
12055            });
12056        }
12057
12058        if self.text_highlights::<InputComposition>(cx).is_none() {
12059            self.ime_transaction.take();
12060        }
12061    }
12062
12063    fn bounds_for_range(
12064        &mut self,
12065        range_utf16: Range<usize>,
12066        element_bounds: gpui::Bounds<Pixels>,
12067        cx: &mut ViewContext<Self>,
12068    ) -> Option<gpui::Bounds<Pixels>> {
12069        let text_layout_details = self.text_layout_details(cx);
12070        let style = &text_layout_details.editor_style;
12071        let font_id = cx.text_system().resolve_font(&style.text.font());
12072        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12073        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12074        let em_width = cx
12075            .text_system()
12076            .typographic_bounds(font_id, font_size, 'm')
12077            .unwrap()
12078            .size
12079            .width;
12080
12081        let snapshot = self.snapshot(cx);
12082        let scroll_position = snapshot.scroll_position();
12083        let scroll_left = scroll_position.x * em_width;
12084
12085        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12086        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12087            + self.gutter_dimensions.width;
12088        let y = line_height * (start.row().as_f32() - scroll_position.y);
12089
12090        Some(Bounds {
12091            origin: element_bounds.origin + point(x, y),
12092            size: size(em_width, line_height),
12093        })
12094    }
12095}
12096
12097trait SelectionExt {
12098    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12099    fn spanned_rows(
12100        &self,
12101        include_end_if_at_line_start: bool,
12102        map: &DisplaySnapshot,
12103    ) -> Range<MultiBufferRow>;
12104}
12105
12106impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12107    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12108        let start = self
12109            .start
12110            .to_point(&map.buffer_snapshot)
12111            .to_display_point(map);
12112        let end = self
12113            .end
12114            .to_point(&map.buffer_snapshot)
12115            .to_display_point(map);
12116        if self.reversed {
12117            end..start
12118        } else {
12119            start..end
12120        }
12121    }
12122
12123    fn spanned_rows(
12124        &self,
12125        include_end_if_at_line_start: bool,
12126        map: &DisplaySnapshot,
12127    ) -> Range<MultiBufferRow> {
12128        let start = self.start.to_point(&map.buffer_snapshot);
12129        let mut end = self.end.to_point(&map.buffer_snapshot);
12130        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12131            end.row -= 1;
12132        }
12133
12134        let buffer_start = map.prev_line_boundary(start).0;
12135        let buffer_end = map.next_line_boundary(end).0;
12136        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12137    }
12138}
12139
12140impl<T: InvalidationRegion> InvalidationStack<T> {
12141    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12142    where
12143        S: Clone + ToOffset,
12144    {
12145        while let Some(region) = self.last() {
12146            let all_selections_inside_invalidation_ranges =
12147                if selections.len() == region.ranges().len() {
12148                    selections
12149                        .iter()
12150                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12151                        .all(|(selection, invalidation_range)| {
12152                            let head = selection.head().to_offset(buffer);
12153                            invalidation_range.start <= head && invalidation_range.end >= head
12154                        })
12155                } else {
12156                    false
12157                };
12158
12159            if all_selections_inside_invalidation_ranges {
12160                break;
12161            } else {
12162                self.pop();
12163            }
12164        }
12165    }
12166}
12167
12168impl<T> Default for InvalidationStack<T> {
12169    fn default() -> Self {
12170        Self(Default::default())
12171    }
12172}
12173
12174impl<T> Deref for InvalidationStack<T> {
12175    type Target = Vec<T>;
12176
12177    fn deref(&self) -> &Self::Target {
12178        &self.0
12179    }
12180}
12181
12182impl<T> DerefMut for InvalidationStack<T> {
12183    fn deref_mut(&mut self) -> &mut Self::Target {
12184        &mut self.0
12185    }
12186}
12187
12188impl InvalidationRegion for SnippetState {
12189    fn ranges(&self) -> &[Range<Anchor>] {
12190        &self.ranges[self.active_index]
12191    }
12192}
12193
12194pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
12195    let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
12196
12197    Box::new(move |cx: &mut BlockContext| {
12198        let group_id: SharedString = cx.block_id.to_string().into();
12199
12200        let mut text_style = cx.text_style().clone();
12201        text_style.color = diagnostic_style(diagnostic.severity, true, cx.theme().status());
12202        let theme_settings = ThemeSettings::get_global(cx);
12203        text_style.font_family = theme_settings.buffer_font.family.clone();
12204        text_style.font_style = theme_settings.buffer_font.style;
12205        text_style.font_features = theme_settings.buffer_font.features.clone();
12206        text_style.font_weight = theme_settings.buffer_font.weight;
12207
12208        let multi_line_diagnostic = diagnostic.message.contains('\n');
12209
12210        let buttons = |diagnostic: &Diagnostic, block_id: usize| {
12211            if multi_line_diagnostic {
12212                v_flex()
12213            } else {
12214                h_flex()
12215            }
12216            .children(diagnostic.is_primary.then(|| {
12217                IconButton::new(("close-block", block_id), IconName::XCircle)
12218                    .icon_color(Color::Muted)
12219                    .size(ButtonSize::Compact)
12220                    .style(ButtonStyle::Transparent)
12221                    .visible_on_hover(group_id.clone())
12222                    .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
12223                    .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
12224            }))
12225            .child(
12226                IconButton::new(("copy-block", block_id), IconName::Copy)
12227                    .icon_color(Color::Muted)
12228                    .size(ButtonSize::Compact)
12229                    .style(ButtonStyle::Transparent)
12230                    .visible_on_hover(group_id.clone())
12231                    .on_click({
12232                        let message = diagnostic.message.clone();
12233                        move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
12234                    })
12235                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
12236            )
12237        };
12238
12239        let icon_size = buttons(&diagnostic, cx.block_id)
12240            .into_any_element()
12241            .layout_as_root(AvailableSpace::min_size(), cx);
12242
12243        h_flex()
12244            .id(cx.block_id)
12245            .group(group_id.clone())
12246            .relative()
12247            .size_full()
12248            .pl(cx.gutter_dimensions.width)
12249            .w(cx.max_width + cx.gutter_dimensions.width)
12250            .child(
12251                div()
12252                    .flex()
12253                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
12254                    .flex_shrink(),
12255            )
12256            .child(buttons(&diagnostic, cx.block_id))
12257            .child(div().flex().flex_shrink_0().child(
12258                StyledText::new(text_without_backticks.clone()).with_highlights(
12259                    &text_style,
12260                    code_ranges.iter().map(|range| {
12261                        (
12262                            range.clone(),
12263                            HighlightStyle {
12264                                font_weight: Some(FontWeight::BOLD),
12265                                ..Default::default()
12266                            },
12267                        )
12268                    }),
12269                ),
12270            ))
12271            .into_any_element()
12272    })
12273}
12274
12275pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
12276    let mut text_without_backticks = String::new();
12277    let mut code_ranges = Vec::new();
12278
12279    if let Some(source) = &diagnostic.source {
12280        text_without_backticks.push_str(&source);
12281        code_ranges.push(0..source.len());
12282        text_without_backticks.push_str(": ");
12283    }
12284
12285    let mut prev_offset = 0;
12286    let mut in_code_block = false;
12287    for (ix, _) in diagnostic
12288        .message
12289        .match_indices('`')
12290        .chain([(diagnostic.message.len(), "")])
12291    {
12292        let prev_len = text_without_backticks.len();
12293        text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
12294        prev_offset = ix + 1;
12295        if in_code_block {
12296            code_ranges.push(prev_len..text_without_backticks.len());
12297            in_code_block = false;
12298        } else {
12299            in_code_block = true;
12300        }
12301    }
12302
12303    (text_without_backticks.into(), code_ranges)
12304}
12305
12306fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, colors: &StatusColors) -> Hsla {
12307    match (severity, valid) {
12308        (DiagnosticSeverity::ERROR, true) => colors.error,
12309        (DiagnosticSeverity::ERROR, false) => colors.error,
12310        (DiagnosticSeverity::WARNING, true) => colors.warning,
12311        (DiagnosticSeverity::WARNING, false) => colors.warning,
12312        (DiagnosticSeverity::INFORMATION, true) => colors.info,
12313        (DiagnosticSeverity::INFORMATION, false) => colors.info,
12314        (DiagnosticSeverity::HINT, true) => colors.info,
12315        (DiagnosticSeverity::HINT, false) => colors.info,
12316        _ => colors.ignored,
12317    }
12318}
12319
12320pub fn styled_runs_for_code_label<'a>(
12321    label: &'a CodeLabel,
12322    syntax_theme: &'a theme::SyntaxTheme,
12323) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
12324    let fade_out = HighlightStyle {
12325        fade_out: Some(0.35),
12326        ..Default::default()
12327    };
12328
12329    let mut prev_end = label.filter_range.end;
12330    label
12331        .runs
12332        .iter()
12333        .enumerate()
12334        .flat_map(move |(ix, (range, highlight_id))| {
12335            let style = if let Some(style) = highlight_id.style(syntax_theme) {
12336                style
12337            } else {
12338                return Default::default();
12339            };
12340            let mut muted_style = style;
12341            muted_style.highlight(fade_out);
12342
12343            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
12344            if range.start >= label.filter_range.end {
12345                if range.start > prev_end {
12346                    runs.push((prev_end..range.start, fade_out));
12347                }
12348                runs.push((range.clone(), muted_style));
12349            } else if range.end <= label.filter_range.end {
12350                runs.push((range.clone(), style));
12351            } else {
12352                runs.push((range.start..label.filter_range.end, style));
12353                runs.push((label.filter_range.end..range.end, muted_style));
12354            }
12355            prev_end = cmp::max(prev_end, range.end);
12356
12357            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
12358                runs.push((prev_end..label.text.len(), fade_out));
12359            }
12360
12361            runs
12362        })
12363}
12364
12365pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
12366    let mut prev_index = 0;
12367    let mut prev_codepoint: Option<char> = None;
12368    text.char_indices()
12369        .chain([(text.len(), '\0')])
12370        .filter_map(move |(index, codepoint)| {
12371            let prev_codepoint = prev_codepoint.replace(codepoint)?;
12372            let is_boundary = index == text.len()
12373                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
12374                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
12375            if is_boundary {
12376                let chunk = &text[prev_index..index];
12377                prev_index = index;
12378                Some(chunk)
12379            } else {
12380                None
12381            }
12382        })
12383}
12384
12385trait RangeToAnchorExt {
12386    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
12387}
12388
12389impl<T: ToOffset> RangeToAnchorExt for Range<T> {
12390    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
12391        let start_offset = self.start.to_offset(snapshot);
12392        let end_offset = self.end.to_offset(snapshot);
12393        if start_offset == end_offset {
12394            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
12395        } else {
12396            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
12397        }
12398    }
12399}
12400
12401pub trait RowExt {
12402    fn as_f32(&self) -> f32;
12403
12404    fn next_row(&self) -> Self;
12405
12406    fn previous_row(&self) -> Self;
12407
12408    fn minus(&self, other: Self) -> u32;
12409}
12410
12411impl RowExt for DisplayRow {
12412    fn as_f32(&self) -> f32 {
12413        self.0 as f32
12414    }
12415
12416    fn next_row(&self) -> Self {
12417        Self(self.0 + 1)
12418    }
12419
12420    fn previous_row(&self) -> Self {
12421        Self(self.0.saturating_sub(1))
12422    }
12423
12424    fn minus(&self, other: Self) -> u32 {
12425        self.0 - other.0
12426    }
12427}
12428
12429impl RowExt for MultiBufferRow {
12430    fn as_f32(&self) -> f32 {
12431        self.0 as f32
12432    }
12433
12434    fn next_row(&self) -> Self {
12435        Self(self.0 + 1)
12436    }
12437
12438    fn previous_row(&self) -> Self {
12439        Self(self.0.saturating_sub(1))
12440    }
12441
12442    fn minus(&self, other: Self) -> u32 {
12443        self.0 - other.0
12444    }
12445}
12446
12447trait RowRangeExt {
12448    type Row;
12449
12450    fn len(&self) -> usize;
12451
12452    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
12453}
12454
12455impl RowRangeExt for Range<MultiBufferRow> {
12456    type Row = MultiBufferRow;
12457
12458    fn len(&self) -> usize {
12459        (self.end.0 - self.start.0) as usize
12460    }
12461
12462    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
12463        (self.start.0..self.end.0).map(MultiBufferRow)
12464    }
12465}
12466
12467impl RowRangeExt for Range<DisplayRow> {
12468    type Row = DisplayRow;
12469
12470    fn len(&self) -> usize {
12471        (self.end.0 - self.start.0) as usize
12472    }
12473
12474    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
12475        (self.start.0..self.end.0).map(DisplayRow)
12476    }
12477}
12478
12479fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
12480    if hunk.diff_base_byte_range.is_empty() {
12481        DiffHunkStatus::Added
12482    } else if hunk.associated_range.is_empty() {
12483        DiffHunkStatus::Removed
12484    } else {
12485        DiffHunkStatus::Modified
12486    }
12487}