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