editor.rs

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