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;
   42mod signature_help;
   43#[cfg(any(test, feature = "test-support"))]
   44pub mod test;
   45
   46use ::git::diff::{DiffHunk, DiffHunkStatus};
   47use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
   48pub(crate) use actions::*;
   49use aho_corasick::AhoCorasick;
   50use anyhow::{anyhow, Context as _, Result};
   51use blink_manager::BlinkManager;
   52use client::{Collaborator, ParticipantIndex};
   53use clock::ReplicaId;
   54use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   55use convert_case::{Case, Casing};
   56use debounced_delay::DebouncedDelay;
   57use display_map::*;
   58pub use display_map::{DisplayPoint, FoldPlaceholder};
   59pub use editor_settings::{CurrentLineHighlight, EditorSettings};
   60use element::LineWithInvisibles;
   61pub use element::{
   62    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   63};
   64use futures::FutureExt;
   65use fuzzy::{StringMatch, StringMatchCandidate};
   66use git::blame::GitBlame;
   67use git::diff_hunk_to_display;
   68use gpui::{
   69    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   70    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardItem,
   71    Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle, FocusOutEvent,
   72    FocusableView, FontId, FontStyle, FontWeight, HighlightStyle, Hsla, InteractiveText,
   73    KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
   74    SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
   75    UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext,
   76    WeakFocusHandle, WeakView, WhiteSpace, WindowContext,
   77};
   78use highlight_matching_bracket::refresh_matching_bracket_highlights;
   79use hover_popover::{hide_hover, HoverState};
   80use hunk_diff::ExpandedHunks;
   81pub(crate) use hunk_diff::HoveredHunk;
   82use indent_guides::ActiveIndentGuidesState;
   83use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   84pub use inline_completion_provider::*;
   85pub use items::MAX_TAB_TITLE_LEN;
   86use itertools::Itertools;
   87use language::{
   88    char_kind,
   89    language_settings::{self, all_language_settings, InlayHintSettings},
   90    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   91    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   92    Point, Selection, SelectionGoal, TransactionId,
   93};
   94use language::{point_to_lsp, BufferRow, Runnable, RunnableRange};
   95use linked_editing_ranges::refresh_linked_ranges;
   96use task::{ResolvedTask, TaskTemplate, TaskVariables};
   97
   98use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
   99pub use lsp::CompletionContext;
  100use lsp::{
  101    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  102    LanguageServerId,
  103};
  104use mouse_context_menu::MouseContextMenu;
  105use movement::TextLayoutDetails;
  106pub use multi_buffer::{
  107    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  108    ToPoint,
  109};
  110use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
  111use ordered_float::OrderedFloat;
  112use parking_lot::{Mutex, RwLock};
  113use project::project_settings::{GitGutterSetting, ProjectSettings};
  114use project::{
  115    CodeAction, Completion, FormatTrigger, Item, Location, Project, ProjectPath,
  116    ProjectTransaction, TaskSourceKind, WorktreeId,
  117};
  118use rand::prelude::*;
  119use rpc::{proto::*, ErrorExt};
  120use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  121use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  122use serde::{Deserialize, Serialize};
  123use settings::{update_settings_file, Settings, SettingsStore};
  124use smallvec::SmallVec;
  125use snippet::Snippet;
  126use std::{
  127    any::TypeId,
  128    borrow::Cow,
  129    cell::RefCell,
  130    cmp::{self, Ordering, Reverse},
  131    mem,
  132    num::NonZeroU32,
  133    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  134    path::{Path, PathBuf},
  135    rc::Rc,
  136    sync::Arc,
  137    time::{Duration, Instant},
  138};
  139pub use sum_tree::Bias;
  140use sum_tree::TreeMap;
  141use text::{BufferId, OffsetUtf16, Rope};
  142use theme::{
  143    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  144    ThemeColors, ThemeSettings,
  145};
  146use ui::{
  147    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  148    ListItem, Popover, Tooltip,
  149};
  150use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  151use workspace::item::{ItemHandle, PreviewTabsSettings};
  152use workspace::notifications::{DetachAndPromptErr, NotificationId};
  153use workspace::{
  154    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  155};
  156use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  157
  158use crate::hover_links::find_url;
  159use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  160
  161pub const FILE_HEADER_HEIGHT: u8 = 1;
  162pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u8 = 1;
  163pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u8 = 1;
  164pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  165const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  166const MAX_LINE_LEN: usize = 1024;
  167const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  168const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  169pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  170#[doc(hidden)]
  171pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  172#[doc(hidden)]
  173pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  174
  175pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  176
  177pub fn render_parsed_markdown(
  178    element_id: impl Into<ElementId>,
  179    parsed: &language::ParsedMarkdown,
  180    editor_style: &EditorStyle,
  181    workspace: Option<WeakView<Workspace>>,
  182    cx: &mut WindowContext,
  183) -> InteractiveText {
  184    let code_span_background_color = cx
  185        .theme()
  186        .colors()
  187        .editor_document_highlight_read_background;
  188
  189    let highlights = gpui::combine_highlights(
  190        parsed.highlights.iter().filter_map(|(range, highlight)| {
  191            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  192            Some((range.clone(), highlight))
  193        }),
  194        parsed
  195            .regions
  196            .iter()
  197            .zip(&parsed.region_ranges)
  198            .filter_map(|(region, range)| {
  199                if region.code {
  200                    Some((
  201                        range.clone(),
  202                        HighlightStyle {
  203                            background_color: Some(code_span_background_color),
  204                            ..Default::default()
  205                        },
  206                    ))
  207                } else {
  208                    None
  209                }
  210            }),
  211    );
  212
  213    let mut links = Vec::new();
  214    let mut link_ranges = Vec::new();
  215    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  216        if let Some(link) = region.link.clone() {
  217            links.push(link);
  218            link_ranges.push(range.clone());
  219        }
  220    }
  221
  222    InteractiveText::new(
  223        element_id,
  224        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  225    )
  226    .on_click(link_ranges, move |clicked_range_ix, cx| {
  227        match &links[clicked_range_ix] {
  228            markdown::Link::Web { url } => cx.open_url(url),
  229            markdown::Link::Path { path } => {
  230                if let Some(workspace) = &workspace {
  231                    _ = workspace.update(cx, |workspace, cx| {
  232                        workspace.open_abs_path(path.clone(), false, cx).detach();
  233                    });
  234                }
  235            }
  236        }
  237    })
  238}
  239
  240#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  241pub(crate) enum InlayId {
  242    Suggestion(usize),
  243    Hint(usize),
  244}
  245
  246impl InlayId {
  247    fn id(&self) -> usize {
  248        match self {
  249            Self::Suggestion(id) => *id,
  250            Self::Hint(id) => *id,
  251        }
  252    }
  253}
  254
  255enum DiffRowHighlight {}
  256enum DocumentHighlightRead {}
  257enum DocumentHighlightWrite {}
  258enum InputComposition {}
  259
  260#[derive(Copy, Clone, PartialEq, Eq)]
  261pub enum Direction {
  262    Prev,
  263    Next,
  264}
  265
  266pub fn init_settings(cx: &mut AppContext) {
  267    EditorSettings::register(cx);
  268}
  269
  270pub fn init(cx: &mut AppContext) {
  271    init_settings(cx);
  272
  273    workspace::register_project_item::<Editor>(cx);
  274    workspace::FollowableViewRegistry::register::<Editor>(cx);
  275    workspace::register_serializable_item::<Editor>(cx);
  276
  277    cx.observe_new_views(
  278        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  279            workspace.register_action(Editor::new_file);
  280            workspace.register_action(Editor::new_file_in_direction);
  281        },
  282    )
  283    .detach();
  284
  285    cx.on_action(move |_: &workspace::NewFile, cx| {
  286        let app_state = workspace::AppState::global(cx);
  287        if let Some(app_state) = app_state.upgrade() {
  288            workspace::open_new(app_state, cx, |workspace, cx| {
  289                Editor::new_file(workspace, &Default::default(), cx)
  290            })
  291            .detach();
  292        }
  293    });
  294    cx.on_action(move |_: &workspace::NewWindow, cx| {
  295        let app_state = workspace::AppState::global(cx);
  296        if let Some(app_state) = app_state.upgrade() {
  297            workspace::open_new(app_state, cx, |workspace, cx| {
  298                Editor::new_file(workspace, &Default::default(), cx)
  299            })
  300            .detach();
  301        }
  302    });
  303}
  304
  305pub struct SearchWithinRange;
  306
  307trait InvalidationRegion {
  308    fn ranges(&self) -> &[Range<Anchor>];
  309}
  310
  311#[derive(Clone, Debug, PartialEq)]
  312pub enum SelectPhase {
  313    Begin {
  314        position: DisplayPoint,
  315        add: bool,
  316        click_count: usize,
  317    },
  318    BeginColumnar {
  319        position: DisplayPoint,
  320        reset: bool,
  321        goal_column: u32,
  322    },
  323    Extend {
  324        position: DisplayPoint,
  325        click_count: usize,
  326    },
  327    Update {
  328        position: DisplayPoint,
  329        goal_column: u32,
  330        scroll_delta: gpui::Point<f32>,
  331    },
  332    End,
  333}
  334
  335#[derive(Clone, Debug)]
  336pub enum SelectMode {
  337    Character,
  338    Word(Range<Anchor>),
  339    Line(Range<Anchor>),
  340    All,
  341}
  342
  343#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  344pub enum EditorMode {
  345    SingleLine { auto_width: bool },
  346    AutoHeight { max_lines: usize },
  347    Full,
  348}
  349
  350#[derive(Clone, Debug)]
  351pub enum SoftWrap {
  352    None,
  353    PreferLine,
  354    EditorWidth,
  355    Column(u32),
  356}
  357
  358#[derive(Clone)]
  359pub struct EditorStyle {
  360    pub background: Hsla,
  361    pub local_player: PlayerColor,
  362    pub text: TextStyle,
  363    pub scrollbar_width: Pixels,
  364    pub syntax: Arc<SyntaxTheme>,
  365    pub status: StatusColors,
  366    pub inlay_hints_style: HighlightStyle,
  367    pub suggestions_style: HighlightStyle,
  368}
  369
  370impl Default for EditorStyle {
  371    fn default() -> Self {
  372        Self {
  373            background: Hsla::default(),
  374            local_player: PlayerColor::default(),
  375            text: TextStyle::default(),
  376            scrollbar_width: Pixels::default(),
  377            syntax: Default::default(),
  378            // HACK: Status colors don't have a real default.
  379            // We should look into removing the status colors from the editor
  380            // style and retrieve them directly from the theme.
  381            status: StatusColors::dark(),
  382            inlay_hints_style: HighlightStyle::default(),
  383            suggestions_style: HighlightStyle::default(),
  384        }
  385    }
  386}
  387
  388type CompletionId = usize;
  389
  390#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  391struct EditorActionId(usize);
  392
  393impl EditorActionId {
  394    pub fn post_inc(&mut self) -> Self {
  395        let answer = self.0;
  396
  397        *self = Self(answer + 1);
  398
  399        Self(answer)
  400    }
  401}
  402
  403// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  404// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  405
  406type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  407type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  408
  409struct ScrollbarMarkerState {
  410    scrollbar_size: Size<Pixels>,
  411    dirty: bool,
  412    markers: Arc<[PaintQuad]>,
  413    pending_refresh: Option<Task<Result<()>>>,
  414}
  415
  416impl ScrollbarMarkerState {
  417    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  418        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  419    }
  420}
  421
  422impl Default for ScrollbarMarkerState {
  423    fn default() -> Self {
  424        Self {
  425            scrollbar_size: Size::default(),
  426            dirty: false,
  427            markers: Arc::from([]),
  428            pending_refresh: None,
  429        }
  430    }
  431}
  432
  433#[derive(Clone, Debug)]
  434struct RunnableTasks {
  435    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  436    offset: MultiBufferOffset,
  437    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  438    column: u32,
  439    // Values of all named captures, including those starting with '_'
  440    extra_variables: HashMap<String, String>,
  441    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  442    context_range: Range<BufferOffset>,
  443}
  444
  445#[derive(Clone)]
  446struct ResolvedTasks {
  447    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  448    position: Anchor,
  449}
  450#[derive(Copy, Clone, Debug)]
  451struct MultiBufferOffset(usize);
  452#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  453struct BufferOffset(usize);
  454/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  455///
  456/// See the [module level documentation](self) for more information.
  457pub struct Editor {
  458    focus_handle: FocusHandle,
  459    last_focused_descendant: Option<WeakFocusHandle>,
  460    /// The text buffer being edited
  461    buffer: Model<MultiBuffer>,
  462    /// Map of how text in the buffer should be displayed.
  463    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  464    pub display_map: Model<DisplayMap>,
  465    pub selections: SelectionsCollection,
  466    pub scroll_manager: ScrollManager,
  467    /// When inline assist editors are linked, they all render cursors because
  468    /// typing enters text into each of them, even the ones that aren't focused.
  469    pub(crate) show_cursor_when_unfocused: bool,
  470    columnar_selection_tail: Option<Anchor>,
  471    add_selections_state: Option<AddSelectionsState>,
  472    select_next_state: Option<SelectNextState>,
  473    select_prev_state: Option<SelectNextState>,
  474    selection_history: SelectionHistory,
  475    autoclose_regions: Vec<AutocloseRegion>,
  476    snippet_stack: InvalidationStack<SnippetState>,
  477    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  478    ime_transaction: Option<TransactionId>,
  479    active_diagnostics: Option<ActiveDiagnosticGroup>,
  480    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  481    project: Option<Model<Project>>,
  482    completion_provider: Option<Box<dyn CompletionProvider>>,
  483    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  484    blink_manager: Model<BlinkManager>,
  485    show_cursor_names: bool,
  486    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  487    pub show_local_selections: bool,
  488    mode: EditorMode,
  489    show_breadcrumbs: bool,
  490    show_gutter: bool,
  491    show_line_numbers: Option<bool>,
  492    show_git_diff_gutter: Option<bool>,
  493    show_code_actions: Option<bool>,
  494    show_runnables: Option<bool>,
  495    show_wrap_guides: Option<bool>,
  496    show_indent_guides: Option<bool>,
  497    placeholder_text: Option<Arc<str>>,
  498    highlight_order: usize,
  499    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  500    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  501    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  502    scrollbar_marker_state: ScrollbarMarkerState,
  503    active_indent_guides_state: ActiveIndentGuidesState,
  504    nav_history: Option<ItemNavHistory>,
  505    context_menu: RwLock<Option<ContextMenu>>,
  506    mouse_context_menu: Option<MouseContextMenu>,
  507    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  508    signature_help_state: SignatureHelpState,
  509    auto_signature_help: Option<bool>,
  510    find_all_references_task_sources: Vec<Anchor>,
  511    next_completion_id: CompletionId,
  512    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  513    available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
  514    code_actions_task: Option<Task<()>>,
  515    document_highlights_task: Option<Task<()>>,
  516    linked_editing_range_task: Option<Task<Option<()>>>,
  517    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  518    pending_rename: Option<RenameState>,
  519    searchable: bool,
  520    cursor_shape: CursorShape,
  521    current_line_highlight: Option<CurrentLineHighlight>,
  522    collapse_matches: bool,
  523    autoindent_mode: Option<AutoindentMode>,
  524    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  525    keymap_context_layers: BTreeMap<TypeId, KeyContext>,
  526    input_enabled: bool,
  527    use_modal_editing: bool,
  528    read_only: bool,
  529    leader_peer_id: Option<PeerId>,
  530    remote_id: Option<ViewId>,
  531    hover_state: HoverState,
  532    gutter_hovered: bool,
  533    hovered_link_state: Option<HoveredLinkState>,
  534    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  535    active_inline_completion: Option<Inlay>,
  536    show_inline_completions: bool,
  537    inlay_hint_cache: InlayHintCache,
  538    expanded_hunks: ExpandedHunks,
  539    next_inlay_id: usize,
  540    _subscriptions: Vec<Subscription>,
  541    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  542    gutter_dimensions: GutterDimensions,
  543    pub vim_replace_map: HashMap<Range<usize>, String>,
  544    style: Option<EditorStyle>,
  545    next_editor_action_id: EditorActionId,
  546    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  547    use_autoclose: bool,
  548    use_auto_surround: bool,
  549    auto_replace_emoji_shortcode: bool,
  550    show_git_blame_gutter: bool,
  551    show_git_blame_inline: bool,
  552    show_git_blame_inline_delay_task: Option<Task<()>>,
  553    git_blame_inline_enabled: bool,
  554    serialize_dirty_buffers: bool,
  555    show_selection_menu: Option<bool>,
  556    blame: Option<Model<GitBlame>>,
  557    blame_subscription: Option<Subscription>,
  558    custom_context_menu: Option<
  559        Box<
  560            dyn 'static
  561                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  562        >,
  563    >,
  564    last_bounds: Option<Bounds<Pixels>>,
  565    expect_bounds_change: Option<Bounds<Pixels>>,
  566    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  567    tasks_update_task: Option<Task<()>>,
  568    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  569    file_header_size: u8,
  570    breadcrumb_header: Option<String>,
  571}
  572
  573#[derive(Clone)]
  574pub struct EditorSnapshot {
  575    pub mode: EditorMode,
  576    show_gutter: bool,
  577    show_line_numbers: Option<bool>,
  578    show_git_diff_gutter: Option<bool>,
  579    show_code_actions: Option<bool>,
  580    show_runnables: Option<bool>,
  581    render_git_blame_gutter: bool,
  582    pub display_snapshot: DisplaySnapshot,
  583    pub placeholder_text: Option<Arc<str>>,
  584    is_focused: bool,
  585    scroll_anchor: ScrollAnchor,
  586    ongoing_scroll: OngoingScroll,
  587    current_line_highlight: CurrentLineHighlight,
  588    gutter_hovered: bool,
  589}
  590
  591const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
  592
  593#[derive(Debug, Clone, Copy)]
  594pub struct GutterDimensions {
  595    pub left_padding: Pixels,
  596    pub right_padding: Pixels,
  597    pub width: Pixels,
  598    pub margin: Pixels,
  599    pub git_blame_entries_width: Option<Pixels>,
  600}
  601
  602impl GutterDimensions {
  603    /// The full width of the space taken up by the gutter.
  604    pub fn full_width(&self) -> Pixels {
  605        self.margin + self.width
  606    }
  607
  608    /// The width of the space reserved for the fold indicators,
  609    /// use alongside 'justify_end' and `gutter_width` to
  610    /// right align content with the line numbers
  611    pub fn fold_area_width(&self) -> Pixels {
  612        self.margin + self.right_padding
  613    }
  614}
  615
  616impl Default for GutterDimensions {
  617    fn default() -> Self {
  618        Self {
  619            left_padding: Pixels::ZERO,
  620            right_padding: Pixels::ZERO,
  621            width: Pixels::ZERO,
  622            margin: Pixels::ZERO,
  623            git_blame_entries_width: None,
  624        }
  625    }
  626}
  627
  628#[derive(Debug)]
  629pub struct RemoteSelection {
  630    pub replica_id: ReplicaId,
  631    pub selection: Selection<Anchor>,
  632    pub cursor_shape: CursorShape,
  633    pub peer_id: PeerId,
  634    pub line_mode: bool,
  635    pub participant_index: Option<ParticipantIndex>,
  636    pub user_name: Option<SharedString>,
  637}
  638
  639#[derive(Clone, Debug)]
  640struct SelectionHistoryEntry {
  641    selections: Arc<[Selection<Anchor>]>,
  642    select_next_state: Option<SelectNextState>,
  643    select_prev_state: Option<SelectNextState>,
  644    add_selections_state: Option<AddSelectionsState>,
  645}
  646
  647enum SelectionHistoryMode {
  648    Normal,
  649    Undoing,
  650    Redoing,
  651}
  652
  653#[derive(Clone, PartialEq, Eq, Hash)]
  654struct HoveredCursor {
  655    replica_id: u16,
  656    selection_id: usize,
  657}
  658
  659impl Default for SelectionHistoryMode {
  660    fn default() -> Self {
  661        Self::Normal
  662    }
  663}
  664
  665#[derive(Default)]
  666struct SelectionHistory {
  667    #[allow(clippy::type_complexity)]
  668    selections_by_transaction:
  669        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  670    mode: SelectionHistoryMode,
  671    undo_stack: VecDeque<SelectionHistoryEntry>,
  672    redo_stack: VecDeque<SelectionHistoryEntry>,
  673}
  674
  675impl SelectionHistory {
  676    fn insert_transaction(
  677        &mut self,
  678        transaction_id: TransactionId,
  679        selections: Arc<[Selection<Anchor>]>,
  680    ) {
  681        self.selections_by_transaction
  682            .insert(transaction_id, (selections, None));
  683    }
  684
  685    #[allow(clippy::type_complexity)]
  686    fn transaction(
  687        &self,
  688        transaction_id: TransactionId,
  689    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  690        self.selections_by_transaction.get(&transaction_id)
  691    }
  692
  693    #[allow(clippy::type_complexity)]
  694    fn transaction_mut(
  695        &mut self,
  696        transaction_id: TransactionId,
  697    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  698        self.selections_by_transaction.get_mut(&transaction_id)
  699    }
  700
  701    fn push(&mut self, entry: SelectionHistoryEntry) {
  702        if !entry.selections.is_empty() {
  703            match self.mode {
  704                SelectionHistoryMode::Normal => {
  705                    self.push_undo(entry);
  706                    self.redo_stack.clear();
  707                }
  708                SelectionHistoryMode::Undoing => self.push_redo(entry),
  709                SelectionHistoryMode::Redoing => self.push_undo(entry),
  710            }
  711        }
  712    }
  713
  714    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  715        if self
  716            .undo_stack
  717            .back()
  718            .map_or(true, |e| e.selections != entry.selections)
  719        {
  720            self.undo_stack.push_back(entry);
  721            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  722                self.undo_stack.pop_front();
  723            }
  724        }
  725    }
  726
  727    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  728        if self
  729            .redo_stack
  730            .back()
  731            .map_or(true, |e| e.selections != entry.selections)
  732        {
  733            self.redo_stack.push_back(entry);
  734            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  735                self.redo_stack.pop_front();
  736            }
  737        }
  738    }
  739}
  740
  741struct RowHighlight {
  742    index: usize,
  743    range: RangeInclusive<Anchor>,
  744    color: Option<Hsla>,
  745    should_autoscroll: bool,
  746}
  747
  748#[derive(Clone, Debug)]
  749struct AddSelectionsState {
  750    above: bool,
  751    stack: Vec<usize>,
  752}
  753
  754#[derive(Clone)]
  755struct SelectNextState {
  756    query: AhoCorasick,
  757    wordwise: bool,
  758    done: bool,
  759}
  760
  761impl std::fmt::Debug for SelectNextState {
  762    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  763        f.debug_struct(std::any::type_name::<Self>())
  764            .field("wordwise", &self.wordwise)
  765            .field("done", &self.done)
  766            .finish()
  767    }
  768}
  769
  770#[derive(Debug)]
  771struct AutocloseRegion {
  772    selection_id: usize,
  773    range: Range<Anchor>,
  774    pair: BracketPair,
  775}
  776
  777#[derive(Debug)]
  778struct SnippetState {
  779    ranges: Vec<Vec<Range<Anchor>>>,
  780    active_index: usize,
  781}
  782
  783#[doc(hidden)]
  784pub struct RenameState {
  785    pub range: Range<Anchor>,
  786    pub old_name: Arc<str>,
  787    pub editor: View<Editor>,
  788    block_id: BlockId,
  789}
  790
  791struct InvalidationStack<T>(Vec<T>);
  792
  793struct RegisteredInlineCompletionProvider {
  794    provider: Arc<dyn InlineCompletionProviderHandle>,
  795    _subscription: Subscription,
  796}
  797
  798enum ContextMenu {
  799    Completions(CompletionsMenu),
  800    CodeActions(CodeActionsMenu),
  801}
  802
  803impl ContextMenu {
  804    fn select_first(
  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_first(project, cx),
  812                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  813            }
  814            true
  815        } else {
  816            false
  817        }
  818    }
  819
  820    fn select_prev(
  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_prev(project, cx),
  828                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  829            }
  830            true
  831        } else {
  832            false
  833        }
  834    }
  835
  836    fn select_next(
  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_next(project, cx),
  844                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  845            }
  846            true
  847        } else {
  848            false
  849        }
  850    }
  851
  852    fn select_last(
  853        &mut self,
  854        project: Option<&Model<Project>>,
  855        cx: &mut ViewContext<Editor>,
  856    ) -> bool {
  857        if self.visible() {
  858            match self {
  859                ContextMenu::Completions(menu) => menu.select_last(project, cx),
  860                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  861            }
  862            true
  863        } else {
  864            false
  865        }
  866    }
  867
  868    fn visible(&self) -> bool {
  869        match self {
  870            ContextMenu::Completions(menu) => menu.visible(),
  871            ContextMenu::CodeActions(menu) => menu.visible(),
  872        }
  873    }
  874
  875    fn render(
  876        &self,
  877        cursor_position: DisplayPoint,
  878        style: &EditorStyle,
  879        max_height: Pixels,
  880        workspace: Option<WeakView<Workspace>>,
  881        cx: &mut ViewContext<Editor>,
  882    ) -> (ContextMenuOrigin, AnyElement) {
  883        match self {
  884            ContextMenu::Completions(menu) => (
  885                ContextMenuOrigin::EditorPoint(cursor_position),
  886                menu.render(style, max_height, workspace, cx),
  887            ),
  888            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  889        }
  890    }
  891}
  892
  893enum ContextMenuOrigin {
  894    EditorPoint(DisplayPoint),
  895    GutterIndicator(DisplayRow),
  896}
  897
  898#[derive(Clone)]
  899struct CompletionsMenu {
  900    id: CompletionId,
  901    initial_position: Anchor,
  902    buffer: Model<Buffer>,
  903    completions: Arc<RwLock<Box<[Completion]>>>,
  904    match_candidates: Arc<[StringMatchCandidate]>,
  905    matches: Arc<[StringMatch]>,
  906    selected_item: usize,
  907    scroll_handle: UniformListScrollHandle,
  908    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  909}
  910
  911impl CompletionsMenu {
  912    fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  913        self.selected_item = 0;
  914        self.scroll_handle.scroll_to_item(self.selected_item);
  915        self.attempt_resolve_selected_completion_documentation(project, cx);
  916        cx.notify();
  917    }
  918
  919    fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  920        if self.selected_item > 0 {
  921            self.selected_item -= 1;
  922        } else {
  923            self.selected_item = self.matches.len() - 1;
  924        }
  925        self.scroll_handle.scroll_to_item(self.selected_item);
  926        self.attempt_resolve_selected_completion_documentation(project, cx);
  927        cx.notify();
  928    }
  929
  930    fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  931        if self.selected_item + 1 < self.matches.len() {
  932            self.selected_item += 1;
  933        } else {
  934            self.selected_item = 0;
  935        }
  936        self.scroll_handle.scroll_to_item(self.selected_item);
  937        self.attempt_resolve_selected_completion_documentation(project, cx);
  938        cx.notify();
  939    }
  940
  941    fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  942        self.selected_item = self.matches.len() - 1;
  943        self.scroll_handle.scroll_to_item(self.selected_item);
  944        self.attempt_resolve_selected_completion_documentation(project, cx);
  945        cx.notify();
  946    }
  947
  948    fn pre_resolve_completion_documentation(
  949        buffer: Model<Buffer>,
  950        completions: Arc<RwLock<Box<[Completion]>>>,
  951        matches: Arc<[StringMatch]>,
  952        editor: &Editor,
  953        cx: &mut ViewContext<Editor>,
  954    ) -> Task<()> {
  955        let settings = EditorSettings::get_global(cx);
  956        if !settings.show_completion_documentation {
  957            return Task::ready(());
  958        }
  959
  960        let Some(provider) = editor.completion_provider.as_ref() else {
  961            return Task::ready(());
  962        };
  963
  964        let resolve_task = provider.resolve_completions(
  965            buffer,
  966            matches.iter().map(|m| m.candidate_id).collect(),
  967            completions.clone(),
  968            cx,
  969        );
  970
  971        return cx.spawn(move |this, mut cx| async move {
  972            if let Some(true) = resolve_task.await.log_err() {
  973                this.update(&mut cx, |_, cx| cx.notify()).ok();
  974            }
  975        });
  976    }
  977
  978    fn attempt_resolve_selected_completion_documentation(
  979        &mut self,
  980        project: Option<&Model<Project>>,
  981        cx: &mut ViewContext<Editor>,
  982    ) {
  983        let settings = EditorSettings::get_global(cx);
  984        if !settings.show_completion_documentation {
  985            return;
  986        }
  987
  988        let completion_index = self.matches[self.selected_item].candidate_id;
  989        let Some(project) = project else {
  990            return;
  991        };
  992
  993        let resolve_task = project.update(cx, |project, cx| {
  994            project.resolve_completions(
  995                self.buffer.clone(),
  996                vec![completion_index],
  997                self.completions.clone(),
  998                cx,
  999            )
 1000        });
 1001
 1002        let delay_ms =
 1003            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
 1004        let delay = Duration::from_millis(delay_ms);
 1005
 1006        self.selected_completion_documentation_resolve_debounce
 1007            .lock()
 1008            .fire_new(delay, cx, |_, cx| {
 1009                cx.spawn(move |this, mut cx| async move {
 1010                    if let Some(true) = resolve_task.await.log_err() {
 1011                        this.update(&mut cx, |_, cx| cx.notify()).ok();
 1012                    }
 1013                })
 1014            });
 1015    }
 1016
 1017    fn visible(&self) -> bool {
 1018        !self.matches.is_empty()
 1019    }
 1020
 1021    fn render(
 1022        &self,
 1023        style: &EditorStyle,
 1024        max_height: Pixels,
 1025        workspace: Option<WeakView<Workspace>>,
 1026        cx: &mut ViewContext<Editor>,
 1027    ) -> AnyElement {
 1028        let settings = EditorSettings::get_global(cx);
 1029        let show_completion_documentation = settings.show_completion_documentation;
 1030
 1031        let widest_completion_ix = self
 1032            .matches
 1033            .iter()
 1034            .enumerate()
 1035            .max_by_key(|(_, mat)| {
 1036                let completions = self.completions.read();
 1037                let completion = &completions[mat.candidate_id];
 1038                let documentation = &completion.documentation;
 1039
 1040                let mut len = completion.label.text.chars().count();
 1041                if let Some(Documentation::SingleLine(text)) = documentation {
 1042                    if show_completion_documentation {
 1043                        len += text.chars().count();
 1044                    }
 1045                }
 1046
 1047                len
 1048            })
 1049            .map(|(ix, _)| ix);
 1050
 1051        let completions = self.completions.clone();
 1052        let matches = self.matches.clone();
 1053        let selected_item = self.selected_item;
 1054        let style = style.clone();
 1055
 1056        let multiline_docs = if show_completion_documentation {
 1057            let mat = &self.matches[selected_item];
 1058            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1059                Some(Documentation::MultiLinePlainText(text)) => {
 1060                    Some(div().child(SharedString::from(text.clone())))
 1061                }
 1062                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1063                    Some(div().child(render_parsed_markdown(
 1064                        "completions_markdown",
 1065                        parsed,
 1066                        &style,
 1067                        workspace,
 1068                        cx,
 1069                    )))
 1070                }
 1071                _ => None,
 1072            };
 1073            multiline_docs.map(|div| {
 1074                div.id("multiline_docs")
 1075                    .max_h(max_height)
 1076                    .flex_1()
 1077                    .px_1p5()
 1078                    .py_1()
 1079                    .min_w(px(260.))
 1080                    .max_w(px(640.))
 1081                    .w(px(500.))
 1082                    .overflow_y_scroll()
 1083                    .occlude()
 1084            })
 1085        } else {
 1086            None
 1087        };
 1088
 1089        let list = uniform_list(
 1090            cx.view().clone(),
 1091            "completions",
 1092            matches.len(),
 1093            move |_editor, range, cx| {
 1094                let start_ix = range.start;
 1095                let completions_guard = completions.read();
 1096
 1097                matches[range]
 1098                    .iter()
 1099                    .enumerate()
 1100                    .map(|(ix, mat)| {
 1101                        let item_ix = start_ix + ix;
 1102                        let candidate_id = mat.candidate_id;
 1103                        let completion = &completions_guard[candidate_id];
 1104
 1105                        let documentation = if show_completion_documentation {
 1106                            &completion.documentation
 1107                        } else {
 1108                            &None
 1109                        };
 1110
 1111                        let highlights = gpui::combine_highlights(
 1112                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1113                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1114                                |(range, mut highlight)| {
 1115                                    // Ignore font weight for syntax highlighting, as we'll use it
 1116                                    // for fuzzy matches.
 1117                                    highlight.font_weight = None;
 1118
 1119                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1120                                        highlight.strikethrough = Some(StrikethroughStyle {
 1121                                            thickness: 1.0.into(),
 1122                                            ..Default::default()
 1123                                        });
 1124                                        highlight.color = Some(cx.theme().colors().text_muted);
 1125                                    }
 1126
 1127                                    (range, highlight)
 1128                                },
 1129                            ),
 1130                        );
 1131                        let completion_label = StyledText::new(completion.label.text.clone())
 1132                            .with_highlights(&style.text, highlights);
 1133                        let documentation_label =
 1134                            if let Some(Documentation::SingleLine(text)) = documentation {
 1135                                if text.trim().is_empty() {
 1136                                    None
 1137                                } else {
 1138                                    Some(
 1139                                        Label::new(text.clone())
 1140                                            .ml_4()
 1141                                            .size(LabelSize::Small)
 1142                                            .color(Color::Muted),
 1143                                    )
 1144                                }
 1145                            } else {
 1146                                None
 1147                            };
 1148
 1149                        div().min_w(px(220.)).max_w(px(540.)).child(
 1150                            ListItem::new(mat.candidate_id)
 1151                                .inset(true)
 1152                                .selected(item_ix == selected_item)
 1153                                .on_click(cx.listener(move |editor, _event, cx| {
 1154                                    cx.stop_propagation();
 1155                                    if let Some(task) = editor.confirm_completion(
 1156                                        &ConfirmCompletion {
 1157                                            item_ix: Some(item_ix),
 1158                                        },
 1159                                        cx,
 1160                                    ) {
 1161                                        task.detach_and_log_err(cx)
 1162                                    }
 1163                                }))
 1164                                .child(h_flex().overflow_hidden().child(completion_label))
 1165                                .end_slot::<Label>(documentation_label),
 1166                        )
 1167                    })
 1168                    .collect()
 1169            },
 1170        )
 1171        .occlude()
 1172        .max_h(max_height)
 1173        .track_scroll(self.scroll_handle.clone())
 1174        .with_width_from_item(widest_completion_ix)
 1175        .with_sizing_behavior(ListSizingBehavior::Infer);
 1176
 1177        Popover::new()
 1178            .child(list)
 1179            .when_some(multiline_docs, |popover, multiline_docs| {
 1180                popover.aside(multiline_docs)
 1181            })
 1182            .into_any_element()
 1183    }
 1184
 1185    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1186        let mut matches = if let Some(query) = query {
 1187            fuzzy::match_strings(
 1188                &self.match_candidates,
 1189                query,
 1190                query.chars().any(|c| c.is_uppercase()),
 1191                100,
 1192                &Default::default(),
 1193                executor,
 1194            )
 1195            .await
 1196        } else {
 1197            self.match_candidates
 1198                .iter()
 1199                .enumerate()
 1200                .map(|(candidate_id, candidate)| StringMatch {
 1201                    candidate_id,
 1202                    score: Default::default(),
 1203                    positions: Default::default(),
 1204                    string: candidate.string.clone(),
 1205                })
 1206                .collect()
 1207        };
 1208
 1209        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1210        if let Some(query) = query {
 1211            if let Some(query_start) = query.chars().next() {
 1212                matches.retain(|string_match| {
 1213                    split_words(&string_match.string).any(|word| {
 1214                        // Check that the first codepoint of the word as lowercase matches the first
 1215                        // codepoint of the query as lowercase
 1216                        word.chars()
 1217                            .flat_map(|codepoint| codepoint.to_lowercase())
 1218                            .zip(query_start.to_lowercase())
 1219                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1220                    })
 1221                });
 1222            }
 1223        }
 1224
 1225        let completions = self.completions.read();
 1226        matches.sort_unstable_by_key(|mat| {
 1227            // We do want to strike a balance here between what the language server tells us
 1228            // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1229            // `Creat` and there is a local variable called `CreateComponent`).
 1230            // So what we do is: we bucket all matches into two buckets
 1231            // - Strong matches
 1232            // - Weak matches
 1233            // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1234            // and the Weak matches are the rest.
 1235            //
 1236            // For the strong matches, we sort by the language-servers score first and for the weak
 1237            // matches, we prefer our fuzzy finder first.
 1238            //
 1239            // The thinking behind that: it's useless to take the sort_text the language-server gives
 1240            // us into account when it's obviously a bad match.
 1241
 1242            #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1243            enum MatchScore<'a> {
 1244                Strong {
 1245                    sort_text: Option<&'a str>,
 1246                    score: Reverse<OrderedFloat<f64>>,
 1247                    sort_key: (usize, &'a str),
 1248                },
 1249                Weak {
 1250                    score: Reverse<OrderedFloat<f64>>,
 1251                    sort_text: Option<&'a str>,
 1252                    sort_key: (usize, &'a str),
 1253                },
 1254            }
 1255
 1256            let completion = &completions[mat.candidate_id];
 1257            let sort_key = completion.sort_key();
 1258            let sort_text = completion.lsp_completion.sort_text.as_deref();
 1259            let score = Reverse(OrderedFloat(mat.score));
 1260
 1261            if mat.score >= 0.2 {
 1262                MatchScore::Strong {
 1263                    sort_text,
 1264                    score,
 1265                    sort_key,
 1266                }
 1267            } else {
 1268                MatchScore::Weak {
 1269                    score,
 1270                    sort_text,
 1271                    sort_key,
 1272                }
 1273            }
 1274        });
 1275
 1276        for mat in &mut matches {
 1277            let completion = &completions[mat.candidate_id];
 1278            mat.string.clone_from(&completion.label.text);
 1279            for position in &mut mat.positions {
 1280                *position += completion.label.filter_range.start;
 1281            }
 1282        }
 1283        drop(completions);
 1284
 1285        self.matches = matches.into();
 1286        self.selected_item = 0;
 1287    }
 1288}
 1289
 1290#[derive(Clone)]
 1291struct CodeActionContents {
 1292    tasks: Option<Arc<ResolvedTasks>>,
 1293    actions: Option<Arc<[CodeAction]>>,
 1294}
 1295
 1296impl CodeActionContents {
 1297    fn len(&self) -> usize {
 1298        match (&self.tasks, &self.actions) {
 1299            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1300            (Some(tasks), None) => tasks.templates.len(),
 1301            (None, Some(actions)) => actions.len(),
 1302            (None, None) => 0,
 1303        }
 1304    }
 1305
 1306    fn is_empty(&self) -> bool {
 1307        match (&self.tasks, &self.actions) {
 1308            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1309            (Some(tasks), None) => tasks.templates.is_empty(),
 1310            (None, Some(actions)) => actions.is_empty(),
 1311            (None, None) => true,
 1312        }
 1313    }
 1314
 1315    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1316        self.tasks
 1317            .iter()
 1318            .flat_map(|tasks| {
 1319                tasks
 1320                    .templates
 1321                    .iter()
 1322                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1323            })
 1324            .chain(self.actions.iter().flat_map(|actions| {
 1325                actions
 1326                    .iter()
 1327                    .map(|action| CodeActionsItem::CodeAction(action.clone()))
 1328            }))
 1329    }
 1330    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1331        match (&self.tasks, &self.actions) {
 1332            (Some(tasks), Some(actions)) => {
 1333                if index < tasks.templates.len() {
 1334                    tasks
 1335                        .templates
 1336                        .get(index)
 1337                        .cloned()
 1338                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1339                } else {
 1340                    actions
 1341                        .get(index - tasks.templates.len())
 1342                        .cloned()
 1343                        .map(CodeActionsItem::CodeAction)
 1344                }
 1345            }
 1346            (Some(tasks), None) => tasks
 1347                .templates
 1348                .get(index)
 1349                .cloned()
 1350                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1351            (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
 1352            (None, None) => None,
 1353        }
 1354    }
 1355}
 1356
 1357#[allow(clippy::large_enum_variant)]
 1358#[derive(Clone)]
 1359enum CodeActionsItem {
 1360    Task(TaskSourceKind, ResolvedTask),
 1361    CodeAction(CodeAction),
 1362}
 1363
 1364impl CodeActionsItem {
 1365    fn as_task(&self) -> Option<&ResolvedTask> {
 1366        let Self::Task(_, task) = self else {
 1367            return None;
 1368        };
 1369        Some(task)
 1370    }
 1371    fn as_code_action(&self) -> Option<&CodeAction> {
 1372        let Self::CodeAction(action) = self else {
 1373            return None;
 1374        };
 1375        Some(action)
 1376    }
 1377    fn label(&self) -> String {
 1378        match self {
 1379            Self::CodeAction(action) => action.lsp_action.title.clone(),
 1380            Self::Task(_, task) => task.resolved_label.clone(),
 1381        }
 1382    }
 1383}
 1384
 1385struct CodeActionsMenu {
 1386    actions: CodeActionContents,
 1387    buffer: Model<Buffer>,
 1388    selected_item: usize,
 1389    scroll_handle: UniformListScrollHandle,
 1390    deployed_from_indicator: Option<DisplayRow>,
 1391}
 1392
 1393impl CodeActionsMenu {
 1394    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1395        self.selected_item = 0;
 1396        self.scroll_handle.scroll_to_item(self.selected_item);
 1397        cx.notify()
 1398    }
 1399
 1400    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1401        if self.selected_item > 0 {
 1402            self.selected_item -= 1;
 1403        } else {
 1404            self.selected_item = self.actions.len() - 1;
 1405        }
 1406        self.scroll_handle.scroll_to_item(self.selected_item);
 1407        cx.notify();
 1408    }
 1409
 1410    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1411        if self.selected_item + 1 < self.actions.len() {
 1412            self.selected_item += 1;
 1413        } else {
 1414            self.selected_item = 0;
 1415        }
 1416        self.scroll_handle.scroll_to_item(self.selected_item);
 1417        cx.notify();
 1418    }
 1419
 1420    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1421        self.selected_item = self.actions.len() - 1;
 1422        self.scroll_handle.scroll_to_item(self.selected_item);
 1423        cx.notify()
 1424    }
 1425
 1426    fn visible(&self) -> bool {
 1427        !self.actions.is_empty()
 1428    }
 1429
 1430    fn render(
 1431        &self,
 1432        cursor_position: DisplayPoint,
 1433        _style: &EditorStyle,
 1434        max_height: Pixels,
 1435        cx: &mut ViewContext<Editor>,
 1436    ) -> (ContextMenuOrigin, AnyElement) {
 1437        let actions = self.actions.clone();
 1438        let selected_item = self.selected_item;
 1439        let element = uniform_list(
 1440            cx.view().clone(),
 1441            "code_actions_menu",
 1442            self.actions.len(),
 1443            move |_this, range, cx| {
 1444                actions
 1445                    .iter()
 1446                    .skip(range.start)
 1447                    .take(range.end - range.start)
 1448                    .enumerate()
 1449                    .map(|(ix, action)| {
 1450                        let item_ix = range.start + ix;
 1451                        let selected = selected_item == item_ix;
 1452                        let colors = cx.theme().colors();
 1453                        div()
 1454                            .px_2()
 1455                            .text_color(colors.text)
 1456                            .when(selected, |style| {
 1457                                style
 1458                                    .bg(colors.element_active)
 1459                                    .text_color(colors.text_accent)
 1460                            })
 1461                            .hover(|style| {
 1462                                style
 1463                                    .bg(colors.element_hover)
 1464                                    .text_color(colors.text_accent)
 1465                            })
 1466                            .whitespace_nowrap()
 1467                            .when_some(action.as_code_action(), |this, action| {
 1468                                this.on_mouse_down(
 1469                                    MouseButton::Left,
 1470                                    cx.listener(move |editor, _, cx| {
 1471                                        cx.stop_propagation();
 1472                                        if let Some(task) = editor.confirm_code_action(
 1473                                            &ConfirmCodeAction {
 1474                                                item_ix: Some(item_ix),
 1475                                            },
 1476                                            cx,
 1477                                        ) {
 1478                                            task.detach_and_log_err(cx)
 1479                                        }
 1480                                    }),
 1481                                )
 1482                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1483                                .child(SharedString::from(action.lsp_action.title.clone()))
 1484                            })
 1485                            .when_some(action.as_task(), |this, task| {
 1486                                this.on_mouse_down(
 1487                                    MouseButton::Left,
 1488                                    cx.listener(move |editor, _, cx| {
 1489                                        cx.stop_propagation();
 1490                                        if let Some(task) = editor.confirm_code_action(
 1491                                            &ConfirmCodeAction {
 1492                                                item_ix: Some(item_ix),
 1493                                            },
 1494                                            cx,
 1495                                        ) {
 1496                                            task.detach_and_log_err(cx)
 1497                                        }
 1498                                    }),
 1499                                )
 1500                                .child(SharedString::from(task.resolved_label.clone()))
 1501                            })
 1502                    })
 1503                    .collect()
 1504            },
 1505        )
 1506        .elevation_1(cx)
 1507        .px_2()
 1508        .py_1()
 1509        .max_h(max_height)
 1510        .occlude()
 1511        .track_scroll(self.scroll_handle.clone())
 1512        .with_width_from_item(
 1513            self.actions
 1514                .iter()
 1515                .enumerate()
 1516                .max_by_key(|(_, action)| match action {
 1517                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1518                    CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
 1519                })
 1520                .map(|(ix, _)| ix),
 1521        )
 1522        .with_sizing_behavior(ListSizingBehavior::Infer)
 1523        .into_any_element();
 1524
 1525        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1526            ContextMenuOrigin::GutterIndicator(row)
 1527        } else {
 1528            ContextMenuOrigin::EditorPoint(cursor_position)
 1529        };
 1530
 1531        (cursor_position, element)
 1532    }
 1533}
 1534
 1535#[derive(Debug)]
 1536struct ActiveDiagnosticGroup {
 1537    primary_range: Range<Anchor>,
 1538    primary_message: String,
 1539    group_id: usize,
 1540    blocks: HashMap<BlockId, Diagnostic>,
 1541    is_valid: bool,
 1542}
 1543
 1544#[derive(Serialize, Deserialize, Clone, Debug)]
 1545pub struct ClipboardSelection {
 1546    pub len: usize,
 1547    pub is_entire_line: bool,
 1548    pub first_line_indent: u32,
 1549}
 1550
 1551#[derive(Debug)]
 1552pub(crate) struct NavigationData {
 1553    cursor_anchor: Anchor,
 1554    cursor_position: Point,
 1555    scroll_anchor: ScrollAnchor,
 1556    scroll_top_row: u32,
 1557}
 1558
 1559enum GotoDefinitionKind {
 1560    Symbol,
 1561    Type,
 1562    Implementation,
 1563}
 1564
 1565#[derive(Debug, Clone)]
 1566enum InlayHintRefreshReason {
 1567    Toggle(bool),
 1568    SettingsChange(InlayHintSettings),
 1569    NewLinesShown,
 1570    BufferEdited(HashSet<Arc<Language>>),
 1571    RefreshRequested,
 1572    ExcerptsRemoved(Vec<ExcerptId>),
 1573}
 1574
 1575impl InlayHintRefreshReason {
 1576    fn description(&self) -> &'static str {
 1577        match self {
 1578            Self::Toggle(_) => "toggle",
 1579            Self::SettingsChange(_) => "settings change",
 1580            Self::NewLinesShown => "new lines shown",
 1581            Self::BufferEdited(_) => "buffer edited",
 1582            Self::RefreshRequested => "refresh requested",
 1583            Self::ExcerptsRemoved(_) => "excerpts removed",
 1584        }
 1585    }
 1586}
 1587
 1588impl Editor {
 1589    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1590        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1591        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1592        Self::new(
 1593            EditorMode::SingleLine { auto_width: false },
 1594            buffer,
 1595            None,
 1596            false,
 1597            cx,
 1598        )
 1599    }
 1600
 1601    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1602        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1603        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1604        Self::new(EditorMode::Full, buffer, None, false, cx)
 1605    }
 1606
 1607    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1608        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1609        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1610        Self::new(
 1611            EditorMode::SingleLine { auto_width: true },
 1612            buffer,
 1613            None,
 1614            false,
 1615            cx,
 1616        )
 1617    }
 1618
 1619    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1620        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1621        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1622        Self::new(
 1623            EditorMode::AutoHeight { max_lines },
 1624            buffer,
 1625            None,
 1626            false,
 1627            cx,
 1628        )
 1629    }
 1630
 1631    pub fn for_buffer(
 1632        buffer: Model<Buffer>,
 1633        project: Option<Model<Project>>,
 1634        cx: &mut ViewContext<Self>,
 1635    ) -> Self {
 1636        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1637        Self::new(EditorMode::Full, buffer, project, false, cx)
 1638    }
 1639
 1640    pub fn for_multibuffer(
 1641        buffer: Model<MultiBuffer>,
 1642        project: Option<Model<Project>>,
 1643        show_excerpt_controls: bool,
 1644        cx: &mut ViewContext<Self>,
 1645    ) -> Self {
 1646        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1647    }
 1648
 1649    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1650        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1651        let mut clone = Self::new(
 1652            self.mode,
 1653            self.buffer.clone(),
 1654            self.project.clone(),
 1655            show_excerpt_controls,
 1656            cx,
 1657        );
 1658        self.display_map.update(cx, |display_map, cx| {
 1659            let snapshot = display_map.snapshot(cx);
 1660            clone.display_map.update(cx, |display_map, cx| {
 1661                display_map.set_state(&snapshot, cx);
 1662            });
 1663        });
 1664        clone.selections.clone_state(&self.selections);
 1665        clone.scroll_manager.clone_state(&self.scroll_manager);
 1666        clone.searchable = self.searchable;
 1667        clone
 1668    }
 1669
 1670    pub fn new(
 1671        mode: EditorMode,
 1672        buffer: Model<MultiBuffer>,
 1673        project: Option<Model<Project>>,
 1674        show_excerpt_controls: bool,
 1675        cx: &mut ViewContext<Self>,
 1676    ) -> Self {
 1677        let style = cx.text_style();
 1678        let font_size = style.font_size.to_pixels(cx.rem_size());
 1679        let editor = cx.view().downgrade();
 1680        let fold_placeholder = FoldPlaceholder {
 1681            constrain_width: true,
 1682            render: Arc::new(move |fold_id, fold_range, cx| {
 1683                let editor = editor.clone();
 1684                div()
 1685                    .id(fold_id)
 1686                    .bg(cx.theme().colors().ghost_element_background)
 1687                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1688                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1689                    .rounded_sm()
 1690                    .size_full()
 1691                    .cursor_pointer()
 1692                    .child("")
 1693                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1694                    .on_click(move |_, cx| {
 1695                        editor
 1696                            .update(cx, |editor, cx| {
 1697                                editor.unfold_ranges(
 1698                                    [fold_range.start..fold_range.end],
 1699                                    true,
 1700                                    false,
 1701                                    cx,
 1702                                );
 1703                                cx.stop_propagation();
 1704                            })
 1705                            .ok();
 1706                    })
 1707                    .into_any()
 1708            }),
 1709            merge_adjacent: true,
 1710        };
 1711        let file_header_size = if show_excerpt_controls { 3 } else { 2 };
 1712        let display_map = cx.new_model(|cx| {
 1713            DisplayMap::new(
 1714                buffer.clone(),
 1715                style.font(),
 1716                font_size,
 1717                None,
 1718                show_excerpt_controls,
 1719                file_header_size,
 1720                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1721                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1722                fold_placeholder,
 1723                cx,
 1724            )
 1725        });
 1726
 1727        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1728
 1729        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1730
 1731        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1732            .then(|| language_settings::SoftWrap::PreferLine);
 1733
 1734        let mut project_subscriptions = Vec::new();
 1735        if mode == EditorMode::Full {
 1736            if let Some(project) = project.as_ref() {
 1737                if buffer.read(cx).is_singleton() {
 1738                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1739                        cx.emit(EditorEvent::TitleChanged);
 1740                    }));
 1741                }
 1742                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1743                    if let project::Event::RefreshInlayHints = event {
 1744                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1745                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1746                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1747                            let focus_handle = editor.focus_handle(cx);
 1748                            if focus_handle.is_focused(cx) {
 1749                                let snapshot = buffer.read(cx).snapshot();
 1750                                for (range, snippet) in snippet_edits {
 1751                                    let editor_range =
 1752                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1753                                    editor
 1754                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1755                                        .ok();
 1756                                }
 1757                            }
 1758                        }
 1759                    }
 1760                }));
 1761                let task_inventory = project.read(cx).task_inventory().clone();
 1762                project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1763                    editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1764                }));
 1765            }
 1766        }
 1767
 1768        let inlay_hint_settings = inlay_hint_settings(
 1769            selections.newest_anchor().head(),
 1770            &buffer.read(cx).snapshot(cx),
 1771            cx,
 1772        );
 1773        let focus_handle = cx.focus_handle();
 1774        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1775        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1776            .detach();
 1777        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1778            .detach();
 1779        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1780
 1781        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1782            Some(false)
 1783        } else {
 1784            None
 1785        };
 1786
 1787        let mut this = Self {
 1788            focus_handle,
 1789            show_cursor_when_unfocused: false,
 1790            last_focused_descendant: None,
 1791            buffer: buffer.clone(),
 1792            display_map: display_map.clone(),
 1793            selections,
 1794            scroll_manager: ScrollManager::new(cx),
 1795            columnar_selection_tail: None,
 1796            add_selections_state: None,
 1797            select_next_state: None,
 1798            select_prev_state: None,
 1799            selection_history: Default::default(),
 1800            autoclose_regions: Default::default(),
 1801            snippet_stack: Default::default(),
 1802            select_larger_syntax_node_stack: Vec::new(),
 1803            ime_transaction: Default::default(),
 1804            active_diagnostics: None,
 1805            soft_wrap_mode_override,
 1806            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1807            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1808            project,
 1809            blink_manager: blink_manager.clone(),
 1810            show_local_selections: true,
 1811            mode,
 1812            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1813            show_gutter: mode == EditorMode::Full,
 1814            show_line_numbers: None,
 1815            show_git_diff_gutter: None,
 1816            show_code_actions: None,
 1817            show_runnables: None,
 1818            show_wrap_guides: None,
 1819            show_indent_guides,
 1820            placeholder_text: None,
 1821            highlight_order: 0,
 1822            highlighted_rows: HashMap::default(),
 1823            background_highlights: Default::default(),
 1824            gutter_highlights: TreeMap::default(),
 1825            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1826            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1827            nav_history: None,
 1828            context_menu: RwLock::new(None),
 1829            mouse_context_menu: None,
 1830            completion_tasks: Default::default(),
 1831            signature_help_state: SignatureHelpState::default(),
 1832            auto_signature_help: None,
 1833            find_all_references_task_sources: Vec::new(),
 1834            next_completion_id: 0,
 1835            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1836            next_inlay_id: 0,
 1837            available_code_actions: Default::default(),
 1838            code_actions_task: Default::default(),
 1839            document_highlights_task: Default::default(),
 1840            linked_editing_range_task: Default::default(),
 1841            pending_rename: Default::default(),
 1842            searchable: true,
 1843            cursor_shape: Default::default(),
 1844            current_line_highlight: None,
 1845            autoindent_mode: Some(AutoindentMode::EachLine),
 1846            collapse_matches: false,
 1847            workspace: None,
 1848            keymap_context_layers: Default::default(),
 1849            input_enabled: true,
 1850            use_modal_editing: mode == EditorMode::Full,
 1851            read_only: false,
 1852            use_autoclose: true,
 1853            use_auto_surround: true,
 1854            auto_replace_emoji_shortcode: false,
 1855            leader_peer_id: None,
 1856            remote_id: None,
 1857            hover_state: Default::default(),
 1858            hovered_link_state: Default::default(),
 1859            inline_completion_provider: None,
 1860            active_inline_completion: None,
 1861            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1862            expanded_hunks: ExpandedHunks::default(),
 1863            gutter_hovered: false,
 1864            pixel_position_of_newest_cursor: None,
 1865            last_bounds: None,
 1866            expect_bounds_change: None,
 1867            gutter_dimensions: GutterDimensions::default(),
 1868            style: None,
 1869            show_cursor_names: false,
 1870            hovered_cursors: Default::default(),
 1871            next_editor_action_id: EditorActionId::default(),
 1872            editor_actions: Rc::default(),
 1873            vim_replace_map: Default::default(),
 1874            show_inline_completions: mode == EditorMode::Full,
 1875            custom_context_menu: None,
 1876            show_git_blame_gutter: false,
 1877            show_git_blame_inline: false,
 1878            show_selection_menu: None,
 1879            show_git_blame_inline_delay_task: None,
 1880            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1881            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1882                .session
 1883                .restore_unsaved_buffers,
 1884            blame: None,
 1885            blame_subscription: None,
 1886            file_header_size,
 1887            tasks: Default::default(),
 1888            _subscriptions: vec![
 1889                cx.observe(&buffer, Self::on_buffer_changed),
 1890                cx.subscribe(&buffer, Self::on_buffer_event),
 1891                cx.observe(&display_map, Self::on_display_map_changed),
 1892                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1893                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1894                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1895                cx.observe_window_activation(|editor, cx| {
 1896                    let active = cx.is_window_active();
 1897                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1898                        if active {
 1899                            blink_manager.enable(cx);
 1900                        } else {
 1901                            blink_manager.show_cursor(cx);
 1902                            blink_manager.disable(cx);
 1903                        }
 1904                    });
 1905                }),
 1906            ],
 1907            tasks_update_task: None,
 1908            linked_edit_ranges: Default::default(),
 1909            previous_search_ranges: None,
 1910            breadcrumb_header: None,
 1911        };
 1912        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1913        this._subscriptions.extend(project_subscriptions);
 1914
 1915        this.end_selection(cx);
 1916        this.scroll_manager.show_scrollbar(cx);
 1917
 1918        if mode == EditorMode::Full {
 1919            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1920            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1921
 1922            if this.git_blame_inline_enabled {
 1923                this.git_blame_inline_enabled = true;
 1924                this.start_git_blame_inline(false, cx);
 1925            }
 1926        }
 1927
 1928        this.report_editor_event("open", None, cx);
 1929        this
 1930    }
 1931
 1932    pub fn mouse_menu_is_focused(&self, cx: &mut WindowContext) -> bool {
 1933        self.mouse_context_menu
 1934            .as_ref()
 1935            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1936    }
 1937
 1938    fn key_context(&self, cx: &AppContext) -> KeyContext {
 1939        let mut key_context = KeyContext::new_with_defaults();
 1940        key_context.add("Editor");
 1941        let mode = match self.mode {
 1942            EditorMode::SingleLine { .. } => "single_line",
 1943            EditorMode::AutoHeight { .. } => "auto_height",
 1944            EditorMode::Full => "full",
 1945        };
 1946
 1947        if EditorSettings::get_global(cx).jupyter.enabled {
 1948            key_context.add("jupyter");
 1949        }
 1950
 1951        key_context.set("mode", mode);
 1952        if self.pending_rename.is_some() {
 1953            key_context.add("renaming");
 1954        }
 1955        if self.context_menu_visible() {
 1956            match self.context_menu.read().as_ref() {
 1957                Some(ContextMenu::Completions(_)) => {
 1958                    key_context.add("menu");
 1959                    key_context.add("showing_completions")
 1960                }
 1961                Some(ContextMenu::CodeActions(_)) => {
 1962                    key_context.add("menu");
 1963                    key_context.add("showing_code_actions")
 1964                }
 1965                None => {}
 1966            }
 1967        }
 1968
 1969        for layer in self.keymap_context_layers.values() {
 1970            key_context.extend(layer);
 1971        }
 1972
 1973        if let Some(extension) = self
 1974            .buffer
 1975            .read(cx)
 1976            .as_singleton()
 1977            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1978        {
 1979            key_context.set("extension", extension.to_string());
 1980        }
 1981
 1982        if self.has_active_inline_completion(cx) {
 1983            key_context.add("copilot_suggestion");
 1984            key_context.add("inline_completion");
 1985        }
 1986
 1987        key_context
 1988    }
 1989
 1990    pub fn new_file(
 1991        workspace: &mut Workspace,
 1992        _: &workspace::NewFile,
 1993        cx: &mut ViewContext<Workspace>,
 1994    ) {
 1995        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1996            "Failed to create buffer",
 1997            cx,
 1998            |e, _| match e.error_code() {
 1999                ErrorCode::RemoteUpgradeRequired => Some(format!(
 2000                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2001                e.error_tag("required").unwrap_or("the latest version")
 2002            )),
 2003                _ => None,
 2004            },
 2005        );
 2006    }
 2007
 2008    pub fn new_in_workspace(
 2009        workspace: &mut Workspace,
 2010        cx: &mut ViewContext<Workspace>,
 2011    ) -> Task<Result<View<Editor>>> {
 2012        let project = workspace.project().clone();
 2013        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2014
 2015        cx.spawn(|workspace, mut cx| async move {
 2016            let buffer = create.await?;
 2017            workspace.update(&mut cx, |workspace, cx| {
 2018                let editor =
 2019                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2020                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2021                editor
 2022            })
 2023        })
 2024    }
 2025
 2026    pub fn new_file_in_direction(
 2027        workspace: &mut Workspace,
 2028        action: &workspace::NewFileInDirection,
 2029        cx: &mut ViewContext<Workspace>,
 2030    ) {
 2031        let project = workspace.project().clone();
 2032        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2033        let direction = action.0;
 2034
 2035        cx.spawn(|workspace, mut cx| async move {
 2036            let buffer = create.await?;
 2037            workspace.update(&mut cx, move |workspace, cx| {
 2038                workspace.split_item(
 2039                    direction,
 2040                    Box::new(
 2041                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2042                    ),
 2043                    cx,
 2044                )
 2045            })?;
 2046            anyhow::Ok(())
 2047        })
 2048        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2049            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2050                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2051                e.error_tag("required").unwrap_or("the latest version")
 2052            )),
 2053            _ => None,
 2054        });
 2055    }
 2056
 2057    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
 2058        self.buffer.read(cx).replica_id()
 2059    }
 2060
 2061    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2062        self.leader_peer_id
 2063    }
 2064
 2065    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2066        &self.buffer
 2067    }
 2068
 2069    pub fn workspace(&self) -> Option<View<Workspace>> {
 2070        self.workspace.as_ref()?.0.upgrade()
 2071    }
 2072
 2073    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2074        self.buffer().read(cx).title(cx)
 2075    }
 2076
 2077    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2078        EditorSnapshot {
 2079            mode: self.mode,
 2080            show_gutter: self.show_gutter,
 2081            show_line_numbers: self.show_line_numbers,
 2082            show_git_diff_gutter: self.show_git_diff_gutter,
 2083            show_code_actions: self.show_code_actions,
 2084            show_runnables: self.show_runnables,
 2085            render_git_blame_gutter: self.render_git_blame_gutter(cx),
 2086            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2087            scroll_anchor: self.scroll_manager.anchor(),
 2088            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2089            placeholder_text: self.placeholder_text.clone(),
 2090            is_focused: self.focus_handle.is_focused(cx),
 2091            current_line_highlight: self
 2092                .current_line_highlight
 2093                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2094            gutter_hovered: self.gutter_hovered,
 2095        }
 2096    }
 2097
 2098    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2099        self.buffer.read(cx).language_at(point, cx)
 2100    }
 2101
 2102    pub fn file_at<T: ToOffset>(
 2103        &self,
 2104        point: T,
 2105        cx: &AppContext,
 2106    ) -> Option<Arc<dyn language::File>> {
 2107        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2108    }
 2109
 2110    pub fn active_excerpt(
 2111        &self,
 2112        cx: &AppContext,
 2113    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2114        self.buffer
 2115            .read(cx)
 2116            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2117    }
 2118
 2119    pub fn mode(&self) -> EditorMode {
 2120        self.mode
 2121    }
 2122
 2123    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2124        self.collaboration_hub.as_deref()
 2125    }
 2126
 2127    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2128        self.collaboration_hub = Some(hub);
 2129    }
 2130
 2131    pub fn set_custom_context_menu(
 2132        &mut self,
 2133        f: impl 'static
 2134            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2135    ) {
 2136        self.custom_context_menu = Some(Box::new(f))
 2137    }
 2138
 2139    pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
 2140        self.completion_provider = Some(provider);
 2141    }
 2142
 2143    pub fn set_inline_completion_provider<T>(
 2144        &mut self,
 2145        provider: Option<Model<T>>,
 2146        cx: &mut ViewContext<Self>,
 2147    ) where
 2148        T: InlineCompletionProvider,
 2149    {
 2150        self.inline_completion_provider =
 2151            provider.map(|provider| RegisteredInlineCompletionProvider {
 2152                _subscription: cx.observe(&provider, |this, _, cx| {
 2153                    if this.focus_handle.is_focused(cx) {
 2154                        this.update_visible_inline_completion(cx);
 2155                    }
 2156                }),
 2157                provider: Arc::new(provider),
 2158            });
 2159        self.refresh_inline_completion(false, cx);
 2160    }
 2161
 2162    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2163        self.placeholder_text.as_deref()
 2164    }
 2165
 2166    pub fn set_placeholder_text(
 2167        &mut self,
 2168        placeholder_text: impl Into<Arc<str>>,
 2169        cx: &mut ViewContext<Self>,
 2170    ) {
 2171        let placeholder_text = Some(placeholder_text.into());
 2172        if self.placeholder_text != placeholder_text {
 2173            self.placeholder_text = placeholder_text;
 2174            cx.notify();
 2175        }
 2176    }
 2177
 2178    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2179        self.cursor_shape = cursor_shape;
 2180
 2181        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2182        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2183
 2184        cx.notify();
 2185    }
 2186
 2187    pub fn set_current_line_highlight(
 2188        &mut self,
 2189        current_line_highlight: Option<CurrentLineHighlight>,
 2190    ) {
 2191        self.current_line_highlight = current_line_highlight;
 2192    }
 2193
 2194    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2195        self.collapse_matches = collapse_matches;
 2196    }
 2197
 2198    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2199        if self.collapse_matches {
 2200            return range.start..range.start;
 2201        }
 2202        range.clone()
 2203    }
 2204
 2205    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2206        if self.display_map.read(cx).clip_at_line_ends != clip {
 2207            self.display_map
 2208                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2209        }
 2210    }
 2211
 2212    pub fn set_keymap_context_layer<Tag: 'static>(
 2213        &mut self,
 2214        context: KeyContext,
 2215        cx: &mut ViewContext<Self>,
 2216    ) {
 2217        self.keymap_context_layers
 2218            .insert(TypeId::of::<Tag>(), context);
 2219        cx.notify();
 2220    }
 2221
 2222    pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
 2223        self.keymap_context_layers.remove(&TypeId::of::<Tag>());
 2224        cx.notify();
 2225    }
 2226
 2227    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2228        self.input_enabled = input_enabled;
 2229    }
 2230
 2231    pub fn set_autoindent(&mut self, autoindent: bool) {
 2232        if autoindent {
 2233            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2234        } else {
 2235            self.autoindent_mode = None;
 2236        }
 2237    }
 2238
 2239    pub fn read_only(&self, cx: &AppContext) -> bool {
 2240        self.read_only || self.buffer.read(cx).read_only()
 2241    }
 2242
 2243    pub fn set_read_only(&mut self, read_only: bool) {
 2244        self.read_only = read_only;
 2245    }
 2246
 2247    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2248        self.use_autoclose = autoclose;
 2249    }
 2250
 2251    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2252        self.use_auto_surround = auto_surround;
 2253    }
 2254
 2255    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2256        self.auto_replace_emoji_shortcode = auto_replace;
 2257    }
 2258
 2259    pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
 2260        self.show_inline_completions = show_inline_completions;
 2261    }
 2262
 2263    pub fn set_use_modal_editing(&mut self, to: bool) {
 2264        self.use_modal_editing = to;
 2265    }
 2266
 2267    pub fn use_modal_editing(&self) -> bool {
 2268        self.use_modal_editing
 2269    }
 2270
 2271    fn selections_did_change(
 2272        &mut self,
 2273        local: bool,
 2274        old_cursor_position: &Anchor,
 2275        show_completions: bool,
 2276        cx: &mut ViewContext<Self>,
 2277    ) {
 2278        // Copy selections to primary selection buffer
 2279        #[cfg(target_os = "linux")]
 2280        if local {
 2281            let selections = self.selections.all::<usize>(cx);
 2282            let buffer_handle = self.buffer.read(cx).read(cx);
 2283
 2284            let mut text = String::new();
 2285            for (index, selection) in selections.iter().enumerate() {
 2286                let text_for_selection = buffer_handle
 2287                    .text_for_range(selection.start..selection.end)
 2288                    .collect::<String>();
 2289
 2290                text.push_str(&text_for_selection);
 2291                if index != selections.len() - 1 {
 2292                    text.push('\n');
 2293                }
 2294            }
 2295
 2296            if !text.is_empty() {
 2297                cx.write_to_primary(ClipboardItem::new(text));
 2298            }
 2299        }
 2300
 2301        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2302            self.buffer.update(cx, |buffer, cx| {
 2303                buffer.set_active_selections(
 2304                    &self.selections.disjoint_anchors(),
 2305                    self.selections.line_mode,
 2306                    self.cursor_shape,
 2307                    cx,
 2308                )
 2309            });
 2310        }
 2311        let display_map = self
 2312            .display_map
 2313            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2314        let buffer = &display_map.buffer_snapshot;
 2315        self.add_selections_state = None;
 2316        self.select_next_state = None;
 2317        self.select_prev_state = None;
 2318        self.select_larger_syntax_node_stack.clear();
 2319        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2320        self.snippet_stack
 2321            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2322        self.take_rename(false, cx);
 2323
 2324        let new_cursor_position = self.selections.newest_anchor().head();
 2325
 2326        self.push_to_nav_history(
 2327            *old_cursor_position,
 2328            Some(new_cursor_position.to_point(buffer)),
 2329            cx,
 2330        );
 2331
 2332        if local {
 2333            let new_cursor_position = self.selections.newest_anchor().head();
 2334            let mut context_menu = self.context_menu.write();
 2335            let completion_menu = match context_menu.as_ref() {
 2336                Some(ContextMenu::Completions(menu)) => Some(menu),
 2337
 2338                _ => {
 2339                    *context_menu = None;
 2340                    None
 2341                }
 2342            };
 2343
 2344            if let Some(completion_menu) = completion_menu {
 2345                let cursor_position = new_cursor_position.to_offset(buffer);
 2346                let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
 2347                if kind == Some(CharKind::Word)
 2348                    && word_range.to_inclusive().contains(&cursor_position)
 2349                {
 2350                    let mut completion_menu = completion_menu.clone();
 2351                    drop(context_menu);
 2352
 2353                    let query = Self::completion_query(buffer, cursor_position);
 2354                    cx.spawn(move |this, mut cx| async move {
 2355                        completion_menu
 2356                            .filter(query.as_deref(), cx.background_executor().clone())
 2357                            .await;
 2358
 2359                        this.update(&mut cx, |this, cx| {
 2360                            let mut context_menu = this.context_menu.write();
 2361                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2362                                return;
 2363                            };
 2364
 2365                            if menu.id > completion_menu.id {
 2366                                return;
 2367                            }
 2368
 2369                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2370                            drop(context_menu);
 2371                            cx.notify();
 2372                        })
 2373                    })
 2374                    .detach();
 2375
 2376                    if show_completions {
 2377                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2378                    }
 2379                } else {
 2380                    drop(context_menu);
 2381                    self.hide_context_menu(cx);
 2382                }
 2383            } else {
 2384                drop(context_menu);
 2385            }
 2386
 2387            hide_hover(self, cx);
 2388
 2389            if old_cursor_position.to_display_point(&display_map).row()
 2390                != new_cursor_position.to_display_point(&display_map).row()
 2391            {
 2392                self.available_code_actions.take();
 2393            }
 2394            self.refresh_code_actions(cx);
 2395            self.refresh_document_highlights(cx);
 2396            refresh_matching_bracket_highlights(self, cx);
 2397            self.discard_inline_completion(false, cx);
 2398            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2399            if self.git_blame_inline_enabled {
 2400                self.start_inline_blame_timer(cx);
 2401            }
 2402        }
 2403
 2404        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2405        cx.emit(EditorEvent::SelectionsChanged { local });
 2406
 2407        if self.selections.disjoint_anchors().len() == 1 {
 2408            cx.emit(SearchEvent::ActiveMatchChanged)
 2409        }
 2410        cx.notify();
 2411    }
 2412
 2413    pub fn change_selections<R>(
 2414        &mut self,
 2415        autoscroll: Option<Autoscroll>,
 2416        cx: &mut ViewContext<Self>,
 2417        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2418    ) -> R {
 2419        self.change_selections_inner(autoscroll, true, cx, change)
 2420    }
 2421
 2422    pub fn change_selections_inner<R>(
 2423        &mut self,
 2424        autoscroll: Option<Autoscroll>,
 2425        request_completions: bool,
 2426        cx: &mut ViewContext<Self>,
 2427        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2428    ) -> R {
 2429        let old_cursor_position = self.selections.newest_anchor().head();
 2430        self.push_to_selection_history();
 2431
 2432        let (changed, result) = self.selections.change_with(cx, change);
 2433
 2434        if changed {
 2435            if let Some(autoscroll) = autoscroll {
 2436                self.request_autoscroll(autoscroll, cx);
 2437            }
 2438            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2439
 2440            if self.should_open_signature_help_automatically(
 2441                &old_cursor_position,
 2442                self.signature_help_state.backspace_pressed(),
 2443                cx,
 2444            ) {
 2445                self.show_signature_help(&ShowSignatureHelp, cx);
 2446            }
 2447            self.signature_help_state.set_backspace_pressed(false);
 2448        }
 2449
 2450        result
 2451    }
 2452
 2453    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2454    where
 2455        I: IntoIterator<Item = (Range<S>, T)>,
 2456        S: ToOffset,
 2457        T: Into<Arc<str>>,
 2458    {
 2459        if self.read_only(cx) {
 2460            return;
 2461        }
 2462
 2463        self.buffer
 2464            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2465    }
 2466
 2467    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2468    where
 2469        I: IntoIterator<Item = (Range<S>, T)>,
 2470        S: ToOffset,
 2471        T: Into<Arc<str>>,
 2472    {
 2473        if self.read_only(cx) {
 2474            return;
 2475        }
 2476
 2477        self.buffer.update(cx, |buffer, cx| {
 2478            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2479        });
 2480    }
 2481
 2482    pub fn edit_with_block_indent<I, S, T>(
 2483        &mut self,
 2484        edits: I,
 2485        original_indent_columns: Vec<u32>,
 2486        cx: &mut ViewContext<Self>,
 2487    ) where
 2488        I: IntoIterator<Item = (Range<S>, T)>,
 2489        S: ToOffset,
 2490        T: Into<Arc<str>>,
 2491    {
 2492        if self.read_only(cx) {
 2493            return;
 2494        }
 2495
 2496        self.buffer.update(cx, |buffer, cx| {
 2497            buffer.edit(
 2498                edits,
 2499                Some(AutoindentMode::Block {
 2500                    original_indent_columns,
 2501                }),
 2502                cx,
 2503            )
 2504        });
 2505    }
 2506
 2507    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2508        self.hide_context_menu(cx);
 2509
 2510        match phase {
 2511            SelectPhase::Begin {
 2512                position,
 2513                add,
 2514                click_count,
 2515            } => self.begin_selection(position, add, click_count, cx),
 2516            SelectPhase::BeginColumnar {
 2517                position,
 2518                goal_column,
 2519                reset,
 2520            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2521            SelectPhase::Extend {
 2522                position,
 2523                click_count,
 2524            } => self.extend_selection(position, click_count, cx),
 2525            SelectPhase::Update {
 2526                position,
 2527                goal_column,
 2528                scroll_delta,
 2529            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2530            SelectPhase::End => self.end_selection(cx),
 2531        }
 2532    }
 2533
 2534    fn extend_selection(
 2535        &mut self,
 2536        position: DisplayPoint,
 2537        click_count: usize,
 2538        cx: &mut ViewContext<Self>,
 2539    ) {
 2540        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2541        let tail = self.selections.newest::<usize>(cx).tail();
 2542        self.begin_selection(position, false, click_count, cx);
 2543
 2544        let position = position.to_offset(&display_map, Bias::Left);
 2545        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2546
 2547        let mut pending_selection = self
 2548            .selections
 2549            .pending_anchor()
 2550            .expect("extend_selection not called with pending selection");
 2551        if position >= tail {
 2552            pending_selection.start = tail_anchor;
 2553        } else {
 2554            pending_selection.end = tail_anchor;
 2555            pending_selection.reversed = true;
 2556        }
 2557
 2558        let mut pending_mode = self.selections.pending_mode().unwrap();
 2559        match &mut pending_mode {
 2560            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2561            _ => {}
 2562        }
 2563
 2564        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2565            s.set_pending(pending_selection, pending_mode)
 2566        });
 2567    }
 2568
 2569    fn begin_selection(
 2570        &mut self,
 2571        position: DisplayPoint,
 2572        add: bool,
 2573        click_count: usize,
 2574        cx: &mut ViewContext<Self>,
 2575    ) {
 2576        if !self.focus_handle.is_focused(cx) {
 2577            self.last_focused_descendant = None;
 2578            cx.focus(&self.focus_handle);
 2579        }
 2580
 2581        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2582        let buffer = &display_map.buffer_snapshot;
 2583        let newest_selection = self.selections.newest_anchor().clone();
 2584        let position = display_map.clip_point(position, Bias::Left);
 2585
 2586        let start;
 2587        let end;
 2588        let mode;
 2589        let auto_scroll;
 2590        match click_count {
 2591            1 => {
 2592                start = buffer.anchor_before(position.to_point(&display_map));
 2593                end = start;
 2594                mode = SelectMode::Character;
 2595                auto_scroll = true;
 2596            }
 2597            2 => {
 2598                let range = movement::surrounding_word(&display_map, position);
 2599                start = buffer.anchor_before(range.start.to_point(&display_map));
 2600                end = buffer.anchor_before(range.end.to_point(&display_map));
 2601                mode = SelectMode::Word(start..end);
 2602                auto_scroll = true;
 2603            }
 2604            3 => {
 2605                let position = display_map
 2606                    .clip_point(position, Bias::Left)
 2607                    .to_point(&display_map);
 2608                let line_start = display_map.prev_line_boundary(position).0;
 2609                let next_line_start = buffer.clip_point(
 2610                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2611                    Bias::Left,
 2612                );
 2613                start = buffer.anchor_before(line_start);
 2614                end = buffer.anchor_before(next_line_start);
 2615                mode = SelectMode::Line(start..end);
 2616                auto_scroll = true;
 2617            }
 2618            _ => {
 2619                start = buffer.anchor_before(0);
 2620                end = buffer.anchor_before(buffer.len());
 2621                mode = SelectMode::All;
 2622                auto_scroll = false;
 2623            }
 2624        }
 2625
 2626        let point_to_delete: Option<usize> = {
 2627            let selected_points: Vec<Selection<Point>> =
 2628                self.selections.disjoint_in_range(start..end, cx);
 2629
 2630            if !add || click_count > 1 {
 2631                None
 2632            } else if selected_points.len() > 0 {
 2633                Some(selected_points[0].id)
 2634            } else {
 2635                let clicked_point_already_selected =
 2636                    self.selections.disjoint.iter().find(|selection| {
 2637                        selection.start.to_point(buffer) == start.to_point(buffer)
 2638                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2639                    });
 2640
 2641                if let Some(selection) = clicked_point_already_selected {
 2642                    Some(selection.id)
 2643                } else {
 2644                    None
 2645                }
 2646            }
 2647        };
 2648
 2649        let selections_count = self.selections.count();
 2650
 2651        self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
 2652            if let Some(point_to_delete) = point_to_delete {
 2653                s.delete(point_to_delete);
 2654
 2655                if selections_count == 1 {
 2656                    s.set_pending_anchor_range(start..end, mode);
 2657                }
 2658            } else {
 2659                if !add {
 2660                    s.clear_disjoint();
 2661                } else if click_count > 1 {
 2662                    s.delete(newest_selection.id)
 2663                }
 2664
 2665                s.set_pending_anchor_range(start..end, mode);
 2666            }
 2667        });
 2668    }
 2669
 2670    fn begin_columnar_selection(
 2671        &mut self,
 2672        position: DisplayPoint,
 2673        goal_column: u32,
 2674        reset: bool,
 2675        cx: &mut ViewContext<Self>,
 2676    ) {
 2677        if !self.focus_handle.is_focused(cx) {
 2678            self.last_focused_descendant = None;
 2679            cx.focus(&self.focus_handle);
 2680        }
 2681
 2682        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2683
 2684        if reset {
 2685            let pointer_position = display_map
 2686                .buffer_snapshot
 2687                .anchor_before(position.to_point(&display_map));
 2688
 2689            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2690                s.clear_disjoint();
 2691                s.set_pending_anchor_range(
 2692                    pointer_position..pointer_position,
 2693                    SelectMode::Character,
 2694                );
 2695            });
 2696        }
 2697
 2698        let tail = self.selections.newest::<Point>(cx).tail();
 2699        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2700
 2701        if !reset {
 2702            self.select_columns(
 2703                tail.to_display_point(&display_map),
 2704                position,
 2705                goal_column,
 2706                &display_map,
 2707                cx,
 2708            );
 2709        }
 2710    }
 2711
 2712    fn update_selection(
 2713        &mut self,
 2714        position: DisplayPoint,
 2715        goal_column: u32,
 2716        scroll_delta: gpui::Point<f32>,
 2717        cx: &mut ViewContext<Self>,
 2718    ) {
 2719        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2720
 2721        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2722            let tail = tail.to_display_point(&display_map);
 2723            self.select_columns(tail, position, goal_column, &display_map, cx);
 2724        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2725            let buffer = self.buffer.read(cx).snapshot(cx);
 2726            let head;
 2727            let tail;
 2728            let mode = self.selections.pending_mode().unwrap();
 2729            match &mode {
 2730                SelectMode::Character => {
 2731                    head = position.to_point(&display_map);
 2732                    tail = pending.tail().to_point(&buffer);
 2733                }
 2734                SelectMode::Word(original_range) => {
 2735                    let original_display_range = original_range.start.to_display_point(&display_map)
 2736                        ..original_range.end.to_display_point(&display_map);
 2737                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2738                        ..original_display_range.end.to_point(&display_map);
 2739                    if movement::is_inside_word(&display_map, position)
 2740                        || original_display_range.contains(&position)
 2741                    {
 2742                        let word_range = movement::surrounding_word(&display_map, position);
 2743                        if word_range.start < original_display_range.start {
 2744                            head = word_range.start.to_point(&display_map);
 2745                        } else {
 2746                            head = word_range.end.to_point(&display_map);
 2747                        }
 2748                    } else {
 2749                        head = position.to_point(&display_map);
 2750                    }
 2751
 2752                    if head <= original_buffer_range.start {
 2753                        tail = original_buffer_range.end;
 2754                    } else {
 2755                        tail = original_buffer_range.start;
 2756                    }
 2757                }
 2758                SelectMode::Line(original_range) => {
 2759                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2760
 2761                    let position = display_map
 2762                        .clip_point(position, Bias::Left)
 2763                        .to_point(&display_map);
 2764                    let line_start = display_map.prev_line_boundary(position).0;
 2765                    let next_line_start = buffer.clip_point(
 2766                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2767                        Bias::Left,
 2768                    );
 2769
 2770                    if line_start < original_range.start {
 2771                        head = line_start
 2772                    } else {
 2773                        head = next_line_start
 2774                    }
 2775
 2776                    if head <= original_range.start {
 2777                        tail = original_range.end;
 2778                    } else {
 2779                        tail = original_range.start;
 2780                    }
 2781                }
 2782                SelectMode::All => {
 2783                    return;
 2784                }
 2785            };
 2786
 2787            if head < tail {
 2788                pending.start = buffer.anchor_before(head);
 2789                pending.end = buffer.anchor_before(tail);
 2790                pending.reversed = true;
 2791            } else {
 2792                pending.start = buffer.anchor_before(tail);
 2793                pending.end = buffer.anchor_before(head);
 2794                pending.reversed = false;
 2795            }
 2796
 2797            self.change_selections(None, cx, |s| {
 2798                s.set_pending(pending, mode);
 2799            });
 2800        } else {
 2801            log::error!("update_selection dispatched with no pending selection");
 2802            return;
 2803        }
 2804
 2805        self.apply_scroll_delta(scroll_delta, cx);
 2806        cx.notify();
 2807    }
 2808
 2809    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2810        self.columnar_selection_tail.take();
 2811        if self.selections.pending_anchor().is_some() {
 2812            let selections = self.selections.all::<usize>(cx);
 2813            self.change_selections(None, cx, |s| {
 2814                s.select(selections);
 2815                s.clear_pending();
 2816            });
 2817        }
 2818    }
 2819
 2820    fn select_columns(
 2821        &mut self,
 2822        tail: DisplayPoint,
 2823        head: DisplayPoint,
 2824        goal_column: u32,
 2825        display_map: &DisplaySnapshot,
 2826        cx: &mut ViewContext<Self>,
 2827    ) {
 2828        let start_row = cmp::min(tail.row(), head.row());
 2829        let end_row = cmp::max(tail.row(), head.row());
 2830        let start_column = cmp::min(tail.column(), goal_column);
 2831        let end_column = cmp::max(tail.column(), goal_column);
 2832        let reversed = start_column < tail.column();
 2833
 2834        let selection_ranges = (start_row.0..=end_row.0)
 2835            .map(DisplayRow)
 2836            .filter_map(|row| {
 2837                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2838                    let start = display_map
 2839                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2840                        .to_point(display_map);
 2841                    let end = display_map
 2842                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2843                        .to_point(display_map);
 2844                    if reversed {
 2845                        Some(end..start)
 2846                    } else {
 2847                        Some(start..end)
 2848                    }
 2849                } else {
 2850                    None
 2851                }
 2852            })
 2853            .collect::<Vec<_>>();
 2854
 2855        self.change_selections(None, cx, |s| {
 2856            s.select_ranges(selection_ranges);
 2857        });
 2858        cx.notify();
 2859    }
 2860
 2861    pub fn has_pending_nonempty_selection(&self) -> bool {
 2862        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2863            Some(Selection { start, end, .. }) => start != end,
 2864            None => false,
 2865        };
 2866
 2867        pending_nonempty_selection
 2868            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2869    }
 2870
 2871    pub fn has_pending_selection(&self) -> bool {
 2872        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2873    }
 2874
 2875    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2876        if self.clear_clicked_diff_hunks(cx) {
 2877            cx.notify();
 2878            return;
 2879        }
 2880        if self.dismiss_menus_and_popups(true, cx) {
 2881            return;
 2882        }
 2883
 2884        if self.mode == EditorMode::Full {
 2885            if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
 2886                return;
 2887            }
 2888        }
 2889
 2890        cx.propagate();
 2891    }
 2892
 2893    pub fn dismiss_menus_and_popups(
 2894        &mut self,
 2895        should_report_inline_completion_event: bool,
 2896        cx: &mut ViewContext<Self>,
 2897    ) -> bool {
 2898        if self.take_rename(false, cx).is_some() {
 2899            return true;
 2900        }
 2901
 2902        if hide_hover(self, cx) {
 2903            return true;
 2904        }
 2905
 2906        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2907            return true;
 2908        }
 2909
 2910        if self.hide_context_menu(cx).is_some() {
 2911            return true;
 2912        }
 2913
 2914        if self.mouse_context_menu.take().is_some() {
 2915            return true;
 2916        }
 2917
 2918        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2919            return true;
 2920        }
 2921
 2922        if self.snippet_stack.pop().is_some() {
 2923            return true;
 2924        }
 2925
 2926        if self.mode == EditorMode::Full {
 2927            if self.active_diagnostics.is_some() {
 2928                self.dismiss_diagnostics(cx);
 2929                return true;
 2930            }
 2931        }
 2932
 2933        false
 2934    }
 2935
 2936    fn linked_editing_ranges_for(
 2937        &self,
 2938        selection: Range<text::Anchor>,
 2939        cx: &AppContext,
 2940    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2941        if self.linked_edit_ranges.is_empty() {
 2942            return None;
 2943        }
 2944        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2945            selection.end.buffer_id.and_then(|end_buffer_id| {
 2946                if selection.start.buffer_id != Some(end_buffer_id) {
 2947                    return None;
 2948                }
 2949                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2950                let snapshot = buffer.read(cx).snapshot();
 2951                self.linked_edit_ranges
 2952                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2953                    .map(|ranges| (ranges, snapshot, buffer))
 2954            })?;
 2955        use text::ToOffset as TO;
 2956        // find offset from the start of current range to current cursor position
 2957        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2958
 2959        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2960        let start_difference = start_offset - start_byte_offset;
 2961        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2962        let end_difference = end_offset - start_byte_offset;
 2963        // Current range has associated linked ranges.
 2964        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2965        for range in linked_ranges.iter() {
 2966            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2967            let end_offset = start_offset + end_difference;
 2968            let start_offset = start_offset + start_difference;
 2969            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2970                continue;
 2971            }
 2972            let start = buffer_snapshot.anchor_after(start_offset);
 2973            let end = buffer_snapshot.anchor_after(end_offset);
 2974            linked_edits
 2975                .entry(buffer.clone())
 2976                .or_default()
 2977                .push(start..end);
 2978        }
 2979        Some(linked_edits)
 2980    }
 2981
 2982    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2983        let text: Arc<str> = text.into();
 2984
 2985        if self.read_only(cx) {
 2986            return;
 2987        }
 2988
 2989        let selections = self.selections.all_adjusted(cx);
 2990        let mut bracket_inserted = false;
 2991        let mut edits = Vec::new();
 2992        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2993        let mut new_selections = Vec::with_capacity(selections.len());
 2994        let mut new_autoclose_regions = Vec::new();
 2995        let snapshot = self.buffer.read(cx).read(cx);
 2996
 2997        for (selection, autoclose_region) in
 2998            self.selections_with_autoclose_regions(selections, &snapshot)
 2999        {
 3000            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 3001                // Determine if the inserted text matches the opening or closing
 3002                // bracket of any of this language's bracket pairs.
 3003                let mut bracket_pair = None;
 3004                let mut is_bracket_pair_start = false;
 3005                let mut is_bracket_pair_end = false;
 3006                if !text.is_empty() {
 3007                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 3008                    //  and they are removing the character that triggered IME popup.
 3009                    for (pair, enabled) in scope.brackets() {
 3010                        if !pair.close && !pair.surround {
 3011                            continue;
 3012                        }
 3013
 3014                        if enabled && pair.start.ends_with(text.as_ref()) {
 3015                            bracket_pair = Some(pair.clone());
 3016                            is_bracket_pair_start = true;
 3017                            break;
 3018                        }
 3019                        if pair.end.as_str() == text.as_ref() {
 3020                            bracket_pair = Some(pair.clone());
 3021                            is_bracket_pair_end = true;
 3022                            break;
 3023                        }
 3024                    }
 3025                }
 3026
 3027                if let Some(bracket_pair) = bracket_pair {
 3028                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3029                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3030                    let auto_surround =
 3031                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3032                    if selection.is_empty() {
 3033                        if is_bracket_pair_start {
 3034                            let prefix_len = bracket_pair.start.len() - text.len();
 3035
 3036                            // If the inserted text is a suffix of an opening bracket and the
 3037                            // selection is preceded by the rest of the opening bracket, then
 3038                            // insert the closing bracket.
 3039                            let following_text_allows_autoclose = snapshot
 3040                                .chars_at(selection.start)
 3041                                .next()
 3042                                .map_or(true, |c| scope.should_autoclose_before(c));
 3043                            let preceding_text_matches_prefix = prefix_len == 0
 3044                                || (selection.start.column >= (prefix_len as u32)
 3045                                    && snapshot.contains_str_at(
 3046                                        Point::new(
 3047                                            selection.start.row,
 3048                                            selection.start.column - (prefix_len as u32),
 3049                                        ),
 3050                                        &bracket_pair.start[..prefix_len],
 3051                                    ));
 3052
 3053                            if autoclose
 3054                                && bracket_pair.close
 3055                                && following_text_allows_autoclose
 3056                                && preceding_text_matches_prefix
 3057                            {
 3058                                let anchor = snapshot.anchor_before(selection.end);
 3059                                new_selections.push((selection.map(|_| anchor), text.len()));
 3060                                new_autoclose_regions.push((
 3061                                    anchor,
 3062                                    text.len(),
 3063                                    selection.id,
 3064                                    bracket_pair.clone(),
 3065                                ));
 3066                                edits.push((
 3067                                    selection.range(),
 3068                                    format!("{}{}", text, bracket_pair.end).into(),
 3069                                ));
 3070                                bracket_inserted = true;
 3071                                continue;
 3072                            }
 3073                        }
 3074
 3075                        if let Some(region) = autoclose_region {
 3076                            // If the selection is followed by an auto-inserted closing bracket,
 3077                            // then don't insert that closing bracket again; just move the selection
 3078                            // past the closing bracket.
 3079                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3080                                && text.as_ref() == region.pair.end.as_str();
 3081                            if should_skip {
 3082                                let anchor = snapshot.anchor_after(selection.end);
 3083                                new_selections
 3084                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3085                                continue;
 3086                            }
 3087                        }
 3088
 3089                        let always_treat_brackets_as_autoclosed = snapshot
 3090                            .settings_at(selection.start, cx)
 3091                            .always_treat_brackets_as_autoclosed;
 3092                        if always_treat_brackets_as_autoclosed
 3093                            && is_bracket_pair_end
 3094                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3095                        {
 3096                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3097                            // and the inserted text is a closing bracket and the selection is followed
 3098                            // by the closing bracket then move the selection past the closing bracket.
 3099                            let anchor = snapshot.anchor_after(selection.end);
 3100                            new_selections.push((selection.map(|_| anchor), text.len()));
 3101                            continue;
 3102                        }
 3103                    }
 3104                    // If an opening bracket is 1 character long and is typed while
 3105                    // text is selected, then surround that text with the bracket pair.
 3106                    else if auto_surround
 3107                        && bracket_pair.surround
 3108                        && is_bracket_pair_start
 3109                        && bracket_pair.start.chars().count() == 1
 3110                    {
 3111                        edits.push((selection.start..selection.start, text.clone()));
 3112                        edits.push((
 3113                            selection.end..selection.end,
 3114                            bracket_pair.end.as_str().into(),
 3115                        ));
 3116                        bracket_inserted = true;
 3117                        new_selections.push((
 3118                            Selection {
 3119                                id: selection.id,
 3120                                start: snapshot.anchor_after(selection.start),
 3121                                end: snapshot.anchor_before(selection.end),
 3122                                reversed: selection.reversed,
 3123                                goal: selection.goal,
 3124                            },
 3125                            0,
 3126                        ));
 3127                        continue;
 3128                    }
 3129                }
 3130            }
 3131
 3132            if self.auto_replace_emoji_shortcode
 3133                && selection.is_empty()
 3134                && text.as_ref().ends_with(':')
 3135            {
 3136                if let Some(possible_emoji_short_code) =
 3137                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3138                {
 3139                    if !possible_emoji_short_code.is_empty() {
 3140                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3141                            let emoji_shortcode_start = Point::new(
 3142                                selection.start.row,
 3143                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3144                            );
 3145
 3146                            // Remove shortcode from buffer
 3147                            edits.push((
 3148                                emoji_shortcode_start..selection.start,
 3149                                "".to_string().into(),
 3150                            ));
 3151                            new_selections.push((
 3152                                Selection {
 3153                                    id: selection.id,
 3154                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3155                                    end: snapshot.anchor_before(selection.start),
 3156                                    reversed: selection.reversed,
 3157                                    goal: selection.goal,
 3158                                },
 3159                                0,
 3160                            ));
 3161
 3162                            // Insert emoji
 3163                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3164                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3165                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3166
 3167                            continue;
 3168                        }
 3169                    }
 3170                }
 3171            }
 3172
 3173            // If not handling any auto-close operation, then just replace the selected
 3174            // text with the given input and move the selection to the end of the
 3175            // newly inserted text.
 3176            let anchor = snapshot.anchor_after(selection.end);
 3177            if !self.linked_edit_ranges.is_empty() {
 3178                let start_anchor = snapshot.anchor_before(selection.start);
 3179
 3180                let is_word_char = text.chars().next().map_or(true, |char| {
 3181                    let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
 3182                    let kind = char_kind(&scope, char);
 3183
 3184                    kind == CharKind::Word
 3185                });
 3186
 3187                if is_word_char {
 3188                    if let Some(ranges) = self
 3189                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3190                    {
 3191                        for (buffer, edits) in ranges {
 3192                            linked_edits
 3193                                .entry(buffer.clone())
 3194                                .or_default()
 3195                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3196                        }
 3197                    }
 3198                }
 3199            }
 3200
 3201            new_selections.push((selection.map(|_| anchor), 0));
 3202            edits.push((selection.start..selection.end, text.clone()));
 3203        }
 3204
 3205        drop(snapshot);
 3206
 3207        self.transact(cx, |this, cx| {
 3208            this.buffer.update(cx, |buffer, cx| {
 3209                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3210            });
 3211            for (buffer, edits) in linked_edits {
 3212                buffer.update(cx, |buffer, cx| {
 3213                    let snapshot = buffer.snapshot();
 3214                    let edits = edits
 3215                        .into_iter()
 3216                        .map(|(range, text)| {
 3217                            use text::ToPoint as TP;
 3218                            let end_point = TP::to_point(&range.end, &snapshot);
 3219                            let start_point = TP::to_point(&range.start, &snapshot);
 3220                            (start_point..end_point, text)
 3221                        })
 3222                        .sorted_by_key(|(range, _)| range.start)
 3223                        .collect::<Vec<_>>();
 3224                    buffer.edit(edits, None, cx);
 3225                })
 3226            }
 3227            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3228            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3229            let snapshot = this.buffer.read(cx).read(cx);
 3230            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3231                .zip(new_selection_deltas)
 3232                .map(|(selection, delta)| Selection {
 3233                    id: selection.id,
 3234                    start: selection.start + delta,
 3235                    end: selection.end + delta,
 3236                    reversed: selection.reversed,
 3237                    goal: SelectionGoal::None,
 3238                })
 3239                .collect::<Vec<_>>();
 3240
 3241            let mut i = 0;
 3242            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3243                let position = position.to_offset(&snapshot) + delta;
 3244                let start = snapshot.anchor_before(position);
 3245                let end = snapshot.anchor_after(position);
 3246                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3247                    match existing_state.range.start.cmp(&start, &snapshot) {
 3248                        Ordering::Less => i += 1,
 3249                        Ordering::Greater => break,
 3250                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3251                            Ordering::Less => i += 1,
 3252                            Ordering::Equal => break,
 3253                            Ordering::Greater => break,
 3254                        },
 3255                    }
 3256                }
 3257                this.autoclose_regions.insert(
 3258                    i,
 3259                    AutocloseRegion {
 3260                        selection_id,
 3261                        range: start..end,
 3262                        pair,
 3263                    },
 3264                );
 3265            }
 3266
 3267            drop(snapshot);
 3268            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3269            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3270                s.select(new_selections)
 3271            });
 3272
 3273            if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
 3274                if let Some(on_type_format_task) =
 3275                    this.trigger_on_type_formatting(text.to_string(), cx)
 3276                {
 3277                    on_type_format_task.detach_and_log_err(cx);
 3278                }
 3279            }
 3280
 3281            let editor_settings = EditorSettings::get_global(cx);
 3282            if bracket_inserted
 3283                && (editor_settings.auto_signature_help
 3284                    || editor_settings.show_signature_help_after_edits)
 3285            {
 3286                this.show_signature_help(&ShowSignatureHelp, cx);
 3287            }
 3288
 3289            let trigger_in_words = !had_active_inline_completion;
 3290            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3291            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3292            this.refresh_inline_completion(true, cx);
 3293        });
 3294    }
 3295
 3296    fn find_possible_emoji_shortcode_at_position(
 3297        snapshot: &MultiBufferSnapshot,
 3298        position: Point,
 3299    ) -> Option<String> {
 3300        let mut chars = Vec::new();
 3301        let mut found_colon = false;
 3302        for char in snapshot.reversed_chars_at(position).take(100) {
 3303            // Found a possible emoji shortcode in the middle of the buffer
 3304            if found_colon {
 3305                if char.is_whitespace() {
 3306                    chars.reverse();
 3307                    return Some(chars.iter().collect());
 3308                }
 3309                // If the previous character is not a whitespace, we are in the middle of a word
 3310                // and we only want to complete the shortcode if the word is made up of other emojis
 3311                let mut containing_word = String::new();
 3312                for ch in snapshot
 3313                    .reversed_chars_at(position)
 3314                    .skip(chars.len() + 1)
 3315                    .take(100)
 3316                {
 3317                    if ch.is_whitespace() {
 3318                        break;
 3319                    }
 3320                    containing_word.push(ch);
 3321                }
 3322                let containing_word = containing_word.chars().rev().collect::<String>();
 3323                if util::word_consists_of_emojis(containing_word.as_str()) {
 3324                    chars.reverse();
 3325                    return Some(chars.iter().collect());
 3326                }
 3327            }
 3328
 3329            if char.is_whitespace() || !char.is_ascii() {
 3330                return None;
 3331            }
 3332            if char == ':' {
 3333                found_colon = true;
 3334            } else {
 3335                chars.push(char);
 3336            }
 3337        }
 3338        // Found a possible emoji shortcode at the beginning of the buffer
 3339        chars.reverse();
 3340        Some(chars.iter().collect())
 3341    }
 3342
 3343    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3344        self.transact(cx, |this, cx| {
 3345            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3346                let selections = this.selections.all::<usize>(cx);
 3347                let multi_buffer = this.buffer.read(cx);
 3348                let buffer = multi_buffer.snapshot(cx);
 3349                selections
 3350                    .iter()
 3351                    .map(|selection| {
 3352                        let start_point = selection.start.to_point(&buffer);
 3353                        let mut indent =
 3354                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3355                        indent.len = cmp::min(indent.len, start_point.column);
 3356                        let start = selection.start;
 3357                        let end = selection.end;
 3358                        let selection_is_empty = start == end;
 3359                        let language_scope = buffer.language_scope_at(start);
 3360                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3361                            &language_scope
 3362                        {
 3363                            let leading_whitespace_len = buffer
 3364                                .reversed_chars_at(start)
 3365                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3366                                .map(|c| c.len_utf8())
 3367                                .sum::<usize>();
 3368
 3369                            let trailing_whitespace_len = buffer
 3370                                .chars_at(end)
 3371                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3372                                .map(|c| c.len_utf8())
 3373                                .sum::<usize>();
 3374
 3375                            let insert_extra_newline =
 3376                                language.brackets().any(|(pair, enabled)| {
 3377                                    let pair_start = pair.start.trim_end();
 3378                                    let pair_end = pair.end.trim_start();
 3379
 3380                                    enabled
 3381                                        && pair.newline
 3382                                        && buffer.contains_str_at(
 3383                                            end + trailing_whitespace_len,
 3384                                            pair_end,
 3385                                        )
 3386                                        && buffer.contains_str_at(
 3387                                            (start - leading_whitespace_len)
 3388                                                .saturating_sub(pair_start.len()),
 3389                                            pair_start,
 3390                                        )
 3391                                });
 3392
 3393                            // Comment extension on newline is allowed only for cursor selections
 3394                            let comment_delimiter = maybe!({
 3395                                if !selection_is_empty {
 3396                                    return None;
 3397                                }
 3398
 3399                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3400                                    return None;
 3401                                }
 3402
 3403                                let delimiters = language.line_comment_prefixes();
 3404                                let max_len_of_delimiter =
 3405                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3406                                let (snapshot, range) =
 3407                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3408
 3409                                let mut index_of_first_non_whitespace = 0;
 3410                                let comment_candidate = snapshot
 3411                                    .chars_for_range(range)
 3412                                    .skip_while(|c| {
 3413                                        let should_skip = c.is_whitespace();
 3414                                        if should_skip {
 3415                                            index_of_first_non_whitespace += 1;
 3416                                        }
 3417                                        should_skip
 3418                                    })
 3419                                    .take(max_len_of_delimiter)
 3420                                    .collect::<String>();
 3421                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3422                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3423                                })?;
 3424                                let cursor_is_placed_after_comment_marker =
 3425                                    index_of_first_non_whitespace + comment_prefix.len()
 3426                                        <= start_point.column as usize;
 3427                                if cursor_is_placed_after_comment_marker {
 3428                                    Some(comment_prefix.clone())
 3429                                } else {
 3430                                    None
 3431                                }
 3432                            });
 3433                            (comment_delimiter, insert_extra_newline)
 3434                        } else {
 3435                            (None, false)
 3436                        };
 3437
 3438                        let capacity_for_delimiter = comment_delimiter
 3439                            .as_deref()
 3440                            .map(str::len)
 3441                            .unwrap_or_default();
 3442                        let mut new_text =
 3443                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3444                        new_text.push_str("\n");
 3445                        new_text.extend(indent.chars());
 3446                        if let Some(delimiter) = &comment_delimiter {
 3447                            new_text.push_str(&delimiter);
 3448                        }
 3449                        if insert_extra_newline {
 3450                            new_text = new_text.repeat(2);
 3451                        }
 3452
 3453                        let anchor = buffer.anchor_after(end);
 3454                        let new_selection = selection.map(|_| anchor);
 3455                        (
 3456                            (start..end, new_text),
 3457                            (insert_extra_newline, new_selection),
 3458                        )
 3459                    })
 3460                    .unzip()
 3461            };
 3462
 3463            this.edit_with_autoindent(edits, cx);
 3464            let buffer = this.buffer.read(cx).snapshot(cx);
 3465            let new_selections = selection_fixup_info
 3466                .into_iter()
 3467                .map(|(extra_newline_inserted, new_selection)| {
 3468                    let mut cursor = new_selection.end.to_point(&buffer);
 3469                    if extra_newline_inserted {
 3470                        cursor.row -= 1;
 3471                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3472                    }
 3473                    new_selection.map(|_| cursor)
 3474                })
 3475                .collect();
 3476
 3477            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3478            this.refresh_inline_completion(true, cx);
 3479        });
 3480    }
 3481
 3482    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3483        let buffer = self.buffer.read(cx);
 3484        let snapshot = buffer.snapshot(cx);
 3485
 3486        let mut edits = Vec::new();
 3487        let mut rows = Vec::new();
 3488
 3489        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3490            let cursor = selection.head();
 3491            let row = cursor.row;
 3492
 3493            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3494
 3495            let newline = "\n".to_string();
 3496            edits.push((start_of_line..start_of_line, newline));
 3497
 3498            rows.push(row + rows_inserted as u32);
 3499        }
 3500
 3501        self.transact(cx, |editor, cx| {
 3502            editor.edit(edits, cx);
 3503
 3504            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3505                let mut index = 0;
 3506                s.move_cursors_with(|map, _, _| {
 3507                    let row = rows[index];
 3508                    index += 1;
 3509
 3510                    let point = Point::new(row, 0);
 3511                    let boundary = map.next_line_boundary(point).1;
 3512                    let clipped = map.clip_point(boundary, Bias::Left);
 3513
 3514                    (clipped, SelectionGoal::None)
 3515                });
 3516            });
 3517
 3518            let mut indent_edits = Vec::new();
 3519            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3520            for row in rows {
 3521                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3522                for (row, indent) in indents {
 3523                    if indent.len == 0 {
 3524                        continue;
 3525                    }
 3526
 3527                    let text = match indent.kind {
 3528                        IndentKind::Space => " ".repeat(indent.len as usize),
 3529                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3530                    };
 3531                    let point = Point::new(row.0, 0);
 3532                    indent_edits.push((point..point, text));
 3533                }
 3534            }
 3535            editor.edit(indent_edits, cx);
 3536        });
 3537    }
 3538
 3539    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3540        let buffer = self.buffer.read(cx);
 3541        let snapshot = buffer.snapshot(cx);
 3542
 3543        let mut edits = Vec::new();
 3544        let mut rows = Vec::new();
 3545        let mut rows_inserted = 0;
 3546
 3547        for selection in self.selections.all_adjusted(cx) {
 3548            let cursor = selection.head();
 3549            let row = cursor.row;
 3550
 3551            let point = Point::new(row + 1, 0);
 3552            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3553
 3554            let newline = "\n".to_string();
 3555            edits.push((start_of_line..start_of_line, newline));
 3556
 3557            rows_inserted += 1;
 3558            rows.push(row + rows_inserted);
 3559        }
 3560
 3561        self.transact(cx, |editor, cx| {
 3562            editor.edit(edits, cx);
 3563
 3564            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3565                let mut index = 0;
 3566                s.move_cursors_with(|map, _, _| {
 3567                    let row = rows[index];
 3568                    index += 1;
 3569
 3570                    let point = Point::new(row, 0);
 3571                    let boundary = map.next_line_boundary(point).1;
 3572                    let clipped = map.clip_point(boundary, Bias::Left);
 3573
 3574                    (clipped, SelectionGoal::None)
 3575                });
 3576            });
 3577
 3578            let mut indent_edits = Vec::new();
 3579            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3580            for row in rows {
 3581                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3582                for (row, indent) in indents {
 3583                    if indent.len == 0 {
 3584                        continue;
 3585                    }
 3586
 3587                    let text = match indent.kind {
 3588                        IndentKind::Space => " ".repeat(indent.len as usize),
 3589                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3590                    };
 3591                    let point = Point::new(row.0, 0);
 3592                    indent_edits.push((point..point, text));
 3593                }
 3594            }
 3595            editor.edit(indent_edits, cx);
 3596        });
 3597    }
 3598
 3599    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3600        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3601            original_indent_columns: Vec::new(),
 3602        });
 3603        self.insert_with_autoindent_mode(text, autoindent, cx);
 3604    }
 3605
 3606    fn insert_with_autoindent_mode(
 3607        &mut self,
 3608        text: &str,
 3609        autoindent_mode: Option<AutoindentMode>,
 3610        cx: &mut ViewContext<Self>,
 3611    ) {
 3612        if self.read_only(cx) {
 3613            return;
 3614        }
 3615
 3616        let text: Arc<str> = text.into();
 3617        self.transact(cx, |this, cx| {
 3618            let old_selections = this.selections.all_adjusted(cx);
 3619            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3620                let anchors = {
 3621                    let snapshot = buffer.read(cx);
 3622                    old_selections
 3623                        .iter()
 3624                        .map(|s| {
 3625                            let anchor = snapshot.anchor_after(s.head());
 3626                            s.map(|_| anchor)
 3627                        })
 3628                        .collect::<Vec<_>>()
 3629                };
 3630                buffer.edit(
 3631                    old_selections
 3632                        .iter()
 3633                        .map(|s| (s.start..s.end, text.clone())),
 3634                    autoindent_mode,
 3635                    cx,
 3636                );
 3637                anchors
 3638            });
 3639
 3640            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3641                s.select_anchors(selection_anchors);
 3642            })
 3643        });
 3644    }
 3645
 3646    fn trigger_completion_on_input(
 3647        &mut self,
 3648        text: &str,
 3649        trigger_in_words: bool,
 3650        cx: &mut ViewContext<Self>,
 3651    ) {
 3652        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3653            self.show_completions(
 3654                &ShowCompletions {
 3655                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3656                },
 3657                cx,
 3658            );
 3659        } else {
 3660            self.hide_context_menu(cx);
 3661        }
 3662    }
 3663
 3664    fn is_completion_trigger(
 3665        &self,
 3666        text: &str,
 3667        trigger_in_words: bool,
 3668        cx: &mut ViewContext<Self>,
 3669    ) -> bool {
 3670        let position = self.selections.newest_anchor().head();
 3671        let multibuffer = self.buffer.read(cx);
 3672        let Some(buffer) = position
 3673            .buffer_id
 3674            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3675        else {
 3676            return false;
 3677        };
 3678
 3679        if let Some(completion_provider) = &self.completion_provider {
 3680            completion_provider.is_completion_trigger(
 3681                &buffer,
 3682                position.text_anchor,
 3683                text,
 3684                trigger_in_words,
 3685                cx,
 3686            )
 3687        } else {
 3688            false
 3689        }
 3690    }
 3691
 3692    /// If any empty selections is touching the start of its innermost containing autoclose
 3693    /// region, expand it to select the brackets.
 3694    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3695        let selections = self.selections.all::<usize>(cx);
 3696        let buffer = self.buffer.read(cx).read(cx);
 3697        let new_selections = self
 3698            .selections_with_autoclose_regions(selections, &buffer)
 3699            .map(|(mut selection, region)| {
 3700                if !selection.is_empty() {
 3701                    return selection;
 3702                }
 3703
 3704                if let Some(region) = region {
 3705                    let mut range = region.range.to_offset(&buffer);
 3706                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3707                        range.start -= region.pair.start.len();
 3708                        if buffer.contains_str_at(range.start, &region.pair.start)
 3709                            && buffer.contains_str_at(range.end, &region.pair.end)
 3710                        {
 3711                            range.end += region.pair.end.len();
 3712                            selection.start = range.start;
 3713                            selection.end = range.end;
 3714
 3715                            return selection;
 3716                        }
 3717                    }
 3718                }
 3719
 3720                let always_treat_brackets_as_autoclosed = buffer
 3721                    .settings_at(selection.start, cx)
 3722                    .always_treat_brackets_as_autoclosed;
 3723
 3724                if !always_treat_brackets_as_autoclosed {
 3725                    return selection;
 3726                }
 3727
 3728                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3729                    for (pair, enabled) in scope.brackets() {
 3730                        if !enabled || !pair.close {
 3731                            continue;
 3732                        }
 3733
 3734                        if buffer.contains_str_at(selection.start, &pair.end) {
 3735                            let pair_start_len = pair.start.len();
 3736                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3737                            {
 3738                                selection.start -= pair_start_len;
 3739                                selection.end += pair.end.len();
 3740
 3741                                return selection;
 3742                            }
 3743                        }
 3744                    }
 3745                }
 3746
 3747                selection
 3748            })
 3749            .collect();
 3750
 3751        drop(buffer);
 3752        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3753    }
 3754
 3755    /// Iterate the given selections, and for each one, find the smallest surrounding
 3756    /// autoclose region. This uses the ordering of the selections and the autoclose
 3757    /// regions to avoid repeated comparisons.
 3758    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3759        &'a self,
 3760        selections: impl IntoIterator<Item = Selection<D>>,
 3761        buffer: &'a MultiBufferSnapshot,
 3762    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3763        let mut i = 0;
 3764        let mut regions = self.autoclose_regions.as_slice();
 3765        selections.into_iter().map(move |selection| {
 3766            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3767
 3768            let mut enclosing = None;
 3769            while let Some(pair_state) = regions.get(i) {
 3770                if pair_state.range.end.to_offset(buffer) < range.start {
 3771                    regions = &regions[i + 1..];
 3772                    i = 0;
 3773                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3774                    break;
 3775                } else {
 3776                    if pair_state.selection_id == selection.id {
 3777                        enclosing = Some(pair_state);
 3778                    }
 3779                    i += 1;
 3780                }
 3781            }
 3782
 3783            (selection.clone(), enclosing)
 3784        })
 3785    }
 3786
 3787    /// Remove any autoclose regions that no longer contain their selection.
 3788    fn invalidate_autoclose_regions(
 3789        &mut self,
 3790        mut selections: &[Selection<Anchor>],
 3791        buffer: &MultiBufferSnapshot,
 3792    ) {
 3793        self.autoclose_regions.retain(|state| {
 3794            let mut i = 0;
 3795            while let Some(selection) = selections.get(i) {
 3796                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3797                    selections = &selections[1..];
 3798                    continue;
 3799                }
 3800                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3801                    break;
 3802                }
 3803                if selection.id == state.selection_id {
 3804                    return true;
 3805                } else {
 3806                    i += 1;
 3807                }
 3808            }
 3809            false
 3810        });
 3811    }
 3812
 3813    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3814        let offset = position.to_offset(buffer);
 3815        let (word_range, kind) = buffer.surrounding_word(offset);
 3816        if offset > word_range.start && kind == Some(CharKind::Word) {
 3817            Some(
 3818                buffer
 3819                    .text_for_range(word_range.start..offset)
 3820                    .collect::<String>(),
 3821            )
 3822        } else {
 3823            None
 3824        }
 3825    }
 3826
 3827    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3828        self.refresh_inlay_hints(
 3829            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3830            cx,
 3831        );
 3832    }
 3833
 3834    pub fn inlay_hints_enabled(&self) -> bool {
 3835        self.inlay_hint_cache.enabled
 3836    }
 3837
 3838    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3839        if self.project.is_none() || self.mode != EditorMode::Full {
 3840            return;
 3841        }
 3842
 3843        let reason_description = reason.description();
 3844        let ignore_debounce = matches!(
 3845            reason,
 3846            InlayHintRefreshReason::SettingsChange(_)
 3847                | InlayHintRefreshReason::Toggle(_)
 3848                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3849        );
 3850        let (invalidate_cache, required_languages) = match reason {
 3851            InlayHintRefreshReason::Toggle(enabled) => {
 3852                self.inlay_hint_cache.enabled = enabled;
 3853                if enabled {
 3854                    (InvalidationStrategy::RefreshRequested, None)
 3855                } else {
 3856                    self.inlay_hint_cache.clear();
 3857                    self.splice_inlays(
 3858                        self.visible_inlay_hints(cx)
 3859                            .iter()
 3860                            .map(|inlay| inlay.id)
 3861                            .collect(),
 3862                        Vec::new(),
 3863                        cx,
 3864                    );
 3865                    return;
 3866                }
 3867            }
 3868            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3869                match self.inlay_hint_cache.update_settings(
 3870                    &self.buffer,
 3871                    new_settings,
 3872                    self.visible_inlay_hints(cx),
 3873                    cx,
 3874                ) {
 3875                    ControlFlow::Break(Some(InlaySplice {
 3876                        to_remove,
 3877                        to_insert,
 3878                    })) => {
 3879                        self.splice_inlays(to_remove, to_insert, cx);
 3880                        return;
 3881                    }
 3882                    ControlFlow::Break(None) => return,
 3883                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3884                }
 3885            }
 3886            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3887                if let Some(InlaySplice {
 3888                    to_remove,
 3889                    to_insert,
 3890                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3891                {
 3892                    self.splice_inlays(to_remove, to_insert, cx);
 3893                }
 3894                return;
 3895            }
 3896            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3897            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3898                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3899            }
 3900            InlayHintRefreshReason::RefreshRequested => {
 3901                (InvalidationStrategy::RefreshRequested, None)
 3902            }
 3903        };
 3904
 3905        if let Some(InlaySplice {
 3906            to_remove,
 3907            to_insert,
 3908        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3909            reason_description,
 3910            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3911            invalidate_cache,
 3912            ignore_debounce,
 3913            cx,
 3914        ) {
 3915            self.splice_inlays(to_remove, to_insert, cx);
 3916        }
 3917    }
 3918
 3919    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3920        self.display_map
 3921            .read(cx)
 3922            .current_inlays()
 3923            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3924            .cloned()
 3925            .collect()
 3926    }
 3927
 3928    pub fn excerpts_for_inlay_hints_query(
 3929        &self,
 3930        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3931        cx: &mut ViewContext<Editor>,
 3932    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3933        let Some(project) = self.project.as_ref() else {
 3934            return HashMap::default();
 3935        };
 3936        let project = project.read(cx);
 3937        let multi_buffer = self.buffer().read(cx);
 3938        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3939        let multi_buffer_visible_start = self
 3940            .scroll_manager
 3941            .anchor()
 3942            .anchor
 3943            .to_point(&multi_buffer_snapshot);
 3944        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3945            multi_buffer_visible_start
 3946                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3947            Bias::Left,
 3948        );
 3949        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3950        multi_buffer
 3951            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3952            .into_iter()
 3953            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3954            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3955                let buffer = buffer_handle.read(cx);
 3956                let buffer_file = project::File::from_dyn(buffer.file())?;
 3957                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3958                let worktree_entry = buffer_worktree
 3959                    .read(cx)
 3960                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3961                if worktree_entry.is_ignored {
 3962                    return None;
 3963                }
 3964
 3965                let language = buffer.language()?;
 3966                if let Some(restrict_to_languages) = restrict_to_languages {
 3967                    if !restrict_to_languages.contains(language) {
 3968                        return None;
 3969                    }
 3970                }
 3971                Some((
 3972                    excerpt_id,
 3973                    (
 3974                        buffer_handle,
 3975                        buffer.version().clone(),
 3976                        excerpt_visible_range,
 3977                    ),
 3978                ))
 3979            })
 3980            .collect()
 3981    }
 3982
 3983    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3984        TextLayoutDetails {
 3985            text_system: cx.text_system().clone(),
 3986            editor_style: self.style.clone().unwrap(),
 3987            rem_size: cx.rem_size(),
 3988            scroll_anchor: self.scroll_manager.anchor(),
 3989            visible_rows: self.visible_line_count(),
 3990            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3991        }
 3992    }
 3993
 3994    fn splice_inlays(
 3995        &self,
 3996        to_remove: Vec<InlayId>,
 3997        to_insert: Vec<Inlay>,
 3998        cx: &mut ViewContext<Self>,
 3999    ) {
 4000        self.display_map.update(cx, |display_map, cx| {
 4001            display_map.splice_inlays(to_remove, to_insert, cx);
 4002        });
 4003        cx.notify();
 4004    }
 4005
 4006    fn trigger_on_type_formatting(
 4007        &self,
 4008        input: String,
 4009        cx: &mut ViewContext<Self>,
 4010    ) -> Option<Task<Result<()>>> {
 4011        if input.len() != 1 {
 4012            return None;
 4013        }
 4014
 4015        let project = self.project.as_ref()?;
 4016        let position = self.selections.newest_anchor().head();
 4017        let (buffer, buffer_position) = self
 4018            .buffer
 4019            .read(cx)
 4020            .text_anchor_for_position(position, cx)?;
 4021
 4022        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4023        // hence we do LSP request & edit on host side only — add formats to host's history.
 4024        let push_to_lsp_host_history = true;
 4025        // If this is not the host, append its history with new edits.
 4026        let push_to_client_history = project.read(cx).is_remote();
 4027
 4028        let on_type_formatting = project.update(cx, |project, cx| {
 4029            project.on_type_format(
 4030                buffer.clone(),
 4031                buffer_position,
 4032                input,
 4033                push_to_lsp_host_history,
 4034                cx,
 4035            )
 4036        });
 4037        Some(cx.spawn(|editor, mut cx| async move {
 4038            if let Some(transaction) = on_type_formatting.await? {
 4039                if push_to_client_history {
 4040                    buffer
 4041                        .update(&mut cx, |buffer, _| {
 4042                            buffer.push_transaction(transaction, Instant::now());
 4043                        })
 4044                        .ok();
 4045                }
 4046                editor.update(&mut cx, |editor, cx| {
 4047                    editor.refresh_document_highlights(cx);
 4048                })?;
 4049            }
 4050            Ok(())
 4051        }))
 4052    }
 4053
 4054    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4055        if self.pending_rename.is_some() {
 4056            return;
 4057        }
 4058
 4059        let Some(provider) = self.completion_provider.as_ref() else {
 4060            return;
 4061        };
 4062
 4063        let position = self.selections.newest_anchor().head();
 4064        let (buffer, buffer_position) =
 4065            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4066                output
 4067            } else {
 4068                return;
 4069            };
 4070
 4071        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4072        let is_followup_invoke = {
 4073            let context_menu_state = self.context_menu.read();
 4074            matches!(
 4075                context_menu_state.deref(),
 4076                Some(ContextMenu::Completions(_))
 4077            )
 4078        };
 4079        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4080            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4081            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(&trigger) => {
 4082                CompletionTriggerKind::TRIGGER_CHARACTER
 4083            }
 4084
 4085            _ => CompletionTriggerKind::INVOKED,
 4086        };
 4087        let completion_context = CompletionContext {
 4088            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4089                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4090                    Some(String::from(trigger))
 4091                } else {
 4092                    None
 4093                }
 4094            }),
 4095            trigger_kind,
 4096        };
 4097        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4098
 4099        let id = post_inc(&mut self.next_completion_id);
 4100        let task = cx.spawn(|this, mut cx| {
 4101            async move {
 4102                this.update(&mut cx, |this, _| {
 4103                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4104                })?;
 4105                let completions = completions.await.log_err();
 4106                let menu = if let Some(completions) = completions {
 4107                    let mut menu = CompletionsMenu {
 4108                        id,
 4109                        initial_position: position,
 4110                        match_candidates: completions
 4111                            .iter()
 4112                            .enumerate()
 4113                            .map(|(id, completion)| {
 4114                                StringMatchCandidate::new(
 4115                                    id,
 4116                                    completion.label.text[completion.label.filter_range.clone()]
 4117                                        .into(),
 4118                                )
 4119                            })
 4120                            .collect(),
 4121                        buffer: buffer.clone(),
 4122                        completions: Arc::new(RwLock::new(completions.into())),
 4123                        matches: Vec::new().into(),
 4124                        selected_item: 0,
 4125                        scroll_handle: UniformListScrollHandle::new(),
 4126                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4127                            DebouncedDelay::new(),
 4128                        )),
 4129                    };
 4130                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4131                        .await;
 4132
 4133                    if menu.matches.is_empty() {
 4134                        None
 4135                    } else {
 4136                        this.update(&mut cx, |editor, cx| {
 4137                            let completions = menu.completions.clone();
 4138                            let matches = menu.matches.clone();
 4139
 4140                            let delay_ms = EditorSettings::get_global(cx)
 4141                                .completion_documentation_secondary_query_debounce;
 4142                            let delay = Duration::from_millis(delay_ms);
 4143                            editor
 4144                                .completion_documentation_pre_resolve_debounce
 4145                                .fire_new(delay, cx, |editor, cx| {
 4146                                    CompletionsMenu::pre_resolve_completion_documentation(
 4147                                        buffer,
 4148                                        completions,
 4149                                        matches,
 4150                                        editor,
 4151                                        cx,
 4152                                    )
 4153                                });
 4154                        })
 4155                        .ok();
 4156                        Some(menu)
 4157                    }
 4158                } else {
 4159                    None
 4160                };
 4161
 4162                this.update(&mut cx, |this, cx| {
 4163                    let mut context_menu = this.context_menu.write();
 4164                    match context_menu.as_ref() {
 4165                        None => {}
 4166
 4167                        Some(ContextMenu::Completions(prev_menu)) => {
 4168                            if prev_menu.id > id {
 4169                                return;
 4170                            }
 4171                        }
 4172
 4173                        _ => return,
 4174                    }
 4175
 4176                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4177                        let menu = menu.unwrap();
 4178                        *context_menu = Some(ContextMenu::Completions(menu));
 4179                        drop(context_menu);
 4180                        this.discard_inline_completion(false, cx);
 4181                        cx.notify();
 4182                    } else if this.completion_tasks.len() <= 1 {
 4183                        // If there are no more completion tasks and the last menu was
 4184                        // empty, we should hide it. If it was already hidden, we should
 4185                        // also show the copilot completion when available.
 4186                        drop(context_menu);
 4187                        if this.hide_context_menu(cx).is_none() {
 4188                            this.update_visible_inline_completion(cx);
 4189                        }
 4190                    }
 4191                })?;
 4192
 4193                Ok::<_, anyhow::Error>(())
 4194            }
 4195            .log_err()
 4196        });
 4197
 4198        self.completion_tasks.push((id, task));
 4199    }
 4200
 4201    pub fn confirm_completion(
 4202        &mut self,
 4203        action: &ConfirmCompletion,
 4204        cx: &mut ViewContext<Self>,
 4205    ) -> Option<Task<Result<()>>> {
 4206        use language::ToOffset as _;
 4207
 4208        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4209            menu
 4210        } else {
 4211            return None;
 4212        };
 4213
 4214        let mat = completions_menu
 4215            .matches
 4216            .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
 4217        let buffer_handle = completions_menu.buffer;
 4218        let completions = completions_menu.completions.read();
 4219        let completion = completions.get(mat.candidate_id)?;
 4220        cx.stop_propagation();
 4221
 4222        let snippet;
 4223        let text;
 4224
 4225        if completion.is_snippet() {
 4226            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4227            text = snippet.as_ref().unwrap().text.clone();
 4228        } else {
 4229            snippet = None;
 4230            text = completion.new_text.clone();
 4231        };
 4232        let selections = self.selections.all::<usize>(cx);
 4233        let buffer = buffer_handle.read(cx);
 4234        let old_range = completion.old_range.to_offset(buffer);
 4235        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4236
 4237        let newest_selection = self.selections.newest_anchor();
 4238        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4239            return None;
 4240        }
 4241
 4242        let lookbehind = newest_selection
 4243            .start
 4244            .text_anchor
 4245            .to_offset(buffer)
 4246            .saturating_sub(old_range.start);
 4247        let lookahead = old_range
 4248            .end
 4249            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4250        let mut common_prefix_len = old_text
 4251            .bytes()
 4252            .zip(text.bytes())
 4253            .take_while(|(a, b)| a == b)
 4254            .count();
 4255
 4256        let snapshot = self.buffer.read(cx).snapshot(cx);
 4257        let mut range_to_replace: Option<Range<isize>> = None;
 4258        let mut ranges = Vec::new();
 4259        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4260        for selection in &selections {
 4261            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4262                let start = selection.start.saturating_sub(lookbehind);
 4263                let end = selection.end + lookahead;
 4264                if selection.id == newest_selection.id {
 4265                    range_to_replace = Some(
 4266                        ((start + common_prefix_len) as isize - selection.start as isize)
 4267                            ..(end as isize - selection.start as isize),
 4268                    );
 4269                }
 4270                ranges.push(start + common_prefix_len..end);
 4271            } else {
 4272                common_prefix_len = 0;
 4273                ranges.clear();
 4274                ranges.extend(selections.iter().map(|s| {
 4275                    if s.id == newest_selection.id {
 4276                        range_to_replace = Some(
 4277                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4278                                - selection.start as isize
 4279                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4280                                    - selection.start as isize,
 4281                        );
 4282                        old_range.clone()
 4283                    } else {
 4284                        s.start..s.end
 4285                    }
 4286                }));
 4287                break;
 4288            }
 4289            if !self.linked_edit_ranges.is_empty() {
 4290                let start_anchor = snapshot.anchor_before(selection.head());
 4291                let end_anchor = snapshot.anchor_after(selection.tail());
 4292                if let Some(ranges) = self
 4293                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4294                {
 4295                    for (buffer, edits) in ranges {
 4296                        linked_edits.entry(buffer.clone()).or_default().extend(
 4297                            edits
 4298                                .into_iter()
 4299                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4300                        );
 4301                    }
 4302                }
 4303            }
 4304        }
 4305        let text = &text[common_prefix_len..];
 4306
 4307        cx.emit(EditorEvent::InputHandled {
 4308            utf16_range_to_replace: range_to_replace,
 4309            text: text.into(),
 4310        });
 4311
 4312        self.transact(cx, |this, cx| {
 4313            if let Some(mut snippet) = snippet {
 4314                snippet.text = text.to_string();
 4315                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4316                    tabstop.start -= common_prefix_len as isize;
 4317                    tabstop.end -= common_prefix_len as isize;
 4318                }
 4319
 4320                this.insert_snippet(&ranges, snippet, cx).log_err();
 4321            } else {
 4322                this.buffer.update(cx, |buffer, cx| {
 4323                    buffer.edit(
 4324                        ranges.iter().map(|range| (range.clone(), text)),
 4325                        this.autoindent_mode.clone(),
 4326                        cx,
 4327                    );
 4328                });
 4329            }
 4330            for (buffer, edits) in linked_edits {
 4331                buffer.update(cx, |buffer, cx| {
 4332                    let snapshot = buffer.snapshot();
 4333                    let edits = edits
 4334                        .into_iter()
 4335                        .map(|(range, text)| {
 4336                            use text::ToPoint as TP;
 4337                            let end_point = TP::to_point(&range.end, &snapshot);
 4338                            let start_point = TP::to_point(&range.start, &snapshot);
 4339                            (start_point..end_point, text)
 4340                        })
 4341                        .sorted_by_key(|(range, _)| range.start)
 4342                        .collect::<Vec<_>>();
 4343                    buffer.edit(edits, None, cx);
 4344                })
 4345            }
 4346
 4347            this.refresh_inline_completion(true, cx);
 4348        });
 4349
 4350        if let Some(confirm) = completion.confirm.as_ref() {
 4351            (confirm)(cx);
 4352        }
 4353
 4354        if completion.show_new_completions_on_confirm {
 4355            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4356        }
 4357
 4358        let provider = self.completion_provider.as_ref()?;
 4359        let apply_edits = provider.apply_additional_edits_for_completion(
 4360            buffer_handle,
 4361            completion.clone(),
 4362            true,
 4363            cx,
 4364        );
 4365
 4366        let editor_settings = EditorSettings::get_global(cx);
 4367        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4368            // After the code completion is finished, users often want to know what signatures are needed.
 4369            // so we should automatically call signature_help
 4370            self.show_signature_help(&ShowSignatureHelp, cx);
 4371        }
 4372
 4373        Some(cx.foreground_executor().spawn(async move {
 4374            apply_edits.await?;
 4375            Ok(())
 4376        }))
 4377    }
 4378
 4379    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4380        let mut context_menu = self.context_menu.write();
 4381        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4382            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4383                // Toggle if we're selecting the same one
 4384                *context_menu = None;
 4385                cx.notify();
 4386                return;
 4387            } else {
 4388                // Otherwise, clear it and start a new one
 4389                *context_menu = None;
 4390                cx.notify();
 4391            }
 4392        }
 4393        drop(context_menu);
 4394        let snapshot = self.snapshot(cx);
 4395        let deployed_from_indicator = action.deployed_from_indicator;
 4396        let mut task = self.code_actions_task.take();
 4397        let action = action.clone();
 4398        cx.spawn(|editor, mut cx| async move {
 4399            while let Some(prev_task) = task {
 4400                prev_task.await;
 4401                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4402            }
 4403
 4404            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4405                if editor.focus_handle.is_focused(cx) {
 4406                    let multibuffer_point = action
 4407                        .deployed_from_indicator
 4408                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4409                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4410                    let (buffer, buffer_row) = snapshot
 4411                        .buffer_snapshot
 4412                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4413                        .and_then(|(buffer_snapshot, range)| {
 4414                            editor
 4415                                .buffer
 4416                                .read(cx)
 4417                                .buffer(buffer_snapshot.remote_id())
 4418                                .map(|buffer| (buffer, range.start.row))
 4419                        })?;
 4420                    let (_, code_actions) = editor
 4421                        .available_code_actions
 4422                        .clone()
 4423                        .and_then(|(location, code_actions)| {
 4424                            let snapshot = location.buffer.read(cx).snapshot();
 4425                            let point_range = location.range.to_point(&snapshot);
 4426                            let point_range = point_range.start.row..=point_range.end.row;
 4427                            if point_range.contains(&buffer_row) {
 4428                                Some((location, code_actions))
 4429                            } else {
 4430                                None
 4431                            }
 4432                        })
 4433                        .unzip();
 4434                    let buffer_id = buffer.read(cx).remote_id();
 4435                    let tasks = editor
 4436                        .tasks
 4437                        .get(&(buffer_id, buffer_row))
 4438                        .map(|t| Arc::new(t.to_owned()));
 4439                    if tasks.is_none() && code_actions.is_none() {
 4440                        return None;
 4441                    }
 4442
 4443                    editor.completion_tasks.clear();
 4444                    editor.discard_inline_completion(false, cx);
 4445                    let task_context =
 4446                        tasks
 4447                            .as_ref()
 4448                            .zip(editor.project.clone())
 4449                            .map(|(tasks, project)| {
 4450                                let position = Point::new(buffer_row, tasks.column);
 4451                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4452                                let location = Location {
 4453                                    buffer: buffer.clone(),
 4454                                    range: range_start..range_start,
 4455                                };
 4456                                // Fill in the environmental variables from the tree-sitter captures
 4457                                let mut captured_task_variables = TaskVariables::default();
 4458                                for (capture_name, value) in tasks.extra_variables.clone() {
 4459                                    captured_task_variables.insert(
 4460                                        task::VariableName::Custom(capture_name.into()),
 4461                                        value.clone(),
 4462                                    );
 4463                                }
 4464                                project.update(cx, |project, cx| {
 4465                                    project.task_context_for_location(
 4466                                        captured_task_variables,
 4467                                        location,
 4468                                        cx,
 4469                                    )
 4470                                })
 4471                            });
 4472
 4473                    Some(cx.spawn(|editor, mut cx| async move {
 4474                        let task_context = match task_context {
 4475                            Some(task_context) => task_context.await,
 4476                            None => None,
 4477                        };
 4478                        let resolved_tasks =
 4479                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4480                                Arc::new(ResolvedTasks {
 4481                                    templates: tasks
 4482                                        .templates
 4483                                        .iter()
 4484                                        .filter_map(|(kind, template)| {
 4485                                            template
 4486                                                .resolve_task(&kind.to_id_base(), &task_context)
 4487                                                .map(|task| (kind.clone(), task))
 4488                                        })
 4489                                        .collect(),
 4490                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4491                                        multibuffer_point.row,
 4492                                        tasks.column,
 4493                                    )),
 4494                                })
 4495                            });
 4496                        let spawn_straight_away = resolved_tasks
 4497                            .as_ref()
 4498                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4499                            && code_actions
 4500                                .as_ref()
 4501                                .map_or(true, |actions| actions.is_empty());
 4502                        if let Some(task) = editor
 4503                            .update(&mut cx, |editor, cx| {
 4504                                *editor.context_menu.write() =
 4505                                    Some(ContextMenu::CodeActions(CodeActionsMenu {
 4506                                        buffer,
 4507                                        actions: CodeActionContents {
 4508                                            tasks: resolved_tasks,
 4509                                            actions: code_actions,
 4510                                        },
 4511                                        selected_item: Default::default(),
 4512                                        scroll_handle: UniformListScrollHandle::default(),
 4513                                        deployed_from_indicator,
 4514                                    }));
 4515                                if spawn_straight_away {
 4516                                    if let Some(task) = editor.confirm_code_action(
 4517                                        &ConfirmCodeAction { item_ix: Some(0) },
 4518                                        cx,
 4519                                    ) {
 4520                                        cx.notify();
 4521                                        return task;
 4522                                    }
 4523                                }
 4524                                cx.notify();
 4525                                Task::ready(Ok(()))
 4526                            })
 4527                            .ok()
 4528                        {
 4529                            task.await
 4530                        } else {
 4531                            Ok(())
 4532                        }
 4533                    }))
 4534                } else {
 4535                    Some(Task::ready(Ok(())))
 4536                }
 4537            })?;
 4538            if let Some(task) = spawned_test_task {
 4539                task.await?;
 4540            }
 4541
 4542            Ok::<_, anyhow::Error>(())
 4543        })
 4544        .detach_and_log_err(cx);
 4545    }
 4546
 4547    pub fn confirm_code_action(
 4548        &mut self,
 4549        action: &ConfirmCodeAction,
 4550        cx: &mut ViewContext<Self>,
 4551    ) -> Option<Task<Result<()>>> {
 4552        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4553            menu
 4554        } else {
 4555            return None;
 4556        };
 4557        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4558        let action = actions_menu.actions.get(action_ix)?;
 4559        let title = action.label();
 4560        let buffer = actions_menu.buffer;
 4561        let workspace = self.workspace()?;
 4562
 4563        match action {
 4564            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4565                workspace.update(cx, |workspace, cx| {
 4566                    workspace::tasks::schedule_resolved_task(
 4567                        workspace,
 4568                        task_source_kind,
 4569                        resolved_task,
 4570                        false,
 4571                        cx,
 4572                    );
 4573
 4574                    Some(Task::ready(Ok(())))
 4575                })
 4576            }
 4577            CodeActionsItem::CodeAction(action) => {
 4578                let apply_code_actions = workspace
 4579                    .read(cx)
 4580                    .project()
 4581                    .clone()
 4582                    .update(cx, |project, cx| {
 4583                        project.apply_code_action(buffer, action, true, cx)
 4584                    });
 4585                let workspace = workspace.downgrade();
 4586                Some(cx.spawn(|editor, cx| async move {
 4587                    let project_transaction = apply_code_actions.await?;
 4588                    Self::open_project_transaction(
 4589                        &editor,
 4590                        workspace,
 4591                        project_transaction,
 4592                        title,
 4593                        cx,
 4594                    )
 4595                    .await
 4596                }))
 4597            }
 4598        }
 4599    }
 4600
 4601    pub async fn open_project_transaction(
 4602        this: &WeakView<Editor>,
 4603        workspace: WeakView<Workspace>,
 4604        transaction: ProjectTransaction,
 4605        title: String,
 4606        mut cx: AsyncWindowContext,
 4607    ) -> Result<()> {
 4608        let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
 4609
 4610        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4611        cx.update(|cx| {
 4612            entries.sort_unstable_by_key(|(buffer, _)| {
 4613                buffer.read(cx).file().map(|f| f.path().clone())
 4614            });
 4615        })?;
 4616
 4617        // If the project transaction's edits are all contained within this editor, then
 4618        // avoid opening a new editor to display them.
 4619
 4620        if let Some((buffer, transaction)) = entries.first() {
 4621            if entries.len() == 1 {
 4622                let excerpt = this.update(&mut cx, |editor, cx| {
 4623                    editor
 4624                        .buffer()
 4625                        .read(cx)
 4626                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4627                })?;
 4628                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4629                    if excerpted_buffer == *buffer {
 4630                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4631                            let excerpt_range = excerpt_range.to_offset(buffer);
 4632                            buffer
 4633                                .edited_ranges_for_transaction::<usize>(transaction)
 4634                                .all(|range| {
 4635                                    excerpt_range.start <= range.start
 4636                                        && excerpt_range.end >= range.end
 4637                                })
 4638                        })?;
 4639
 4640                        if all_edits_within_excerpt {
 4641                            return Ok(());
 4642                        }
 4643                    }
 4644                }
 4645            }
 4646        } else {
 4647            return Ok(());
 4648        }
 4649
 4650        let mut ranges_to_highlight = Vec::new();
 4651        let excerpt_buffer = cx.new_model(|cx| {
 4652            let mut multibuffer =
 4653                MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
 4654            for (buffer_handle, transaction) in &entries {
 4655                let buffer = buffer_handle.read(cx);
 4656                ranges_to_highlight.extend(
 4657                    multibuffer.push_excerpts_with_context_lines(
 4658                        buffer_handle.clone(),
 4659                        buffer
 4660                            .edited_ranges_for_transaction::<usize>(transaction)
 4661                            .collect(),
 4662                        DEFAULT_MULTIBUFFER_CONTEXT,
 4663                        cx,
 4664                    ),
 4665                );
 4666            }
 4667            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4668            multibuffer
 4669        })?;
 4670
 4671        workspace.update(&mut cx, |workspace, cx| {
 4672            let project = workspace.project().clone();
 4673            let editor =
 4674                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4675            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4676            editor.update(cx, |editor, cx| {
 4677                editor.highlight_background::<Self>(
 4678                    &ranges_to_highlight,
 4679                    |theme| theme.editor_highlighted_line_background,
 4680                    cx,
 4681                );
 4682            });
 4683        })?;
 4684
 4685        Ok(())
 4686    }
 4687
 4688    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4689        let project = self.project.clone()?;
 4690        let buffer = self.buffer.read(cx);
 4691        let newest_selection = self.selections.newest_anchor().clone();
 4692        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4693        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4694        if start_buffer != end_buffer {
 4695            return None;
 4696        }
 4697
 4698        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4699            cx.background_executor()
 4700                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4701                .await;
 4702
 4703            let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
 4704                project.code_actions(&start_buffer, start..end, cx)
 4705            }) {
 4706                code_actions.await
 4707            } else {
 4708                Vec::new()
 4709            };
 4710
 4711            this.update(&mut cx, |this, cx| {
 4712                this.available_code_actions = if actions.is_empty() {
 4713                    None
 4714                } else {
 4715                    Some((
 4716                        Location {
 4717                            buffer: start_buffer,
 4718                            range: start..end,
 4719                        },
 4720                        actions.into(),
 4721                    ))
 4722                };
 4723                cx.notify();
 4724            })
 4725            .log_err();
 4726        }));
 4727        None
 4728    }
 4729
 4730    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4731        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4732            self.show_git_blame_inline = false;
 4733
 4734            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4735                cx.background_executor().timer(delay).await;
 4736
 4737                this.update(&mut cx, |this, cx| {
 4738                    this.show_git_blame_inline = true;
 4739                    cx.notify();
 4740                })
 4741                .log_err();
 4742            }));
 4743        }
 4744    }
 4745
 4746    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4747        if self.pending_rename.is_some() {
 4748            return None;
 4749        }
 4750
 4751        let project = self.project.clone()?;
 4752        let buffer = self.buffer.read(cx);
 4753        let newest_selection = self.selections.newest_anchor().clone();
 4754        let cursor_position = newest_selection.head();
 4755        let (cursor_buffer, cursor_buffer_position) =
 4756            buffer.text_anchor_for_position(cursor_position, cx)?;
 4757        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4758        if cursor_buffer != tail_buffer {
 4759            return None;
 4760        }
 4761
 4762        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4763            cx.background_executor()
 4764                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 4765                .await;
 4766
 4767            let highlights = if let Some(highlights) = project
 4768                .update(&mut cx, |project, cx| {
 4769                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4770                })
 4771                .log_err()
 4772            {
 4773                highlights.await.log_err()
 4774            } else {
 4775                None
 4776            };
 4777
 4778            if let Some(highlights) = highlights {
 4779                this.update(&mut cx, |this, cx| {
 4780                    if this.pending_rename.is_some() {
 4781                        return;
 4782                    }
 4783
 4784                    let buffer_id = cursor_position.buffer_id;
 4785                    let buffer = this.buffer.read(cx);
 4786                    if !buffer
 4787                        .text_anchor_for_position(cursor_position, cx)
 4788                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4789                    {
 4790                        return;
 4791                    }
 4792
 4793                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4794                    let mut write_ranges = Vec::new();
 4795                    let mut read_ranges = Vec::new();
 4796                    for highlight in highlights {
 4797                        for (excerpt_id, excerpt_range) in
 4798                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4799                        {
 4800                            let start = highlight
 4801                                .range
 4802                                .start
 4803                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4804                            let end = highlight
 4805                                .range
 4806                                .end
 4807                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4808                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4809                                continue;
 4810                            }
 4811
 4812                            let range = Anchor {
 4813                                buffer_id,
 4814                                excerpt_id: excerpt_id,
 4815                                text_anchor: start,
 4816                            }..Anchor {
 4817                                buffer_id,
 4818                                excerpt_id,
 4819                                text_anchor: end,
 4820                            };
 4821                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4822                                write_ranges.push(range);
 4823                            } else {
 4824                                read_ranges.push(range);
 4825                            }
 4826                        }
 4827                    }
 4828
 4829                    this.highlight_background::<DocumentHighlightRead>(
 4830                        &read_ranges,
 4831                        |theme| theme.editor_document_highlight_read_background,
 4832                        cx,
 4833                    );
 4834                    this.highlight_background::<DocumentHighlightWrite>(
 4835                        &write_ranges,
 4836                        |theme| theme.editor_document_highlight_write_background,
 4837                        cx,
 4838                    );
 4839                    cx.notify();
 4840                })
 4841                .log_err();
 4842            }
 4843        }));
 4844        None
 4845    }
 4846
 4847    fn refresh_inline_completion(
 4848        &mut self,
 4849        debounce: bool,
 4850        cx: &mut ViewContext<Self>,
 4851    ) -> Option<()> {
 4852        let provider = self.inline_completion_provider()?;
 4853        let cursor = self.selections.newest_anchor().head();
 4854        let (buffer, cursor_buffer_position) =
 4855            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4856        if !self.show_inline_completions
 4857            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4858        {
 4859            self.discard_inline_completion(false, cx);
 4860            return None;
 4861        }
 4862
 4863        self.update_visible_inline_completion(cx);
 4864        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4865        Some(())
 4866    }
 4867
 4868    fn cycle_inline_completion(
 4869        &mut self,
 4870        direction: Direction,
 4871        cx: &mut ViewContext<Self>,
 4872    ) -> Option<()> {
 4873        let provider = self.inline_completion_provider()?;
 4874        let cursor = self.selections.newest_anchor().head();
 4875        let (buffer, cursor_buffer_position) =
 4876            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4877        if !self.show_inline_completions
 4878            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4879        {
 4880            return None;
 4881        }
 4882
 4883        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4884        self.update_visible_inline_completion(cx);
 4885
 4886        Some(())
 4887    }
 4888
 4889    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4890        if !self.has_active_inline_completion(cx) {
 4891            self.refresh_inline_completion(false, cx);
 4892            return;
 4893        }
 4894
 4895        self.update_visible_inline_completion(cx);
 4896    }
 4897
 4898    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4899        self.show_cursor_names(cx);
 4900    }
 4901
 4902    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4903        self.show_cursor_names = true;
 4904        cx.notify();
 4905        cx.spawn(|this, mut cx| async move {
 4906            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4907            this.update(&mut cx, |this, cx| {
 4908                this.show_cursor_names = false;
 4909                cx.notify()
 4910            })
 4911            .ok()
 4912        })
 4913        .detach();
 4914    }
 4915
 4916    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4917        if self.has_active_inline_completion(cx) {
 4918            self.cycle_inline_completion(Direction::Next, cx);
 4919        } else {
 4920            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4921            if is_copilot_disabled {
 4922                cx.propagate();
 4923            }
 4924        }
 4925    }
 4926
 4927    pub fn previous_inline_completion(
 4928        &mut self,
 4929        _: &PreviousInlineCompletion,
 4930        cx: &mut ViewContext<Self>,
 4931    ) {
 4932        if self.has_active_inline_completion(cx) {
 4933            self.cycle_inline_completion(Direction::Prev, cx);
 4934        } else {
 4935            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4936            if is_copilot_disabled {
 4937                cx.propagate();
 4938            }
 4939        }
 4940    }
 4941
 4942    pub fn accept_inline_completion(
 4943        &mut self,
 4944        _: &AcceptInlineCompletion,
 4945        cx: &mut ViewContext<Self>,
 4946    ) {
 4947        let Some(completion) = self.take_active_inline_completion(cx) else {
 4948            return;
 4949        };
 4950        if let Some(provider) = self.inline_completion_provider() {
 4951            provider.accept(cx);
 4952        }
 4953
 4954        cx.emit(EditorEvent::InputHandled {
 4955            utf16_range_to_replace: None,
 4956            text: completion.text.to_string().into(),
 4957        });
 4958        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 4959        self.refresh_inline_completion(true, cx);
 4960        cx.notify();
 4961    }
 4962
 4963    pub fn accept_partial_inline_completion(
 4964        &mut self,
 4965        _: &AcceptPartialInlineCompletion,
 4966        cx: &mut ViewContext<Self>,
 4967    ) {
 4968        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 4969            if let Some(completion) = self.take_active_inline_completion(cx) {
 4970                let mut partial_completion = completion
 4971                    .text
 4972                    .chars()
 4973                    .by_ref()
 4974                    .take_while(|c| c.is_alphabetic())
 4975                    .collect::<String>();
 4976                if partial_completion.is_empty() {
 4977                    partial_completion = completion
 4978                        .text
 4979                        .chars()
 4980                        .by_ref()
 4981                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4982                        .collect::<String>();
 4983                }
 4984
 4985                cx.emit(EditorEvent::InputHandled {
 4986                    utf16_range_to_replace: None,
 4987                    text: partial_completion.clone().into(),
 4988                });
 4989                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4990                self.refresh_inline_completion(true, cx);
 4991                cx.notify();
 4992            }
 4993        }
 4994    }
 4995
 4996    fn discard_inline_completion(
 4997        &mut self,
 4998        should_report_inline_completion_event: bool,
 4999        cx: &mut ViewContext<Self>,
 5000    ) -> bool {
 5001        if let Some(provider) = self.inline_completion_provider() {
 5002            provider.discard(should_report_inline_completion_event, cx);
 5003        }
 5004
 5005        self.take_active_inline_completion(cx).is_some()
 5006    }
 5007
 5008    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5009        if let Some(completion) = self.active_inline_completion.as_ref() {
 5010            let buffer = self.buffer.read(cx).read(cx);
 5011            completion.position.is_valid(&buffer)
 5012        } else {
 5013            false
 5014        }
 5015    }
 5016
 5017    fn take_active_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
 5018        let completion = self.active_inline_completion.take()?;
 5019        self.display_map.update(cx, |map, cx| {
 5020            map.splice_inlays(vec![completion.id], Default::default(), cx);
 5021        });
 5022        let buffer = self.buffer.read(cx).read(cx);
 5023
 5024        if completion.position.is_valid(&buffer) {
 5025            Some(completion)
 5026        } else {
 5027            None
 5028        }
 5029    }
 5030
 5031    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5032        let selection = self.selections.newest_anchor();
 5033        let cursor = selection.head();
 5034
 5035        if self.context_menu.read().is_none()
 5036            && self.completion_tasks.is_empty()
 5037            && selection.start == selection.end
 5038        {
 5039            if let Some(provider) = self.inline_completion_provider() {
 5040                if let Some((buffer, cursor_buffer_position)) =
 5041                    self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 5042                {
 5043                    if let Some(text) =
 5044                        provider.active_completion_text(&buffer, cursor_buffer_position, cx)
 5045                    {
 5046                        let text = Rope::from(text);
 5047                        let mut to_remove = Vec::new();
 5048                        if let Some(completion) = self.active_inline_completion.take() {
 5049                            to_remove.push(completion.id);
 5050                        }
 5051
 5052                        let completion_inlay =
 5053                            Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
 5054                        self.active_inline_completion = Some(completion_inlay.clone());
 5055                        self.display_map.update(cx, move |map, cx| {
 5056                            map.splice_inlays(to_remove, vec![completion_inlay], cx)
 5057                        });
 5058                        cx.notify();
 5059                        return;
 5060                    }
 5061                }
 5062            }
 5063        }
 5064
 5065        self.discard_inline_completion(false, cx);
 5066    }
 5067
 5068    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5069        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5070    }
 5071
 5072    fn render_code_actions_indicator(
 5073        &self,
 5074        _style: &EditorStyle,
 5075        row: DisplayRow,
 5076        is_active: bool,
 5077        cx: &mut ViewContext<Self>,
 5078    ) -> Option<IconButton> {
 5079        if self.available_code_actions.is_some() {
 5080            Some(
 5081                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5082                    .shape(ui::IconButtonShape::Square)
 5083                    .icon_size(IconSize::XSmall)
 5084                    .icon_color(Color::Muted)
 5085                    .selected(is_active)
 5086                    .on_click(cx.listener(move |editor, _e, cx| {
 5087                        editor.focus(cx);
 5088                        editor.toggle_code_actions(
 5089                            &ToggleCodeActions {
 5090                                deployed_from_indicator: Some(row),
 5091                            },
 5092                            cx,
 5093                        );
 5094                    })),
 5095            )
 5096        } else {
 5097            None
 5098        }
 5099    }
 5100
 5101    fn clear_tasks(&mut self) {
 5102        self.tasks.clear()
 5103    }
 5104
 5105    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5106        if let Some(_) = self.tasks.insert(key, value) {
 5107            // This case should hopefully be rare, but just in case...
 5108            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5109        }
 5110    }
 5111
 5112    fn render_run_indicator(
 5113        &self,
 5114        _style: &EditorStyle,
 5115        is_active: bool,
 5116        row: DisplayRow,
 5117        cx: &mut ViewContext<Self>,
 5118    ) -> IconButton {
 5119        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5120            .shape(ui::IconButtonShape::Square)
 5121            .icon_size(IconSize::XSmall)
 5122            .icon_color(Color::Muted)
 5123            .selected(is_active)
 5124            .on_click(cx.listener(move |editor, _e, cx| {
 5125                editor.focus(cx);
 5126                editor.toggle_code_actions(
 5127                    &ToggleCodeActions {
 5128                        deployed_from_indicator: Some(row),
 5129                    },
 5130                    cx,
 5131                );
 5132            }))
 5133    }
 5134
 5135    fn render_close_hunk_diff_button(
 5136        &self,
 5137        hunk: HoveredHunk,
 5138        row: DisplayRow,
 5139        cx: &mut ViewContext<Self>,
 5140    ) -> IconButton {
 5141        IconButton::new(
 5142            ("close_hunk_diff_indicator", row.0 as usize),
 5143            ui::IconName::Close,
 5144        )
 5145        .shape(ui::IconButtonShape::Square)
 5146        .icon_size(IconSize::XSmall)
 5147        .icon_color(Color::Muted)
 5148        .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
 5149        .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
 5150    }
 5151
 5152    pub fn context_menu_visible(&self) -> bool {
 5153        self.context_menu
 5154            .read()
 5155            .as_ref()
 5156            .map_or(false, |menu| menu.visible())
 5157    }
 5158
 5159    fn render_context_menu(
 5160        &self,
 5161        cursor_position: DisplayPoint,
 5162        style: &EditorStyle,
 5163        max_height: Pixels,
 5164        cx: &mut ViewContext<Editor>,
 5165    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5166        self.context_menu.read().as_ref().map(|menu| {
 5167            menu.render(
 5168                cursor_position,
 5169                style,
 5170                max_height,
 5171                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5172                cx,
 5173            )
 5174        })
 5175    }
 5176
 5177    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5178        cx.notify();
 5179        self.completion_tasks.clear();
 5180        let context_menu = self.context_menu.write().take();
 5181        if context_menu.is_some() {
 5182            self.update_visible_inline_completion(cx);
 5183        }
 5184        context_menu
 5185    }
 5186
 5187    pub fn insert_snippet(
 5188        &mut self,
 5189        insertion_ranges: &[Range<usize>],
 5190        snippet: Snippet,
 5191        cx: &mut ViewContext<Self>,
 5192    ) -> Result<()> {
 5193        struct Tabstop<T> {
 5194            is_end_tabstop: bool,
 5195            ranges: Vec<Range<T>>,
 5196        }
 5197
 5198        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5199            let snippet_text: Arc<str> = snippet.text.clone().into();
 5200            buffer.edit(
 5201                insertion_ranges
 5202                    .iter()
 5203                    .cloned()
 5204                    .map(|range| (range, snippet_text.clone())),
 5205                Some(AutoindentMode::EachLine),
 5206                cx,
 5207            );
 5208
 5209            let snapshot = &*buffer.read(cx);
 5210            let snippet = &snippet;
 5211            snippet
 5212                .tabstops
 5213                .iter()
 5214                .map(|tabstop| {
 5215                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5216                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5217                    });
 5218                    let mut tabstop_ranges = tabstop
 5219                        .iter()
 5220                        .flat_map(|tabstop_range| {
 5221                            let mut delta = 0_isize;
 5222                            insertion_ranges.iter().map(move |insertion_range| {
 5223                                let insertion_start = insertion_range.start as isize + delta;
 5224                                delta +=
 5225                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5226
 5227                                let start = ((insertion_start + tabstop_range.start) as usize)
 5228                                    .min(snapshot.len());
 5229                                let end = ((insertion_start + tabstop_range.end) as usize)
 5230                                    .min(snapshot.len());
 5231                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5232                            })
 5233                        })
 5234                        .collect::<Vec<_>>();
 5235                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5236
 5237                    Tabstop {
 5238                        is_end_tabstop,
 5239                        ranges: tabstop_ranges,
 5240                    }
 5241                })
 5242                .collect::<Vec<_>>()
 5243        });
 5244        if let Some(tabstop) = tabstops.first() {
 5245            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5246                s.select_ranges(tabstop.ranges.iter().cloned());
 5247            });
 5248
 5249            // If we're already at the last tabstop and it's at the end of the snippet,
 5250            // we're done, we don't need to keep the state around.
 5251            if !tabstop.is_end_tabstop {
 5252                let ranges = tabstops
 5253                    .into_iter()
 5254                    .map(|tabstop| tabstop.ranges)
 5255                    .collect::<Vec<_>>();
 5256                self.snippet_stack.push(SnippetState {
 5257                    active_index: 0,
 5258                    ranges,
 5259                });
 5260            }
 5261
 5262            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5263            if self.autoclose_regions.is_empty() {
 5264                let snapshot = self.buffer.read(cx).snapshot(cx);
 5265                for selection in &mut self.selections.all::<Point>(cx) {
 5266                    let selection_head = selection.head();
 5267                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5268                        continue;
 5269                    };
 5270
 5271                    let mut bracket_pair = None;
 5272                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5273                    let prev_chars = snapshot
 5274                        .reversed_chars_at(selection_head)
 5275                        .collect::<String>();
 5276                    for (pair, enabled) in scope.brackets() {
 5277                        if enabled
 5278                            && pair.close
 5279                            && prev_chars.starts_with(pair.start.as_str())
 5280                            && next_chars.starts_with(pair.end.as_str())
 5281                        {
 5282                            bracket_pair = Some(pair.clone());
 5283                            break;
 5284                        }
 5285                    }
 5286                    if let Some(pair) = bracket_pair {
 5287                        let start = snapshot.anchor_after(selection_head);
 5288                        let end = snapshot.anchor_after(selection_head);
 5289                        self.autoclose_regions.push(AutocloseRegion {
 5290                            selection_id: selection.id,
 5291                            range: start..end,
 5292                            pair,
 5293                        });
 5294                    }
 5295                }
 5296            }
 5297        }
 5298        Ok(())
 5299    }
 5300
 5301    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5302        self.move_to_snippet_tabstop(Bias::Right, cx)
 5303    }
 5304
 5305    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5306        self.move_to_snippet_tabstop(Bias::Left, cx)
 5307    }
 5308
 5309    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5310        if let Some(mut snippet) = self.snippet_stack.pop() {
 5311            match bias {
 5312                Bias::Left => {
 5313                    if snippet.active_index > 0 {
 5314                        snippet.active_index -= 1;
 5315                    } else {
 5316                        self.snippet_stack.push(snippet);
 5317                        return false;
 5318                    }
 5319                }
 5320                Bias::Right => {
 5321                    if snippet.active_index + 1 < snippet.ranges.len() {
 5322                        snippet.active_index += 1;
 5323                    } else {
 5324                        self.snippet_stack.push(snippet);
 5325                        return false;
 5326                    }
 5327                }
 5328            }
 5329            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5330                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5331                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5332                });
 5333                // If snippet state is not at the last tabstop, push it back on the stack
 5334                if snippet.active_index + 1 < snippet.ranges.len() {
 5335                    self.snippet_stack.push(snippet);
 5336                }
 5337                return true;
 5338            }
 5339        }
 5340
 5341        false
 5342    }
 5343
 5344    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5345        self.transact(cx, |this, cx| {
 5346            this.select_all(&SelectAll, cx);
 5347            this.insert("", cx);
 5348        });
 5349    }
 5350
 5351    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5352        self.transact(cx, |this, cx| {
 5353            this.select_autoclose_pair(cx);
 5354            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5355            if !this.linked_edit_ranges.is_empty() {
 5356                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5357                let snapshot = this.buffer.read(cx).snapshot(cx);
 5358
 5359                for selection in selections.iter() {
 5360                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5361                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5362                    if selection_start.buffer_id != selection_end.buffer_id {
 5363                        continue;
 5364                    }
 5365                    if let Some(ranges) =
 5366                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5367                    {
 5368                        for (buffer, entries) in ranges {
 5369                            linked_ranges.entry(buffer).or_default().extend(entries);
 5370                        }
 5371                    }
 5372                }
 5373            }
 5374
 5375            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5376            if !this.selections.line_mode {
 5377                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5378                for selection in &mut selections {
 5379                    if selection.is_empty() {
 5380                        let old_head = selection.head();
 5381                        let mut new_head =
 5382                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5383                                .to_point(&display_map);
 5384                        if let Some((buffer, line_buffer_range)) = display_map
 5385                            .buffer_snapshot
 5386                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5387                        {
 5388                            let indent_size =
 5389                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5390                            let indent_len = match indent_size.kind {
 5391                                IndentKind::Space => {
 5392                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5393                                }
 5394                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5395                            };
 5396                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5397                                let indent_len = indent_len.get();
 5398                                new_head = cmp::min(
 5399                                    new_head,
 5400                                    MultiBufferPoint::new(
 5401                                        old_head.row,
 5402                                        ((old_head.column - 1) / indent_len) * indent_len,
 5403                                    ),
 5404                                );
 5405                            }
 5406                        }
 5407
 5408                        selection.set_head(new_head, SelectionGoal::None);
 5409                    }
 5410                }
 5411            }
 5412
 5413            this.signature_help_state.set_backspace_pressed(true);
 5414            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5415            this.insert("", cx);
 5416            let empty_str: Arc<str> = Arc::from("");
 5417            for (buffer, edits) in linked_ranges {
 5418                let snapshot = buffer.read(cx).snapshot();
 5419                use text::ToPoint as TP;
 5420
 5421                let edits = edits
 5422                    .into_iter()
 5423                    .map(|range| {
 5424                        let end_point = TP::to_point(&range.end, &snapshot);
 5425                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5426
 5427                        if end_point == start_point {
 5428                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5429                                .saturating_sub(1);
 5430                            start_point = TP::to_point(&offset, &snapshot);
 5431                        };
 5432
 5433                        (start_point..end_point, empty_str.clone())
 5434                    })
 5435                    .sorted_by_key(|(range, _)| range.start)
 5436                    .collect::<Vec<_>>();
 5437                buffer.update(cx, |this, cx| {
 5438                    this.edit(edits, None, cx);
 5439                })
 5440            }
 5441            this.refresh_inline_completion(true, cx);
 5442            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5443        });
 5444    }
 5445
 5446    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5447        self.transact(cx, |this, cx| {
 5448            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5449                let line_mode = s.line_mode;
 5450                s.move_with(|map, selection| {
 5451                    if selection.is_empty() && !line_mode {
 5452                        let cursor = movement::right(map, selection.head());
 5453                        selection.end = cursor;
 5454                        selection.reversed = true;
 5455                        selection.goal = SelectionGoal::None;
 5456                    }
 5457                })
 5458            });
 5459            this.insert("", cx);
 5460            this.refresh_inline_completion(true, cx);
 5461        });
 5462    }
 5463
 5464    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5465        if self.move_to_prev_snippet_tabstop(cx) {
 5466            return;
 5467        }
 5468
 5469        self.outdent(&Outdent, cx);
 5470    }
 5471
 5472    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5473        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5474            return;
 5475        }
 5476
 5477        let mut selections = self.selections.all_adjusted(cx);
 5478        let buffer = self.buffer.read(cx);
 5479        let snapshot = buffer.snapshot(cx);
 5480        let rows_iter = selections.iter().map(|s| s.head().row);
 5481        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5482
 5483        let mut edits = Vec::new();
 5484        let mut prev_edited_row = 0;
 5485        let mut row_delta = 0;
 5486        for selection in &mut selections {
 5487            if selection.start.row != prev_edited_row {
 5488                row_delta = 0;
 5489            }
 5490            prev_edited_row = selection.end.row;
 5491
 5492            // If the selection is non-empty, then increase the indentation of the selected lines.
 5493            if !selection.is_empty() {
 5494                row_delta =
 5495                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5496                continue;
 5497            }
 5498
 5499            // If the selection is empty and the cursor is in the leading whitespace before the
 5500            // suggested indentation, then auto-indent the line.
 5501            let cursor = selection.head();
 5502            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5503            if let Some(suggested_indent) =
 5504                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5505            {
 5506                if cursor.column < suggested_indent.len
 5507                    && cursor.column <= current_indent.len
 5508                    && current_indent.len <= suggested_indent.len
 5509                {
 5510                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5511                    selection.end = selection.start;
 5512                    if row_delta == 0 {
 5513                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5514                            cursor.row,
 5515                            current_indent,
 5516                            suggested_indent,
 5517                        ));
 5518                        row_delta = suggested_indent.len - current_indent.len;
 5519                    }
 5520                    continue;
 5521                }
 5522            }
 5523
 5524            // Otherwise, insert a hard or soft tab.
 5525            let settings = buffer.settings_at(cursor, cx);
 5526            let tab_size = if settings.hard_tabs {
 5527                IndentSize::tab()
 5528            } else {
 5529                let tab_size = settings.tab_size.get();
 5530                let char_column = snapshot
 5531                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5532                    .flat_map(str::chars)
 5533                    .count()
 5534                    + row_delta as usize;
 5535                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5536                IndentSize::spaces(chars_to_next_tab_stop)
 5537            };
 5538            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5539            selection.end = selection.start;
 5540            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5541            row_delta += tab_size.len;
 5542        }
 5543
 5544        self.transact(cx, |this, cx| {
 5545            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5546            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5547            this.refresh_inline_completion(true, cx);
 5548        });
 5549    }
 5550
 5551    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5552        if self.read_only(cx) {
 5553            return;
 5554        }
 5555        let mut selections = self.selections.all::<Point>(cx);
 5556        let mut prev_edited_row = 0;
 5557        let mut row_delta = 0;
 5558        let mut edits = Vec::new();
 5559        let buffer = self.buffer.read(cx);
 5560        let snapshot = buffer.snapshot(cx);
 5561        for selection in &mut selections {
 5562            if selection.start.row != prev_edited_row {
 5563                row_delta = 0;
 5564            }
 5565            prev_edited_row = selection.end.row;
 5566
 5567            row_delta =
 5568                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5569        }
 5570
 5571        self.transact(cx, |this, cx| {
 5572            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5573            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5574        });
 5575    }
 5576
 5577    fn indent_selection(
 5578        buffer: &MultiBuffer,
 5579        snapshot: &MultiBufferSnapshot,
 5580        selection: &mut Selection<Point>,
 5581        edits: &mut Vec<(Range<Point>, String)>,
 5582        delta_for_start_row: u32,
 5583        cx: &AppContext,
 5584    ) -> u32 {
 5585        let settings = buffer.settings_at(selection.start, cx);
 5586        let tab_size = settings.tab_size.get();
 5587        let indent_kind = if settings.hard_tabs {
 5588            IndentKind::Tab
 5589        } else {
 5590            IndentKind::Space
 5591        };
 5592        let mut start_row = selection.start.row;
 5593        let mut end_row = selection.end.row + 1;
 5594
 5595        // If a selection ends at the beginning of a line, don't indent
 5596        // that last line.
 5597        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5598            end_row -= 1;
 5599        }
 5600
 5601        // Avoid re-indenting a row that has already been indented by a
 5602        // previous selection, but still update this selection's column
 5603        // to reflect that indentation.
 5604        if delta_for_start_row > 0 {
 5605            start_row += 1;
 5606            selection.start.column += delta_for_start_row;
 5607            if selection.end.row == selection.start.row {
 5608                selection.end.column += delta_for_start_row;
 5609            }
 5610        }
 5611
 5612        let mut delta_for_end_row = 0;
 5613        let has_multiple_rows = start_row + 1 != end_row;
 5614        for row in start_row..end_row {
 5615            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5616            let indent_delta = match (current_indent.kind, indent_kind) {
 5617                (IndentKind::Space, IndentKind::Space) => {
 5618                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5619                    IndentSize::spaces(columns_to_next_tab_stop)
 5620                }
 5621                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5622                (_, IndentKind::Tab) => IndentSize::tab(),
 5623            };
 5624
 5625            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5626                0
 5627            } else {
 5628                selection.start.column
 5629            };
 5630            let row_start = Point::new(row, start);
 5631            edits.push((
 5632                row_start..row_start,
 5633                indent_delta.chars().collect::<String>(),
 5634            ));
 5635
 5636            // Update this selection's endpoints to reflect the indentation.
 5637            if row == selection.start.row {
 5638                selection.start.column += indent_delta.len;
 5639            }
 5640            if row == selection.end.row {
 5641                selection.end.column += indent_delta.len;
 5642                delta_for_end_row = indent_delta.len;
 5643            }
 5644        }
 5645
 5646        if selection.start.row == selection.end.row {
 5647            delta_for_start_row + delta_for_end_row
 5648        } else {
 5649            delta_for_end_row
 5650        }
 5651    }
 5652
 5653    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5654        if self.read_only(cx) {
 5655            return;
 5656        }
 5657        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5658        let selections = self.selections.all::<Point>(cx);
 5659        let mut deletion_ranges = Vec::new();
 5660        let mut last_outdent = None;
 5661        {
 5662            let buffer = self.buffer.read(cx);
 5663            let snapshot = buffer.snapshot(cx);
 5664            for selection in &selections {
 5665                let settings = buffer.settings_at(selection.start, cx);
 5666                let tab_size = settings.tab_size.get();
 5667                let mut rows = selection.spanned_rows(false, &display_map);
 5668
 5669                // Avoid re-outdenting a row that has already been outdented by a
 5670                // previous selection.
 5671                if let Some(last_row) = last_outdent {
 5672                    if last_row == rows.start {
 5673                        rows.start = rows.start.next_row();
 5674                    }
 5675                }
 5676                let has_multiple_rows = rows.len() > 1;
 5677                for row in rows.iter_rows() {
 5678                    let indent_size = snapshot.indent_size_for_line(row);
 5679                    if indent_size.len > 0 {
 5680                        let deletion_len = match indent_size.kind {
 5681                            IndentKind::Space => {
 5682                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5683                                if columns_to_prev_tab_stop == 0 {
 5684                                    tab_size
 5685                                } else {
 5686                                    columns_to_prev_tab_stop
 5687                                }
 5688                            }
 5689                            IndentKind::Tab => 1,
 5690                        };
 5691                        let start = if has_multiple_rows
 5692                            || deletion_len > selection.start.column
 5693                            || indent_size.len < selection.start.column
 5694                        {
 5695                            0
 5696                        } else {
 5697                            selection.start.column - deletion_len
 5698                        };
 5699                        deletion_ranges.push(
 5700                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5701                        );
 5702                        last_outdent = Some(row);
 5703                    }
 5704                }
 5705            }
 5706        }
 5707
 5708        self.transact(cx, |this, cx| {
 5709            this.buffer.update(cx, |buffer, cx| {
 5710                let empty_str: Arc<str> = "".into();
 5711                buffer.edit(
 5712                    deletion_ranges
 5713                        .into_iter()
 5714                        .map(|range| (range, empty_str.clone())),
 5715                    None,
 5716                    cx,
 5717                );
 5718            });
 5719            let selections = this.selections.all::<usize>(cx);
 5720            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5721        });
 5722    }
 5723
 5724    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5725        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5726        let selections = self.selections.all::<Point>(cx);
 5727
 5728        let mut new_cursors = Vec::new();
 5729        let mut edit_ranges = Vec::new();
 5730        let mut selections = selections.iter().peekable();
 5731        while let Some(selection) = selections.next() {
 5732            let mut rows = selection.spanned_rows(false, &display_map);
 5733            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5734
 5735            // Accumulate contiguous regions of rows that we want to delete.
 5736            while let Some(next_selection) = selections.peek() {
 5737                let next_rows = next_selection.spanned_rows(false, &display_map);
 5738                if next_rows.start <= rows.end {
 5739                    rows.end = next_rows.end;
 5740                    selections.next().unwrap();
 5741                } else {
 5742                    break;
 5743                }
 5744            }
 5745
 5746            let buffer = &display_map.buffer_snapshot;
 5747            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5748            let edit_end;
 5749            let cursor_buffer_row;
 5750            if buffer.max_point().row >= rows.end.0 {
 5751                // If there's a line after the range, delete the \n from the end of the row range
 5752                // and position the cursor on the next line.
 5753                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5754                cursor_buffer_row = rows.end;
 5755            } else {
 5756                // If there isn't a line after the range, delete the \n from the line before the
 5757                // start of the row range and position the cursor there.
 5758                edit_start = edit_start.saturating_sub(1);
 5759                edit_end = buffer.len();
 5760                cursor_buffer_row = rows.start.previous_row();
 5761            }
 5762
 5763            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5764            *cursor.column_mut() =
 5765                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5766
 5767            new_cursors.push((
 5768                selection.id,
 5769                buffer.anchor_after(cursor.to_point(&display_map)),
 5770            ));
 5771            edit_ranges.push(edit_start..edit_end);
 5772        }
 5773
 5774        self.transact(cx, |this, cx| {
 5775            let buffer = this.buffer.update(cx, |buffer, cx| {
 5776                let empty_str: Arc<str> = "".into();
 5777                buffer.edit(
 5778                    edit_ranges
 5779                        .into_iter()
 5780                        .map(|range| (range, empty_str.clone())),
 5781                    None,
 5782                    cx,
 5783                );
 5784                buffer.snapshot(cx)
 5785            });
 5786            let new_selections = new_cursors
 5787                .into_iter()
 5788                .map(|(id, cursor)| {
 5789                    let cursor = cursor.to_point(&buffer);
 5790                    Selection {
 5791                        id,
 5792                        start: cursor,
 5793                        end: cursor,
 5794                        reversed: false,
 5795                        goal: SelectionGoal::None,
 5796                    }
 5797                })
 5798                .collect();
 5799
 5800            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5801                s.select(new_selections);
 5802            });
 5803        });
 5804    }
 5805
 5806    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5807        if self.read_only(cx) {
 5808            return;
 5809        }
 5810        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5811        for selection in self.selections.all::<Point>(cx) {
 5812            let start = MultiBufferRow(selection.start.row);
 5813            let end = if selection.start.row == selection.end.row {
 5814                MultiBufferRow(selection.start.row + 1)
 5815            } else {
 5816                MultiBufferRow(selection.end.row)
 5817            };
 5818
 5819            if let Some(last_row_range) = row_ranges.last_mut() {
 5820                if start <= last_row_range.end {
 5821                    last_row_range.end = end;
 5822                    continue;
 5823                }
 5824            }
 5825            row_ranges.push(start..end);
 5826        }
 5827
 5828        let snapshot = self.buffer.read(cx).snapshot(cx);
 5829        let mut cursor_positions = Vec::new();
 5830        for row_range in &row_ranges {
 5831            let anchor = snapshot.anchor_before(Point::new(
 5832                row_range.end.previous_row().0,
 5833                snapshot.line_len(row_range.end.previous_row()),
 5834            ));
 5835            cursor_positions.push(anchor..anchor);
 5836        }
 5837
 5838        self.transact(cx, |this, cx| {
 5839            for row_range in row_ranges.into_iter().rev() {
 5840                for row in row_range.iter_rows().rev() {
 5841                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5842                    let next_line_row = row.next_row();
 5843                    let indent = snapshot.indent_size_for_line(next_line_row);
 5844                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5845
 5846                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5847                        " "
 5848                    } else {
 5849                        ""
 5850                    };
 5851
 5852                    this.buffer.update(cx, |buffer, cx| {
 5853                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5854                    });
 5855                }
 5856            }
 5857
 5858            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5859                s.select_anchor_ranges(cursor_positions)
 5860            });
 5861        });
 5862    }
 5863
 5864    pub fn sort_lines_case_sensitive(
 5865        &mut self,
 5866        _: &SortLinesCaseSensitive,
 5867        cx: &mut ViewContext<Self>,
 5868    ) {
 5869        self.manipulate_lines(cx, |lines| lines.sort())
 5870    }
 5871
 5872    pub fn sort_lines_case_insensitive(
 5873        &mut self,
 5874        _: &SortLinesCaseInsensitive,
 5875        cx: &mut ViewContext<Self>,
 5876    ) {
 5877        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5878    }
 5879
 5880    pub fn unique_lines_case_insensitive(
 5881        &mut self,
 5882        _: &UniqueLinesCaseInsensitive,
 5883        cx: &mut ViewContext<Self>,
 5884    ) {
 5885        self.manipulate_lines(cx, |lines| {
 5886            let mut seen = HashSet::default();
 5887            lines.retain(|line| seen.insert(line.to_lowercase()));
 5888        })
 5889    }
 5890
 5891    pub fn unique_lines_case_sensitive(
 5892        &mut self,
 5893        _: &UniqueLinesCaseSensitive,
 5894        cx: &mut ViewContext<Self>,
 5895    ) {
 5896        self.manipulate_lines(cx, |lines| {
 5897            let mut seen = HashSet::default();
 5898            lines.retain(|line| seen.insert(*line));
 5899        })
 5900    }
 5901
 5902    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5903        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 5904        if !revert_changes.is_empty() {
 5905            self.transact(cx, |editor, cx| {
 5906                editor.revert(revert_changes, cx);
 5907            });
 5908        }
 5909    }
 5910
 5911    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5912        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5913            let project_path = buffer.read(cx).project_path(cx)?;
 5914            let project = self.project.as_ref()?.read(cx);
 5915            let entry = project.entry_for_path(&project_path, cx)?;
 5916            let abs_path = project.absolute_path(&project_path, cx)?;
 5917            let parent = if entry.is_symlink {
 5918                abs_path.canonicalize().ok()?
 5919            } else {
 5920                abs_path
 5921            }
 5922            .parent()?
 5923            .to_path_buf();
 5924            Some(parent)
 5925        }) {
 5926            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5927        }
 5928    }
 5929
 5930    fn gather_revert_changes(
 5931        &mut self,
 5932        selections: &[Selection<Anchor>],
 5933        cx: &mut ViewContext<'_, Editor>,
 5934    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 5935        let mut revert_changes = HashMap::default();
 5936        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 5937        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 5938            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 5939        }
 5940        revert_changes
 5941    }
 5942
 5943    pub fn prepare_revert_change(
 5944        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 5945        multi_buffer: &Model<MultiBuffer>,
 5946        hunk: &DiffHunk<MultiBufferRow>,
 5947        cx: &AppContext,
 5948    ) -> Option<()> {
 5949        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 5950        let buffer = buffer.read(cx);
 5951        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 5952        let buffer_snapshot = buffer.snapshot();
 5953        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5954        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5955            probe
 5956                .0
 5957                .start
 5958                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5959                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5960        }) {
 5961            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 5962            Some(())
 5963        } else {
 5964            None
 5965        }
 5966    }
 5967
 5968    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5969        self.manipulate_lines(cx, |lines| lines.reverse())
 5970    }
 5971
 5972    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5973        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5974    }
 5975
 5976    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5977    where
 5978        Fn: FnMut(&mut Vec<&str>),
 5979    {
 5980        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5981        let buffer = self.buffer.read(cx).snapshot(cx);
 5982
 5983        let mut edits = Vec::new();
 5984
 5985        let selections = self.selections.all::<Point>(cx);
 5986        let mut selections = selections.iter().peekable();
 5987        let mut contiguous_row_selections = Vec::new();
 5988        let mut new_selections = Vec::new();
 5989        let mut added_lines = 0;
 5990        let mut removed_lines = 0;
 5991
 5992        while let Some(selection) = selections.next() {
 5993            let (start_row, end_row) = consume_contiguous_rows(
 5994                &mut contiguous_row_selections,
 5995                selection,
 5996                &display_map,
 5997                &mut selections,
 5998            );
 5999
 6000            let start_point = Point::new(start_row.0, 0);
 6001            let end_point = Point::new(
 6002                end_row.previous_row().0,
 6003                buffer.line_len(end_row.previous_row()),
 6004            );
 6005            let text = buffer
 6006                .text_for_range(start_point..end_point)
 6007                .collect::<String>();
 6008
 6009            let mut lines = text.split('\n').collect_vec();
 6010
 6011            let lines_before = lines.len();
 6012            callback(&mut lines);
 6013            let lines_after = lines.len();
 6014
 6015            edits.push((start_point..end_point, lines.join("\n")));
 6016
 6017            // Selections must change based on added and removed line count
 6018            let start_row =
 6019                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6020            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6021            new_selections.push(Selection {
 6022                id: selection.id,
 6023                start: start_row,
 6024                end: end_row,
 6025                goal: SelectionGoal::None,
 6026                reversed: selection.reversed,
 6027            });
 6028
 6029            if lines_after > lines_before {
 6030                added_lines += lines_after - lines_before;
 6031            } else if lines_before > lines_after {
 6032                removed_lines += lines_before - lines_after;
 6033            }
 6034        }
 6035
 6036        self.transact(cx, |this, cx| {
 6037            let buffer = this.buffer.update(cx, |buffer, cx| {
 6038                buffer.edit(edits, None, cx);
 6039                buffer.snapshot(cx)
 6040            });
 6041
 6042            // Recalculate offsets on newly edited buffer
 6043            let new_selections = new_selections
 6044                .iter()
 6045                .map(|s| {
 6046                    let start_point = Point::new(s.start.0, 0);
 6047                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6048                    Selection {
 6049                        id: s.id,
 6050                        start: buffer.point_to_offset(start_point),
 6051                        end: buffer.point_to_offset(end_point),
 6052                        goal: s.goal,
 6053                        reversed: s.reversed,
 6054                    }
 6055                })
 6056                .collect();
 6057
 6058            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6059                s.select(new_selections);
 6060            });
 6061
 6062            this.request_autoscroll(Autoscroll::fit(), cx);
 6063        });
 6064    }
 6065
 6066    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6067        self.manipulate_text(cx, |text| text.to_uppercase())
 6068    }
 6069
 6070    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6071        self.manipulate_text(cx, |text| text.to_lowercase())
 6072    }
 6073
 6074    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6075        self.manipulate_text(cx, |text| {
 6076            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6077            // https://github.com/rutrum/convert-case/issues/16
 6078            text.split('\n')
 6079                .map(|line| line.to_case(Case::Title))
 6080                .join("\n")
 6081        })
 6082    }
 6083
 6084    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6085        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6086    }
 6087
 6088    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6089        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6090    }
 6091
 6092    pub fn convert_to_upper_camel_case(
 6093        &mut self,
 6094        _: &ConvertToUpperCamelCase,
 6095        cx: &mut ViewContext<Self>,
 6096    ) {
 6097        self.manipulate_text(cx, |text| {
 6098            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6099            // https://github.com/rutrum/convert-case/issues/16
 6100            text.split('\n')
 6101                .map(|line| line.to_case(Case::UpperCamel))
 6102                .join("\n")
 6103        })
 6104    }
 6105
 6106    pub fn convert_to_lower_camel_case(
 6107        &mut self,
 6108        _: &ConvertToLowerCamelCase,
 6109        cx: &mut ViewContext<Self>,
 6110    ) {
 6111        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6112    }
 6113
 6114    pub fn convert_to_opposite_case(
 6115        &mut self,
 6116        _: &ConvertToOppositeCase,
 6117        cx: &mut ViewContext<Self>,
 6118    ) {
 6119        self.manipulate_text(cx, |text| {
 6120            text.chars()
 6121                .fold(String::with_capacity(text.len()), |mut t, c| {
 6122                    if c.is_uppercase() {
 6123                        t.extend(c.to_lowercase());
 6124                    } else {
 6125                        t.extend(c.to_uppercase());
 6126                    }
 6127                    t
 6128                })
 6129        })
 6130    }
 6131
 6132    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6133    where
 6134        Fn: FnMut(&str) -> String,
 6135    {
 6136        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6137        let buffer = self.buffer.read(cx).snapshot(cx);
 6138
 6139        let mut new_selections = Vec::new();
 6140        let mut edits = Vec::new();
 6141        let mut selection_adjustment = 0i32;
 6142
 6143        for selection in self.selections.all::<usize>(cx) {
 6144            let selection_is_empty = selection.is_empty();
 6145
 6146            let (start, end) = if selection_is_empty {
 6147                let word_range = movement::surrounding_word(
 6148                    &display_map,
 6149                    selection.start.to_display_point(&display_map),
 6150                );
 6151                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6152                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6153                (start, end)
 6154            } else {
 6155                (selection.start, selection.end)
 6156            };
 6157
 6158            let text = buffer.text_for_range(start..end).collect::<String>();
 6159            let old_length = text.len() as i32;
 6160            let text = callback(&text);
 6161
 6162            new_selections.push(Selection {
 6163                start: (start as i32 - selection_adjustment) as usize,
 6164                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6165                goal: SelectionGoal::None,
 6166                ..selection
 6167            });
 6168
 6169            selection_adjustment += old_length - text.len() as i32;
 6170
 6171            edits.push((start..end, text));
 6172        }
 6173
 6174        self.transact(cx, |this, cx| {
 6175            this.buffer.update(cx, |buffer, cx| {
 6176                buffer.edit(edits, None, cx);
 6177            });
 6178
 6179            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6180                s.select(new_selections);
 6181            });
 6182
 6183            this.request_autoscroll(Autoscroll::fit(), cx);
 6184        });
 6185    }
 6186
 6187    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6188        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6189        let buffer = &display_map.buffer_snapshot;
 6190        let selections = self.selections.all::<Point>(cx);
 6191
 6192        let mut edits = Vec::new();
 6193        let mut selections_iter = selections.iter().peekable();
 6194        while let Some(selection) = selections_iter.next() {
 6195            // Avoid duplicating the same lines twice.
 6196            let mut rows = selection.spanned_rows(false, &display_map);
 6197
 6198            while let Some(next_selection) = selections_iter.peek() {
 6199                let next_rows = next_selection.spanned_rows(false, &display_map);
 6200                if next_rows.start < rows.end {
 6201                    rows.end = next_rows.end;
 6202                    selections_iter.next().unwrap();
 6203                } else {
 6204                    break;
 6205                }
 6206            }
 6207
 6208            // Copy the text from the selected row region and splice it either at the start
 6209            // or end of the region.
 6210            let start = Point::new(rows.start.0, 0);
 6211            let end = Point::new(
 6212                rows.end.previous_row().0,
 6213                buffer.line_len(rows.end.previous_row()),
 6214            );
 6215            let text = buffer
 6216                .text_for_range(start..end)
 6217                .chain(Some("\n"))
 6218                .collect::<String>();
 6219            let insert_location = if upwards {
 6220                Point::new(rows.end.0, 0)
 6221            } else {
 6222                start
 6223            };
 6224            edits.push((insert_location..insert_location, text));
 6225        }
 6226
 6227        self.transact(cx, |this, cx| {
 6228            this.buffer.update(cx, |buffer, cx| {
 6229                buffer.edit(edits, None, cx);
 6230            });
 6231
 6232            this.request_autoscroll(Autoscroll::fit(), cx);
 6233        });
 6234    }
 6235
 6236    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6237        self.duplicate_line(true, cx);
 6238    }
 6239
 6240    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6241        self.duplicate_line(false, cx);
 6242    }
 6243
 6244    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6245        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6246        let buffer = self.buffer.read(cx).snapshot(cx);
 6247
 6248        let mut edits = Vec::new();
 6249        let mut unfold_ranges = Vec::new();
 6250        let mut refold_ranges = Vec::new();
 6251
 6252        let selections = self.selections.all::<Point>(cx);
 6253        let mut selections = selections.iter().peekable();
 6254        let mut contiguous_row_selections = Vec::new();
 6255        let mut new_selections = Vec::new();
 6256
 6257        while let Some(selection) = selections.next() {
 6258            // Find all the selections that span a contiguous row range
 6259            let (start_row, end_row) = consume_contiguous_rows(
 6260                &mut contiguous_row_selections,
 6261                selection,
 6262                &display_map,
 6263                &mut selections,
 6264            );
 6265
 6266            // Move the text spanned by the row range to be before the line preceding the row range
 6267            if start_row.0 > 0 {
 6268                let range_to_move = Point::new(
 6269                    start_row.previous_row().0,
 6270                    buffer.line_len(start_row.previous_row()),
 6271                )
 6272                    ..Point::new(
 6273                        end_row.previous_row().0,
 6274                        buffer.line_len(end_row.previous_row()),
 6275                    );
 6276                let insertion_point = display_map
 6277                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6278                    .0;
 6279
 6280                // Don't move lines across excerpts
 6281                if buffer
 6282                    .excerpt_boundaries_in_range((
 6283                        Bound::Excluded(insertion_point),
 6284                        Bound::Included(range_to_move.end),
 6285                    ))
 6286                    .next()
 6287                    .is_none()
 6288                {
 6289                    let text = buffer
 6290                        .text_for_range(range_to_move.clone())
 6291                        .flat_map(|s| s.chars())
 6292                        .skip(1)
 6293                        .chain(['\n'])
 6294                        .collect::<String>();
 6295
 6296                    edits.push((
 6297                        buffer.anchor_after(range_to_move.start)
 6298                            ..buffer.anchor_before(range_to_move.end),
 6299                        String::new(),
 6300                    ));
 6301                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6302                    edits.push((insertion_anchor..insertion_anchor, text));
 6303
 6304                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6305
 6306                    // Move selections up
 6307                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6308                        |mut selection| {
 6309                            selection.start.row -= row_delta;
 6310                            selection.end.row -= row_delta;
 6311                            selection
 6312                        },
 6313                    ));
 6314
 6315                    // Move folds up
 6316                    unfold_ranges.push(range_to_move.clone());
 6317                    for fold in display_map.folds_in_range(
 6318                        buffer.anchor_before(range_to_move.start)
 6319                            ..buffer.anchor_after(range_to_move.end),
 6320                    ) {
 6321                        let mut start = fold.range.start.to_point(&buffer);
 6322                        let mut end = fold.range.end.to_point(&buffer);
 6323                        start.row -= row_delta;
 6324                        end.row -= row_delta;
 6325                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6326                    }
 6327                }
 6328            }
 6329
 6330            // If we didn't move line(s), preserve the existing selections
 6331            new_selections.append(&mut contiguous_row_selections);
 6332        }
 6333
 6334        self.transact(cx, |this, cx| {
 6335            this.unfold_ranges(unfold_ranges, true, true, cx);
 6336            this.buffer.update(cx, |buffer, cx| {
 6337                for (range, text) in edits {
 6338                    buffer.edit([(range, text)], None, cx);
 6339                }
 6340            });
 6341            this.fold_ranges(refold_ranges, true, cx);
 6342            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6343                s.select(new_selections);
 6344            })
 6345        });
 6346    }
 6347
 6348    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6349        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6350        let buffer = self.buffer.read(cx).snapshot(cx);
 6351
 6352        let mut edits = Vec::new();
 6353        let mut unfold_ranges = Vec::new();
 6354        let mut refold_ranges = Vec::new();
 6355
 6356        let selections = self.selections.all::<Point>(cx);
 6357        let mut selections = selections.iter().peekable();
 6358        let mut contiguous_row_selections = Vec::new();
 6359        let mut new_selections = Vec::new();
 6360
 6361        while let Some(selection) = selections.next() {
 6362            // Find all the selections that span a contiguous row range
 6363            let (start_row, end_row) = consume_contiguous_rows(
 6364                &mut contiguous_row_selections,
 6365                selection,
 6366                &display_map,
 6367                &mut selections,
 6368            );
 6369
 6370            // Move the text spanned by the row range to be after the last line of the row range
 6371            if end_row.0 <= buffer.max_point().row {
 6372                let range_to_move =
 6373                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6374                let insertion_point = display_map
 6375                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6376                    .0;
 6377
 6378                // Don't move lines across excerpt boundaries
 6379                if buffer
 6380                    .excerpt_boundaries_in_range((
 6381                        Bound::Excluded(range_to_move.start),
 6382                        Bound::Included(insertion_point),
 6383                    ))
 6384                    .next()
 6385                    .is_none()
 6386                {
 6387                    let mut text = String::from("\n");
 6388                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6389                    text.pop(); // Drop trailing newline
 6390                    edits.push((
 6391                        buffer.anchor_after(range_to_move.start)
 6392                            ..buffer.anchor_before(range_to_move.end),
 6393                        String::new(),
 6394                    ));
 6395                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6396                    edits.push((insertion_anchor..insertion_anchor, text));
 6397
 6398                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6399
 6400                    // Move selections down
 6401                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6402                        |mut selection| {
 6403                            selection.start.row += row_delta;
 6404                            selection.end.row += row_delta;
 6405                            selection
 6406                        },
 6407                    ));
 6408
 6409                    // Move folds down
 6410                    unfold_ranges.push(range_to_move.clone());
 6411                    for fold in display_map.folds_in_range(
 6412                        buffer.anchor_before(range_to_move.start)
 6413                            ..buffer.anchor_after(range_to_move.end),
 6414                    ) {
 6415                        let mut start = fold.range.start.to_point(&buffer);
 6416                        let mut end = fold.range.end.to_point(&buffer);
 6417                        start.row += row_delta;
 6418                        end.row += row_delta;
 6419                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6420                    }
 6421                }
 6422            }
 6423
 6424            // If we didn't move line(s), preserve the existing selections
 6425            new_selections.append(&mut contiguous_row_selections);
 6426        }
 6427
 6428        self.transact(cx, |this, cx| {
 6429            this.unfold_ranges(unfold_ranges, true, true, cx);
 6430            this.buffer.update(cx, |buffer, cx| {
 6431                for (range, text) in edits {
 6432                    buffer.edit([(range, text)], None, cx);
 6433                }
 6434            });
 6435            this.fold_ranges(refold_ranges, true, cx);
 6436            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6437        });
 6438    }
 6439
 6440    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6441        let text_layout_details = &self.text_layout_details(cx);
 6442        self.transact(cx, |this, cx| {
 6443            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6444                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6445                let line_mode = s.line_mode;
 6446                s.move_with(|display_map, selection| {
 6447                    if !selection.is_empty() || line_mode {
 6448                        return;
 6449                    }
 6450
 6451                    let mut head = selection.head();
 6452                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6453                    if head.column() == display_map.line_len(head.row()) {
 6454                        transpose_offset = display_map
 6455                            .buffer_snapshot
 6456                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6457                    }
 6458
 6459                    if transpose_offset == 0 {
 6460                        return;
 6461                    }
 6462
 6463                    *head.column_mut() += 1;
 6464                    head = display_map.clip_point(head, Bias::Right);
 6465                    let goal = SelectionGoal::HorizontalPosition(
 6466                        display_map
 6467                            .x_for_display_point(head, &text_layout_details)
 6468                            .into(),
 6469                    );
 6470                    selection.collapse_to(head, goal);
 6471
 6472                    let transpose_start = display_map
 6473                        .buffer_snapshot
 6474                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6475                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6476                        let transpose_end = display_map
 6477                            .buffer_snapshot
 6478                            .clip_offset(transpose_offset + 1, Bias::Right);
 6479                        if let Some(ch) =
 6480                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6481                        {
 6482                            edits.push((transpose_start..transpose_offset, String::new()));
 6483                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6484                        }
 6485                    }
 6486                });
 6487                edits
 6488            });
 6489            this.buffer
 6490                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6491            let selections = this.selections.all::<usize>(cx);
 6492            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6493                s.select(selections);
 6494            });
 6495        });
 6496    }
 6497
 6498    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6499        let mut text = String::new();
 6500        let buffer = self.buffer.read(cx).snapshot(cx);
 6501        let mut selections = self.selections.all::<Point>(cx);
 6502        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6503        {
 6504            let max_point = buffer.max_point();
 6505            let mut is_first = true;
 6506            for selection in &mut selections {
 6507                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6508                if is_entire_line {
 6509                    selection.start = Point::new(selection.start.row, 0);
 6510                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6511                    selection.goal = SelectionGoal::None;
 6512                }
 6513                if is_first {
 6514                    is_first = false;
 6515                } else {
 6516                    text += "\n";
 6517                }
 6518                let mut len = 0;
 6519                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6520                    text.push_str(chunk);
 6521                    len += chunk.len();
 6522                }
 6523                clipboard_selections.push(ClipboardSelection {
 6524                    len,
 6525                    is_entire_line,
 6526                    first_line_indent: buffer
 6527                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6528                        .len,
 6529                });
 6530            }
 6531        }
 6532
 6533        self.transact(cx, |this, cx| {
 6534            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6535                s.select(selections);
 6536            });
 6537            this.insert("", cx);
 6538            cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6539        });
 6540    }
 6541
 6542    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6543        let selections = self.selections.all::<Point>(cx);
 6544        let buffer = self.buffer.read(cx).read(cx);
 6545        let mut text = String::new();
 6546
 6547        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6548        {
 6549            let max_point = buffer.max_point();
 6550            let mut is_first = true;
 6551            for selection in selections.iter() {
 6552                let mut start = selection.start;
 6553                let mut end = selection.end;
 6554                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6555                if is_entire_line {
 6556                    start = Point::new(start.row, 0);
 6557                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6558                }
 6559                if is_first {
 6560                    is_first = false;
 6561                } else {
 6562                    text += "\n";
 6563                }
 6564                let mut len = 0;
 6565                for chunk in buffer.text_for_range(start..end) {
 6566                    text.push_str(chunk);
 6567                    len += chunk.len();
 6568                }
 6569                clipboard_selections.push(ClipboardSelection {
 6570                    len,
 6571                    is_entire_line,
 6572                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6573                });
 6574            }
 6575        }
 6576
 6577        cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6578    }
 6579
 6580    pub fn do_paste(
 6581        &mut self,
 6582        text: &String,
 6583        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6584        handle_entire_lines: bool,
 6585        cx: &mut ViewContext<Self>,
 6586    ) {
 6587        if self.read_only(cx) {
 6588            return;
 6589        }
 6590
 6591        let clipboard_text = Cow::Borrowed(text);
 6592
 6593        self.transact(cx, |this, cx| {
 6594            if let Some(mut clipboard_selections) = clipboard_selections {
 6595                let old_selections = this.selections.all::<usize>(cx);
 6596                let all_selections_were_entire_line =
 6597                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6598                let first_selection_indent_column =
 6599                    clipboard_selections.first().map(|s| s.first_line_indent);
 6600                if clipboard_selections.len() != old_selections.len() {
 6601                    clipboard_selections.drain(..);
 6602                }
 6603
 6604                this.buffer.update(cx, |buffer, cx| {
 6605                    let snapshot = buffer.read(cx);
 6606                    let mut start_offset = 0;
 6607                    let mut edits = Vec::new();
 6608                    let mut original_indent_columns = Vec::new();
 6609                    for (ix, selection) in old_selections.iter().enumerate() {
 6610                        let to_insert;
 6611                        let entire_line;
 6612                        let original_indent_column;
 6613                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6614                            let end_offset = start_offset + clipboard_selection.len;
 6615                            to_insert = &clipboard_text[start_offset..end_offset];
 6616                            entire_line = clipboard_selection.is_entire_line;
 6617                            start_offset = end_offset + 1;
 6618                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6619                        } else {
 6620                            to_insert = clipboard_text.as_str();
 6621                            entire_line = all_selections_were_entire_line;
 6622                            original_indent_column = first_selection_indent_column
 6623                        }
 6624
 6625                        // If the corresponding selection was empty when this slice of the
 6626                        // clipboard text was written, then the entire line containing the
 6627                        // selection was copied. If this selection is also currently empty,
 6628                        // then paste the line before the current line of the buffer.
 6629                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6630                            let column = selection.start.to_point(&snapshot).column as usize;
 6631                            let line_start = selection.start - column;
 6632                            line_start..line_start
 6633                        } else {
 6634                            selection.range()
 6635                        };
 6636
 6637                        edits.push((range, to_insert));
 6638                        original_indent_columns.extend(original_indent_column);
 6639                    }
 6640                    drop(snapshot);
 6641
 6642                    buffer.edit(
 6643                        edits,
 6644                        Some(AutoindentMode::Block {
 6645                            original_indent_columns,
 6646                        }),
 6647                        cx,
 6648                    );
 6649                });
 6650
 6651                let selections = this.selections.all::<usize>(cx);
 6652                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6653            } else {
 6654                this.insert(&clipboard_text, cx);
 6655            }
 6656        });
 6657    }
 6658
 6659    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6660        if let Some(item) = cx.read_from_clipboard() {
 6661            self.do_paste(
 6662                item.text(),
 6663                item.metadata::<Vec<ClipboardSelection>>(),
 6664                true,
 6665                cx,
 6666            )
 6667        };
 6668    }
 6669
 6670    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6671        if self.read_only(cx) {
 6672            return;
 6673        }
 6674
 6675        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6676            if let Some((selections, _)) =
 6677                self.selection_history.transaction(transaction_id).cloned()
 6678            {
 6679                self.change_selections(None, cx, |s| {
 6680                    s.select_anchors(selections.to_vec());
 6681                });
 6682            }
 6683            self.request_autoscroll(Autoscroll::fit(), cx);
 6684            self.unmark_text(cx);
 6685            self.refresh_inline_completion(true, cx);
 6686            cx.emit(EditorEvent::Edited { transaction_id });
 6687            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 6688        }
 6689    }
 6690
 6691    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 6692        if self.read_only(cx) {
 6693            return;
 6694        }
 6695
 6696        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 6697            if let Some((_, Some(selections))) =
 6698                self.selection_history.transaction(transaction_id).cloned()
 6699            {
 6700                self.change_selections(None, cx, |s| {
 6701                    s.select_anchors(selections.to_vec());
 6702                });
 6703            }
 6704            self.request_autoscroll(Autoscroll::fit(), cx);
 6705            self.unmark_text(cx);
 6706            self.refresh_inline_completion(true, cx);
 6707            cx.emit(EditorEvent::Edited { transaction_id });
 6708        }
 6709    }
 6710
 6711    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 6712        self.buffer
 6713            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 6714    }
 6715
 6716    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 6717        self.buffer
 6718            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 6719    }
 6720
 6721    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 6722        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6723            let line_mode = s.line_mode;
 6724            s.move_with(|map, selection| {
 6725                let cursor = if selection.is_empty() && !line_mode {
 6726                    movement::left(map, selection.start)
 6727                } else {
 6728                    selection.start
 6729                };
 6730                selection.collapse_to(cursor, SelectionGoal::None);
 6731            });
 6732        })
 6733    }
 6734
 6735    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 6736        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6737            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 6738        })
 6739    }
 6740
 6741    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 6742        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6743            let line_mode = s.line_mode;
 6744            s.move_with(|map, selection| {
 6745                let cursor = if selection.is_empty() && !line_mode {
 6746                    movement::right(map, selection.end)
 6747                } else {
 6748                    selection.end
 6749                };
 6750                selection.collapse_to(cursor, SelectionGoal::None)
 6751            });
 6752        })
 6753    }
 6754
 6755    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 6756        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6757            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 6758        })
 6759    }
 6760
 6761    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 6762        if self.take_rename(true, cx).is_some() {
 6763            return;
 6764        }
 6765
 6766        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6767            cx.propagate();
 6768            return;
 6769        }
 6770
 6771        let text_layout_details = &self.text_layout_details(cx);
 6772        let selection_count = self.selections.count();
 6773        let first_selection = self.selections.first_anchor();
 6774
 6775        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6776            let line_mode = s.line_mode;
 6777            s.move_with(|map, selection| {
 6778                if !selection.is_empty() && !line_mode {
 6779                    selection.goal = SelectionGoal::None;
 6780                }
 6781                let (cursor, goal) = movement::up(
 6782                    map,
 6783                    selection.start,
 6784                    selection.goal,
 6785                    false,
 6786                    &text_layout_details,
 6787                );
 6788                selection.collapse_to(cursor, goal);
 6789            });
 6790        });
 6791
 6792        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6793        {
 6794            cx.propagate();
 6795        }
 6796    }
 6797
 6798    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 6799        if self.take_rename(true, cx).is_some() {
 6800            return;
 6801        }
 6802
 6803        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6804            cx.propagate();
 6805            return;
 6806        }
 6807
 6808        let text_layout_details = &self.text_layout_details(cx);
 6809
 6810        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6811            let line_mode = s.line_mode;
 6812            s.move_with(|map, selection| {
 6813                if !selection.is_empty() && !line_mode {
 6814                    selection.goal = SelectionGoal::None;
 6815                }
 6816                let (cursor, goal) = movement::up_by_rows(
 6817                    map,
 6818                    selection.start,
 6819                    action.lines,
 6820                    selection.goal,
 6821                    false,
 6822                    &text_layout_details,
 6823                );
 6824                selection.collapse_to(cursor, goal);
 6825            });
 6826        })
 6827    }
 6828
 6829    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 6830        if self.take_rename(true, cx).is_some() {
 6831            return;
 6832        }
 6833
 6834        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6835            cx.propagate();
 6836            return;
 6837        }
 6838
 6839        let text_layout_details = &self.text_layout_details(cx);
 6840
 6841        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6842            let line_mode = s.line_mode;
 6843            s.move_with(|map, selection| {
 6844                if !selection.is_empty() && !line_mode {
 6845                    selection.goal = SelectionGoal::None;
 6846                }
 6847                let (cursor, goal) = movement::down_by_rows(
 6848                    map,
 6849                    selection.start,
 6850                    action.lines,
 6851                    selection.goal,
 6852                    false,
 6853                    &text_layout_details,
 6854                );
 6855                selection.collapse_to(cursor, goal);
 6856            });
 6857        })
 6858    }
 6859
 6860    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 6861        let text_layout_details = &self.text_layout_details(cx);
 6862        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6863            s.move_heads_with(|map, head, goal| {
 6864                movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6865            })
 6866        })
 6867    }
 6868
 6869    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 6870        let text_layout_details = &self.text_layout_details(cx);
 6871        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6872            s.move_heads_with(|map, head, goal| {
 6873                movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6874            })
 6875        })
 6876    }
 6877
 6878    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 6879        let Some(row_count) = self.visible_row_count() else {
 6880            return;
 6881        };
 6882
 6883        let text_layout_details = &self.text_layout_details(cx);
 6884
 6885        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6886            s.move_heads_with(|map, head, goal| {
 6887                movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
 6888            })
 6889        })
 6890    }
 6891
 6892    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 6893        if self.take_rename(true, cx).is_some() {
 6894            return;
 6895        }
 6896
 6897        if self
 6898            .context_menu
 6899            .write()
 6900            .as_mut()
 6901            .map(|menu| menu.select_first(self.project.as_ref(), cx))
 6902            .unwrap_or(false)
 6903        {
 6904            return;
 6905        }
 6906
 6907        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6908            cx.propagate();
 6909            return;
 6910        }
 6911
 6912        let Some(row_count) = self.visible_row_count() else {
 6913            return;
 6914        };
 6915
 6916        let autoscroll = if action.center_cursor {
 6917            Autoscroll::center()
 6918        } else {
 6919            Autoscroll::fit()
 6920        };
 6921
 6922        let text_layout_details = &self.text_layout_details(cx);
 6923
 6924        self.change_selections(Some(autoscroll), cx, |s| {
 6925            let line_mode = s.line_mode;
 6926            s.move_with(|map, selection| {
 6927                if !selection.is_empty() && !line_mode {
 6928                    selection.goal = SelectionGoal::None;
 6929                }
 6930                let (cursor, goal) = movement::up_by_rows(
 6931                    map,
 6932                    selection.end,
 6933                    row_count,
 6934                    selection.goal,
 6935                    false,
 6936                    &text_layout_details,
 6937                );
 6938                selection.collapse_to(cursor, goal);
 6939            });
 6940        });
 6941    }
 6942
 6943    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 6944        let text_layout_details = &self.text_layout_details(cx);
 6945        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6946            s.move_heads_with(|map, head, goal| {
 6947                movement::up(map, head, goal, false, &text_layout_details)
 6948            })
 6949        })
 6950    }
 6951
 6952    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 6953        self.take_rename(true, cx);
 6954
 6955        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6956            cx.propagate();
 6957            return;
 6958        }
 6959
 6960        let text_layout_details = &self.text_layout_details(cx);
 6961        let selection_count = self.selections.count();
 6962        let first_selection = self.selections.first_anchor();
 6963
 6964        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6965            let line_mode = s.line_mode;
 6966            s.move_with(|map, selection| {
 6967                if !selection.is_empty() && !line_mode {
 6968                    selection.goal = SelectionGoal::None;
 6969                }
 6970                let (cursor, goal) = movement::down(
 6971                    map,
 6972                    selection.end,
 6973                    selection.goal,
 6974                    false,
 6975                    &text_layout_details,
 6976                );
 6977                selection.collapse_to(cursor, goal);
 6978            });
 6979        });
 6980
 6981        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6982        {
 6983            cx.propagate();
 6984        }
 6985    }
 6986
 6987    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 6988        let Some(row_count) = self.visible_row_count() else {
 6989            return;
 6990        };
 6991
 6992        let text_layout_details = &self.text_layout_details(cx);
 6993
 6994        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6995            s.move_heads_with(|map, head, goal| {
 6996                movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
 6997            })
 6998        })
 6999    }
 7000
 7001    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7002        if self.take_rename(true, cx).is_some() {
 7003            return;
 7004        }
 7005
 7006        if self
 7007            .context_menu
 7008            .write()
 7009            .as_mut()
 7010            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 7011            .unwrap_or(false)
 7012        {
 7013            return;
 7014        }
 7015
 7016        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7017            cx.propagate();
 7018            return;
 7019        }
 7020
 7021        let Some(row_count) = self.visible_row_count() else {
 7022            return;
 7023        };
 7024
 7025        let autoscroll = if action.center_cursor {
 7026            Autoscroll::center()
 7027        } else {
 7028            Autoscroll::fit()
 7029        };
 7030
 7031        let text_layout_details = &self.text_layout_details(cx);
 7032        self.change_selections(Some(autoscroll), cx, |s| {
 7033            let line_mode = s.line_mode;
 7034            s.move_with(|map, selection| {
 7035                if !selection.is_empty() && !line_mode {
 7036                    selection.goal = SelectionGoal::None;
 7037                }
 7038                let (cursor, goal) = movement::down_by_rows(
 7039                    map,
 7040                    selection.end,
 7041                    row_count,
 7042                    selection.goal,
 7043                    false,
 7044                    &text_layout_details,
 7045                );
 7046                selection.collapse_to(cursor, goal);
 7047            });
 7048        });
 7049    }
 7050
 7051    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7052        let text_layout_details = &self.text_layout_details(cx);
 7053        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7054            s.move_heads_with(|map, head, goal| {
 7055                movement::down(map, head, goal, false, &text_layout_details)
 7056            })
 7057        });
 7058    }
 7059
 7060    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7061        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7062            context_menu.select_first(self.project.as_ref(), cx);
 7063        }
 7064    }
 7065
 7066    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7067        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7068            context_menu.select_prev(self.project.as_ref(), cx);
 7069        }
 7070    }
 7071
 7072    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7073        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7074            context_menu.select_next(self.project.as_ref(), cx);
 7075        }
 7076    }
 7077
 7078    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7079        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7080            context_menu.select_last(self.project.as_ref(), cx);
 7081        }
 7082    }
 7083
 7084    pub fn move_to_previous_word_start(
 7085        &mut self,
 7086        _: &MoveToPreviousWordStart,
 7087        cx: &mut ViewContext<Self>,
 7088    ) {
 7089        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7090            s.move_cursors_with(|map, head, _| {
 7091                (
 7092                    movement::previous_word_start(map, head),
 7093                    SelectionGoal::None,
 7094                )
 7095            });
 7096        })
 7097    }
 7098
 7099    pub fn move_to_previous_subword_start(
 7100        &mut self,
 7101        _: &MoveToPreviousSubwordStart,
 7102        cx: &mut ViewContext<Self>,
 7103    ) {
 7104        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7105            s.move_cursors_with(|map, head, _| {
 7106                (
 7107                    movement::previous_subword_start(map, head),
 7108                    SelectionGoal::None,
 7109                )
 7110            });
 7111        })
 7112    }
 7113
 7114    pub fn select_to_previous_word_start(
 7115        &mut self,
 7116        _: &SelectToPreviousWordStart,
 7117        cx: &mut ViewContext<Self>,
 7118    ) {
 7119        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7120            s.move_heads_with(|map, head, _| {
 7121                (
 7122                    movement::previous_word_start(map, head),
 7123                    SelectionGoal::None,
 7124                )
 7125            });
 7126        })
 7127    }
 7128
 7129    pub fn select_to_previous_subword_start(
 7130        &mut self,
 7131        _: &SelectToPreviousSubwordStart,
 7132        cx: &mut ViewContext<Self>,
 7133    ) {
 7134        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7135            s.move_heads_with(|map, head, _| {
 7136                (
 7137                    movement::previous_subword_start(map, head),
 7138                    SelectionGoal::None,
 7139                )
 7140            });
 7141        })
 7142    }
 7143
 7144    pub fn delete_to_previous_word_start(
 7145        &mut self,
 7146        _: &DeleteToPreviousWordStart,
 7147        cx: &mut ViewContext<Self>,
 7148    ) {
 7149        self.transact(cx, |this, cx| {
 7150            this.select_autoclose_pair(cx);
 7151            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7152                let line_mode = s.line_mode;
 7153                s.move_with(|map, selection| {
 7154                    if selection.is_empty() && !line_mode {
 7155                        let cursor = movement::previous_word_start(map, selection.head());
 7156                        selection.set_head(cursor, SelectionGoal::None);
 7157                    }
 7158                });
 7159            });
 7160            this.insert("", cx);
 7161        });
 7162    }
 7163
 7164    pub fn delete_to_previous_subword_start(
 7165        &mut self,
 7166        _: &DeleteToPreviousSubwordStart,
 7167        cx: &mut ViewContext<Self>,
 7168    ) {
 7169        self.transact(cx, |this, cx| {
 7170            this.select_autoclose_pair(cx);
 7171            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7172                let line_mode = s.line_mode;
 7173                s.move_with(|map, selection| {
 7174                    if selection.is_empty() && !line_mode {
 7175                        let cursor = movement::previous_subword_start(map, selection.head());
 7176                        selection.set_head(cursor, SelectionGoal::None);
 7177                    }
 7178                });
 7179            });
 7180            this.insert("", cx);
 7181        });
 7182    }
 7183
 7184    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7185        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7186            s.move_cursors_with(|map, head, _| {
 7187                (movement::next_word_end(map, head), SelectionGoal::None)
 7188            });
 7189        })
 7190    }
 7191
 7192    pub fn move_to_next_subword_end(
 7193        &mut self,
 7194        _: &MoveToNextSubwordEnd,
 7195        cx: &mut ViewContext<Self>,
 7196    ) {
 7197        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7198            s.move_cursors_with(|map, head, _| {
 7199                (movement::next_subword_end(map, head), SelectionGoal::None)
 7200            });
 7201        })
 7202    }
 7203
 7204    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7205        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7206            s.move_heads_with(|map, head, _| {
 7207                (movement::next_word_end(map, head), SelectionGoal::None)
 7208            });
 7209        })
 7210    }
 7211
 7212    pub fn select_to_next_subword_end(
 7213        &mut self,
 7214        _: &SelectToNextSubwordEnd,
 7215        cx: &mut ViewContext<Self>,
 7216    ) {
 7217        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7218            s.move_heads_with(|map, head, _| {
 7219                (movement::next_subword_end(map, head), SelectionGoal::None)
 7220            });
 7221        })
 7222    }
 7223
 7224    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
 7225        self.transact(cx, |this, cx| {
 7226            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7227                let line_mode = s.line_mode;
 7228                s.move_with(|map, selection| {
 7229                    if selection.is_empty() && !line_mode {
 7230                        let cursor = movement::next_word_end(map, selection.head());
 7231                        selection.set_head(cursor, SelectionGoal::None);
 7232                    }
 7233                });
 7234            });
 7235            this.insert("", cx);
 7236        });
 7237    }
 7238
 7239    pub fn delete_to_next_subword_end(
 7240        &mut self,
 7241        _: &DeleteToNextSubwordEnd,
 7242        cx: &mut ViewContext<Self>,
 7243    ) {
 7244        self.transact(cx, |this, cx| {
 7245            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7246                s.move_with(|map, selection| {
 7247                    if selection.is_empty() {
 7248                        let cursor = movement::next_subword_end(map, selection.head());
 7249                        selection.set_head(cursor, SelectionGoal::None);
 7250                    }
 7251                });
 7252            });
 7253            this.insert("", cx);
 7254        });
 7255    }
 7256
 7257    pub fn move_to_beginning_of_line(
 7258        &mut self,
 7259        action: &MoveToBeginningOfLine,
 7260        cx: &mut ViewContext<Self>,
 7261    ) {
 7262        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7263            s.move_cursors_with(|map, head, _| {
 7264                (
 7265                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7266                    SelectionGoal::None,
 7267                )
 7268            });
 7269        })
 7270    }
 7271
 7272    pub fn select_to_beginning_of_line(
 7273        &mut self,
 7274        action: &SelectToBeginningOfLine,
 7275        cx: &mut ViewContext<Self>,
 7276    ) {
 7277        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7278            s.move_heads_with(|map, head, _| {
 7279                (
 7280                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7281                    SelectionGoal::None,
 7282                )
 7283            });
 7284        });
 7285    }
 7286
 7287    pub fn delete_to_beginning_of_line(
 7288        &mut self,
 7289        _: &DeleteToBeginningOfLine,
 7290        cx: &mut ViewContext<Self>,
 7291    ) {
 7292        self.transact(cx, |this, cx| {
 7293            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7294                s.move_with(|_, selection| {
 7295                    selection.reversed = true;
 7296                });
 7297            });
 7298
 7299            this.select_to_beginning_of_line(
 7300                &SelectToBeginningOfLine {
 7301                    stop_at_soft_wraps: false,
 7302                },
 7303                cx,
 7304            );
 7305            this.backspace(&Backspace, cx);
 7306        });
 7307    }
 7308
 7309    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7310        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7311            s.move_cursors_with(|map, head, _| {
 7312                (
 7313                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7314                    SelectionGoal::None,
 7315                )
 7316            });
 7317        })
 7318    }
 7319
 7320    pub fn select_to_end_of_line(
 7321        &mut self,
 7322        action: &SelectToEndOfLine,
 7323        cx: &mut ViewContext<Self>,
 7324    ) {
 7325        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7326            s.move_heads_with(|map, head, _| {
 7327                (
 7328                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7329                    SelectionGoal::None,
 7330                )
 7331            });
 7332        })
 7333    }
 7334
 7335    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7336        self.transact(cx, |this, cx| {
 7337            this.select_to_end_of_line(
 7338                &SelectToEndOfLine {
 7339                    stop_at_soft_wraps: false,
 7340                },
 7341                cx,
 7342            );
 7343            this.delete(&Delete, cx);
 7344        });
 7345    }
 7346
 7347    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7348        self.transact(cx, |this, cx| {
 7349            this.select_to_end_of_line(
 7350                &SelectToEndOfLine {
 7351                    stop_at_soft_wraps: false,
 7352                },
 7353                cx,
 7354            );
 7355            this.cut(&Cut, cx);
 7356        });
 7357    }
 7358
 7359    pub fn move_to_start_of_paragraph(
 7360        &mut self,
 7361        _: &MoveToStartOfParagraph,
 7362        cx: &mut ViewContext<Self>,
 7363    ) {
 7364        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7365            cx.propagate();
 7366            return;
 7367        }
 7368
 7369        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7370            s.move_with(|map, selection| {
 7371                selection.collapse_to(
 7372                    movement::start_of_paragraph(map, selection.head(), 1),
 7373                    SelectionGoal::None,
 7374                )
 7375            });
 7376        })
 7377    }
 7378
 7379    pub fn move_to_end_of_paragraph(
 7380        &mut self,
 7381        _: &MoveToEndOfParagraph,
 7382        cx: &mut ViewContext<Self>,
 7383    ) {
 7384        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7385            cx.propagate();
 7386            return;
 7387        }
 7388
 7389        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7390            s.move_with(|map, selection| {
 7391                selection.collapse_to(
 7392                    movement::end_of_paragraph(map, selection.head(), 1),
 7393                    SelectionGoal::None,
 7394                )
 7395            });
 7396        })
 7397    }
 7398
 7399    pub fn select_to_start_of_paragraph(
 7400        &mut self,
 7401        _: &SelectToStartOfParagraph,
 7402        cx: &mut ViewContext<Self>,
 7403    ) {
 7404        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7405            cx.propagate();
 7406            return;
 7407        }
 7408
 7409        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7410            s.move_heads_with(|map, head, _| {
 7411                (
 7412                    movement::start_of_paragraph(map, head, 1),
 7413                    SelectionGoal::None,
 7414                )
 7415            });
 7416        })
 7417    }
 7418
 7419    pub fn select_to_end_of_paragraph(
 7420        &mut self,
 7421        _: &SelectToEndOfParagraph,
 7422        cx: &mut ViewContext<Self>,
 7423    ) {
 7424        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7425            cx.propagate();
 7426            return;
 7427        }
 7428
 7429        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7430            s.move_heads_with(|map, head, _| {
 7431                (
 7432                    movement::end_of_paragraph(map, head, 1),
 7433                    SelectionGoal::None,
 7434                )
 7435            });
 7436        })
 7437    }
 7438
 7439    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7440        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7441            cx.propagate();
 7442            return;
 7443        }
 7444
 7445        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7446            s.select_ranges(vec![0..0]);
 7447        });
 7448    }
 7449
 7450    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7451        let mut selection = self.selections.last::<Point>(cx);
 7452        selection.set_head(Point::zero(), SelectionGoal::None);
 7453
 7454        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7455            s.select(vec![selection]);
 7456        });
 7457    }
 7458
 7459    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7460        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7461            cx.propagate();
 7462            return;
 7463        }
 7464
 7465        let cursor = self.buffer.read(cx).read(cx).len();
 7466        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7467            s.select_ranges(vec![cursor..cursor])
 7468        });
 7469    }
 7470
 7471    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7472        self.nav_history = nav_history;
 7473    }
 7474
 7475    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7476        self.nav_history.as_ref()
 7477    }
 7478
 7479    fn push_to_nav_history(
 7480        &mut self,
 7481        cursor_anchor: Anchor,
 7482        new_position: Option<Point>,
 7483        cx: &mut ViewContext<Self>,
 7484    ) {
 7485        if let Some(nav_history) = self.nav_history.as_mut() {
 7486            let buffer = self.buffer.read(cx).read(cx);
 7487            let cursor_position = cursor_anchor.to_point(&buffer);
 7488            let scroll_state = self.scroll_manager.anchor();
 7489            let scroll_top_row = scroll_state.top_row(&buffer);
 7490            drop(buffer);
 7491
 7492            if let Some(new_position) = new_position {
 7493                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7494                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7495                    return;
 7496                }
 7497            }
 7498
 7499            nav_history.push(
 7500                Some(NavigationData {
 7501                    cursor_anchor,
 7502                    cursor_position,
 7503                    scroll_anchor: scroll_state,
 7504                    scroll_top_row,
 7505                }),
 7506                cx,
 7507            );
 7508        }
 7509    }
 7510
 7511    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7512        let buffer = self.buffer.read(cx).snapshot(cx);
 7513        let mut selection = self.selections.first::<usize>(cx);
 7514        selection.set_head(buffer.len(), SelectionGoal::None);
 7515        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7516            s.select(vec![selection]);
 7517        });
 7518    }
 7519
 7520    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7521        let end = self.buffer.read(cx).read(cx).len();
 7522        self.change_selections(None, cx, |s| {
 7523            s.select_ranges(vec![0..end]);
 7524        });
 7525    }
 7526
 7527    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7528        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7529        let mut selections = self.selections.all::<Point>(cx);
 7530        let max_point = display_map.buffer_snapshot.max_point();
 7531        for selection in &mut selections {
 7532            let rows = selection.spanned_rows(true, &display_map);
 7533            selection.start = Point::new(rows.start.0, 0);
 7534            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7535            selection.reversed = false;
 7536        }
 7537        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7538            s.select(selections);
 7539        });
 7540    }
 7541
 7542    pub fn split_selection_into_lines(
 7543        &mut self,
 7544        _: &SplitSelectionIntoLines,
 7545        cx: &mut ViewContext<Self>,
 7546    ) {
 7547        let mut to_unfold = Vec::new();
 7548        let mut new_selection_ranges = Vec::new();
 7549        {
 7550            let selections = self.selections.all::<Point>(cx);
 7551            let buffer = self.buffer.read(cx).read(cx);
 7552            for selection in selections {
 7553                for row in selection.start.row..selection.end.row {
 7554                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7555                    new_selection_ranges.push(cursor..cursor);
 7556                }
 7557                new_selection_ranges.push(selection.end..selection.end);
 7558                to_unfold.push(selection.start..selection.end);
 7559            }
 7560        }
 7561        self.unfold_ranges(to_unfold, true, true, cx);
 7562        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7563            s.select_ranges(new_selection_ranges);
 7564        });
 7565    }
 7566
 7567    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7568        self.add_selection(true, cx);
 7569    }
 7570
 7571    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7572        self.add_selection(false, cx);
 7573    }
 7574
 7575    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7576        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7577        let mut selections = self.selections.all::<Point>(cx);
 7578        let text_layout_details = self.text_layout_details(cx);
 7579        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7580            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7581            let range = oldest_selection.display_range(&display_map).sorted();
 7582
 7583            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7584            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7585            let positions = start_x.min(end_x)..start_x.max(end_x);
 7586
 7587            selections.clear();
 7588            let mut stack = Vec::new();
 7589            for row in range.start.row().0..=range.end.row().0 {
 7590                if let Some(selection) = self.selections.build_columnar_selection(
 7591                    &display_map,
 7592                    DisplayRow(row),
 7593                    &positions,
 7594                    oldest_selection.reversed,
 7595                    &text_layout_details,
 7596                ) {
 7597                    stack.push(selection.id);
 7598                    selections.push(selection);
 7599                }
 7600            }
 7601
 7602            if above {
 7603                stack.reverse();
 7604            }
 7605
 7606            AddSelectionsState { above, stack }
 7607        });
 7608
 7609        let last_added_selection = *state.stack.last().unwrap();
 7610        let mut new_selections = Vec::new();
 7611        if above == state.above {
 7612            let end_row = if above {
 7613                DisplayRow(0)
 7614            } else {
 7615                display_map.max_point().row()
 7616            };
 7617
 7618            'outer: for selection in selections {
 7619                if selection.id == last_added_selection {
 7620                    let range = selection.display_range(&display_map).sorted();
 7621                    debug_assert_eq!(range.start.row(), range.end.row());
 7622                    let mut row = range.start.row();
 7623                    let positions =
 7624                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7625                            px(start)..px(end)
 7626                        } else {
 7627                            let start_x =
 7628                                display_map.x_for_display_point(range.start, &text_layout_details);
 7629                            let end_x =
 7630                                display_map.x_for_display_point(range.end, &text_layout_details);
 7631                            start_x.min(end_x)..start_x.max(end_x)
 7632                        };
 7633
 7634                    while row != end_row {
 7635                        if above {
 7636                            row.0 -= 1;
 7637                        } else {
 7638                            row.0 += 1;
 7639                        }
 7640
 7641                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7642                            &display_map,
 7643                            row,
 7644                            &positions,
 7645                            selection.reversed,
 7646                            &text_layout_details,
 7647                        ) {
 7648                            state.stack.push(new_selection.id);
 7649                            if above {
 7650                                new_selections.push(new_selection);
 7651                                new_selections.push(selection);
 7652                            } else {
 7653                                new_selections.push(selection);
 7654                                new_selections.push(new_selection);
 7655                            }
 7656
 7657                            continue 'outer;
 7658                        }
 7659                    }
 7660                }
 7661
 7662                new_selections.push(selection);
 7663            }
 7664        } else {
 7665            new_selections = selections;
 7666            new_selections.retain(|s| s.id != last_added_selection);
 7667            state.stack.pop();
 7668        }
 7669
 7670        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7671            s.select(new_selections);
 7672        });
 7673        if state.stack.len() > 1 {
 7674            self.add_selections_state = Some(state);
 7675        }
 7676    }
 7677
 7678    pub fn select_next_match_internal(
 7679        &mut self,
 7680        display_map: &DisplaySnapshot,
 7681        replace_newest: bool,
 7682        autoscroll: Option<Autoscroll>,
 7683        cx: &mut ViewContext<Self>,
 7684    ) -> Result<()> {
 7685        fn select_next_match_ranges(
 7686            this: &mut Editor,
 7687            range: Range<usize>,
 7688            replace_newest: bool,
 7689            auto_scroll: Option<Autoscroll>,
 7690            cx: &mut ViewContext<Editor>,
 7691        ) {
 7692            this.unfold_ranges([range.clone()], false, true, cx);
 7693            this.change_selections(auto_scroll, cx, |s| {
 7694                if replace_newest {
 7695                    s.delete(s.newest_anchor().id);
 7696                }
 7697                s.insert_range(range.clone());
 7698            });
 7699        }
 7700
 7701        let buffer = &display_map.buffer_snapshot;
 7702        let mut selections = self.selections.all::<usize>(cx);
 7703        if let Some(mut select_next_state) = self.select_next_state.take() {
 7704            let query = &select_next_state.query;
 7705            if !select_next_state.done {
 7706                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7707                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7708                let mut next_selected_range = None;
 7709
 7710                let bytes_after_last_selection =
 7711                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7712                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7713                let query_matches = query
 7714                    .stream_find_iter(bytes_after_last_selection)
 7715                    .map(|result| (last_selection.end, result))
 7716                    .chain(
 7717                        query
 7718                            .stream_find_iter(bytes_before_first_selection)
 7719                            .map(|result| (0, result)),
 7720                    );
 7721
 7722                for (start_offset, query_match) in query_matches {
 7723                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7724                    let offset_range =
 7725                        start_offset + query_match.start()..start_offset + query_match.end();
 7726                    let display_range = offset_range.start.to_display_point(&display_map)
 7727                        ..offset_range.end.to_display_point(&display_map);
 7728
 7729                    if !select_next_state.wordwise
 7730                        || (!movement::is_inside_word(&display_map, display_range.start)
 7731                            && !movement::is_inside_word(&display_map, display_range.end))
 7732                    {
 7733                        // TODO: This is n^2, because we might check all the selections
 7734                        if !selections
 7735                            .iter()
 7736                            .any(|selection| selection.range().overlaps(&offset_range))
 7737                        {
 7738                            next_selected_range = Some(offset_range);
 7739                            break;
 7740                        }
 7741                    }
 7742                }
 7743
 7744                if let Some(next_selected_range) = next_selected_range {
 7745                    select_next_match_ranges(
 7746                        self,
 7747                        next_selected_range,
 7748                        replace_newest,
 7749                        autoscroll,
 7750                        cx,
 7751                    );
 7752                } else {
 7753                    select_next_state.done = true;
 7754                }
 7755            }
 7756
 7757            self.select_next_state = Some(select_next_state);
 7758        } else {
 7759            let mut only_carets = true;
 7760            let mut same_text_selected = true;
 7761            let mut selected_text = None;
 7762
 7763            let mut selections_iter = selections.iter().peekable();
 7764            while let Some(selection) = selections_iter.next() {
 7765                if selection.start != selection.end {
 7766                    only_carets = false;
 7767                }
 7768
 7769                if same_text_selected {
 7770                    if selected_text.is_none() {
 7771                        selected_text =
 7772                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7773                    }
 7774
 7775                    if let Some(next_selection) = selections_iter.peek() {
 7776                        if next_selection.range().len() == selection.range().len() {
 7777                            let next_selected_text = buffer
 7778                                .text_for_range(next_selection.range())
 7779                                .collect::<String>();
 7780                            if Some(next_selected_text) != selected_text {
 7781                                same_text_selected = false;
 7782                                selected_text = None;
 7783                            }
 7784                        } else {
 7785                            same_text_selected = false;
 7786                            selected_text = None;
 7787                        }
 7788                    }
 7789                }
 7790            }
 7791
 7792            if only_carets {
 7793                for selection in &mut selections {
 7794                    let word_range = movement::surrounding_word(
 7795                        &display_map,
 7796                        selection.start.to_display_point(&display_map),
 7797                    );
 7798                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7799                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7800                    selection.goal = SelectionGoal::None;
 7801                    selection.reversed = false;
 7802                    select_next_match_ranges(
 7803                        self,
 7804                        selection.start..selection.end,
 7805                        replace_newest,
 7806                        autoscroll,
 7807                        cx,
 7808                    );
 7809                }
 7810
 7811                if selections.len() == 1 {
 7812                    let selection = selections
 7813                        .last()
 7814                        .expect("ensured that there's only one selection");
 7815                    let query = buffer
 7816                        .text_for_range(selection.start..selection.end)
 7817                        .collect::<String>();
 7818                    let is_empty = query.is_empty();
 7819                    let select_state = SelectNextState {
 7820                        query: AhoCorasick::new(&[query])?,
 7821                        wordwise: true,
 7822                        done: is_empty,
 7823                    };
 7824                    self.select_next_state = Some(select_state);
 7825                } else {
 7826                    self.select_next_state = None;
 7827                }
 7828            } else if let Some(selected_text) = selected_text {
 7829                self.select_next_state = Some(SelectNextState {
 7830                    query: AhoCorasick::new(&[selected_text])?,
 7831                    wordwise: false,
 7832                    done: false,
 7833                });
 7834                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 7835            }
 7836        }
 7837        Ok(())
 7838    }
 7839
 7840    pub fn select_all_matches(
 7841        &mut self,
 7842        _action: &SelectAllMatches,
 7843        cx: &mut ViewContext<Self>,
 7844    ) -> Result<()> {
 7845        self.push_to_selection_history();
 7846        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7847
 7848        self.select_next_match_internal(&display_map, false, None, cx)?;
 7849        let Some(select_next_state) = self.select_next_state.as_mut() else {
 7850            return Ok(());
 7851        };
 7852        if select_next_state.done {
 7853            return Ok(());
 7854        }
 7855
 7856        let mut new_selections = self.selections.all::<usize>(cx);
 7857
 7858        let buffer = &display_map.buffer_snapshot;
 7859        let query_matches = select_next_state
 7860            .query
 7861            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 7862
 7863        for query_match in query_matches {
 7864            let query_match = query_match.unwrap(); // can only fail due to I/O
 7865            let offset_range = query_match.start()..query_match.end();
 7866            let display_range = offset_range.start.to_display_point(&display_map)
 7867                ..offset_range.end.to_display_point(&display_map);
 7868
 7869            if !select_next_state.wordwise
 7870                || (!movement::is_inside_word(&display_map, display_range.start)
 7871                    && !movement::is_inside_word(&display_map, display_range.end))
 7872            {
 7873                self.selections.change_with(cx, |selections| {
 7874                    new_selections.push(Selection {
 7875                        id: selections.new_selection_id(),
 7876                        start: offset_range.start,
 7877                        end: offset_range.end,
 7878                        reversed: false,
 7879                        goal: SelectionGoal::None,
 7880                    });
 7881                });
 7882            }
 7883        }
 7884
 7885        new_selections.sort_by_key(|selection| selection.start);
 7886        let mut ix = 0;
 7887        while ix + 1 < new_selections.len() {
 7888            let current_selection = &new_selections[ix];
 7889            let next_selection = &new_selections[ix + 1];
 7890            if current_selection.range().overlaps(&next_selection.range()) {
 7891                if current_selection.id < next_selection.id {
 7892                    new_selections.remove(ix + 1);
 7893                } else {
 7894                    new_selections.remove(ix);
 7895                }
 7896            } else {
 7897                ix += 1;
 7898            }
 7899        }
 7900
 7901        select_next_state.done = true;
 7902        self.unfold_ranges(
 7903            new_selections.iter().map(|selection| selection.range()),
 7904            false,
 7905            false,
 7906            cx,
 7907        );
 7908        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 7909            selections.select(new_selections)
 7910        });
 7911
 7912        Ok(())
 7913    }
 7914
 7915    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 7916        self.push_to_selection_history();
 7917        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7918        self.select_next_match_internal(
 7919            &display_map,
 7920            action.replace_newest,
 7921            Some(Autoscroll::newest()),
 7922            cx,
 7923        )?;
 7924        Ok(())
 7925    }
 7926
 7927    pub fn select_previous(
 7928        &mut self,
 7929        action: &SelectPrevious,
 7930        cx: &mut ViewContext<Self>,
 7931    ) -> Result<()> {
 7932        self.push_to_selection_history();
 7933        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7934        let buffer = &display_map.buffer_snapshot;
 7935        let mut selections = self.selections.all::<usize>(cx);
 7936        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 7937            let query = &select_prev_state.query;
 7938            if !select_prev_state.done {
 7939                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7940                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7941                let mut next_selected_range = None;
 7942                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 7943                let bytes_before_last_selection =
 7944                    buffer.reversed_bytes_in_range(0..last_selection.start);
 7945                let bytes_after_first_selection =
 7946                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 7947                let query_matches = query
 7948                    .stream_find_iter(bytes_before_last_selection)
 7949                    .map(|result| (last_selection.start, result))
 7950                    .chain(
 7951                        query
 7952                            .stream_find_iter(bytes_after_first_selection)
 7953                            .map(|result| (buffer.len(), result)),
 7954                    );
 7955                for (end_offset, query_match) in query_matches {
 7956                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7957                    let offset_range =
 7958                        end_offset - query_match.end()..end_offset - query_match.start();
 7959                    let display_range = offset_range.start.to_display_point(&display_map)
 7960                        ..offset_range.end.to_display_point(&display_map);
 7961
 7962                    if !select_prev_state.wordwise
 7963                        || (!movement::is_inside_word(&display_map, display_range.start)
 7964                            && !movement::is_inside_word(&display_map, display_range.end))
 7965                    {
 7966                        next_selected_range = Some(offset_range);
 7967                        break;
 7968                    }
 7969                }
 7970
 7971                if let Some(next_selected_range) = next_selected_range {
 7972                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 7973                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7974                        if action.replace_newest {
 7975                            s.delete(s.newest_anchor().id);
 7976                        }
 7977                        s.insert_range(next_selected_range);
 7978                    });
 7979                } else {
 7980                    select_prev_state.done = true;
 7981                }
 7982            }
 7983
 7984            self.select_prev_state = Some(select_prev_state);
 7985        } else {
 7986            let mut only_carets = true;
 7987            let mut same_text_selected = true;
 7988            let mut selected_text = None;
 7989
 7990            let mut selections_iter = selections.iter().peekable();
 7991            while let Some(selection) = selections_iter.next() {
 7992                if selection.start != selection.end {
 7993                    only_carets = false;
 7994                }
 7995
 7996                if same_text_selected {
 7997                    if selected_text.is_none() {
 7998                        selected_text =
 7999                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8000                    }
 8001
 8002                    if let Some(next_selection) = selections_iter.peek() {
 8003                        if next_selection.range().len() == selection.range().len() {
 8004                            let next_selected_text = buffer
 8005                                .text_for_range(next_selection.range())
 8006                                .collect::<String>();
 8007                            if Some(next_selected_text) != selected_text {
 8008                                same_text_selected = false;
 8009                                selected_text = None;
 8010                            }
 8011                        } else {
 8012                            same_text_selected = false;
 8013                            selected_text = None;
 8014                        }
 8015                    }
 8016                }
 8017            }
 8018
 8019            if only_carets {
 8020                for selection in &mut selections {
 8021                    let word_range = movement::surrounding_word(
 8022                        &display_map,
 8023                        selection.start.to_display_point(&display_map),
 8024                    );
 8025                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8026                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8027                    selection.goal = SelectionGoal::None;
 8028                    selection.reversed = false;
 8029                }
 8030                if selections.len() == 1 {
 8031                    let selection = selections
 8032                        .last()
 8033                        .expect("ensured that there's only one selection");
 8034                    let query = buffer
 8035                        .text_for_range(selection.start..selection.end)
 8036                        .collect::<String>();
 8037                    let is_empty = query.is_empty();
 8038                    let select_state = SelectNextState {
 8039                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8040                        wordwise: true,
 8041                        done: is_empty,
 8042                    };
 8043                    self.select_prev_state = Some(select_state);
 8044                } else {
 8045                    self.select_prev_state = None;
 8046                }
 8047
 8048                self.unfold_ranges(
 8049                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8050                    false,
 8051                    true,
 8052                    cx,
 8053                );
 8054                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8055                    s.select(selections);
 8056                });
 8057            } else if let Some(selected_text) = selected_text {
 8058                self.select_prev_state = Some(SelectNextState {
 8059                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8060                    wordwise: false,
 8061                    done: false,
 8062                });
 8063                self.select_previous(action, cx)?;
 8064            }
 8065        }
 8066        Ok(())
 8067    }
 8068
 8069    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8070        let text_layout_details = &self.text_layout_details(cx);
 8071        self.transact(cx, |this, cx| {
 8072            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8073            let mut edits = Vec::new();
 8074            let mut selection_edit_ranges = Vec::new();
 8075            let mut last_toggled_row = None;
 8076            let snapshot = this.buffer.read(cx).read(cx);
 8077            let empty_str: Arc<str> = "".into();
 8078            let mut suffixes_inserted = Vec::new();
 8079
 8080            fn comment_prefix_range(
 8081                snapshot: &MultiBufferSnapshot,
 8082                row: MultiBufferRow,
 8083                comment_prefix: &str,
 8084                comment_prefix_whitespace: &str,
 8085            ) -> Range<Point> {
 8086                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8087
 8088                let mut line_bytes = snapshot
 8089                    .bytes_in_range(start..snapshot.max_point())
 8090                    .flatten()
 8091                    .copied();
 8092
 8093                // If this line currently begins with the line comment prefix, then record
 8094                // the range containing the prefix.
 8095                if line_bytes
 8096                    .by_ref()
 8097                    .take(comment_prefix.len())
 8098                    .eq(comment_prefix.bytes())
 8099                {
 8100                    // Include any whitespace that matches the comment prefix.
 8101                    let matching_whitespace_len = line_bytes
 8102                        .zip(comment_prefix_whitespace.bytes())
 8103                        .take_while(|(a, b)| a == b)
 8104                        .count() as u32;
 8105                    let end = Point::new(
 8106                        start.row,
 8107                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8108                    );
 8109                    start..end
 8110                } else {
 8111                    start..start
 8112                }
 8113            }
 8114
 8115            fn comment_suffix_range(
 8116                snapshot: &MultiBufferSnapshot,
 8117                row: MultiBufferRow,
 8118                comment_suffix: &str,
 8119                comment_suffix_has_leading_space: bool,
 8120            ) -> Range<Point> {
 8121                let end = Point::new(row.0, snapshot.line_len(row));
 8122                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8123
 8124                let mut line_end_bytes = snapshot
 8125                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8126                    .flatten()
 8127                    .copied();
 8128
 8129                let leading_space_len = if suffix_start_column > 0
 8130                    && line_end_bytes.next() == Some(b' ')
 8131                    && comment_suffix_has_leading_space
 8132                {
 8133                    1
 8134                } else {
 8135                    0
 8136                };
 8137
 8138                // If this line currently begins with the line comment prefix, then record
 8139                // the range containing the prefix.
 8140                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8141                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8142                    start..end
 8143                } else {
 8144                    end..end
 8145                }
 8146            }
 8147
 8148            // TODO: Handle selections that cross excerpts
 8149            for selection in &mut selections {
 8150                let start_column = snapshot
 8151                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8152                    .len;
 8153                let language = if let Some(language) =
 8154                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8155                {
 8156                    language
 8157                } else {
 8158                    continue;
 8159                };
 8160
 8161                selection_edit_ranges.clear();
 8162
 8163                // If multiple selections contain a given row, avoid processing that
 8164                // row more than once.
 8165                let mut start_row = MultiBufferRow(selection.start.row);
 8166                if last_toggled_row == Some(start_row) {
 8167                    start_row = start_row.next_row();
 8168                }
 8169                let end_row =
 8170                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8171                        MultiBufferRow(selection.end.row - 1)
 8172                    } else {
 8173                        MultiBufferRow(selection.end.row)
 8174                    };
 8175                last_toggled_row = Some(end_row);
 8176
 8177                if start_row > end_row {
 8178                    continue;
 8179                }
 8180
 8181                // If the language has line comments, toggle those.
 8182                let full_comment_prefixes = language.line_comment_prefixes();
 8183                if !full_comment_prefixes.is_empty() {
 8184                    let first_prefix = full_comment_prefixes
 8185                        .first()
 8186                        .expect("prefixes is non-empty");
 8187                    let prefix_trimmed_lengths = full_comment_prefixes
 8188                        .iter()
 8189                        .map(|p| p.trim_end_matches(' ').len())
 8190                        .collect::<SmallVec<[usize; 4]>>();
 8191
 8192                    let mut all_selection_lines_are_comments = true;
 8193
 8194                    for row in start_row.0..=end_row.0 {
 8195                        let row = MultiBufferRow(row);
 8196                        if start_row < end_row && snapshot.is_line_blank(row) {
 8197                            continue;
 8198                        }
 8199
 8200                        let prefix_range = full_comment_prefixes
 8201                            .iter()
 8202                            .zip(prefix_trimmed_lengths.iter().copied())
 8203                            .map(|(prefix, trimmed_prefix_len)| {
 8204                                comment_prefix_range(
 8205                                    snapshot.deref(),
 8206                                    row,
 8207                                    &prefix[..trimmed_prefix_len],
 8208                                    &prefix[trimmed_prefix_len..],
 8209                                )
 8210                            })
 8211                            .max_by_key(|range| range.end.column - range.start.column)
 8212                            .expect("prefixes is non-empty");
 8213
 8214                        if prefix_range.is_empty() {
 8215                            all_selection_lines_are_comments = false;
 8216                        }
 8217
 8218                        selection_edit_ranges.push(prefix_range);
 8219                    }
 8220
 8221                    if all_selection_lines_are_comments {
 8222                        edits.extend(
 8223                            selection_edit_ranges
 8224                                .iter()
 8225                                .cloned()
 8226                                .map(|range| (range, empty_str.clone())),
 8227                        );
 8228                    } else {
 8229                        let min_column = selection_edit_ranges
 8230                            .iter()
 8231                            .map(|range| range.start.column)
 8232                            .min()
 8233                            .unwrap_or(0);
 8234                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8235                            let position = Point::new(range.start.row, min_column);
 8236                            (position..position, first_prefix.clone())
 8237                        }));
 8238                    }
 8239                } else if let Some((full_comment_prefix, comment_suffix)) =
 8240                    language.block_comment_delimiters()
 8241                {
 8242                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8243                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8244                    let prefix_range = comment_prefix_range(
 8245                        snapshot.deref(),
 8246                        start_row,
 8247                        comment_prefix,
 8248                        comment_prefix_whitespace,
 8249                    );
 8250                    let suffix_range = comment_suffix_range(
 8251                        snapshot.deref(),
 8252                        end_row,
 8253                        comment_suffix.trim_start_matches(' '),
 8254                        comment_suffix.starts_with(' '),
 8255                    );
 8256
 8257                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8258                        edits.push((
 8259                            prefix_range.start..prefix_range.start,
 8260                            full_comment_prefix.clone(),
 8261                        ));
 8262                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8263                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8264                    } else {
 8265                        edits.push((prefix_range, empty_str.clone()));
 8266                        edits.push((suffix_range, empty_str.clone()));
 8267                    }
 8268                } else {
 8269                    continue;
 8270                }
 8271            }
 8272
 8273            drop(snapshot);
 8274            this.buffer.update(cx, |buffer, cx| {
 8275                buffer.edit(edits, None, cx);
 8276            });
 8277
 8278            // Adjust selections so that they end before any comment suffixes that
 8279            // were inserted.
 8280            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8281            let mut selections = this.selections.all::<Point>(cx);
 8282            let snapshot = this.buffer.read(cx).read(cx);
 8283            for selection in &mut selections {
 8284                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8285                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8286                        Ordering::Less => {
 8287                            suffixes_inserted.next();
 8288                            continue;
 8289                        }
 8290                        Ordering::Greater => break,
 8291                        Ordering::Equal => {
 8292                            if selection.end.column == snapshot.line_len(row) {
 8293                                if selection.is_empty() {
 8294                                    selection.start.column -= suffix_len as u32;
 8295                                }
 8296                                selection.end.column -= suffix_len as u32;
 8297                            }
 8298                            break;
 8299                        }
 8300                    }
 8301                }
 8302            }
 8303
 8304            drop(snapshot);
 8305            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8306
 8307            let selections = this.selections.all::<Point>(cx);
 8308            let selections_on_single_row = selections.windows(2).all(|selections| {
 8309                selections[0].start.row == selections[1].start.row
 8310                    && selections[0].end.row == selections[1].end.row
 8311                    && selections[0].start.row == selections[0].end.row
 8312            });
 8313            let selections_selecting = selections
 8314                .iter()
 8315                .any(|selection| selection.start != selection.end);
 8316            let advance_downwards = action.advance_downwards
 8317                && selections_on_single_row
 8318                && !selections_selecting
 8319                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8320
 8321            if advance_downwards {
 8322                let snapshot = this.buffer.read(cx).snapshot(cx);
 8323
 8324                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8325                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8326                        let mut point = display_point.to_point(display_snapshot);
 8327                        point.row += 1;
 8328                        point = snapshot.clip_point(point, Bias::Left);
 8329                        let display_point = point.to_display_point(display_snapshot);
 8330                        let goal = SelectionGoal::HorizontalPosition(
 8331                            display_snapshot
 8332                                .x_for_display_point(display_point, &text_layout_details)
 8333                                .into(),
 8334                        );
 8335                        (display_point, goal)
 8336                    })
 8337                });
 8338            }
 8339        });
 8340    }
 8341
 8342    pub fn select_enclosing_symbol(
 8343        &mut self,
 8344        _: &SelectEnclosingSymbol,
 8345        cx: &mut ViewContext<Self>,
 8346    ) {
 8347        let buffer = self.buffer.read(cx).snapshot(cx);
 8348        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8349
 8350        fn update_selection(
 8351            selection: &Selection<usize>,
 8352            buffer_snap: &MultiBufferSnapshot,
 8353        ) -> Option<Selection<usize>> {
 8354            let cursor = selection.head();
 8355            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8356            for symbol in symbols.iter().rev() {
 8357                let start = symbol.range.start.to_offset(&buffer_snap);
 8358                let end = symbol.range.end.to_offset(&buffer_snap);
 8359                let new_range = start..end;
 8360                if start < selection.start || end > selection.end {
 8361                    return Some(Selection {
 8362                        id: selection.id,
 8363                        start: new_range.start,
 8364                        end: new_range.end,
 8365                        goal: SelectionGoal::None,
 8366                        reversed: selection.reversed,
 8367                    });
 8368                }
 8369            }
 8370            None
 8371        }
 8372
 8373        let mut selected_larger_symbol = false;
 8374        let new_selections = old_selections
 8375            .iter()
 8376            .map(|selection| match update_selection(selection, &buffer) {
 8377                Some(new_selection) => {
 8378                    if new_selection.range() != selection.range() {
 8379                        selected_larger_symbol = true;
 8380                    }
 8381                    new_selection
 8382                }
 8383                None => selection.clone(),
 8384            })
 8385            .collect::<Vec<_>>();
 8386
 8387        if selected_larger_symbol {
 8388            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8389                s.select(new_selections);
 8390            });
 8391        }
 8392    }
 8393
 8394    pub fn select_larger_syntax_node(
 8395        &mut self,
 8396        _: &SelectLargerSyntaxNode,
 8397        cx: &mut ViewContext<Self>,
 8398    ) {
 8399        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8400        let buffer = self.buffer.read(cx).snapshot(cx);
 8401        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8402
 8403        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8404        let mut selected_larger_node = false;
 8405        let new_selections = old_selections
 8406            .iter()
 8407            .map(|selection| {
 8408                let old_range = selection.start..selection.end;
 8409                let mut new_range = old_range.clone();
 8410                while let Some(containing_range) =
 8411                    buffer.range_for_syntax_ancestor(new_range.clone())
 8412                {
 8413                    new_range = containing_range;
 8414                    if !display_map.intersects_fold(new_range.start)
 8415                        && !display_map.intersects_fold(new_range.end)
 8416                    {
 8417                        break;
 8418                    }
 8419                }
 8420
 8421                selected_larger_node |= new_range != old_range;
 8422                Selection {
 8423                    id: selection.id,
 8424                    start: new_range.start,
 8425                    end: new_range.end,
 8426                    goal: SelectionGoal::None,
 8427                    reversed: selection.reversed,
 8428                }
 8429            })
 8430            .collect::<Vec<_>>();
 8431
 8432        if selected_larger_node {
 8433            stack.push(old_selections);
 8434            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8435                s.select(new_selections);
 8436            });
 8437        }
 8438        self.select_larger_syntax_node_stack = stack;
 8439    }
 8440
 8441    pub fn select_smaller_syntax_node(
 8442        &mut self,
 8443        _: &SelectSmallerSyntaxNode,
 8444        cx: &mut ViewContext<Self>,
 8445    ) {
 8446        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8447        if let Some(selections) = stack.pop() {
 8448            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8449                s.select(selections.to_vec());
 8450            });
 8451        }
 8452        self.select_larger_syntax_node_stack = stack;
 8453    }
 8454
 8455    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8456        if !EditorSettings::get_global(cx).gutter.runnables {
 8457            self.clear_tasks();
 8458            return Task::ready(());
 8459        }
 8460        let project = self.project.clone();
 8461        cx.spawn(|this, mut cx| async move {
 8462            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8463                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8464            }) else {
 8465                return;
 8466            };
 8467
 8468            let Some(project) = project else {
 8469                return;
 8470            };
 8471
 8472            let hide_runnables = project
 8473                .update(&mut cx, |project, cx| {
 8474                    // Do not display any test indicators in non-dev server remote projects.
 8475                    project.is_remote() && project.ssh_connection_string(cx).is_none()
 8476                })
 8477                .unwrap_or(true);
 8478            if hide_runnables {
 8479                return;
 8480            }
 8481            let new_rows =
 8482                cx.background_executor()
 8483                    .spawn({
 8484                        let snapshot = display_snapshot.clone();
 8485                        async move {
 8486                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8487                        }
 8488                    })
 8489                    .await;
 8490            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8491
 8492            this.update(&mut cx, |this, _| {
 8493                this.clear_tasks();
 8494                for (key, value) in rows {
 8495                    this.insert_tasks(key, value);
 8496                }
 8497            })
 8498            .ok();
 8499        })
 8500    }
 8501    fn fetch_runnable_ranges(
 8502        snapshot: &DisplaySnapshot,
 8503        range: Range<Anchor>,
 8504    ) -> Vec<language::RunnableRange> {
 8505        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8506    }
 8507
 8508    fn runnable_rows(
 8509        project: Model<Project>,
 8510        snapshot: DisplaySnapshot,
 8511        runnable_ranges: Vec<RunnableRange>,
 8512        mut cx: AsyncWindowContext,
 8513    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8514        runnable_ranges
 8515            .into_iter()
 8516            .filter_map(|mut runnable| {
 8517                let tasks = cx
 8518                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8519                    .ok()?;
 8520                if tasks.is_empty() {
 8521                    return None;
 8522                }
 8523
 8524                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8525
 8526                let row = snapshot
 8527                    .buffer_snapshot
 8528                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8529                    .1
 8530                    .start
 8531                    .row;
 8532
 8533                let context_range =
 8534                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8535                Some((
 8536                    (runnable.buffer_id, row),
 8537                    RunnableTasks {
 8538                        templates: tasks,
 8539                        offset: MultiBufferOffset(runnable.run_range.start),
 8540                        context_range,
 8541                        column: point.column,
 8542                        extra_variables: runnable.extra_captures,
 8543                    },
 8544                ))
 8545            })
 8546            .collect()
 8547    }
 8548
 8549    fn templates_with_tags(
 8550        project: &Model<Project>,
 8551        runnable: &mut Runnable,
 8552        cx: &WindowContext<'_>,
 8553    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8554        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8555            let (worktree_id, file) = project
 8556                .buffer_for_id(runnable.buffer, cx)
 8557                .and_then(|buffer| buffer.read(cx).file())
 8558                .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
 8559                .unzip();
 8560
 8561            (project.task_inventory().clone(), worktree_id, file)
 8562        });
 8563
 8564        let inventory = inventory.read(cx);
 8565        let tags = mem::take(&mut runnable.tags);
 8566        let mut tags: Vec<_> = tags
 8567            .into_iter()
 8568            .flat_map(|tag| {
 8569                let tag = tag.0.clone();
 8570                inventory
 8571                    .list_tasks(
 8572                        file.clone(),
 8573                        Some(runnable.language.clone()),
 8574                        worktree_id,
 8575                        cx,
 8576                    )
 8577                    .into_iter()
 8578                    .filter(move |(_, template)| {
 8579                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8580                    })
 8581            })
 8582            .sorted_by_key(|(kind, _)| kind.to_owned())
 8583            .collect();
 8584        if let Some((leading_tag_source, _)) = tags.first() {
 8585            // Strongest source wins; if we have worktree tag binding, prefer that to
 8586            // global and language bindings;
 8587            // if we have a global binding, prefer that to language binding.
 8588            let first_mismatch = tags
 8589                .iter()
 8590                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8591            if let Some(index) = first_mismatch {
 8592                tags.truncate(index);
 8593            }
 8594        }
 8595
 8596        tags
 8597    }
 8598
 8599    pub fn move_to_enclosing_bracket(
 8600        &mut self,
 8601        _: &MoveToEnclosingBracket,
 8602        cx: &mut ViewContext<Self>,
 8603    ) {
 8604        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8605            s.move_offsets_with(|snapshot, selection| {
 8606                let Some(enclosing_bracket_ranges) =
 8607                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8608                else {
 8609                    return;
 8610                };
 8611
 8612                let mut best_length = usize::MAX;
 8613                let mut best_inside = false;
 8614                let mut best_in_bracket_range = false;
 8615                let mut best_destination = None;
 8616                for (open, close) in enclosing_bracket_ranges {
 8617                    let close = close.to_inclusive();
 8618                    let length = close.end() - open.start;
 8619                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8620                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8621                        || close.contains(&selection.head());
 8622
 8623                    // If best is next to a bracket and current isn't, skip
 8624                    if !in_bracket_range && best_in_bracket_range {
 8625                        continue;
 8626                    }
 8627
 8628                    // Prefer smaller lengths unless best is inside and current isn't
 8629                    if length > best_length && (best_inside || !inside) {
 8630                        continue;
 8631                    }
 8632
 8633                    best_length = length;
 8634                    best_inside = inside;
 8635                    best_in_bracket_range = in_bracket_range;
 8636                    best_destination = Some(
 8637                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8638                            if inside {
 8639                                open.end
 8640                            } else {
 8641                                open.start
 8642                            }
 8643                        } else {
 8644                            if inside {
 8645                                *close.start()
 8646                            } else {
 8647                                *close.end()
 8648                            }
 8649                        },
 8650                    );
 8651                }
 8652
 8653                if let Some(destination) = best_destination {
 8654                    selection.collapse_to(destination, SelectionGoal::None);
 8655                }
 8656            })
 8657        });
 8658    }
 8659
 8660    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 8661        self.end_selection(cx);
 8662        self.selection_history.mode = SelectionHistoryMode::Undoing;
 8663        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 8664            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8665            self.select_next_state = entry.select_next_state;
 8666            self.select_prev_state = entry.select_prev_state;
 8667            self.add_selections_state = entry.add_selections_state;
 8668            self.request_autoscroll(Autoscroll::newest(), cx);
 8669        }
 8670        self.selection_history.mode = SelectionHistoryMode::Normal;
 8671    }
 8672
 8673    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 8674        self.end_selection(cx);
 8675        self.selection_history.mode = SelectionHistoryMode::Redoing;
 8676        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 8677            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8678            self.select_next_state = entry.select_next_state;
 8679            self.select_prev_state = entry.select_prev_state;
 8680            self.add_selections_state = entry.add_selections_state;
 8681            self.request_autoscroll(Autoscroll::newest(), cx);
 8682        }
 8683        self.selection_history.mode = SelectionHistoryMode::Normal;
 8684    }
 8685
 8686    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 8687        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 8688    }
 8689
 8690    pub fn expand_excerpts_down(
 8691        &mut self,
 8692        action: &ExpandExcerptsDown,
 8693        cx: &mut ViewContext<Self>,
 8694    ) {
 8695        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 8696    }
 8697
 8698    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 8699        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 8700    }
 8701
 8702    pub fn expand_excerpts_for_direction(
 8703        &mut self,
 8704        lines: u32,
 8705        direction: ExpandExcerptDirection,
 8706        cx: &mut ViewContext<Self>,
 8707    ) {
 8708        let selections = self.selections.disjoint_anchors();
 8709
 8710        let lines = if lines == 0 {
 8711            EditorSettings::get_global(cx).expand_excerpt_lines
 8712        } else {
 8713            lines
 8714        };
 8715
 8716        self.buffer.update(cx, |buffer, cx| {
 8717            buffer.expand_excerpts(
 8718                selections
 8719                    .into_iter()
 8720                    .map(|selection| selection.head().excerpt_id)
 8721                    .dedup(),
 8722                lines,
 8723                direction,
 8724                cx,
 8725            )
 8726        })
 8727    }
 8728
 8729    pub fn expand_excerpt(
 8730        &mut self,
 8731        excerpt: ExcerptId,
 8732        direction: ExpandExcerptDirection,
 8733        cx: &mut ViewContext<Self>,
 8734    ) {
 8735        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 8736        self.buffer.update(cx, |buffer, cx| {
 8737            buffer.expand_excerpts([excerpt], lines, direction, cx)
 8738        })
 8739    }
 8740
 8741    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8742        self.go_to_diagnostic_impl(Direction::Next, cx)
 8743    }
 8744
 8745    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8746        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8747    }
 8748
 8749    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8750        let buffer = self.buffer.read(cx).snapshot(cx);
 8751        let selection = self.selections.newest::<usize>(cx);
 8752
 8753        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8754        if direction == Direction::Next {
 8755            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8756                let (group_id, jump_to) = popover.activation_info();
 8757                if self.activate_diagnostics(group_id, cx) {
 8758                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8759                        let mut new_selection = s.newest_anchor().clone();
 8760                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 8761                        s.select_anchors(vec![new_selection.clone()]);
 8762                    });
 8763                }
 8764                return;
 8765            }
 8766        }
 8767
 8768        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 8769            active_diagnostics
 8770                .primary_range
 8771                .to_offset(&buffer)
 8772                .to_inclusive()
 8773        });
 8774        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 8775            if active_primary_range.contains(&selection.head()) {
 8776                *active_primary_range.start()
 8777            } else {
 8778                selection.head()
 8779            }
 8780        } else {
 8781            selection.head()
 8782        };
 8783        let snapshot = self.snapshot(cx);
 8784        loop {
 8785            let diagnostics = if direction == Direction::Prev {
 8786                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 8787            } else {
 8788                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 8789            }
 8790            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 8791            let group = diagnostics
 8792                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 8793                // be sorted in a stable way
 8794                // skip until we are at current active diagnostic, if it exists
 8795                .skip_while(|entry| {
 8796                    (match direction {
 8797                        Direction::Prev => entry.range.start >= search_start,
 8798                        Direction::Next => entry.range.start <= search_start,
 8799                    }) && self
 8800                        .active_diagnostics
 8801                        .as_ref()
 8802                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 8803                })
 8804                .find_map(|entry| {
 8805                    if entry.diagnostic.is_primary
 8806                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 8807                        && !entry.range.is_empty()
 8808                        // if we match with the active diagnostic, skip it
 8809                        && Some(entry.diagnostic.group_id)
 8810                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 8811                    {
 8812                        Some((entry.range, entry.diagnostic.group_id))
 8813                    } else {
 8814                        None
 8815                    }
 8816                });
 8817
 8818            if let Some((primary_range, group_id)) = group {
 8819                if self.activate_diagnostics(group_id, cx) {
 8820                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8821                        s.select(vec![Selection {
 8822                            id: selection.id,
 8823                            start: primary_range.start,
 8824                            end: primary_range.start,
 8825                            reversed: false,
 8826                            goal: SelectionGoal::None,
 8827                        }]);
 8828                    });
 8829                }
 8830                break;
 8831            } else {
 8832                // Cycle around to the start of the buffer, potentially moving back to the start of
 8833                // the currently active diagnostic.
 8834                active_primary_range.take();
 8835                if direction == Direction::Prev {
 8836                    if search_start == buffer.len() {
 8837                        break;
 8838                    } else {
 8839                        search_start = buffer.len();
 8840                    }
 8841                } else if search_start == 0 {
 8842                    break;
 8843                } else {
 8844                    search_start = 0;
 8845                }
 8846            }
 8847        }
 8848    }
 8849
 8850    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 8851        let snapshot = self
 8852            .display_map
 8853            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8854        let selection = self.selections.newest::<Point>(cx);
 8855
 8856        if !self.seek_in_direction(
 8857            &snapshot,
 8858            selection.head(),
 8859            false,
 8860            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8861                MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
 8862            ),
 8863            cx,
 8864        ) {
 8865            let wrapped_point = Point::zero();
 8866            self.seek_in_direction(
 8867                &snapshot,
 8868                wrapped_point,
 8869                true,
 8870                snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8871                    MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 8872                ),
 8873                cx,
 8874            );
 8875        }
 8876    }
 8877
 8878    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 8879        let snapshot = self
 8880            .display_map
 8881            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8882        let selection = self.selections.newest::<Point>(cx);
 8883
 8884        if !self.seek_in_direction(
 8885            &snapshot,
 8886            selection.head(),
 8887            false,
 8888            snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8889                MultiBufferRow(0)..MultiBufferRow(selection.head().row),
 8890            ),
 8891            cx,
 8892        ) {
 8893            let wrapped_point = snapshot.buffer_snapshot.max_point();
 8894            self.seek_in_direction(
 8895                &snapshot,
 8896                wrapped_point,
 8897                true,
 8898                snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8899                    MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
 8900                ),
 8901                cx,
 8902            );
 8903        }
 8904    }
 8905
 8906    fn seek_in_direction(
 8907        &mut self,
 8908        snapshot: &DisplaySnapshot,
 8909        initial_point: Point,
 8910        is_wrapped: bool,
 8911        hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
 8912        cx: &mut ViewContext<Editor>,
 8913    ) -> bool {
 8914        let display_point = initial_point.to_display_point(snapshot);
 8915        let mut hunks = hunks
 8916            .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
 8917            .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
 8918            .dedup();
 8919
 8920        if let Some(hunk) = hunks.next() {
 8921            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8922                let row = hunk.start_display_row();
 8923                let point = DisplayPoint::new(row, 0);
 8924                s.select_display_ranges([point..point]);
 8925            });
 8926
 8927            true
 8928        } else {
 8929            false
 8930        }
 8931    }
 8932
 8933    pub fn go_to_definition(
 8934        &mut self,
 8935        _: &GoToDefinition,
 8936        cx: &mut ViewContext<Self>,
 8937    ) -> Task<Result<bool>> {
 8938        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
 8939    }
 8940
 8941    pub fn go_to_implementation(
 8942        &mut self,
 8943        _: &GoToImplementation,
 8944        cx: &mut ViewContext<Self>,
 8945    ) -> Task<Result<bool>> {
 8946        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 8947    }
 8948
 8949    pub fn go_to_implementation_split(
 8950        &mut self,
 8951        _: &GoToImplementationSplit,
 8952        cx: &mut ViewContext<Self>,
 8953    ) -> Task<Result<bool>> {
 8954        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 8955    }
 8956
 8957    pub fn go_to_type_definition(
 8958        &mut self,
 8959        _: &GoToTypeDefinition,
 8960        cx: &mut ViewContext<Self>,
 8961    ) -> Task<Result<bool>> {
 8962        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 8963    }
 8964
 8965    pub fn go_to_definition_split(
 8966        &mut self,
 8967        _: &GoToDefinitionSplit,
 8968        cx: &mut ViewContext<Self>,
 8969    ) -> Task<Result<bool>> {
 8970        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 8971    }
 8972
 8973    pub fn go_to_type_definition_split(
 8974        &mut self,
 8975        _: &GoToTypeDefinitionSplit,
 8976        cx: &mut ViewContext<Self>,
 8977    ) -> Task<Result<bool>> {
 8978        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 8979    }
 8980
 8981    fn go_to_definition_of_kind(
 8982        &mut self,
 8983        kind: GotoDefinitionKind,
 8984        split: bool,
 8985        cx: &mut ViewContext<Self>,
 8986    ) -> Task<Result<bool>> {
 8987        let Some(workspace) = self.workspace() else {
 8988            return Task::ready(Ok(false));
 8989        };
 8990        let buffer = self.buffer.read(cx);
 8991        let head = self.selections.newest::<usize>(cx).head();
 8992        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 8993            text_anchor
 8994        } else {
 8995            return Task::ready(Ok(false));
 8996        };
 8997
 8998        let project = workspace.read(cx).project().clone();
 8999        let definitions = project.update(cx, |project, cx| match kind {
 9000            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 9001            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 9002            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 9003        });
 9004
 9005        cx.spawn(|editor, mut cx| async move {
 9006            let definitions = definitions.await?;
 9007            let navigated = editor
 9008                .update(&mut cx, |editor, cx| {
 9009                    editor.navigate_to_hover_links(
 9010                        Some(kind),
 9011                        definitions
 9012                            .into_iter()
 9013                            .filter(|location| {
 9014                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9015                            })
 9016                            .map(HoverLink::Text)
 9017                            .collect::<Vec<_>>(),
 9018                        split,
 9019                        cx,
 9020                    )
 9021                })?
 9022                .await?;
 9023            anyhow::Ok(navigated)
 9024        })
 9025    }
 9026
 9027    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9028        let position = self.selections.newest_anchor().head();
 9029        let Some((buffer, buffer_position)) =
 9030            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9031        else {
 9032            return;
 9033        };
 9034
 9035        cx.spawn(|editor, mut cx| async move {
 9036            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9037                editor.update(&mut cx, |_, cx| {
 9038                    cx.open_url(&url);
 9039                })
 9040            } else {
 9041                Ok(())
 9042            }
 9043        })
 9044        .detach();
 9045    }
 9046
 9047    pub(crate) fn navigate_to_hover_links(
 9048        &mut self,
 9049        kind: Option<GotoDefinitionKind>,
 9050        mut definitions: Vec<HoverLink>,
 9051        split: bool,
 9052        cx: &mut ViewContext<Editor>,
 9053    ) -> Task<Result<bool>> {
 9054        // If there is one definition, just open it directly
 9055        if definitions.len() == 1 {
 9056            let definition = definitions.pop().unwrap();
 9057            let target_task = match definition {
 9058                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9059                HoverLink::InlayHint(lsp_location, server_id) => {
 9060                    self.compute_target_location(lsp_location, server_id, cx)
 9061                }
 9062                HoverLink::Url(url) => {
 9063                    cx.open_url(&url);
 9064                    Task::ready(Ok(None))
 9065                }
 9066            };
 9067            cx.spawn(|editor, mut cx| async move {
 9068                let target = target_task.await.context("target resolution task")?;
 9069                if let Some(target) = target {
 9070                    editor.update(&mut cx, |editor, cx| {
 9071                        let Some(workspace) = editor.workspace() else {
 9072                            return false;
 9073                        };
 9074                        let pane = workspace.read(cx).active_pane().clone();
 9075
 9076                        let range = target.range.to_offset(target.buffer.read(cx));
 9077                        let range = editor.range_for_match(&range);
 9078
 9079                        /// If select range has more than one line, we
 9080                        /// just point the cursor to range.start.
 9081                        fn check_multiline_range(
 9082                            buffer: &Buffer,
 9083                            range: Range<usize>,
 9084                        ) -> Range<usize> {
 9085                            if buffer.offset_to_point(range.start).row
 9086                                == buffer.offset_to_point(range.end).row
 9087                            {
 9088                                range
 9089                            } else {
 9090                                range.start..range.start
 9091                            }
 9092                        }
 9093
 9094                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9095                            let buffer = target.buffer.read(cx);
 9096                            let range = check_multiline_range(buffer, range);
 9097                            editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 9098                                s.select_ranges([range]);
 9099                            });
 9100                        } else {
 9101                            cx.window_context().defer(move |cx| {
 9102                                let target_editor: View<Self> =
 9103                                    workspace.update(cx, |workspace, cx| {
 9104                                        let pane = if split {
 9105                                            workspace.adjacent_pane(cx)
 9106                                        } else {
 9107                                            workspace.active_pane().clone()
 9108                                        };
 9109
 9110                                        workspace.open_project_item(
 9111                                            pane,
 9112                                            target.buffer.clone(),
 9113                                            true,
 9114                                            true,
 9115                                            cx,
 9116                                        )
 9117                                    });
 9118                                target_editor.update(cx, |target_editor, cx| {
 9119                                    // When selecting a definition in a different buffer, disable the nav history
 9120                                    // to avoid creating a history entry at the previous cursor location.
 9121                                    pane.update(cx, |pane, _| pane.disable_history());
 9122                                    let buffer = target.buffer.read(cx);
 9123                                    let range = check_multiline_range(buffer, range);
 9124                                    target_editor.change_selections(
 9125                                        Some(Autoscroll::focused()),
 9126                                        cx,
 9127                                        |s| {
 9128                                            s.select_ranges([range]);
 9129                                        },
 9130                                    );
 9131                                    pane.update(cx, |pane, _| pane.enable_history());
 9132                                });
 9133                            });
 9134                        }
 9135                        true
 9136                    })
 9137                } else {
 9138                    Ok(false)
 9139                }
 9140            })
 9141        } else if !definitions.is_empty() {
 9142            let replica_id = self.replica_id(cx);
 9143            cx.spawn(|editor, mut cx| async move {
 9144                let (title, location_tasks, workspace) = editor
 9145                    .update(&mut cx, |editor, cx| {
 9146                        let tab_kind = match kind {
 9147                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9148                            _ => "Definitions",
 9149                        };
 9150                        let title = definitions
 9151                            .iter()
 9152                            .find_map(|definition| match definition {
 9153                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9154                                    let buffer = origin.buffer.read(cx);
 9155                                    format!(
 9156                                        "{} for {}",
 9157                                        tab_kind,
 9158                                        buffer
 9159                                            .text_for_range(origin.range.clone())
 9160                                            .collect::<String>()
 9161                                    )
 9162                                }),
 9163                                HoverLink::InlayHint(_, _) => None,
 9164                                HoverLink::Url(_) => None,
 9165                            })
 9166                            .unwrap_or(tab_kind.to_string());
 9167                        let location_tasks = definitions
 9168                            .into_iter()
 9169                            .map(|definition| match definition {
 9170                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9171                                HoverLink::InlayHint(lsp_location, server_id) => {
 9172                                    editor.compute_target_location(lsp_location, server_id, cx)
 9173                                }
 9174                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9175                            })
 9176                            .collect::<Vec<_>>();
 9177                        (title, location_tasks, editor.workspace().clone())
 9178                    })
 9179                    .context("location tasks preparation")?;
 9180
 9181                let locations = futures::future::join_all(location_tasks)
 9182                    .await
 9183                    .into_iter()
 9184                    .filter_map(|location| location.transpose())
 9185                    .collect::<Result<_>>()
 9186                    .context("location tasks")?;
 9187
 9188                let Some(workspace) = workspace else {
 9189                    return Ok(false);
 9190                };
 9191                let opened = workspace
 9192                    .update(&mut cx, |workspace, cx| {
 9193                        Self::open_locations_in_multibuffer(
 9194                            workspace, locations, replica_id, title, split, cx,
 9195                        )
 9196                    })
 9197                    .ok();
 9198
 9199                anyhow::Ok(opened.is_some())
 9200            })
 9201        } else {
 9202            Task::ready(Ok(false))
 9203        }
 9204    }
 9205
 9206    fn compute_target_location(
 9207        &self,
 9208        lsp_location: lsp::Location,
 9209        server_id: LanguageServerId,
 9210        cx: &mut ViewContext<Editor>,
 9211    ) -> Task<anyhow::Result<Option<Location>>> {
 9212        let Some(project) = self.project.clone() else {
 9213            return Task::Ready(Some(Ok(None)));
 9214        };
 9215
 9216        cx.spawn(move |editor, mut cx| async move {
 9217            let location_task = editor.update(&mut cx, |editor, cx| {
 9218                project.update(cx, |project, cx| {
 9219                    let language_server_name =
 9220                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 9221                            project
 9222                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 9223                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 9224                        });
 9225                    language_server_name.map(|language_server_name| {
 9226                        project.open_local_buffer_via_lsp(
 9227                            lsp_location.uri.clone(),
 9228                            server_id,
 9229                            language_server_name,
 9230                            cx,
 9231                        )
 9232                    })
 9233                })
 9234            })?;
 9235            let location = match location_task {
 9236                Some(task) => Some({
 9237                    let target_buffer_handle = task.await.context("open local buffer")?;
 9238                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9239                        let target_start = target_buffer
 9240                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9241                        let target_end = target_buffer
 9242                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9243                        target_buffer.anchor_after(target_start)
 9244                            ..target_buffer.anchor_before(target_end)
 9245                    })?;
 9246                    Location {
 9247                        buffer: target_buffer_handle,
 9248                        range,
 9249                    }
 9250                }),
 9251                None => None,
 9252            };
 9253            Ok(location)
 9254        })
 9255    }
 9256
 9257    pub fn find_all_references(
 9258        &mut self,
 9259        _: &FindAllReferences,
 9260        cx: &mut ViewContext<Self>,
 9261    ) -> Option<Task<Result<()>>> {
 9262        let multi_buffer = self.buffer.read(cx);
 9263        let selection = self.selections.newest::<usize>(cx);
 9264        let head = selection.head();
 9265
 9266        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9267        let head_anchor = multi_buffer_snapshot.anchor_at(
 9268            head,
 9269            if head < selection.tail() {
 9270                Bias::Right
 9271            } else {
 9272                Bias::Left
 9273            },
 9274        );
 9275
 9276        match self
 9277            .find_all_references_task_sources
 9278            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9279        {
 9280            Ok(_) => {
 9281                log::info!(
 9282                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9283                );
 9284                return None;
 9285            }
 9286            Err(i) => {
 9287                self.find_all_references_task_sources.insert(i, head_anchor);
 9288            }
 9289        }
 9290
 9291        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9292        let replica_id = self.replica_id(cx);
 9293        let workspace = self.workspace()?;
 9294        let project = workspace.read(cx).project().clone();
 9295        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9296        Some(cx.spawn(|editor, mut cx| async move {
 9297            let _cleanup = defer({
 9298                let mut cx = cx.clone();
 9299                move || {
 9300                    let _ = editor.update(&mut cx, |editor, _| {
 9301                        if let Ok(i) =
 9302                            editor
 9303                                .find_all_references_task_sources
 9304                                .binary_search_by(|anchor| {
 9305                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9306                                })
 9307                        {
 9308                            editor.find_all_references_task_sources.remove(i);
 9309                        }
 9310                    });
 9311                }
 9312            });
 9313
 9314            let locations = references.await?;
 9315            if locations.is_empty() {
 9316                return anyhow::Ok(());
 9317            }
 9318
 9319            workspace.update(&mut cx, |workspace, cx| {
 9320                let title = locations
 9321                    .first()
 9322                    .as_ref()
 9323                    .map(|location| {
 9324                        let buffer = location.buffer.read(cx);
 9325                        format!(
 9326                            "References to `{}`",
 9327                            buffer
 9328                                .text_for_range(location.range.clone())
 9329                                .collect::<String>()
 9330                        )
 9331                    })
 9332                    .unwrap();
 9333                Self::open_locations_in_multibuffer(
 9334                    workspace, locations, replica_id, title, false, cx,
 9335                );
 9336            })
 9337        }))
 9338    }
 9339
 9340    /// Opens a multibuffer with the given project locations in it
 9341    pub fn open_locations_in_multibuffer(
 9342        workspace: &mut Workspace,
 9343        mut locations: Vec<Location>,
 9344        replica_id: ReplicaId,
 9345        title: String,
 9346        split: bool,
 9347        cx: &mut ViewContext<Workspace>,
 9348    ) {
 9349        // If there are multiple definitions, open them in a multibuffer
 9350        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9351        let mut locations = locations.into_iter().peekable();
 9352        let mut ranges_to_highlight = Vec::new();
 9353        let capability = workspace.project().read(cx).capability();
 9354
 9355        let excerpt_buffer = cx.new_model(|cx| {
 9356            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 9357            while let Some(location) = locations.next() {
 9358                let buffer = location.buffer.read(cx);
 9359                let mut ranges_for_buffer = Vec::new();
 9360                let range = location.range.to_offset(buffer);
 9361                ranges_for_buffer.push(range.clone());
 9362
 9363                while let Some(next_location) = locations.peek() {
 9364                    if next_location.buffer == location.buffer {
 9365                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9366                        locations.next();
 9367                    } else {
 9368                        break;
 9369                    }
 9370                }
 9371
 9372                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9373                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9374                    location.buffer.clone(),
 9375                    ranges_for_buffer,
 9376                    DEFAULT_MULTIBUFFER_CONTEXT,
 9377                    cx,
 9378                ))
 9379            }
 9380
 9381            multibuffer.with_title(title)
 9382        });
 9383
 9384        let editor = cx.new_view(|cx| {
 9385            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9386        });
 9387        editor.update(cx, |editor, cx| {
 9388            if let Some(first_range) = ranges_to_highlight.first() {
 9389                editor.change_selections(None, cx, |selections| {
 9390                    selections.clear_disjoint();
 9391                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9392                });
 9393            }
 9394            editor.highlight_background::<Self>(
 9395                &ranges_to_highlight,
 9396                |theme| theme.editor_highlighted_line_background,
 9397                cx,
 9398            );
 9399        });
 9400
 9401        let item = Box::new(editor);
 9402        let item_id = item.item_id();
 9403
 9404        if split {
 9405            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9406        } else {
 9407            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9408                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9409                    pane.close_current_preview_item(cx)
 9410                } else {
 9411                    None
 9412                }
 9413            });
 9414            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9415        }
 9416        workspace.active_pane().update(cx, |pane, cx| {
 9417            pane.set_preview_item_id(Some(item_id), cx);
 9418        });
 9419    }
 9420
 9421    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9422        use language::ToOffset as _;
 9423
 9424        let project = self.project.clone()?;
 9425        let selection = self.selections.newest_anchor().clone();
 9426        let (cursor_buffer, cursor_buffer_position) = self
 9427            .buffer
 9428            .read(cx)
 9429            .text_anchor_for_position(selection.head(), cx)?;
 9430        let (tail_buffer, cursor_buffer_position_end) = self
 9431            .buffer
 9432            .read(cx)
 9433            .text_anchor_for_position(selection.tail(), cx)?;
 9434        if tail_buffer != cursor_buffer {
 9435            return None;
 9436        }
 9437
 9438        let snapshot = cursor_buffer.read(cx).snapshot();
 9439        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9440        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9441        let prepare_rename = project.update(cx, |project, cx| {
 9442            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 9443        });
 9444        drop(snapshot);
 9445
 9446        Some(cx.spawn(|this, mut cx| async move {
 9447            let rename_range = if let Some(range) = prepare_rename.await? {
 9448                Some(range)
 9449            } else {
 9450                this.update(&mut cx, |this, cx| {
 9451                    let buffer = this.buffer.read(cx).snapshot(cx);
 9452                    let mut buffer_highlights = this
 9453                        .document_highlights_for_position(selection.head(), &buffer)
 9454                        .filter(|highlight| {
 9455                            highlight.start.excerpt_id == selection.head().excerpt_id
 9456                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9457                        });
 9458                    buffer_highlights
 9459                        .next()
 9460                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9461                })?
 9462            };
 9463            if let Some(rename_range) = rename_range {
 9464                this.update(&mut cx, |this, cx| {
 9465                    let snapshot = cursor_buffer.read(cx).snapshot();
 9466                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9467                    let cursor_offset_in_rename_range =
 9468                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9469                    let cursor_offset_in_rename_range_end =
 9470                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9471
 9472                    this.take_rename(false, cx);
 9473                    let buffer = this.buffer.read(cx).read(cx);
 9474                    let cursor_offset = selection.head().to_offset(&buffer);
 9475                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9476                    let rename_end = rename_start + rename_buffer_range.len();
 9477                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9478                    let mut old_highlight_id = None;
 9479                    let old_name: Arc<str> = buffer
 9480                        .chunks(rename_start..rename_end, true)
 9481                        .map(|chunk| {
 9482                            if old_highlight_id.is_none() {
 9483                                old_highlight_id = chunk.syntax_highlight_id;
 9484                            }
 9485                            chunk.text
 9486                        })
 9487                        .collect::<String>()
 9488                        .into();
 9489
 9490                    drop(buffer);
 9491
 9492                    // Position the selection in the rename editor so that it matches the current selection.
 9493                    this.show_local_selections = false;
 9494                    let rename_editor = cx.new_view(|cx| {
 9495                        let mut editor = Editor::single_line(cx);
 9496                        editor.buffer.update(cx, |buffer, cx| {
 9497                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9498                        });
 9499                        let rename_selection_range = match cursor_offset_in_rename_range
 9500                            .cmp(&cursor_offset_in_rename_range_end)
 9501                        {
 9502                            Ordering::Equal => {
 9503                                editor.select_all(&SelectAll, cx);
 9504                                return editor;
 9505                            }
 9506                            Ordering::Less => {
 9507                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9508                            }
 9509                            Ordering::Greater => {
 9510                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9511                            }
 9512                        };
 9513                        if rename_selection_range.end > old_name.len() {
 9514                            editor.select_all(&SelectAll, cx);
 9515                        } else {
 9516                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9517                                s.select_ranges([rename_selection_range]);
 9518                            });
 9519                        }
 9520                        editor
 9521                    });
 9522                    cx.subscribe(&rename_editor, |_, _, e, cx| match e {
 9523                        EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
 9524                        _ => {}
 9525                    })
 9526                    .detach();
 9527
 9528                    let write_highlights =
 9529                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9530                    let read_highlights =
 9531                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9532                    let ranges = write_highlights
 9533                        .iter()
 9534                        .flat_map(|(_, ranges)| ranges.iter())
 9535                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9536                        .cloned()
 9537                        .collect();
 9538
 9539                    this.highlight_text::<Rename>(
 9540                        ranges,
 9541                        HighlightStyle {
 9542                            fade_out: Some(0.6),
 9543                            ..Default::default()
 9544                        },
 9545                        cx,
 9546                    );
 9547                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9548                    cx.focus(&rename_focus_handle);
 9549                    let block_id = this.insert_blocks(
 9550                        [BlockProperties {
 9551                            style: BlockStyle::Flex,
 9552                            position: range.start,
 9553                            height: 1,
 9554                            render: Box::new({
 9555                                let rename_editor = rename_editor.clone();
 9556                                move |cx: &mut BlockContext| {
 9557                                    let mut text_style = cx.editor_style.text.clone();
 9558                                    if let Some(highlight_style) = old_highlight_id
 9559                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 9560                                    {
 9561                                        text_style = text_style.highlight(highlight_style);
 9562                                    }
 9563                                    div()
 9564                                        .pl(cx.anchor_x)
 9565                                        .child(EditorElement::new(
 9566                                            &rename_editor,
 9567                                            EditorStyle {
 9568                                                background: cx.theme().system().transparent,
 9569                                                local_player: cx.editor_style.local_player,
 9570                                                text: text_style,
 9571                                                scrollbar_width: cx.editor_style.scrollbar_width,
 9572                                                syntax: cx.editor_style.syntax.clone(),
 9573                                                status: cx.editor_style.status.clone(),
 9574                                                inlay_hints_style: HighlightStyle {
 9575                                                    color: Some(cx.theme().status().hint),
 9576                                                    font_weight: Some(FontWeight::BOLD),
 9577                                                    ..HighlightStyle::default()
 9578                                                },
 9579                                                suggestions_style: HighlightStyle {
 9580                                                    color: Some(cx.theme().status().predictive),
 9581                                                    ..HighlightStyle::default()
 9582                                                },
 9583                                            },
 9584                                        ))
 9585                                        .into_any_element()
 9586                                }
 9587                            }),
 9588                            disposition: BlockDisposition::Below,
 9589                        }],
 9590                        Some(Autoscroll::fit()),
 9591                        cx,
 9592                    )[0];
 9593                    this.pending_rename = Some(RenameState {
 9594                        range,
 9595                        old_name,
 9596                        editor: rename_editor,
 9597                        block_id,
 9598                    });
 9599                })?;
 9600            }
 9601
 9602            Ok(())
 9603        }))
 9604    }
 9605
 9606    pub fn confirm_rename(
 9607        &mut self,
 9608        _: &ConfirmRename,
 9609        cx: &mut ViewContext<Self>,
 9610    ) -> Option<Task<Result<()>>> {
 9611        let rename = self.take_rename(false, cx)?;
 9612        let workspace = self.workspace()?;
 9613        let (start_buffer, start) = self
 9614            .buffer
 9615            .read(cx)
 9616            .text_anchor_for_position(rename.range.start, cx)?;
 9617        let (end_buffer, end) = self
 9618            .buffer
 9619            .read(cx)
 9620            .text_anchor_for_position(rename.range.end, cx)?;
 9621        if start_buffer != end_buffer {
 9622            return None;
 9623        }
 9624
 9625        let buffer = start_buffer;
 9626        let range = start..end;
 9627        let old_name = rename.old_name;
 9628        let new_name = rename.editor.read(cx).text(cx);
 9629
 9630        let rename = workspace
 9631            .read(cx)
 9632            .project()
 9633            .clone()
 9634            .update(cx, |project, cx| {
 9635                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 9636            });
 9637        let workspace = workspace.downgrade();
 9638
 9639        Some(cx.spawn(|editor, mut cx| async move {
 9640            let project_transaction = rename.await?;
 9641            Self::open_project_transaction(
 9642                &editor,
 9643                workspace,
 9644                project_transaction,
 9645                format!("Rename: {}{}", old_name, new_name),
 9646                cx.clone(),
 9647            )
 9648            .await?;
 9649
 9650            editor.update(&mut cx, |editor, cx| {
 9651                editor.refresh_document_highlights(cx);
 9652            })?;
 9653            Ok(())
 9654        }))
 9655    }
 9656
 9657    fn take_rename(
 9658        &mut self,
 9659        moving_cursor: bool,
 9660        cx: &mut ViewContext<Self>,
 9661    ) -> Option<RenameState> {
 9662        let rename = self.pending_rename.take()?;
 9663        if rename.editor.focus_handle(cx).is_focused(cx) {
 9664            cx.focus(&self.focus_handle);
 9665        }
 9666
 9667        self.remove_blocks(
 9668            [rename.block_id].into_iter().collect(),
 9669            Some(Autoscroll::fit()),
 9670            cx,
 9671        );
 9672        self.clear_highlights::<Rename>(cx);
 9673        self.show_local_selections = true;
 9674
 9675        if moving_cursor {
 9676            let rename_editor = rename.editor.read(cx);
 9677            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 9678
 9679            // Update the selection to match the position of the selection inside
 9680            // the rename editor.
 9681            let snapshot = self.buffer.read(cx).read(cx);
 9682            let rename_range = rename.range.to_offset(&snapshot);
 9683            let cursor_in_editor = snapshot
 9684                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 9685                .min(rename_range.end);
 9686            drop(snapshot);
 9687
 9688            self.change_selections(None, cx, |s| {
 9689                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 9690            });
 9691        } else {
 9692            self.refresh_document_highlights(cx);
 9693        }
 9694
 9695        Some(rename)
 9696    }
 9697
 9698    pub fn pending_rename(&self) -> Option<&RenameState> {
 9699        self.pending_rename.as_ref()
 9700    }
 9701
 9702    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9703        let project = match &self.project {
 9704            Some(project) => project.clone(),
 9705            None => return None,
 9706        };
 9707
 9708        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 9709    }
 9710
 9711    fn perform_format(
 9712        &mut self,
 9713        project: Model<Project>,
 9714        trigger: FormatTrigger,
 9715        cx: &mut ViewContext<Self>,
 9716    ) -> Task<Result<()>> {
 9717        let buffer = self.buffer().clone();
 9718        let mut buffers = buffer.read(cx).all_buffers();
 9719        if trigger == FormatTrigger::Save {
 9720            buffers.retain(|buffer| buffer.read(cx).is_dirty());
 9721        }
 9722
 9723        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 9724        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 9725
 9726        cx.spawn(|_, mut cx| async move {
 9727            let transaction = futures::select_biased! {
 9728                () = timeout => {
 9729                    log::warn!("timed out waiting for formatting");
 9730                    None
 9731                }
 9732                transaction = format.log_err().fuse() => transaction,
 9733            };
 9734
 9735            buffer
 9736                .update(&mut cx, |buffer, cx| {
 9737                    if let Some(transaction) = transaction {
 9738                        if !buffer.is_singleton() {
 9739                            buffer.push_transaction(&transaction.0, cx);
 9740                        }
 9741                    }
 9742
 9743                    cx.notify();
 9744                })
 9745                .ok();
 9746
 9747            Ok(())
 9748        })
 9749    }
 9750
 9751    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
 9752        if let Some(project) = self.project.clone() {
 9753            self.buffer.update(cx, |multi_buffer, cx| {
 9754                project.update(cx, |project, cx| {
 9755                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
 9756                });
 9757            })
 9758        }
 9759    }
 9760
 9761    fn cancel_language_server_work(
 9762        &mut self,
 9763        _: &CancelLanguageServerWork,
 9764        cx: &mut ViewContext<Self>,
 9765    ) {
 9766        if let Some(project) = self.project.clone() {
 9767            self.buffer.update(cx, |multi_buffer, cx| {
 9768                project.update(cx, |project, cx| {
 9769                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
 9770                });
 9771            })
 9772        }
 9773    }
 9774
 9775    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 9776        cx.show_character_palette();
 9777    }
 9778
 9779    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
 9780        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
 9781            let buffer = self.buffer.read(cx).snapshot(cx);
 9782            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
 9783            let is_valid = buffer
 9784                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
 9785                .any(|entry| {
 9786                    entry.diagnostic.is_primary
 9787                        && !entry.range.is_empty()
 9788                        && entry.range.start == primary_range_start
 9789                        && entry.diagnostic.message == active_diagnostics.primary_message
 9790                });
 9791
 9792            if is_valid != active_diagnostics.is_valid {
 9793                active_diagnostics.is_valid = is_valid;
 9794                let mut new_styles = HashMap::default();
 9795                for (block_id, diagnostic) in &active_diagnostics.blocks {
 9796                    new_styles.insert(
 9797                        *block_id,
 9798                        (
 9799                            None,
 9800                            diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
 9801                        ),
 9802                    );
 9803                }
 9804                self.display_map.update(cx, |display_map, cx| {
 9805                    display_map.replace_blocks(new_styles, cx)
 9806                });
 9807            }
 9808        }
 9809    }
 9810
 9811    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
 9812        self.dismiss_diagnostics(cx);
 9813        let snapshot = self.snapshot(cx);
 9814        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
 9815            let buffer = self.buffer.read(cx).snapshot(cx);
 9816
 9817            let mut primary_range = None;
 9818            let mut primary_message = None;
 9819            let mut group_end = Point::zero();
 9820            let diagnostic_group = buffer
 9821                .diagnostic_group::<MultiBufferPoint>(group_id)
 9822                .filter_map(|entry| {
 9823                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
 9824                        && (entry.range.start.row == entry.range.end.row
 9825                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
 9826                    {
 9827                        return None;
 9828                    }
 9829                    if entry.range.end > group_end {
 9830                        group_end = entry.range.end;
 9831                    }
 9832                    if entry.diagnostic.is_primary {
 9833                        primary_range = Some(entry.range.clone());
 9834                        primary_message = Some(entry.diagnostic.message.clone());
 9835                    }
 9836                    Some(entry)
 9837                })
 9838                .collect::<Vec<_>>();
 9839            let primary_range = primary_range?;
 9840            let primary_message = primary_message?;
 9841            let primary_range =
 9842                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
 9843
 9844            let blocks = display_map
 9845                .insert_blocks(
 9846                    diagnostic_group.iter().map(|entry| {
 9847                        let diagnostic = entry.diagnostic.clone();
 9848                        let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
 9849                        BlockProperties {
 9850                            style: BlockStyle::Fixed,
 9851                            position: buffer.anchor_after(entry.range.start),
 9852                            height: message_height,
 9853                            render: diagnostic_block_renderer(diagnostic, None, true, true),
 9854                            disposition: BlockDisposition::Below,
 9855                        }
 9856                    }),
 9857                    cx,
 9858                )
 9859                .into_iter()
 9860                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
 9861                .collect();
 9862
 9863            Some(ActiveDiagnosticGroup {
 9864                primary_range,
 9865                primary_message,
 9866                group_id,
 9867                blocks,
 9868                is_valid: true,
 9869            })
 9870        });
 9871        self.active_diagnostics.is_some()
 9872    }
 9873
 9874    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
 9875        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
 9876            self.display_map.update(cx, |display_map, cx| {
 9877                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
 9878            });
 9879            cx.notify();
 9880        }
 9881    }
 9882
 9883    pub fn set_selections_from_remote(
 9884        &mut self,
 9885        selections: Vec<Selection<Anchor>>,
 9886        pending_selection: Option<Selection<Anchor>>,
 9887        cx: &mut ViewContext<Self>,
 9888    ) {
 9889        let old_cursor_position = self.selections.newest_anchor().head();
 9890        self.selections.change_with(cx, |s| {
 9891            s.select_anchors(selections);
 9892            if let Some(pending_selection) = pending_selection {
 9893                s.set_pending(pending_selection, SelectMode::Character);
 9894            } else {
 9895                s.clear_pending();
 9896            }
 9897        });
 9898        self.selections_did_change(false, &old_cursor_position, true, cx);
 9899    }
 9900
 9901    fn push_to_selection_history(&mut self) {
 9902        self.selection_history.push(SelectionHistoryEntry {
 9903            selections: self.selections.disjoint_anchors(),
 9904            select_next_state: self.select_next_state.clone(),
 9905            select_prev_state: self.select_prev_state.clone(),
 9906            add_selections_state: self.add_selections_state.clone(),
 9907        });
 9908    }
 9909
 9910    pub fn transact(
 9911        &mut self,
 9912        cx: &mut ViewContext<Self>,
 9913        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
 9914    ) -> Option<TransactionId> {
 9915        self.start_transaction_at(Instant::now(), cx);
 9916        update(self, cx);
 9917        self.end_transaction_at(Instant::now(), cx)
 9918    }
 9919
 9920    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
 9921        self.end_selection(cx);
 9922        if let Some(tx_id) = self
 9923            .buffer
 9924            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
 9925        {
 9926            self.selection_history
 9927                .insert_transaction(tx_id, self.selections.disjoint_anchors());
 9928            cx.emit(EditorEvent::TransactionBegun {
 9929                transaction_id: tx_id,
 9930            })
 9931        }
 9932    }
 9933
 9934    fn end_transaction_at(
 9935        &mut self,
 9936        now: Instant,
 9937        cx: &mut ViewContext<Self>,
 9938    ) -> Option<TransactionId> {
 9939        if let Some(transaction_id) = self
 9940            .buffer
 9941            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 9942        {
 9943            if let Some((_, end_selections)) =
 9944                self.selection_history.transaction_mut(transaction_id)
 9945            {
 9946                *end_selections = Some(self.selections.disjoint_anchors());
 9947            } else {
 9948                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
 9949            }
 9950
 9951            cx.emit(EditorEvent::Edited { transaction_id });
 9952            Some(transaction_id)
 9953        } else {
 9954            None
 9955        }
 9956    }
 9957
 9958    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
 9959        let mut fold_ranges = Vec::new();
 9960
 9961        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9962
 9963        let selections = self.selections.all_adjusted(cx);
 9964        for selection in selections {
 9965            let range = selection.range().sorted();
 9966            let buffer_start_row = range.start.row;
 9967
 9968            for row in (0..=range.end.row).rev() {
 9969                if let Some((foldable_range, fold_text)) =
 9970                    display_map.foldable_range(MultiBufferRow(row))
 9971                {
 9972                    if foldable_range.end.row >= buffer_start_row {
 9973                        fold_ranges.push((foldable_range, fold_text));
 9974                        if row <= range.start.row {
 9975                            break;
 9976                        }
 9977                    }
 9978                }
 9979            }
 9980        }
 9981
 9982        self.fold_ranges(fold_ranges, true, cx);
 9983    }
 9984
 9985    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
 9986        let buffer_row = fold_at.buffer_row;
 9987        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9988
 9989        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
 9990            let autoscroll = self
 9991                .selections
 9992                .all::<Point>(cx)
 9993                .iter()
 9994                .any(|selection| fold_range.overlaps(&selection.range()));
 9995
 9996            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
 9997        }
 9998    }
 9999
10000    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10001        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10002        let buffer = &display_map.buffer_snapshot;
10003        let selections = self.selections.all::<Point>(cx);
10004        let ranges = selections
10005            .iter()
10006            .map(|s| {
10007                let range = s.display_range(&display_map).sorted();
10008                let mut start = range.start.to_point(&display_map);
10009                let mut end = range.end.to_point(&display_map);
10010                start.column = 0;
10011                end.column = buffer.line_len(MultiBufferRow(end.row));
10012                start..end
10013            })
10014            .collect::<Vec<_>>();
10015
10016        self.unfold_ranges(ranges, true, true, cx);
10017    }
10018
10019    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10020        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10021
10022        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10023            ..Point::new(
10024                unfold_at.buffer_row.0,
10025                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10026            );
10027
10028        let autoscroll = self
10029            .selections
10030            .all::<Point>(cx)
10031            .iter()
10032            .any(|selection| selection.range().overlaps(&intersection_range));
10033
10034        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10035    }
10036
10037    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10038        let selections = self.selections.all::<Point>(cx);
10039        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10040        let line_mode = self.selections.line_mode;
10041        let ranges = selections.into_iter().map(|s| {
10042            if line_mode {
10043                let start = Point::new(s.start.row, 0);
10044                let end = Point::new(
10045                    s.end.row,
10046                    display_map
10047                        .buffer_snapshot
10048                        .line_len(MultiBufferRow(s.end.row)),
10049                );
10050                (start..end, display_map.fold_placeholder.clone())
10051            } else {
10052                (s.start..s.end, display_map.fold_placeholder.clone())
10053            }
10054        });
10055        self.fold_ranges(ranges, true, cx);
10056    }
10057
10058    pub fn fold_ranges<T: ToOffset + Clone>(
10059        &mut self,
10060        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10061        auto_scroll: bool,
10062        cx: &mut ViewContext<Self>,
10063    ) {
10064        let mut fold_ranges = Vec::new();
10065        let mut buffers_affected = HashMap::default();
10066        let multi_buffer = self.buffer().read(cx);
10067        for (fold_range, fold_text) in ranges {
10068            if let Some((_, buffer, _)) =
10069                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10070            {
10071                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10072            };
10073            fold_ranges.push((fold_range, fold_text));
10074        }
10075
10076        let mut ranges = fold_ranges.into_iter().peekable();
10077        if ranges.peek().is_some() {
10078            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10079
10080            if auto_scroll {
10081                self.request_autoscroll(Autoscroll::fit(), cx);
10082            }
10083
10084            for buffer in buffers_affected.into_values() {
10085                self.sync_expanded_diff_hunks(buffer, cx);
10086            }
10087
10088            cx.notify();
10089
10090            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10091                // Clear diagnostics block when folding a range that contains it.
10092                let snapshot = self.snapshot(cx);
10093                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10094                    drop(snapshot);
10095                    self.active_diagnostics = Some(active_diagnostics);
10096                    self.dismiss_diagnostics(cx);
10097                } else {
10098                    self.active_diagnostics = Some(active_diagnostics);
10099                }
10100            }
10101
10102            self.scrollbar_marker_state.dirty = true;
10103        }
10104    }
10105
10106    pub fn unfold_ranges<T: ToOffset + Clone>(
10107        &mut self,
10108        ranges: impl IntoIterator<Item = Range<T>>,
10109        inclusive: bool,
10110        auto_scroll: bool,
10111        cx: &mut ViewContext<Self>,
10112    ) {
10113        let mut unfold_ranges = Vec::new();
10114        let mut buffers_affected = HashMap::default();
10115        let multi_buffer = self.buffer().read(cx);
10116        for range in ranges {
10117            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10118                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10119            };
10120            unfold_ranges.push(range);
10121        }
10122
10123        let mut ranges = unfold_ranges.into_iter().peekable();
10124        if ranges.peek().is_some() {
10125            self.display_map
10126                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10127            if auto_scroll {
10128                self.request_autoscroll(Autoscroll::fit(), cx);
10129            }
10130
10131            for buffer in buffers_affected.into_values() {
10132                self.sync_expanded_diff_hunks(buffer, cx);
10133            }
10134
10135            cx.notify();
10136            self.scrollbar_marker_state.dirty = true;
10137            self.active_indent_guides_state.dirty = true;
10138        }
10139    }
10140
10141    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10142        if hovered != self.gutter_hovered {
10143            self.gutter_hovered = hovered;
10144            cx.notify();
10145        }
10146    }
10147
10148    pub fn insert_blocks(
10149        &mut self,
10150        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10151        autoscroll: Option<Autoscroll>,
10152        cx: &mut ViewContext<Self>,
10153    ) -> Vec<BlockId> {
10154        let blocks = self
10155            .display_map
10156            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10157        if let Some(autoscroll) = autoscroll {
10158            self.request_autoscroll(autoscroll, cx);
10159        }
10160        blocks
10161    }
10162
10163    pub fn replace_blocks(
10164        &mut self,
10165        blocks: HashMap<BlockId, (Option<u8>, RenderBlock)>,
10166        autoscroll: Option<Autoscroll>,
10167        cx: &mut ViewContext<Self>,
10168    ) {
10169        self.display_map
10170            .update(cx, |display_map, cx| display_map.replace_blocks(blocks, cx));
10171        if let Some(autoscroll) = autoscroll {
10172            self.request_autoscroll(autoscroll, cx);
10173        }
10174    }
10175
10176    pub fn remove_blocks(
10177        &mut self,
10178        block_ids: HashSet<BlockId>,
10179        autoscroll: Option<Autoscroll>,
10180        cx: &mut ViewContext<Self>,
10181    ) {
10182        self.display_map.update(cx, |display_map, cx| {
10183            display_map.remove_blocks(block_ids, cx)
10184        });
10185        if let Some(autoscroll) = autoscroll {
10186            self.request_autoscroll(autoscroll, cx);
10187        }
10188    }
10189
10190    pub fn row_for_block(
10191        &self,
10192        block_id: BlockId,
10193        cx: &mut ViewContext<Self>,
10194    ) -> Option<DisplayRow> {
10195        self.display_map
10196            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10197    }
10198
10199    pub fn insert_creases(
10200        &mut self,
10201        creases: impl IntoIterator<Item = Crease>,
10202        cx: &mut ViewContext<Self>,
10203    ) -> Vec<CreaseId> {
10204        self.display_map
10205            .update(cx, |map, cx| map.insert_creases(creases, cx))
10206    }
10207
10208    pub fn remove_creases(
10209        &mut self,
10210        ids: impl IntoIterator<Item = CreaseId>,
10211        cx: &mut ViewContext<Self>,
10212    ) {
10213        self.display_map
10214            .update(cx, |map, cx| map.remove_creases(ids, cx));
10215    }
10216
10217    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10218        self.display_map
10219            .update(cx, |map, cx| map.snapshot(cx))
10220            .longest_row()
10221    }
10222
10223    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10224        self.display_map
10225            .update(cx, |map, cx| map.snapshot(cx))
10226            .max_point()
10227    }
10228
10229    pub fn text(&self, cx: &AppContext) -> String {
10230        self.buffer.read(cx).read(cx).text()
10231    }
10232
10233    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10234        let text = self.text(cx);
10235        let text = text.trim();
10236
10237        if text.is_empty() {
10238            return None;
10239        }
10240
10241        Some(text.to_string())
10242    }
10243
10244    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10245        self.transact(cx, |this, cx| {
10246            this.buffer
10247                .read(cx)
10248                .as_singleton()
10249                .expect("you can only call set_text on editors for singleton buffers")
10250                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10251        });
10252    }
10253
10254    pub fn display_text(&self, cx: &mut AppContext) -> String {
10255        self.display_map
10256            .update(cx, |map, cx| map.snapshot(cx))
10257            .text()
10258    }
10259
10260    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10261        let mut wrap_guides = smallvec::smallvec![];
10262
10263        if self.show_wrap_guides == Some(false) {
10264            return wrap_guides;
10265        }
10266
10267        let settings = self.buffer.read(cx).settings_at(0, cx);
10268        if settings.show_wrap_guides {
10269            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10270                wrap_guides.push((soft_wrap as usize, true));
10271            }
10272            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10273        }
10274
10275        wrap_guides
10276    }
10277
10278    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10279        let settings = self.buffer.read(cx).settings_at(0, cx);
10280        let mode = self
10281            .soft_wrap_mode_override
10282            .unwrap_or_else(|| settings.soft_wrap);
10283        match mode {
10284            language_settings::SoftWrap::None => SoftWrap::None,
10285            language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10286            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10287            language_settings::SoftWrap::PreferredLineLength => {
10288                SoftWrap::Column(settings.preferred_line_length)
10289            }
10290        }
10291    }
10292
10293    pub fn set_soft_wrap_mode(
10294        &mut self,
10295        mode: language_settings::SoftWrap,
10296        cx: &mut ViewContext<Self>,
10297    ) {
10298        self.soft_wrap_mode_override = Some(mode);
10299        cx.notify();
10300    }
10301
10302    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10303        let rem_size = cx.rem_size();
10304        self.display_map.update(cx, |map, cx| {
10305            map.set_font(
10306                style.text.font(),
10307                style.text.font_size.to_pixels(rem_size),
10308                cx,
10309            )
10310        });
10311        self.style = Some(style);
10312    }
10313
10314    pub fn style(&self) -> Option<&EditorStyle> {
10315        self.style.as_ref()
10316    }
10317
10318    // Called by the element. This method is not designed to be called outside of the editor
10319    // element's layout code because it does not notify when rewrapping is computed synchronously.
10320    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10321        self.display_map
10322            .update(cx, |map, cx| map.set_wrap_width(width, cx))
10323    }
10324
10325    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10326        if self.soft_wrap_mode_override.is_some() {
10327            self.soft_wrap_mode_override.take();
10328        } else {
10329            let soft_wrap = match self.soft_wrap_mode(cx) {
10330                SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10331                SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10332                    language_settings::SoftWrap::PreferLine
10333                }
10334            };
10335            self.soft_wrap_mode_override = Some(soft_wrap);
10336        }
10337        cx.notify();
10338    }
10339
10340    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10341        let Some(workspace) = self.workspace() else {
10342            return;
10343        };
10344        let fs = workspace.read(cx).app_state().fs.clone();
10345        let current_show = TabBarSettings::get_global(cx).show;
10346        update_settings_file::<TabBarSettings>(fs, cx, move |setting| {
10347            setting.show = Some(!current_show);
10348        });
10349    }
10350
10351    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10352        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10353            self.buffer
10354                .read(cx)
10355                .settings_at(0, cx)
10356                .indent_guides
10357                .enabled
10358        });
10359        self.show_indent_guides = Some(!currently_enabled);
10360        cx.notify();
10361    }
10362
10363    fn should_show_indent_guides(&self) -> Option<bool> {
10364        self.show_indent_guides
10365    }
10366
10367    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10368        let mut editor_settings = EditorSettings::get_global(cx).clone();
10369        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10370        EditorSettings::override_global(editor_settings, cx);
10371    }
10372
10373    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10374        self.show_gutter = show_gutter;
10375        cx.notify();
10376    }
10377
10378    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10379        self.show_line_numbers = Some(show_line_numbers);
10380        cx.notify();
10381    }
10382
10383    pub fn set_show_git_diff_gutter(
10384        &mut self,
10385        show_git_diff_gutter: bool,
10386        cx: &mut ViewContext<Self>,
10387    ) {
10388        self.show_git_diff_gutter = Some(show_git_diff_gutter);
10389        cx.notify();
10390    }
10391
10392    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10393        self.show_code_actions = Some(show_code_actions);
10394        cx.notify();
10395    }
10396
10397    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10398        self.show_runnables = Some(show_runnables);
10399        cx.notify();
10400    }
10401
10402    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10403        self.show_wrap_guides = Some(show_wrap_guides);
10404        cx.notify();
10405    }
10406
10407    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10408        self.show_indent_guides = Some(show_indent_guides);
10409        cx.notify();
10410    }
10411
10412    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10413        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10414            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10415                if let Some(dir) = file.abs_path(cx).parent() {
10416                    return Some(dir.to_owned());
10417                }
10418            }
10419
10420            if let Some(project_path) = buffer.read(cx).project_path(cx) {
10421                return Some(project_path.path.to_path_buf());
10422            }
10423        }
10424
10425        None
10426    }
10427
10428    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10429        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10430            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10431                cx.reveal_path(&file.abs_path(cx));
10432            }
10433        }
10434    }
10435
10436    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10437        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10438            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10439                if let Some(path) = file.abs_path(cx).to_str() {
10440                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10441                }
10442            }
10443        }
10444    }
10445
10446    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10447        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10448            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10449                if let Some(path) = file.path().to_str() {
10450                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10451                }
10452            }
10453        }
10454    }
10455
10456    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10457        self.show_git_blame_gutter = !self.show_git_blame_gutter;
10458
10459        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10460            self.start_git_blame(true, cx);
10461        }
10462
10463        cx.notify();
10464    }
10465
10466    pub fn toggle_git_blame_inline(
10467        &mut self,
10468        _: &ToggleGitBlameInline,
10469        cx: &mut ViewContext<Self>,
10470    ) {
10471        self.toggle_git_blame_inline_internal(true, cx);
10472        cx.notify();
10473    }
10474
10475    pub fn git_blame_inline_enabled(&self) -> bool {
10476        self.git_blame_inline_enabled
10477    }
10478
10479    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10480        self.show_selection_menu = self
10481            .show_selection_menu
10482            .map(|show_selections_menu| !show_selections_menu)
10483            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10484
10485        cx.notify();
10486    }
10487
10488    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10489        self.show_selection_menu
10490            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10491    }
10492
10493    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10494        if let Some(project) = self.project.as_ref() {
10495            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10496                return;
10497            };
10498
10499            if buffer.read(cx).file().is_none() {
10500                return;
10501            }
10502
10503            let focused = self.focus_handle(cx).contains_focused(cx);
10504
10505            let project = project.clone();
10506            let blame =
10507                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10508            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10509            self.blame = Some(blame);
10510        }
10511    }
10512
10513    fn toggle_git_blame_inline_internal(
10514        &mut self,
10515        user_triggered: bool,
10516        cx: &mut ViewContext<Self>,
10517    ) {
10518        if self.git_blame_inline_enabled {
10519            self.git_blame_inline_enabled = false;
10520            self.show_git_blame_inline = false;
10521            self.show_git_blame_inline_delay_task.take();
10522        } else {
10523            self.git_blame_inline_enabled = true;
10524            self.start_git_blame_inline(user_triggered, cx);
10525        }
10526
10527        cx.notify();
10528    }
10529
10530    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10531        self.start_git_blame(user_triggered, cx);
10532
10533        if ProjectSettings::get_global(cx)
10534            .git
10535            .inline_blame_delay()
10536            .is_some()
10537        {
10538            self.start_inline_blame_timer(cx);
10539        } else {
10540            self.show_git_blame_inline = true
10541        }
10542    }
10543
10544    pub fn blame(&self) -> Option<&Model<GitBlame>> {
10545        self.blame.as_ref()
10546    }
10547
10548    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10549        self.show_git_blame_gutter && self.has_blame_entries(cx)
10550    }
10551
10552    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10553        self.show_git_blame_inline
10554            && self.focus_handle.is_focused(cx)
10555            && !self.newest_selection_head_on_empty_line(cx)
10556            && self.has_blame_entries(cx)
10557    }
10558
10559    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10560        self.blame()
10561            .map_or(false, |blame| blame.read(cx).has_generated_entries())
10562    }
10563
10564    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10565        let cursor_anchor = self.selections.newest_anchor().head();
10566
10567        let snapshot = self.buffer.read(cx).snapshot(cx);
10568        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10569
10570        snapshot.line_len(buffer_row) == 0
10571    }
10572
10573    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10574        let (path, selection, repo) = maybe!({
10575            let project_handle = self.project.as_ref()?.clone();
10576            let project = project_handle.read(cx);
10577
10578            let selection = self.selections.newest::<Point>(cx);
10579            let selection_range = selection.range();
10580
10581            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10582                (buffer, selection_range.start.row..selection_range.end.row)
10583            } else {
10584                let buffer_ranges = self
10585                    .buffer()
10586                    .read(cx)
10587                    .range_to_buffer_ranges(selection_range, cx);
10588
10589                let (buffer, range, _) = if selection.reversed {
10590                    buffer_ranges.first()
10591                } else {
10592                    buffer_ranges.last()
10593                }?;
10594
10595                let snapshot = buffer.read(cx).snapshot();
10596                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10597                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
10598                (buffer.clone(), selection)
10599            };
10600
10601            let path = buffer
10602                .read(cx)
10603                .file()?
10604                .as_local()?
10605                .path()
10606                .to_str()?
10607                .to_string();
10608            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10609            Some((path, selection, repo))
10610        })
10611        .ok_or_else(|| anyhow!("unable to open git repository"))?;
10612
10613        const REMOTE_NAME: &str = "origin";
10614        let origin_url = repo
10615            .remote_url(REMOTE_NAME)
10616            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10617        let sha = repo
10618            .head_sha()
10619            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10620
10621        let (provider, remote) =
10622            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10623                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10624
10625        Ok(provider.build_permalink(
10626            remote,
10627            BuildPermalinkParams {
10628                sha: &sha,
10629                path: &path,
10630                selection: Some(selection),
10631            },
10632        ))
10633    }
10634
10635    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10636        let permalink = self.get_permalink_to_line(cx);
10637
10638        match permalink {
10639            Ok(permalink) => {
10640                cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
10641            }
10642            Err(err) => {
10643                let message = format!("Failed to copy permalink: {err}");
10644
10645                Err::<(), anyhow::Error>(err).log_err();
10646
10647                if let Some(workspace) = self.workspace() {
10648                    workspace.update(cx, |workspace, cx| {
10649                        struct CopyPermalinkToLine;
10650
10651                        workspace.show_toast(
10652                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10653                            cx,
10654                        )
10655                    })
10656                }
10657            }
10658        }
10659    }
10660
10661    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10662        let permalink = self.get_permalink_to_line(cx);
10663
10664        match permalink {
10665            Ok(permalink) => {
10666                cx.open_url(permalink.as_ref());
10667            }
10668            Err(err) => {
10669                let message = format!("Failed to open permalink: {err}");
10670
10671                Err::<(), anyhow::Error>(err).log_err();
10672
10673                if let Some(workspace) = self.workspace() {
10674                    workspace.update(cx, |workspace, cx| {
10675                        struct OpenPermalinkToLine;
10676
10677                        workspace.show_toast(
10678                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10679                            cx,
10680                        )
10681                    })
10682                }
10683            }
10684        }
10685    }
10686
10687    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10688    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10689    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10690    pub fn highlight_rows<T: 'static>(
10691        &mut self,
10692        rows: RangeInclusive<Anchor>,
10693        color: Option<Hsla>,
10694        should_autoscroll: bool,
10695        cx: &mut ViewContext<Self>,
10696    ) {
10697        let snapshot = self.buffer().read(cx).snapshot(cx);
10698        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10699        let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10700            highlight
10701                .range
10702                .start()
10703                .cmp(&rows.start(), &snapshot)
10704                .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10705        });
10706        match (color, existing_highlight_index) {
10707            (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10708                ix,
10709                RowHighlight {
10710                    index: post_inc(&mut self.highlight_order),
10711                    range: rows,
10712                    should_autoscroll,
10713                    color,
10714                },
10715            ),
10716            (None, Ok(i)) => {
10717                row_highlights.remove(i);
10718            }
10719        }
10720    }
10721
10722    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10723    pub fn clear_row_highlights<T: 'static>(&mut self) {
10724        self.highlighted_rows.remove(&TypeId::of::<T>());
10725    }
10726
10727    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10728    pub fn highlighted_rows<T: 'static>(
10729        &self,
10730    ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10731        Some(
10732            self.highlighted_rows
10733                .get(&TypeId::of::<T>())?
10734                .iter()
10735                .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10736        )
10737    }
10738
10739    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10740    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10741    /// Allows to ignore certain kinds of highlights.
10742    pub fn highlighted_display_rows(
10743        &mut self,
10744        cx: &mut WindowContext,
10745    ) -> BTreeMap<DisplayRow, Hsla> {
10746        let snapshot = self.snapshot(cx);
10747        let mut used_highlight_orders = HashMap::default();
10748        self.highlighted_rows
10749            .iter()
10750            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10751            .fold(
10752                BTreeMap::<DisplayRow, Hsla>::new(),
10753                |mut unique_rows, highlight| {
10754                    let start_row = highlight.range.start().to_display_point(&snapshot).row();
10755                    let end_row = highlight.range.end().to_display_point(&snapshot).row();
10756                    for row in start_row.0..=end_row.0 {
10757                        let used_index =
10758                            used_highlight_orders.entry(row).or_insert(highlight.index);
10759                        if highlight.index >= *used_index {
10760                            *used_index = highlight.index;
10761                            match highlight.color {
10762                                Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10763                                None => unique_rows.remove(&DisplayRow(row)),
10764                            };
10765                        }
10766                    }
10767                    unique_rows
10768                },
10769            )
10770    }
10771
10772    pub fn highlighted_display_row_for_autoscroll(
10773        &self,
10774        snapshot: &DisplaySnapshot,
10775    ) -> Option<DisplayRow> {
10776        self.highlighted_rows
10777            .values()
10778            .flat_map(|highlighted_rows| highlighted_rows.iter())
10779            .filter_map(|highlight| {
10780                if highlight.color.is_none() || !highlight.should_autoscroll {
10781                    return None;
10782                }
10783                Some(highlight.range.start().to_display_point(&snapshot).row())
10784            })
10785            .min()
10786    }
10787
10788    pub fn set_search_within_ranges(
10789        &mut self,
10790        ranges: &[Range<Anchor>],
10791        cx: &mut ViewContext<Self>,
10792    ) {
10793        self.highlight_background::<SearchWithinRange>(
10794            ranges,
10795            |colors| colors.editor_document_highlight_read_background,
10796            cx,
10797        )
10798    }
10799
10800    pub fn set_breadcrumb_header(&mut self, new_header: String) {
10801        self.breadcrumb_header = Some(new_header);
10802    }
10803
10804    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10805        self.clear_background_highlights::<SearchWithinRange>(cx);
10806    }
10807
10808    pub fn highlight_background<T: 'static>(
10809        &mut self,
10810        ranges: &[Range<Anchor>],
10811        color_fetcher: fn(&ThemeColors) -> Hsla,
10812        cx: &mut ViewContext<Self>,
10813    ) {
10814        let snapshot = self.snapshot(cx);
10815        // this is to try and catch a panic sooner
10816        for range in ranges {
10817            snapshot
10818                .buffer_snapshot
10819                .summary_for_anchor::<usize>(&range.start);
10820            snapshot
10821                .buffer_snapshot
10822                .summary_for_anchor::<usize>(&range.end);
10823        }
10824
10825        self.background_highlights
10826            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10827        self.scrollbar_marker_state.dirty = true;
10828        cx.notify();
10829    }
10830
10831    pub fn clear_background_highlights<T: 'static>(
10832        &mut self,
10833        cx: &mut ViewContext<Self>,
10834    ) -> Option<BackgroundHighlight> {
10835        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10836        if !text_highlights.1.is_empty() {
10837            self.scrollbar_marker_state.dirty = true;
10838            cx.notify();
10839        }
10840        Some(text_highlights)
10841    }
10842
10843    pub fn highlight_gutter<T: 'static>(
10844        &mut self,
10845        ranges: &[Range<Anchor>],
10846        color_fetcher: fn(&AppContext) -> Hsla,
10847        cx: &mut ViewContext<Self>,
10848    ) {
10849        self.gutter_highlights
10850            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10851        cx.notify();
10852    }
10853
10854    pub fn clear_gutter_highlights<T: 'static>(
10855        &mut self,
10856        cx: &mut ViewContext<Self>,
10857    ) -> Option<GutterHighlight> {
10858        cx.notify();
10859        self.gutter_highlights.remove(&TypeId::of::<T>())
10860    }
10861
10862    #[cfg(feature = "test-support")]
10863    pub fn all_text_background_highlights(
10864        &mut self,
10865        cx: &mut ViewContext<Self>,
10866    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10867        let snapshot = self.snapshot(cx);
10868        let buffer = &snapshot.buffer_snapshot;
10869        let start = buffer.anchor_before(0);
10870        let end = buffer.anchor_after(buffer.len());
10871        let theme = cx.theme().colors();
10872        self.background_highlights_in_range(start..end, &snapshot, theme)
10873    }
10874
10875    #[cfg(feature = "test-support")]
10876    pub fn search_background_highlights(
10877        &mut self,
10878        cx: &mut ViewContext<Self>,
10879    ) -> Vec<Range<Point>> {
10880        let snapshot = self.buffer().read(cx).snapshot(cx);
10881
10882        let highlights = self
10883            .background_highlights
10884            .get(&TypeId::of::<items::BufferSearchHighlights>());
10885
10886        if let Some((_color, ranges)) = highlights {
10887            ranges
10888                .iter()
10889                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
10890                .collect_vec()
10891        } else {
10892            vec![]
10893        }
10894    }
10895
10896    fn document_highlights_for_position<'a>(
10897        &'a self,
10898        position: Anchor,
10899        buffer: &'a MultiBufferSnapshot,
10900    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
10901        let read_highlights = self
10902            .background_highlights
10903            .get(&TypeId::of::<DocumentHighlightRead>())
10904            .map(|h| &h.1);
10905        let write_highlights = self
10906            .background_highlights
10907            .get(&TypeId::of::<DocumentHighlightWrite>())
10908            .map(|h| &h.1);
10909        let left_position = position.bias_left(buffer);
10910        let right_position = position.bias_right(buffer);
10911        read_highlights
10912            .into_iter()
10913            .chain(write_highlights)
10914            .flat_map(move |ranges| {
10915                let start_ix = match ranges.binary_search_by(|probe| {
10916                    let cmp = probe.end.cmp(&left_position, buffer);
10917                    if cmp.is_ge() {
10918                        Ordering::Greater
10919                    } else {
10920                        Ordering::Less
10921                    }
10922                }) {
10923                    Ok(i) | Err(i) => i,
10924                };
10925
10926                ranges[start_ix..]
10927                    .iter()
10928                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
10929            })
10930    }
10931
10932    pub fn has_background_highlights<T: 'static>(&self) -> bool {
10933        self.background_highlights
10934            .get(&TypeId::of::<T>())
10935            .map_or(false, |(_, highlights)| !highlights.is_empty())
10936    }
10937
10938    pub fn background_highlights_in_range(
10939        &self,
10940        search_range: Range<Anchor>,
10941        display_snapshot: &DisplaySnapshot,
10942        theme: &ThemeColors,
10943    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10944        let mut results = Vec::new();
10945        for (color_fetcher, ranges) in self.background_highlights.values() {
10946            let color = color_fetcher(theme);
10947            let start_ix = match ranges.binary_search_by(|probe| {
10948                let cmp = probe
10949                    .end
10950                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10951                if cmp.is_gt() {
10952                    Ordering::Greater
10953                } else {
10954                    Ordering::Less
10955                }
10956            }) {
10957                Ok(i) | Err(i) => i,
10958            };
10959            for range in &ranges[start_ix..] {
10960                if range
10961                    .start
10962                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10963                    .is_ge()
10964                {
10965                    break;
10966                }
10967
10968                let start = range.start.to_display_point(&display_snapshot);
10969                let end = range.end.to_display_point(&display_snapshot);
10970                results.push((start..end, color))
10971            }
10972        }
10973        results
10974    }
10975
10976    pub fn background_highlight_row_ranges<T: 'static>(
10977        &self,
10978        search_range: Range<Anchor>,
10979        display_snapshot: &DisplaySnapshot,
10980        count: usize,
10981    ) -> Vec<RangeInclusive<DisplayPoint>> {
10982        let mut results = Vec::new();
10983        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
10984            return vec![];
10985        };
10986
10987        let start_ix = match ranges.binary_search_by(|probe| {
10988            let cmp = probe
10989                .end
10990                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10991            if cmp.is_gt() {
10992                Ordering::Greater
10993            } else {
10994                Ordering::Less
10995            }
10996        }) {
10997            Ok(i) | Err(i) => i,
10998        };
10999        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11000            if let (Some(start_display), Some(end_display)) = (start, end) {
11001                results.push(
11002                    start_display.to_display_point(display_snapshot)
11003                        ..=end_display.to_display_point(display_snapshot),
11004                );
11005            }
11006        };
11007        let mut start_row: Option<Point> = None;
11008        let mut end_row: Option<Point> = None;
11009        if ranges.len() > count {
11010            return Vec::new();
11011        }
11012        for range in &ranges[start_ix..] {
11013            if range
11014                .start
11015                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11016                .is_ge()
11017            {
11018                break;
11019            }
11020            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11021            if let Some(current_row) = &end_row {
11022                if end.row == current_row.row {
11023                    continue;
11024                }
11025            }
11026            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11027            if start_row.is_none() {
11028                assert_eq!(end_row, None);
11029                start_row = Some(start);
11030                end_row = Some(end);
11031                continue;
11032            }
11033            if let Some(current_end) = end_row.as_mut() {
11034                if start.row > current_end.row + 1 {
11035                    push_region(start_row, end_row);
11036                    start_row = Some(start);
11037                    end_row = Some(end);
11038                } else {
11039                    // Merge two hunks.
11040                    *current_end = end;
11041                }
11042            } else {
11043                unreachable!();
11044            }
11045        }
11046        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11047        push_region(start_row, end_row);
11048        results
11049    }
11050
11051    pub fn gutter_highlights_in_range(
11052        &self,
11053        search_range: Range<Anchor>,
11054        display_snapshot: &DisplaySnapshot,
11055        cx: &AppContext,
11056    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11057        let mut results = Vec::new();
11058        for (color_fetcher, ranges) in self.gutter_highlights.values() {
11059            let color = color_fetcher(cx);
11060            let start_ix = match ranges.binary_search_by(|probe| {
11061                let cmp = probe
11062                    .end
11063                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11064                if cmp.is_gt() {
11065                    Ordering::Greater
11066                } else {
11067                    Ordering::Less
11068                }
11069            }) {
11070                Ok(i) | Err(i) => i,
11071            };
11072            for range in &ranges[start_ix..] {
11073                if range
11074                    .start
11075                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11076                    .is_ge()
11077                {
11078                    break;
11079                }
11080
11081                let start = range.start.to_display_point(&display_snapshot);
11082                let end = range.end.to_display_point(&display_snapshot);
11083                results.push((start..end, color))
11084            }
11085        }
11086        results
11087    }
11088
11089    /// Get the text ranges corresponding to the redaction query
11090    pub fn redacted_ranges(
11091        &self,
11092        search_range: Range<Anchor>,
11093        display_snapshot: &DisplaySnapshot,
11094        cx: &WindowContext,
11095    ) -> Vec<Range<DisplayPoint>> {
11096        display_snapshot
11097            .buffer_snapshot
11098            .redacted_ranges(search_range, |file| {
11099                if let Some(file) = file {
11100                    file.is_private()
11101                        && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11102                } else {
11103                    false
11104                }
11105            })
11106            .map(|range| {
11107                range.start.to_display_point(display_snapshot)
11108                    ..range.end.to_display_point(display_snapshot)
11109            })
11110            .collect()
11111    }
11112
11113    pub fn highlight_text<T: 'static>(
11114        &mut self,
11115        ranges: Vec<Range<Anchor>>,
11116        style: HighlightStyle,
11117        cx: &mut ViewContext<Self>,
11118    ) {
11119        self.display_map.update(cx, |map, _| {
11120            map.highlight_text(TypeId::of::<T>(), ranges, style)
11121        });
11122        cx.notify();
11123    }
11124
11125    pub(crate) fn highlight_inlays<T: 'static>(
11126        &mut self,
11127        highlights: Vec<InlayHighlight>,
11128        style: HighlightStyle,
11129        cx: &mut ViewContext<Self>,
11130    ) {
11131        self.display_map.update(cx, |map, _| {
11132            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11133        });
11134        cx.notify();
11135    }
11136
11137    pub fn text_highlights<'a, T: 'static>(
11138        &'a self,
11139        cx: &'a AppContext,
11140    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11141        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11142    }
11143
11144    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11145        let cleared = self
11146            .display_map
11147            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11148        if cleared {
11149            cx.notify();
11150        }
11151    }
11152
11153    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11154        (self.read_only(cx) || self.blink_manager.read(cx).visible())
11155            && self.focus_handle.is_focused(cx)
11156    }
11157
11158    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11159        self.show_cursor_when_unfocused = is_enabled;
11160        cx.notify();
11161    }
11162
11163    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11164        cx.notify();
11165    }
11166
11167    fn on_buffer_event(
11168        &mut self,
11169        multibuffer: Model<MultiBuffer>,
11170        event: &multi_buffer::Event,
11171        cx: &mut ViewContext<Self>,
11172    ) {
11173        match event {
11174            multi_buffer::Event::Edited {
11175                singleton_buffer_edited,
11176            } => {
11177                self.scrollbar_marker_state.dirty = true;
11178                self.active_indent_guides_state.dirty = true;
11179                self.refresh_active_diagnostics(cx);
11180                self.refresh_code_actions(cx);
11181                if self.has_active_inline_completion(cx) {
11182                    self.update_visible_inline_completion(cx);
11183                }
11184                cx.emit(EditorEvent::BufferEdited);
11185                cx.emit(SearchEvent::MatchesInvalidated);
11186                if *singleton_buffer_edited {
11187                    if let Some(project) = &self.project {
11188                        let project = project.read(cx);
11189                        #[allow(clippy::mutable_key_type)]
11190                        let languages_affected = multibuffer
11191                            .read(cx)
11192                            .all_buffers()
11193                            .into_iter()
11194                            .filter_map(|buffer| {
11195                                let buffer = buffer.read(cx);
11196                                let language = buffer.language()?;
11197                                if project.is_local()
11198                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
11199                                {
11200                                    None
11201                                } else {
11202                                    Some(language)
11203                                }
11204                            })
11205                            .cloned()
11206                            .collect::<HashSet<_>>();
11207                        if !languages_affected.is_empty() {
11208                            self.refresh_inlay_hints(
11209                                InlayHintRefreshReason::BufferEdited(languages_affected),
11210                                cx,
11211                            );
11212                        }
11213                    }
11214                }
11215
11216                let Some(project) = &self.project else { return };
11217                let telemetry = project.read(cx).client().telemetry().clone();
11218                refresh_linked_ranges(self, cx);
11219                telemetry.log_edit_event("editor");
11220            }
11221            multi_buffer::Event::ExcerptsAdded {
11222                buffer,
11223                predecessor,
11224                excerpts,
11225            } => {
11226                self.tasks_update_task = Some(self.refresh_runnables(cx));
11227                cx.emit(EditorEvent::ExcerptsAdded {
11228                    buffer: buffer.clone(),
11229                    predecessor: *predecessor,
11230                    excerpts: excerpts.clone(),
11231                });
11232                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11233            }
11234            multi_buffer::Event::ExcerptsRemoved { ids } => {
11235                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11236                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11237            }
11238            multi_buffer::Event::ExcerptsEdited { ids } => {
11239                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11240            }
11241            multi_buffer::Event::ExcerptsExpanded { ids } => {
11242                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11243            }
11244            multi_buffer::Event::Reparsed(buffer_id) => {
11245                self.tasks_update_task = Some(self.refresh_runnables(cx));
11246
11247                cx.emit(EditorEvent::Reparsed(*buffer_id));
11248            }
11249            multi_buffer::Event::LanguageChanged(buffer_id) => {
11250                linked_editing_ranges::refresh_linked_ranges(self, cx);
11251                cx.emit(EditorEvent::Reparsed(*buffer_id));
11252                cx.notify();
11253            }
11254            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11255            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11256            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11257                cx.emit(EditorEvent::TitleChanged)
11258            }
11259            multi_buffer::Event::DiffBaseChanged => {
11260                self.scrollbar_marker_state.dirty = true;
11261                cx.emit(EditorEvent::DiffBaseChanged);
11262                cx.notify();
11263            }
11264            multi_buffer::Event::DiffUpdated { buffer } => {
11265                self.sync_expanded_diff_hunks(buffer.clone(), cx);
11266                cx.notify();
11267            }
11268            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11269            multi_buffer::Event::DiagnosticsUpdated => {
11270                self.refresh_active_diagnostics(cx);
11271                self.scrollbar_marker_state.dirty = true;
11272                cx.notify();
11273            }
11274            _ => {}
11275        };
11276    }
11277
11278    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11279        cx.notify();
11280    }
11281
11282    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11283        self.tasks_update_task = Some(self.refresh_runnables(cx));
11284        self.refresh_inline_completion(true, cx);
11285        self.refresh_inlay_hints(
11286            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11287                self.selections.newest_anchor().head(),
11288                &self.buffer.read(cx).snapshot(cx),
11289                cx,
11290            )),
11291            cx,
11292        );
11293        let editor_settings = EditorSettings::get_global(cx);
11294        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11295        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11296
11297        let project_settings = ProjectSettings::get_global(cx);
11298        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11299
11300        if self.mode == EditorMode::Full {
11301            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11302            if self.git_blame_inline_enabled != inline_blame_enabled {
11303                self.toggle_git_blame_inline_internal(false, cx);
11304            }
11305        }
11306
11307        cx.notify();
11308    }
11309
11310    pub fn set_searchable(&mut self, searchable: bool) {
11311        self.searchable = searchable;
11312    }
11313
11314    pub fn searchable(&self) -> bool {
11315        self.searchable
11316    }
11317
11318    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11319        self.open_excerpts_common(true, cx)
11320    }
11321
11322    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11323        self.open_excerpts_common(false, cx)
11324    }
11325
11326    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11327        let buffer = self.buffer.read(cx);
11328        if buffer.is_singleton() {
11329            cx.propagate();
11330            return;
11331        }
11332
11333        let Some(workspace) = self.workspace() else {
11334            cx.propagate();
11335            return;
11336        };
11337
11338        let mut new_selections_by_buffer = HashMap::default();
11339        for selection in self.selections.all::<usize>(cx) {
11340            for (buffer, mut range, _) in
11341                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11342            {
11343                if selection.reversed {
11344                    mem::swap(&mut range.start, &mut range.end);
11345                }
11346                new_selections_by_buffer
11347                    .entry(buffer)
11348                    .or_insert(Vec::new())
11349                    .push(range)
11350            }
11351        }
11352
11353        // We defer the pane interaction because we ourselves are a workspace item
11354        // and activating a new item causes the pane to call a method on us reentrantly,
11355        // which panics if we're on the stack.
11356        cx.window_context().defer(move |cx| {
11357            workspace.update(cx, |workspace, cx| {
11358                let pane = if split {
11359                    workspace.adjacent_pane(cx)
11360                } else {
11361                    workspace.active_pane().clone()
11362                };
11363
11364                for (buffer, ranges) in new_selections_by_buffer {
11365                    let editor =
11366                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11367                    editor.update(cx, |editor, cx| {
11368                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11369                            s.select_ranges(ranges);
11370                        });
11371                    });
11372                }
11373            })
11374        });
11375    }
11376
11377    fn jump(
11378        &mut self,
11379        path: ProjectPath,
11380        position: Point,
11381        anchor: language::Anchor,
11382        offset_from_top: u32,
11383        cx: &mut ViewContext<Self>,
11384    ) {
11385        let workspace = self.workspace();
11386        cx.spawn(|_, mut cx| async move {
11387            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11388            let editor = workspace.update(&mut cx, |workspace, cx| {
11389                // Reset the preview item id before opening the new item
11390                workspace.active_pane().update(cx, |pane, cx| {
11391                    pane.set_preview_item_id(None, cx);
11392                });
11393                workspace.open_path_preview(path, None, true, true, cx)
11394            })?;
11395            let editor = editor
11396                .await?
11397                .downcast::<Editor>()
11398                .ok_or_else(|| anyhow!("opened item was not an editor"))?
11399                .downgrade();
11400            editor.update(&mut cx, |editor, cx| {
11401                let buffer = editor
11402                    .buffer()
11403                    .read(cx)
11404                    .as_singleton()
11405                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11406                let buffer = buffer.read(cx);
11407                let cursor = if buffer.can_resolve(&anchor) {
11408                    language::ToPoint::to_point(&anchor, buffer)
11409                } else {
11410                    buffer.clip_point(position, Bias::Left)
11411                };
11412
11413                let nav_history = editor.nav_history.take();
11414                editor.change_selections(
11415                    Some(Autoscroll::top_relative(offset_from_top as usize)),
11416                    cx,
11417                    |s| {
11418                        s.select_ranges([cursor..cursor]);
11419                    },
11420                );
11421                editor.nav_history = nav_history;
11422
11423                anyhow::Ok(())
11424            })??;
11425
11426            anyhow::Ok(())
11427        })
11428        .detach_and_log_err(cx);
11429    }
11430
11431    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11432        let snapshot = self.buffer.read(cx).read(cx);
11433        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11434        Some(
11435            ranges
11436                .iter()
11437                .map(move |range| {
11438                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11439                })
11440                .collect(),
11441        )
11442    }
11443
11444    fn selection_replacement_ranges(
11445        &self,
11446        range: Range<OffsetUtf16>,
11447        cx: &AppContext,
11448    ) -> Vec<Range<OffsetUtf16>> {
11449        let selections = self.selections.all::<OffsetUtf16>(cx);
11450        let newest_selection = selections
11451            .iter()
11452            .max_by_key(|selection| selection.id)
11453            .unwrap();
11454        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11455        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11456        let snapshot = self.buffer.read(cx).read(cx);
11457        selections
11458            .into_iter()
11459            .map(|mut selection| {
11460                selection.start.0 =
11461                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
11462                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11463                snapshot.clip_offset_utf16(selection.start, Bias::Left)
11464                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11465            })
11466            .collect()
11467    }
11468
11469    fn report_editor_event(
11470        &self,
11471        operation: &'static str,
11472        file_extension: Option<String>,
11473        cx: &AppContext,
11474    ) {
11475        if cfg!(any(test, feature = "test-support")) {
11476            return;
11477        }
11478
11479        let Some(project) = &self.project else { return };
11480
11481        // If None, we are in a file without an extension
11482        let file = self
11483            .buffer
11484            .read(cx)
11485            .as_singleton()
11486            .and_then(|b| b.read(cx).file());
11487        let file_extension = file_extension.or(file
11488            .as_ref()
11489            .and_then(|file| Path::new(file.file_name(cx)).extension())
11490            .and_then(|e| e.to_str())
11491            .map(|a| a.to_string()));
11492
11493        let vim_mode = cx
11494            .global::<SettingsStore>()
11495            .raw_user_settings()
11496            .get("vim_mode")
11497            == Some(&serde_json::Value::Bool(true));
11498
11499        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11500            == language::language_settings::InlineCompletionProvider::Copilot;
11501        let copilot_enabled_for_language = self
11502            .buffer
11503            .read(cx)
11504            .settings_at(0, cx)
11505            .show_inline_completions;
11506
11507        let telemetry = project.read(cx).client().telemetry().clone();
11508        telemetry.report_editor_event(
11509            file_extension,
11510            vim_mode,
11511            operation,
11512            copilot_enabled,
11513            copilot_enabled_for_language,
11514        )
11515    }
11516
11517    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11518    /// with each line being an array of {text, highlight} objects.
11519    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11520        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11521            return;
11522        };
11523
11524        #[derive(Serialize)]
11525        struct Chunk<'a> {
11526            text: String,
11527            highlight: Option<&'a str>,
11528        }
11529
11530        let snapshot = buffer.read(cx).snapshot();
11531        let range = self
11532            .selected_text_range(cx)
11533            .and_then(|selected_range| {
11534                if selected_range.is_empty() {
11535                    None
11536                } else {
11537                    Some(selected_range)
11538                }
11539            })
11540            .unwrap_or_else(|| 0..snapshot.len());
11541
11542        let chunks = snapshot.chunks(range, true);
11543        let mut lines = Vec::new();
11544        let mut line: VecDeque<Chunk> = VecDeque::new();
11545
11546        let Some(style) = self.style.as_ref() else {
11547            return;
11548        };
11549
11550        for chunk in chunks {
11551            let highlight = chunk
11552                .syntax_highlight_id
11553                .and_then(|id| id.name(&style.syntax));
11554            let mut chunk_lines = chunk.text.split('\n').peekable();
11555            while let Some(text) = chunk_lines.next() {
11556                let mut merged_with_last_token = false;
11557                if let Some(last_token) = line.back_mut() {
11558                    if last_token.highlight == highlight {
11559                        last_token.text.push_str(text);
11560                        merged_with_last_token = true;
11561                    }
11562                }
11563
11564                if !merged_with_last_token {
11565                    line.push_back(Chunk {
11566                        text: text.into(),
11567                        highlight,
11568                    });
11569                }
11570
11571                if chunk_lines.peek().is_some() {
11572                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
11573                        line.pop_front();
11574                    }
11575                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
11576                        line.pop_back();
11577                    }
11578
11579                    lines.push(mem::take(&mut line));
11580                }
11581            }
11582        }
11583
11584        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11585            return;
11586        };
11587        cx.write_to_clipboard(ClipboardItem::new(lines));
11588    }
11589
11590    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11591        &self.inlay_hint_cache
11592    }
11593
11594    pub fn replay_insert_event(
11595        &mut self,
11596        text: &str,
11597        relative_utf16_range: Option<Range<isize>>,
11598        cx: &mut ViewContext<Self>,
11599    ) {
11600        if !self.input_enabled {
11601            cx.emit(EditorEvent::InputIgnored { text: text.into() });
11602            return;
11603        }
11604        if let Some(relative_utf16_range) = relative_utf16_range {
11605            let selections = self.selections.all::<OffsetUtf16>(cx);
11606            self.change_selections(None, cx, |s| {
11607                let new_ranges = selections.into_iter().map(|range| {
11608                    let start = OffsetUtf16(
11609                        range
11610                            .head()
11611                            .0
11612                            .saturating_add_signed(relative_utf16_range.start),
11613                    );
11614                    let end = OffsetUtf16(
11615                        range
11616                            .head()
11617                            .0
11618                            .saturating_add_signed(relative_utf16_range.end),
11619                    );
11620                    start..end
11621                });
11622                s.select_ranges(new_ranges);
11623            });
11624        }
11625
11626        self.handle_input(text, cx);
11627    }
11628
11629    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11630        let Some(project) = self.project.as_ref() else {
11631            return false;
11632        };
11633        let project = project.read(cx);
11634
11635        let mut supports = false;
11636        self.buffer().read(cx).for_each_buffer(|buffer| {
11637            if !supports {
11638                supports = project
11639                    .language_servers_for_buffer(buffer.read(cx), cx)
11640                    .any(
11641                        |(_, server)| match server.capabilities().inlay_hint_provider {
11642                            Some(lsp::OneOf::Left(enabled)) => enabled,
11643                            Some(lsp::OneOf::Right(_)) => true,
11644                            None => false,
11645                        },
11646                    )
11647            }
11648        });
11649        supports
11650    }
11651
11652    pub fn focus(&self, cx: &mut WindowContext) {
11653        cx.focus(&self.focus_handle)
11654    }
11655
11656    pub fn is_focused(&self, cx: &WindowContext) -> bool {
11657        self.focus_handle.is_focused(cx)
11658    }
11659
11660    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11661        cx.emit(EditorEvent::Focused);
11662
11663        if let Some(descendant) = self
11664            .last_focused_descendant
11665            .take()
11666            .and_then(|descendant| descendant.upgrade())
11667        {
11668            cx.focus(&descendant);
11669        } else {
11670            if let Some(blame) = self.blame.as_ref() {
11671                blame.update(cx, GitBlame::focus)
11672            }
11673
11674            self.blink_manager.update(cx, BlinkManager::enable);
11675            self.show_cursor_names(cx);
11676            self.buffer.update(cx, |buffer, cx| {
11677                buffer.finalize_last_transaction(cx);
11678                if self.leader_peer_id.is_none() {
11679                    buffer.set_active_selections(
11680                        &self.selections.disjoint_anchors(),
11681                        self.selections.line_mode,
11682                        self.cursor_shape,
11683                        cx,
11684                    );
11685                }
11686            });
11687        }
11688    }
11689
11690    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
11691        cx.emit(EditorEvent::FocusedIn)
11692    }
11693
11694    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11695        if event.blurred != self.focus_handle {
11696            self.last_focused_descendant = Some(event.blurred);
11697        }
11698    }
11699
11700    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11701        self.blink_manager.update(cx, BlinkManager::disable);
11702        self.buffer
11703            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11704
11705        if let Some(blame) = self.blame.as_ref() {
11706            blame.update(cx, GitBlame::blur)
11707        }
11708        if !self.hover_state.focused(cx) {
11709            hide_hover(self, cx);
11710        }
11711
11712        self.hide_context_menu(cx);
11713        cx.emit(EditorEvent::Blurred);
11714        cx.notify();
11715    }
11716
11717    pub fn register_action<A: Action>(
11718        &mut self,
11719        listener: impl Fn(&A, &mut WindowContext) + 'static,
11720    ) -> Subscription {
11721        let id = self.next_editor_action_id.post_inc();
11722        let listener = Arc::new(listener);
11723        self.editor_actions.borrow_mut().insert(
11724            id,
11725            Box::new(move |cx| {
11726                let _view = cx.view().clone();
11727                let cx = cx.window_context();
11728                let listener = listener.clone();
11729                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11730                    let action = action.downcast_ref().unwrap();
11731                    if phase == DispatchPhase::Bubble {
11732                        listener(action, cx)
11733                    }
11734                })
11735            }),
11736        );
11737
11738        let editor_actions = self.editor_actions.clone();
11739        Subscription::new(move || {
11740            editor_actions.borrow_mut().remove(&id);
11741        })
11742    }
11743
11744    pub fn file_header_size(&self) -> u8 {
11745        self.file_header_size
11746    }
11747
11748    pub fn revert(
11749        &mut self,
11750        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
11751        cx: &mut ViewContext<Self>,
11752    ) {
11753        self.buffer().update(cx, |multi_buffer, cx| {
11754            for (buffer_id, changes) in revert_changes {
11755                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
11756                    buffer.update(cx, |buffer, cx| {
11757                        buffer.edit(
11758                            changes.into_iter().map(|(range, text)| {
11759                                (range, text.to_string().map(Arc::<str>::from))
11760                            }),
11761                            None,
11762                            cx,
11763                        );
11764                    });
11765                }
11766            }
11767        });
11768        self.change_selections(None, cx, |selections| selections.refresh());
11769    }
11770
11771    pub fn to_pixel_point(
11772        &mut self,
11773        source: multi_buffer::Anchor,
11774        editor_snapshot: &EditorSnapshot,
11775        cx: &mut ViewContext<Self>,
11776    ) -> Option<gpui::Point<Pixels>> {
11777        let text_layout_details = self.text_layout_details(cx);
11778        let line_height = text_layout_details
11779            .editor_style
11780            .text
11781            .line_height_in_pixels(cx.rem_size());
11782        let source_point = source.to_display_point(editor_snapshot);
11783        let first_visible_line = text_layout_details
11784            .scroll_anchor
11785            .anchor
11786            .to_display_point(editor_snapshot);
11787        if first_visible_line > source_point {
11788            return None;
11789        }
11790        let source_x = editor_snapshot.x_for_display_point(source_point, &text_layout_details);
11791        let source_y = line_height
11792            * ((source_point.row() - first_visible_line.row()).0 as f32
11793                - text_layout_details.scroll_anchor.offset.y);
11794        Some(gpui::Point::new(source_x, source_y))
11795    }
11796
11797    pub fn display_to_pixel_point(
11798        &mut self,
11799        source: DisplayPoint,
11800        editor_snapshot: &EditorSnapshot,
11801        cx: &mut ViewContext<Self>,
11802    ) -> Option<gpui::Point<Pixels>> {
11803        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
11804        let text_layout_details = self.text_layout_details(cx);
11805        let first_visible_line = text_layout_details
11806            .scroll_anchor
11807            .anchor
11808            .to_display_point(editor_snapshot);
11809        if first_visible_line > source {
11810            return None;
11811        }
11812        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
11813        let source_y = line_height * (source.row() - first_visible_line.row()).0 as f32;
11814        Some(gpui::Point::new(source_x, source_y))
11815    }
11816}
11817
11818fn hunks_for_selections(
11819    multi_buffer_snapshot: &MultiBufferSnapshot,
11820    selections: &[Selection<Anchor>],
11821) -> Vec<DiffHunk<MultiBufferRow>> {
11822    let buffer_rows_for_selections = selections.iter().map(|selection| {
11823        let head = selection.head();
11824        let tail = selection.tail();
11825        let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11826        let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11827        if start > end {
11828            end..start
11829        } else {
11830            start..end
11831        }
11832    });
11833
11834    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
11835}
11836
11837pub fn hunks_for_rows(
11838    rows: impl Iterator<Item = Range<MultiBufferRow>>,
11839    multi_buffer_snapshot: &MultiBufferSnapshot,
11840) -> Vec<DiffHunk<MultiBufferRow>> {
11841    let mut hunks = Vec::new();
11842    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11843        HashMap::default();
11844    for selected_multi_buffer_rows in rows {
11845        let query_rows =
11846            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11847        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11848            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11849            // when the caret is just above or just below the deleted hunk.
11850            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11851            let related_to_selection = if allow_adjacent {
11852                hunk.associated_range.overlaps(&query_rows)
11853                    || hunk.associated_range.start == query_rows.end
11854                    || hunk.associated_range.end == query_rows.start
11855            } else {
11856                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11857                // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11858                hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11859                    || selected_multi_buffer_rows.end == hunk.associated_range.start
11860            };
11861            if related_to_selection {
11862                if !processed_buffer_rows
11863                    .entry(hunk.buffer_id)
11864                    .or_default()
11865                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
11866                {
11867                    continue;
11868                }
11869                hunks.push(hunk);
11870            }
11871        }
11872    }
11873
11874    hunks
11875}
11876
11877pub trait CollaborationHub {
11878    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
11879    fn user_participant_indices<'a>(
11880        &self,
11881        cx: &'a AppContext,
11882    ) -> &'a HashMap<u64, ParticipantIndex>;
11883    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
11884}
11885
11886impl CollaborationHub for Model<Project> {
11887    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
11888        self.read(cx).collaborators()
11889    }
11890
11891    fn user_participant_indices<'a>(
11892        &self,
11893        cx: &'a AppContext,
11894    ) -> &'a HashMap<u64, ParticipantIndex> {
11895        self.read(cx).user_store().read(cx).participant_indices()
11896    }
11897
11898    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
11899        let this = self.read(cx);
11900        let user_ids = this.collaborators().values().map(|c| c.user_id);
11901        this.user_store().read_with(cx, |user_store, cx| {
11902            user_store.participant_names(user_ids, cx)
11903        })
11904    }
11905}
11906
11907pub trait CompletionProvider {
11908    fn completions(
11909        &self,
11910        buffer: &Model<Buffer>,
11911        buffer_position: text::Anchor,
11912        trigger: CompletionContext,
11913        cx: &mut ViewContext<Editor>,
11914    ) -> Task<Result<Vec<Completion>>>;
11915
11916    fn resolve_completions(
11917        &self,
11918        buffer: Model<Buffer>,
11919        completion_indices: Vec<usize>,
11920        completions: Arc<RwLock<Box<[Completion]>>>,
11921        cx: &mut ViewContext<Editor>,
11922    ) -> Task<Result<bool>>;
11923
11924    fn apply_additional_edits_for_completion(
11925        &self,
11926        buffer: Model<Buffer>,
11927        completion: Completion,
11928        push_to_history: bool,
11929        cx: &mut ViewContext<Editor>,
11930    ) -> Task<Result<Option<language::Transaction>>>;
11931
11932    fn is_completion_trigger(
11933        &self,
11934        buffer: &Model<Buffer>,
11935        position: language::Anchor,
11936        text: &str,
11937        trigger_in_words: bool,
11938        cx: &mut ViewContext<Editor>,
11939    ) -> bool;
11940}
11941
11942fn snippet_completions(
11943    project: &Project,
11944    buffer: &Model<Buffer>,
11945    buffer_position: text::Anchor,
11946    cx: &mut AppContext,
11947) -> Vec<Completion> {
11948    let language = buffer.read(cx).language_at(buffer_position);
11949    let language_name = language.as_ref().map(|language| language.lsp_id());
11950    let snippet_store = project.snippets().read(cx);
11951    let snippets = snippet_store.snippets_for(language_name, cx);
11952
11953    if snippets.is_empty() {
11954        return vec![];
11955    }
11956    let snapshot = buffer.read(cx).text_snapshot();
11957    let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
11958
11959    let mut lines = chunks.lines();
11960    let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
11961        return vec![];
11962    };
11963
11964    let scope = language.map(|language| language.default_scope());
11965    let mut last_word = line_at
11966        .chars()
11967        .rev()
11968        .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
11969        .collect::<String>();
11970    last_word = last_word.chars().rev().collect();
11971    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
11972    let to_lsp = |point: &text::Anchor| {
11973        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
11974        point_to_lsp(end)
11975    };
11976    let lsp_end = to_lsp(&buffer_position);
11977    snippets
11978        .into_iter()
11979        .filter_map(|snippet| {
11980            let matching_prefix = snippet
11981                .prefix
11982                .iter()
11983                .find(|prefix| prefix.starts_with(&last_word))?;
11984            let start = as_offset - last_word.len();
11985            let start = snapshot.anchor_before(start);
11986            let range = start..buffer_position;
11987            let lsp_start = to_lsp(&start);
11988            let lsp_range = lsp::Range {
11989                start: lsp_start,
11990                end: lsp_end,
11991            };
11992            Some(Completion {
11993                old_range: range,
11994                new_text: snippet.body.clone(),
11995                label: CodeLabel {
11996                    text: matching_prefix.clone(),
11997                    runs: vec![],
11998                    filter_range: 0..matching_prefix.len(),
11999                },
12000                server_id: LanguageServerId(usize::MAX),
12001                documentation: snippet
12002                    .description
12003                    .clone()
12004                    .map(|description| Documentation::SingleLine(description)),
12005                lsp_completion: lsp::CompletionItem {
12006                    label: snippet.prefix.first().unwrap().clone(),
12007                    kind: Some(CompletionItemKind::SNIPPET),
12008                    label_details: snippet.description.as_ref().map(|description| {
12009                        lsp::CompletionItemLabelDetails {
12010                            detail: Some(description.clone()),
12011                            description: None,
12012                        }
12013                    }),
12014                    insert_text_format: Some(InsertTextFormat::SNIPPET),
12015                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12016                        lsp::InsertReplaceEdit {
12017                            new_text: snippet.body.clone(),
12018                            insert: lsp_range,
12019                            replace: lsp_range,
12020                        },
12021                    )),
12022                    filter_text: Some(snippet.body.clone()),
12023                    sort_text: Some(char::MAX.to_string()),
12024                    ..Default::default()
12025                },
12026                confirm: None,
12027                show_new_completions_on_confirm: false,
12028            })
12029        })
12030        .collect()
12031}
12032
12033impl CompletionProvider for Model<Project> {
12034    fn completions(
12035        &self,
12036        buffer: &Model<Buffer>,
12037        buffer_position: text::Anchor,
12038        options: CompletionContext,
12039        cx: &mut ViewContext<Editor>,
12040    ) -> Task<Result<Vec<Completion>>> {
12041        self.update(cx, |project, cx| {
12042            let snippets = snippet_completions(project, buffer, buffer_position, cx);
12043            let project_completions = project.completions(&buffer, buffer_position, options, cx);
12044            cx.background_executor().spawn(async move {
12045                let mut completions = project_completions.await?;
12046                //let snippets = snippets.into_iter().;
12047                completions.extend(snippets);
12048                Ok(completions)
12049            })
12050        })
12051    }
12052
12053    fn resolve_completions(
12054        &self,
12055        buffer: Model<Buffer>,
12056        completion_indices: Vec<usize>,
12057        completions: Arc<RwLock<Box<[Completion]>>>,
12058        cx: &mut ViewContext<Editor>,
12059    ) -> Task<Result<bool>> {
12060        self.update(cx, |project, cx| {
12061            project.resolve_completions(buffer, completion_indices, completions, cx)
12062        })
12063    }
12064
12065    fn apply_additional_edits_for_completion(
12066        &self,
12067        buffer: Model<Buffer>,
12068        completion: Completion,
12069        push_to_history: bool,
12070        cx: &mut ViewContext<Editor>,
12071    ) -> Task<Result<Option<language::Transaction>>> {
12072        self.update(cx, |project, cx| {
12073            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12074        })
12075    }
12076
12077    fn is_completion_trigger(
12078        &self,
12079        buffer: &Model<Buffer>,
12080        position: language::Anchor,
12081        text: &str,
12082        trigger_in_words: bool,
12083        cx: &mut ViewContext<Editor>,
12084    ) -> bool {
12085        if !EditorSettings::get_global(cx).show_completions_on_input {
12086            return false;
12087        }
12088
12089        let mut chars = text.chars();
12090        let char = if let Some(char) = chars.next() {
12091            char
12092        } else {
12093            return false;
12094        };
12095        if chars.next().is_some() {
12096            return false;
12097        }
12098
12099        let buffer = buffer.read(cx);
12100        let scope = buffer.snapshot().language_scope_at(position);
12101        if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
12102            return true;
12103        }
12104
12105        buffer
12106            .completion_triggers()
12107            .iter()
12108            .any(|string| string == text)
12109    }
12110}
12111
12112fn inlay_hint_settings(
12113    location: Anchor,
12114    snapshot: &MultiBufferSnapshot,
12115    cx: &mut ViewContext<'_, Editor>,
12116) -> InlayHintSettings {
12117    let file = snapshot.file_at(location);
12118    let language = snapshot.language_at(location);
12119    let settings = all_language_settings(file, cx);
12120    settings
12121        .language(language.map(|l| l.name()).as_deref())
12122        .inlay_hints
12123}
12124
12125fn consume_contiguous_rows(
12126    contiguous_row_selections: &mut Vec<Selection<Point>>,
12127    selection: &Selection<Point>,
12128    display_map: &DisplaySnapshot,
12129    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12130) -> (MultiBufferRow, MultiBufferRow) {
12131    contiguous_row_selections.push(selection.clone());
12132    let start_row = MultiBufferRow(selection.start.row);
12133    let mut end_row = ending_row(selection, display_map);
12134
12135    while let Some(next_selection) = selections.peek() {
12136        if next_selection.start.row <= end_row.0 {
12137            end_row = ending_row(next_selection, display_map);
12138            contiguous_row_selections.push(selections.next().unwrap().clone());
12139        } else {
12140            break;
12141        }
12142    }
12143    (start_row, end_row)
12144}
12145
12146fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12147    if next_selection.end.column > 0 || next_selection.is_empty() {
12148        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12149    } else {
12150        MultiBufferRow(next_selection.end.row)
12151    }
12152}
12153
12154impl EditorSnapshot {
12155    pub fn remote_selections_in_range<'a>(
12156        &'a self,
12157        range: &'a Range<Anchor>,
12158        collaboration_hub: &dyn CollaborationHub,
12159        cx: &'a AppContext,
12160    ) -> impl 'a + Iterator<Item = RemoteSelection> {
12161        let participant_names = collaboration_hub.user_names(cx);
12162        let participant_indices = collaboration_hub.user_participant_indices(cx);
12163        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12164        let collaborators_by_replica_id = collaborators_by_peer_id
12165            .iter()
12166            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12167            .collect::<HashMap<_, _>>();
12168        self.buffer_snapshot
12169            .selections_in_range(range, false)
12170            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12171                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12172                let participant_index = participant_indices.get(&collaborator.user_id).copied();
12173                let user_name = participant_names.get(&collaborator.user_id).cloned();
12174                Some(RemoteSelection {
12175                    replica_id,
12176                    selection,
12177                    cursor_shape,
12178                    line_mode,
12179                    participant_index,
12180                    peer_id: collaborator.peer_id,
12181                    user_name,
12182                })
12183            })
12184    }
12185
12186    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12187        self.display_snapshot.buffer_snapshot.language_at(position)
12188    }
12189
12190    pub fn is_focused(&self) -> bool {
12191        self.is_focused
12192    }
12193
12194    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12195        self.placeholder_text.as_ref()
12196    }
12197
12198    pub fn scroll_position(&self) -> gpui::Point<f32> {
12199        self.scroll_anchor.scroll_position(&self.display_snapshot)
12200    }
12201
12202    pub fn gutter_dimensions(
12203        &self,
12204        font_id: FontId,
12205        font_size: Pixels,
12206        em_width: Pixels,
12207        max_line_number_width: Pixels,
12208        cx: &AppContext,
12209    ) -> GutterDimensions {
12210        if !self.show_gutter {
12211            return GutterDimensions::default();
12212        }
12213        let descent = cx.text_system().descent(font_id, font_size);
12214
12215        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12216            matches!(
12217                ProjectSettings::get_global(cx).git.git_gutter,
12218                Some(GitGutterSetting::TrackedFiles)
12219            )
12220        });
12221        let gutter_settings = EditorSettings::get_global(cx).gutter;
12222        let show_line_numbers = self
12223            .show_line_numbers
12224            .unwrap_or(gutter_settings.line_numbers);
12225        let line_gutter_width = if show_line_numbers {
12226            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12227            let min_width_for_number_on_gutter = em_width * 4.0;
12228            max_line_number_width.max(min_width_for_number_on_gutter)
12229        } else {
12230            0.0.into()
12231        };
12232
12233        let show_code_actions = self
12234            .show_code_actions
12235            .unwrap_or(gutter_settings.code_actions);
12236
12237        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12238
12239        let git_blame_entries_width = self
12240            .render_git_blame_gutter
12241            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12242
12243        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12244        left_padding += if show_code_actions || show_runnables {
12245            em_width * 3.0
12246        } else if show_git_gutter && show_line_numbers {
12247            em_width * 2.0
12248        } else if show_git_gutter || show_line_numbers {
12249            em_width
12250        } else {
12251            px(0.)
12252        };
12253
12254        let right_padding = if gutter_settings.folds && show_line_numbers {
12255            em_width * 4.0
12256        } else if gutter_settings.folds {
12257            em_width * 3.0
12258        } else if show_line_numbers {
12259            em_width
12260        } else {
12261            px(0.)
12262        };
12263
12264        GutterDimensions {
12265            left_padding,
12266            right_padding,
12267            width: line_gutter_width + left_padding + right_padding,
12268            margin: -descent,
12269            git_blame_entries_width,
12270        }
12271    }
12272
12273    pub fn render_fold_toggle(
12274        &self,
12275        buffer_row: MultiBufferRow,
12276        row_contains_cursor: bool,
12277        editor: View<Editor>,
12278        cx: &mut WindowContext,
12279    ) -> Option<AnyElement> {
12280        let folded = self.is_line_folded(buffer_row);
12281
12282        if let Some(crease) = self
12283            .crease_snapshot
12284            .query_row(buffer_row, &self.buffer_snapshot)
12285        {
12286            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12287                if folded {
12288                    editor.update(cx, |editor, cx| {
12289                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12290                    });
12291                } else {
12292                    editor.update(cx, |editor, cx| {
12293                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12294                    });
12295                }
12296            });
12297
12298            Some((crease.render_toggle)(
12299                buffer_row,
12300                folded,
12301                toggle_callback,
12302                cx,
12303            ))
12304        } else if folded
12305            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12306        {
12307            Some(
12308                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12309                    .selected(folded)
12310                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12311                        if folded {
12312                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
12313                        } else {
12314                            this.fold_at(&FoldAt { buffer_row }, cx);
12315                        }
12316                    }))
12317                    .into_any_element(),
12318            )
12319        } else {
12320            None
12321        }
12322    }
12323
12324    pub fn render_crease_trailer(
12325        &self,
12326        buffer_row: MultiBufferRow,
12327        cx: &mut WindowContext,
12328    ) -> Option<AnyElement> {
12329        let folded = self.is_line_folded(buffer_row);
12330        let crease = self
12331            .crease_snapshot
12332            .query_row(buffer_row, &self.buffer_snapshot)?;
12333        Some((crease.render_trailer)(buffer_row, folded, cx))
12334    }
12335}
12336
12337impl Deref for EditorSnapshot {
12338    type Target = DisplaySnapshot;
12339
12340    fn deref(&self) -> &Self::Target {
12341        &self.display_snapshot
12342    }
12343}
12344
12345#[derive(Clone, Debug, PartialEq, Eq)]
12346pub enum EditorEvent {
12347    InputIgnored {
12348        text: Arc<str>,
12349    },
12350    InputHandled {
12351        utf16_range_to_replace: Option<Range<isize>>,
12352        text: Arc<str>,
12353    },
12354    ExcerptsAdded {
12355        buffer: Model<Buffer>,
12356        predecessor: ExcerptId,
12357        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12358    },
12359    ExcerptsRemoved {
12360        ids: Vec<ExcerptId>,
12361    },
12362    ExcerptsEdited {
12363        ids: Vec<ExcerptId>,
12364    },
12365    ExcerptsExpanded {
12366        ids: Vec<ExcerptId>,
12367    },
12368    BufferEdited,
12369    Edited {
12370        transaction_id: clock::Lamport,
12371    },
12372    Reparsed(BufferId),
12373    Focused,
12374    FocusedIn,
12375    Blurred,
12376    DirtyChanged,
12377    Saved,
12378    TitleChanged,
12379    DiffBaseChanged,
12380    SelectionsChanged {
12381        local: bool,
12382    },
12383    ScrollPositionChanged {
12384        local: bool,
12385        autoscroll: bool,
12386    },
12387    Closed,
12388    TransactionUndone {
12389        transaction_id: clock::Lamport,
12390    },
12391    TransactionBegun {
12392        transaction_id: clock::Lamport,
12393    },
12394}
12395
12396impl EventEmitter<EditorEvent> for Editor {}
12397
12398impl FocusableView for Editor {
12399    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12400        self.focus_handle.clone()
12401    }
12402}
12403
12404impl Render for Editor {
12405    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12406        let settings = ThemeSettings::get_global(cx);
12407
12408        let text_style = match self.mode {
12409            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12410                color: cx.theme().colors().editor_foreground,
12411                font_family: settings.ui_font.family.clone(),
12412                font_features: settings.ui_font.features.clone(),
12413                font_size: rems(0.875).into(),
12414                font_weight: settings.ui_font.weight,
12415                font_style: FontStyle::Normal,
12416                line_height: relative(settings.buffer_line_height.value()),
12417                background_color: None,
12418                underline: None,
12419                strikethrough: None,
12420                white_space: WhiteSpace::Normal,
12421            },
12422            EditorMode::Full => TextStyle {
12423                color: cx.theme().colors().editor_foreground,
12424                font_family: settings.buffer_font.family.clone(),
12425                font_features: settings.buffer_font.features.clone(),
12426                font_size: settings.buffer_font_size(cx).into(),
12427                font_weight: settings.buffer_font.weight,
12428                font_style: FontStyle::Normal,
12429                line_height: relative(settings.buffer_line_height.value()),
12430                background_color: None,
12431                underline: None,
12432                strikethrough: None,
12433                white_space: WhiteSpace::Normal,
12434            },
12435        };
12436
12437        let background = match self.mode {
12438            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12439            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12440            EditorMode::Full => cx.theme().colors().editor_background,
12441        };
12442
12443        EditorElement::new(
12444            cx.view(),
12445            EditorStyle {
12446                background,
12447                local_player: cx.theme().players().local(),
12448                text: text_style,
12449                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12450                syntax: cx.theme().syntax().clone(),
12451                status: cx.theme().status().clone(),
12452                inlay_hints_style: HighlightStyle {
12453                    color: Some(cx.theme().status().hint),
12454                    ..HighlightStyle::default()
12455                },
12456                suggestions_style: HighlightStyle {
12457                    color: Some(cx.theme().status().predictive),
12458                    ..HighlightStyle::default()
12459                },
12460            },
12461        )
12462    }
12463}
12464
12465impl ViewInputHandler for Editor {
12466    fn text_for_range(
12467        &mut self,
12468        range_utf16: Range<usize>,
12469        cx: &mut ViewContext<Self>,
12470    ) -> Option<String> {
12471        Some(
12472            self.buffer
12473                .read(cx)
12474                .read(cx)
12475                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12476                .collect(),
12477        )
12478    }
12479
12480    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12481        // Prevent the IME menu from appearing when holding down an alphabetic key
12482        // while input is disabled.
12483        if !self.input_enabled {
12484            return None;
12485        }
12486
12487        let range = self.selections.newest::<OffsetUtf16>(cx).range();
12488        Some(range.start.0..range.end.0)
12489    }
12490
12491    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12492        let snapshot = self.buffer.read(cx).read(cx);
12493        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12494        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12495    }
12496
12497    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12498        self.clear_highlights::<InputComposition>(cx);
12499        self.ime_transaction.take();
12500    }
12501
12502    fn replace_text_in_range(
12503        &mut self,
12504        range_utf16: Option<Range<usize>>,
12505        text: &str,
12506        cx: &mut ViewContext<Self>,
12507    ) {
12508        if !self.input_enabled {
12509            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12510            return;
12511        }
12512
12513        self.transact(cx, |this, cx| {
12514            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12515                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12516                Some(this.selection_replacement_ranges(range_utf16, cx))
12517            } else {
12518                this.marked_text_ranges(cx)
12519            };
12520
12521            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12522                let newest_selection_id = this.selections.newest_anchor().id;
12523                this.selections
12524                    .all::<OffsetUtf16>(cx)
12525                    .iter()
12526                    .zip(ranges_to_replace.iter())
12527                    .find_map(|(selection, range)| {
12528                        if selection.id == newest_selection_id {
12529                            Some(
12530                                (range.start.0 as isize - selection.head().0 as isize)
12531                                    ..(range.end.0 as isize - selection.head().0 as isize),
12532                            )
12533                        } else {
12534                            None
12535                        }
12536                    })
12537            });
12538
12539            cx.emit(EditorEvent::InputHandled {
12540                utf16_range_to_replace: range_to_replace,
12541                text: text.into(),
12542            });
12543
12544            if let Some(new_selected_ranges) = new_selected_ranges {
12545                this.change_selections(None, cx, |selections| {
12546                    selections.select_ranges(new_selected_ranges)
12547                });
12548                this.backspace(&Default::default(), cx);
12549            }
12550
12551            this.handle_input(text, cx);
12552        });
12553
12554        if let Some(transaction) = self.ime_transaction {
12555            self.buffer.update(cx, |buffer, cx| {
12556                buffer.group_until_transaction(transaction, cx);
12557            });
12558        }
12559
12560        self.unmark_text(cx);
12561    }
12562
12563    fn replace_and_mark_text_in_range(
12564        &mut self,
12565        range_utf16: Option<Range<usize>>,
12566        text: &str,
12567        new_selected_range_utf16: Option<Range<usize>>,
12568        cx: &mut ViewContext<Self>,
12569    ) {
12570        if !self.input_enabled {
12571            return;
12572        }
12573
12574        let transaction = self.transact(cx, |this, cx| {
12575            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12576                let snapshot = this.buffer.read(cx).read(cx);
12577                if let Some(relative_range_utf16) = range_utf16.as_ref() {
12578                    for marked_range in &mut marked_ranges {
12579                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12580                        marked_range.start.0 += relative_range_utf16.start;
12581                        marked_range.start =
12582                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12583                        marked_range.end =
12584                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12585                    }
12586                }
12587                Some(marked_ranges)
12588            } else if let Some(range_utf16) = range_utf16 {
12589                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12590                Some(this.selection_replacement_ranges(range_utf16, cx))
12591            } else {
12592                None
12593            };
12594
12595            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12596                let newest_selection_id = this.selections.newest_anchor().id;
12597                this.selections
12598                    .all::<OffsetUtf16>(cx)
12599                    .iter()
12600                    .zip(ranges_to_replace.iter())
12601                    .find_map(|(selection, range)| {
12602                        if selection.id == newest_selection_id {
12603                            Some(
12604                                (range.start.0 as isize - selection.head().0 as isize)
12605                                    ..(range.end.0 as isize - selection.head().0 as isize),
12606                            )
12607                        } else {
12608                            None
12609                        }
12610                    })
12611            });
12612
12613            cx.emit(EditorEvent::InputHandled {
12614                utf16_range_to_replace: range_to_replace,
12615                text: text.into(),
12616            });
12617
12618            if let Some(ranges) = ranges_to_replace {
12619                this.change_selections(None, cx, |s| s.select_ranges(ranges));
12620            }
12621
12622            let marked_ranges = {
12623                let snapshot = this.buffer.read(cx).read(cx);
12624                this.selections
12625                    .disjoint_anchors()
12626                    .iter()
12627                    .map(|selection| {
12628                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12629                    })
12630                    .collect::<Vec<_>>()
12631            };
12632
12633            if text.is_empty() {
12634                this.unmark_text(cx);
12635            } else {
12636                this.highlight_text::<InputComposition>(
12637                    marked_ranges.clone(),
12638                    HighlightStyle {
12639                        underline: Some(UnderlineStyle {
12640                            thickness: px(1.),
12641                            color: None,
12642                            wavy: false,
12643                        }),
12644                        ..Default::default()
12645                    },
12646                    cx,
12647                );
12648            }
12649
12650            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12651            let use_autoclose = this.use_autoclose;
12652            let use_auto_surround = this.use_auto_surround;
12653            this.set_use_autoclose(false);
12654            this.set_use_auto_surround(false);
12655            this.handle_input(text, cx);
12656            this.set_use_autoclose(use_autoclose);
12657            this.set_use_auto_surround(use_auto_surround);
12658
12659            if let Some(new_selected_range) = new_selected_range_utf16 {
12660                let snapshot = this.buffer.read(cx).read(cx);
12661                let new_selected_ranges = marked_ranges
12662                    .into_iter()
12663                    .map(|marked_range| {
12664                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12665                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12666                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12667                        snapshot.clip_offset_utf16(new_start, Bias::Left)
12668                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12669                    })
12670                    .collect::<Vec<_>>();
12671
12672                drop(snapshot);
12673                this.change_selections(None, cx, |selections| {
12674                    selections.select_ranges(new_selected_ranges)
12675                });
12676            }
12677        });
12678
12679        self.ime_transaction = self.ime_transaction.or(transaction);
12680        if let Some(transaction) = self.ime_transaction {
12681            self.buffer.update(cx, |buffer, cx| {
12682                buffer.group_until_transaction(transaction, cx);
12683            });
12684        }
12685
12686        if self.text_highlights::<InputComposition>(cx).is_none() {
12687            self.ime_transaction.take();
12688        }
12689    }
12690
12691    fn bounds_for_range(
12692        &mut self,
12693        range_utf16: Range<usize>,
12694        element_bounds: gpui::Bounds<Pixels>,
12695        cx: &mut ViewContext<Self>,
12696    ) -> Option<gpui::Bounds<Pixels>> {
12697        let text_layout_details = self.text_layout_details(cx);
12698        let style = &text_layout_details.editor_style;
12699        let font_id = cx.text_system().resolve_font(&style.text.font());
12700        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12701        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12702
12703        let em_width = cx
12704            .text_system()
12705            .typographic_bounds(font_id, font_size, 'm')
12706            .unwrap()
12707            .size
12708            .width;
12709
12710        let snapshot = self.snapshot(cx);
12711        let scroll_position = snapshot.scroll_position();
12712        let scroll_left = scroll_position.x * em_width;
12713
12714        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12715        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12716            + self.gutter_dimensions.width;
12717        let y = line_height * (start.row().as_f32() - scroll_position.y);
12718
12719        Some(Bounds {
12720            origin: element_bounds.origin + point(x, y),
12721            size: size(em_width, line_height),
12722        })
12723    }
12724}
12725
12726trait SelectionExt {
12727    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12728    fn spanned_rows(
12729        &self,
12730        include_end_if_at_line_start: bool,
12731        map: &DisplaySnapshot,
12732    ) -> Range<MultiBufferRow>;
12733}
12734
12735impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12736    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12737        let start = self
12738            .start
12739            .to_point(&map.buffer_snapshot)
12740            .to_display_point(map);
12741        let end = self
12742            .end
12743            .to_point(&map.buffer_snapshot)
12744            .to_display_point(map);
12745        if self.reversed {
12746            end..start
12747        } else {
12748            start..end
12749        }
12750    }
12751
12752    fn spanned_rows(
12753        &self,
12754        include_end_if_at_line_start: bool,
12755        map: &DisplaySnapshot,
12756    ) -> Range<MultiBufferRow> {
12757        let start = self.start.to_point(&map.buffer_snapshot);
12758        let mut end = self.end.to_point(&map.buffer_snapshot);
12759        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12760            end.row -= 1;
12761        }
12762
12763        let buffer_start = map.prev_line_boundary(start).0;
12764        let buffer_end = map.next_line_boundary(end).0;
12765        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12766    }
12767}
12768
12769impl<T: InvalidationRegion> InvalidationStack<T> {
12770    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12771    where
12772        S: Clone + ToOffset,
12773    {
12774        while let Some(region) = self.last() {
12775            let all_selections_inside_invalidation_ranges =
12776                if selections.len() == region.ranges().len() {
12777                    selections
12778                        .iter()
12779                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12780                        .all(|(selection, invalidation_range)| {
12781                            let head = selection.head().to_offset(buffer);
12782                            invalidation_range.start <= head && invalidation_range.end >= head
12783                        })
12784                } else {
12785                    false
12786                };
12787
12788            if all_selections_inside_invalidation_ranges {
12789                break;
12790            } else {
12791                self.pop();
12792            }
12793        }
12794    }
12795}
12796
12797impl<T> Default for InvalidationStack<T> {
12798    fn default() -> Self {
12799        Self(Default::default())
12800    }
12801}
12802
12803impl<T> Deref for InvalidationStack<T> {
12804    type Target = Vec<T>;
12805
12806    fn deref(&self) -> &Self::Target {
12807        &self.0
12808    }
12809}
12810
12811impl<T> DerefMut for InvalidationStack<T> {
12812    fn deref_mut(&mut self) -> &mut Self::Target {
12813        &mut self.0
12814    }
12815}
12816
12817impl InvalidationRegion for SnippetState {
12818    fn ranges(&self) -> &[Range<Anchor>] {
12819        &self.ranges[self.active_index]
12820    }
12821}
12822
12823pub fn diagnostic_block_renderer(
12824    diagnostic: Diagnostic,
12825    max_message_rows: Option<u8>,
12826    allow_closing: bool,
12827    _is_valid: bool,
12828) -> RenderBlock {
12829    let (text_without_backticks, code_ranges) =
12830        highlight_diagnostic_message(&diagnostic, max_message_rows);
12831
12832    Box::new(move |cx: &mut BlockContext| {
12833        let group_id: SharedString = cx.transform_block_id.to_string().into();
12834
12835        let mut text_style = cx.text_style().clone();
12836        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
12837        let theme_settings = ThemeSettings::get_global(cx);
12838        text_style.font_family = theme_settings.buffer_font.family.clone();
12839        text_style.font_style = theme_settings.buffer_font.style;
12840        text_style.font_features = theme_settings.buffer_font.features.clone();
12841        text_style.font_weight = theme_settings.buffer_font.weight;
12842
12843        let multi_line_diagnostic = diagnostic.message.contains('\n');
12844
12845        let buttons = |diagnostic: &Diagnostic, block_id: TransformBlockId| {
12846            if multi_line_diagnostic {
12847                v_flex()
12848            } else {
12849                h_flex()
12850            }
12851            .when(allow_closing, |div| {
12852                div.children(diagnostic.is_primary.then(|| {
12853                    IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
12854                        .icon_color(Color::Muted)
12855                        .size(ButtonSize::Compact)
12856                        .style(ButtonStyle::Transparent)
12857                        .visible_on_hover(group_id.clone())
12858                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
12859                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
12860                }))
12861            })
12862            .child(
12863                IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
12864                    .icon_color(Color::Muted)
12865                    .size(ButtonSize::Compact)
12866                    .style(ButtonStyle::Transparent)
12867                    .visible_on_hover(group_id.clone())
12868                    .on_click({
12869                        let message = diagnostic.message.clone();
12870                        move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
12871                    })
12872                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
12873            )
12874        };
12875
12876        let icon_size = buttons(&diagnostic, cx.transform_block_id)
12877            .into_any_element()
12878            .layout_as_root(AvailableSpace::min_size(), cx);
12879
12880        h_flex()
12881            .id(cx.transform_block_id)
12882            .group(group_id.clone())
12883            .relative()
12884            .size_full()
12885            .pl(cx.gutter_dimensions.width)
12886            .w(cx.max_width + cx.gutter_dimensions.width)
12887            .child(
12888                div()
12889                    .flex()
12890                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
12891                    .flex_shrink(),
12892            )
12893            .child(buttons(&diagnostic, cx.transform_block_id))
12894            .child(div().flex().flex_shrink_0().child(
12895                StyledText::new(text_without_backticks.clone()).with_highlights(
12896                    &text_style,
12897                    code_ranges.iter().map(|range| {
12898                        (
12899                            range.clone(),
12900                            HighlightStyle {
12901                                font_weight: Some(FontWeight::BOLD),
12902                                ..Default::default()
12903                            },
12904                        )
12905                    }),
12906                ),
12907            ))
12908            .into_any_element()
12909    })
12910}
12911
12912pub fn highlight_diagnostic_message(
12913    diagnostic: &Diagnostic,
12914    mut max_message_rows: Option<u8>,
12915) -> (SharedString, Vec<Range<usize>>) {
12916    let mut text_without_backticks = String::new();
12917    let mut code_ranges = Vec::new();
12918
12919    if let Some(source) = &diagnostic.source {
12920        text_without_backticks.push_str(&source);
12921        code_ranges.push(0..source.len());
12922        text_without_backticks.push_str(": ");
12923    }
12924
12925    let mut prev_offset = 0;
12926    let mut in_code_block = false;
12927    let has_row_limit = max_message_rows.is_some();
12928    let mut newline_indices = diagnostic
12929        .message
12930        .match_indices('\n')
12931        .filter(|_| has_row_limit)
12932        .map(|(ix, _)| ix)
12933        .fuse()
12934        .peekable();
12935
12936    for (quote_ix, _) in diagnostic
12937        .message
12938        .match_indices('`')
12939        .chain([(diagnostic.message.len(), "")])
12940    {
12941        let mut first_newline_ix = None;
12942        let mut last_newline_ix = None;
12943        while let Some(newline_ix) = newline_indices.peek() {
12944            if *newline_ix < quote_ix {
12945                if first_newline_ix.is_none() {
12946                    first_newline_ix = Some(*newline_ix);
12947                }
12948                last_newline_ix = Some(*newline_ix);
12949
12950                if let Some(rows_left) = &mut max_message_rows {
12951                    if *rows_left == 0 {
12952                        break;
12953                    } else {
12954                        *rows_left -= 1;
12955                    }
12956                }
12957                let _ = newline_indices.next();
12958            } else {
12959                break;
12960            }
12961        }
12962        let prev_len = text_without_backticks.len();
12963        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
12964        text_without_backticks.push_str(new_text);
12965        if in_code_block {
12966            code_ranges.push(prev_len..text_without_backticks.len());
12967        }
12968        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
12969        in_code_block = !in_code_block;
12970        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
12971            text_without_backticks.push_str("...");
12972            break;
12973        }
12974    }
12975
12976    (text_without_backticks.into(), code_ranges)
12977}
12978
12979fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
12980    match severity {
12981        DiagnosticSeverity::ERROR => colors.error,
12982        DiagnosticSeverity::WARNING => colors.warning,
12983        DiagnosticSeverity::INFORMATION => colors.info,
12984        DiagnosticSeverity::HINT => colors.info,
12985        _ => colors.ignored,
12986    }
12987}
12988
12989pub fn styled_runs_for_code_label<'a>(
12990    label: &'a CodeLabel,
12991    syntax_theme: &'a theme::SyntaxTheme,
12992) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
12993    let fade_out = HighlightStyle {
12994        fade_out: Some(0.35),
12995        ..Default::default()
12996    };
12997
12998    let mut prev_end = label.filter_range.end;
12999    label
13000        .runs
13001        .iter()
13002        .enumerate()
13003        .flat_map(move |(ix, (range, highlight_id))| {
13004            let style = if let Some(style) = highlight_id.style(syntax_theme) {
13005                style
13006            } else {
13007                return Default::default();
13008            };
13009            let mut muted_style = style;
13010            muted_style.highlight(fade_out);
13011
13012            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13013            if range.start >= label.filter_range.end {
13014                if range.start > prev_end {
13015                    runs.push((prev_end..range.start, fade_out));
13016                }
13017                runs.push((range.clone(), muted_style));
13018            } else if range.end <= label.filter_range.end {
13019                runs.push((range.clone(), style));
13020            } else {
13021                runs.push((range.start..label.filter_range.end, style));
13022                runs.push((label.filter_range.end..range.end, muted_style));
13023            }
13024            prev_end = cmp::max(prev_end, range.end);
13025
13026            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13027                runs.push((prev_end..label.text.len(), fade_out));
13028            }
13029
13030            runs
13031        })
13032}
13033
13034pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13035    let mut prev_index = 0;
13036    let mut prev_codepoint: Option<char> = None;
13037    text.char_indices()
13038        .chain([(text.len(), '\0')])
13039        .filter_map(move |(index, codepoint)| {
13040            let prev_codepoint = prev_codepoint.replace(codepoint)?;
13041            let is_boundary = index == text.len()
13042                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13043                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13044            if is_boundary {
13045                let chunk = &text[prev_index..index];
13046                prev_index = index;
13047                Some(chunk)
13048            } else {
13049                None
13050            }
13051        })
13052}
13053
13054pub trait RangeToAnchorExt: Sized {
13055    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13056
13057    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13058        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13059        anchor_range.start.to_display_point(&snapshot)..anchor_range.end.to_display_point(&snapshot)
13060    }
13061}
13062
13063impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13064    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13065        let start_offset = self.start.to_offset(snapshot);
13066        let end_offset = self.end.to_offset(snapshot);
13067        if start_offset == end_offset {
13068            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13069        } else {
13070            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13071        }
13072    }
13073}
13074
13075pub trait RowExt {
13076    fn as_f32(&self) -> f32;
13077
13078    fn next_row(&self) -> Self;
13079
13080    fn previous_row(&self) -> Self;
13081
13082    fn minus(&self, other: Self) -> u32;
13083}
13084
13085impl RowExt for DisplayRow {
13086    fn as_f32(&self) -> f32 {
13087        self.0 as f32
13088    }
13089
13090    fn next_row(&self) -> Self {
13091        Self(self.0 + 1)
13092    }
13093
13094    fn previous_row(&self) -> Self {
13095        Self(self.0.saturating_sub(1))
13096    }
13097
13098    fn minus(&self, other: Self) -> u32 {
13099        self.0 - other.0
13100    }
13101}
13102
13103impl RowExt for MultiBufferRow {
13104    fn as_f32(&self) -> f32 {
13105        self.0 as f32
13106    }
13107
13108    fn next_row(&self) -> Self {
13109        Self(self.0 + 1)
13110    }
13111
13112    fn previous_row(&self) -> Self {
13113        Self(self.0.saturating_sub(1))
13114    }
13115
13116    fn minus(&self, other: Self) -> u32 {
13117        self.0 - other.0
13118    }
13119}
13120
13121trait RowRangeExt {
13122    type Row;
13123
13124    fn len(&self) -> usize;
13125
13126    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13127}
13128
13129impl RowRangeExt for Range<MultiBufferRow> {
13130    type Row = MultiBufferRow;
13131
13132    fn len(&self) -> usize {
13133        (self.end.0 - self.start.0) as usize
13134    }
13135
13136    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13137        (self.start.0..self.end.0).map(MultiBufferRow)
13138    }
13139}
13140
13141impl RowRangeExt for Range<DisplayRow> {
13142    type Row = DisplayRow;
13143
13144    fn len(&self) -> usize {
13145        (self.end.0 - self.start.0) as usize
13146    }
13147
13148    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13149        (self.start.0..self.end.0).map(DisplayRow)
13150    }
13151}
13152
13153fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13154    if hunk.diff_base_byte_range.is_empty() {
13155        DiffHunkStatus::Added
13156    } else if hunk.associated_range.is_empty() {
13157        DiffHunkStatus::Removed
13158    } else {
13159        DiffHunkStatus::Modified
13160    }
13161}