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