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 behavior.
   15pub mod actions;
   16mod blame_entry_tooltip;
   17mod blink_manager;
   18mod debounced_delay;
   19pub mod display_map;
   20mod editor_settings;
   21mod editor_settings_controls;
   22mod element;
   23mod git;
   24mod highlight_matching_bracket;
   25mod hover_links;
   26mod hover_popover;
   27mod hunk_diff;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30mod inline_completion_provider;
   31pub mod items;
   32mod linked_editing_ranges;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod rust_analyzer_ext;
   37pub mod scroll;
   38mod selections_collection;
   39pub mod tasks;
   40
   41#[cfg(test)]
   42mod editor_tests;
   43mod signature_help;
   44#[cfg(any(test, feature = "test-support"))]
   45pub mod test;
   46
   47use ::git::diff::{DiffHunk, DiffHunkStatus};
   48use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
   49pub(crate) use actions::*;
   50use aho_corasick::AhoCorasick;
   51use anyhow::{anyhow, Context as _, Result};
   52use blink_manager::BlinkManager;
   53use client::{Collaborator, ParticipantIndex};
   54use clock::ReplicaId;
   55use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   56use convert_case::{Case, Casing};
   57use debounced_delay::DebouncedDelay;
   58use display_map::*;
   59pub use display_map::{DisplayPoint, FoldPlaceholder};
   60pub use editor_settings::{CurrentLineHighlight, EditorSettings};
   61pub use editor_settings_controls::*;
   62use element::LineWithInvisibles;
   63pub use element::{
   64    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   65};
   66use futures::FutureExt;
   67use fuzzy::{StringMatch, StringMatchCandidate};
   68use git::blame::GitBlame;
   69use git::diff_hunk_to_display;
   70use gpui::{
   71    div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
   72    AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardItem,
   73    Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle, FocusOutEvent,
   74    FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext,
   75    ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString,
   76    Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle, UnderlineStyle,
   77    UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
   78    WeakView, WindowContext,
   79};
   80use highlight_matching_bracket::refresh_matching_bracket_highlights;
   81use hover_popover::{hide_hover, HoverState};
   82use hunk_diff::ExpandedHunks;
   83pub(crate) use hunk_diff::HoveredHunk;
   84use indent_guides::ActiveIndentGuidesState;
   85use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   86pub use inline_completion_provider::*;
   87pub use items::MAX_TAB_TITLE_LEN;
   88use itertools::Itertools;
   89use language::{
   90    char_kind,
   91    language_settings::{self, all_language_settings, InlayHintSettings},
   92    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   93    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
   94    Point, Selection, SelectionGoal, TransactionId,
   95};
   96use language::{point_to_lsp, BufferRow, Runnable, RunnableRange};
   97use linked_editing_ranges::refresh_linked_ranges;
   98use task::{ResolvedTask, TaskTemplate, TaskVariables};
   99
  100use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
  101pub use lsp::CompletionContext;
  102use lsp::{
  103    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  104    LanguageServerId,
  105};
  106use mouse_context_menu::MouseContextMenu;
  107use movement::TextLayoutDetails;
  108pub use multi_buffer::{
  109    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  110    ToPoint,
  111};
  112use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
  113use ordered_float::OrderedFloat;
  114use parking_lot::{Mutex, RwLock};
  115use project::project_settings::{GitGutterSetting, ProjectSettings};
  116use project::{
  117    CodeAction, Completion, FormatTrigger, Item, Location, Project, ProjectPath,
  118    ProjectTransaction, TaskSourceKind, WorktreeId,
  119};
  120use rand::prelude::*;
  121use rpc::{proto::*, ErrorExt};
  122use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  123use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  124use serde::{Deserialize, Serialize};
  125use settings::{update_settings_file, Settings, SettingsStore};
  126use smallvec::SmallVec;
  127use snippet::Snippet;
  128use std::{
  129    any::TypeId,
  130    borrow::Cow,
  131    cell::RefCell,
  132    cmp::{self, Ordering, Reverse},
  133    mem,
  134    num::NonZeroU32,
  135    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  136    path::{Path, PathBuf},
  137    rc::Rc,
  138    sync::Arc,
  139    time::{Duration, Instant},
  140};
  141pub use sum_tree::Bias;
  142use sum_tree::TreeMap;
  143use text::{BufferId, OffsetUtf16, Rope};
  144use theme::{
  145    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  146    ThemeColors, ThemeSettings,
  147};
  148use ui::{
  149    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  150    ListItem, Popover, Tooltip,
  151};
  152use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  153use workspace::item::{ItemHandle, PreviewTabsSettings};
  154use workspace::notifications::{DetachAndPromptErr, NotificationId};
  155use workspace::{
  156    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  157};
  158use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  159
  160use crate::hover_links::find_url;
  161use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  162
  163pub const FILE_HEADER_HEIGHT: u8 = 1;
  164pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u8 = 1;
  165pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u8 = 1;
  166pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  167const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  168const MAX_LINE_LEN: usize = 1024;
  169const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  170const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  171pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  172#[doc(hidden)]
  173pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  174#[doc(hidden)]
  175pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
  176
  177pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  178
  179pub fn render_parsed_markdown(
  180    element_id: impl Into<ElementId>,
  181    parsed: &language::ParsedMarkdown,
  182    editor_style: &EditorStyle,
  183    workspace: Option<WeakView<Workspace>>,
  184    cx: &mut WindowContext,
  185) -> InteractiveText {
  186    let code_span_background_color = cx
  187        .theme()
  188        .colors()
  189        .editor_document_highlight_read_background;
  190
  191    let highlights = gpui::combine_highlights(
  192        parsed.highlights.iter().filter_map(|(range, highlight)| {
  193            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  194            Some((range.clone(), highlight))
  195        }),
  196        parsed
  197            .regions
  198            .iter()
  199            .zip(&parsed.region_ranges)
  200            .filter_map(|(region, range)| {
  201                if region.code {
  202                    Some((
  203                        range.clone(),
  204                        HighlightStyle {
  205                            background_color: Some(code_span_background_color),
  206                            ..Default::default()
  207                        },
  208                    ))
  209                } else {
  210                    None
  211                }
  212            }),
  213    );
  214
  215    let mut links = Vec::new();
  216    let mut link_ranges = Vec::new();
  217    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  218        if let Some(link) = region.link.clone() {
  219            links.push(link);
  220            link_ranges.push(range.clone());
  221        }
  222    }
  223
  224    InteractiveText::new(
  225        element_id,
  226        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  227    )
  228    .on_click(link_ranges, move |clicked_range_ix, cx| {
  229        match &links[clicked_range_ix] {
  230            markdown::Link::Web { url } => cx.open_url(url),
  231            markdown::Link::Path { path } => {
  232                if let Some(workspace) = &workspace {
  233                    _ = workspace.update(cx, |workspace, cx| {
  234                        workspace.open_abs_path(path.clone(), false, cx).detach();
  235                    });
  236                }
  237            }
  238        }
  239    })
  240}
  241
  242#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  243pub(crate) enum InlayId {
  244    Suggestion(usize),
  245    Hint(usize),
  246}
  247
  248impl InlayId {
  249    fn id(&self) -> usize {
  250        match self {
  251            Self::Suggestion(id) => *id,
  252            Self::Hint(id) => *id,
  253        }
  254    }
  255}
  256
  257enum DiffRowHighlight {}
  258enum DocumentHighlightRead {}
  259enum DocumentHighlightWrite {}
  260enum InputComposition {}
  261
  262#[derive(Copy, Clone, PartialEq, Eq)]
  263pub enum Direction {
  264    Prev,
  265    Next,
  266}
  267
  268pub fn init_settings(cx: &mut AppContext) {
  269    EditorSettings::register(cx);
  270}
  271
  272pub fn init(cx: &mut AppContext) {
  273    init_settings(cx);
  274
  275    workspace::register_project_item::<Editor>(cx);
  276    workspace::FollowableViewRegistry::register::<Editor>(cx);
  277    workspace::register_serializable_item::<Editor>(cx);
  278
  279    cx.observe_new_views(
  280        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  281            workspace.register_action(Editor::new_file);
  282            workspace.register_action(Editor::new_file_in_direction);
  283        },
  284    )
  285    .detach();
  286
  287    cx.on_action(move |_: &workspace::NewFile, cx| {
  288        let app_state = workspace::AppState::global(cx);
  289        if let Some(app_state) = app_state.upgrade() {
  290            workspace::open_new(app_state, cx, |workspace, cx| {
  291                Editor::new_file(workspace, &Default::default(), cx)
  292            })
  293            .detach();
  294        }
  295    });
  296    cx.on_action(move |_: &workspace::NewWindow, cx| {
  297        let app_state = workspace::AppState::global(cx);
  298        if let Some(app_state) = app_state.upgrade() {
  299            workspace::open_new(app_state, cx, |workspace, cx| {
  300                Editor::new_file(workspace, &Default::default(), cx)
  301            })
  302            .detach();
  303        }
  304    });
  305}
  306
  307pub struct SearchWithinRange;
  308
  309trait InvalidationRegion {
  310    fn ranges(&self) -> &[Range<Anchor>];
  311}
  312
  313#[derive(Clone, Debug, PartialEq)]
  314pub enum SelectPhase {
  315    Begin {
  316        position: DisplayPoint,
  317        add: bool,
  318        click_count: usize,
  319    },
  320    BeginColumnar {
  321        position: DisplayPoint,
  322        reset: bool,
  323        goal_column: u32,
  324    },
  325    Extend {
  326        position: DisplayPoint,
  327        click_count: usize,
  328    },
  329    Update {
  330        position: DisplayPoint,
  331        goal_column: u32,
  332        scroll_delta: gpui::Point<f32>,
  333    },
  334    End,
  335}
  336
  337#[derive(Clone, Debug)]
  338pub enum SelectMode {
  339    Character,
  340    Word(Range<Anchor>),
  341    Line(Range<Anchor>),
  342    All,
  343}
  344
  345#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  346pub enum EditorMode {
  347    SingleLine { auto_width: bool },
  348    AutoHeight { max_lines: usize },
  349    Full,
  350}
  351
  352#[derive(Clone, Debug)]
  353pub enum SoftWrap {
  354    None,
  355    PreferLine,
  356    EditorWidth,
  357    Column(u32),
  358}
  359
  360#[derive(Clone)]
  361pub struct EditorStyle {
  362    pub background: Hsla,
  363    pub local_player: PlayerColor,
  364    pub text: TextStyle,
  365    pub scrollbar_width: Pixels,
  366    pub syntax: Arc<SyntaxTheme>,
  367    pub status: StatusColors,
  368    pub inlay_hints_style: HighlightStyle,
  369    pub suggestions_style: HighlightStyle,
  370}
  371
  372impl Default for EditorStyle {
  373    fn default() -> Self {
  374        Self {
  375            background: Hsla::default(),
  376            local_player: PlayerColor::default(),
  377            text: TextStyle::default(),
  378            scrollbar_width: Pixels::default(),
  379            syntax: Default::default(),
  380            // HACK: Status colors don't have a real default.
  381            // We should look into removing the status colors from the editor
  382            // style and retrieve them directly from the theme.
  383            status: StatusColors::dark(),
  384            inlay_hints_style: HighlightStyle::default(),
  385            suggestions_style: HighlightStyle::default(),
  386        }
  387    }
  388}
  389
  390type CompletionId = usize;
  391
  392#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  393struct EditorActionId(usize);
  394
  395impl EditorActionId {
  396    pub fn post_inc(&mut self) -> Self {
  397        let answer = self.0;
  398
  399        *self = Self(answer + 1);
  400
  401        Self(answer)
  402    }
  403}
  404
  405// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  406// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  407
  408type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  409type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  410
  411#[derive(Default)]
  412struct ScrollbarMarkerState {
  413    scrollbar_size: Size<Pixels>,
  414    dirty: bool,
  415    markers: Arc<[PaintQuad]>,
  416    pending_refresh: Option<Task<Result<()>>>,
  417}
  418
  419impl ScrollbarMarkerState {
  420    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  421        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  422    }
  423}
  424
  425#[derive(Clone, Debug)]
  426struct RunnableTasks {
  427    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  428    offset: MultiBufferOffset,
  429    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  430    column: u32,
  431    // Values of all named captures, including those starting with '_'
  432    extra_variables: HashMap<String, String>,
  433    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  434    context_range: Range<BufferOffset>,
  435}
  436
  437#[derive(Clone)]
  438struct ResolvedTasks {
  439    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  440    position: Anchor,
  441}
  442#[derive(Copy, Clone, Debug)]
  443struct MultiBufferOffset(usize);
  444#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  445struct BufferOffset(usize);
  446/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  447///
  448/// See the [module level documentation](self) for more information.
  449pub struct Editor {
  450    focus_handle: FocusHandle,
  451    last_focused_descendant: Option<WeakFocusHandle>,
  452    /// The text buffer being edited
  453    buffer: Model<MultiBuffer>,
  454    /// Map of how text in the buffer should be displayed.
  455    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  456    pub display_map: Model<DisplayMap>,
  457    pub selections: SelectionsCollection,
  458    pub scroll_manager: ScrollManager,
  459    /// When inline assist editors are linked, they all render cursors because
  460    /// typing enters text into each of them, even the ones that aren't focused.
  461    pub(crate) show_cursor_when_unfocused: bool,
  462    columnar_selection_tail: Option<Anchor>,
  463    add_selections_state: Option<AddSelectionsState>,
  464    select_next_state: Option<SelectNextState>,
  465    select_prev_state: Option<SelectNextState>,
  466    selection_history: SelectionHistory,
  467    autoclose_regions: Vec<AutocloseRegion>,
  468    snippet_stack: InvalidationStack<SnippetState>,
  469    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  470    ime_transaction: Option<TransactionId>,
  471    active_diagnostics: Option<ActiveDiagnosticGroup>,
  472    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  473    project: Option<Model<Project>>,
  474    completion_provider: Option<Box<dyn CompletionProvider>>,
  475    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  476    blink_manager: Model<BlinkManager>,
  477    show_cursor_names: bool,
  478    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  479    pub show_local_selections: bool,
  480    mode: EditorMode,
  481    show_breadcrumbs: bool,
  482    show_gutter: bool,
  483    show_line_numbers: Option<bool>,
  484    show_git_diff_gutter: Option<bool>,
  485    show_code_actions: Option<bool>,
  486    show_runnables: Option<bool>,
  487    show_wrap_guides: Option<bool>,
  488    show_indent_guides: Option<bool>,
  489    placeholder_text: Option<Arc<str>>,
  490    highlight_order: usize,
  491    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  492    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  493    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  494    scrollbar_marker_state: ScrollbarMarkerState,
  495    active_indent_guides_state: ActiveIndentGuidesState,
  496    nav_history: Option<ItemNavHistory>,
  497    context_menu: RwLock<Option<ContextMenu>>,
  498    mouse_context_menu: Option<MouseContextMenu>,
  499    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  500    signature_help_state: SignatureHelpState,
  501    auto_signature_help: Option<bool>,
  502    find_all_references_task_sources: Vec<Anchor>,
  503    next_completion_id: CompletionId,
  504    completion_documentation_pre_resolve_debounce: DebouncedDelay,
  505    available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
  506    code_actions_task: Option<Task<()>>,
  507    document_highlights_task: Option<Task<()>>,
  508    linked_editing_range_task: Option<Task<Option<()>>>,
  509    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  510    pending_rename: Option<RenameState>,
  511    searchable: bool,
  512    cursor_shape: CursorShape,
  513    current_line_highlight: Option<CurrentLineHighlight>,
  514    collapse_matches: bool,
  515    autoindent_mode: Option<AutoindentMode>,
  516    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  517    keymap_context_layers: BTreeMap<TypeId, KeyContext>,
  518    input_enabled: bool,
  519    use_modal_editing: bool,
  520    read_only: bool,
  521    leader_peer_id: Option<PeerId>,
  522    remote_id: Option<ViewId>,
  523    hover_state: HoverState,
  524    gutter_hovered: bool,
  525    hovered_link_state: Option<HoveredLinkState>,
  526    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  527    active_inline_completion: Option<(Inlay, Option<Range<Anchor>>)>,
  528    show_inline_completions: bool,
  529    inlay_hint_cache: InlayHintCache,
  530    expanded_hunks: ExpandedHunks,
  531    next_inlay_id: usize,
  532    _subscriptions: Vec<Subscription>,
  533    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  534    gutter_dimensions: GutterDimensions,
  535    pub vim_replace_map: HashMap<Range<usize>, String>,
  536    style: Option<EditorStyle>,
  537    next_editor_action_id: EditorActionId,
  538    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  539    use_autoclose: bool,
  540    use_auto_surround: bool,
  541    auto_replace_emoji_shortcode: bool,
  542    show_git_blame_gutter: bool,
  543    show_git_blame_inline: bool,
  544    show_git_blame_inline_delay_task: Option<Task<()>>,
  545    git_blame_inline_enabled: bool,
  546    serialize_dirty_buffers: bool,
  547    show_selection_menu: Option<bool>,
  548    blame: Option<Model<GitBlame>>,
  549    blame_subscription: Option<Subscription>,
  550    custom_context_menu: Option<
  551        Box<
  552            dyn 'static
  553                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  554        >,
  555    >,
  556    last_bounds: Option<Bounds<Pixels>>,
  557    expect_bounds_change: Option<Bounds<Pixels>>,
  558    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  559    tasks_update_task: Option<Task<()>>,
  560    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  561    file_header_size: u8,
  562    breadcrumb_header: Option<String>,
  563    focused_block: Option<FocusedBlock>,
  564}
  565
  566#[derive(Clone)]
  567pub struct EditorSnapshot {
  568    pub mode: EditorMode,
  569    show_gutter: bool,
  570    show_line_numbers: Option<bool>,
  571    show_git_diff_gutter: Option<bool>,
  572    show_code_actions: Option<bool>,
  573    show_runnables: Option<bool>,
  574    render_git_blame_gutter: bool,
  575    pub display_snapshot: DisplaySnapshot,
  576    pub placeholder_text: Option<Arc<str>>,
  577    is_focused: bool,
  578    scroll_anchor: ScrollAnchor,
  579    ongoing_scroll: OngoingScroll,
  580    current_line_highlight: CurrentLineHighlight,
  581    gutter_hovered: bool,
  582}
  583
  584const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
  585
  586#[derive(Default, Debug, Clone, Copy)]
  587pub struct GutterDimensions {
  588    pub left_padding: Pixels,
  589    pub right_padding: Pixels,
  590    pub width: Pixels,
  591    pub margin: Pixels,
  592    pub git_blame_entries_width: Option<Pixels>,
  593}
  594
  595impl GutterDimensions {
  596    /// The full width of the space taken up by the gutter.
  597    pub fn full_width(&self) -> Pixels {
  598        self.margin + self.width
  599    }
  600
  601    /// The width of the space reserved for the fold indicators,
  602    /// use alongside 'justify_end' and `gutter_width` to
  603    /// right align content with the line numbers
  604    pub fn fold_area_width(&self) -> Pixels {
  605        self.margin + self.right_padding
  606    }
  607}
  608
  609#[derive(Debug)]
  610pub struct RemoteSelection {
  611    pub replica_id: ReplicaId,
  612    pub selection: Selection<Anchor>,
  613    pub cursor_shape: CursorShape,
  614    pub peer_id: PeerId,
  615    pub line_mode: bool,
  616    pub participant_index: Option<ParticipantIndex>,
  617    pub user_name: Option<SharedString>,
  618}
  619
  620#[derive(Clone, Debug)]
  621struct SelectionHistoryEntry {
  622    selections: Arc<[Selection<Anchor>]>,
  623    select_next_state: Option<SelectNextState>,
  624    select_prev_state: Option<SelectNextState>,
  625    add_selections_state: Option<AddSelectionsState>,
  626}
  627
  628enum SelectionHistoryMode {
  629    Normal,
  630    Undoing,
  631    Redoing,
  632}
  633
  634#[derive(Clone, PartialEq, Eq, Hash)]
  635struct HoveredCursor {
  636    replica_id: u16,
  637    selection_id: usize,
  638}
  639
  640impl Default for SelectionHistoryMode {
  641    fn default() -> Self {
  642        Self::Normal
  643    }
  644}
  645
  646#[derive(Default)]
  647struct SelectionHistory {
  648    #[allow(clippy::type_complexity)]
  649    selections_by_transaction:
  650        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  651    mode: SelectionHistoryMode,
  652    undo_stack: VecDeque<SelectionHistoryEntry>,
  653    redo_stack: VecDeque<SelectionHistoryEntry>,
  654}
  655
  656impl SelectionHistory {
  657    fn insert_transaction(
  658        &mut self,
  659        transaction_id: TransactionId,
  660        selections: Arc<[Selection<Anchor>]>,
  661    ) {
  662        self.selections_by_transaction
  663            .insert(transaction_id, (selections, None));
  664    }
  665
  666    #[allow(clippy::type_complexity)]
  667    fn transaction(
  668        &self,
  669        transaction_id: TransactionId,
  670    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  671        self.selections_by_transaction.get(&transaction_id)
  672    }
  673
  674    #[allow(clippy::type_complexity)]
  675    fn transaction_mut(
  676        &mut self,
  677        transaction_id: TransactionId,
  678    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  679        self.selections_by_transaction.get_mut(&transaction_id)
  680    }
  681
  682    fn push(&mut self, entry: SelectionHistoryEntry) {
  683        if !entry.selections.is_empty() {
  684            match self.mode {
  685                SelectionHistoryMode::Normal => {
  686                    self.push_undo(entry);
  687                    self.redo_stack.clear();
  688                }
  689                SelectionHistoryMode::Undoing => self.push_redo(entry),
  690                SelectionHistoryMode::Redoing => self.push_undo(entry),
  691            }
  692        }
  693    }
  694
  695    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  696        if self
  697            .undo_stack
  698            .back()
  699            .map_or(true, |e| e.selections != entry.selections)
  700        {
  701            self.undo_stack.push_back(entry);
  702            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  703                self.undo_stack.pop_front();
  704            }
  705        }
  706    }
  707
  708    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  709        if self
  710            .redo_stack
  711            .back()
  712            .map_or(true, |e| e.selections != entry.selections)
  713        {
  714            self.redo_stack.push_back(entry);
  715            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  716                self.redo_stack.pop_front();
  717            }
  718        }
  719    }
  720}
  721
  722struct RowHighlight {
  723    index: usize,
  724    range: RangeInclusive<Anchor>,
  725    color: Option<Hsla>,
  726    should_autoscroll: bool,
  727}
  728
  729#[derive(Clone, Debug)]
  730struct AddSelectionsState {
  731    above: bool,
  732    stack: Vec<usize>,
  733}
  734
  735#[derive(Clone)]
  736struct SelectNextState {
  737    query: AhoCorasick,
  738    wordwise: bool,
  739    done: bool,
  740}
  741
  742impl std::fmt::Debug for SelectNextState {
  743    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  744        f.debug_struct(std::any::type_name::<Self>())
  745            .field("wordwise", &self.wordwise)
  746            .field("done", &self.done)
  747            .finish()
  748    }
  749}
  750
  751#[derive(Debug)]
  752struct AutocloseRegion {
  753    selection_id: usize,
  754    range: Range<Anchor>,
  755    pair: BracketPair,
  756}
  757
  758#[derive(Debug)]
  759struct SnippetState {
  760    ranges: Vec<Vec<Range<Anchor>>>,
  761    active_index: usize,
  762}
  763
  764#[doc(hidden)]
  765pub struct RenameState {
  766    pub range: Range<Anchor>,
  767    pub old_name: Arc<str>,
  768    pub editor: View<Editor>,
  769    block_id: CustomBlockId,
  770}
  771
  772struct InvalidationStack<T>(Vec<T>);
  773
  774struct RegisteredInlineCompletionProvider {
  775    provider: Arc<dyn InlineCompletionProviderHandle>,
  776    _subscription: Subscription,
  777}
  778
  779enum ContextMenu {
  780    Completions(CompletionsMenu),
  781    CodeActions(CodeActionsMenu),
  782}
  783
  784impl ContextMenu {
  785    fn select_first(
  786        &mut self,
  787        project: Option<&Model<Project>>,
  788        cx: &mut ViewContext<Editor>,
  789    ) -> bool {
  790        if self.visible() {
  791            match self {
  792                ContextMenu::Completions(menu) => menu.select_first(project, cx),
  793                ContextMenu::CodeActions(menu) => menu.select_first(cx),
  794            }
  795            true
  796        } else {
  797            false
  798        }
  799    }
  800
  801    fn select_prev(
  802        &mut self,
  803        project: Option<&Model<Project>>,
  804        cx: &mut ViewContext<Editor>,
  805    ) -> bool {
  806        if self.visible() {
  807            match self {
  808                ContextMenu::Completions(menu) => menu.select_prev(project, cx),
  809                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
  810            }
  811            true
  812        } else {
  813            false
  814        }
  815    }
  816
  817    fn select_next(
  818        &mut self,
  819        project: Option<&Model<Project>>,
  820        cx: &mut ViewContext<Editor>,
  821    ) -> bool {
  822        if self.visible() {
  823            match self {
  824                ContextMenu::Completions(menu) => menu.select_next(project, cx),
  825                ContextMenu::CodeActions(menu) => menu.select_next(cx),
  826            }
  827            true
  828        } else {
  829            false
  830        }
  831    }
  832
  833    fn select_last(
  834        &mut self,
  835        project: Option<&Model<Project>>,
  836        cx: &mut ViewContext<Editor>,
  837    ) -> bool {
  838        if self.visible() {
  839            match self {
  840                ContextMenu::Completions(menu) => menu.select_last(project, cx),
  841                ContextMenu::CodeActions(menu) => menu.select_last(cx),
  842            }
  843            true
  844        } else {
  845            false
  846        }
  847    }
  848
  849    fn visible(&self) -> bool {
  850        match self {
  851            ContextMenu::Completions(menu) => menu.visible(),
  852            ContextMenu::CodeActions(menu) => menu.visible(),
  853        }
  854    }
  855
  856    fn render(
  857        &self,
  858        cursor_position: DisplayPoint,
  859        style: &EditorStyle,
  860        max_height: Pixels,
  861        workspace: Option<WeakView<Workspace>>,
  862        cx: &mut ViewContext<Editor>,
  863    ) -> (ContextMenuOrigin, AnyElement) {
  864        match self {
  865            ContextMenu::Completions(menu) => (
  866                ContextMenuOrigin::EditorPoint(cursor_position),
  867                menu.render(style, max_height, workspace, cx),
  868            ),
  869            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
  870        }
  871    }
  872}
  873
  874enum ContextMenuOrigin {
  875    EditorPoint(DisplayPoint),
  876    GutterIndicator(DisplayRow),
  877}
  878
  879#[derive(Clone)]
  880struct CompletionsMenu {
  881    id: CompletionId,
  882    initial_position: Anchor,
  883    buffer: Model<Buffer>,
  884    completions: Arc<RwLock<Box<[Completion]>>>,
  885    match_candidates: Arc<[StringMatchCandidate]>,
  886    matches: Arc<[StringMatch]>,
  887    selected_item: usize,
  888    scroll_handle: UniformListScrollHandle,
  889    selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
  890}
  891
  892impl CompletionsMenu {
  893    fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  894        self.selected_item = 0;
  895        self.scroll_handle.scroll_to_item(self.selected_item);
  896        self.attempt_resolve_selected_completion_documentation(project, cx);
  897        cx.notify();
  898    }
  899
  900    fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  901        if self.selected_item > 0 {
  902            self.selected_item -= 1;
  903        } else {
  904            self.selected_item = self.matches.len() - 1;
  905        }
  906        self.scroll_handle.scroll_to_item(self.selected_item);
  907        self.attempt_resolve_selected_completion_documentation(project, cx);
  908        cx.notify();
  909    }
  910
  911    fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  912        if self.selected_item + 1 < self.matches.len() {
  913            self.selected_item += 1;
  914        } else {
  915            self.selected_item = 0;
  916        }
  917        self.scroll_handle.scroll_to_item(self.selected_item);
  918        self.attempt_resolve_selected_completion_documentation(project, cx);
  919        cx.notify();
  920    }
  921
  922    fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
  923        self.selected_item = self.matches.len() - 1;
  924        self.scroll_handle.scroll_to_item(self.selected_item);
  925        self.attempt_resolve_selected_completion_documentation(project, cx);
  926        cx.notify();
  927    }
  928
  929    fn pre_resolve_completion_documentation(
  930        buffer: Model<Buffer>,
  931        completions: Arc<RwLock<Box<[Completion]>>>,
  932        matches: Arc<[StringMatch]>,
  933        editor: &Editor,
  934        cx: &mut ViewContext<Editor>,
  935    ) -> Task<()> {
  936        let settings = EditorSettings::get_global(cx);
  937        if !settings.show_completion_documentation {
  938            return Task::ready(());
  939        }
  940
  941        let Some(provider) = editor.completion_provider.as_ref() else {
  942            return Task::ready(());
  943        };
  944
  945        let resolve_task = provider.resolve_completions(
  946            buffer,
  947            matches.iter().map(|m| m.candidate_id).collect(),
  948            completions.clone(),
  949            cx,
  950        );
  951
  952        return cx.spawn(move |this, mut cx| async move {
  953            if let Some(true) = resolve_task.await.log_err() {
  954                this.update(&mut cx, |_, cx| cx.notify()).ok();
  955            }
  956        });
  957    }
  958
  959    fn attempt_resolve_selected_completion_documentation(
  960        &mut self,
  961        project: Option<&Model<Project>>,
  962        cx: &mut ViewContext<Editor>,
  963    ) {
  964        let settings = EditorSettings::get_global(cx);
  965        if !settings.show_completion_documentation {
  966            return;
  967        }
  968
  969        let completion_index = self.matches[self.selected_item].candidate_id;
  970        let Some(project) = project else {
  971            return;
  972        };
  973
  974        let resolve_task = project.update(cx, |project, cx| {
  975            project.resolve_completions(
  976                self.buffer.clone(),
  977                vec![completion_index],
  978                self.completions.clone(),
  979                cx,
  980            )
  981        });
  982
  983        let delay_ms =
  984            EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
  985        let delay = Duration::from_millis(delay_ms);
  986
  987        self.selected_completion_documentation_resolve_debounce
  988            .lock()
  989            .fire_new(delay, cx, |_, cx| {
  990                cx.spawn(move |this, mut cx| async move {
  991                    if let Some(true) = resolve_task.await.log_err() {
  992                        this.update(&mut cx, |_, cx| cx.notify()).ok();
  993                    }
  994                })
  995            });
  996    }
  997
  998    fn visible(&self) -> bool {
  999        !self.matches.is_empty()
 1000    }
 1001
 1002    fn render(
 1003        &self,
 1004        style: &EditorStyle,
 1005        max_height: Pixels,
 1006        workspace: Option<WeakView<Workspace>>,
 1007        cx: &mut ViewContext<Editor>,
 1008    ) -> AnyElement {
 1009        let settings = EditorSettings::get_global(cx);
 1010        let show_completion_documentation = settings.show_completion_documentation;
 1011
 1012        let widest_completion_ix = self
 1013            .matches
 1014            .iter()
 1015            .enumerate()
 1016            .max_by_key(|(_, mat)| {
 1017                let completions = self.completions.read();
 1018                let completion = &completions[mat.candidate_id];
 1019                let documentation = &completion.documentation;
 1020
 1021                let mut len = completion.label.text.chars().count();
 1022                if let Some(Documentation::SingleLine(text)) = documentation {
 1023                    if show_completion_documentation {
 1024                        len += text.chars().count();
 1025                    }
 1026                }
 1027
 1028                len
 1029            })
 1030            .map(|(ix, _)| ix);
 1031
 1032        let completions = self.completions.clone();
 1033        let matches = self.matches.clone();
 1034        let selected_item = self.selected_item;
 1035        let style = style.clone();
 1036
 1037        let multiline_docs = if show_completion_documentation {
 1038            let mat = &self.matches[selected_item];
 1039            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
 1040                Some(Documentation::MultiLinePlainText(text)) => {
 1041                    Some(div().child(SharedString::from(text.clone())))
 1042                }
 1043                Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
 1044                    Some(div().child(render_parsed_markdown(
 1045                        "completions_markdown",
 1046                        parsed,
 1047                        &style,
 1048                        workspace,
 1049                        cx,
 1050                    )))
 1051                }
 1052                _ => None,
 1053            };
 1054            multiline_docs.map(|div| {
 1055                div.id("multiline_docs")
 1056                    .max_h(max_height)
 1057                    .flex_1()
 1058                    .px_1p5()
 1059                    .py_1()
 1060                    .min_w(px(260.))
 1061                    .max_w(px(640.))
 1062                    .w(px(500.))
 1063                    .overflow_y_scroll()
 1064                    .occlude()
 1065            })
 1066        } else {
 1067            None
 1068        };
 1069
 1070        let list = uniform_list(
 1071            cx.view().clone(),
 1072            "completions",
 1073            matches.len(),
 1074            move |_editor, range, cx| {
 1075                let start_ix = range.start;
 1076                let completions_guard = completions.read();
 1077
 1078                matches[range]
 1079                    .iter()
 1080                    .enumerate()
 1081                    .map(|(ix, mat)| {
 1082                        let item_ix = start_ix + ix;
 1083                        let candidate_id = mat.candidate_id;
 1084                        let completion = &completions_guard[candidate_id];
 1085
 1086                        let documentation = if show_completion_documentation {
 1087                            &completion.documentation
 1088                        } else {
 1089                            &None
 1090                        };
 1091
 1092                        let highlights = gpui::combine_highlights(
 1093                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
 1094                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
 1095                                |(range, mut highlight)| {
 1096                                    // Ignore font weight for syntax highlighting, as we'll use it
 1097                                    // for fuzzy matches.
 1098                                    highlight.font_weight = None;
 1099
 1100                                    if completion.lsp_completion.deprecated.unwrap_or(false) {
 1101                                        highlight.strikethrough = Some(StrikethroughStyle {
 1102                                            thickness: 1.0.into(),
 1103                                            ..Default::default()
 1104                                        });
 1105                                        highlight.color = Some(cx.theme().colors().text_muted);
 1106                                    }
 1107
 1108                                    (range, highlight)
 1109                                },
 1110                            ),
 1111                        );
 1112                        let completion_label = StyledText::new(completion.label.text.clone())
 1113                            .with_highlights(&style.text, highlights);
 1114                        let documentation_label =
 1115                            if let Some(Documentation::SingleLine(text)) = documentation {
 1116                                if text.trim().is_empty() {
 1117                                    None
 1118                                } else {
 1119                                    Some(
 1120                                        Label::new(text.clone())
 1121                                            .ml_4()
 1122                                            .size(LabelSize::Small)
 1123                                            .color(Color::Muted),
 1124                                    )
 1125                                }
 1126                            } else {
 1127                                None
 1128                            };
 1129
 1130                        div().min_w(px(220.)).max_w(px(540.)).child(
 1131                            ListItem::new(mat.candidate_id)
 1132                                .inset(true)
 1133                                .selected(item_ix == selected_item)
 1134                                .on_click(cx.listener(move |editor, _event, cx| {
 1135                                    cx.stop_propagation();
 1136                                    if let Some(task) = editor.confirm_completion(
 1137                                        &ConfirmCompletion {
 1138                                            item_ix: Some(item_ix),
 1139                                        },
 1140                                        cx,
 1141                                    ) {
 1142                                        task.detach_and_log_err(cx)
 1143                                    }
 1144                                }))
 1145                                .child(h_flex().overflow_hidden().child(completion_label))
 1146                                .end_slot::<Label>(documentation_label),
 1147                        )
 1148                    })
 1149                    .collect()
 1150            },
 1151        )
 1152        .occlude()
 1153        .max_h(max_height)
 1154        .track_scroll(self.scroll_handle.clone())
 1155        .with_width_from_item(widest_completion_ix)
 1156        .with_sizing_behavior(ListSizingBehavior::Infer);
 1157
 1158        Popover::new()
 1159            .child(list)
 1160            .when_some(multiline_docs, |popover, multiline_docs| {
 1161                popover.aside(multiline_docs)
 1162            })
 1163            .into_any_element()
 1164    }
 1165
 1166    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
 1167        let mut matches = if let Some(query) = query {
 1168            fuzzy::match_strings(
 1169                &self.match_candidates,
 1170                query,
 1171                query.chars().any(|c| c.is_uppercase()),
 1172                100,
 1173                &Default::default(),
 1174                executor,
 1175            )
 1176            .await
 1177        } else {
 1178            self.match_candidates
 1179                .iter()
 1180                .enumerate()
 1181                .map(|(candidate_id, candidate)| StringMatch {
 1182                    candidate_id,
 1183                    score: Default::default(),
 1184                    positions: Default::default(),
 1185                    string: candidate.string.clone(),
 1186                })
 1187                .collect()
 1188        };
 1189
 1190        // Remove all candidates where the query's start does not match the start of any word in the candidate
 1191        if let Some(query) = query {
 1192            if let Some(query_start) = query.chars().next() {
 1193                matches.retain(|string_match| {
 1194                    split_words(&string_match.string).any(|word| {
 1195                        // Check that the first codepoint of the word as lowercase matches the first
 1196                        // codepoint of the query as lowercase
 1197                        word.chars()
 1198                            .flat_map(|codepoint| codepoint.to_lowercase())
 1199                            .zip(query_start.to_lowercase())
 1200                            .all(|(word_cp, query_cp)| word_cp == query_cp)
 1201                    })
 1202                });
 1203            }
 1204        }
 1205
 1206        let completions = self.completions.read();
 1207        matches.sort_unstable_by_key(|mat| {
 1208            // We do want to strike a balance here between what the language server tells us
 1209            // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
 1210            // `Creat` and there is a local variable called `CreateComponent`).
 1211            // So what we do is: we bucket all matches into two buckets
 1212            // - Strong matches
 1213            // - Weak matches
 1214            // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
 1215            // and the Weak matches are the rest.
 1216            //
 1217            // For the strong matches, we sort by the language-servers score first and for the weak
 1218            // matches, we prefer our fuzzy finder first.
 1219            //
 1220            // The thinking behind that: it's useless to take the sort_text the language-server gives
 1221            // us into account when it's obviously a bad match.
 1222
 1223            #[derive(PartialEq, Eq, PartialOrd, Ord)]
 1224            enum MatchScore<'a> {
 1225                Strong {
 1226                    sort_text: Option<&'a str>,
 1227                    score: Reverse<OrderedFloat<f64>>,
 1228                    sort_key: (usize, &'a str),
 1229                },
 1230                Weak {
 1231                    score: Reverse<OrderedFloat<f64>>,
 1232                    sort_text: Option<&'a str>,
 1233                    sort_key: (usize, &'a str),
 1234                },
 1235            }
 1236
 1237            let completion = &completions[mat.candidate_id];
 1238            let sort_key = completion.sort_key();
 1239            let sort_text = completion.lsp_completion.sort_text.as_deref();
 1240            let score = Reverse(OrderedFloat(mat.score));
 1241
 1242            if mat.score >= 0.2 {
 1243                MatchScore::Strong {
 1244                    sort_text,
 1245                    score,
 1246                    sort_key,
 1247                }
 1248            } else {
 1249                MatchScore::Weak {
 1250                    score,
 1251                    sort_text,
 1252                    sort_key,
 1253                }
 1254            }
 1255        });
 1256
 1257        for mat in &mut matches {
 1258            let completion = &completions[mat.candidate_id];
 1259            mat.string.clone_from(&completion.label.text);
 1260            for position in &mut mat.positions {
 1261                *position += completion.label.filter_range.start;
 1262            }
 1263        }
 1264        drop(completions);
 1265
 1266        self.matches = matches.into();
 1267        self.selected_item = 0;
 1268    }
 1269}
 1270
 1271#[derive(Clone)]
 1272struct CodeActionContents {
 1273    tasks: Option<Arc<ResolvedTasks>>,
 1274    actions: Option<Arc<[CodeAction]>>,
 1275}
 1276
 1277impl CodeActionContents {
 1278    fn len(&self) -> usize {
 1279        match (&self.tasks, &self.actions) {
 1280            (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
 1281            (Some(tasks), None) => tasks.templates.len(),
 1282            (None, Some(actions)) => actions.len(),
 1283            (None, None) => 0,
 1284        }
 1285    }
 1286
 1287    fn is_empty(&self) -> bool {
 1288        match (&self.tasks, &self.actions) {
 1289            (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
 1290            (Some(tasks), None) => tasks.templates.is_empty(),
 1291            (None, Some(actions)) => actions.is_empty(),
 1292            (None, None) => true,
 1293        }
 1294    }
 1295
 1296    fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
 1297        self.tasks
 1298            .iter()
 1299            .flat_map(|tasks| {
 1300                tasks
 1301                    .templates
 1302                    .iter()
 1303                    .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
 1304            })
 1305            .chain(self.actions.iter().flat_map(|actions| {
 1306                actions
 1307                    .iter()
 1308                    .map(|action| CodeActionsItem::CodeAction(action.clone()))
 1309            }))
 1310    }
 1311    fn get(&self, index: usize) -> Option<CodeActionsItem> {
 1312        match (&self.tasks, &self.actions) {
 1313            (Some(tasks), Some(actions)) => {
 1314                if index < tasks.templates.len() {
 1315                    tasks
 1316                        .templates
 1317                        .get(index)
 1318                        .cloned()
 1319                        .map(|(kind, task)| CodeActionsItem::Task(kind, task))
 1320                } else {
 1321                    actions
 1322                        .get(index - tasks.templates.len())
 1323                        .cloned()
 1324                        .map(CodeActionsItem::CodeAction)
 1325                }
 1326            }
 1327            (Some(tasks), None) => tasks
 1328                .templates
 1329                .get(index)
 1330                .cloned()
 1331                .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
 1332            (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
 1333            (None, None) => None,
 1334        }
 1335    }
 1336}
 1337
 1338#[allow(clippy::large_enum_variant)]
 1339#[derive(Clone)]
 1340enum CodeActionsItem {
 1341    Task(TaskSourceKind, ResolvedTask),
 1342    CodeAction(CodeAction),
 1343}
 1344
 1345impl CodeActionsItem {
 1346    fn as_task(&self) -> Option<&ResolvedTask> {
 1347        let Self::Task(_, task) = self else {
 1348            return None;
 1349        };
 1350        Some(task)
 1351    }
 1352    fn as_code_action(&self) -> Option<&CodeAction> {
 1353        let Self::CodeAction(action) = self else {
 1354            return None;
 1355        };
 1356        Some(action)
 1357    }
 1358    fn label(&self) -> String {
 1359        match self {
 1360            Self::CodeAction(action) => action.lsp_action.title.clone(),
 1361            Self::Task(_, task) => task.resolved_label.clone(),
 1362        }
 1363    }
 1364}
 1365
 1366struct CodeActionsMenu {
 1367    actions: CodeActionContents,
 1368    buffer: Model<Buffer>,
 1369    selected_item: usize,
 1370    scroll_handle: UniformListScrollHandle,
 1371    deployed_from_indicator: Option<DisplayRow>,
 1372}
 1373
 1374impl CodeActionsMenu {
 1375    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
 1376        self.selected_item = 0;
 1377        self.scroll_handle.scroll_to_item(self.selected_item);
 1378        cx.notify()
 1379    }
 1380
 1381    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
 1382        if self.selected_item > 0 {
 1383            self.selected_item -= 1;
 1384        } else {
 1385            self.selected_item = self.actions.len() - 1;
 1386        }
 1387        self.scroll_handle.scroll_to_item(self.selected_item);
 1388        cx.notify();
 1389    }
 1390
 1391    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
 1392        if self.selected_item + 1 < self.actions.len() {
 1393            self.selected_item += 1;
 1394        } else {
 1395            self.selected_item = 0;
 1396        }
 1397        self.scroll_handle.scroll_to_item(self.selected_item);
 1398        cx.notify();
 1399    }
 1400
 1401    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
 1402        self.selected_item = self.actions.len() - 1;
 1403        self.scroll_handle.scroll_to_item(self.selected_item);
 1404        cx.notify()
 1405    }
 1406
 1407    fn visible(&self) -> bool {
 1408        !self.actions.is_empty()
 1409    }
 1410
 1411    fn render(
 1412        &self,
 1413        cursor_position: DisplayPoint,
 1414        _style: &EditorStyle,
 1415        max_height: Pixels,
 1416        cx: &mut ViewContext<Editor>,
 1417    ) -> (ContextMenuOrigin, AnyElement) {
 1418        let actions = self.actions.clone();
 1419        let selected_item = self.selected_item;
 1420        let element = uniform_list(
 1421            cx.view().clone(),
 1422            "code_actions_menu",
 1423            self.actions.len(),
 1424            move |_this, range, cx| {
 1425                actions
 1426                    .iter()
 1427                    .skip(range.start)
 1428                    .take(range.end - range.start)
 1429                    .enumerate()
 1430                    .map(|(ix, action)| {
 1431                        let item_ix = range.start + ix;
 1432                        let selected = selected_item == item_ix;
 1433                        let colors = cx.theme().colors();
 1434                        div()
 1435                            .px_2()
 1436                            .text_color(colors.text)
 1437                            .when(selected, |style| {
 1438                                style
 1439                                    .bg(colors.element_active)
 1440                                    .text_color(colors.text_accent)
 1441                            })
 1442                            .hover(|style| {
 1443                                style
 1444                                    .bg(colors.element_hover)
 1445                                    .text_color(colors.text_accent)
 1446                            })
 1447                            .whitespace_nowrap()
 1448                            .when_some(action.as_code_action(), |this, action| {
 1449                                this.on_mouse_down(
 1450                                    MouseButton::Left,
 1451                                    cx.listener(move |editor, _, cx| {
 1452                                        cx.stop_propagation();
 1453                                        if let Some(task) = editor.confirm_code_action(
 1454                                            &ConfirmCodeAction {
 1455                                                item_ix: Some(item_ix),
 1456                                            },
 1457                                            cx,
 1458                                        ) {
 1459                                            task.detach_and_log_err(cx)
 1460                                        }
 1461                                    }),
 1462                                )
 1463                                // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
 1464                                .child(SharedString::from(action.lsp_action.title.clone()))
 1465                            })
 1466                            .when_some(action.as_task(), |this, task| {
 1467                                this.on_mouse_down(
 1468                                    MouseButton::Left,
 1469                                    cx.listener(move |editor, _, cx| {
 1470                                        cx.stop_propagation();
 1471                                        if let Some(task) = editor.confirm_code_action(
 1472                                            &ConfirmCodeAction {
 1473                                                item_ix: Some(item_ix),
 1474                                            },
 1475                                            cx,
 1476                                        ) {
 1477                                            task.detach_and_log_err(cx)
 1478                                        }
 1479                                    }),
 1480                                )
 1481                                .child(SharedString::from(task.resolved_label.clone()))
 1482                            })
 1483                    })
 1484                    .collect()
 1485            },
 1486        )
 1487        .elevation_1(cx)
 1488        .px_2()
 1489        .py_1()
 1490        .max_h(max_height)
 1491        .occlude()
 1492        .track_scroll(self.scroll_handle.clone())
 1493        .with_width_from_item(
 1494            self.actions
 1495                .iter()
 1496                .enumerate()
 1497                .max_by_key(|(_, action)| match action {
 1498                    CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
 1499                    CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
 1500                })
 1501                .map(|(ix, _)| ix),
 1502        )
 1503        .with_sizing_behavior(ListSizingBehavior::Infer)
 1504        .into_any_element();
 1505
 1506        let cursor_position = if let Some(row) = self.deployed_from_indicator {
 1507            ContextMenuOrigin::GutterIndicator(row)
 1508        } else {
 1509            ContextMenuOrigin::EditorPoint(cursor_position)
 1510        };
 1511
 1512        (cursor_position, element)
 1513    }
 1514}
 1515
 1516#[derive(Debug)]
 1517struct ActiveDiagnosticGroup {
 1518    primary_range: Range<Anchor>,
 1519    primary_message: String,
 1520    group_id: usize,
 1521    blocks: HashMap<CustomBlockId, Diagnostic>,
 1522    is_valid: bool,
 1523}
 1524
 1525#[derive(Serialize, Deserialize, Clone, Debug)]
 1526pub struct ClipboardSelection {
 1527    pub len: usize,
 1528    pub is_entire_line: bool,
 1529    pub first_line_indent: u32,
 1530}
 1531
 1532#[derive(Debug)]
 1533pub(crate) struct NavigationData {
 1534    cursor_anchor: Anchor,
 1535    cursor_position: Point,
 1536    scroll_anchor: ScrollAnchor,
 1537    scroll_top_row: u32,
 1538}
 1539
 1540enum GotoDefinitionKind {
 1541    Symbol,
 1542    Type,
 1543    Implementation,
 1544}
 1545
 1546#[derive(Debug, Clone)]
 1547enum InlayHintRefreshReason {
 1548    Toggle(bool),
 1549    SettingsChange(InlayHintSettings),
 1550    NewLinesShown,
 1551    BufferEdited(HashSet<Arc<Language>>),
 1552    RefreshRequested,
 1553    ExcerptsRemoved(Vec<ExcerptId>),
 1554}
 1555
 1556impl InlayHintRefreshReason {
 1557    fn description(&self) -> &'static str {
 1558        match self {
 1559            Self::Toggle(_) => "toggle",
 1560            Self::SettingsChange(_) => "settings change",
 1561            Self::NewLinesShown => "new lines shown",
 1562            Self::BufferEdited(_) => "buffer edited",
 1563            Self::RefreshRequested => "refresh requested",
 1564            Self::ExcerptsRemoved(_) => "excerpts removed",
 1565        }
 1566    }
 1567}
 1568
 1569pub(crate) struct FocusedBlock {
 1570    id: BlockId,
 1571    focus_handle: WeakFocusHandle,
 1572}
 1573
 1574impl Editor {
 1575    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1576        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1577        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1578        Self::new(
 1579            EditorMode::SingleLine { auto_width: false },
 1580            buffer,
 1581            None,
 1582            false,
 1583            cx,
 1584        )
 1585    }
 1586
 1587    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1588        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1589        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1590        Self::new(EditorMode::Full, buffer, None, false, cx)
 1591    }
 1592
 1593    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1594        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1595        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1596        Self::new(
 1597            EditorMode::SingleLine { auto_width: true },
 1598            buffer,
 1599            None,
 1600            false,
 1601            cx,
 1602        )
 1603    }
 1604
 1605    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1606        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1607        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1608        Self::new(
 1609            EditorMode::AutoHeight { max_lines },
 1610            buffer,
 1611            None,
 1612            false,
 1613            cx,
 1614        )
 1615    }
 1616
 1617    pub fn for_buffer(
 1618        buffer: Model<Buffer>,
 1619        project: Option<Model<Project>>,
 1620        cx: &mut ViewContext<Self>,
 1621    ) -> Self {
 1622        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1623        Self::new(EditorMode::Full, buffer, project, false, cx)
 1624    }
 1625
 1626    pub fn for_multibuffer(
 1627        buffer: Model<MultiBuffer>,
 1628        project: Option<Model<Project>>,
 1629        show_excerpt_controls: bool,
 1630        cx: &mut ViewContext<Self>,
 1631    ) -> Self {
 1632        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1633    }
 1634
 1635    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1636        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1637        let mut clone = Self::new(
 1638            self.mode,
 1639            self.buffer.clone(),
 1640            self.project.clone(),
 1641            show_excerpt_controls,
 1642            cx,
 1643        );
 1644        self.display_map.update(cx, |display_map, cx| {
 1645            let snapshot = display_map.snapshot(cx);
 1646            clone.display_map.update(cx, |display_map, cx| {
 1647                display_map.set_state(&snapshot, cx);
 1648            });
 1649        });
 1650        clone.selections.clone_state(&self.selections);
 1651        clone.scroll_manager.clone_state(&self.scroll_manager);
 1652        clone.searchable = self.searchable;
 1653        clone
 1654    }
 1655
 1656    pub fn new(
 1657        mode: EditorMode,
 1658        buffer: Model<MultiBuffer>,
 1659        project: Option<Model<Project>>,
 1660        show_excerpt_controls: bool,
 1661        cx: &mut ViewContext<Self>,
 1662    ) -> Self {
 1663        let style = cx.text_style();
 1664        let font_size = style.font_size.to_pixels(cx.rem_size());
 1665        let editor = cx.view().downgrade();
 1666        let fold_placeholder = FoldPlaceholder {
 1667            constrain_width: true,
 1668            render: Arc::new(move |fold_id, fold_range, cx| {
 1669                let editor = editor.clone();
 1670                div()
 1671                    .id(fold_id)
 1672                    .bg(cx.theme().colors().ghost_element_background)
 1673                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1674                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1675                    .rounded_sm()
 1676                    .size_full()
 1677                    .cursor_pointer()
 1678                    .child("")
 1679                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1680                    .on_click(move |_, cx| {
 1681                        editor
 1682                            .update(cx, |editor, cx| {
 1683                                editor.unfold_ranges(
 1684                                    [fold_range.start..fold_range.end],
 1685                                    true,
 1686                                    false,
 1687                                    cx,
 1688                                );
 1689                                cx.stop_propagation();
 1690                            })
 1691                            .ok();
 1692                    })
 1693                    .into_any()
 1694            }),
 1695            merge_adjacent: true,
 1696        };
 1697        let file_header_size = if show_excerpt_controls { 3 } else { 2 };
 1698        let display_map = cx.new_model(|cx| {
 1699            DisplayMap::new(
 1700                buffer.clone(),
 1701                style.font(),
 1702                font_size,
 1703                None,
 1704                show_excerpt_controls,
 1705                file_header_size,
 1706                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1707                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1708                fold_placeholder,
 1709                cx,
 1710            )
 1711        });
 1712
 1713        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1714
 1715        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1716
 1717        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1718            .then(|| language_settings::SoftWrap::PreferLine);
 1719
 1720        let mut project_subscriptions = Vec::new();
 1721        if mode == EditorMode::Full {
 1722            if let Some(project) = project.as_ref() {
 1723                if buffer.read(cx).is_singleton() {
 1724                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1725                        cx.emit(EditorEvent::TitleChanged);
 1726                    }));
 1727                }
 1728                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1729                    if let project::Event::RefreshInlayHints = event {
 1730                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1731                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1732                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1733                            let focus_handle = editor.focus_handle(cx);
 1734                            if focus_handle.is_focused(cx) {
 1735                                let snapshot = buffer.read(cx).snapshot();
 1736                                for (range, snippet) in snippet_edits {
 1737                                    let editor_range =
 1738                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1739                                    editor
 1740                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1741                                        .ok();
 1742                                }
 1743                            }
 1744                        }
 1745                    }
 1746                }));
 1747                let task_inventory = project.read(cx).task_inventory().clone();
 1748                project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1749                    editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1750                }));
 1751            }
 1752        }
 1753
 1754        let inlay_hint_settings = inlay_hint_settings(
 1755            selections.newest_anchor().head(),
 1756            &buffer.read(cx).snapshot(cx),
 1757            cx,
 1758        );
 1759        let focus_handle = cx.focus_handle();
 1760        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1761        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1762            .detach();
 1763        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1764            .detach();
 1765        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1766
 1767        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1768            Some(false)
 1769        } else {
 1770            None
 1771        };
 1772
 1773        let mut this = Self {
 1774            focus_handle,
 1775            show_cursor_when_unfocused: false,
 1776            last_focused_descendant: None,
 1777            buffer: buffer.clone(),
 1778            display_map: display_map.clone(),
 1779            selections,
 1780            scroll_manager: ScrollManager::new(cx),
 1781            columnar_selection_tail: None,
 1782            add_selections_state: None,
 1783            select_next_state: None,
 1784            select_prev_state: None,
 1785            selection_history: Default::default(),
 1786            autoclose_regions: Default::default(),
 1787            snippet_stack: Default::default(),
 1788            select_larger_syntax_node_stack: Vec::new(),
 1789            ime_transaction: Default::default(),
 1790            active_diagnostics: None,
 1791            soft_wrap_mode_override,
 1792            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1793            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1794            project,
 1795            blink_manager: blink_manager.clone(),
 1796            show_local_selections: true,
 1797            mode,
 1798            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1799            show_gutter: mode == EditorMode::Full,
 1800            show_line_numbers: None,
 1801            show_git_diff_gutter: None,
 1802            show_code_actions: None,
 1803            show_runnables: None,
 1804            show_wrap_guides: None,
 1805            show_indent_guides,
 1806            placeholder_text: None,
 1807            highlight_order: 0,
 1808            highlighted_rows: HashMap::default(),
 1809            background_highlights: Default::default(),
 1810            gutter_highlights: TreeMap::default(),
 1811            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1812            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1813            nav_history: None,
 1814            context_menu: RwLock::new(None),
 1815            mouse_context_menu: None,
 1816            completion_tasks: Default::default(),
 1817            signature_help_state: SignatureHelpState::default(),
 1818            auto_signature_help: None,
 1819            find_all_references_task_sources: Vec::new(),
 1820            next_completion_id: 0,
 1821            completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
 1822            next_inlay_id: 0,
 1823            available_code_actions: Default::default(),
 1824            code_actions_task: Default::default(),
 1825            document_highlights_task: Default::default(),
 1826            linked_editing_range_task: Default::default(),
 1827            pending_rename: Default::default(),
 1828            searchable: true,
 1829            cursor_shape: Default::default(),
 1830            current_line_highlight: None,
 1831            autoindent_mode: Some(AutoindentMode::EachLine),
 1832            collapse_matches: false,
 1833            workspace: None,
 1834            keymap_context_layers: Default::default(),
 1835            input_enabled: true,
 1836            use_modal_editing: mode == EditorMode::Full,
 1837            read_only: false,
 1838            use_autoclose: true,
 1839            use_auto_surround: true,
 1840            auto_replace_emoji_shortcode: false,
 1841            leader_peer_id: None,
 1842            remote_id: None,
 1843            hover_state: Default::default(),
 1844            hovered_link_state: Default::default(),
 1845            inline_completion_provider: None,
 1846            active_inline_completion: None,
 1847            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1848            expanded_hunks: ExpandedHunks::default(),
 1849            gutter_hovered: false,
 1850            pixel_position_of_newest_cursor: None,
 1851            last_bounds: None,
 1852            expect_bounds_change: None,
 1853            gutter_dimensions: GutterDimensions::default(),
 1854            style: None,
 1855            show_cursor_names: false,
 1856            hovered_cursors: Default::default(),
 1857            next_editor_action_id: EditorActionId::default(),
 1858            editor_actions: Rc::default(),
 1859            vim_replace_map: Default::default(),
 1860            show_inline_completions: mode == EditorMode::Full,
 1861            custom_context_menu: None,
 1862            show_git_blame_gutter: false,
 1863            show_git_blame_inline: false,
 1864            show_selection_menu: None,
 1865            show_git_blame_inline_delay_task: None,
 1866            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1867            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1868                .session
 1869                .restore_unsaved_buffers,
 1870            blame: None,
 1871            blame_subscription: None,
 1872            file_header_size,
 1873            tasks: Default::default(),
 1874            _subscriptions: vec![
 1875                cx.observe(&buffer, Self::on_buffer_changed),
 1876                cx.subscribe(&buffer, Self::on_buffer_event),
 1877                cx.observe(&display_map, Self::on_display_map_changed),
 1878                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1879                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1880                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1881                cx.observe_window_activation(|editor, cx| {
 1882                    let active = cx.is_window_active();
 1883                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1884                        if active {
 1885                            blink_manager.enable(cx);
 1886                        } else {
 1887                            blink_manager.disable(cx);
 1888                        }
 1889                    });
 1890                }),
 1891            ],
 1892            tasks_update_task: None,
 1893            linked_edit_ranges: Default::default(),
 1894            previous_search_ranges: None,
 1895            breadcrumb_header: None,
 1896            focused_block: None,
 1897        };
 1898        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1899        this._subscriptions.extend(project_subscriptions);
 1900
 1901        this.end_selection(cx);
 1902        this.scroll_manager.show_scrollbar(cx);
 1903
 1904        if mode == EditorMode::Full {
 1905            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1906            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1907
 1908            if this.git_blame_inline_enabled {
 1909                this.git_blame_inline_enabled = true;
 1910                this.start_git_blame_inline(false, cx);
 1911            }
 1912        }
 1913
 1914        this.report_editor_event("open", None, cx);
 1915        this
 1916    }
 1917
 1918    pub fn mouse_menu_is_focused(&self, cx: &mut WindowContext) -> bool {
 1919        self.mouse_context_menu
 1920            .as_ref()
 1921            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1922    }
 1923
 1924    fn key_context(&self, cx: &AppContext) -> KeyContext {
 1925        let mut key_context = KeyContext::new_with_defaults();
 1926        key_context.add("Editor");
 1927        let mode = match self.mode {
 1928            EditorMode::SingleLine { .. } => "single_line",
 1929            EditorMode::AutoHeight { .. } => "auto_height",
 1930            EditorMode::Full => "full",
 1931        };
 1932
 1933        if EditorSettings::jupyter_enabled(cx) {
 1934            key_context.add("jupyter");
 1935        }
 1936
 1937        key_context.set("mode", mode);
 1938        if self.pending_rename.is_some() {
 1939            key_context.add("renaming");
 1940        }
 1941        if self.context_menu_visible() {
 1942            match self.context_menu.read().as_ref() {
 1943                Some(ContextMenu::Completions(_)) => {
 1944                    key_context.add("menu");
 1945                    key_context.add("showing_completions")
 1946                }
 1947                Some(ContextMenu::CodeActions(_)) => {
 1948                    key_context.add("menu");
 1949                    key_context.add("showing_code_actions")
 1950                }
 1951                None => {}
 1952            }
 1953        }
 1954
 1955        for layer in self.keymap_context_layers.values() {
 1956            key_context.extend(layer);
 1957        }
 1958
 1959        if let Some(extension) = self
 1960            .buffer
 1961            .read(cx)
 1962            .as_singleton()
 1963            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1964        {
 1965            key_context.set("extension", extension.to_string());
 1966        }
 1967
 1968        if self.has_active_inline_completion(cx) {
 1969            key_context.add("copilot_suggestion");
 1970            key_context.add("inline_completion");
 1971        }
 1972
 1973        key_context
 1974    }
 1975
 1976    pub fn new_file(
 1977        workspace: &mut Workspace,
 1978        _: &workspace::NewFile,
 1979        cx: &mut ViewContext<Workspace>,
 1980    ) {
 1981        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1982            "Failed to create buffer",
 1983            cx,
 1984            |e, _| match e.error_code() {
 1985                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1986                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1987                e.error_tag("required").unwrap_or("the latest version")
 1988            )),
 1989                _ => None,
 1990            },
 1991        );
 1992    }
 1993
 1994    pub fn new_in_workspace(
 1995        workspace: &mut Workspace,
 1996        cx: &mut ViewContext<Workspace>,
 1997    ) -> Task<Result<View<Editor>>> {
 1998        let project = workspace.project().clone();
 1999        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2000
 2001        cx.spawn(|workspace, mut cx| async move {
 2002            let buffer = create.await?;
 2003            workspace.update(&mut cx, |workspace, cx| {
 2004                let editor =
 2005                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 2006                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 2007                editor
 2008            })
 2009        })
 2010    }
 2011
 2012    pub fn new_file_in_direction(
 2013        workspace: &mut Workspace,
 2014        action: &workspace::NewFileInDirection,
 2015        cx: &mut ViewContext<Workspace>,
 2016    ) {
 2017        let project = workspace.project().clone();
 2018        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 2019        let direction = action.0;
 2020
 2021        cx.spawn(|workspace, mut cx| async move {
 2022            let buffer = create.await?;
 2023            workspace.update(&mut cx, move |workspace, cx| {
 2024                workspace.split_item(
 2025                    direction,
 2026                    Box::new(
 2027                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 2028                    ),
 2029                    cx,
 2030                )
 2031            })?;
 2032            anyhow::Ok(())
 2033        })
 2034        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 2035            ErrorCode::RemoteUpgradeRequired => Some(format!(
 2036                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 2037                e.error_tag("required").unwrap_or("the latest version")
 2038            )),
 2039            _ => None,
 2040        });
 2041    }
 2042
 2043    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
 2044        self.buffer.read(cx).replica_id()
 2045    }
 2046
 2047    pub fn leader_peer_id(&self) -> Option<PeerId> {
 2048        self.leader_peer_id
 2049    }
 2050
 2051    pub fn buffer(&self) -> &Model<MultiBuffer> {
 2052        &self.buffer
 2053    }
 2054
 2055    pub fn workspace(&self) -> Option<View<Workspace>> {
 2056        self.workspace.as_ref()?.0.upgrade()
 2057    }
 2058
 2059    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 2060        self.buffer().read(cx).title(cx)
 2061    }
 2062
 2063    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 2064        EditorSnapshot {
 2065            mode: self.mode,
 2066            show_gutter: self.show_gutter,
 2067            show_line_numbers: self.show_line_numbers,
 2068            show_git_diff_gutter: self.show_git_diff_gutter,
 2069            show_code_actions: self.show_code_actions,
 2070            show_runnables: self.show_runnables,
 2071            render_git_blame_gutter: self.render_git_blame_gutter(cx),
 2072            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 2073            scroll_anchor: self.scroll_manager.anchor(),
 2074            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 2075            placeholder_text: self.placeholder_text.clone(),
 2076            is_focused: self.focus_handle.is_focused(cx),
 2077            current_line_highlight: self
 2078                .current_line_highlight
 2079                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 2080            gutter_hovered: self.gutter_hovered,
 2081        }
 2082    }
 2083
 2084    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 2085        self.buffer.read(cx).language_at(point, cx)
 2086    }
 2087
 2088    pub fn file_at<T: ToOffset>(
 2089        &self,
 2090        point: T,
 2091        cx: &AppContext,
 2092    ) -> Option<Arc<dyn language::File>> {
 2093        self.buffer.read(cx).read(cx).file_at(point).cloned()
 2094    }
 2095
 2096    pub fn active_excerpt(
 2097        &self,
 2098        cx: &AppContext,
 2099    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 2100        self.buffer
 2101            .read(cx)
 2102            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 2103    }
 2104
 2105    pub fn mode(&self) -> EditorMode {
 2106        self.mode
 2107    }
 2108
 2109    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 2110        self.collaboration_hub.as_deref()
 2111    }
 2112
 2113    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 2114        self.collaboration_hub = Some(hub);
 2115    }
 2116
 2117    pub fn set_custom_context_menu(
 2118        &mut self,
 2119        f: impl 'static
 2120            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 2121    ) {
 2122        self.custom_context_menu = Some(Box::new(f))
 2123    }
 2124
 2125    pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
 2126        self.completion_provider = Some(provider);
 2127    }
 2128
 2129    pub fn set_inline_completion_provider<T>(
 2130        &mut self,
 2131        provider: Option<Model<T>>,
 2132        cx: &mut ViewContext<Self>,
 2133    ) where
 2134        T: InlineCompletionProvider,
 2135    {
 2136        self.inline_completion_provider =
 2137            provider.map(|provider| RegisteredInlineCompletionProvider {
 2138                _subscription: cx.observe(&provider, |this, _, cx| {
 2139                    if this.focus_handle.is_focused(cx) {
 2140                        this.update_visible_inline_completion(cx);
 2141                    }
 2142                }),
 2143                provider: Arc::new(provider),
 2144            });
 2145        self.refresh_inline_completion(false, cx);
 2146    }
 2147
 2148    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 2149        self.placeholder_text.as_deref()
 2150    }
 2151
 2152    pub fn set_placeholder_text(
 2153        &mut self,
 2154        placeholder_text: impl Into<Arc<str>>,
 2155        cx: &mut ViewContext<Self>,
 2156    ) {
 2157        let placeholder_text = Some(placeholder_text.into());
 2158        if self.placeholder_text != placeholder_text {
 2159            self.placeholder_text = placeholder_text;
 2160            cx.notify();
 2161        }
 2162    }
 2163
 2164    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 2165        self.cursor_shape = cursor_shape;
 2166
 2167        // Disrupt blink for immediate user feedback that the cursor shape has changed
 2168        self.blink_manager.update(cx, BlinkManager::show_cursor);
 2169
 2170        cx.notify();
 2171    }
 2172
 2173    pub fn set_current_line_highlight(
 2174        &mut self,
 2175        current_line_highlight: Option<CurrentLineHighlight>,
 2176    ) {
 2177        self.current_line_highlight = current_line_highlight;
 2178    }
 2179
 2180    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 2181        self.collapse_matches = collapse_matches;
 2182    }
 2183
 2184    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 2185        if self.collapse_matches {
 2186            return range.start..range.start;
 2187        }
 2188        range.clone()
 2189    }
 2190
 2191    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 2192        if self.display_map.read(cx).clip_at_line_ends != clip {
 2193            self.display_map
 2194                .update(cx, |map, _| map.clip_at_line_ends = clip);
 2195        }
 2196    }
 2197
 2198    pub fn set_keymap_context_layer<Tag: 'static>(
 2199        &mut self,
 2200        context: KeyContext,
 2201        cx: &mut ViewContext<Self>,
 2202    ) {
 2203        self.keymap_context_layers
 2204            .insert(TypeId::of::<Tag>(), context);
 2205        cx.notify();
 2206    }
 2207
 2208    pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
 2209        self.keymap_context_layers.remove(&TypeId::of::<Tag>());
 2210        cx.notify();
 2211    }
 2212
 2213    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 2214        self.input_enabled = input_enabled;
 2215    }
 2216
 2217    pub fn set_autoindent(&mut self, autoindent: bool) {
 2218        if autoindent {
 2219            self.autoindent_mode = Some(AutoindentMode::EachLine);
 2220        } else {
 2221            self.autoindent_mode = None;
 2222        }
 2223    }
 2224
 2225    pub fn read_only(&self, cx: &AppContext) -> bool {
 2226        self.read_only || self.buffer.read(cx).read_only()
 2227    }
 2228
 2229    pub fn set_read_only(&mut self, read_only: bool) {
 2230        self.read_only = read_only;
 2231    }
 2232
 2233    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 2234        self.use_autoclose = autoclose;
 2235    }
 2236
 2237    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 2238        self.use_auto_surround = auto_surround;
 2239    }
 2240
 2241    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 2242        self.auto_replace_emoji_shortcode = auto_replace;
 2243    }
 2244
 2245    pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
 2246        self.show_inline_completions = show_inline_completions;
 2247    }
 2248
 2249    pub fn set_use_modal_editing(&mut self, to: bool) {
 2250        self.use_modal_editing = to;
 2251    }
 2252
 2253    pub fn use_modal_editing(&self) -> bool {
 2254        self.use_modal_editing
 2255    }
 2256
 2257    fn selections_did_change(
 2258        &mut self,
 2259        local: bool,
 2260        old_cursor_position: &Anchor,
 2261        show_completions: bool,
 2262        cx: &mut ViewContext<Self>,
 2263    ) {
 2264        // Copy selections to primary selection buffer
 2265        #[cfg(target_os = "linux")]
 2266        if local {
 2267            let selections = self.selections.all::<usize>(cx);
 2268            let buffer_handle = self.buffer.read(cx).read(cx);
 2269
 2270            let mut text = String::new();
 2271            for (index, selection) in selections.iter().enumerate() {
 2272                let text_for_selection = buffer_handle
 2273                    .text_for_range(selection.start..selection.end)
 2274                    .collect::<String>();
 2275
 2276                text.push_str(&text_for_selection);
 2277                if index != selections.len() - 1 {
 2278                    text.push('\n');
 2279                }
 2280            }
 2281
 2282            if !text.is_empty() {
 2283                cx.write_to_primary(ClipboardItem::new(text));
 2284            }
 2285        }
 2286
 2287        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 2288            self.buffer.update(cx, |buffer, cx| {
 2289                buffer.set_active_selections(
 2290                    &self.selections.disjoint_anchors(),
 2291                    self.selections.line_mode,
 2292                    self.cursor_shape,
 2293                    cx,
 2294                )
 2295            });
 2296        }
 2297        let display_map = self
 2298            .display_map
 2299            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2300        let buffer = &display_map.buffer_snapshot;
 2301        self.add_selections_state = None;
 2302        self.select_next_state = None;
 2303        self.select_prev_state = None;
 2304        self.select_larger_syntax_node_stack.clear();
 2305        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2306        self.snippet_stack
 2307            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2308        self.take_rename(false, cx);
 2309
 2310        let new_cursor_position = self.selections.newest_anchor().head();
 2311
 2312        self.push_to_nav_history(
 2313            *old_cursor_position,
 2314            Some(new_cursor_position.to_point(buffer)),
 2315            cx,
 2316        );
 2317
 2318        if local {
 2319            let new_cursor_position = self.selections.newest_anchor().head();
 2320            let mut context_menu = self.context_menu.write();
 2321            let completion_menu = match context_menu.as_ref() {
 2322                Some(ContextMenu::Completions(menu)) => Some(menu),
 2323
 2324                _ => {
 2325                    *context_menu = None;
 2326                    None
 2327                }
 2328            };
 2329
 2330            if let Some(completion_menu) = completion_menu {
 2331                let cursor_position = new_cursor_position.to_offset(buffer);
 2332                let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
 2333                if kind == Some(CharKind::Word)
 2334                    && word_range.to_inclusive().contains(&cursor_position)
 2335                {
 2336                    let mut completion_menu = completion_menu.clone();
 2337                    drop(context_menu);
 2338
 2339                    let query = Self::completion_query(buffer, cursor_position);
 2340                    cx.spawn(move |this, mut cx| async move {
 2341                        completion_menu
 2342                            .filter(query.as_deref(), cx.background_executor().clone())
 2343                            .await;
 2344
 2345                        this.update(&mut cx, |this, cx| {
 2346                            let mut context_menu = this.context_menu.write();
 2347                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
 2348                                return;
 2349                            };
 2350
 2351                            if menu.id > completion_menu.id {
 2352                                return;
 2353                            }
 2354
 2355                            *context_menu = Some(ContextMenu::Completions(completion_menu));
 2356                            drop(context_menu);
 2357                            cx.notify();
 2358                        })
 2359                    })
 2360                    .detach();
 2361
 2362                    if show_completions {
 2363                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 2364                    }
 2365                } else {
 2366                    drop(context_menu);
 2367                    self.hide_context_menu(cx);
 2368                }
 2369            } else {
 2370                drop(context_menu);
 2371            }
 2372
 2373            hide_hover(self, cx);
 2374
 2375            if old_cursor_position.to_display_point(&display_map).row()
 2376                != new_cursor_position.to_display_point(&display_map).row()
 2377            {
 2378                self.available_code_actions.take();
 2379            }
 2380            self.refresh_code_actions(cx);
 2381            self.refresh_document_highlights(cx);
 2382            refresh_matching_bracket_highlights(self, cx);
 2383            self.discard_inline_completion(false, cx);
 2384            linked_editing_ranges::refresh_linked_ranges(self, cx);
 2385            if self.git_blame_inline_enabled {
 2386                self.start_inline_blame_timer(cx);
 2387            }
 2388        }
 2389
 2390        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2391        cx.emit(EditorEvent::SelectionsChanged { local });
 2392
 2393        if self.selections.disjoint_anchors().len() == 1 {
 2394            cx.emit(SearchEvent::ActiveMatchChanged)
 2395        }
 2396        cx.notify();
 2397    }
 2398
 2399    pub fn change_selections<R>(
 2400        &mut self,
 2401        autoscroll: Option<Autoscroll>,
 2402        cx: &mut ViewContext<Self>,
 2403        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2404    ) -> R {
 2405        self.change_selections_inner(autoscroll, true, cx, change)
 2406    }
 2407
 2408    pub fn change_selections_inner<R>(
 2409        &mut self,
 2410        autoscroll: Option<Autoscroll>,
 2411        request_completions: bool,
 2412        cx: &mut ViewContext<Self>,
 2413        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2414    ) -> R {
 2415        let old_cursor_position = self.selections.newest_anchor().head();
 2416        self.push_to_selection_history();
 2417
 2418        let (changed, result) = self.selections.change_with(cx, change);
 2419
 2420        if changed {
 2421            if let Some(autoscroll) = autoscroll {
 2422                self.request_autoscroll(autoscroll, cx);
 2423            }
 2424            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2425
 2426            if self.should_open_signature_help_automatically(
 2427                &old_cursor_position,
 2428                self.signature_help_state.backspace_pressed(),
 2429                cx,
 2430            ) {
 2431                self.show_signature_help(&ShowSignatureHelp, cx);
 2432            }
 2433            self.signature_help_state.set_backspace_pressed(false);
 2434        }
 2435
 2436        result
 2437    }
 2438
 2439    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2440    where
 2441        I: IntoIterator<Item = (Range<S>, T)>,
 2442        S: ToOffset,
 2443        T: Into<Arc<str>>,
 2444    {
 2445        if self.read_only(cx) {
 2446            return;
 2447        }
 2448
 2449        self.buffer
 2450            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2451    }
 2452
 2453    pub fn edit_with_autoindent<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.update(cx, |buffer, cx| {
 2464            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2465        });
 2466    }
 2467
 2468    pub fn edit_with_block_indent<I, S, T>(
 2469        &mut self,
 2470        edits: I,
 2471        original_indent_columns: Vec<u32>,
 2472        cx: &mut ViewContext<Self>,
 2473    ) where
 2474        I: IntoIterator<Item = (Range<S>, T)>,
 2475        S: ToOffset,
 2476        T: Into<Arc<str>>,
 2477    {
 2478        if self.read_only(cx) {
 2479            return;
 2480        }
 2481
 2482        self.buffer.update(cx, |buffer, cx| {
 2483            buffer.edit(
 2484                edits,
 2485                Some(AutoindentMode::Block {
 2486                    original_indent_columns,
 2487                }),
 2488                cx,
 2489            )
 2490        });
 2491    }
 2492
 2493    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2494        self.hide_context_menu(cx);
 2495
 2496        match phase {
 2497            SelectPhase::Begin {
 2498                position,
 2499                add,
 2500                click_count,
 2501            } => self.begin_selection(position, add, click_count, cx),
 2502            SelectPhase::BeginColumnar {
 2503                position,
 2504                goal_column,
 2505                reset,
 2506            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2507            SelectPhase::Extend {
 2508                position,
 2509                click_count,
 2510            } => self.extend_selection(position, click_count, cx),
 2511            SelectPhase::Update {
 2512                position,
 2513                goal_column,
 2514                scroll_delta,
 2515            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2516            SelectPhase::End => self.end_selection(cx),
 2517        }
 2518    }
 2519
 2520    fn extend_selection(
 2521        &mut self,
 2522        position: DisplayPoint,
 2523        click_count: usize,
 2524        cx: &mut ViewContext<Self>,
 2525    ) {
 2526        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2527        let tail = self.selections.newest::<usize>(cx).tail();
 2528        self.begin_selection(position, false, click_count, cx);
 2529
 2530        let position = position.to_offset(&display_map, Bias::Left);
 2531        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2532
 2533        let mut pending_selection = self
 2534            .selections
 2535            .pending_anchor()
 2536            .expect("extend_selection not called with pending selection");
 2537        if position >= tail {
 2538            pending_selection.start = tail_anchor;
 2539        } else {
 2540            pending_selection.end = tail_anchor;
 2541            pending_selection.reversed = true;
 2542        }
 2543
 2544        let mut pending_mode = self.selections.pending_mode().unwrap();
 2545        match &mut pending_mode {
 2546            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2547            _ => {}
 2548        }
 2549
 2550        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2551            s.set_pending(pending_selection, pending_mode)
 2552        });
 2553    }
 2554
 2555    fn begin_selection(
 2556        &mut self,
 2557        position: DisplayPoint,
 2558        add: bool,
 2559        click_count: usize,
 2560        cx: &mut ViewContext<Self>,
 2561    ) {
 2562        if !self.focus_handle.is_focused(cx) {
 2563            self.last_focused_descendant = None;
 2564            cx.focus(&self.focus_handle);
 2565        }
 2566
 2567        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2568        let buffer = &display_map.buffer_snapshot;
 2569        let newest_selection = self.selections.newest_anchor().clone();
 2570        let position = display_map.clip_point(position, Bias::Left);
 2571
 2572        let start;
 2573        let end;
 2574        let mode;
 2575        let auto_scroll;
 2576        match click_count {
 2577            1 => {
 2578                start = buffer.anchor_before(position.to_point(&display_map));
 2579                end = start;
 2580                mode = SelectMode::Character;
 2581                auto_scroll = true;
 2582            }
 2583            2 => {
 2584                let range = movement::surrounding_word(&display_map, position);
 2585                start = buffer.anchor_before(range.start.to_point(&display_map));
 2586                end = buffer.anchor_before(range.end.to_point(&display_map));
 2587                mode = SelectMode::Word(start..end);
 2588                auto_scroll = true;
 2589            }
 2590            3 => {
 2591                let position = display_map
 2592                    .clip_point(position, Bias::Left)
 2593                    .to_point(&display_map);
 2594                let line_start = display_map.prev_line_boundary(position).0;
 2595                let next_line_start = buffer.clip_point(
 2596                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2597                    Bias::Left,
 2598                );
 2599                start = buffer.anchor_before(line_start);
 2600                end = buffer.anchor_before(next_line_start);
 2601                mode = SelectMode::Line(start..end);
 2602                auto_scroll = true;
 2603            }
 2604            _ => {
 2605                start = buffer.anchor_before(0);
 2606                end = buffer.anchor_before(buffer.len());
 2607                mode = SelectMode::All;
 2608                auto_scroll = false;
 2609            }
 2610        }
 2611
 2612        let point_to_delete: Option<usize> = {
 2613            let selected_points: Vec<Selection<Point>> =
 2614                self.selections.disjoint_in_range(start..end, cx);
 2615
 2616            if !add || click_count > 1 {
 2617                None
 2618            } else if selected_points.len() > 0 {
 2619                Some(selected_points[0].id)
 2620            } else {
 2621                let clicked_point_already_selected =
 2622                    self.selections.disjoint.iter().find(|selection| {
 2623                        selection.start.to_point(buffer) == start.to_point(buffer)
 2624                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2625                    });
 2626
 2627                if let Some(selection) = clicked_point_already_selected {
 2628                    Some(selection.id)
 2629                } else {
 2630                    None
 2631                }
 2632            }
 2633        };
 2634
 2635        let selections_count = self.selections.count();
 2636
 2637        self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
 2638            if let Some(point_to_delete) = point_to_delete {
 2639                s.delete(point_to_delete);
 2640
 2641                if selections_count == 1 {
 2642                    s.set_pending_anchor_range(start..end, mode);
 2643                }
 2644            } else {
 2645                if !add {
 2646                    s.clear_disjoint();
 2647                } else if click_count > 1 {
 2648                    s.delete(newest_selection.id)
 2649                }
 2650
 2651                s.set_pending_anchor_range(start..end, mode);
 2652            }
 2653        });
 2654    }
 2655
 2656    fn begin_columnar_selection(
 2657        &mut self,
 2658        position: DisplayPoint,
 2659        goal_column: u32,
 2660        reset: bool,
 2661        cx: &mut ViewContext<Self>,
 2662    ) {
 2663        if !self.focus_handle.is_focused(cx) {
 2664            self.last_focused_descendant = None;
 2665            cx.focus(&self.focus_handle);
 2666        }
 2667
 2668        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2669
 2670        if reset {
 2671            let pointer_position = display_map
 2672                .buffer_snapshot
 2673                .anchor_before(position.to_point(&display_map));
 2674
 2675            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2676                s.clear_disjoint();
 2677                s.set_pending_anchor_range(
 2678                    pointer_position..pointer_position,
 2679                    SelectMode::Character,
 2680                );
 2681            });
 2682        }
 2683
 2684        let tail = self.selections.newest::<Point>(cx).tail();
 2685        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2686
 2687        if !reset {
 2688            self.select_columns(
 2689                tail.to_display_point(&display_map),
 2690                position,
 2691                goal_column,
 2692                &display_map,
 2693                cx,
 2694            );
 2695        }
 2696    }
 2697
 2698    fn update_selection(
 2699        &mut self,
 2700        position: DisplayPoint,
 2701        goal_column: u32,
 2702        scroll_delta: gpui::Point<f32>,
 2703        cx: &mut ViewContext<Self>,
 2704    ) {
 2705        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2706
 2707        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2708            let tail = tail.to_display_point(&display_map);
 2709            self.select_columns(tail, position, goal_column, &display_map, cx);
 2710        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2711            let buffer = self.buffer.read(cx).snapshot(cx);
 2712            let head;
 2713            let tail;
 2714            let mode = self.selections.pending_mode().unwrap();
 2715            match &mode {
 2716                SelectMode::Character => {
 2717                    head = position.to_point(&display_map);
 2718                    tail = pending.tail().to_point(&buffer);
 2719                }
 2720                SelectMode::Word(original_range) => {
 2721                    let original_display_range = original_range.start.to_display_point(&display_map)
 2722                        ..original_range.end.to_display_point(&display_map);
 2723                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2724                        ..original_display_range.end.to_point(&display_map);
 2725                    if movement::is_inside_word(&display_map, position)
 2726                        || original_display_range.contains(&position)
 2727                    {
 2728                        let word_range = movement::surrounding_word(&display_map, position);
 2729                        if word_range.start < original_display_range.start {
 2730                            head = word_range.start.to_point(&display_map);
 2731                        } else {
 2732                            head = word_range.end.to_point(&display_map);
 2733                        }
 2734                    } else {
 2735                        head = position.to_point(&display_map);
 2736                    }
 2737
 2738                    if head <= original_buffer_range.start {
 2739                        tail = original_buffer_range.end;
 2740                    } else {
 2741                        tail = original_buffer_range.start;
 2742                    }
 2743                }
 2744                SelectMode::Line(original_range) => {
 2745                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2746
 2747                    let position = display_map
 2748                        .clip_point(position, Bias::Left)
 2749                        .to_point(&display_map);
 2750                    let line_start = display_map.prev_line_boundary(position).0;
 2751                    let next_line_start = buffer.clip_point(
 2752                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2753                        Bias::Left,
 2754                    );
 2755
 2756                    if line_start < original_range.start {
 2757                        head = line_start
 2758                    } else {
 2759                        head = next_line_start
 2760                    }
 2761
 2762                    if head <= original_range.start {
 2763                        tail = original_range.end;
 2764                    } else {
 2765                        tail = original_range.start;
 2766                    }
 2767                }
 2768                SelectMode::All => {
 2769                    return;
 2770                }
 2771            };
 2772
 2773            if head < tail {
 2774                pending.start = buffer.anchor_before(head);
 2775                pending.end = buffer.anchor_before(tail);
 2776                pending.reversed = true;
 2777            } else {
 2778                pending.start = buffer.anchor_before(tail);
 2779                pending.end = buffer.anchor_before(head);
 2780                pending.reversed = false;
 2781            }
 2782
 2783            self.change_selections(None, cx, |s| {
 2784                s.set_pending(pending, mode);
 2785            });
 2786        } else {
 2787            log::error!("update_selection dispatched with no pending selection");
 2788            return;
 2789        }
 2790
 2791        self.apply_scroll_delta(scroll_delta, cx);
 2792        cx.notify();
 2793    }
 2794
 2795    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2796        self.columnar_selection_tail.take();
 2797        if self.selections.pending_anchor().is_some() {
 2798            let selections = self.selections.all::<usize>(cx);
 2799            self.change_selections(None, cx, |s| {
 2800                s.select(selections);
 2801                s.clear_pending();
 2802            });
 2803        }
 2804    }
 2805
 2806    fn select_columns(
 2807        &mut self,
 2808        tail: DisplayPoint,
 2809        head: DisplayPoint,
 2810        goal_column: u32,
 2811        display_map: &DisplaySnapshot,
 2812        cx: &mut ViewContext<Self>,
 2813    ) {
 2814        let start_row = cmp::min(tail.row(), head.row());
 2815        let end_row = cmp::max(tail.row(), head.row());
 2816        let start_column = cmp::min(tail.column(), goal_column);
 2817        let end_column = cmp::max(tail.column(), goal_column);
 2818        let reversed = start_column < tail.column();
 2819
 2820        let selection_ranges = (start_row.0..=end_row.0)
 2821            .map(DisplayRow)
 2822            .filter_map(|row| {
 2823                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2824                    let start = display_map
 2825                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2826                        .to_point(display_map);
 2827                    let end = display_map
 2828                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2829                        .to_point(display_map);
 2830                    if reversed {
 2831                        Some(end..start)
 2832                    } else {
 2833                        Some(start..end)
 2834                    }
 2835                } else {
 2836                    None
 2837                }
 2838            })
 2839            .collect::<Vec<_>>();
 2840
 2841        self.change_selections(None, cx, |s| {
 2842            s.select_ranges(selection_ranges);
 2843        });
 2844        cx.notify();
 2845    }
 2846
 2847    pub fn has_pending_nonempty_selection(&self) -> bool {
 2848        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2849            Some(Selection { start, end, .. }) => start != end,
 2850            None => false,
 2851        };
 2852
 2853        pending_nonempty_selection
 2854            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2855    }
 2856
 2857    pub fn has_pending_selection(&self) -> bool {
 2858        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2859    }
 2860
 2861    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2862        if self.clear_clicked_diff_hunks(cx) {
 2863            cx.notify();
 2864            return;
 2865        }
 2866        if self.dismiss_menus_and_popups(true, cx) {
 2867            return;
 2868        }
 2869
 2870        if self.mode == EditorMode::Full {
 2871            if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
 2872                return;
 2873            }
 2874        }
 2875
 2876        cx.propagate();
 2877    }
 2878
 2879    pub fn dismiss_menus_and_popups(
 2880        &mut self,
 2881        should_report_inline_completion_event: bool,
 2882        cx: &mut ViewContext<Self>,
 2883    ) -> bool {
 2884        if self.take_rename(false, cx).is_some() {
 2885            return true;
 2886        }
 2887
 2888        if hide_hover(self, cx) {
 2889            return true;
 2890        }
 2891
 2892        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2893            return true;
 2894        }
 2895
 2896        if self.hide_context_menu(cx).is_some() {
 2897            return true;
 2898        }
 2899
 2900        if self.mouse_context_menu.take().is_some() {
 2901            return true;
 2902        }
 2903
 2904        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2905            return true;
 2906        }
 2907
 2908        if self.snippet_stack.pop().is_some() {
 2909            return true;
 2910        }
 2911
 2912        if self.mode == EditorMode::Full {
 2913            if self.active_diagnostics.is_some() {
 2914                self.dismiss_diagnostics(cx);
 2915                return true;
 2916            }
 2917        }
 2918
 2919        false
 2920    }
 2921
 2922    fn linked_editing_ranges_for(
 2923        &self,
 2924        selection: Range<text::Anchor>,
 2925        cx: &AppContext,
 2926    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2927        if self.linked_edit_ranges.is_empty() {
 2928            return None;
 2929        }
 2930        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2931            selection.end.buffer_id.and_then(|end_buffer_id| {
 2932                if selection.start.buffer_id != Some(end_buffer_id) {
 2933                    return None;
 2934                }
 2935                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2936                let snapshot = buffer.read(cx).snapshot();
 2937                self.linked_edit_ranges
 2938                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2939                    .map(|ranges| (ranges, snapshot, buffer))
 2940            })?;
 2941        use text::ToOffset as TO;
 2942        // find offset from the start of current range to current cursor position
 2943        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2944
 2945        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2946        let start_difference = start_offset - start_byte_offset;
 2947        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2948        let end_difference = end_offset - start_byte_offset;
 2949        // Current range has associated linked ranges.
 2950        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2951        for range in linked_ranges.iter() {
 2952            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2953            let end_offset = start_offset + end_difference;
 2954            let start_offset = start_offset + start_difference;
 2955            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2956                continue;
 2957            }
 2958            let start = buffer_snapshot.anchor_after(start_offset);
 2959            let end = buffer_snapshot.anchor_after(end_offset);
 2960            linked_edits
 2961                .entry(buffer.clone())
 2962                .or_default()
 2963                .push(start..end);
 2964        }
 2965        Some(linked_edits)
 2966    }
 2967
 2968    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2969        let text: Arc<str> = text.into();
 2970
 2971        if self.read_only(cx) {
 2972            return;
 2973        }
 2974
 2975        let selections = self.selections.all_adjusted(cx);
 2976        let mut bracket_inserted = false;
 2977        let mut edits = Vec::new();
 2978        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2979        let mut new_selections = Vec::with_capacity(selections.len());
 2980        let mut new_autoclose_regions = Vec::new();
 2981        let snapshot = self.buffer.read(cx).read(cx);
 2982
 2983        for (selection, autoclose_region) in
 2984            self.selections_with_autoclose_regions(selections, &snapshot)
 2985        {
 2986            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2987                // Determine if the inserted text matches the opening or closing
 2988                // bracket of any of this language's bracket pairs.
 2989                let mut bracket_pair = None;
 2990                let mut is_bracket_pair_start = false;
 2991                let mut is_bracket_pair_end = false;
 2992                if !text.is_empty() {
 2993                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2994                    //  and they are removing the character that triggered IME popup.
 2995                    for (pair, enabled) in scope.brackets() {
 2996                        if !pair.close && !pair.surround {
 2997                            continue;
 2998                        }
 2999
 3000                        if enabled && pair.start.ends_with(text.as_ref()) {
 3001                            bracket_pair = Some(pair.clone());
 3002                            is_bracket_pair_start = true;
 3003                            break;
 3004                        }
 3005                        if pair.end.as_str() == text.as_ref() {
 3006                            bracket_pair = Some(pair.clone());
 3007                            is_bracket_pair_end = true;
 3008                            break;
 3009                        }
 3010                    }
 3011                }
 3012
 3013                if let Some(bracket_pair) = bracket_pair {
 3014                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 3015                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 3016                    let auto_surround =
 3017                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 3018                    if selection.is_empty() {
 3019                        if is_bracket_pair_start {
 3020                            let prefix_len = bracket_pair.start.len() - text.len();
 3021
 3022                            // If the inserted text is a suffix of an opening bracket and the
 3023                            // selection is preceded by the rest of the opening bracket, then
 3024                            // insert the closing bracket.
 3025                            let following_text_allows_autoclose = snapshot
 3026                                .chars_at(selection.start)
 3027                                .next()
 3028                                .map_or(true, |c| scope.should_autoclose_before(c));
 3029                            let preceding_text_matches_prefix = prefix_len == 0
 3030                                || (selection.start.column >= (prefix_len as u32)
 3031                                    && snapshot.contains_str_at(
 3032                                        Point::new(
 3033                                            selection.start.row,
 3034                                            selection.start.column - (prefix_len as u32),
 3035                                        ),
 3036                                        &bracket_pair.start[..prefix_len],
 3037                                    ));
 3038
 3039                            if autoclose
 3040                                && bracket_pair.close
 3041                                && following_text_allows_autoclose
 3042                                && preceding_text_matches_prefix
 3043                            {
 3044                                let anchor = snapshot.anchor_before(selection.end);
 3045                                new_selections.push((selection.map(|_| anchor), text.len()));
 3046                                new_autoclose_regions.push((
 3047                                    anchor,
 3048                                    text.len(),
 3049                                    selection.id,
 3050                                    bracket_pair.clone(),
 3051                                ));
 3052                                edits.push((
 3053                                    selection.range(),
 3054                                    format!("{}{}", text, bracket_pair.end).into(),
 3055                                ));
 3056                                bracket_inserted = true;
 3057                                continue;
 3058                            }
 3059                        }
 3060
 3061                        if let Some(region) = autoclose_region {
 3062                            // If the selection is followed by an auto-inserted closing bracket,
 3063                            // then don't insert that closing bracket again; just move the selection
 3064                            // past the closing bracket.
 3065                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 3066                                && text.as_ref() == region.pair.end.as_str();
 3067                            if should_skip {
 3068                                let anchor = snapshot.anchor_after(selection.end);
 3069                                new_selections
 3070                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 3071                                continue;
 3072                            }
 3073                        }
 3074
 3075                        let always_treat_brackets_as_autoclosed = snapshot
 3076                            .settings_at(selection.start, cx)
 3077                            .always_treat_brackets_as_autoclosed;
 3078                        if always_treat_brackets_as_autoclosed
 3079                            && is_bracket_pair_end
 3080                            && snapshot.contains_str_at(selection.end, text.as_ref())
 3081                        {
 3082                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 3083                            // and the inserted text is a closing bracket and the selection is followed
 3084                            // by the closing bracket then move the selection past the closing bracket.
 3085                            let anchor = snapshot.anchor_after(selection.end);
 3086                            new_selections.push((selection.map(|_| anchor), text.len()));
 3087                            continue;
 3088                        }
 3089                    }
 3090                    // If an opening bracket is 1 character long and is typed while
 3091                    // text is selected, then surround that text with the bracket pair.
 3092                    else if auto_surround
 3093                        && bracket_pair.surround
 3094                        && is_bracket_pair_start
 3095                        && bracket_pair.start.chars().count() == 1
 3096                    {
 3097                        edits.push((selection.start..selection.start, text.clone()));
 3098                        edits.push((
 3099                            selection.end..selection.end,
 3100                            bracket_pair.end.as_str().into(),
 3101                        ));
 3102                        bracket_inserted = true;
 3103                        new_selections.push((
 3104                            Selection {
 3105                                id: selection.id,
 3106                                start: snapshot.anchor_after(selection.start),
 3107                                end: snapshot.anchor_before(selection.end),
 3108                                reversed: selection.reversed,
 3109                                goal: selection.goal,
 3110                            },
 3111                            0,
 3112                        ));
 3113                        continue;
 3114                    }
 3115                }
 3116            }
 3117
 3118            if self.auto_replace_emoji_shortcode
 3119                && selection.is_empty()
 3120                && text.as_ref().ends_with(':')
 3121            {
 3122                if let Some(possible_emoji_short_code) =
 3123                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 3124                {
 3125                    if !possible_emoji_short_code.is_empty() {
 3126                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 3127                            let emoji_shortcode_start = Point::new(
 3128                                selection.start.row,
 3129                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 3130                            );
 3131
 3132                            // Remove shortcode from buffer
 3133                            edits.push((
 3134                                emoji_shortcode_start..selection.start,
 3135                                "".to_string().into(),
 3136                            ));
 3137                            new_selections.push((
 3138                                Selection {
 3139                                    id: selection.id,
 3140                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3141                                    end: snapshot.anchor_before(selection.start),
 3142                                    reversed: selection.reversed,
 3143                                    goal: selection.goal,
 3144                                },
 3145                                0,
 3146                            ));
 3147
 3148                            // Insert emoji
 3149                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3150                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3151                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3152
 3153                            continue;
 3154                        }
 3155                    }
 3156                }
 3157            }
 3158
 3159            // If not handling any auto-close operation, then just replace the selected
 3160            // text with the given input and move the selection to the end of the
 3161            // newly inserted text.
 3162            let anchor = snapshot.anchor_after(selection.end);
 3163            if !self.linked_edit_ranges.is_empty() {
 3164                let start_anchor = snapshot.anchor_before(selection.start);
 3165
 3166                let is_word_char = text.chars().next().map_or(true, |char| {
 3167                    let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
 3168                    let kind = char_kind(&scope, char);
 3169
 3170                    kind == CharKind::Word
 3171                });
 3172
 3173                if is_word_char {
 3174                    if let Some(ranges) = self
 3175                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3176                    {
 3177                        for (buffer, edits) in ranges {
 3178                            linked_edits
 3179                                .entry(buffer.clone())
 3180                                .or_default()
 3181                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3182                        }
 3183                    }
 3184                }
 3185            }
 3186
 3187            new_selections.push((selection.map(|_| anchor), 0));
 3188            edits.push((selection.start..selection.end, text.clone()));
 3189        }
 3190
 3191        drop(snapshot);
 3192
 3193        self.transact(cx, |this, cx| {
 3194            this.buffer.update(cx, |buffer, cx| {
 3195                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3196            });
 3197            for (buffer, edits) in linked_edits {
 3198                buffer.update(cx, |buffer, cx| {
 3199                    let snapshot = buffer.snapshot();
 3200                    let edits = edits
 3201                        .into_iter()
 3202                        .map(|(range, text)| {
 3203                            use text::ToPoint as TP;
 3204                            let end_point = TP::to_point(&range.end, &snapshot);
 3205                            let start_point = TP::to_point(&range.start, &snapshot);
 3206                            (start_point..end_point, text)
 3207                        })
 3208                        .sorted_by_key(|(range, _)| range.start)
 3209                        .collect::<Vec<_>>();
 3210                    buffer.edit(edits, None, cx);
 3211                })
 3212            }
 3213            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3214            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3215            let snapshot = this.buffer.read(cx).read(cx);
 3216            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
 3217                .zip(new_selection_deltas)
 3218                .map(|(selection, delta)| Selection {
 3219                    id: selection.id,
 3220                    start: selection.start + delta,
 3221                    end: selection.end + delta,
 3222                    reversed: selection.reversed,
 3223                    goal: SelectionGoal::None,
 3224                })
 3225                .collect::<Vec<_>>();
 3226
 3227            let mut i = 0;
 3228            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3229                let position = position.to_offset(&snapshot) + delta;
 3230                let start = snapshot.anchor_before(position);
 3231                let end = snapshot.anchor_after(position);
 3232                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3233                    match existing_state.range.start.cmp(&start, &snapshot) {
 3234                        Ordering::Less => i += 1,
 3235                        Ordering::Greater => break,
 3236                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
 3237                            Ordering::Less => i += 1,
 3238                            Ordering::Equal => break,
 3239                            Ordering::Greater => break,
 3240                        },
 3241                    }
 3242                }
 3243                this.autoclose_regions.insert(
 3244                    i,
 3245                    AutocloseRegion {
 3246                        selection_id,
 3247                        range: start..end,
 3248                        pair,
 3249                    },
 3250                );
 3251            }
 3252
 3253            drop(snapshot);
 3254            let had_active_inline_completion = this.has_active_inline_completion(cx);
 3255            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 3256                s.select(new_selections)
 3257            });
 3258
 3259            if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
 3260                if let Some(on_type_format_task) =
 3261                    this.trigger_on_type_formatting(text.to_string(), cx)
 3262                {
 3263                    on_type_format_task.detach_and_log_err(cx);
 3264                }
 3265            }
 3266
 3267            let editor_settings = EditorSettings::get_global(cx);
 3268            if bracket_inserted
 3269                && (editor_settings.auto_signature_help
 3270                    || editor_settings.show_signature_help_after_edits)
 3271            {
 3272                this.show_signature_help(&ShowSignatureHelp, cx);
 3273            }
 3274
 3275            let trigger_in_words = !had_active_inline_completion;
 3276            this.trigger_completion_on_input(&text, trigger_in_words, cx);
 3277            linked_editing_ranges::refresh_linked_ranges(this, cx);
 3278            this.refresh_inline_completion(true, cx);
 3279        });
 3280    }
 3281
 3282    fn find_possible_emoji_shortcode_at_position(
 3283        snapshot: &MultiBufferSnapshot,
 3284        position: Point,
 3285    ) -> Option<String> {
 3286        let mut chars = Vec::new();
 3287        let mut found_colon = false;
 3288        for char in snapshot.reversed_chars_at(position).take(100) {
 3289            // Found a possible emoji shortcode in the middle of the buffer
 3290            if found_colon {
 3291                if char.is_whitespace() {
 3292                    chars.reverse();
 3293                    return Some(chars.iter().collect());
 3294                }
 3295                // If the previous character is not a whitespace, we are in the middle of a word
 3296                // and we only want to complete the shortcode if the word is made up of other emojis
 3297                let mut containing_word = String::new();
 3298                for ch in snapshot
 3299                    .reversed_chars_at(position)
 3300                    .skip(chars.len() + 1)
 3301                    .take(100)
 3302                {
 3303                    if ch.is_whitespace() {
 3304                        break;
 3305                    }
 3306                    containing_word.push(ch);
 3307                }
 3308                let containing_word = containing_word.chars().rev().collect::<String>();
 3309                if util::word_consists_of_emojis(containing_word.as_str()) {
 3310                    chars.reverse();
 3311                    return Some(chars.iter().collect());
 3312                }
 3313            }
 3314
 3315            if char.is_whitespace() || !char.is_ascii() {
 3316                return None;
 3317            }
 3318            if char == ':' {
 3319                found_colon = true;
 3320            } else {
 3321                chars.push(char);
 3322            }
 3323        }
 3324        // Found a possible emoji shortcode at the beginning of the buffer
 3325        chars.reverse();
 3326        Some(chars.iter().collect())
 3327    }
 3328
 3329    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 3330        self.transact(cx, |this, cx| {
 3331            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3332                let selections = this.selections.all::<usize>(cx);
 3333                let multi_buffer = this.buffer.read(cx);
 3334                let buffer = multi_buffer.snapshot(cx);
 3335                selections
 3336                    .iter()
 3337                    .map(|selection| {
 3338                        let start_point = selection.start.to_point(&buffer);
 3339                        let mut indent =
 3340                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3341                        indent.len = cmp::min(indent.len, start_point.column);
 3342                        let start = selection.start;
 3343                        let end = selection.end;
 3344                        let selection_is_empty = start == end;
 3345                        let language_scope = buffer.language_scope_at(start);
 3346                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3347                            &language_scope
 3348                        {
 3349                            let leading_whitespace_len = buffer
 3350                                .reversed_chars_at(start)
 3351                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3352                                .map(|c| c.len_utf8())
 3353                                .sum::<usize>();
 3354
 3355                            let trailing_whitespace_len = buffer
 3356                                .chars_at(end)
 3357                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3358                                .map(|c| c.len_utf8())
 3359                                .sum::<usize>();
 3360
 3361                            let insert_extra_newline =
 3362                                language.brackets().any(|(pair, enabled)| {
 3363                                    let pair_start = pair.start.trim_end();
 3364                                    let pair_end = pair.end.trim_start();
 3365
 3366                                    enabled
 3367                                        && pair.newline
 3368                                        && buffer.contains_str_at(
 3369                                            end + trailing_whitespace_len,
 3370                                            pair_end,
 3371                                        )
 3372                                        && buffer.contains_str_at(
 3373                                            (start - leading_whitespace_len)
 3374                                                .saturating_sub(pair_start.len()),
 3375                                            pair_start,
 3376                                        )
 3377                                });
 3378
 3379                            // Comment extension on newline is allowed only for cursor selections
 3380                            let comment_delimiter = maybe!({
 3381                                if !selection_is_empty {
 3382                                    return None;
 3383                                }
 3384
 3385                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3386                                    return None;
 3387                                }
 3388
 3389                                let delimiters = language.line_comment_prefixes();
 3390                                let max_len_of_delimiter =
 3391                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3392                                let (snapshot, range) =
 3393                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3394
 3395                                let mut index_of_first_non_whitespace = 0;
 3396                                let comment_candidate = snapshot
 3397                                    .chars_for_range(range)
 3398                                    .skip_while(|c| {
 3399                                        let should_skip = c.is_whitespace();
 3400                                        if should_skip {
 3401                                            index_of_first_non_whitespace += 1;
 3402                                        }
 3403                                        should_skip
 3404                                    })
 3405                                    .take(max_len_of_delimiter)
 3406                                    .collect::<String>();
 3407                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3408                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3409                                })?;
 3410                                let cursor_is_placed_after_comment_marker =
 3411                                    index_of_first_non_whitespace + comment_prefix.len()
 3412                                        <= start_point.column as usize;
 3413                                if cursor_is_placed_after_comment_marker {
 3414                                    Some(comment_prefix.clone())
 3415                                } else {
 3416                                    None
 3417                                }
 3418                            });
 3419                            (comment_delimiter, insert_extra_newline)
 3420                        } else {
 3421                            (None, false)
 3422                        };
 3423
 3424                        let capacity_for_delimiter = comment_delimiter
 3425                            .as_deref()
 3426                            .map(str::len)
 3427                            .unwrap_or_default();
 3428                        let mut new_text =
 3429                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3430                        new_text.push_str("\n");
 3431                        new_text.extend(indent.chars());
 3432                        if let Some(delimiter) = &comment_delimiter {
 3433                            new_text.push_str(&delimiter);
 3434                        }
 3435                        if insert_extra_newline {
 3436                            new_text = new_text.repeat(2);
 3437                        }
 3438
 3439                        let anchor = buffer.anchor_after(end);
 3440                        let new_selection = selection.map(|_| anchor);
 3441                        (
 3442                            (start..end, new_text),
 3443                            (insert_extra_newline, new_selection),
 3444                        )
 3445                    })
 3446                    .unzip()
 3447            };
 3448
 3449            this.edit_with_autoindent(edits, cx);
 3450            let buffer = this.buffer.read(cx).snapshot(cx);
 3451            let new_selections = selection_fixup_info
 3452                .into_iter()
 3453                .map(|(extra_newline_inserted, new_selection)| {
 3454                    let mut cursor = new_selection.end.to_point(&buffer);
 3455                    if extra_newline_inserted {
 3456                        cursor.row -= 1;
 3457                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3458                    }
 3459                    new_selection.map(|_| cursor)
 3460                })
 3461                .collect();
 3462
 3463            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3464            this.refresh_inline_completion(true, cx);
 3465        });
 3466    }
 3467
 3468    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3469        let buffer = self.buffer.read(cx);
 3470        let snapshot = buffer.snapshot(cx);
 3471
 3472        let mut edits = Vec::new();
 3473        let mut rows = Vec::new();
 3474
 3475        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3476            let cursor = selection.head();
 3477            let row = cursor.row;
 3478
 3479            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3480
 3481            let newline = "\n".to_string();
 3482            edits.push((start_of_line..start_of_line, newline));
 3483
 3484            rows.push(row + rows_inserted as u32);
 3485        }
 3486
 3487        self.transact(cx, |editor, cx| {
 3488            editor.edit(edits, cx);
 3489
 3490            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3491                let mut index = 0;
 3492                s.move_cursors_with(|map, _, _| {
 3493                    let row = rows[index];
 3494                    index += 1;
 3495
 3496                    let point = Point::new(row, 0);
 3497                    let boundary = map.next_line_boundary(point).1;
 3498                    let clipped = map.clip_point(boundary, Bias::Left);
 3499
 3500                    (clipped, SelectionGoal::None)
 3501                });
 3502            });
 3503
 3504            let mut indent_edits = Vec::new();
 3505            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3506            for row in rows {
 3507                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3508                for (row, indent) in indents {
 3509                    if indent.len == 0 {
 3510                        continue;
 3511                    }
 3512
 3513                    let text = match indent.kind {
 3514                        IndentKind::Space => " ".repeat(indent.len as usize),
 3515                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3516                    };
 3517                    let point = Point::new(row.0, 0);
 3518                    indent_edits.push((point..point, text));
 3519                }
 3520            }
 3521            editor.edit(indent_edits, cx);
 3522        });
 3523    }
 3524
 3525    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3526        let buffer = self.buffer.read(cx);
 3527        let snapshot = buffer.snapshot(cx);
 3528
 3529        let mut edits = Vec::new();
 3530        let mut rows = Vec::new();
 3531        let mut rows_inserted = 0;
 3532
 3533        for selection in self.selections.all_adjusted(cx) {
 3534            let cursor = selection.head();
 3535            let row = cursor.row;
 3536
 3537            let point = Point::new(row + 1, 0);
 3538            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3539
 3540            let newline = "\n".to_string();
 3541            edits.push((start_of_line..start_of_line, newline));
 3542
 3543            rows_inserted += 1;
 3544            rows.push(row + rows_inserted);
 3545        }
 3546
 3547        self.transact(cx, |editor, cx| {
 3548            editor.edit(edits, cx);
 3549
 3550            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3551                let mut index = 0;
 3552                s.move_cursors_with(|map, _, _| {
 3553                    let row = rows[index];
 3554                    index += 1;
 3555
 3556                    let point = Point::new(row, 0);
 3557                    let boundary = map.next_line_boundary(point).1;
 3558                    let clipped = map.clip_point(boundary, Bias::Left);
 3559
 3560                    (clipped, SelectionGoal::None)
 3561                });
 3562            });
 3563
 3564            let mut indent_edits = Vec::new();
 3565            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3566            for row in rows {
 3567                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3568                for (row, indent) in indents {
 3569                    if indent.len == 0 {
 3570                        continue;
 3571                    }
 3572
 3573                    let text = match indent.kind {
 3574                        IndentKind::Space => " ".repeat(indent.len as usize),
 3575                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3576                    };
 3577                    let point = Point::new(row.0, 0);
 3578                    indent_edits.push((point..point, text));
 3579                }
 3580            }
 3581            editor.edit(indent_edits, cx);
 3582        });
 3583    }
 3584
 3585    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3586        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3587            original_indent_columns: Vec::new(),
 3588        });
 3589        self.insert_with_autoindent_mode(text, autoindent, cx);
 3590    }
 3591
 3592    fn insert_with_autoindent_mode(
 3593        &mut self,
 3594        text: &str,
 3595        autoindent_mode: Option<AutoindentMode>,
 3596        cx: &mut ViewContext<Self>,
 3597    ) {
 3598        if self.read_only(cx) {
 3599            return;
 3600        }
 3601
 3602        let text: Arc<str> = text.into();
 3603        self.transact(cx, |this, cx| {
 3604            let old_selections = this.selections.all_adjusted(cx);
 3605            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3606                let anchors = {
 3607                    let snapshot = buffer.read(cx);
 3608                    old_selections
 3609                        .iter()
 3610                        .map(|s| {
 3611                            let anchor = snapshot.anchor_after(s.head());
 3612                            s.map(|_| anchor)
 3613                        })
 3614                        .collect::<Vec<_>>()
 3615                };
 3616                buffer.edit(
 3617                    old_selections
 3618                        .iter()
 3619                        .map(|s| (s.start..s.end, text.clone())),
 3620                    autoindent_mode,
 3621                    cx,
 3622                );
 3623                anchors
 3624            });
 3625
 3626            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3627                s.select_anchors(selection_anchors);
 3628            })
 3629        });
 3630    }
 3631
 3632    fn trigger_completion_on_input(
 3633        &mut self,
 3634        text: &str,
 3635        trigger_in_words: bool,
 3636        cx: &mut ViewContext<Self>,
 3637    ) {
 3638        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3639            self.show_completions(
 3640                &ShowCompletions {
 3641                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3642                },
 3643                cx,
 3644            );
 3645        } else {
 3646            self.hide_context_menu(cx);
 3647        }
 3648    }
 3649
 3650    fn is_completion_trigger(
 3651        &self,
 3652        text: &str,
 3653        trigger_in_words: bool,
 3654        cx: &mut ViewContext<Self>,
 3655    ) -> bool {
 3656        let position = self.selections.newest_anchor().head();
 3657        let multibuffer = self.buffer.read(cx);
 3658        let Some(buffer) = position
 3659            .buffer_id
 3660            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3661        else {
 3662            return false;
 3663        };
 3664
 3665        if let Some(completion_provider) = &self.completion_provider {
 3666            completion_provider.is_completion_trigger(
 3667                &buffer,
 3668                position.text_anchor,
 3669                text,
 3670                trigger_in_words,
 3671                cx,
 3672            )
 3673        } else {
 3674            false
 3675        }
 3676    }
 3677
 3678    /// If any empty selections is touching the start of its innermost containing autoclose
 3679    /// region, expand it to select the brackets.
 3680    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3681        let selections = self.selections.all::<usize>(cx);
 3682        let buffer = self.buffer.read(cx).read(cx);
 3683        let new_selections = self
 3684            .selections_with_autoclose_regions(selections, &buffer)
 3685            .map(|(mut selection, region)| {
 3686                if !selection.is_empty() {
 3687                    return selection;
 3688                }
 3689
 3690                if let Some(region) = region {
 3691                    let mut range = region.range.to_offset(&buffer);
 3692                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3693                        range.start -= region.pair.start.len();
 3694                        if buffer.contains_str_at(range.start, &region.pair.start)
 3695                            && buffer.contains_str_at(range.end, &region.pair.end)
 3696                        {
 3697                            range.end += region.pair.end.len();
 3698                            selection.start = range.start;
 3699                            selection.end = range.end;
 3700
 3701                            return selection;
 3702                        }
 3703                    }
 3704                }
 3705
 3706                let always_treat_brackets_as_autoclosed = buffer
 3707                    .settings_at(selection.start, cx)
 3708                    .always_treat_brackets_as_autoclosed;
 3709
 3710                if !always_treat_brackets_as_autoclosed {
 3711                    return selection;
 3712                }
 3713
 3714                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3715                    for (pair, enabled) in scope.brackets() {
 3716                        if !enabled || !pair.close {
 3717                            continue;
 3718                        }
 3719
 3720                        if buffer.contains_str_at(selection.start, &pair.end) {
 3721                            let pair_start_len = pair.start.len();
 3722                            if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
 3723                            {
 3724                                selection.start -= pair_start_len;
 3725                                selection.end += pair.end.len();
 3726
 3727                                return selection;
 3728                            }
 3729                        }
 3730                    }
 3731                }
 3732
 3733                selection
 3734            })
 3735            .collect();
 3736
 3737        drop(buffer);
 3738        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3739    }
 3740
 3741    /// Iterate the given selections, and for each one, find the smallest surrounding
 3742    /// autoclose region. This uses the ordering of the selections and the autoclose
 3743    /// regions to avoid repeated comparisons.
 3744    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3745        &'a self,
 3746        selections: impl IntoIterator<Item = Selection<D>>,
 3747        buffer: &'a MultiBufferSnapshot,
 3748    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3749        let mut i = 0;
 3750        let mut regions = self.autoclose_regions.as_slice();
 3751        selections.into_iter().map(move |selection| {
 3752            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3753
 3754            let mut enclosing = None;
 3755            while let Some(pair_state) = regions.get(i) {
 3756                if pair_state.range.end.to_offset(buffer) < range.start {
 3757                    regions = &regions[i + 1..];
 3758                    i = 0;
 3759                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3760                    break;
 3761                } else {
 3762                    if pair_state.selection_id == selection.id {
 3763                        enclosing = Some(pair_state);
 3764                    }
 3765                    i += 1;
 3766                }
 3767            }
 3768
 3769            (selection.clone(), enclosing)
 3770        })
 3771    }
 3772
 3773    /// Remove any autoclose regions that no longer contain their selection.
 3774    fn invalidate_autoclose_regions(
 3775        &mut self,
 3776        mut selections: &[Selection<Anchor>],
 3777        buffer: &MultiBufferSnapshot,
 3778    ) {
 3779        self.autoclose_regions.retain(|state| {
 3780            let mut i = 0;
 3781            while let Some(selection) = selections.get(i) {
 3782                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3783                    selections = &selections[1..];
 3784                    continue;
 3785                }
 3786                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3787                    break;
 3788                }
 3789                if selection.id == state.selection_id {
 3790                    return true;
 3791                } else {
 3792                    i += 1;
 3793                }
 3794            }
 3795            false
 3796        });
 3797    }
 3798
 3799    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3800        let offset = position.to_offset(buffer);
 3801        let (word_range, kind) = buffer.surrounding_word(offset);
 3802        if offset > word_range.start && kind == Some(CharKind::Word) {
 3803            Some(
 3804                buffer
 3805                    .text_for_range(word_range.start..offset)
 3806                    .collect::<String>(),
 3807            )
 3808        } else {
 3809            None
 3810        }
 3811    }
 3812
 3813    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3814        self.refresh_inlay_hints(
 3815            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3816            cx,
 3817        );
 3818    }
 3819
 3820    pub fn inlay_hints_enabled(&self) -> bool {
 3821        self.inlay_hint_cache.enabled
 3822    }
 3823
 3824    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3825        if self.project.is_none() || self.mode != EditorMode::Full {
 3826            return;
 3827        }
 3828
 3829        let reason_description = reason.description();
 3830        let ignore_debounce = matches!(
 3831            reason,
 3832            InlayHintRefreshReason::SettingsChange(_)
 3833                | InlayHintRefreshReason::Toggle(_)
 3834                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3835        );
 3836        let (invalidate_cache, required_languages) = match reason {
 3837            InlayHintRefreshReason::Toggle(enabled) => {
 3838                self.inlay_hint_cache.enabled = enabled;
 3839                if enabled {
 3840                    (InvalidationStrategy::RefreshRequested, None)
 3841                } else {
 3842                    self.inlay_hint_cache.clear();
 3843                    self.splice_inlays(
 3844                        self.visible_inlay_hints(cx)
 3845                            .iter()
 3846                            .map(|inlay| inlay.id)
 3847                            .collect(),
 3848                        Vec::new(),
 3849                        cx,
 3850                    );
 3851                    return;
 3852                }
 3853            }
 3854            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3855                match self.inlay_hint_cache.update_settings(
 3856                    &self.buffer,
 3857                    new_settings,
 3858                    self.visible_inlay_hints(cx),
 3859                    cx,
 3860                ) {
 3861                    ControlFlow::Break(Some(InlaySplice {
 3862                        to_remove,
 3863                        to_insert,
 3864                    })) => {
 3865                        self.splice_inlays(to_remove, to_insert, cx);
 3866                        return;
 3867                    }
 3868                    ControlFlow::Break(None) => return,
 3869                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3870                }
 3871            }
 3872            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3873                if let Some(InlaySplice {
 3874                    to_remove,
 3875                    to_insert,
 3876                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3877                {
 3878                    self.splice_inlays(to_remove, to_insert, cx);
 3879                }
 3880                return;
 3881            }
 3882            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3883            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3884                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3885            }
 3886            InlayHintRefreshReason::RefreshRequested => {
 3887                (InvalidationStrategy::RefreshRequested, None)
 3888            }
 3889        };
 3890
 3891        if let Some(InlaySplice {
 3892            to_remove,
 3893            to_insert,
 3894        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3895            reason_description,
 3896            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3897            invalidate_cache,
 3898            ignore_debounce,
 3899            cx,
 3900        ) {
 3901            self.splice_inlays(to_remove, to_insert, cx);
 3902        }
 3903    }
 3904
 3905    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3906        self.display_map
 3907            .read(cx)
 3908            .current_inlays()
 3909            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3910            .cloned()
 3911            .collect()
 3912    }
 3913
 3914    pub fn excerpts_for_inlay_hints_query(
 3915        &self,
 3916        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3917        cx: &mut ViewContext<Editor>,
 3918    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3919        let Some(project) = self.project.as_ref() else {
 3920            return HashMap::default();
 3921        };
 3922        let project = project.read(cx);
 3923        let multi_buffer = self.buffer().read(cx);
 3924        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3925        let multi_buffer_visible_start = self
 3926            .scroll_manager
 3927            .anchor()
 3928            .anchor
 3929            .to_point(&multi_buffer_snapshot);
 3930        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3931            multi_buffer_visible_start
 3932                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3933            Bias::Left,
 3934        );
 3935        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3936        multi_buffer
 3937            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3938            .into_iter()
 3939            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3940            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3941                let buffer = buffer_handle.read(cx);
 3942                let buffer_file = project::File::from_dyn(buffer.file())?;
 3943                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3944                let worktree_entry = buffer_worktree
 3945                    .read(cx)
 3946                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3947                if worktree_entry.is_ignored {
 3948                    return None;
 3949                }
 3950
 3951                let language = buffer.language()?;
 3952                if let Some(restrict_to_languages) = restrict_to_languages {
 3953                    if !restrict_to_languages.contains(language) {
 3954                        return None;
 3955                    }
 3956                }
 3957                Some((
 3958                    excerpt_id,
 3959                    (
 3960                        buffer_handle,
 3961                        buffer.version().clone(),
 3962                        excerpt_visible_range,
 3963                    ),
 3964                ))
 3965            })
 3966            .collect()
 3967    }
 3968
 3969    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3970        TextLayoutDetails {
 3971            text_system: cx.text_system().clone(),
 3972            editor_style: self.style.clone().unwrap(),
 3973            rem_size: cx.rem_size(),
 3974            scroll_anchor: self.scroll_manager.anchor(),
 3975            visible_rows: self.visible_line_count(),
 3976            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3977        }
 3978    }
 3979
 3980    fn splice_inlays(
 3981        &self,
 3982        to_remove: Vec<InlayId>,
 3983        to_insert: Vec<Inlay>,
 3984        cx: &mut ViewContext<Self>,
 3985    ) {
 3986        self.display_map.update(cx, |display_map, cx| {
 3987            display_map.splice_inlays(to_remove, to_insert, cx);
 3988        });
 3989        cx.notify();
 3990    }
 3991
 3992    fn trigger_on_type_formatting(
 3993        &self,
 3994        input: String,
 3995        cx: &mut ViewContext<Self>,
 3996    ) -> Option<Task<Result<()>>> {
 3997        if input.len() != 1 {
 3998            return None;
 3999        }
 4000
 4001        let project = self.project.as_ref()?;
 4002        let position = self.selections.newest_anchor().head();
 4003        let (buffer, buffer_position) = self
 4004            .buffer
 4005            .read(cx)
 4006            .text_anchor_for_position(position, cx)?;
 4007
 4008        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 4009        // hence we do LSP request & edit on host side only — add formats to host's history.
 4010        let push_to_lsp_host_history = true;
 4011        // If this is not the host, append its history with new edits.
 4012        let push_to_client_history = project.read(cx).is_remote();
 4013
 4014        let on_type_formatting = project.update(cx, |project, cx| {
 4015            project.on_type_format(
 4016                buffer.clone(),
 4017                buffer_position,
 4018                input,
 4019                push_to_lsp_host_history,
 4020                cx,
 4021            )
 4022        });
 4023        Some(cx.spawn(|editor, mut cx| async move {
 4024            if let Some(transaction) = on_type_formatting.await? {
 4025                if push_to_client_history {
 4026                    buffer
 4027                        .update(&mut cx, |buffer, _| {
 4028                            buffer.push_transaction(transaction, Instant::now());
 4029                        })
 4030                        .ok();
 4031                }
 4032                editor.update(&mut cx, |editor, cx| {
 4033                    editor.refresh_document_highlights(cx);
 4034                })?;
 4035            }
 4036            Ok(())
 4037        }))
 4038    }
 4039
 4040    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 4041        if self.pending_rename.is_some() {
 4042            return;
 4043        }
 4044
 4045        let Some(provider) = self.completion_provider.as_ref() else {
 4046            return;
 4047        };
 4048
 4049        let position = self.selections.newest_anchor().head();
 4050        let (buffer, buffer_position) =
 4051            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 4052                output
 4053            } else {
 4054                return;
 4055            };
 4056
 4057        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 4058        let is_followup_invoke = {
 4059            let context_menu_state = self.context_menu.read();
 4060            matches!(
 4061                context_menu_state.deref(),
 4062                Some(ContextMenu::Completions(_))
 4063            )
 4064        };
 4065        let trigger_kind = match (&options.trigger, is_followup_invoke) {
 4066            (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
 4067            (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(&trigger) => {
 4068                CompletionTriggerKind::TRIGGER_CHARACTER
 4069            }
 4070
 4071            _ => CompletionTriggerKind::INVOKED,
 4072        };
 4073        let completion_context = CompletionContext {
 4074            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 4075                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 4076                    Some(String::from(trigger))
 4077                } else {
 4078                    None
 4079                }
 4080            }),
 4081            trigger_kind,
 4082        };
 4083        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 4084
 4085        let id = post_inc(&mut self.next_completion_id);
 4086        let task = cx.spawn(|this, mut cx| {
 4087            async move {
 4088                this.update(&mut cx, |this, _| {
 4089                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 4090                })?;
 4091                let completions = completions.await.log_err();
 4092                let menu = if let Some(completions) = completions {
 4093                    let mut menu = CompletionsMenu {
 4094                        id,
 4095                        initial_position: position,
 4096                        match_candidates: completions
 4097                            .iter()
 4098                            .enumerate()
 4099                            .map(|(id, completion)| {
 4100                                StringMatchCandidate::new(
 4101                                    id,
 4102                                    completion.label.text[completion.label.filter_range.clone()]
 4103                                        .into(),
 4104                                )
 4105                            })
 4106                            .collect(),
 4107                        buffer: buffer.clone(),
 4108                        completions: Arc::new(RwLock::new(completions.into())),
 4109                        matches: Vec::new().into(),
 4110                        selected_item: 0,
 4111                        scroll_handle: UniformListScrollHandle::new(),
 4112                        selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
 4113                            DebouncedDelay::new(),
 4114                        )),
 4115                    };
 4116                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4117                        .await;
 4118
 4119                    if menu.matches.is_empty() {
 4120                        None
 4121                    } else {
 4122                        this.update(&mut cx, |editor, cx| {
 4123                            let completions = menu.completions.clone();
 4124                            let matches = menu.matches.clone();
 4125
 4126                            let delay_ms = EditorSettings::get_global(cx)
 4127                                .completion_documentation_secondary_query_debounce;
 4128                            let delay = Duration::from_millis(delay_ms);
 4129                            editor
 4130                                .completion_documentation_pre_resolve_debounce
 4131                                .fire_new(delay, cx, |editor, cx| {
 4132                                    CompletionsMenu::pre_resolve_completion_documentation(
 4133                                        buffer,
 4134                                        completions,
 4135                                        matches,
 4136                                        editor,
 4137                                        cx,
 4138                                    )
 4139                                });
 4140                        })
 4141                        .ok();
 4142                        Some(menu)
 4143                    }
 4144                } else {
 4145                    None
 4146                };
 4147
 4148                this.update(&mut cx, |this, cx| {
 4149                    let mut context_menu = this.context_menu.write();
 4150                    match context_menu.as_ref() {
 4151                        None => {}
 4152
 4153                        Some(ContextMenu::Completions(prev_menu)) => {
 4154                            if prev_menu.id > id {
 4155                                return;
 4156                            }
 4157                        }
 4158
 4159                        _ => return,
 4160                    }
 4161
 4162                    if this.focus_handle.is_focused(cx) && menu.is_some() {
 4163                        let menu = menu.unwrap();
 4164                        *context_menu = Some(ContextMenu::Completions(menu));
 4165                        drop(context_menu);
 4166                        this.discard_inline_completion(false, cx);
 4167                        cx.notify();
 4168                    } else if this.completion_tasks.len() <= 1 {
 4169                        // If there are no more completion tasks and the last menu was
 4170                        // empty, we should hide it. If it was already hidden, we should
 4171                        // also show the copilot completion when available.
 4172                        drop(context_menu);
 4173                        if this.hide_context_menu(cx).is_none() {
 4174                            this.update_visible_inline_completion(cx);
 4175                        }
 4176                    }
 4177                })?;
 4178
 4179                Ok::<_, anyhow::Error>(())
 4180            }
 4181            .log_err()
 4182        });
 4183
 4184        self.completion_tasks.push((id, task));
 4185    }
 4186
 4187    pub fn confirm_completion(
 4188        &mut self,
 4189        action: &ConfirmCompletion,
 4190        cx: &mut ViewContext<Self>,
 4191    ) -> Option<Task<Result<()>>> {
 4192        use language::ToOffset as _;
 4193
 4194        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 4195            menu
 4196        } else {
 4197            return None;
 4198        };
 4199
 4200        let mat = completions_menu
 4201            .matches
 4202            .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
 4203        let buffer_handle = completions_menu.buffer;
 4204        let completions = completions_menu.completions.read();
 4205        let completion = completions.get(mat.candidate_id)?;
 4206        cx.stop_propagation();
 4207
 4208        let snippet;
 4209        let text;
 4210
 4211        if completion.is_snippet() {
 4212            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4213            text = snippet.as_ref().unwrap().text.clone();
 4214        } else {
 4215            snippet = None;
 4216            text = completion.new_text.clone();
 4217        };
 4218        let selections = self.selections.all::<usize>(cx);
 4219        let buffer = buffer_handle.read(cx);
 4220        let old_range = completion.old_range.to_offset(buffer);
 4221        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4222
 4223        let newest_selection = self.selections.newest_anchor();
 4224        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4225            return None;
 4226        }
 4227
 4228        let lookbehind = newest_selection
 4229            .start
 4230            .text_anchor
 4231            .to_offset(buffer)
 4232            .saturating_sub(old_range.start);
 4233        let lookahead = old_range
 4234            .end
 4235            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4236        let mut common_prefix_len = old_text
 4237            .bytes()
 4238            .zip(text.bytes())
 4239            .take_while(|(a, b)| a == b)
 4240            .count();
 4241
 4242        let snapshot = self.buffer.read(cx).snapshot(cx);
 4243        let mut range_to_replace: Option<Range<isize>> = None;
 4244        let mut ranges = Vec::new();
 4245        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4246        for selection in &selections {
 4247            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4248                let start = selection.start.saturating_sub(lookbehind);
 4249                let end = selection.end + lookahead;
 4250                if selection.id == newest_selection.id {
 4251                    range_to_replace = Some(
 4252                        ((start + common_prefix_len) as isize - selection.start as isize)
 4253                            ..(end as isize - selection.start as isize),
 4254                    );
 4255                }
 4256                ranges.push(start + common_prefix_len..end);
 4257            } else {
 4258                common_prefix_len = 0;
 4259                ranges.clear();
 4260                ranges.extend(selections.iter().map(|s| {
 4261                    if s.id == newest_selection.id {
 4262                        range_to_replace = Some(
 4263                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4264                                - selection.start as isize
 4265                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4266                                    - selection.start as isize,
 4267                        );
 4268                        old_range.clone()
 4269                    } else {
 4270                        s.start..s.end
 4271                    }
 4272                }));
 4273                break;
 4274            }
 4275            if !self.linked_edit_ranges.is_empty() {
 4276                let start_anchor = snapshot.anchor_before(selection.head());
 4277                let end_anchor = snapshot.anchor_after(selection.tail());
 4278                if let Some(ranges) = self
 4279                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4280                {
 4281                    for (buffer, edits) in ranges {
 4282                        linked_edits.entry(buffer.clone()).or_default().extend(
 4283                            edits
 4284                                .into_iter()
 4285                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4286                        );
 4287                    }
 4288                }
 4289            }
 4290        }
 4291        let text = &text[common_prefix_len..];
 4292
 4293        cx.emit(EditorEvent::InputHandled {
 4294            utf16_range_to_replace: range_to_replace,
 4295            text: text.into(),
 4296        });
 4297
 4298        self.transact(cx, |this, cx| {
 4299            if let Some(mut snippet) = snippet {
 4300                snippet.text = text.to_string();
 4301                for tabstop in snippet.tabstops.iter_mut().flatten() {
 4302                    tabstop.start -= common_prefix_len as isize;
 4303                    tabstop.end -= common_prefix_len as isize;
 4304                }
 4305
 4306                this.insert_snippet(&ranges, snippet, cx).log_err();
 4307            } else {
 4308                this.buffer.update(cx, |buffer, cx| {
 4309                    buffer.edit(
 4310                        ranges.iter().map(|range| (range.clone(), text)),
 4311                        this.autoindent_mode.clone(),
 4312                        cx,
 4313                    );
 4314                });
 4315            }
 4316            for (buffer, edits) in linked_edits {
 4317                buffer.update(cx, |buffer, cx| {
 4318                    let snapshot = buffer.snapshot();
 4319                    let edits = edits
 4320                        .into_iter()
 4321                        .map(|(range, text)| {
 4322                            use text::ToPoint as TP;
 4323                            let end_point = TP::to_point(&range.end, &snapshot);
 4324                            let start_point = TP::to_point(&range.start, &snapshot);
 4325                            (start_point..end_point, text)
 4326                        })
 4327                        .sorted_by_key(|(range, _)| range.start)
 4328                        .collect::<Vec<_>>();
 4329                    buffer.edit(edits, None, cx);
 4330                })
 4331            }
 4332
 4333            this.refresh_inline_completion(true, cx);
 4334        });
 4335
 4336        if let Some(confirm) = completion.confirm.as_ref() {
 4337            (confirm)(cx);
 4338        }
 4339
 4340        if completion.show_new_completions_on_confirm {
 4341            self.show_completions(&ShowCompletions { trigger: None }, cx);
 4342        }
 4343
 4344        let provider = self.completion_provider.as_ref()?;
 4345        let apply_edits = provider.apply_additional_edits_for_completion(
 4346            buffer_handle,
 4347            completion.clone(),
 4348            true,
 4349            cx,
 4350        );
 4351
 4352        let editor_settings = EditorSettings::get_global(cx);
 4353        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4354            // After the code completion is finished, users often want to know what signatures are needed.
 4355            // so we should automatically call signature_help
 4356            self.show_signature_help(&ShowSignatureHelp, cx);
 4357        }
 4358
 4359        Some(cx.foreground_executor().spawn(async move {
 4360            apply_edits.await?;
 4361            Ok(())
 4362        }))
 4363    }
 4364
 4365    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 4366        let mut context_menu = self.context_menu.write();
 4367        if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4368            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4369                // Toggle if we're selecting the same one
 4370                *context_menu = None;
 4371                cx.notify();
 4372                return;
 4373            } else {
 4374                // Otherwise, clear it and start a new one
 4375                *context_menu = None;
 4376                cx.notify();
 4377            }
 4378        }
 4379        drop(context_menu);
 4380        let snapshot = self.snapshot(cx);
 4381        let deployed_from_indicator = action.deployed_from_indicator;
 4382        let mut task = self.code_actions_task.take();
 4383        let action = action.clone();
 4384        cx.spawn(|editor, mut cx| async move {
 4385            while let Some(prev_task) = task {
 4386                prev_task.await;
 4387                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4388            }
 4389
 4390            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4391                if editor.focus_handle.is_focused(cx) {
 4392                    let multibuffer_point = action
 4393                        .deployed_from_indicator
 4394                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4395                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4396                    let (buffer, buffer_row) = snapshot
 4397                        .buffer_snapshot
 4398                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4399                        .and_then(|(buffer_snapshot, range)| {
 4400                            editor
 4401                                .buffer
 4402                                .read(cx)
 4403                                .buffer(buffer_snapshot.remote_id())
 4404                                .map(|buffer| (buffer, range.start.row))
 4405                        })?;
 4406                    let (_, code_actions) = editor
 4407                        .available_code_actions
 4408                        .clone()
 4409                        .and_then(|(location, code_actions)| {
 4410                            let snapshot = location.buffer.read(cx).snapshot();
 4411                            let point_range = location.range.to_point(&snapshot);
 4412                            let point_range = point_range.start.row..=point_range.end.row;
 4413                            if point_range.contains(&buffer_row) {
 4414                                Some((location, code_actions))
 4415                            } else {
 4416                                None
 4417                            }
 4418                        })
 4419                        .unzip();
 4420                    let buffer_id = buffer.read(cx).remote_id();
 4421                    let tasks = editor
 4422                        .tasks
 4423                        .get(&(buffer_id, buffer_row))
 4424                        .map(|t| Arc::new(t.to_owned()));
 4425                    if tasks.is_none() && code_actions.is_none() {
 4426                        return None;
 4427                    }
 4428
 4429                    editor.completion_tasks.clear();
 4430                    editor.discard_inline_completion(false, cx);
 4431                    let task_context =
 4432                        tasks
 4433                            .as_ref()
 4434                            .zip(editor.project.clone())
 4435                            .map(|(tasks, project)| {
 4436                                let position = Point::new(buffer_row, tasks.column);
 4437                                let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4438                                let location = Location {
 4439                                    buffer: buffer.clone(),
 4440                                    range: range_start..range_start,
 4441                                };
 4442                                // Fill in the environmental variables from the tree-sitter captures
 4443                                let mut captured_task_variables = TaskVariables::default();
 4444                                for (capture_name, value) in tasks.extra_variables.clone() {
 4445                                    captured_task_variables.insert(
 4446                                        task::VariableName::Custom(capture_name.into()),
 4447                                        value.clone(),
 4448                                    );
 4449                                }
 4450                                project.update(cx, |project, cx| {
 4451                                    project.task_context_for_location(
 4452                                        captured_task_variables,
 4453                                        location,
 4454                                        cx,
 4455                                    )
 4456                                })
 4457                            });
 4458
 4459                    Some(cx.spawn(|editor, mut cx| async move {
 4460                        let task_context = match task_context {
 4461                            Some(task_context) => task_context.await,
 4462                            None => None,
 4463                        };
 4464                        let resolved_tasks =
 4465                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4466                                Arc::new(ResolvedTasks {
 4467                                    templates: tasks
 4468                                        .templates
 4469                                        .iter()
 4470                                        .filter_map(|(kind, template)| {
 4471                                            template
 4472                                                .resolve_task(&kind.to_id_base(), &task_context)
 4473                                                .map(|task| (kind.clone(), task))
 4474                                        })
 4475                                        .collect(),
 4476                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4477                                        multibuffer_point.row,
 4478                                        tasks.column,
 4479                                    )),
 4480                                })
 4481                            });
 4482                        let spawn_straight_away = resolved_tasks
 4483                            .as_ref()
 4484                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4485                            && code_actions
 4486                                .as_ref()
 4487                                .map_or(true, |actions| actions.is_empty());
 4488                        if let Some(task) = editor
 4489                            .update(&mut cx, |editor, cx| {
 4490                                *editor.context_menu.write() =
 4491                                    Some(ContextMenu::CodeActions(CodeActionsMenu {
 4492                                        buffer,
 4493                                        actions: CodeActionContents {
 4494                                            tasks: resolved_tasks,
 4495                                            actions: code_actions,
 4496                                        },
 4497                                        selected_item: Default::default(),
 4498                                        scroll_handle: UniformListScrollHandle::default(),
 4499                                        deployed_from_indicator,
 4500                                    }));
 4501                                if spawn_straight_away {
 4502                                    if let Some(task) = editor.confirm_code_action(
 4503                                        &ConfirmCodeAction { item_ix: Some(0) },
 4504                                        cx,
 4505                                    ) {
 4506                                        cx.notify();
 4507                                        return task;
 4508                                    }
 4509                                }
 4510                                cx.notify();
 4511                                Task::ready(Ok(()))
 4512                            })
 4513                            .ok()
 4514                        {
 4515                            task.await
 4516                        } else {
 4517                            Ok(())
 4518                        }
 4519                    }))
 4520                } else {
 4521                    Some(Task::ready(Ok(())))
 4522                }
 4523            })?;
 4524            if let Some(task) = spawned_test_task {
 4525                task.await?;
 4526            }
 4527
 4528            Ok::<_, anyhow::Error>(())
 4529        })
 4530        .detach_and_log_err(cx);
 4531    }
 4532
 4533    pub fn confirm_code_action(
 4534        &mut self,
 4535        action: &ConfirmCodeAction,
 4536        cx: &mut ViewContext<Self>,
 4537    ) -> Option<Task<Result<()>>> {
 4538        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4539            menu
 4540        } else {
 4541            return None;
 4542        };
 4543        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4544        let action = actions_menu.actions.get(action_ix)?;
 4545        let title = action.label();
 4546        let buffer = actions_menu.buffer;
 4547        let workspace = self.workspace()?;
 4548
 4549        match action {
 4550            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4551                workspace.update(cx, |workspace, cx| {
 4552                    workspace::tasks::schedule_resolved_task(
 4553                        workspace,
 4554                        task_source_kind,
 4555                        resolved_task,
 4556                        false,
 4557                        cx,
 4558                    );
 4559
 4560                    Some(Task::ready(Ok(())))
 4561                })
 4562            }
 4563            CodeActionsItem::CodeAction(action) => {
 4564                let apply_code_actions = workspace
 4565                    .read(cx)
 4566                    .project()
 4567                    .clone()
 4568                    .update(cx, |project, cx| {
 4569                        project.apply_code_action(buffer, action, true, cx)
 4570                    });
 4571                let workspace = workspace.downgrade();
 4572                Some(cx.spawn(|editor, cx| async move {
 4573                    let project_transaction = apply_code_actions.await?;
 4574                    Self::open_project_transaction(
 4575                        &editor,
 4576                        workspace,
 4577                        project_transaction,
 4578                        title,
 4579                        cx,
 4580                    )
 4581                    .await
 4582                }))
 4583            }
 4584        }
 4585    }
 4586
 4587    pub async fn open_project_transaction(
 4588        this: &WeakView<Editor>,
 4589        workspace: WeakView<Workspace>,
 4590        transaction: ProjectTransaction,
 4591        title: String,
 4592        mut cx: AsyncWindowContext,
 4593    ) -> Result<()> {
 4594        let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
 4595
 4596        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4597        cx.update(|cx| {
 4598            entries.sort_unstable_by_key(|(buffer, _)| {
 4599                buffer.read(cx).file().map(|f| f.path().clone())
 4600            });
 4601        })?;
 4602
 4603        // If the project transaction's edits are all contained within this editor, then
 4604        // avoid opening a new editor to display them.
 4605
 4606        if let Some((buffer, transaction)) = entries.first() {
 4607            if entries.len() == 1 {
 4608                let excerpt = this.update(&mut cx, |editor, cx| {
 4609                    editor
 4610                        .buffer()
 4611                        .read(cx)
 4612                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4613                })?;
 4614                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4615                    if excerpted_buffer == *buffer {
 4616                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4617                            let excerpt_range = excerpt_range.to_offset(buffer);
 4618                            buffer
 4619                                .edited_ranges_for_transaction::<usize>(transaction)
 4620                                .all(|range| {
 4621                                    excerpt_range.start <= range.start
 4622                                        && excerpt_range.end >= range.end
 4623                                })
 4624                        })?;
 4625
 4626                        if all_edits_within_excerpt {
 4627                            return Ok(());
 4628                        }
 4629                    }
 4630                }
 4631            }
 4632        } else {
 4633            return Ok(());
 4634        }
 4635
 4636        let mut ranges_to_highlight = Vec::new();
 4637        let excerpt_buffer = cx.new_model(|cx| {
 4638            let mut multibuffer =
 4639                MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
 4640            for (buffer_handle, transaction) in &entries {
 4641                let buffer = buffer_handle.read(cx);
 4642                ranges_to_highlight.extend(
 4643                    multibuffer.push_excerpts_with_context_lines(
 4644                        buffer_handle.clone(),
 4645                        buffer
 4646                            .edited_ranges_for_transaction::<usize>(transaction)
 4647                            .collect(),
 4648                        DEFAULT_MULTIBUFFER_CONTEXT,
 4649                        cx,
 4650                    ),
 4651                );
 4652            }
 4653            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4654            multibuffer
 4655        })?;
 4656
 4657        workspace.update(&mut cx, |workspace, cx| {
 4658            let project = workspace.project().clone();
 4659            let editor =
 4660                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4661            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4662            editor.update(cx, |editor, cx| {
 4663                editor.highlight_background::<Self>(
 4664                    &ranges_to_highlight,
 4665                    |theme| theme.editor_highlighted_line_background,
 4666                    cx,
 4667                );
 4668            });
 4669        })?;
 4670
 4671        Ok(())
 4672    }
 4673
 4674    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4675        let project = self.project.clone()?;
 4676        let buffer = self.buffer.read(cx);
 4677        let newest_selection = self.selections.newest_anchor().clone();
 4678        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4679        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4680        if start_buffer != end_buffer {
 4681            return None;
 4682        }
 4683
 4684        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4685            cx.background_executor()
 4686                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4687                .await;
 4688
 4689            let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
 4690                project.code_actions(&start_buffer, start..end, cx)
 4691            }) {
 4692                code_actions.await
 4693            } else {
 4694                Vec::new()
 4695            };
 4696
 4697            this.update(&mut cx, |this, cx| {
 4698                this.available_code_actions = if actions.is_empty() {
 4699                    None
 4700                } else {
 4701                    Some((
 4702                        Location {
 4703                            buffer: start_buffer,
 4704                            range: start..end,
 4705                        },
 4706                        actions.into(),
 4707                    ))
 4708                };
 4709                cx.notify();
 4710            })
 4711            .log_err();
 4712        }));
 4713        None
 4714    }
 4715
 4716    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4717        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4718            self.show_git_blame_inline = false;
 4719
 4720            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4721                cx.background_executor().timer(delay).await;
 4722
 4723                this.update(&mut cx, |this, cx| {
 4724                    this.show_git_blame_inline = true;
 4725                    cx.notify();
 4726                })
 4727                .log_err();
 4728            }));
 4729        }
 4730    }
 4731
 4732    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4733        if self.pending_rename.is_some() {
 4734            return None;
 4735        }
 4736
 4737        let project = self.project.clone()?;
 4738        let buffer = self.buffer.read(cx);
 4739        let newest_selection = self.selections.newest_anchor().clone();
 4740        let cursor_position = newest_selection.head();
 4741        let (cursor_buffer, cursor_buffer_position) =
 4742            buffer.text_anchor_for_position(cursor_position, cx)?;
 4743        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4744        if cursor_buffer != tail_buffer {
 4745            return None;
 4746        }
 4747
 4748        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4749            cx.background_executor()
 4750                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
 4751                .await;
 4752
 4753            let highlights = if let Some(highlights) = project
 4754                .update(&mut cx, |project, cx| {
 4755                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4756                })
 4757                .log_err()
 4758            {
 4759                highlights.await.log_err()
 4760            } else {
 4761                None
 4762            };
 4763
 4764            if let Some(highlights) = highlights {
 4765                this.update(&mut cx, |this, cx| {
 4766                    if this.pending_rename.is_some() {
 4767                        return;
 4768                    }
 4769
 4770                    let buffer_id = cursor_position.buffer_id;
 4771                    let buffer = this.buffer.read(cx);
 4772                    if !buffer
 4773                        .text_anchor_for_position(cursor_position, cx)
 4774                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4775                    {
 4776                        return;
 4777                    }
 4778
 4779                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4780                    let mut write_ranges = Vec::new();
 4781                    let mut read_ranges = Vec::new();
 4782                    for highlight in highlights {
 4783                        for (excerpt_id, excerpt_range) in
 4784                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4785                        {
 4786                            let start = highlight
 4787                                .range
 4788                                .start
 4789                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4790                            let end = highlight
 4791                                .range
 4792                                .end
 4793                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4794                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4795                                continue;
 4796                            }
 4797
 4798                            let range = Anchor {
 4799                                buffer_id,
 4800                                excerpt_id: excerpt_id,
 4801                                text_anchor: start,
 4802                            }..Anchor {
 4803                                buffer_id,
 4804                                excerpt_id,
 4805                                text_anchor: end,
 4806                            };
 4807                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4808                                write_ranges.push(range);
 4809                            } else {
 4810                                read_ranges.push(range);
 4811                            }
 4812                        }
 4813                    }
 4814
 4815                    this.highlight_background::<DocumentHighlightRead>(
 4816                        &read_ranges,
 4817                        |theme| theme.editor_document_highlight_read_background,
 4818                        cx,
 4819                    );
 4820                    this.highlight_background::<DocumentHighlightWrite>(
 4821                        &write_ranges,
 4822                        |theme| theme.editor_document_highlight_write_background,
 4823                        cx,
 4824                    );
 4825                    cx.notify();
 4826                })
 4827                .log_err();
 4828            }
 4829        }));
 4830        None
 4831    }
 4832
 4833    fn refresh_inline_completion(
 4834        &mut self,
 4835        debounce: bool,
 4836        cx: &mut ViewContext<Self>,
 4837    ) -> Option<()> {
 4838        let provider = self.inline_completion_provider()?;
 4839        let cursor = self.selections.newest_anchor().head();
 4840        let (buffer, cursor_buffer_position) =
 4841            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4842        if !self.show_inline_completions
 4843            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4844        {
 4845            self.discard_inline_completion(false, cx);
 4846            return None;
 4847        }
 4848
 4849        self.update_visible_inline_completion(cx);
 4850        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4851        Some(())
 4852    }
 4853
 4854    fn cycle_inline_completion(
 4855        &mut self,
 4856        direction: Direction,
 4857        cx: &mut ViewContext<Self>,
 4858    ) -> Option<()> {
 4859        let provider = self.inline_completion_provider()?;
 4860        let cursor = self.selections.newest_anchor().head();
 4861        let (buffer, cursor_buffer_position) =
 4862            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4863        if !self.show_inline_completions
 4864            || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
 4865        {
 4866            return None;
 4867        }
 4868
 4869        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4870        self.update_visible_inline_completion(cx);
 4871
 4872        Some(())
 4873    }
 4874
 4875    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4876        if !self.has_active_inline_completion(cx) {
 4877            self.refresh_inline_completion(false, cx);
 4878            return;
 4879        }
 4880
 4881        self.update_visible_inline_completion(cx);
 4882    }
 4883
 4884    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4885        self.show_cursor_names(cx);
 4886    }
 4887
 4888    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4889        self.show_cursor_names = true;
 4890        cx.notify();
 4891        cx.spawn(|this, mut cx| async move {
 4892            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4893            this.update(&mut cx, |this, cx| {
 4894                this.show_cursor_names = false;
 4895                cx.notify()
 4896            })
 4897            .ok()
 4898        })
 4899        .detach();
 4900    }
 4901
 4902    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4903        if self.has_active_inline_completion(cx) {
 4904            self.cycle_inline_completion(Direction::Next, cx);
 4905        } else {
 4906            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4907            if is_copilot_disabled {
 4908                cx.propagate();
 4909            }
 4910        }
 4911    }
 4912
 4913    pub fn previous_inline_completion(
 4914        &mut self,
 4915        _: &PreviousInlineCompletion,
 4916        cx: &mut ViewContext<Self>,
 4917    ) {
 4918        if self.has_active_inline_completion(cx) {
 4919            self.cycle_inline_completion(Direction::Prev, cx);
 4920        } else {
 4921            let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
 4922            if is_copilot_disabled {
 4923                cx.propagate();
 4924            }
 4925        }
 4926    }
 4927
 4928    pub fn accept_inline_completion(
 4929        &mut self,
 4930        _: &AcceptInlineCompletion,
 4931        cx: &mut ViewContext<Self>,
 4932    ) {
 4933        let Some((completion, delete_range)) = self.take_active_inline_completion(cx) else {
 4934            return;
 4935        };
 4936        if let Some(provider) = self.inline_completion_provider() {
 4937            provider.accept(cx);
 4938        }
 4939
 4940        cx.emit(EditorEvent::InputHandled {
 4941            utf16_range_to_replace: None,
 4942            text: completion.text.to_string().into(),
 4943        });
 4944
 4945        if let Some(range) = delete_range {
 4946            self.change_selections(None, cx, |s| s.select_ranges([range]))
 4947        }
 4948        self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
 4949        self.refresh_inline_completion(true, cx);
 4950        cx.notify();
 4951    }
 4952
 4953    pub fn accept_partial_inline_completion(
 4954        &mut self,
 4955        _: &AcceptPartialInlineCompletion,
 4956        cx: &mut ViewContext<Self>,
 4957    ) {
 4958        if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
 4959            if let Some((completion, delete_range)) = self.take_active_inline_completion(cx) {
 4960                let mut partial_completion = completion
 4961                    .text
 4962                    .chars()
 4963                    .by_ref()
 4964                    .take_while(|c| c.is_alphabetic())
 4965                    .collect::<String>();
 4966                if partial_completion.is_empty() {
 4967                    partial_completion = completion
 4968                        .text
 4969                        .chars()
 4970                        .by_ref()
 4971                        .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4972                        .collect::<String>();
 4973                }
 4974
 4975                cx.emit(EditorEvent::InputHandled {
 4976                    utf16_range_to_replace: None,
 4977                    text: partial_completion.clone().into(),
 4978                });
 4979
 4980                if let Some(range) = delete_range {
 4981                    self.change_selections(None, cx, |s| s.select_ranges([range]))
 4982                }
 4983                self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4984
 4985                self.refresh_inline_completion(true, cx);
 4986                cx.notify();
 4987            }
 4988        }
 4989    }
 4990
 4991    fn discard_inline_completion(
 4992        &mut self,
 4993        should_report_inline_completion_event: bool,
 4994        cx: &mut ViewContext<Self>,
 4995    ) -> bool {
 4996        if let Some(provider) = self.inline_completion_provider() {
 4997            provider.discard(should_report_inline_completion_event, cx);
 4998        }
 4999
 5000        self.take_active_inline_completion(cx).is_some()
 5001    }
 5002
 5003    pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
 5004        if let Some(completion) = self.active_inline_completion.as_ref() {
 5005            let buffer = self.buffer.read(cx).read(cx);
 5006            completion.0.position.is_valid(&buffer)
 5007        } else {
 5008            false
 5009        }
 5010    }
 5011
 5012    fn take_active_inline_completion(
 5013        &mut self,
 5014        cx: &mut ViewContext<Self>,
 5015    ) -> Option<(Inlay, Option<Range<Anchor>>)> {
 5016        let completion = self.active_inline_completion.take()?;
 5017        self.display_map.update(cx, |map, cx| {
 5018            map.splice_inlays(vec![completion.0.id], Default::default(), cx);
 5019        });
 5020        let buffer = self.buffer.read(cx).read(cx);
 5021
 5022        if completion.0.position.is_valid(&buffer) {
 5023            Some(completion)
 5024        } else {
 5025            None
 5026        }
 5027    }
 5028
 5029    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 5030        let selection = self.selections.newest_anchor();
 5031        let cursor = selection.head();
 5032
 5033        let excerpt_id = cursor.excerpt_id;
 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, text_anchor_range)) =
 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.0.id);
 5050                        }
 5051
 5052                        let completion_inlay =
 5053                            Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
 5054
 5055                        let multibuffer_anchor_range = text_anchor_range.and_then(|range| {
 5056                            let snapshot = self.buffer.read(cx).snapshot(cx);
 5057                            Some(
 5058                                snapshot.anchor_in_excerpt(excerpt_id, range.start)?
 5059                                    ..snapshot.anchor_in_excerpt(excerpt_id, range.end)?,
 5060                            )
 5061                        });
 5062                        self.active_inline_completion =
 5063                            Some((completion_inlay.clone(), multibuffer_anchor_range));
 5064
 5065                        self.display_map.update(cx, move |map, cx| {
 5066                            map.splice_inlays(to_remove, vec![completion_inlay], cx)
 5067                        });
 5068                        cx.notify();
 5069                        return;
 5070                    }
 5071                }
 5072            }
 5073        }
 5074
 5075        self.discard_inline_completion(false, cx);
 5076    }
 5077
 5078    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5079        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5080    }
 5081
 5082    fn render_code_actions_indicator(
 5083        &self,
 5084        _style: &EditorStyle,
 5085        row: DisplayRow,
 5086        is_active: bool,
 5087        cx: &mut ViewContext<Self>,
 5088    ) -> Option<IconButton> {
 5089        if self.available_code_actions.is_some() {
 5090            Some(
 5091                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5092                    .shape(ui::IconButtonShape::Square)
 5093                    .icon_size(IconSize::XSmall)
 5094                    .icon_color(Color::Muted)
 5095                    .selected(is_active)
 5096                    .on_click(cx.listener(move |editor, _e, cx| {
 5097                        editor.focus(cx);
 5098                        editor.toggle_code_actions(
 5099                            &ToggleCodeActions {
 5100                                deployed_from_indicator: Some(row),
 5101                            },
 5102                            cx,
 5103                        );
 5104                    })),
 5105            )
 5106        } else {
 5107            None
 5108        }
 5109    }
 5110
 5111    fn clear_tasks(&mut self) {
 5112        self.tasks.clear()
 5113    }
 5114
 5115    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5116        if let Some(_) = self.tasks.insert(key, value) {
 5117            // This case should hopefully be rare, but just in case...
 5118            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5119        }
 5120    }
 5121
 5122    fn render_run_indicator(
 5123        &self,
 5124        _style: &EditorStyle,
 5125        is_active: bool,
 5126        row: DisplayRow,
 5127        cx: &mut ViewContext<Self>,
 5128    ) -> IconButton {
 5129        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5130            .shape(ui::IconButtonShape::Square)
 5131            .icon_size(IconSize::XSmall)
 5132            .icon_color(Color::Muted)
 5133            .selected(is_active)
 5134            .on_click(cx.listener(move |editor, _e, cx| {
 5135                editor.focus(cx);
 5136                editor.toggle_code_actions(
 5137                    &ToggleCodeActions {
 5138                        deployed_from_indicator: Some(row),
 5139                    },
 5140                    cx,
 5141                );
 5142            }))
 5143    }
 5144
 5145    fn close_hunk_diff_button(
 5146        &self,
 5147        hunk: HoveredHunk,
 5148        row: DisplayRow,
 5149        cx: &mut ViewContext<Self>,
 5150    ) -> IconButton {
 5151        IconButton::new(
 5152            ("close_hunk_diff_indicator", row.0 as usize),
 5153            ui::IconName::Close,
 5154        )
 5155        .shape(ui::IconButtonShape::Square)
 5156        .icon_size(IconSize::XSmall)
 5157        .icon_color(Color::Muted)
 5158        .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
 5159        .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
 5160    }
 5161
 5162    pub fn context_menu_visible(&self) -> bool {
 5163        self.context_menu
 5164            .read()
 5165            .as_ref()
 5166            .map_or(false, |menu| menu.visible())
 5167    }
 5168
 5169    fn render_context_menu(
 5170        &self,
 5171        cursor_position: DisplayPoint,
 5172        style: &EditorStyle,
 5173        max_height: Pixels,
 5174        cx: &mut ViewContext<Editor>,
 5175    ) -> Option<(ContextMenuOrigin, AnyElement)> {
 5176        self.context_menu.read().as_ref().map(|menu| {
 5177            menu.render(
 5178                cursor_position,
 5179                style,
 5180                max_height,
 5181                self.workspace.as_ref().map(|(w, _)| w.clone()),
 5182                cx,
 5183            )
 5184        })
 5185    }
 5186
 5187    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
 5188        cx.notify();
 5189        self.completion_tasks.clear();
 5190        let context_menu = self.context_menu.write().take();
 5191        if context_menu.is_some() {
 5192            self.update_visible_inline_completion(cx);
 5193        }
 5194        context_menu
 5195    }
 5196
 5197    pub fn insert_snippet(
 5198        &mut self,
 5199        insertion_ranges: &[Range<usize>],
 5200        snippet: Snippet,
 5201        cx: &mut ViewContext<Self>,
 5202    ) -> Result<()> {
 5203        struct Tabstop<T> {
 5204            is_end_tabstop: bool,
 5205            ranges: Vec<Range<T>>,
 5206        }
 5207
 5208        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5209            let snippet_text: Arc<str> = snippet.text.clone().into();
 5210            buffer.edit(
 5211                insertion_ranges
 5212                    .iter()
 5213                    .cloned()
 5214                    .map(|range| (range, snippet_text.clone())),
 5215                Some(AutoindentMode::EachLine),
 5216                cx,
 5217            );
 5218
 5219            let snapshot = &*buffer.read(cx);
 5220            let snippet = &snippet;
 5221            snippet
 5222                .tabstops
 5223                .iter()
 5224                .map(|tabstop| {
 5225                    let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
 5226                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5227                    });
 5228                    let mut tabstop_ranges = tabstop
 5229                        .iter()
 5230                        .flat_map(|tabstop_range| {
 5231                            let mut delta = 0_isize;
 5232                            insertion_ranges.iter().map(move |insertion_range| {
 5233                                let insertion_start = insertion_range.start as isize + delta;
 5234                                delta +=
 5235                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5236
 5237                                let start = ((insertion_start + tabstop_range.start) as usize)
 5238                                    .min(snapshot.len());
 5239                                let end = ((insertion_start + tabstop_range.end) as usize)
 5240                                    .min(snapshot.len());
 5241                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5242                            })
 5243                        })
 5244                        .collect::<Vec<_>>();
 5245                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5246
 5247                    Tabstop {
 5248                        is_end_tabstop,
 5249                        ranges: tabstop_ranges,
 5250                    }
 5251                })
 5252                .collect::<Vec<_>>()
 5253        });
 5254        if let Some(tabstop) = tabstops.first() {
 5255            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5256                s.select_ranges(tabstop.ranges.iter().cloned());
 5257            });
 5258
 5259            // If we're already at the last tabstop and it's at the end of the snippet,
 5260            // we're done, we don't need to keep the state around.
 5261            if !tabstop.is_end_tabstop {
 5262                let ranges = tabstops
 5263                    .into_iter()
 5264                    .map(|tabstop| tabstop.ranges)
 5265                    .collect::<Vec<_>>();
 5266                self.snippet_stack.push(SnippetState {
 5267                    active_index: 0,
 5268                    ranges,
 5269                });
 5270            }
 5271
 5272            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5273            if self.autoclose_regions.is_empty() {
 5274                let snapshot = self.buffer.read(cx).snapshot(cx);
 5275                for selection in &mut self.selections.all::<Point>(cx) {
 5276                    let selection_head = selection.head();
 5277                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5278                        continue;
 5279                    };
 5280
 5281                    let mut bracket_pair = None;
 5282                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5283                    let prev_chars = snapshot
 5284                        .reversed_chars_at(selection_head)
 5285                        .collect::<String>();
 5286                    for (pair, enabled) in scope.brackets() {
 5287                        if enabled
 5288                            && pair.close
 5289                            && prev_chars.starts_with(pair.start.as_str())
 5290                            && next_chars.starts_with(pair.end.as_str())
 5291                        {
 5292                            bracket_pair = Some(pair.clone());
 5293                            break;
 5294                        }
 5295                    }
 5296                    if let Some(pair) = bracket_pair {
 5297                        let start = snapshot.anchor_after(selection_head);
 5298                        let end = snapshot.anchor_after(selection_head);
 5299                        self.autoclose_regions.push(AutocloseRegion {
 5300                            selection_id: selection.id,
 5301                            range: start..end,
 5302                            pair,
 5303                        });
 5304                    }
 5305                }
 5306            }
 5307        }
 5308        Ok(())
 5309    }
 5310
 5311    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5312        self.move_to_snippet_tabstop(Bias::Right, cx)
 5313    }
 5314
 5315    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5316        self.move_to_snippet_tabstop(Bias::Left, cx)
 5317    }
 5318
 5319    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5320        if let Some(mut snippet) = self.snippet_stack.pop() {
 5321            match bias {
 5322                Bias::Left => {
 5323                    if snippet.active_index > 0 {
 5324                        snippet.active_index -= 1;
 5325                    } else {
 5326                        self.snippet_stack.push(snippet);
 5327                        return false;
 5328                    }
 5329                }
 5330                Bias::Right => {
 5331                    if snippet.active_index + 1 < snippet.ranges.len() {
 5332                        snippet.active_index += 1;
 5333                    } else {
 5334                        self.snippet_stack.push(snippet);
 5335                        return false;
 5336                    }
 5337                }
 5338            }
 5339            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5340                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5341                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5342                });
 5343                // If snippet state is not at the last tabstop, push it back on the stack
 5344                if snippet.active_index + 1 < snippet.ranges.len() {
 5345                    self.snippet_stack.push(snippet);
 5346                }
 5347                return true;
 5348            }
 5349        }
 5350
 5351        false
 5352    }
 5353
 5354    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5355        self.transact(cx, |this, cx| {
 5356            this.select_all(&SelectAll, cx);
 5357            this.insert("", cx);
 5358        });
 5359    }
 5360
 5361    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5362        self.transact(cx, |this, cx| {
 5363            this.select_autoclose_pair(cx);
 5364            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5365            if !this.linked_edit_ranges.is_empty() {
 5366                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5367                let snapshot = this.buffer.read(cx).snapshot(cx);
 5368
 5369                for selection in selections.iter() {
 5370                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5371                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5372                    if selection_start.buffer_id != selection_end.buffer_id {
 5373                        continue;
 5374                    }
 5375                    if let Some(ranges) =
 5376                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5377                    {
 5378                        for (buffer, entries) in ranges {
 5379                            linked_ranges.entry(buffer).or_default().extend(entries);
 5380                        }
 5381                    }
 5382                }
 5383            }
 5384
 5385            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5386            if !this.selections.line_mode {
 5387                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5388                for selection in &mut selections {
 5389                    if selection.is_empty() {
 5390                        let old_head = selection.head();
 5391                        let mut new_head =
 5392                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5393                                .to_point(&display_map);
 5394                        if let Some((buffer, line_buffer_range)) = display_map
 5395                            .buffer_snapshot
 5396                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5397                        {
 5398                            let indent_size =
 5399                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5400                            let indent_len = match indent_size.kind {
 5401                                IndentKind::Space => {
 5402                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5403                                }
 5404                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5405                            };
 5406                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5407                                let indent_len = indent_len.get();
 5408                                new_head = cmp::min(
 5409                                    new_head,
 5410                                    MultiBufferPoint::new(
 5411                                        old_head.row,
 5412                                        ((old_head.column - 1) / indent_len) * indent_len,
 5413                                    ),
 5414                                );
 5415                            }
 5416                        }
 5417
 5418                        selection.set_head(new_head, SelectionGoal::None);
 5419                    }
 5420                }
 5421            }
 5422
 5423            this.signature_help_state.set_backspace_pressed(true);
 5424            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5425            this.insert("", cx);
 5426            let empty_str: Arc<str> = Arc::from("");
 5427            for (buffer, edits) in linked_ranges {
 5428                let snapshot = buffer.read(cx).snapshot();
 5429                use text::ToPoint as TP;
 5430
 5431                let edits = edits
 5432                    .into_iter()
 5433                    .map(|range| {
 5434                        let end_point = TP::to_point(&range.end, &snapshot);
 5435                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5436
 5437                        if end_point == start_point {
 5438                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5439                                .saturating_sub(1);
 5440                            start_point = TP::to_point(&offset, &snapshot);
 5441                        };
 5442
 5443                        (start_point..end_point, empty_str.clone())
 5444                    })
 5445                    .sorted_by_key(|(range, _)| range.start)
 5446                    .collect::<Vec<_>>();
 5447                buffer.update(cx, |this, cx| {
 5448                    this.edit(edits, None, cx);
 5449                })
 5450            }
 5451            this.refresh_inline_completion(true, cx);
 5452            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5453        });
 5454    }
 5455
 5456    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5457        self.transact(cx, |this, cx| {
 5458            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5459                let line_mode = s.line_mode;
 5460                s.move_with(|map, selection| {
 5461                    if selection.is_empty() && !line_mode {
 5462                        let cursor = movement::right(map, selection.head());
 5463                        selection.end = cursor;
 5464                        selection.reversed = true;
 5465                        selection.goal = SelectionGoal::None;
 5466                    }
 5467                })
 5468            });
 5469            this.insert("", cx);
 5470            this.refresh_inline_completion(true, cx);
 5471        });
 5472    }
 5473
 5474    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5475        if self.move_to_prev_snippet_tabstop(cx) {
 5476            return;
 5477        }
 5478
 5479        self.outdent(&Outdent, cx);
 5480    }
 5481
 5482    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5483        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5484            return;
 5485        }
 5486
 5487        let mut selections = self.selections.all_adjusted(cx);
 5488        let buffer = self.buffer.read(cx);
 5489        let snapshot = buffer.snapshot(cx);
 5490        let rows_iter = selections.iter().map(|s| s.head().row);
 5491        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5492
 5493        let mut edits = Vec::new();
 5494        let mut prev_edited_row = 0;
 5495        let mut row_delta = 0;
 5496        for selection in &mut selections {
 5497            if selection.start.row != prev_edited_row {
 5498                row_delta = 0;
 5499            }
 5500            prev_edited_row = selection.end.row;
 5501
 5502            // If the selection is non-empty, then increase the indentation of the selected lines.
 5503            if !selection.is_empty() {
 5504                row_delta =
 5505                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5506                continue;
 5507            }
 5508
 5509            // If the selection is empty and the cursor is in the leading whitespace before the
 5510            // suggested indentation, then auto-indent the line.
 5511            let cursor = selection.head();
 5512            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5513            if let Some(suggested_indent) =
 5514                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5515            {
 5516                if cursor.column < suggested_indent.len
 5517                    && cursor.column <= current_indent.len
 5518                    && current_indent.len <= suggested_indent.len
 5519                {
 5520                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5521                    selection.end = selection.start;
 5522                    if row_delta == 0 {
 5523                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5524                            cursor.row,
 5525                            current_indent,
 5526                            suggested_indent,
 5527                        ));
 5528                        row_delta = suggested_indent.len - current_indent.len;
 5529                    }
 5530                    continue;
 5531                }
 5532            }
 5533
 5534            // Otherwise, insert a hard or soft tab.
 5535            let settings = buffer.settings_at(cursor, cx);
 5536            let tab_size = if settings.hard_tabs {
 5537                IndentSize::tab()
 5538            } else {
 5539                let tab_size = settings.tab_size.get();
 5540                let char_column = snapshot
 5541                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5542                    .flat_map(str::chars)
 5543                    .count()
 5544                    + row_delta as usize;
 5545                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5546                IndentSize::spaces(chars_to_next_tab_stop)
 5547            };
 5548            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5549            selection.end = selection.start;
 5550            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5551            row_delta += tab_size.len;
 5552        }
 5553
 5554        self.transact(cx, |this, cx| {
 5555            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5556            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5557            this.refresh_inline_completion(true, cx);
 5558        });
 5559    }
 5560
 5561    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5562        if self.read_only(cx) {
 5563            return;
 5564        }
 5565        let mut selections = self.selections.all::<Point>(cx);
 5566        let mut prev_edited_row = 0;
 5567        let mut row_delta = 0;
 5568        let mut edits = Vec::new();
 5569        let buffer = self.buffer.read(cx);
 5570        let snapshot = buffer.snapshot(cx);
 5571        for selection in &mut selections {
 5572            if selection.start.row != prev_edited_row {
 5573                row_delta = 0;
 5574            }
 5575            prev_edited_row = selection.end.row;
 5576
 5577            row_delta =
 5578                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5579        }
 5580
 5581        self.transact(cx, |this, cx| {
 5582            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5583            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5584        });
 5585    }
 5586
 5587    fn indent_selection(
 5588        buffer: &MultiBuffer,
 5589        snapshot: &MultiBufferSnapshot,
 5590        selection: &mut Selection<Point>,
 5591        edits: &mut Vec<(Range<Point>, String)>,
 5592        delta_for_start_row: u32,
 5593        cx: &AppContext,
 5594    ) -> u32 {
 5595        let settings = buffer.settings_at(selection.start, cx);
 5596        let tab_size = settings.tab_size.get();
 5597        let indent_kind = if settings.hard_tabs {
 5598            IndentKind::Tab
 5599        } else {
 5600            IndentKind::Space
 5601        };
 5602        let mut start_row = selection.start.row;
 5603        let mut end_row = selection.end.row + 1;
 5604
 5605        // If a selection ends at the beginning of a line, don't indent
 5606        // that last line.
 5607        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5608            end_row -= 1;
 5609        }
 5610
 5611        // Avoid re-indenting a row that has already been indented by a
 5612        // previous selection, but still update this selection's column
 5613        // to reflect that indentation.
 5614        if delta_for_start_row > 0 {
 5615            start_row += 1;
 5616            selection.start.column += delta_for_start_row;
 5617            if selection.end.row == selection.start.row {
 5618                selection.end.column += delta_for_start_row;
 5619            }
 5620        }
 5621
 5622        let mut delta_for_end_row = 0;
 5623        let has_multiple_rows = start_row + 1 != end_row;
 5624        for row in start_row..end_row {
 5625            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5626            let indent_delta = match (current_indent.kind, indent_kind) {
 5627                (IndentKind::Space, IndentKind::Space) => {
 5628                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5629                    IndentSize::spaces(columns_to_next_tab_stop)
 5630                }
 5631                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5632                (_, IndentKind::Tab) => IndentSize::tab(),
 5633            };
 5634
 5635            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5636                0
 5637            } else {
 5638                selection.start.column
 5639            };
 5640            let row_start = Point::new(row, start);
 5641            edits.push((
 5642                row_start..row_start,
 5643                indent_delta.chars().collect::<String>(),
 5644            ));
 5645
 5646            // Update this selection's endpoints to reflect the indentation.
 5647            if row == selection.start.row {
 5648                selection.start.column += indent_delta.len;
 5649            }
 5650            if row == selection.end.row {
 5651                selection.end.column += indent_delta.len;
 5652                delta_for_end_row = indent_delta.len;
 5653            }
 5654        }
 5655
 5656        if selection.start.row == selection.end.row {
 5657            delta_for_start_row + delta_for_end_row
 5658        } else {
 5659            delta_for_end_row
 5660        }
 5661    }
 5662
 5663    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5664        if self.read_only(cx) {
 5665            return;
 5666        }
 5667        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5668        let selections = self.selections.all::<Point>(cx);
 5669        let mut deletion_ranges = Vec::new();
 5670        let mut last_outdent = None;
 5671        {
 5672            let buffer = self.buffer.read(cx);
 5673            let snapshot = buffer.snapshot(cx);
 5674            for selection in &selections {
 5675                let settings = buffer.settings_at(selection.start, cx);
 5676                let tab_size = settings.tab_size.get();
 5677                let mut rows = selection.spanned_rows(false, &display_map);
 5678
 5679                // Avoid re-outdenting a row that has already been outdented by a
 5680                // previous selection.
 5681                if let Some(last_row) = last_outdent {
 5682                    if last_row == rows.start {
 5683                        rows.start = rows.start.next_row();
 5684                    }
 5685                }
 5686                let has_multiple_rows = rows.len() > 1;
 5687                for row in rows.iter_rows() {
 5688                    let indent_size = snapshot.indent_size_for_line(row);
 5689                    if indent_size.len > 0 {
 5690                        let deletion_len = match indent_size.kind {
 5691                            IndentKind::Space => {
 5692                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5693                                if columns_to_prev_tab_stop == 0 {
 5694                                    tab_size
 5695                                } else {
 5696                                    columns_to_prev_tab_stop
 5697                                }
 5698                            }
 5699                            IndentKind::Tab => 1,
 5700                        };
 5701                        let start = if has_multiple_rows
 5702                            || deletion_len > selection.start.column
 5703                            || indent_size.len < selection.start.column
 5704                        {
 5705                            0
 5706                        } else {
 5707                            selection.start.column - deletion_len
 5708                        };
 5709                        deletion_ranges.push(
 5710                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5711                        );
 5712                        last_outdent = Some(row);
 5713                    }
 5714                }
 5715            }
 5716        }
 5717
 5718        self.transact(cx, |this, cx| {
 5719            this.buffer.update(cx, |buffer, cx| {
 5720                let empty_str: Arc<str> = Arc::default();
 5721                buffer.edit(
 5722                    deletion_ranges
 5723                        .into_iter()
 5724                        .map(|range| (range, empty_str.clone())),
 5725                    None,
 5726                    cx,
 5727                );
 5728            });
 5729            let selections = this.selections.all::<usize>(cx);
 5730            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5731        });
 5732    }
 5733
 5734    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5735        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5736        let selections = self.selections.all::<Point>(cx);
 5737
 5738        let mut new_cursors = Vec::new();
 5739        let mut edit_ranges = Vec::new();
 5740        let mut selections = selections.iter().peekable();
 5741        while let Some(selection) = selections.next() {
 5742            let mut rows = selection.spanned_rows(false, &display_map);
 5743            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5744
 5745            // Accumulate contiguous regions of rows that we want to delete.
 5746            while let Some(next_selection) = selections.peek() {
 5747                let next_rows = next_selection.spanned_rows(false, &display_map);
 5748                if next_rows.start <= rows.end {
 5749                    rows.end = next_rows.end;
 5750                    selections.next().unwrap();
 5751                } else {
 5752                    break;
 5753                }
 5754            }
 5755
 5756            let buffer = &display_map.buffer_snapshot;
 5757            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5758            let edit_end;
 5759            let cursor_buffer_row;
 5760            if buffer.max_point().row >= rows.end.0 {
 5761                // If there's a line after the range, delete the \n from the end of the row range
 5762                // and position the cursor on the next line.
 5763                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5764                cursor_buffer_row = rows.end;
 5765            } else {
 5766                // If there isn't a line after the range, delete the \n from the line before the
 5767                // start of the row range and position the cursor there.
 5768                edit_start = edit_start.saturating_sub(1);
 5769                edit_end = buffer.len();
 5770                cursor_buffer_row = rows.start.previous_row();
 5771            }
 5772
 5773            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5774            *cursor.column_mut() =
 5775                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5776
 5777            new_cursors.push((
 5778                selection.id,
 5779                buffer.anchor_after(cursor.to_point(&display_map)),
 5780            ));
 5781            edit_ranges.push(edit_start..edit_end);
 5782        }
 5783
 5784        self.transact(cx, |this, cx| {
 5785            let buffer = this.buffer.update(cx, |buffer, cx| {
 5786                let empty_str: Arc<str> = Arc::default();
 5787                buffer.edit(
 5788                    edit_ranges
 5789                        .into_iter()
 5790                        .map(|range| (range, empty_str.clone())),
 5791                    None,
 5792                    cx,
 5793                );
 5794                buffer.snapshot(cx)
 5795            });
 5796            let new_selections = new_cursors
 5797                .into_iter()
 5798                .map(|(id, cursor)| {
 5799                    let cursor = cursor.to_point(&buffer);
 5800                    Selection {
 5801                        id,
 5802                        start: cursor,
 5803                        end: cursor,
 5804                        reversed: false,
 5805                        goal: SelectionGoal::None,
 5806                    }
 5807                })
 5808                .collect();
 5809
 5810            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5811                s.select(new_selections);
 5812            });
 5813        });
 5814    }
 5815
 5816    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5817        if self.read_only(cx) {
 5818            return;
 5819        }
 5820        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5821        for selection in self.selections.all::<Point>(cx) {
 5822            let start = MultiBufferRow(selection.start.row);
 5823            let end = if selection.start.row == selection.end.row {
 5824                MultiBufferRow(selection.start.row + 1)
 5825            } else {
 5826                MultiBufferRow(selection.end.row)
 5827            };
 5828
 5829            if let Some(last_row_range) = row_ranges.last_mut() {
 5830                if start <= last_row_range.end {
 5831                    last_row_range.end = end;
 5832                    continue;
 5833                }
 5834            }
 5835            row_ranges.push(start..end);
 5836        }
 5837
 5838        let snapshot = self.buffer.read(cx).snapshot(cx);
 5839        let mut cursor_positions = Vec::new();
 5840        for row_range in &row_ranges {
 5841            let anchor = snapshot.anchor_before(Point::new(
 5842                row_range.end.previous_row().0,
 5843                snapshot.line_len(row_range.end.previous_row()),
 5844            ));
 5845            cursor_positions.push(anchor..anchor);
 5846        }
 5847
 5848        self.transact(cx, |this, cx| {
 5849            for row_range in row_ranges.into_iter().rev() {
 5850                for row in row_range.iter_rows().rev() {
 5851                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5852                    let next_line_row = row.next_row();
 5853                    let indent = snapshot.indent_size_for_line(next_line_row);
 5854                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5855
 5856                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5857                        " "
 5858                    } else {
 5859                        ""
 5860                    };
 5861
 5862                    this.buffer.update(cx, |buffer, cx| {
 5863                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5864                    });
 5865                }
 5866            }
 5867
 5868            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5869                s.select_anchor_ranges(cursor_positions)
 5870            });
 5871        });
 5872    }
 5873
 5874    pub fn sort_lines_case_sensitive(
 5875        &mut self,
 5876        _: &SortLinesCaseSensitive,
 5877        cx: &mut ViewContext<Self>,
 5878    ) {
 5879        self.manipulate_lines(cx, |lines| lines.sort())
 5880    }
 5881
 5882    pub fn sort_lines_case_insensitive(
 5883        &mut self,
 5884        _: &SortLinesCaseInsensitive,
 5885        cx: &mut ViewContext<Self>,
 5886    ) {
 5887        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5888    }
 5889
 5890    pub fn unique_lines_case_insensitive(
 5891        &mut self,
 5892        _: &UniqueLinesCaseInsensitive,
 5893        cx: &mut ViewContext<Self>,
 5894    ) {
 5895        self.manipulate_lines(cx, |lines| {
 5896            let mut seen = HashSet::default();
 5897            lines.retain(|line| seen.insert(line.to_lowercase()));
 5898        })
 5899    }
 5900
 5901    pub fn unique_lines_case_sensitive(
 5902        &mut self,
 5903        _: &UniqueLinesCaseSensitive,
 5904        cx: &mut ViewContext<Self>,
 5905    ) {
 5906        self.manipulate_lines(cx, |lines| {
 5907            let mut seen = HashSet::default();
 5908            lines.retain(|line| seen.insert(*line));
 5909        })
 5910    }
 5911
 5912    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5913        let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
 5914        if !revert_changes.is_empty() {
 5915            self.transact(cx, |editor, cx| {
 5916                editor.revert(revert_changes, cx);
 5917            });
 5918        }
 5919    }
 5920
 5921    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5922        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5923            let project_path = buffer.read(cx).project_path(cx)?;
 5924            let project = self.project.as_ref()?.read(cx);
 5925            let entry = project.entry_for_path(&project_path, cx)?;
 5926            let abs_path = project.absolute_path(&project_path, cx)?;
 5927            let parent = if entry.is_symlink {
 5928                abs_path.canonicalize().ok()?
 5929            } else {
 5930                abs_path
 5931            }
 5932            .parent()?
 5933            .to_path_buf();
 5934            Some(parent)
 5935        }) {
 5936            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5937        }
 5938    }
 5939
 5940    fn gather_revert_changes(
 5941        &mut self,
 5942        selections: &[Selection<Anchor>],
 5943        cx: &mut ViewContext<'_, Editor>,
 5944    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 5945        let mut revert_changes = HashMap::default();
 5946        let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
 5947        for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
 5948            Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
 5949        }
 5950        revert_changes
 5951    }
 5952
 5953    pub fn prepare_revert_change(
 5954        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 5955        multi_buffer: &Model<MultiBuffer>,
 5956        hunk: &DiffHunk<MultiBufferRow>,
 5957        cx: &AppContext,
 5958    ) -> Option<()> {
 5959        let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
 5960        let buffer = buffer.read(cx);
 5961        let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
 5962        let buffer_snapshot = buffer.snapshot();
 5963        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 5964        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 5965            probe
 5966                .0
 5967                .start
 5968                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 5969                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 5970        }) {
 5971            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 5972            Some(())
 5973        } else {
 5974            None
 5975        }
 5976    }
 5977
 5978    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 5979        self.manipulate_lines(cx, |lines| lines.reverse())
 5980    }
 5981
 5982    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 5983        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 5984    }
 5985
 5986    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 5987    where
 5988        Fn: FnMut(&mut Vec<&str>),
 5989    {
 5990        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5991        let buffer = self.buffer.read(cx).snapshot(cx);
 5992
 5993        let mut edits = Vec::new();
 5994
 5995        let selections = self.selections.all::<Point>(cx);
 5996        let mut selections = selections.iter().peekable();
 5997        let mut contiguous_row_selections = Vec::new();
 5998        let mut new_selections = Vec::new();
 5999        let mut added_lines = 0;
 6000        let mut removed_lines = 0;
 6001
 6002        while let Some(selection) = selections.next() {
 6003            let (start_row, end_row) = consume_contiguous_rows(
 6004                &mut contiguous_row_selections,
 6005                selection,
 6006                &display_map,
 6007                &mut selections,
 6008            );
 6009
 6010            let start_point = Point::new(start_row.0, 0);
 6011            let end_point = Point::new(
 6012                end_row.previous_row().0,
 6013                buffer.line_len(end_row.previous_row()),
 6014            );
 6015            let text = buffer
 6016                .text_for_range(start_point..end_point)
 6017                .collect::<String>();
 6018
 6019            let mut lines = text.split('\n').collect_vec();
 6020
 6021            let lines_before = lines.len();
 6022            callback(&mut lines);
 6023            let lines_after = lines.len();
 6024
 6025            edits.push((start_point..end_point, lines.join("\n")));
 6026
 6027            // Selections must change based on added and removed line count
 6028            let start_row =
 6029                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6030            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6031            new_selections.push(Selection {
 6032                id: selection.id,
 6033                start: start_row,
 6034                end: end_row,
 6035                goal: SelectionGoal::None,
 6036                reversed: selection.reversed,
 6037            });
 6038
 6039            if lines_after > lines_before {
 6040                added_lines += lines_after - lines_before;
 6041            } else if lines_before > lines_after {
 6042                removed_lines += lines_before - lines_after;
 6043            }
 6044        }
 6045
 6046        self.transact(cx, |this, cx| {
 6047            let buffer = this.buffer.update(cx, |buffer, cx| {
 6048                buffer.edit(edits, None, cx);
 6049                buffer.snapshot(cx)
 6050            });
 6051
 6052            // Recalculate offsets on newly edited buffer
 6053            let new_selections = new_selections
 6054                .iter()
 6055                .map(|s| {
 6056                    let start_point = Point::new(s.start.0, 0);
 6057                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6058                    Selection {
 6059                        id: s.id,
 6060                        start: buffer.point_to_offset(start_point),
 6061                        end: buffer.point_to_offset(end_point),
 6062                        goal: s.goal,
 6063                        reversed: s.reversed,
 6064                    }
 6065                })
 6066                .collect();
 6067
 6068            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6069                s.select(new_selections);
 6070            });
 6071
 6072            this.request_autoscroll(Autoscroll::fit(), cx);
 6073        });
 6074    }
 6075
 6076    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6077        self.manipulate_text(cx, |text| text.to_uppercase())
 6078    }
 6079
 6080    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6081        self.manipulate_text(cx, |text| text.to_lowercase())
 6082    }
 6083
 6084    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6085        self.manipulate_text(cx, |text| {
 6086            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6087            // https://github.com/rutrum/convert-case/issues/16
 6088            text.split('\n')
 6089                .map(|line| line.to_case(Case::Title))
 6090                .join("\n")
 6091        })
 6092    }
 6093
 6094    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6095        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6096    }
 6097
 6098    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6099        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6100    }
 6101
 6102    pub fn convert_to_upper_camel_case(
 6103        &mut self,
 6104        _: &ConvertToUpperCamelCase,
 6105        cx: &mut ViewContext<Self>,
 6106    ) {
 6107        self.manipulate_text(cx, |text| {
 6108            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6109            // https://github.com/rutrum/convert-case/issues/16
 6110            text.split('\n')
 6111                .map(|line| line.to_case(Case::UpperCamel))
 6112                .join("\n")
 6113        })
 6114    }
 6115
 6116    pub fn convert_to_lower_camel_case(
 6117        &mut self,
 6118        _: &ConvertToLowerCamelCase,
 6119        cx: &mut ViewContext<Self>,
 6120    ) {
 6121        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6122    }
 6123
 6124    pub fn convert_to_opposite_case(
 6125        &mut self,
 6126        _: &ConvertToOppositeCase,
 6127        cx: &mut ViewContext<Self>,
 6128    ) {
 6129        self.manipulate_text(cx, |text| {
 6130            text.chars()
 6131                .fold(String::with_capacity(text.len()), |mut t, c| {
 6132                    if c.is_uppercase() {
 6133                        t.extend(c.to_lowercase());
 6134                    } else {
 6135                        t.extend(c.to_uppercase());
 6136                    }
 6137                    t
 6138                })
 6139        })
 6140    }
 6141
 6142    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6143    where
 6144        Fn: FnMut(&str) -> String,
 6145    {
 6146        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6147        let buffer = self.buffer.read(cx).snapshot(cx);
 6148
 6149        let mut new_selections = Vec::new();
 6150        let mut edits = Vec::new();
 6151        let mut selection_adjustment = 0i32;
 6152
 6153        for selection in self.selections.all::<usize>(cx) {
 6154            let selection_is_empty = selection.is_empty();
 6155
 6156            let (start, end) = if selection_is_empty {
 6157                let word_range = movement::surrounding_word(
 6158                    &display_map,
 6159                    selection.start.to_display_point(&display_map),
 6160                );
 6161                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6162                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6163                (start, end)
 6164            } else {
 6165                (selection.start, selection.end)
 6166            };
 6167
 6168            let text = buffer.text_for_range(start..end).collect::<String>();
 6169            let old_length = text.len() as i32;
 6170            let text = callback(&text);
 6171
 6172            new_selections.push(Selection {
 6173                start: (start as i32 - selection_adjustment) as usize,
 6174                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6175                goal: SelectionGoal::None,
 6176                ..selection
 6177            });
 6178
 6179            selection_adjustment += old_length - text.len() as i32;
 6180
 6181            edits.push((start..end, text));
 6182        }
 6183
 6184        self.transact(cx, |this, cx| {
 6185            this.buffer.update(cx, |buffer, cx| {
 6186                buffer.edit(edits, None, cx);
 6187            });
 6188
 6189            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6190                s.select(new_selections);
 6191            });
 6192
 6193            this.request_autoscroll(Autoscroll::fit(), cx);
 6194        });
 6195    }
 6196
 6197    pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
 6198        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6199        let buffer = &display_map.buffer_snapshot;
 6200        let selections = self.selections.all::<Point>(cx);
 6201
 6202        let mut edits = Vec::new();
 6203        let mut selections_iter = selections.iter().peekable();
 6204        while let Some(selection) = selections_iter.next() {
 6205            // Avoid duplicating the same lines twice.
 6206            let mut rows = selection.spanned_rows(false, &display_map);
 6207
 6208            while let Some(next_selection) = selections_iter.peek() {
 6209                let next_rows = next_selection.spanned_rows(false, &display_map);
 6210                if next_rows.start < rows.end {
 6211                    rows.end = next_rows.end;
 6212                    selections_iter.next().unwrap();
 6213                } else {
 6214                    break;
 6215                }
 6216            }
 6217
 6218            // Copy the text from the selected row region and splice it either at the start
 6219            // or end of the region.
 6220            let start = Point::new(rows.start.0, 0);
 6221            let end = Point::new(
 6222                rows.end.previous_row().0,
 6223                buffer.line_len(rows.end.previous_row()),
 6224            );
 6225            let text = buffer
 6226                .text_for_range(start..end)
 6227                .chain(Some("\n"))
 6228                .collect::<String>();
 6229            let insert_location = if upwards {
 6230                Point::new(rows.end.0, 0)
 6231            } else {
 6232                start
 6233            };
 6234            edits.push((insert_location..insert_location, text));
 6235        }
 6236
 6237        self.transact(cx, |this, cx| {
 6238            this.buffer.update(cx, |buffer, cx| {
 6239                buffer.edit(edits, None, cx);
 6240            });
 6241
 6242            this.request_autoscroll(Autoscroll::fit(), cx);
 6243        });
 6244    }
 6245
 6246    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6247        self.duplicate_line(true, cx);
 6248    }
 6249
 6250    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6251        self.duplicate_line(false, cx);
 6252    }
 6253
 6254    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6255        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6256        let buffer = self.buffer.read(cx).snapshot(cx);
 6257
 6258        let mut edits = Vec::new();
 6259        let mut unfold_ranges = Vec::new();
 6260        let mut refold_ranges = Vec::new();
 6261
 6262        let selections = self.selections.all::<Point>(cx);
 6263        let mut selections = selections.iter().peekable();
 6264        let mut contiguous_row_selections = Vec::new();
 6265        let mut new_selections = Vec::new();
 6266
 6267        while let Some(selection) = selections.next() {
 6268            // Find all the selections that span a contiguous row range
 6269            let (start_row, end_row) = consume_contiguous_rows(
 6270                &mut contiguous_row_selections,
 6271                selection,
 6272                &display_map,
 6273                &mut selections,
 6274            );
 6275
 6276            // Move the text spanned by the row range to be before the line preceding the row range
 6277            if start_row.0 > 0 {
 6278                let range_to_move = Point::new(
 6279                    start_row.previous_row().0,
 6280                    buffer.line_len(start_row.previous_row()),
 6281                )
 6282                    ..Point::new(
 6283                        end_row.previous_row().0,
 6284                        buffer.line_len(end_row.previous_row()),
 6285                    );
 6286                let insertion_point = display_map
 6287                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6288                    .0;
 6289
 6290                // Don't move lines across excerpts
 6291                if buffer
 6292                    .excerpt_boundaries_in_range((
 6293                        Bound::Excluded(insertion_point),
 6294                        Bound::Included(range_to_move.end),
 6295                    ))
 6296                    .next()
 6297                    .is_none()
 6298                {
 6299                    let text = buffer
 6300                        .text_for_range(range_to_move.clone())
 6301                        .flat_map(|s| s.chars())
 6302                        .skip(1)
 6303                        .chain(['\n'])
 6304                        .collect::<String>();
 6305
 6306                    edits.push((
 6307                        buffer.anchor_after(range_to_move.start)
 6308                            ..buffer.anchor_before(range_to_move.end),
 6309                        String::new(),
 6310                    ));
 6311                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6312                    edits.push((insertion_anchor..insertion_anchor, text));
 6313
 6314                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6315
 6316                    // Move selections up
 6317                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6318                        |mut selection| {
 6319                            selection.start.row -= row_delta;
 6320                            selection.end.row -= row_delta;
 6321                            selection
 6322                        },
 6323                    ));
 6324
 6325                    // Move folds up
 6326                    unfold_ranges.push(range_to_move.clone());
 6327                    for fold in display_map.folds_in_range(
 6328                        buffer.anchor_before(range_to_move.start)
 6329                            ..buffer.anchor_after(range_to_move.end),
 6330                    ) {
 6331                        let mut start = fold.range.start.to_point(&buffer);
 6332                        let mut end = fold.range.end.to_point(&buffer);
 6333                        start.row -= row_delta;
 6334                        end.row -= row_delta;
 6335                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6336                    }
 6337                }
 6338            }
 6339
 6340            // If we didn't move line(s), preserve the existing selections
 6341            new_selections.append(&mut contiguous_row_selections);
 6342        }
 6343
 6344        self.transact(cx, |this, cx| {
 6345            this.unfold_ranges(unfold_ranges, true, true, cx);
 6346            this.buffer.update(cx, |buffer, cx| {
 6347                for (range, text) in edits {
 6348                    buffer.edit([(range, text)], None, cx);
 6349                }
 6350            });
 6351            this.fold_ranges(refold_ranges, true, cx);
 6352            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6353                s.select(new_selections);
 6354            })
 6355        });
 6356    }
 6357
 6358    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6359        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6360        let buffer = self.buffer.read(cx).snapshot(cx);
 6361
 6362        let mut edits = Vec::new();
 6363        let mut unfold_ranges = Vec::new();
 6364        let mut refold_ranges = Vec::new();
 6365
 6366        let selections = self.selections.all::<Point>(cx);
 6367        let mut selections = selections.iter().peekable();
 6368        let mut contiguous_row_selections = Vec::new();
 6369        let mut new_selections = Vec::new();
 6370
 6371        while let Some(selection) = selections.next() {
 6372            // Find all the selections that span a contiguous row range
 6373            let (start_row, end_row) = consume_contiguous_rows(
 6374                &mut contiguous_row_selections,
 6375                selection,
 6376                &display_map,
 6377                &mut selections,
 6378            );
 6379
 6380            // Move the text spanned by the row range to be after the last line of the row range
 6381            if end_row.0 <= buffer.max_point().row {
 6382                let range_to_move =
 6383                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6384                let insertion_point = display_map
 6385                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6386                    .0;
 6387
 6388                // Don't move lines across excerpt boundaries
 6389                if buffer
 6390                    .excerpt_boundaries_in_range((
 6391                        Bound::Excluded(range_to_move.start),
 6392                        Bound::Included(insertion_point),
 6393                    ))
 6394                    .next()
 6395                    .is_none()
 6396                {
 6397                    let mut text = String::from("\n");
 6398                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6399                    text.pop(); // Drop trailing newline
 6400                    edits.push((
 6401                        buffer.anchor_after(range_to_move.start)
 6402                            ..buffer.anchor_before(range_to_move.end),
 6403                        String::new(),
 6404                    ));
 6405                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6406                    edits.push((insertion_anchor..insertion_anchor, text));
 6407
 6408                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6409
 6410                    // Move selections down
 6411                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6412                        |mut selection| {
 6413                            selection.start.row += row_delta;
 6414                            selection.end.row += row_delta;
 6415                            selection
 6416                        },
 6417                    ));
 6418
 6419                    // Move folds down
 6420                    unfold_ranges.push(range_to_move.clone());
 6421                    for fold in display_map.folds_in_range(
 6422                        buffer.anchor_before(range_to_move.start)
 6423                            ..buffer.anchor_after(range_to_move.end),
 6424                    ) {
 6425                        let mut start = fold.range.start.to_point(&buffer);
 6426                        let mut end = fold.range.end.to_point(&buffer);
 6427                        start.row += row_delta;
 6428                        end.row += row_delta;
 6429                        refold_ranges.push((start..end, fold.placeholder.clone()));
 6430                    }
 6431                }
 6432            }
 6433
 6434            // If we didn't move line(s), preserve the existing selections
 6435            new_selections.append(&mut contiguous_row_selections);
 6436        }
 6437
 6438        self.transact(cx, |this, cx| {
 6439            this.unfold_ranges(unfold_ranges, true, true, cx);
 6440            this.buffer.update(cx, |buffer, cx| {
 6441                for (range, text) in edits {
 6442                    buffer.edit([(range, text)], None, cx);
 6443                }
 6444            });
 6445            this.fold_ranges(refold_ranges, true, cx);
 6446            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6447        });
 6448    }
 6449
 6450    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6451        let text_layout_details = &self.text_layout_details(cx);
 6452        self.transact(cx, |this, cx| {
 6453            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6454                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6455                let line_mode = s.line_mode;
 6456                s.move_with(|display_map, selection| {
 6457                    if !selection.is_empty() || line_mode {
 6458                        return;
 6459                    }
 6460
 6461                    let mut head = selection.head();
 6462                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6463                    if head.column() == display_map.line_len(head.row()) {
 6464                        transpose_offset = display_map
 6465                            .buffer_snapshot
 6466                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6467                    }
 6468
 6469                    if transpose_offset == 0 {
 6470                        return;
 6471                    }
 6472
 6473                    *head.column_mut() += 1;
 6474                    head = display_map.clip_point(head, Bias::Right);
 6475                    let goal = SelectionGoal::HorizontalPosition(
 6476                        display_map
 6477                            .x_for_display_point(head, &text_layout_details)
 6478                            .into(),
 6479                    );
 6480                    selection.collapse_to(head, goal);
 6481
 6482                    let transpose_start = display_map
 6483                        .buffer_snapshot
 6484                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6485                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6486                        let transpose_end = display_map
 6487                            .buffer_snapshot
 6488                            .clip_offset(transpose_offset + 1, Bias::Right);
 6489                        if let Some(ch) =
 6490                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6491                        {
 6492                            edits.push((transpose_start..transpose_offset, String::new()));
 6493                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6494                        }
 6495                    }
 6496                });
 6497                edits
 6498            });
 6499            this.buffer
 6500                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6501            let selections = this.selections.all::<usize>(cx);
 6502            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6503                s.select(selections);
 6504            });
 6505        });
 6506    }
 6507
 6508    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6509        let mut text = String::new();
 6510        let buffer = self.buffer.read(cx).snapshot(cx);
 6511        let mut selections = self.selections.all::<Point>(cx);
 6512        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6513        {
 6514            let max_point = buffer.max_point();
 6515            let mut is_first = true;
 6516            for selection in &mut selections {
 6517                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6518                if is_entire_line {
 6519                    selection.start = Point::new(selection.start.row, 0);
 6520                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6521                    selection.goal = SelectionGoal::None;
 6522                }
 6523                if is_first {
 6524                    is_first = false;
 6525                } else {
 6526                    text += "\n";
 6527                }
 6528                let mut len = 0;
 6529                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6530                    text.push_str(chunk);
 6531                    len += chunk.len();
 6532                }
 6533                clipboard_selections.push(ClipboardSelection {
 6534                    len,
 6535                    is_entire_line,
 6536                    first_line_indent: buffer
 6537                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6538                        .len,
 6539                });
 6540            }
 6541        }
 6542
 6543        self.transact(cx, |this, cx| {
 6544            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6545                s.select(selections);
 6546            });
 6547            this.insert("", cx);
 6548            cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6549        });
 6550    }
 6551
 6552    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6553        let selections = self.selections.all::<Point>(cx);
 6554        let buffer = self.buffer.read(cx).read(cx);
 6555        let mut text = String::new();
 6556
 6557        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6558        {
 6559            let max_point = buffer.max_point();
 6560            let mut is_first = true;
 6561            for selection in selections.iter() {
 6562                let mut start = selection.start;
 6563                let mut end = selection.end;
 6564                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6565                if is_entire_line {
 6566                    start = Point::new(start.row, 0);
 6567                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6568                }
 6569                if is_first {
 6570                    is_first = false;
 6571                } else {
 6572                    text += "\n";
 6573                }
 6574                let mut len = 0;
 6575                for chunk in buffer.text_for_range(start..end) {
 6576                    text.push_str(chunk);
 6577                    len += chunk.len();
 6578                }
 6579                clipboard_selections.push(ClipboardSelection {
 6580                    len,
 6581                    is_entire_line,
 6582                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6583                });
 6584            }
 6585        }
 6586
 6587        cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
 6588    }
 6589
 6590    pub fn do_paste(
 6591        &mut self,
 6592        text: &String,
 6593        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6594        handle_entire_lines: bool,
 6595        cx: &mut ViewContext<Self>,
 6596    ) {
 6597        if self.read_only(cx) {
 6598            return;
 6599        }
 6600
 6601        let clipboard_text = Cow::Borrowed(text);
 6602
 6603        self.transact(cx, |this, cx| {
 6604            if let Some(mut clipboard_selections) = clipboard_selections {
 6605                let old_selections = this.selections.all::<usize>(cx);
 6606                let all_selections_were_entire_line =
 6607                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6608                let first_selection_indent_column =
 6609                    clipboard_selections.first().map(|s| s.first_line_indent);
 6610                if clipboard_selections.len() != old_selections.len() {
 6611                    clipboard_selections.drain(..);
 6612                }
 6613
 6614                this.buffer.update(cx, |buffer, cx| {
 6615                    let snapshot = buffer.read(cx);
 6616                    let mut start_offset = 0;
 6617                    let mut edits = Vec::new();
 6618                    let mut original_indent_columns = Vec::new();
 6619                    for (ix, selection) in old_selections.iter().enumerate() {
 6620                        let to_insert;
 6621                        let entire_line;
 6622                        let original_indent_column;
 6623                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6624                            let end_offset = start_offset + clipboard_selection.len;
 6625                            to_insert = &clipboard_text[start_offset..end_offset];
 6626                            entire_line = clipboard_selection.is_entire_line;
 6627                            start_offset = end_offset + 1;
 6628                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6629                        } else {
 6630                            to_insert = clipboard_text.as_str();
 6631                            entire_line = all_selections_were_entire_line;
 6632                            original_indent_column = first_selection_indent_column
 6633                        }
 6634
 6635                        // If the corresponding selection was empty when this slice of the
 6636                        // clipboard text was written, then the entire line containing the
 6637                        // selection was copied. If this selection is also currently empty,
 6638                        // then paste the line before the current line of the buffer.
 6639                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6640                            let column = selection.start.to_point(&snapshot).column as usize;
 6641                            let line_start = selection.start - column;
 6642                            line_start..line_start
 6643                        } else {
 6644                            selection.range()
 6645                        };
 6646
 6647                        edits.push((range, to_insert));
 6648                        original_indent_columns.extend(original_indent_column);
 6649                    }
 6650                    drop(snapshot);
 6651
 6652                    buffer.edit(
 6653                        edits,
 6654                        Some(AutoindentMode::Block {
 6655                            original_indent_columns,
 6656                        }),
 6657                        cx,
 6658                    );
 6659                });
 6660
 6661                let selections = this.selections.all::<usize>(cx);
 6662                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6663            } else {
 6664                this.insert(&clipboard_text, cx);
 6665            }
 6666        });
 6667    }
 6668
 6669    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6670        if let Some(item) = cx.read_from_clipboard() {
 6671            self.do_paste(
 6672                item.text(),
 6673                item.metadata::<Vec<ClipboardSelection>>(),
 6674                true,
 6675                cx,
 6676            )
 6677        };
 6678    }
 6679
 6680    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6681        if self.read_only(cx) {
 6682            return;
 6683        }
 6684
 6685        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6686            if let Some((selections, _)) =
 6687                self.selection_history.transaction(transaction_id).cloned()
 6688            {
 6689                self.change_selections(None, cx, |s| {
 6690                    s.select_anchors(selections.to_vec());
 6691                });
 6692            }
 6693            self.request_autoscroll(Autoscroll::fit(), cx);
 6694            self.unmark_text(cx);
 6695            self.refresh_inline_completion(true, cx);
 6696            cx.emit(EditorEvent::Edited { transaction_id });
 6697            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 6698        }
 6699    }
 6700
 6701    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 6702        if self.read_only(cx) {
 6703            return;
 6704        }
 6705
 6706        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 6707            if let Some((_, Some(selections))) =
 6708                self.selection_history.transaction(transaction_id).cloned()
 6709            {
 6710                self.change_selections(None, cx, |s| {
 6711                    s.select_anchors(selections.to_vec());
 6712                });
 6713            }
 6714            self.request_autoscroll(Autoscroll::fit(), cx);
 6715            self.unmark_text(cx);
 6716            self.refresh_inline_completion(true, cx);
 6717            cx.emit(EditorEvent::Edited { transaction_id });
 6718        }
 6719    }
 6720
 6721    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 6722        self.buffer
 6723            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 6724    }
 6725
 6726    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 6727        self.buffer
 6728            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 6729    }
 6730
 6731    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 6732        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6733            let line_mode = s.line_mode;
 6734            s.move_with(|map, selection| {
 6735                let cursor = if selection.is_empty() && !line_mode {
 6736                    movement::left(map, selection.start)
 6737                } else {
 6738                    selection.start
 6739                };
 6740                selection.collapse_to(cursor, SelectionGoal::None);
 6741            });
 6742        })
 6743    }
 6744
 6745    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 6746        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6747            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 6748        })
 6749    }
 6750
 6751    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 6752        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6753            let line_mode = s.line_mode;
 6754            s.move_with(|map, selection| {
 6755                let cursor = if selection.is_empty() && !line_mode {
 6756                    movement::right(map, selection.end)
 6757                } else {
 6758                    selection.end
 6759                };
 6760                selection.collapse_to(cursor, SelectionGoal::None)
 6761            });
 6762        })
 6763    }
 6764
 6765    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 6766        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6767            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 6768        })
 6769    }
 6770
 6771    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 6772        if self.take_rename(true, cx).is_some() {
 6773            return;
 6774        }
 6775
 6776        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6777            cx.propagate();
 6778            return;
 6779        }
 6780
 6781        let text_layout_details = &self.text_layout_details(cx);
 6782        let selection_count = self.selections.count();
 6783        let first_selection = self.selections.first_anchor();
 6784
 6785        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6786            let line_mode = s.line_mode;
 6787            s.move_with(|map, selection| {
 6788                if !selection.is_empty() && !line_mode {
 6789                    selection.goal = SelectionGoal::None;
 6790                }
 6791                let (cursor, goal) = movement::up(
 6792                    map,
 6793                    selection.start,
 6794                    selection.goal,
 6795                    false,
 6796                    &text_layout_details,
 6797                );
 6798                selection.collapse_to(cursor, goal);
 6799            });
 6800        });
 6801
 6802        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6803        {
 6804            cx.propagate();
 6805        }
 6806    }
 6807
 6808    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 6809        if self.take_rename(true, cx).is_some() {
 6810            return;
 6811        }
 6812
 6813        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6814            cx.propagate();
 6815            return;
 6816        }
 6817
 6818        let text_layout_details = &self.text_layout_details(cx);
 6819
 6820        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6821            let line_mode = s.line_mode;
 6822            s.move_with(|map, selection| {
 6823                if !selection.is_empty() && !line_mode {
 6824                    selection.goal = SelectionGoal::None;
 6825                }
 6826                let (cursor, goal) = movement::up_by_rows(
 6827                    map,
 6828                    selection.start,
 6829                    action.lines,
 6830                    selection.goal,
 6831                    false,
 6832                    &text_layout_details,
 6833                );
 6834                selection.collapse_to(cursor, goal);
 6835            });
 6836        })
 6837    }
 6838
 6839    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 6840        if self.take_rename(true, cx).is_some() {
 6841            return;
 6842        }
 6843
 6844        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6845            cx.propagate();
 6846            return;
 6847        }
 6848
 6849        let text_layout_details = &self.text_layout_details(cx);
 6850
 6851        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6852            let line_mode = s.line_mode;
 6853            s.move_with(|map, selection| {
 6854                if !selection.is_empty() && !line_mode {
 6855                    selection.goal = SelectionGoal::None;
 6856                }
 6857                let (cursor, goal) = movement::down_by_rows(
 6858                    map,
 6859                    selection.start,
 6860                    action.lines,
 6861                    selection.goal,
 6862                    false,
 6863                    &text_layout_details,
 6864                );
 6865                selection.collapse_to(cursor, goal);
 6866            });
 6867        })
 6868    }
 6869
 6870    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 6871        let text_layout_details = &self.text_layout_details(cx);
 6872        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6873            s.move_heads_with(|map, head, goal| {
 6874                movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6875            })
 6876        })
 6877    }
 6878
 6879    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 6880        let text_layout_details = &self.text_layout_details(cx);
 6881        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6882            s.move_heads_with(|map, head, goal| {
 6883                movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
 6884            })
 6885        })
 6886    }
 6887
 6888    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 6889        let Some(row_count) = self.visible_row_count() else {
 6890            return;
 6891        };
 6892
 6893        let text_layout_details = &self.text_layout_details(cx);
 6894
 6895        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6896            s.move_heads_with(|map, head, goal| {
 6897                movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
 6898            })
 6899        })
 6900    }
 6901
 6902    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 6903        if self.take_rename(true, cx).is_some() {
 6904            return;
 6905        }
 6906
 6907        if self
 6908            .context_menu
 6909            .write()
 6910            .as_mut()
 6911            .map(|menu| menu.select_first(self.project.as_ref(), cx))
 6912            .unwrap_or(false)
 6913        {
 6914            return;
 6915        }
 6916
 6917        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6918            cx.propagate();
 6919            return;
 6920        }
 6921
 6922        let Some(row_count) = self.visible_row_count() else {
 6923            return;
 6924        };
 6925
 6926        let autoscroll = if action.center_cursor {
 6927            Autoscroll::center()
 6928        } else {
 6929            Autoscroll::fit()
 6930        };
 6931
 6932        let text_layout_details = &self.text_layout_details(cx);
 6933
 6934        self.change_selections(Some(autoscroll), cx, |s| {
 6935            let line_mode = s.line_mode;
 6936            s.move_with(|map, selection| {
 6937                if !selection.is_empty() && !line_mode {
 6938                    selection.goal = SelectionGoal::None;
 6939                }
 6940                let (cursor, goal) = movement::up_by_rows(
 6941                    map,
 6942                    selection.end,
 6943                    row_count,
 6944                    selection.goal,
 6945                    false,
 6946                    &text_layout_details,
 6947                );
 6948                selection.collapse_to(cursor, goal);
 6949            });
 6950        });
 6951    }
 6952
 6953    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 6954        let text_layout_details = &self.text_layout_details(cx);
 6955        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6956            s.move_heads_with(|map, head, goal| {
 6957                movement::up(map, head, goal, false, &text_layout_details)
 6958            })
 6959        })
 6960    }
 6961
 6962    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 6963        self.take_rename(true, cx);
 6964
 6965        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 6966            cx.propagate();
 6967            return;
 6968        }
 6969
 6970        let text_layout_details = &self.text_layout_details(cx);
 6971        let selection_count = self.selections.count();
 6972        let first_selection = self.selections.first_anchor();
 6973
 6974        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6975            let line_mode = s.line_mode;
 6976            s.move_with(|map, selection| {
 6977                if !selection.is_empty() && !line_mode {
 6978                    selection.goal = SelectionGoal::None;
 6979                }
 6980                let (cursor, goal) = movement::down(
 6981                    map,
 6982                    selection.end,
 6983                    selection.goal,
 6984                    false,
 6985                    &text_layout_details,
 6986                );
 6987                selection.collapse_to(cursor, goal);
 6988            });
 6989        });
 6990
 6991        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 6992        {
 6993            cx.propagate();
 6994        }
 6995    }
 6996
 6997    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 6998        let Some(row_count) = self.visible_row_count() else {
 6999            return;
 7000        };
 7001
 7002        let text_layout_details = &self.text_layout_details(cx);
 7003
 7004        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7005            s.move_heads_with(|map, head, goal| {
 7006                movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
 7007            })
 7008        })
 7009    }
 7010
 7011    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7012        if self.take_rename(true, cx).is_some() {
 7013            return;
 7014        }
 7015
 7016        if self
 7017            .context_menu
 7018            .write()
 7019            .as_mut()
 7020            .map(|menu| menu.select_last(self.project.as_ref(), cx))
 7021            .unwrap_or(false)
 7022        {
 7023            return;
 7024        }
 7025
 7026        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7027            cx.propagate();
 7028            return;
 7029        }
 7030
 7031        let Some(row_count) = self.visible_row_count() else {
 7032            return;
 7033        };
 7034
 7035        let autoscroll = if action.center_cursor {
 7036            Autoscroll::center()
 7037        } else {
 7038            Autoscroll::fit()
 7039        };
 7040
 7041        let text_layout_details = &self.text_layout_details(cx);
 7042        self.change_selections(Some(autoscroll), cx, |s| {
 7043            let line_mode = s.line_mode;
 7044            s.move_with(|map, selection| {
 7045                if !selection.is_empty() && !line_mode {
 7046                    selection.goal = SelectionGoal::None;
 7047                }
 7048                let (cursor, goal) = movement::down_by_rows(
 7049                    map,
 7050                    selection.end,
 7051                    row_count,
 7052                    selection.goal,
 7053                    false,
 7054                    &text_layout_details,
 7055                );
 7056                selection.collapse_to(cursor, goal);
 7057            });
 7058        });
 7059    }
 7060
 7061    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7062        let text_layout_details = &self.text_layout_details(cx);
 7063        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7064            s.move_heads_with(|map, head, goal| {
 7065                movement::down(map, head, goal, false, &text_layout_details)
 7066            })
 7067        });
 7068    }
 7069
 7070    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7071        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7072            context_menu.select_first(self.project.as_ref(), cx);
 7073        }
 7074    }
 7075
 7076    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7077        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7078            context_menu.select_prev(self.project.as_ref(), cx);
 7079        }
 7080    }
 7081
 7082    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7083        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7084            context_menu.select_next(self.project.as_ref(), cx);
 7085        }
 7086    }
 7087
 7088    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7089        if let Some(context_menu) = self.context_menu.write().as_mut() {
 7090            context_menu.select_last(self.project.as_ref(), cx);
 7091        }
 7092    }
 7093
 7094    pub fn move_to_previous_word_start(
 7095        &mut self,
 7096        _: &MoveToPreviousWordStart,
 7097        cx: &mut ViewContext<Self>,
 7098    ) {
 7099        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7100            s.move_cursors_with(|map, head, _| {
 7101                (
 7102                    movement::previous_word_start(map, head),
 7103                    SelectionGoal::None,
 7104                )
 7105            });
 7106        })
 7107    }
 7108
 7109    pub fn move_to_previous_subword_start(
 7110        &mut self,
 7111        _: &MoveToPreviousSubwordStart,
 7112        cx: &mut ViewContext<Self>,
 7113    ) {
 7114        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7115            s.move_cursors_with(|map, head, _| {
 7116                (
 7117                    movement::previous_subword_start(map, head),
 7118                    SelectionGoal::None,
 7119                )
 7120            });
 7121        })
 7122    }
 7123
 7124    pub fn select_to_previous_word_start(
 7125        &mut self,
 7126        _: &SelectToPreviousWordStart,
 7127        cx: &mut ViewContext<Self>,
 7128    ) {
 7129        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7130            s.move_heads_with(|map, head, _| {
 7131                (
 7132                    movement::previous_word_start(map, head),
 7133                    SelectionGoal::None,
 7134                )
 7135            });
 7136        })
 7137    }
 7138
 7139    pub fn select_to_previous_subword_start(
 7140        &mut self,
 7141        _: &SelectToPreviousSubwordStart,
 7142        cx: &mut ViewContext<Self>,
 7143    ) {
 7144        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7145            s.move_heads_with(|map, head, _| {
 7146                (
 7147                    movement::previous_subword_start(map, head),
 7148                    SelectionGoal::None,
 7149                )
 7150            });
 7151        })
 7152    }
 7153
 7154    pub fn delete_to_previous_word_start(
 7155        &mut self,
 7156        _: &DeleteToPreviousWordStart,
 7157        cx: &mut ViewContext<Self>,
 7158    ) {
 7159        self.transact(cx, |this, cx| {
 7160            this.select_autoclose_pair(cx);
 7161            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7162                let line_mode = s.line_mode;
 7163                s.move_with(|map, selection| {
 7164                    if selection.is_empty() && !line_mode {
 7165                        let cursor = movement::previous_word_start(map, selection.head());
 7166                        selection.set_head(cursor, SelectionGoal::None);
 7167                    }
 7168                });
 7169            });
 7170            this.insert("", cx);
 7171        });
 7172    }
 7173
 7174    pub fn delete_to_previous_subword_start(
 7175        &mut self,
 7176        _: &DeleteToPreviousSubwordStart,
 7177        cx: &mut ViewContext<Self>,
 7178    ) {
 7179        self.transact(cx, |this, cx| {
 7180            this.select_autoclose_pair(cx);
 7181            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7182                let line_mode = s.line_mode;
 7183                s.move_with(|map, selection| {
 7184                    if selection.is_empty() && !line_mode {
 7185                        let cursor = movement::previous_subword_start(map, selection.head());
 7186                        selection.set_head(cursor, SelectionGoal::None);
 7187                    }
 7188                });
 7189            });
 7190            this.insert("", cx);
 7191        });
 7192    }
 7193
 7194    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7195        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7196            s.move_cursors_with(|map, head, _| {
 7197                (movement::next_word_end(map, head), SelectionGoal::None)
 7198            });
 7199        })
 7200    }
 7201
 7202    pub fn move_to_next_subword_end(
 7203        &mut self,
 7204        _: &MoveToNextSubwordEnd,
 7205        cx: &mut ViewContext<Self>,
 7206    ) {
 7207        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7208            s.move_cursors_with(|map, head, _| {
 7209                (movement::next_subword_end(map, head), SelectionGoal::None)
 7210            });
 7211        })
 7212    }
 7213
 7214    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7215        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7216            s.move_heads_with(|map, head, _| {
 7217                (movement::next_word_end(map, head), SelectionGoal::None)
 7218            });
 7219        })
 7220    }
 7221
 7222    pub fn select_to_next_subword_end(
 7223        &mut self,
 7224        _: &SelectToNextSubwordEnd,
 7225        cx: &mut ViewContext<Self>,
 7226    ) {
 7227        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7228            s.move_heads_with(|map, head, _| {
 7229                (movement::next_subword_end(map, head), SelectionGoal::None)
 7230            });
 7231        })
 7232    }
 7233
 7234    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
 7235        self.transact(cx, |this, cx| {
 7236            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7237                let line_mode = s.line_mode;
 7238                s.move_with(|map, selection| {
 7239                    if selection.is_empty() && !line_mode {
 7240                        let cursor = movement::next_word_end(map, selection.head());
 7241                        selection.set_head(cursor, SelectionGoal::None);
 7242                    }
 7243                });
 7244            });
 7245            this.insert("", cx);
 7246        });
 7247    }
 7248
 7249    pub fn delete_to_next_subword_end(
 7250        &mut self,
 7251        _: &DeleteToNextSubwordEnd,
 7252        cx: &mut ViewContext<Self>,
 7253    ) {
 7254        self.transact(cx, |this, cx| {
 7255            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7256                s.move_with(|map, selection| {
 7257                    if selection.is_empty() {
 7258                        let cursor = movement::next_subword_end(map, selection.head());
 7259                        selection.set_head(cursor, SelectionGoal::None);
 7260                    }
 7261                });
 7262            });
 7263            this.insert("", cx);
 7264        });
 7265    }
 7266
 7267    pub fn move_to_beginning_of_line(
 7268        &mut self,
 7269        action: &MoveToBeginningOfLine,
 7270        cx: &mut ViewContext<Self>,
 7271    ) {
 7272        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7273            s.move_cursors_with(|map, head, _| {
 7274                (
 7275                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7276                    SelectionGoal::None,
 7277                )
 7278            });
 7279        })
 7280    }
 7281
 7282    pub fn select_to_beginning_of_line(
 7283        &mut self,
 7284        action: &SelectToBeginningOfLine,
 7285        cx: &mut ViewContext<Self>,
 7286    ) {
 7287        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7288            s.move_heads_with(|map, head, _| {
 7289                (
 7290                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7291                    SelectionGoal::None,
 7292                )
 7293            });
 7294        });
 7295    }
 7296
 7297    pub fn delete_to_beginning_of_line(
 7298        &mut self,
 7299        _: &DeleteToBeginningOfLine,
 7300        cx: &mut ViewContext<Self>,
 7301    ) {
 7302        self.transact(cx, |this, cx| {
 7303            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7304                s.move_with(|_, selection| {
 7305                    selection.reversed = true;
 7306                });
 7307            });
 7308
 7309            this.select_to_beginning_of_line(
 7310                &SelectToBeginningOfLine {
 7311                    stop_at_soft_wraps: false,
 7312                },
 7313                cx,
 7314            );
 7315            this.backspace(&Backspace, cx);
 7316        });
 7317    }
 7318
 7319    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7320        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7321            s.move_cursors_with(|map, head, _| {
 7322                (
 7323                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7324                    SelectionGoal::None,
 7325                )
 7326            });
 7327        })
 7328    }
 7329
 7330    pub fn select_to_end_of_line(
 7331        &mut self,
 7332        action: &SelectToEndOfLine,
 7333        cx: &mut ViewContext<Self>,
 7334    ) {
 7335        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7336            s.move_heads_with(|map, head, _| {
 7337                (
 7338                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7339                    SelectionGoal::None,
 7340                )
 7341            });
 7342        })
 7343    }
 7344
 7345    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7346        self.transact(cx, |this, cx| {
 7347            this.select_to_end_of_line(
 7348                &SelectToEndOfLine {
 7349                    stop_at_soft_wraps: false,
 7350                },
 7351                cx,
 7352            );
 7353            this.delete(&Delete, cx);
 7354        });
 7355    }
 7356
 7357    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7358        self.transact(cx, |this, cx| {
 7359            this.select_to_end_of_line(
 7360                &SelectToEndOfLine {
 7361                    stop_at_soft_wraps: false,
 7362                },
 7363                cx,
 7364            );
 7365            this.cut(&Cut, cx);
 7366        });
 7367    }
 7368
 7369    pub fn move_to_start_of_paragraph(
 7370        &mut self,
 7371        _: &MoveToStartOfParagraph,
 7372        cx: &mut ViewContext<Self>,
 7373    ) {
 7374        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7375            cx.propagate();
 7376            return;
 7377        }
 7378
 7379        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7380            s.move_with(|map, selection| {
 7381                selection.collapse_to(
 7382                    movement::start_of_paragraph(map, selection.head(), 1),
 7383                    SelectionGoal::None,
 7384                )
 7385            });
 7386        })
 7387    }
 7388
 7389    pub fn move_to_end_of_paragraph(
 7390        &mut self,
 7391        _: &MoveToEndOfParagraph,
 7392        cx: &mut ViewContext<Self>,
 7393    ) {
 7394        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7395            cx.propagate();
 7396            return;
 7397        }
 7398
 7399        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7400            s.move_with(|map, selection| {
 7401                selection.collapse_to(
 7402                    movement::end_of_paragraph(map, selection.head(), 1),
 7403                    SelectionGoal::None,
 7404                )
 7405            });
 7406        })
 7407    }
 7408
 7409    pub fn select_to_start_of_paragraph(
 7410        &mut self,
 7411        _: &SelectToStartOfParagraph,
 7412        cx: &mut ViewContext<Self>,
 7413    ) {
 7414        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7415            cx.propagate();
 7416            return;
 7417        }
 7418
 7419        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7420            s.move_heads_with(|map, head, _| {
 7421                (
 7422                    movement::start_of_paragraph(map, head, 1),
 7423                    SelectionGoal::None,
 7424                )
 7425            });
 7426        })
 7427    }
 7428
 7429    pub fn select_to_end_of_paragraph(
 7430        &mut self,
 7431        _: &SelectToEndOfParagraph,
 7432        cx: &mut ViewContext<Self>,
 7433    ) {
 7434        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7435            cx.propagate();
 7436            return;
 7437        }
 7438
 7439        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7440            s.move_heads_with(|map, head, _| {
 7441                (
 7442                    movement::end_of_paragraph(map, head, 1),
 7443                    SelectionGoal::None,
 7444                )
 7445            });
 7446        })
 7447    }
 7448
 7449    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7450        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7451            cx.propagate();
 7452            return;
 7453        }
 7454
 7455        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7456            s.select_ranges(vec![0..0]);
 7457        });
 7458    }
 7459
 7460    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7461        let mut selection = self.selections.last::<Point>(cx);
 7462        selection.set_head(Point::zero(), SelectionGoal::None);
 7463
 7464        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7465            s.select(vec![selection]);
 7466        });
 7467    }
 7468
 7469    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7470        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7471            cx.propagate();
 7472            return;
 7473        }
 7474
 7475        let cursor = self.buffer.read(cx).read(cx).len();
 7476        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7477            s.select_ranges(vec![cursor..cursor])
 7478        });
 7479    }
 7480
 7481    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7482        self.nav_history = nav_history;
 7483    }
 7484
 7485    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7486        self.nav_history.as_ref()
 7487    }
 7488
 7489    fn push_to_nav_history(
 7490        &mut self,
 7491        cursor_anchor: Anchor,
 7492        new_position: Option<Point>,
 7493        cx: &mut ViewContext<Self>,
 7494    ) {
 7495        if let Some(nav_history) = self.nav_history.as_mut() {
 7496            let buffer = self.buffer.read(cx).read(cx);
 7497            let cursor_position = cursor_anchor.to_point(&buffer);
 7498            let scroll_state = self.scroll_manager.anchor();
 7499            let scroll_top_row = scroll_state.top_row(&buffer);
 7500            drop(buffer);
 7501
 7502            if let Some(new_position) = new_position {
 7503                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7504                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7505                    return;
 7506                }
 7507            }
 7508
 7509            nav_history.push(
 7510                Some(NavigationData {
 7511                    cursor_anchor,
 7512                    cursor_position,
 7513                    scroll_anchor: scroll_state,
 7514                    scroll_top_row,
 7515                }),
 7516                cx,
 7517            );
 7518        }
 7519    }
 7520
 7521    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7522        let buffer = self.buffer.read(cx).snapshot(cx);
 7523        let mut selection = self.selections.first::<usize>(cx);
 7524        selection.set_head(buffer.len(), SelectionGoal::None);
 7525        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7526            s.select(vec![selection]);
 7527        });
 7528    }
 7529
 7530    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7531        let end = self.buffer.read(cx).read(cx).len();
 7532        self.change_selections(None, cx, |s| {
 7533            s.select_ranges(vec![0..end]);
 7534        });
 7535    }
 7536
 7537    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7538        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7539        let mut selections = self.selections.all::<Point>(cx);
 7540        let max_point = display_map.buffer_snapshot.max_point();
 7541        for selection in &mut selections {
 7542            let rows = selection.spanned_rows(true, &display_map);
 7543            selection.start = Point::new(rows.start.0, 0);
 7544            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7545            selection.reversed = false;
 7546        }
 7547        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7548            s.select(selections);
 7549        });
 7550    }
 7551
 7552    pub fn split_selection_into_lines(
 7553        &mut self,
 7554        _: &SplitSelectionIntoLines,
 7555        cx: &mut ViewContext<Self>,
 7556    ) {
 7557        let mut to_unfold = Vec::new();
 7558        let mut new_selection_ranges = Vec::new();
 7559        {
 7560            let selections = self.selections.all::<Point>(cx);
 7561            let buffer = self.buffer.read(cx).read(cx);
 7562            for selection in selections {
 7563                for row in selection.start.row..selection.end.row {
 7564                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7565                    new_selection_ranges.push(cursor..cursor);
 7566                }
 7567                new_selection_ranges.push(selection.end..selection.end);
 7568                to_unfold.push(selection.start..selection.end);
 7569            }
 7570        }
 7571        self.unfold_ranges(to_unfold, true, true, cx);
 7572        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7573            s.select_ranges(new_selection_ranges);
 7574        });
 7575    }
 7576
 7577    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7578        self.add_selection(true, cx);
 7579    }
 7580
 7581    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7582        self.add_selection(false, cx);
 7583    }
 7584
 7585    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7586        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7587        let mut selections = self.selections.all::<Point>(cx);
 7588        let text_layout_details = self.text_layout_details(cx);
 7589        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7590            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7591            let range = oldest_selection.display_range(&display_map).sorted();
 7592
 7593            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7594            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7595            let positions = start_x.min(end_x)..start_x.max(end_x);
 7596
 7597            selections.clear();
 7598            let mut stack = Vec::new();
 7599            for row in range.start.row().0..=range.end.row().0 {
 7600                if let Some(selection) = self.selections.build_columnar_selection(
 7601                    &display_map,
 7602                    DisplayRow(row),
 7603                    &positions,
 7604                    oldest_selection.reversed,
 7605                    &text_layout_details,
 7606                ) {
 7607                    stack.push(selection.id);
 7608                    selections.push(selection);
 7609                }
 7610            }
 7611
 7612            if above {
 7613                stack.reverse();
 7614            }
 7615
 7616            AddSelectionsState { above, stack }
 7617        });
 7618
 7619        let last_added_selection = *state.stack.last().unwrap();
 7620        let mut new_selections = Vec::new();
 7621        if above == state.above {
 7622            let end_row = if above {
 7623                DisplayRow(0)
 7624            } else {
 7625                display_map.max_point().row()
 7626            };
 7627
 7628            'outer: for selection in selections {
 7629                if selection.id == last_added_selection {
 7630                    let range = selection.display_range(&display_map).sorted();
 7631                    debug_assert_eq!(range.start.row(), range.end.row());
 7632                    let mut row = range.start.row();
 7633                    let positions =
 7634                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7635                            px(start)..px(end)
 7636                        } else {
 7637                            let start_x =
 7638                                display_map.x_for_display_point(range.start, &text_layout_details);
 7639                            let end_x =
 7640                                display_map.x_for_display_point(range.end, &text_layout_details);
 7641                            start_x.min(end_x)..start_x.max(end_x)
 7642                        };
 7643
 7644                    while row != end_row {
 7645                        if above {
 7646                            row.0 -= 1;
 7647                        } else {
 7648                            row.0 += 1;
 7649                        }
 7650
 7651                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7652                            &display_map,
 7653                            row,
 7654                            &positions,
 7655                            selection.reversed,
 7656                            &text_layout_details,
 7657                        ) {
 7658                            state.stack.push(new_selection.id);
 7659                            if above {
 7660                                new_selections.push(new_selection);
 7661                                new_selections.push(selection);
 7662                            } else {
 7663                                new_selections.push(selection);
 7664                                new_selections.push(new_selection);
 7665                            }
 7666
 7667                            continue 'outer;
 7668                        }
 7669                    }
 7670                }
 7671
 7672                new_selections.push(selection);
 7673            }
 7674        } else {
 7675            new_selections = selections;
 7676            new_selections.retain(|s| s.id != last_added_selection);
 7677            state.stack.pop();
 7678        }
 7679
 7680        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7681            s.select(new_selections);
 7682        });
 7683        if state.stack.len() > 1 {
 7684            self.add_selections_state = Some(state);
 7685        }
 7686    }
 7687
 7688    pub fn select_next_match_internal(
 7689        &mut self,
 7690        display_map: &DisplaySnapshot,
 7691        replace_newest: bool,
 7692        autoscroll: Option<Autoscroll>,
 7693        cx: &mut ViewContext<Self>,
 7694    ) -> Result<()> {
 7695        fn select_next_match_ranges(
 7696            this: &mut Editor,
 7697            range: Range<usize>,
 7698            replace_newest: bool,
 7699            auto_scroll: Option<Autoscroll>,
 7700            cx: &mut ViewContext<Editor>,
 7701        ) {
 7702            this.unfold_ranges([range.clone()], false, true, cx);
 7703            this.change_selections(auto_scroll, cx, |s| {
 7704                if replace_newest {
 7705                    s.delete(s.newest_anchor().id);
 7706                }
 7707                s.insert_range(range.clone());
 7708            });
 7709        }
 7710
 7711        let buffer = &display_map.buffer_snapshot;
 7712        let mut selections = self.selections.all::<usize>(cx);
 7713        if let Some(mut select_next_state) = self.select_next_state.take() {
 7714            let query = &select_next_state.query;
 7715            if !select_next_state.done {
 7716                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7717                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7718                let mut next_selected_range = None;
 7719
 7720                let bytes_after_last_selection =
 7721                    buffer.bytes_in_range(last_selection.end..buffer.len());
 7722                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 7723                let query_matches = query
 7724                    .stream_find_iter(bytes_after_last_selection)
 7725                    .map(|result| (last_selection.end, result))
 7726                    .chain(
 7727                        query
 7728                            .stream_find_iter(bytes_before_first_selection)
 7729                            .map(|result| (0, result)),
 7730                    );
 7731
 7732                for (start_offset, query_match) in query_matches {
 7733                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7734                    let offset_range =
 7735                        start_offset + query_match.start()..start_offset + query_match.end();
 7736                    let display_range = offset_range.start.to_display_point(&display_map)
 7737                        ..offset_range.end.to_display_point(&display_map);
 7738
 7739                    if !select_next_state.wordwise
 7740                        || (!movement::is_inside_word(&display_map, display_range.start)
 7741                            && !movement::is_inside_word(&display_map, display_range.end))
 7742                    {
 7743                        // TODO: This is n^2, because we might check all the selections
 7744                        if !selections
 7745                            .iter()
 7746                            .any(|selection| selection.range().overlaps(&offset_range))
 7747                        {
 7748                            next_selected_range = Some(offset_range);
 7749                            break;
 7750                        }
 7751                    }
 7752                }
 7753
 7754                if let Some(next_selected_range) = next_selected_range {
 7755                    select_next_match_ranges(
 7756                        self,
 7757                        next_selected_range,
 7758                        replace_newest,
 7759                        autoscroll,
 7760                        cx,
 7761                    );
 7762                } else {
 7763                    select_next_state.done = true;
 7764                }
 7765            }
 7766
 7767            self.select_next_state = Some(select_next_state);
 7768        } else {
 7769            let mut only_carets = true;
 7770            let mut same_text_selected = true;
 7771            let mut selected_text = None;
 7772
 7773            let mut selections_iter = selections.iter().peekable();
 7774            while let Some(selection) = selections_iter.next() {
 7775                if selection.start != selection.end {
 7776                    only_carets = false;
 7777                }
 7778
 7779                if same_text_selected {
 7780                    if selected_text.is_none() {
 7781                        selected_text =
 7782                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 7783                    }
 7784
 7785                    if let Some(next_selection) = selections_iter.peek() {
 7786                        if next_selection.range().len() == selection.range().len() {
 7787                            let next_selected_text = buffer
 7788                                .text_for_range(next_selection.range())
 7789                                .collect::<String>();
 7790                            if Some(next_selected_text) != selected_text {
 7791                                same_text_selected = false;
 7792                                selected_text = None;
 7793                            }
 7794                        } else {
 7795                            same_text_selected = false;
 7796                            selected_text = None;
 7797                        }
 7798                    }
 7799                }
 7800            }
 7801
 7802            if only_carets {
 7803                for selection in &mut selections {
 7804                    let word_range = movement::surrounding_word(
 7805                        &display_map,
 7806                        selection.start.to_display_point(&display_map),
 7807                    );
 7808                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 7809                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 7810                    selection.goal = SelectionGoal::None;
 7811                    selection.reversed = false;
 7812                    select_next_match_ranges(
 7813                        self,
 7814                        selection.start..selection.end,
 7815                        replace_newest,
 7816                        autoscroll,
 7817                        cx,
 7818                    );
 7819                }
 7820
 7821                if selections.len() == 1 {
 7822                    let selection = selections
 7823                        .last()
 7824                        .expect("ensured that there's only one selection");
 7825                    let query = buffer
 7826                        .text_for_range(selection.start..selection.end)
 7827                        .collect::<String>();
 7828                    let is_empty = query.is_empty();
 7829                    let select_state = SelectNextState {
 7830                        query: AhoCorasick::new(&[query])?,
 7831                        wordwise: true,
 7832                        done: is_empty,
 7833                    };
 7834                    self.select_next_state = Some(select_state);
 7835                } else {
 7836                    self.select_next_state = None;
 7837                }
 7838            } else if let Some(selected_text) = selected_text {
 7839                self.select_next_state = Some(SelectNextState {
 7840                    query: AhoCorasick::new(&[selected_text])?,
 7841                    wordwise: false,
 7842                    done: false,
 7843                });
 7844                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 7845            }
 7846        }
 7847        Ok(())
 7848    }
 7849
 7850    pub fn select_all_matches(
 7851        &mut self,
 7852        _action: &SelectAllMatches,
 7853        cx: &mut ViewContext<Self>,
 7854    ) -> Result<()> {
 7855        self.push_to_selection_history();
 7856        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7857
 7858        self.select_next_match_internal(&display_map, false, None, cx)?;
 7859        let Some(select_next_state) = self.select_next_state.as_mut() else {
 7860            return Ok(());
 7861        };
 7862        if select_next_state.done {
 7863            return Ok(());
 7864        }
 7865
 7866        let mut new_selections = self.selections.all::<usize>(cx);
 7867
 7868        let buffer = &display_map.buffer_snapshot;
 7869        let query_matches = select_next_state
 7870            .query
 7871            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 7872
 7873        for query_match in query_matches {
 7874            let query_match = query_match.unwrap(); // can only fail due to I/O
 7875            let offset_range = query_match.start()..query_match.end();
 7876            let display_range = offset_range.start.to_display_point(&display_map)
 7877                ..offset_range.end.to_display_point(&display_map);
 7878
 7879            if !select_next_state.wordwise
 7880                || (!movement::is_inside_word(&display_map, display_range.start)
 7881                    && !movement::is_inside_word(&display_map, display_range.end))
 7882            {
 7883                self.selections.change_with(cx, |selections| {
 7884                    new_selections.push(Selection {
 7885                        id: selections.new_selection_id(),
 7886                        start: offset_range.start,
 7887                        end: offset_range.end,
 7888                        reversed: false,
 7889                        goal: SelectionGoal::None,
 7890                    });
 7891                });
 7892            }
 7893        }
 7894
 7895        new_selections.sort_by_key(|selection| selection.start);
 7896        let mut ix = 0;
 7897        while ix + 1 < new_selections.len() {
 7898            let current_selection = &new_selections[ix];
 7899            let next_selection = &new_selections[ix + 1];
 7900            if current_selection.range().overlaps(&next_selection.range()) {
 7901                if current_selection.id < next_selection.id {
 7902                    new_selections.remove(ix + 1);
 7903                } else {
 7904                    new_selections.remove(ix);
 7905                }
 7906            } else {
 7907                ix += 1;
 7908            }
 7909        }
 7910
 7911        select_next_state.done = true;
 7912        self.unfold_ranges(
 7913            new_selections.iter().map(|selection| selection.range()),
 7914            false,
 7915            false,
 7916            cx,
 7917        );
 7918        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 7919            selections.select(new_selections)
 7920        });
 7921
 7922        Ok(())
 7923    }
 7924
 7925    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 7926        self.push_to_selection_history();
 7927        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7928        self.select_next_match_internal(
 7929            &display_map,
 7930            action.replace_newest,
 7931            Some(Autoscroll::newest()),
 7932            cx,
 7933        )?;
 7934        Ok(())
 7935    }
 7936
 7937    pub fn select_previous(
 7938        &mut self,
 7939        action: &SelectPrevious,
 7940        cx: &mut ViewContext<Self>,
 7941    ) -> Result<()> {
 7942        self.push_to_selection_history();
 7943        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7944        let buffer = &display_map.buffer_snapshot;
 7945        let mut selections = self.selections.all::<usize>(cx);
 7946        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 7947            let query = &select_prev_state.query;
 7948            if !select_prev_state.done {
 7949                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 7950                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 7951                let mut next_selected_range = None;
 7952                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 7953                let bytes_before_last_selection =
 7954                    buffer.reversed_bytes_in_range(0..last_selection.start);
 7955                let bytes_after_first_selection =
 7956                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 7957                let query_matches = query
 7958                    .stream_find_iter(bytes_before_last_selection)
 7959                    .map(|result| (last_selection.start, result))
 7960                    .chain(
 7961                        query
 7962                            .stream_find_iter(bytes_after_first_selection)
 7963                            .map(|result| (buffer.len(), result)),
 7964                    );
 7965                for (end_offset, query_match) in query_matches {
 7966                    let query_match = query_match.unwrap(); // can only fail due to I/O
 7967                    let offset_range =
 7968                        end_offset - query_match.end()..end_offset - query_match.start();
 7969                    let display_range = offset_range.start.to_display_point(&display_map)
 7970                        ..offset_range.end.to_display_point(&display_map);
 7971
 7972                    if !select_prev_state.wordwise
 7973                        || (!movement::is_inside_word(&display_map, display_range.start)
 7974                            && !movement::is_inside_word(&display_map, display_range.end))
 7975                    {
 7976                        next_selected_range = Some(offset_range);
 7977                        break;
 7978                    }
 7979                }
 7980
 7981                if let Some(next_selected_range) = next_selected_range {
 7982                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
 7983                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 7984                        if action.replace_newest {
 7985                            s.delete(s.newest_anchor().id);
 7986                        }
 7987                        s.insert_range(next_selected_range);
 7988                    });
 7989                } else {
 7990                    select_prev_state.done = true;
 7991                }
 7992            }
 7993
 7994            self.select_prev_state = Some(select_prev_state);
 7995        } else {
 7996            let mut only_carets = true;
 7997            let mut same_text_selected = true;
 7998            let mut selected_text = None;
 7999
 8000            let mut selections_iter = selections.iter().peekable();
 8001            while let Some(selection) = selections_iter.next() {
 8002                if selection.start != selection.end {
 8003                    only_carets = false;
 8004                }
 8005
 8006                if same_text_selected {
 8007                    if selected_text.is_none() {
 8008                        selected_text =
 8009                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8010                    }
 8011
 8012                    if let Some(next_selection) = selections_iter.peek() {
 8013                        if next_selection.range().len() == selection.range().len() {
 8014                            let next_selected_text = buffer
 8015                                .text_for_range(next_selection.range())
 8016                                .collect::<String>();
 8017                            if Some(next_selected_text) != selected_text {
 8018                                same_text_selected = false;
 8019                                selected_text = None;
 8020                            }
 8021                        } else {
 8022                            same_text_selected = false;
 8023                            selected_text = None;
 8024                        }
 8025                    }
 8026                }
 8027            }
 8028
 8029            if only_carets {
 8030                for selection in &mut selections {
 8031                    let word_range = movement::surrounding_word(
 8032                        &display_map,
 8033                        selection.start.to_display_point(&display_map),
 8034                    );
 8035                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8036                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8037                    selection.goal = SelectionGoal::None;
 8038                    selection.reversed = false;
 8039                }
 8040                if selections.len() == 1 {
 8041                    let selection = selections
 8042                        .last()
 8043                        .expect("ensured that there's only one selection");
 8044                    let query = buffer
 8045                        .text_for_range(selection.start..selection.end)
 8046                        .collect::<String>();
 8047                    let is_empty = query.is_empty();
 8048                    let select_state = SelectNextState {
 8049                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8050                        wordwise: true,
 8051                        done: is_empty,
 8052                    };
 8053                    self.select_prev_state = Some(select_state);
 8054                } else {
 8055                    self.select_prev_state = None;
 8056                }
 8057
 8058                self.unfold_ranges(
 8059                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8060                    false,
 8061                    true,
 8062                    cx,
 8063                );
 8064                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8065                    s.select(selections);
 8066                });
 8067            } else if let Some(selected_text) = selected_text {
 8068                self.select_prev_state = Some(SelectNextState {
 8069                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8070                    wordwise: false,
 8071                    done: false,
 8072                });
 8073                self.select_previous(action, cx)?;
 8074            }
 8075        }
 8076        Ok(())
 8077    }
 8078
 8079    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8080        let text_layout_details = &self.text_layout_details(cx);
 8081        self.transact(cx, |this, cx| {
 8082            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8083            let mut edits = Vec::new();
 8084            let mut selection_edit_ranges = Vec::new();
 8085            let mut last_toggled_row = None;
 8086            let snapshot = this.buffer.read(cx).read(cx);
 8087            let empty_str: Arc<str> = Arc::default();
 8088            let mut suffixes_inserted = Vec::new();
 8089
 8090            fn comment_prefix_range(
 8091                snapshot: &MultiBufferSnapshot,
 8092                row: MultiBufferRow,
 8093                comment_prefix: &str,
 8094                comment_prefix_whitespace: &str,
 8095            ) -> Range<Point> {
 8096                let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
 8097
 8098                let mut line_bytes = snapshot
 8099                    .bytes_in_range(start..snapshot.max_point())
 8100                    .flatten()
 8101                    .copied();
 8102
 8103                // If this line currently begins with the line comment prefix, then record
 8104                // the range containing the prefix.
 8105                if line_bytes
 8106                    .by_ref()
 8107                    .take(comment_prefix.len())
 8108                    .eq(comment_prefix.bytes())
 8109                {
 8110                    // Include any whitespace that matches the comment prefix.
 8111                    let matching_whitespace_len = line_bytes
 8112                        .zip(comment_prefix_whitespace.bytes())
 8113                        .take_while(|(a, b)| a == b)
 8114                        .count() as u32;
 8115                    let end = Point::new(
 8116                        start.row,
 8117                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8118                    );
 8119                    start..end
 8120                } else {
 8121                    start..start
 8122                }
 8123            }
 8124
 8125            fn comment_suffix_range(
 8126                snapshot: &MultiBufferSnapshot,
 8127                row: MultiBufferRow,
 8128                comment_suffix: &str,
 8129                comment_suffix_has_leading_space: bool,
 8130            ) -> Range<Point> {
 8131                let end = Point::new(row.0, snapshot.line_len(row));
 8132                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8133
 8134                let mut line_end_bytes = snapshot
 8135                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8136                    .flatten()
 8137                    .copied();
 8138
 8139                let leading_space_len = if suffix_start_column > 0
 8140                    && line_end_bytes.next() == Some(b' ')
 8141                    && comment_suffix_has_leading_space
 8142                {
 8143                    1
 8144                } else {
 8145                    0
 8146                };
 8147
 8148                // If this line currently begins with the line comment prefix, then record
 8149                // the range containing the prefix.
 8150                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8151                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8152                    start..end
 8153                } else {
 8154                    end..end
 8155                }
 8156            }
 8157
 8158            // TODO: Handle selections that cross excerpts
 8159            for selection in &mut selections {
 8160                let start_column = snapshot
 8161                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8162                    .len;
 8163                let language = if let Some(language) =
 8164                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8165                {
 8166                    language
 8167                } else {
 8168                    continue;
 8169                };
 8170
 8171                selection_edit_ranges.clear();
 8172
 8173                // If multiple selections contain a given row, avoid processing that
 8174                // row more than once.
 8175                let mut start_row = MultiBufferRow(selection.start.row);
 8176                if last_toggled_row == Some(start_row) {
 8177                    start_row = start_row.next_row();
 8178                }
 8179                let end_row =
 8180                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8181                        MultiBufferRow(selection.end.row - 1)
 8182                    } else {
 8183                        MultiBufferRow(selection.end.row)
 8184                    };
 8185                last_toggled_row = Some(end_row);
 8186
 8187                if start_row > end_row {
 8188                    continue;
 8189                }
 8190
 8191                // If the language has line comments, toggle those.
 8192                let full_comment_prefixes = language.line_comment_prefixes();
 8193                if !full_comment_prefixes.is_empty() {
 8194                    let first_prefix = full_comment_prefixes
 8195                        .first()
 8196                        .expect("prefixes is non-empty");
 8197                    let prefix_trimmed_lengths = full_comment_prefixes
 8198                        .iter()
 8199                        .map(|p| p.trim_end_matches(' ').len())
 8200                        .collect::<SmallVec<[usize; 4]>>();
 8201
 8202                    let mut all_selection_lines_are_comments = true;
 8203
 8204                    for row in start_row.0..=end_row.0 {
 8205                        let row = MultiBufferRow(row);
 8206                        if start_row < end_row && snapshot.is_line_blank(row) {
 8207                            continue;
 8208                        }
 8209
 8210                        let prefix_range = full_comment_prefixes
 8211                            .iter()
 8212                            .zip(prefix_trimmed_lengths.iter().copied())
 8213                            .map(|(prefix, trimmed_prefix_len)| {
 8214                                comment_prefix_range(
 8215                                    snapshot.deref(),
 8216                                    row,
 8217                                    &prefix[..trimmed_prefix_len],
 8218                                    &prefix[trimmed_prefix_len..],
 8219                                )
 8220                            })
 8221                            .max_by_key(|range| range.end.column - range.start.column)
 8222                            .expect("prefixes is non-empty");
 8223
 8224                        if prefix_range.is_empty() {
 8225                            all_selection_lines_are_comments = false;
 8226                        }
 8227
 8228                        selection_edit_ranges.push(prefix_range);
 8229                    }
 8230
 8231                    if all_selection_lines_are_comments {
 8232                        edits.extend(
 8233                            selection_edit_ranges
 8234                                .iter()
 8235                                .cloned()
 8236                                .map(|range| (range, empty_str.clone())),
 8237                        );
 8238                    } else {
 8239                        let min_column = selection_edit_ranges
 8240                            .iter()
 8241                            .map(|range| range.start.column)
 8242                            .min()
 8243                            .unwrap_or(0);
 8244                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8245                            let position = Point::new(range.start.row, min_column);
 8246                            (position..position, first_prefix.clone())
 8247                        }));
 8248                    }
 8249                } else if let Some((full_comment_prefix, comment_suffix)) =
 8250                    language.block_comment_delimiters()
 8251                {
 8252                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8253                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8254                    let prefix_range = comment_prefix_range(
 8255                        snapshot.deref(),
 8256                        start_row,
 8257                        comment_prefix,
 8258                        comment_prefix_whitespace,
 8259                    );
 8260                    let suffix_range = comment_suffix_range(
 8261                        snapshot.deref(),
 8262                        end_row,
 8263                        comment_suffix.trim_start_matches(' '),
 8264                        comment_suffix.starts_with(' '),
 8265                    );
 8266
 8267                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8268                        edits.push((
 8269                            prefix_range.start..prefix_range.start,
 8270                            full_comment_prefix.clone(),
 8271                        ));
 8272                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8273                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8274                    } else {
 8275                        edits.push((prefix_range, empty_str.clone()));
 8276                        edits.push((suffix_range, empty_str.clone()));
 8277                    }
 8278                } else {
 8279                    continue;
 8280                }
 8281            }
 8282
 8283            drop(snapshot);
 8284            this.buffer.update(cx, |buffer, cx| {
 8285                buffer.edit(edits, None, cx);
 8286            });
 8287
 8288            // Adjust selections so that they end before any comment suffixes that
 8289            // were inserted.
 8290            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8291            let mut selections = this.selections.all::<Point>(cx);
 8292            let snapshot = this.buffer.read(cx).read(cx);
 8293            for selection in &mut selections {
 8294                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8295                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8296                        Ordering::Less => {
 8297                            suffixes_inserted.next();
 8298                            continue;
 8299                        }
 8300                        Ordering::Greater => break,
 8301                        Ordering::Equal => {
 8302                            if selection.end.column == snapshot.line_len(row) {
 8303                                if selection.is_empty() {
 8304                                    selection.start.column -= suffix_len as u32;
 8305                                }
 8306                                selection.end.column -= suffix_len as u32;
 8307                            }
 8308                            break;
 8309                        }
 8310                    }
 8311                }
 8312            }
 8313
 8314            drop(snapshot);
 8315            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8316
 8317            let selections = this.selections.all::<Point>(cx);
 8318            let selections_on_single_row = selections.windows(2).all(|selections| {
 8319                selections[0].start.row == selections[1].start.row
 8320                    && selections[0].end.row == selections[1].end.row
 8321                    && selections[0].start.row == selections[0].end.row
 8322            });
 8323            let selections_selecting = selections
 8324                .iter()
 8325                .any(|selection| selection.start != selection.end);
 8326            let advance_downwards = action.advance_downwards
 8327                && selections_on_single_row
 8328                && !selections_selecting
 8329                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8330
 8331            if advance_downwards {
 8332                let snapshot = this.buffer.read(cx).snapshot(cx);
 8333
 8334                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8335                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8336                        let mut point = display_point.to_point(display_snapshot);
 8337                        point.row += 1;
 8338                        point = snapshot.clip_point(point, Bias::Left);
 8339                        let display_point = point.to_display_point(display_snapshot);
 8340                        let goal = SelectionGoal::HorizontalPosition(
 8341                            display_snapshot
 8342                                .x_for_display_point(display_point, &text_layout_details)
 8343                                .into(),
 8344                        );
 8345                        (display_point, goal)
 8346                    })
 8347                });
 8348            }
 8349        });
 8350    }
 8351
 8352    pub fn select_enclosing_symbol(
 8353        &mut self,
 8354        _: &SelectEnclosingSymbol,
 8355        cx: &mut ViewContext<Self>,
 8356    ) {
 8357        let buffer = self.buffer.read(cx).snapshot(cx);
 8358        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8359
 8360        fn update_selection(
 8361            selection: &Selection<usize>,
 8362            buffer_snap: &MultiBufferSnapshot,
 8363        ) -> Option<Selection<usize>> {
 8364            let cursor = selection.head();
 8365            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8366            for symbol in symbols.iter().rev() {
 8367                let start = symbol.range.start.to_offset(&buffer_snap);
 8368                let end = symbol.range.end.to_offset(&buffer_snap);
 8369                let new_range = start..end;
 8370                if start < selection.start || end > selection.end {
 8371                    return Some(Selection {
 8372                        id: selection.id,
 8373                        start: new_range.start,
 8374                        end: new_range.end,
 8375                        goal: SelectionGoal::None,
 8376                        reversed: selection.reversed,
 8377                    });
 8378                }
 8379            }
 8380            None
 8381        }
 8382
 8383        let mut selected_larger_symbol = false;
 8384        let new_selections = old_selections
 8385            .iter()
 8386            .map(|selection| match update_selection(selection, &buffer) {
 8387                Some(new_selection) => {
 8388                    if new_selection.range() != selection.range() {
 8389                        selected_larger_symbol = true;
 8390                    }
 8391                    new_selection
 8392                }
 8393                None => selection.clone(),
 8394            })
 8395            .collect::<Vec<_>>();
 8396
 8397        if selected_larger_symbol {
 8398            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8399                s.select(new_selections);
 8400            });
 8401        }
 8402    }
 8403
 8404    pub fn select_larger_syntax_node(
 8405        &mut self,
 8406        _: &SelectLargerSyntaxNode,
 8407        cx: &mut ViewContext<Self>,
 8408    ) {
 8409        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8410        let buffer = self.buffer.read(cx).snapshot(cx);
 8411        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8412
 8413        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8414        let mut selected_larger_node = false;
 8415        let new_selections = old_selections
 8416            .iter()
 8417            .map(|selection| {
 8418                let old_range = selection.start..selection.end;
 8419                let mut new_range = old_range.clone();
 8420                while let Some(containing_range) =
 8421                    buffer.range_for_syntax_ancestor(new_range.clone())
 8422                {
 8423                    new_range = containing_range;
 8424                    if !display_map.intersects_fold(new_range.start)
 8425                        && !display_map.intersects_fold(new_range.end)
 8426                    {
 8427                        break;
 8428                    }
 8429                }
 8430
 8431                selected_larger_node |= new_range != old_range;
 8432                Selection {
 8433                    id: selection.id,
 8434                    start: new_range.start,
 8435                    end: new_range.end,
 8436                    goal: SelectionGoal::None,
 8437                    reversed: selection.reversed,
 8438                }
 8439            })
 8440            .collect::<Vec<_>>();
 8441
 8442        if selected_larger_node {
 8443            stack.push(old_selections);
 8444            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8445                s.select(new_selections);
 8446            });
 8447        }
 8448        self.select_larger_syntax_node_stack = stack;
 8449    }
 8450
 8451    pub fn select_smaller_syntax_node(
 8452        &mut self,
 8453        _: &SelectSmallerSyntaxNode,
 8454        cx: &mut ViewContext<Self>,
 8455    ) {
 8456        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8457        if let Some(selections) = stack.pop() {
 8458            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8459                s.select(selections.to_vec());
 8460            });
 8461        }
 8462        self.select_larger_syntax_node_stack = stack;
 8463    }
 8464
 8465    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8466        if !EditorSettings::get_global(cx).gutter.runnables {
 8467            self.clear_tasks();
 8468            return Task::ready(());
 8469        }
 8470        let project = self.project.clone();
 8471        cx.spawn(|this, mut cx| async move {
 8472            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8473                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8474            }) else {
 8475                return;
 8476            };
 8477
 8478            let Some(project) = project else {
 8479                return;
 8480            };
 8481
 8482            let hide_runnables = project
 8483                .update(&mut cx, |project, cx| {
 8484                    // Do not display any test indicators in non-dev server remote projects.
 8485                    project.is_remote() && project.ssh_connection_string(cx).is_none()
 8486                })
 8487                .unwrap_or(true);
 8488            if hide_runnables {
 8489                return;
 8490            }
 8491            let new_rows =
 8492                cx.background_executor()
 8493                    .spawn({
 8494                        let snapshot = display_snapshot.clone();
 8495                        async move {
 8496                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8497                        }
 8498                    })
 8499                    .await;
 8500            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8501
 8502            this.update(&mut cx, |this, _| {
 8503                this.clear_tasks();
 8504                for (key, value) in rows {
 8505                    this.insert_tasks(key, value);
 8506                }
 8507            })
 8508            .ok();
 8509        })
 8510    }
 8511    fn fetch_runnable_ranges(
 8512        snapshot: &DisplaySnapshot,
 8513        range: Range<Anchor>,
 8514    ) -> Vec<language::RunnableRange> {
 8515        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8516    }
 8517
 8518    fn runnable_rows(
 8519        project: Model<Project>,
 8520        snapshot: DisplaySnapshot,
 8521        runnable_ranges: Vec<RunnableRange>,
 8522        mut cx: AsyncWindowContext,
 8523    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8524        runnable_ranges
 8525            .into_iter()
 8526            .filter_map(|mut runnable| {
 8527                let tasks = cx
 8528                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8529                    .ok()?;
 8530                if tasks.is_empty() {
 8531                    return None;
 8532                }
 8533
 8534                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8535
 8536                let row = snapshot
 8537                    .buffer_snapshot
 8538                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8539                    .1
 8540                    .start
 8541                    .row;
 8542
 8543                let context_range =
 8544                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8545                Some((
 8546                    (runnable.buffer_id, row),
 8547                    RunnableTasks {
 8548                        templates: tasks,
 8549                        offset: MultiBufferOffset(runnable.run_range.start),
 8550                        context_range,
 8551                        column: point.column,
 8552                        extra_variables: runnable.extra_captures,
 8553                    },
 8554                ))
 8555            })
 8556            .collect()
 8557    }
 8558
 8559    fn templates_with_tags(
 8560        project: &Model<Project>,
 8561        runnable: &mut Runnable,
 8562        cx: &WindowContext<'_>,
 8563    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8564        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8565            let (worktree_id, file) = project
 8566                .buffer_for_id(runnable.buffer, cx)
 8567                .and_then(|buffer| buffer.read(cx).file())
 8568                .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
 8569                .unzip();
 8570
 8571            (project.task_inventory().clone(), worktree_id, file)
 8572        });
 8573
 8574        let inventory = inventory.read(cx);
 8575        let tags = mem::take(&mut runnable.tags);
 8576        let mut tags: Vec<_> = tags
 8577            .into_iter()
 8578            .flat_map(|tag| {
 8579                let tag = tag.0.clone();
 8580                inventory
 8581                    .list_tasks(
 8582                        file.clone(),
 8583                        Some(runnable.language.clone()),
 8584                        worktree_id,
 8585                        cx,
 8586                    )
 8587                    .into_iter()
 8588                    .filter(move |(_, template)| {
 8589                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8590                    })
 8591            })
 8592            .sorted_by_key(|(kind, _)| kind.to_owned())
 8593            .collect();
 8594        if let Some((leading_tag_source, _)) = tags.first() {
 8595            // Strongest source wins; if we have worktree tag binding, prefer that to
 8596            // global and language bindings;
 8597            // if we have a global binding, prefer that to language binding.
 8598            let first_mismatch = tags
 8599                .iter()
 8600                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8601            if let Some(index) = first_mismatch {
 8602                tags.truncate(index);
 8603            }
 8604        }
 8605
 8606        tags
 8607    }
 8608
 8609    pub fn move_to_enclosing_bracket(
 8610        &mut self,
 8611        _: &MoveToEnclosingBracket,
 8612        cx: &mut ViewContext<Self>,
 8613    ) {
 8614        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8615            s.move_offsets_with(|snapshot, selection| {
 8616                let Some(enclosing_bracket_ranges) =
 8617                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8618                else {
 8619                    return;
 8620                };
 8621
 8622                let mut best_length = usize::MAX;
 8623                let mut best_inside = false;
 8624                let mut best_in_bracket_range = false;
 8625                let mut best_destination = None;
 8626                for (open, close) in enclosing_bracket_ranges {
 8627                    let close = close.to_inclusive();
 8628                    let length = close.end() - open.start;
 8629                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8630                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8631                        || close.contains(&selection.head());
 8632
 8633                    // If best is next to a bracket and current isn't, skip
 8634                    if !in_bracket_range && best_in_bracket_range {
 8635                        continue;
 8636                    }
 8637
 8638                    // Prefer smaller lengths unless best is inside and current isn't
 8639                    if length > best_length && (best_inside || !inside) {
 8640                        continue;
 8641                    }
 8642
 8643                    best_length = length;
 8644                    best_inside = inside;
 8645                    best_in_bracket_range = in_bracket_range;
 8646                    best_destination = Some(
 8647                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8648                            if inside {
 8649                                open.end
 8650                            } else {
 8651                                open.start
 8652                            }
 8653                        } else {
 8654                            if inside {
 8655                                *close.start()
 8656                            } else {
 8657                                *close.end()
 8658                            }
 8659                        },
 8660                    );
 8661                }
 8662
 8663                if let Some(destination) = best_destination {
 8664                    selection.collapse_to(destination, SelectionGoal::None);
 8665                }
 8666            })
 8667        });
 8668    }
 8669
 8670    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 8671        self.end_selection(cx);
 8672        self.selection_history.mode = SelectionHistoryMode::Undoing;
 8673        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 8674            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8675            self.select_next_state = entry.select_next_state;
 8676            self.select_prev_state = entry.select_prev_state;
 8677            self.add_selections_state = entry.add_selections_state;
 8678            self.request_autoscroll(Autoscroll::newest(), cx);
 8679        }
 8680        self.selection_history.mode = SelectionHistoryMode::Normal;
 8681    }
 8682
 8683    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 8684        self.end_selection(cx);
 8685        self.selection_history.mode = SelectionHistoryMode::Redoing;
 8686        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 8687            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 8688            self.select_next_state = entry.select_next_state;
 8689            self.select_prev_state = entry.select_prev_state;
 8690            self.add_selections_state = entry.add_selections_state;
 8691            self.request_autoscroll(Autoscroll::newest(), cx);
 8692        }
 8693        self.selection_history.mode = SelectionHistoryMode::Normal;
 8694    }
 8695
 8696    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 8697        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 8698    }
 8699
 8700    pub fn expand_excerpts_down(
 8701        &mut self,
 8702        action: &ExpandExcerptsDown,
 8703        cx: &mut ViewContext<Self>,
 8704    ) {
 8705        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 8706    }
 8707
 8708    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 8709        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 8710    }
 8711
 8712    pub fn expand_excerpts_for_direction(
 8713        &mut self,
 8714        lines: u32,
 8715        direction: ExpandExcerptDirection,
 8716        cx: &mut ViewContext<Self>,
 8717    ) {
 8718        let selections = self.selections.disjoint_anchors();
 8719
 8720        let lines = if lines == 0 {
 8721            EditorSettings::get_global(cx).expand_excerpt_lines
 8722        } else {
 8723            lines
 8724        };
 8725
 8726        self.buffer.update(cx, |buffer, cx| {
 8727            buffer.expand_excerpts(
 8728                selections
 8729                    .into_iter()
 8730                    .map(|selection| selection.head().excerpt_id)
 8731                    .dedup(),
 8732                lines,
 8733                direction,
 8734                cx,
 8735            )
 8736        })
 8737    }
 8738
 8739    pub fn expand_excerpt(
 8740        &mut self,
 8741        excerpt: ExcerptId,
 8742        direction: ExpandExcerptDirection,
 8743        cx: &mut ViewContext<Self>,
 8744    ) {
 8745        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 8746        self.buffer.update(cx, |buffer, cx| {
 8747            buffer.expand_excerpts([excerpt], lines, direction, cx)
 8748        })
 8749    }
 8750
 8751    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 8752        self.go_to_diagnostic_impl(Direction::Next, cx)
 8753    }
 8754
 8755    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 8756        self.go_to_diagnostic_impl(Direction::Prev, cx)
 8757    }
 8758
 8759    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 8760        let buffer = self.buffer.read(cx).snapshot(cx);
 8761        let selection = self.selections.newest::<usize>(cx);
 8762
 8763        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 8764        if direction == Direction::Next {
 8765            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 8766                let (group_id, jump_to) = popover.activation_info();
 8767                if self.activate_diagnostics(group_id, cx) {
 8768                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8769                        let mut new_selection = s.newest_anchor().clone();
 8770                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 8771                        s.select_anchors(vec![new_selection.clone()]);
 8772                    });
 8773                }
 8774                return;
 8775            }
 8776        }
 8777
 8778        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 8779            active_diagnostics
 8780                .primary_range
 8781                .to_offset(&buffer)
 8782                .to_inclusive()
 8783        });
 8784        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 8785            if active_primary_range.contains(&selection.head()) {
 8786                *active_primary_range.start()
 8787            } else {
 8788                selection.head()
 8789            }
 8790        } else {
 8791            selection.head()
 8792        };
 8793        let snapshot = self.snapshot(cx);
 8794        loop {
 8795            let diagnostics = if direction == Direction::Prev {
 8796                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 8797            } else {
 8798                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 8799            }
 8800            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 8801            let group = diagnostics
 8802                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 8803                // be sorted in a stable way
 8804                // skip until we are at current active diagnostic, if it exists
 8805                .skip_while(|entry| {
 8806                    (match direction {
 8807                        Direction::Prev => entry.range.start >= search_start,
 8808                        Direction::Next => entry.range.start <= search_start,
 8809                    }) && self
 8810                        .active_diagnostics
 8811                        .as_ref()
 8812                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 8813                })
 8814                .find_map(|entry| {
 8815                    if entry.diagnostic.is_primary
 8816                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 8817                        && !entry.range.is_empty()
 8818                        // if we match with the active diagnostic, skip it
 8819                        && Some(entry.diagnostic.group_id)
 8820                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 8821                    {
 8822                        Some((entry.range, entry.diagnostic.group_id))
 8823                    } else {
 8824                        None
 8825                    }
 8826                });
 8827
 8828            if let Some((primary_range, group_id)) = group {
 8829                if self.activate_diagnostics(group_id, cx) {
 8830                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8831                        s.select(vec![Selection {
 8832                            id: selection.id,
 8833                            start: primary_range.start,
 8834                            end: primary_range.start,
 8835                            reversed: false,
 8836                            goal: SelectionGoal::None,
 8837                        }]);
 8838                    });
 8839                }
 8840                break;
 8841            } else {
 8842                // Cycle around to the start of the buffer, potentially moving back to the start of
 8843                // the currently active diagnostic.
 8844                active_primary_range.take();
 8845                if direction == Direction::Prev {
 8846                    if search_start == buffer.len() {
 8847                        break;
 8848                    } else {
 8849                        search_start = buffer.len();
 8850                    }
 8851                } else if search_start == 0 {
 8852                    break;
 8853                } else {
 8854                    search_start = 0;
 8855                }
 8856            }
 8857        }
 8858    }
 8859
 8860    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 8861        let snapshot = self
 8862            .display_map
 8863            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8864        let selection = self.selections.newest::<Point>(cx);
 8865
 8866        if !self.seek_in_direction(
 8867            &snapshot,
 8868            selection.head(),
 8869            false,
 8870            snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8871                MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
 8872            ),
 8873            cx,
 8874        ) {
 8875            let wrapped_point = Point::zero();
 8876            self.seek_in_direction(
 8877                &snapshot,
 8878                wrapped_point,
 8879                true,
 8880                snapshot.buffer_snapshot.git_diff_hunks_in_range(
 8881                    MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
 8882                ),
 8883                cx,
 8884            );
 8885        }
 8886    }
 8887
 8888    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 8889        let snapshot = self
 8890            .display_map
 8891            .update(cx, |display_map, cx| display_map.snapshot(cx));
 8892        let selection = self.selections.newest::<Point>(cx);
 8893
 8894        if !self.seek_in_direction(
 8895            &snapshot,
 8896            selection.head(),
 8897            false,
 8898            snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8899                MultiBufferRow(0)..MultiBufferRow(selection.head().row),
 8900            ),
 8901            cx,
 8902        ) {
 8903            let wrapped_point = snapshot.buffer_snapshot.max_point();
 8904            self.seek_in_direction(
 8905                &snapshot,
 8906                wrapped_point,
 8907                true,
 8908                snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
 8909                    MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
 8910                ),
 8911                cx,
 8912            );
 8913        }
 8914    }
 8915
 8916    fn seek_in_direction(
 8917        &mut self,
 8918        snapshot: &DisplaySnapshot,
 8919        initial_point: Point,
 8920        is_wrapped: bool,
 8921        hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
 8922        cx: &mut ViewContext<Editor>,
 8923    ) -> bool {
 8924        let display_point = initial_point.to_display_point(snapshot);
 8925        let mut hunks = hunks
 8926            .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
 8927            .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
 8928            .dedup();
 8929
 8930        if let Some(hunk) = hunks.next() {
 8931            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8932                let row = hunk.start_display_row();
 8933                let point = DisplayPoint::new(row, 0);
 8934                s.select_display_ranges([point..point]);
 8935            });
 8936
 8937            true
 8938        } else {
 8939            false
 8940        }
 8941    }
 8942
 8943    pub fn go_to_definition(
 8944        &mut self,
 8945        _: &GoToDefinition,
 8946        cx: &mut ViewContext<Self>,
 8947    ) -> Task<Result<bool>> {
 8948        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx)
 8949    }
 8950
 8951    pub fn go_to_implementation(
 8952        &mut self,
 8953        _: &GoToImplementation,
 8954        cx: &mut ViewContext<Self>,
 8955    ) -> Task<Result<bool>> {
 8956        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 8957    }
 8958
 8959    pub fn go_to_implementation_split(
 8960        &mut self,
 8961        _: &GoToImplementationSplit,
 8962        cx: &mut ViewContext<Self>,
 8963    ) -> Task<Result<bool>> {
 8964        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 8965    }
 8966
 8967    pub fn go_to_type_definition(
 8968        &mut self,
 8969        _: &GoToTypeDefinition,
 8970        cx: &mut ViewContext<Self>,
 8971    ) -> Task<Result<bool>> {
 8972        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 8973    }
 8974
 8975    pub fn go_to_definition_split(
 8976        &mut self,
 8977        _: &GoToDefinitionSplit,
 8978        cx: &mut ViewContext<Self>,
 8979    ) -> Task<Result<bool>> {
 8980        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 8981    }
 8982
 8983    pub fn go_to_type_definition_split(
 8984        &mut self,
 8985        _: &GoToTypeDefinitionSplit,
 8986        cx: &mut ViewContext<Self>,
 8987    ) -> Task<Result<bool>> {
 8988        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 8989    }
 8990
 8991    fn go_to_definition_of_kind(
 8992        &mut self,
 8993        kind: GotoDefinitionKind,
 8994        split: bool,
 8995        cx: &mut ViewContext<Self>,
 8996    ) -> Task<Result<bool>> {
 8997        let Some(workspace) = self.workspace() else {
 8998            return Task::ready(Ok(false));
 8999        };
 9000        let buffer = self.buffer.read(cx);
 9001        let head = self.selections.newest::<usize>(cx).head();
 9002        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9003            text_anchor
 9004        } else {
 9005            return Task::ready(Ok(false));
 9006        };
 9007
 9008        let project = workspace.read(cx).project().clone();
 9009        let definitions = project.update(cx, |project, cx| match kind {
 9010            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
 9011            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
 9012            GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
 9013        });
 9014
 9015        cx.spawn(|editor, mut cx| async move {
 9016            let definitions = definitions.await?;
 9017            let navigated = editor
 9018                .update(&mut cx, |editor, cx| {
 9019                    editor.navigate_to_hover_links(
 9020                        Some(kind),
 9021                        definitions
 9022                            .into_iter()
 9023                            .filter(|location| {
 9024                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9025                            })
 9026                            .map(HoverLink::Text)
 9027                            .collect::<Vec<_>>(),
 9028                        split,
 9029                        cx,
 9030                    )
 9031                })?
 9032                .await?;
 9033            anyhow::Ok(navigated)
 9034        })
 9035    }
 9036
 9037    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9038        let position = self.selections.newest_anchor().head();
 9039        let Some((buffer, buffer_position)) =
 9040            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9041        else {
 9042            return;
 9043        };
 9044
 9045        cx.spawn(|editor, mut cx| async move {
 9046            if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
 9047                editor.update(&mut cx, |_, cx| {
 9048                    cx.open_url(&url);
 9049                })
 9050            } else {
 9051                Ok(())
 9052            }
 9053        })
 9054        .detach();
 9055    }
 9056
 9057    pub(crate) fn navigate_to_hover_links(
 9058        &mut self,
 9059        kind: Option<GotoDefinitionKind>,
 9060        mut definitions: Vec<HoverLink>,
 9061        split: bool,
 9062        cx: &mut ViewContext<Editor>,
 9063    ) -> Task<Result<bool>> {
 9064        // If there is one definition, just open it directly
 9065        if definitions.len() == 1 {
 9066            let definition = definitions.pop().unwrap();
 9067            let target_task = match definition {
 9068                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9069                HoverLink::InlayHint(lsp_location, server_id) => {
 9070                    self.compute_target_location(lsp_location, server_id, cx)
 9071                }
 9072                HoverLink::Url(url) => {
 9073                    cx.open_url(&url);
 9074                    Task::ready(Ok(None))
 9075                }
 9076            };
 9077            cx.spawn(|editor, mut cx| async move {
 9078                let target = target_task.await.context("target resolution task")?;
 9079                if let Some(target) = target {
 9080                    editor.update(&mut cx, |editor, cx| {
 9081                        let Some(workspace) = editor.workspace() else {
 9082                            return false;
 9083                        };
 9084                        let pane = workspace.read(cx).active_pane().clone();
 9085
 9086                        let range = target.range.to_offset(target.buffer.read(cx));
 9087                        let range = editor.range_for_match(&range);
 9088
 9089                        /// If select range has more than one line, we
 9090                        /// just point the cursor to range.start.
 9091                        fn check_multiline_range(
 9092                            buffer: &Buffer,
 9093                            range: Range<usize>,
 9094                        ) -> Range<usize> {
 9095                            if buffer.offset_to_point(range.start).row
 9096                                == buffer.offset_to_point(range.end).row
 9097                            {
 9098                                range
 9099                            } else {
 9100                                range.start..range.start
 9101                            }
 9102                        }
 9103
 9104                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9105                            let buffer = target.buffer.read(cx);
 9106                            let range = check_multiline_range(buffer, range);
 9107                            editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
 9108                                s.select_ranges([range]);
 9109                            });
 9110                        } else {
 9111                            cx.window_context().defer(move |cx| {
 9112                                let target_editor: View<Self> =
 9113                                    workspace.update(cx, |workspace, cx| {
 9114                                        let pane = if split {
 9115                                            workspace.adjacent_pane(cx)
 9116                                        } else {
 9117                                            workspace.active_pane().clone()
 9118                                        };
 9119
 9120                                        workspace.open_project_item(
 9121                                            pane,
 9122                                            target.buffer.clone(),
 9123                                            true,
 9124                                            true,
 9125                                            cx,
 9126                                        )
 9127                                    });
 9128                                target_editor.update(cx, |target_editor, cx| {
 9129                                    // When selecting a definition in a different buffer, disable the nav history
 9130                                    // to avoid creating a history entry at the previous cursor location.
 9131                                    pane.update(cx, |pane, _| pane.disable_history());
 9132                                    let buffer = target.buffer.read(cx);
 9133                                    let range = check_multiline_range(buffer, range);
 9134                                    target_editor.change_selections(
 9135                                        Some(Autoscroll::focused()),
 9136                                        cx,
 9137                                        |s| {
 9138                                            s.select_ranges([range]);
 9139                                        },
 9140                                    );
 9141                                    pane.update(cx, |pane, _| pane.enable_history());
 9142                                });
 9143                            });
 9144                        }
 9145                        true
 9146                    })
 9147                } else {
 9148                    Ok(false)
 9149                }
 9150            })
 9151        } else if !definitions.is_empty() {
 9152            let replica_id = self.replica_id(cx);
 9153            cx.spawn(|editor, mut cx| async move {
 9154                let (title, location_tasks, workspace) = editor
 9155                    .update(&mut cx, |editor, cx| {
 9156                        let tab_kind = match kind {
 9157                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9158                            _ => "Definitions",
 9159                        };
 9160                        let title = definitions
 9161                            .iter()
 9162                            .find_map(|definition| match definition {
 9163                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9164                                    let buffer = origin.buffer.read(cx);
 9165                                    format!(
 9166                                        "{} for {}",
 9167                                        tab_kind,
 9168                                        buffer
 9169                                            .text_for_range(origin.range.clone())
 9170                                            .collect::<String>()
 9171                                    )
 9172                                }),
 9173                                HoverLink::InlayHint(_, _) => None,
 9174                                HoverLink::Url(_) => None,
 9175                            })
 9176                            .unwrap_or(tab_kind.to_string());
 9177                        let location_tasks = definitions
 9178                            .into_iter()
 9179                            .map(|definition| match definition {
 9180                                HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
 9181                                HoverLink::InlayHint(lsp_location, server_id) => {
 9182                                    editor.compute_target_location(lsp_location, server_id, cx)
 9183                                }
 9184                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9185                            })
 9186                            .collect::<Vec<_>>();
 9187                        (title, location_tasks, editor.workspace().clone())
 9188                    })
 9189                    .context("location tasks preparation")?;
 9190
 9191                let locations = futures::future::join_all(location_tasks)
 9192                    .await
 9193                    .into_iter()
 9194                    .filter_map(|location| location.transpose())
 9195                    .collect::<Result<_>>()
 9196                    .context("location tasks")?;
 9197
 9198                let Some(workspace) = workspace else {
 9199                    return Ok(false);
 9200                };
 9201                let opened = workspace
 9202                    .update(&mut cx, |workspace, cx| {
 9203                        Self::open_locations_in_multibuffer(
 9204                            workspace, locations, replica_id, title, split, cx,
 9205                        )
 9206                    })
 9207                    .ok();
 9208
 9209                anyhow::Ok(opened.is_some())
 9210            })
 9211        } else {
 9212            Task::ready(Ok(false))
 9213        }
 9214    }
 9215
 9216    fn compute_target_location(
 9217        &self,
 9218        lsp_location: lsp::Location,
 9219        server_id: LanguageServerId,
 9220        cx: &mut ViewContext<Editor>,
 9221    ) -> Task<anyhow::Result<Option<Location>>> {
 9222        let Some(project) = self.project.clone() else {
 9223            return Task::Ready(Some(Ok(None)));
 9224        };
 9225
 9226        cx.spawn(move |editor, mut cx| async move {
 9227            let location_task = editor.update(&mut cx, |editor, cx| {
 9228                project.update(cx, |project, cx| {
 9229                    let language_server_name =
 9230                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
 9231                            project
 9232                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
 9233                                .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
 9234                        });
 9235                    language_server_name.map(|language_server_name| {
 9236                        project.open_local_buffer_via_lsp(
 9237                            lsp_location.uri.clone(),
 9238                            server_id,
 9239                            language_server_name,
 9240                            cx,
 9241                        )
 9242                    })
 9243                })
 9244            })?;
 9245            let location = match location_task {
 9246                Some(task) => Some({
 9247                    let target_buffer_handle = task.await.context("open local buffer")?;
 9248                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9249                        let target_start = target_buffer
 9250                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9251                        let target_end = target_buffer
 9252                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9253                        target_buffer.anchor_after(target_start)
 9254                            ..target_buffer.anchor_before(target_end)
 9255                    })?;
 9256                    Location {
 9257                        buffer: target_buffer_handle,
 9258                        range,
 9259                    }
 9260                }),
 9261                None => None,
 9262            };
 9263            Ok(location)
 9264        })
 9265    }
 9266
 9267    pub fn find_all_references(
 9268        &mut self,
 9269        _: &FindAllReferences,
 9270        cx: &mut ViewContext<Self>,
 9271    ) -> Option<Task<Result<()>>> {
 9272        let multi_buffer = self.buffer.read(cx);
 9273        let selection = self.selections.newest::<usize>(cx);
 9274        let head = selection.head();
 9275
 9276        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9277        let head_anchor = multi_buffer_snapshot.anchor_at(
 9278            head,
 9279            if head < selection.tail() {
 9280                Bias::Right
 9281            } else {
 9282                Bias::Left
 9283            },
 9284        );
 9285
 9286        match self
 9287            .find_all_references_task_sources
 9288            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9289        {
 9290            Ok(_) => {
 9291                log::info!(
 9292                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9293                );
 9294                return None;
 9295            }
 9296            Err(i) => {
 9297                self.find_all_references_task_sources.insert(i, head_anchor);
 9298            }
 9299        }
 9300
 9301        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9302        let replica_id = self.replica_id(cx);
 9303        let workspace = self.workspace()?;
 9304        let project = workspace.read(cx).project().clone();
 9305        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9306        Some(cx.spawn(|editor, mut cx| async move {
 9307            let _cleanup = defer({
 9308                let mut cx = cx.clone();
 9309                move || {
 9310                    let _ = editor.update(&mut cx, |editor, _| {
 9311                        if let Ok(i) =
 9312                            editor
 9313                                .find_all_references_task_sources
 9314                                .binary_search_by(|anchor| {
 9315                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9316                                })
 9317                        {
 9318                            editor.find_all_references_task_sources.remove(i);
 9319                        }
 9320                    });
 9321                }
 9322            });
 9323
 9324            let locations = references.await?;
 9325            if locations.is_empty() {
 9326                return anyhow::Ok(());
 9327            }
 9328
 9329            workspace.update(&mut cx, |workspace, cx| {
 9330                let title = locations
 9331                    .first()
 9332                    .as_ref()
 9333                    .map(|location| {
 9334                        let buffer = location.buffer.read(cx);
 9335                        format!(
 9336                            "References to `{}`",
 9337                            buffer
 9338                                .text_for_range(location.range.clone())
 9339                                .collect::<String>()
 9340                        )
 9341                    })
 9342                    .unwrap();
 9343                Self::open_locations_in_multibuffer(
 9344                    workspace, locations, replica_id, title, false, cx,
 9345                );
 9346            })
 9347        }))
 9348    }
 9349
 9350    /// Opens a multibuffer with the given project locations in it
 9351    pub fn open_locations_in_multibuffer(
 9352        workspace: &mut Workspace,
 9353        mut locations: Vec<Location>,
 9354        replica_id: ReplicaId,
 9355        title: String,
 9356        split: bool,
 9357        cx: &mut ViewContext<Workspace>,
 9358    ) {
 9359        // If there are multiple definitions, open them in a multibuffer
 9360        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9361        let mut locations = locations.into_iter().peekable();
 9362        let mut ranges_to_highlight = Vec::new();
 9363        let capability = workspace.project().read(cx).capability();
 9364
 9365        let excerpt_buffer = cx.new_model(|cx| {
 9366            let mut multibuffer = MultiBuffer::new(replica_id, capability);
 9367            while let Some(location) = locations.next() {
 9368                let buffer = location.buffer.read(cx);
 9369                let mut ranges_for_buffer = Vec::new();
 9370                let range = location.range.to_offset(buffer);
 9371                ranges_for_buffer.push(range.clone());
 9372
 9373                while let Some(next_location) = locations.peek() {
 9374                    if next_location.buffer == location.buffer {
 9375                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9376                        locations.next();
 9377                    } else {
 9378                        break;
 9379                    }
 9380                }
 9381
 9382                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9383                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9384                    location.buffer.clone(),
 9385                    ranges_for_buffer,
 9386                    DEFAULT_MULTIBUFFER_CONTEXT,
 9387                    cx,
 9388                ))
 9389            }
 9390
 9391            multibuffer.with_title(title)
 9392        });
 9393
 9394        let editor = cx.new_view(|cx| {
 9395            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9396        });
 9397        editor.update(cx, |editor, cx| {
 9398            if let Some(first_range) = ranges_to_highlight.first() {
 9399                editor.change_selections(None, cx, |selections| {
 9400                    selections.clear_disjoint();
 9401                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9402                });
 9403            }
 9404            editor.highlight_background::<Self>(
 9405                &ranges_to_highlight,
 9406                |theme| theme.editor_highlighted_line_background,
 9407                cx,
 9408            );
 9409        });
 9410
 9411        let item = Box::new(editor);
 9412        let item_id = item.item_id();
 9413
 9414        if split {
 9415            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9416        } else {
 9417            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9418                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9419                    pane.close_current_preview_item(cx)
 9420                } else {
 9421                    None
 9422                }
 9423            });
 9424            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9425        }
 9426        workspace.active_pane().update(cx, |pane, cx| {
 9427            pane.set_preview_item_id(Some(item_id), cx);
 9428        });
 9429    }
 9430
 9431    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9432        use language::ToOffset as _;
 9433
 9434        let project = self.project.clone()?;
 9435        let selection = self.selections.newest_anchor().clone();
 9436        let (cursor_buffer, cursor_buffer_position) = self
 9437            .buffer
 9438            .read(cx)
 9439            .text_anchor_for_position(selection.head(), cx)?;
 9440        let (tail_buffer, cursor_buffer_position_end) = self
 9441            .buffer
 9442            .read(cx)
 9443            .text_anchor_for_position(selection.tail(), cx)?;
 9444        if tail_buffer != cursor_buffer {
 9445            return None;
 9446        }
 9447
 9448        let snapshot = cursor_buffer.read(cx).snapshot();
 9449        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9450        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9451        let prepare_rename = project.update(cx, |project, cx| {
 9452            project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
 9453        });
 9454        drop(snapshot);
 9455
 9456        Some(cx.spawn(|this, mut cx| async move {
 9457            let rename_range = if let Some(range) = prepare_rename.await? {
 9458                Some(range)
 9459            } else {
 9460                this.update(&mut cx, |this, cx| {
 9461                    let buffer = this.buffer.read(cx).snapshot(cx);
 9462                    let mut buffer_highlights = this
 9463                        .document_highlights_for_position(selection.head(), &buffer)
 9464                        .filter(|highlight| {
 9465                            highlight.start.excerpt_id == selection.head().excerpt_id
 9466                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9467                        });
 9468                    buffer_highlights
 9469                        .next()
 9470                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9471                })?
 9472            };
 9473            if let Some(rename_range) = rename_range {
 9474                this.update(&mut cx, |this, cx| {
 9475                    let snapshot = cursor_buffer.read(cx).snapshot();
 9476                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9477                    let cursor_offset_in_rename_range =
 9478                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9479                    let cursor_offset_in_rename_range_end =
 9480                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9481
 9482                    this.take_rename(false, cx);
 9483                    let buffer = this.buffer.read(cx).read(cx);
 9484                    let cursor_offset = selection.head().to_offset(&buffer);
 9485                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9486                    let rename_end = rename_start + rename_buffer_range.len();
 9487                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9488                    let mut old_highlight_id = None;
 9489                    let old_name: Arc<str> = buffer
 9490                        .chunks(rename_start..rename_end, true)
 9491                        .map(|chunk| {
 9492                            if old_highlight_id.is_none() {
 9493                                old_highlight_id = chunk.syntax_highlight_id;
 9494                            }
 9495                            chunk.text
 9496                        })
 9497                        .collect::<String>()
 9498                        .into();
 9499
 9500                    drop(buffer);
 9501
 9502                    // Position the selection in the rename editor so that it matches the current selection.
 9503                    this.show_local_selections = false;
 9504                    let rename_editor = cx.new_view(|cx| {
 9505                        let mut editor = Editor::single_line(cx);
 9506                        editor.buffer.update(cx, |buffer, cx| {
 9507                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9508                        });
 9509                        let rename_selection_range = match cursor_offset_in_rename_range
 9510                            .cmp(&cursor_offset_in_rename_range_end)
 9511                        {
 9512                            Ordering::Equal => {
 9513                                editor.select_all(&SelectAll, cx);
 9514                                return editor;
 9515                            }
 9516                            Ordering::Less => {
 9517                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9518                            }
 9519                            Ordering::Greater => {
 9520                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9521                            }
 9522                        };
 9523                        if rename_selection_range.end > old_name.len() {
 9524                            editor.select_all(&SelectAll, cx);
 9525                        } else {
 9526                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9527                                s.select_ranges([rename_selection_range]);
 9528                            });
 9529                        }
 9530                        editor
 9531                    });
 9532                    cx.subscribe(&rename_editor, |_, _, e, cx| match e {
 9533                        EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
 9534                        _ => {}
 9535                    })
 9536                    .detach();
 9537
 9538                    let write_highlights =
 9539                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9540                    let read_highlights =
 9541                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9542                    let ranges = write_highlights
 9543                        .iter()
 9544                        .flat_map(|(_, ranges)| ranges.iter())
 9545                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9546                        .cloned()
 9547                        .collect();
 9548
 9549                    this.highlight_text::<Rename>(
 9550                        ranges,
 9551                        HighlightStyle {
 9552                            fade_out: Some(0.6),
 9553                            ..Default::default()
 9554                        },
 9555                        cx,
 9556                    );
 9557                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9558                    cx.focus(&rename_focus_handle);
 9559                    let block_id = this.insert_blocks(
 9560                        [BlockProperties {
 9561                            style: BlockStyle::Flex,
 9562                            position: range.start,
 9563                            height: 1,
 9564                            render: Box::new({
 9565                                let rename_editor = rename_editor.clone();
 9566                                move |cx: &mut BlockContext| {
 9567                                    let mut text_style = cx.editor_style.text.clone();
 9568                                    if let Some(highlight_style) = old_highlight_id
 9569                                        .and_then(|h| h.style(&cx.editor_style.syntax))
 9570                                    {
 9571                                        text_style = text_style.highlight(highlight_style);
 9572                                    }
 9573                                    div()
 9574                                        .pl(cx.anchor_x)
 9575                                        .child(EditorElement::new(
 9576                                            &rename_editor,
 9577                                            EditorStyle {
 9578                                                background: cx.theme().system().transparent,
 9579                                                local_player: cx.editor_style.local_player,
 9580                                                text: text_style,
 9581                                                scrollbar_width: cx.editor_style.scrollbar_width,
 9582                                                syntax: cx.editor_style.syntax.clone(),
 9583                                                status: cx.editor_style.status.clone(),
 9584                                                inlay_hints_style: HighlightStyle {
 9585                                                    color: Some(cx.theme().status().hint),
 9586                                                    font_weight: Some(FontWeight::BOLD),
 9587                                                    ..HighlightStyle::default()
 9588                                                },
 9589                                                suggestions_style: HighlightStyle {
 9590                                                    color: Some(cx.theme().status().predictive),
 9591                                                    ..HighlightStyle::default()
 9592                                                },
 9593                                            },
 9594                                        ))
 9595                                        .into_any_element()
 9596                                }
 9597                            }),
 9598                            disposition: BlockDisposition::Below,
 9599                        }],
 9600                        Some(Autoscroll::fit()),
 9601                        cx,
 9602                    )[0];
 9603                    this.pending_rename = Some(RenameState {
 9604                        range,
 9605                        old_name,
 9606                        editor: rename_editor,
 9607                        block_id,
 9608                    });
 9609                })?;
 9610            }
 9611
 9612            Ok(())
 9613        }))
 9614    }
 9615
 9616    pub fn confirm_rename(
 9617        &mut self,
 9618        _: &ConfirmRename,
 9619        cx: &mut ViewContext<Self>,
 9620    ) -> Option<Task<Result<()>>> {
 9621        let rename = self.take_rename(false, cx)?;
 9622        let workspace = self.workspace()?;
 9623        let (start_buffer, start) = self
 9624            .buffer
 9625            .read(cx)
 9626            .text_anchor_for_position(rename.range.start, cx)?;
 9627        let (end_buffer, end) = self
 9628            .buffer
 9629            .read(cx)
 9630            .text_anchor_for_position(rename.range.end, cx)?;
 9631        if start_buffer != end_buffer {
 9632            return None;
 9633        }
 9634
 9635        let buffer = start_buffer;
 9636        let range = start..end;
 9637        let old_name = rename.old_name;
 9638        let new_name = rename.editor.read(cx).text(cx);
 9639
 9640        let rename = workspace
 9641            .read(cx)
 9642            .project()
 9643            .clone()
 9644            .update(cx, |project, cx| {
 9645                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
 9646            });
 9647        let workspace = workspace.downgrade();
 9648
 9649        Some(cx.spawn(|editor, mut cx| async move {
 9650            let project_transaction = rename.await?;
 9651            Self::open_project_transaction(
 9652                &editor,
 9653                workspace,
 9654                project_transaction,
 9655                format!("Rename: {}{}", old_name, new_name),
 9656                cx.clone(),
 9657            )
 9658            .await?;
 9659
 9660            editor.update(&mut cx, |editor, cx| {
 9661                editor.refresh_document_highlights(cx);
 9662            })?;
 9663            Ok(())
 9664        }))
 9665    }
 9666
 9667    fn take_rename(
 9668        &mut self,
 9669        moving_cursor: bool,
 9670        cx: &mut ViewContext<Self>,
 9671    ) -> Option<RenameState> {
 9672        let rename = self.pending_rename.take()?;
 9673        if rename.editor.focus_handle(cx).is_focused(cx) {
 9674            cx.focus(&self.focus_handle);
 9675        }
 9676
 9677        self.remove_blocks(
 9678            [rename.block_id].into_iter().collect(),
 9679            Some(Autoscroll::fit()),
 9680            cx,
 9681        );
 9682        self.clear_highlights::<Rename>(cx);
 9683        self.show_local_selections = true;
 9684
 9685        if moving_cursor {
 9686            let rename_editor = rename.editor.read(cx);
 9687            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
 9688
 9689            // Update the selection to match the position of the selection inside
 9690            // the rename editor.
 9691            let snapshot = self.buffer.read(cx).read(cx);
 9692            let rename_range = rename.range.to_offset(&snapshot);
 9693            let cursor_in_editor = snapshot
 9694                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
 9695                .min(rename_range.end);
 9696            drop(snapshot);
 9697
 9698            self.change_selections(None, cx, |s| {
 9699                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
 9700            });
 9701        } else {
 9702            self.refresh_document_highlights(cx);
 9703        }
 9704
 9705        Some(rename)
 9706    }
 9707
 9708    pub fn pending_rename(&self) -> Option<&RenameState> {
 9709        self.pending_rename.as_ref()
 9710    }
 9711
 9712    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9713        let project = match &self.project {
 9714            Some(project) => project.clone(),
 9715            None => return None,
 9716        };
 9717
 9718        Some(self.perform_format(project, FormatTrigger::Manual, cx))
 9719    }
 9720
 9721    fn perform_format(
 9722        &mut self,
 9723        project: Model<Project>,
 9724        trigger: FormatTrigger,
 9725        cx: &mut ViewContext<Self>,
 9726    ) -> Task<Result<()>> {
 9727        let buffer = self.buffer().clone();
 9728        let mut buffers = buffer.read(cx).all_buffers();
 9729        if trigger == FormatTrigger::Save {
 9730            buffers.retain(|buffer| buffer.read(cx).is_dirty());
 9731        }
 9732
 9733        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
 9734        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
 9735
 9736        cx.spawn(|_, mut cx| async move {
 9737            let transaction = futures::select_biased! {
 9738                () = timeout => {
 9739                    log::warn!("timed out waiting for formatting");
 9740                    None
 9741                }
 9742                transaction = format.log_err().fuse() => transaction,
 9743            };
 9744
 9745            buffer
 9746                .update(&mut cx, |buffer, cx| {
 9747                    if let Some(transaction) = transaction {
 9748                        if !buffer.is_singleton() {
 9749                            buffer.push_transaction(&transaction.0, cx);
 9750                        }
 9751                    }
 9752
 9753                    cx.notify();
 9754                })
 9755                .ok();
 9756
 9757            Ok(())
 9758        })
 9759    }
 9760
 9761    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
 9762        if let Some(project) = self.project.clone() {
 9763            self.buffer.update(cx, |multi_buffer, cx| {
 9764                project.update(cx, |project, cx| {
 9765                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
 9766                });
 9767            })
 9768        }
 9769    }
 9770
 9771    fn cancel_language_server_work(
 9772        &mut self,
 9773        _: &CancelLanguageServerWork,
 9774        cx: &mut ViewContext<Self>,
 9775    ) {
 9776        if let Some(project) = self.project.clone() {
 9777            self.buffer.update(cx, |multi_buffer, cx| {
 9778                project.update(cx, |project, cx| {
 9779                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
 9780                });
 9781            })
 9782        }
 9783    }
 9784
 9785    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
 9786        cx.show_character_palette();
 9787    }
 9788
 9789    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
 9790        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
 9791            let buffer = self.buffer.read(cx).snapshot(cx);
 9792            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
 9793            let is_valid = buffer
 9794                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
 9795                .any(|entry| {
 9796                    entry.diagnostic.is_primary
 9797                        && !entry.range.is_empty()
 9798                        && entry.range.start == primary_range_start
 9799                        && entry.diagnostic.message == active_diagnostics.primary_message
 9800                });
 9801
 9802            if is_valid != active_diagnostics.is_valid {
 9803                active_diagnostics.is_valid = is_valid;
 9804                let mut new_styles = HashMap::default();
 9805                for (block_id, diagnostic) in &active_diagnostics.blocks {
 9806                    new_styles.insert(
 9807                        *block_id,
 9808                        (
 9809                            None,
 9810                            diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
 9811                        ),
 9812                    );
 9813                }
 9814                self.display_map.update(cx, |display_map, cx| {
 9815                    display_map.replace_blocks(new_styles, cx)
 9816                });
 9817            }
 9818        }
 9819    }
 9820
 9821    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
 9822        self.dismiss_diagnostics(cx);
 9823        let snapshot = self.snapshot(cx);
 9824        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
 9825            let buffer = self.buffer.read(cx).snapshot(cx);
 9826
 9827            let mut primary_range = None;
 9828            let mut primary_message = None;
 9829            let mut group_end = Point::zero();
 9830            let diagnostic_group = buffer
 9831                .diagnostic_group::<MultiBufferPoint>(group_id)
 9832                .filter_map(|entry| {
 9833                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
 9834                        && (entry.range.start.row == entry.range.end.row
 9835                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
 9836                    {
 9837                        return None;
 9838                    }
 9839                    if entry.range.end > group_end {
 9840                        group_end = entry.range.end;
 9841                    }
 9842                    if entry.diagnostic.is_primary {
 9843                        primary_range = Some(entry.range.clone());
 9844                        primary_message = Some(entry.diagnostic.message.clone());
 9845                    }
 9846                    Some(entry)
 9847                })
 9848                .collect::<Vec<_>>();
 9849            let primary_range = primary_range?;
 9850            let primary_message = primary_message?;
 9851            let primary_range =
 9852                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
 9853
 9854            let blocks = display_map
 9855                .insert_blocks(
 9856                    diagnostic_group.iter().map(|entry| {
 9857                        let diagnostic = entry.diagnostic.clone();
 9858                        let message_height = diagnostic.message.matches('\n').count() as u8 + 1;
 9859                        BlockProperties {
 9860                            style: BlockStyle::Fixed,
 9861                            position: buffer.anchor_after(entry.range.start),
 9862                            height: message_height,
 9863                            render: diagnostic_block_renderer(diagnostic, None, true, true),
 9864                            disposition: BlockDisposition::Below,
 9865                        }
 9866                    }),
 9867                    cx,
 9868                )
 9869                .into_iter()
 9870                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
 9871                .collect();
 9872
 9873            Some(ActiveDiagnosticGroup {
 9874                primary_range,
 9875                primary_message,
 9876                group_id,
 9877                blocks,
 9878                is_valid: true,
 9879            })
 9880        });
 9881        self.active_diagnostics.is_some()
 9882    }
 9883
 9884    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
 9885        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
 9886            self.display_map.update(cx, |display_map, cx| {
 9887                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
 9888            });
 9889            cx.notify();
 9890        }
 9891    }
 9892
 9893    pub fn set_selections_from_remote(
 9894        &mut self,
 9895        selections: Vec<Selection<Anchor>>,
 9896        pending_selection: Option<Selection<Anchor>>,
 9897        cx: &mut ViewContext<Self>,
 9898    ) {
 9899        let old_cursor_position = self.selections.newest_anchor().head();
 9900        self.selections.change_with(cx, |s| {
 9901            s.select_anchors(selections);
 9902            if let Some(pending_selection) = pending_selection {
 9903                s.set_pending(pending_selection, SelectMode::Character);
 9904            } else {
 9905                s.clear_pending();
 9906            }
 9907        });
 9908        self.selections_did_change(false, &old_cursor_position, true, cx);
 9909    }
 9910
 9911    fn push_to_selection_history(&mut self) {
 9912        self.selection_history.push(SelectionHistoryEntry {
 9913            selections: self.selections.disjoint_anchors(),
 9914            select_next_state: self.select_next_state.clone(),
 9915            select_prev_state: self.select_prev_state.clone(),
 9916            add_selections_state: self.add_selections_state.clone(),
 9917        });
 9918    }
 9919
 9920    pub fn transact(
 9921        &mut self,
 9922        cx: &mut ViewContext<Self>,
 9923        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
 9924    ) -> Option<TransactionId> {
 9925        self.start_transaction_at(Instant::now(), cx);
 9926        update(self, cx);
 9927        self.end_transaction_at(Instant::now(), cx)
 9928    }
 9929
 9930    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
 9931        self.end_selection(cx);
 9932        if let Some(tx_id) = self
 9933            .buffer
 9934            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
 9935        {
 9936            self.selection_history
 9937                .insert_transaction(tx_id, self.selections.disjoint_anchors());
 9938            cx.emit(EditorEvent::TransactionBegun {
 9939                transaction_id: tx_id,
 9940            })
 9941        }
 9942    }
 9943
 9944    fn end_transaction_at(
 9945        &mut self,
 9946        now: Instant,
 9947        cx: &mut ViewContext<Self>,
 9948    ) -> Option<TransactionId> {
 9949        if let Some(transaction_id) = self
 9950            .buffer
 9951            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
 9952        {
 9953            if let Some((_, end_selections)) =
 9954                self.selection_history.transaction_mut(transaction_id)
 9955            {
 9956                *end_selections = Some(self.selections.disjoint_anchors());
 9957            } else {
 9958                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
 9959            }
 9960
 9961            cx.emit(EditorEvent::Edited { transaction_id });
 9962            Some(transaction_id)
 9963        } else {
 9964            None
 9965        }
 9966    }
 9967
 9968    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
 9969        let mut fold_ranges = Vec::new();
 9970
 9971        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9972
 9973        let selections = self.selections.all_adjusted(cx);
 9974        for selection in selections {
 9975            let range = selection.range().sorted();
 9976            let buffer_start_row = range.start.row;
 9977
 9978            for row in (0..=range.end.row).rev() {
 9979                if let Some((foldable_range, fold_text)) =
 9980                    display_map.foldable_range(MultiBufferRow(row))
 9981                {
 9982                    if foldable_range.end.row >= buffer_start_row {
 9983                        fold_ranges.push((foldable_range, fold_text));
 9984                        if row <= range.start.row {
 9985                            break;
 9986                        }
 9987                    }
 9988                }
 9989            }
 9990        }
 9991
 9992        self.fold_ranges(fold_ranges, true, cx);
 9993    }
 9994
 9995    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
 9996        let buffer_row = fold_at.buffer_row;
 9997        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9998
 9999        if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10000            let autoscroll = self
10001                .selections
10002                .all::<Point>(cx)
10003                .iter()
10004                .any(|selection| fold_range.overlaps(&selection.range()));
10005
10006            self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10007        }
10008    }
10009
10010    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10011        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10012        let buffer = &display_map.buffer_snapshot;
10013        let selections = self.selections.all::<Point>(cx);
10014        let ranges = selections
10015            .iter()
10016            .map(|s| {
10017                let range = s.display_range(&display_map).sorted();
10018                let mut start = range.start.to_point(&display_map);
10019                let mut end = range.end.to_point(&display_map);
10020                start.column = 0;
10021                end.column = buffer.line_len(MultiBufferRow(end.row));
10022                start..end
10023            })
10024            .collect::<Vec<_>>();
10025
10026        self.unfold_ranges(ranges, true, true, cx);
10027    }
10028
10029    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10030        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10031
10032        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10033            ..Point::new(
10034                unfold_at.buffer_row.0,
10035                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10036            );
10037
10038        let autoscroll = self
10039            .selections
10040            .all::<Point>(cx)
10041            .iter()
10042            .any(|selection| selection.range().overlaps(&intersection_range));
10043
10044        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10045    }
10046
10047    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10048        let selections = self.selections.all::<Point>(cx);
10049        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10050        let line_mode = self.selections.line_mode;
10051        let ranges = selections.into_iter().map(|s| {
10052            if line_mode {
10053                let start = Point::new(s.start.row, 0);
10054                let end = Point::new(
10055                    s.end.row,
10056                    display_map
10057                        .buffer_snapshot
10058                        .line_len(MultiBufferRow(s.end.row)),
10059                );
10060                (start..end, display_map.fold_placeholder.clone())
10061            } else {
10062                (s.start..s.end, display_map.fold_placeholder.clone())
10063            }
10064        });
10065        self.fold_ranges(ranges, true, cx);
10066    }
10067
10068    pub fn fold_ranges<T: ToOffset + Clone>(
10069        &mut self,
10070        ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10071        auto_scroll: bool,
10072        cx: &mut ViewContext<Self>,
10073    ) {
10074        let mut fold_ranges = Vec::new();
10075        let mut buffers_affected = HashMap::default();
10076        let multi_buffer = self.buffer().read(cx);
10077        for (fold_range, fold_text) in ranges {
10078            if let Some((_, buffer, _)) =
10079                multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10080            {
10081                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10082            };
10083            fold_ranges.push((fold_range, fold_text));
10084        }
10085
10086        let mut ranges = fold_ranges.into_iter().peekable();
10087        if ranges.peek().is_some() {
10088            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10089
10090            if auto_scroll {
10091                self.request_autoscroll(Autoscroll::fit(), cx);
10092            }
10093
10094            for buffer in buffers_affected.into_values() {
10095                self.sync_expanded_diff_hunks(buffer, cx);
10096            }
10097
10098            cx.notify();
10099
10100            if let Some(active_diagnostics) = self.active_diagnostics.take() {
10101                // Clear diagnostics block when folding a range that contains it.
10102                let snapshot = self.snapshot(cx);
10103                if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10104                    drop(snapshot);
10105                    self.active_diagnostics = Some(active_diagnostics);
10106                    self.dismiss_diagnostics(cx);
10107                } else {
10108                    self.active_diagnostics = Some(active_diagnostics);
10109                }
10110            }
10111
10112            self.scrollbar_marker_state.dirty = true;
10113        }
10114    }
10115
10116    pub fn unfold_ranges<T: ToOffset + Clone>(
10117        &mut self,
10118        ranges: impl IntoIterator<Item = Range<T>>,
10119        inclusive: bool,
10120        auto_scroll: bool,
10121        cx: &mut ViewContext<Self>,
10122    ) {
10123        let mut unfold_ranges = Vec::new();
10124        let mut buffers_affected = HashMap::default();
10125        let multi_buffer = self.buffer().read(cx);
10126        for range in ranges {
10127            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10128                buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10129            };
10130            unfold_ranges.push(range);
10131        }
10132
10133        let mut ranges = unfold_ranges.into_iter().peekable();
10134        if ranges.peek().is_some() {
10135            self.display_map
10136                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10137            if auto_scroll {
10138                self.request_autoscroll(Autoscroll::fit(), cx);
10139            }
10140
10141            for buffer in buffers_affected.into_values() {
10142                self.sync_expanded_diff_hunks(buffer, cx);
10143            }
10144
10145            cx.notify();
10146            self.scrollbar_marker_state.dirty = true;
10147            self.active_indent_guides_state.dirty = true;
10148        }
10149    }
10150
10151    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10152        if hovered != self.gutter_hovered {
10153            self.gutter_hovered = hovered;
10154            cx.notify();
10155        }
10156    }
10157
10158    pub fn insert_blocks(
10159        &mut self,
10160        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10161        autoscroll: Option<Autoscroll>,
10162        cx: &mut ViewContext<Self>,
10163    ) -> Vec<CustomBlockId> {
10164        let blocks = self
10165            .display_map
10166            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10167        if let Some(autoscroll) = autoscroll {
10168            self.request_autoscroll(autoscroll, cx);
10169        }
10170        blocks
10171    }
10172
10173    pub fn replace_blocks(
10174        &mut self,
10175        blocks: HashMap<CustomBlockId, (Option<u8>, RenderBlock)>,
10176        autoscroll: Option<Autoscroll>,
10177        cx: &mut ViewContext<Self>,
10178    ) {
10179        self.display_map
10180            .update(cx, |display_map, cx| display_map.replace_blocks(blocks, cx));
10181        if let Some(autoscroll) = autoscroll {
10182            self.request_autoscroll(autoscroll, cx);
10183        }
10184    }
10185
10186    pub fn remove_blocks(
10187        &mut self,
10188        block_ids: HashSet<CustomBlockId>,
10189        autoscroll: Option<Autoscroll>,
10190        cx: &mut ViewContext<Self>,
10191    ) {
10192        self.display_map.update(cx, |display_map, cx| {
10193            display_map.remove_blocks(block_ids, cx)
10194        });
10195        if let Some(autoscroll) = autoscroll {
10196            self.request_autoscroll(autoscroll, cx);
10197        }
10198    }
10199
10200    pub fn row_for_block(
10201        &self,
10202        block_id: CustomBlockId,
10203        cx: &mut ViewContext<Self>,
10204    ) -> Option<DisplayRow> {
10205        self.display_map
10206            .update(cx, |map, cx| map.row_for_block(block_id, cx))
10207    }
10208
10209    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10210        self.focused_block = Some(focused_block);
10211    }
10212
10213    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10214        self.focused_block.take()
10215    }
10216
10217    pub fn insert_creases(
10218        &mut self,
10219        creases: impl IntoIterator<Item = Crease>,
10220        cx: &mut ViewContext<Self>,
10221    ) -> Vec<CreaseId> {
10222        self.display_map
10223            .update(cx, |map, cx| map.insert_creases(creases, cx))
10224    }
10225
10226    pub fn remove_creases(
10227        &mut self,
10228        ids: impl IntoIterator<Item = CreaseId>,
10229        cx: &mut ViewContext<Self>,
10230    ) {
10231        self.display_map
10232            .update(cx, |map, cx| map.remove_creases(ids, cx));
10233    }
10234
10235    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10236        self.display_map
10237            .update(cx, |map, cx| map.snapshot(cx))
10238            .longest_row()
10239    }
10240
10241    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10242        self.display_map
10243            .update(cx, |map, cx| map.snapshot(cx))
10244            .max_point()
10245    }
10246
10247    pub fn text(&self, cx: &AppContext) -> String {
10248        self.buffer.read(cx).read(cx).text()
10249    }
10250
10251    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10252        let text = self.text(cx);
10253        let text = text.trim();
10254
10255        if text.is_empty() {
10256            return None;
10257        }
10258
10259        Some(text.to_string())
10260    }
10261
10262    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10263        self.transact(cx, |this, cx| {
10264            this.buffer
10265                .read(cx)
10266                .as_singleton()
10267                .expect("you can only call set_text on editors for singleton buffers")
10268                .update(cx, |buffer, cx| buffer.set_text(text, cx));
10269        });
10270    }
10271
10272    pub fn display_text(&self, cx: &mut AppContext) -> String {
10273        self.display_map
10274            .update(cx, |map, cx| map.snapshot(cx))
10275            .text()
10276    }
10277
10278    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10279        let mut wrap_guides = smallvec::smallvec![];
10280
10281        if self.show_wrap_guides == Some(false) {
10282            return wrap_guides;
10283        }
10284
10285        let settings = self.buffer.read(cx).settings_at(0, cx);
10286        if settings.show_wrap_guides {
10287            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10288                wrap_guides.push((soft_wrap as usize, true));
10289            }
10290            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10291        }
10292
10293        wrap_guides
10294    }
10295
10296    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10297        let settings = self.buffer.read(cx).settings_at(0, cx);
10298        let mode = self
10299            .soft_wrap_mode_override
10300            .unwrap_or_else(|| settings.soft_wrap);
10301        match mode {
10302            language_settings::SoftWrap::None => SoftWrap::None,
10303            language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10304            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10305            language_settings::SoftWrap::PreferredLineLength => {
10306                SoftWrap::Column(settings.preferred_line_length)
10307            }
10308        }
10309    }
10310
10311    pub fn set_soft_wrap_mode(
10312        &mut self,
10313        mode: language_settings::SoftWrap,
10314        cx: &mut ViewContext<Self>,
10315    ) {
10316        self.soft_wrap_mode_override = Some(mode);
10317        cx.notify();
10318    }
10319
10320    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10321        let rem_size = cx.rem_size();
10322        self.display_map.update(cx, |map, cx| {
10323            map.set_font(
10324                style.text.font(),
10325                style.text.font_size.to_pixels(rem_size),
10326                cx,
10327            )
10328        });
10329        self.style = Some(style);
10330    }
10331
10332    pub fn style(&self) -> Option<&EditorStyle> {
10333        self.style.as_ref()
10334    }
10335
10336    // Called by the element. This method is not designed to be called outside of the editor
10337    // element's layout code because it does not notify when rewrapping is computed synchronously.
10338    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10339        self.display_map
10340            .update(cx, |map, cx| map.set_wrap_width(width, cx))
10341    }
10342
10343    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10344        if self.soft_wrap_mode_override.is_some() {
10345            self.soft_wrap_mode_override.take();
10346        } else {
10347            let soft_wrap = match self.soft_wrap_mode(cx) {
10348                SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10349                SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10350                    language_settings::SoftWrap::PreferLine
10351                }
10352            };
10353            self.soft_wrap_mode_override = Some(soft_wrap);
10354        }
10355        cx.notify();
10356    }
10357
10358    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10359        let Some(workspace) = self.workspace() else {
10360            return;
10361        };
10362        let fs = workspace.read(cx).app_state().fs.clone();
10363        let current_show = TabBarSettings::get_global(cx).show;
10364        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10365            setting.show = Some(!current_show);
10366        });
10367    }
10368
10369    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10370        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10371            self.buffer
10372                .read(cx)
10373                .settings_at(0, cx)
10374                .indent_guides
10375                .enabled
10376        });
10377        self.show_indent_guides = Some(!currently_enabled);
10378        cx.notify();
10379    }
10380
10381    fn should_show_indent_guides(&self) -> Option<bool> {
10382        self.show_indent_guides
10383    }
10384
10385    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10386        let mut editor_settings = EditorSettings::get_global(cx).clone();
10387        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10388        EditorSettings::override_global(editor_settings, cx);
10389    }
10390
10391    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10392        self.show_gutter = show_gutter;
10393        cx.notify();
10394    }
10395
10396    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10397        self.show_line_numbers = Some(show_line_numbers);
10398        cx.notify();
10399    }
10400
10401    pub fn set_show_git_diff_gutter(
10402        &mut self,
10403        show_git_diff_gutter: bool,
10404        cx: &mut ViewContext<Self>,
10405    ) {
10406        self.show_git_diff_gutter = Some(show_git_diff_gutter);
10407        cx.notify();
10408    }
10409
10410    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10411        self.show_code_actions = Some(show_code_actions);
10412        cx.notify();
10413    }
10414
10415    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10416        self.show_runnables = Some(show_runnables);
10417        cx.notify();
10418    }
10419
10420    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10421        if self.display_map.read(cx).masked != masked {
10422            self.display_map.update(cx, |map, _| map.masked = masked);
10423        }
10424        cx.notify()
10425    }
10426
10427    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10428        self.show_wrap_guides = Some(show_wrap_guides);
10429        cx.notify();
10430    }
10431
10432    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10433        self.show_indent_guides = Some(show_indent_guides);
10434        cx.notify();
10435    }
10436
10437    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10438        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10439            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10440                if let Some(dir) = file.abs_path(cx).parent() {
10441                    return Some(dir.to_owned());
10442                }
10443            }
10444
10445            if let Some(project_path) = buffer.read(cx).project_path(cx) {
10446                return Some(project_path.path.to_path_buf());
10447            }
10448        }
10449
10450        None
10451    }
10452
10453    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10454        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10455            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10456                cx.reveal_path(&file.abs_path(cx));
10457            }
10458        }
10459    }
10460
10461    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10462        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10463            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10464                if let Some(path) = file.abs_path(cx).to_str() {
10465                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10466                }
10467            }
10468        }
10469    }
10470
10471    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10472        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10473            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10474                if let Some(path) = file.path().to_str() {
10475                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
10476                }
10477            }
10478        }
10479    }
10480
10481    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10482        self.show_git_blame_gutter = !self.show_git_blame_gutter;
10483
10484        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10485            self.start_git_blame(true, cx);
10486        }
10487
10488        cx.notify();
10489    }
10490
10491    pub fn toggle_git_blame_inline(
10492        &mut self,
10493        _: &ToggleGitBlameInline,
10494        cx: &mut ViewContext<Self>,
10495    ) {
10496        self.toggle_git_blame_inline_internal(true, cx);
10497        cx.notify();
10498    }
10499
10500    pub fn git_blame_inline_enabled(&self) -> bool {
10501        self.git_blame_inline_enabled
10502    }
10503
10504    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10505        self.show_selection_menu = self
10506            .show_selection_menu
10507            .map(|show_selections_menu| !show_selections_menu)
10508            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10509
10510        cx.notify();
10511    }
10512
10513    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10514        self.show_selection_menu
10515            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10516    }
10517
10518    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10519        if let Some(project) = self.project.as_ref() {
10520            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10521                return;
10522            };
10523
10524            if buffer.read(cx).file().is_none() {
10525                return;
10526            }
10527
10528            let focused = self.focus_handle(cx).contains_focused(cx);
10529
10530            let project = project.clone();
10531            let blame =
10532                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10533            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10534            self.blame = Some(blame);
10535        }
10536    }
10537
10538    fn toggle_git_blame_inline_internal(
10539        &mut self,
10540        user_triggered: bool,
10541        cx: &mut ViewContext<Self>,
10542    ) {
10543        if self.git_blame_inline_enabled {
10544            self.git_blame_inline_enabled = false;
10545            self.show_git_blame_inline = false;
10546            self.show_git_blame_inline_delay_task.take();
10547        } else {
10548            self.git_blame_inline_enabled = true;
10549            self.start_git_blame_inline(user_triggered, cx);
10550        }
10551
10552        cx.notify();
10553    }
10554
10555    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10556        self.start_git_blame(user_triggered, cx);
10557
10558        if ProjectSettings::get_global(cx)
10559            .git
10560            .inline_blame_delay()
10561            .is_some()
10562        {
10563            self.start_inline_blame_timer(cx);
10564        } else {
10565            self.show_git_blame_inline = true
10566        }
10567    }
10568
10569    pub fn blame(&self) -> Option<&Model<GitBlame>> {
10570        self.blame.as_ref()
10571    }
10572
10573    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10574        self.show_git_blame_gutter && self.has_blame_entries(cx)
10575    }
10576
10577    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10578        self.show_git_blame_inline
10579            && self.focus_handle.is_focused(cx)
10580            && !self.newest_selection_head_on_empty_line(cx)
10581            && self.has_blame_entries(cx)
10582    }
10583
10584    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10585        self.blame()
10586            .map_or(false, |blame| blame.read(cx).has_generated_entries())
10587    }
10588
10589    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10590        let cursor_anchor = self.selections.newest_anchor().head();
10591
10592        let snapshot = self.buffer.read(cx).snapshot(cx);
10593        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10594
10595        snapshot.line_len(buffer_row) == 0
10596    }
10597
10598    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10599        let (path, selection, repo) = maybe!({
10600            let project_handle = self.project.as_ref()?.clone();
10601            let project = project_handle.read(cx);
10602
10603            let selection = self.selections.newest::<Point>(cx);
10604            let selection_range = selection.range();
10605
10606            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10607                (buffer, selection_range.start.row..selection_range.end.row)
10608            } else {
10609                let buffer_ranges = self
10610                    .buffer()
10611                    .read(cx)
10612                    .range_to_buffer_ranges(selection_range, cx);
10613
10614                let (buffer, range, _) = if selection.reversed {
10615                    buffer_ranges.first()
10616                } else {
10617                    buffer_ranges.last()
10618                }?;
10619
10620                let snapshot = buffer.read(cx).snapshot();
10621                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10622                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
10623                (buffer.clone(), selection)
10624            };
10625
10626            let path = buffer
10627                .read(cx)
10628                .file()?
10629                .as_local()?
10630                .path()
10631                .to_str()?
10632                .to_string();
10633            let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10634            Some((path, selection, repo))
10635        })
10636        .ok_or_else(|| anyhow!("unable to open git repository"))?;
10637
10638        const REMOTE_NAME: &str = "origin";
10639        let origin_url = repo
10640            .remote_url(REMOTE_NAME)
10641            .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10642        let sha = repo
10643            .head_sha()
10644            .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10645
10646        let (provider, remote) =
10647            parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10648                .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10649
10650        Ok(provider.build_permalink(
10651            remote,
10652            BuildPermalinkParams {
10653                sha: &sha,
10654                path: &path,
10655                selection: Some(selection),
10656            },
10657        ))
10658    }
10659
10660    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10661        let permalink = self.get_permalink_to_line(cx);
10662
10663        match permalink {
10664            Ok(permalink) => {
10665                cx.write_to_clipboard(ClipboardItem::new(permalink.to_string()));
10666            }
10667            Err(err) => {
10668                let message = format!("Failed to copy permalink: {err}");
10669
10670                Err::<(), anyhow::Error>(err).log_err();
10671
10672                if let Some(workspace) = self.workspace() {
10673                    workspace.update(cx, |workspace, cx| {
10674                        struct CopyPermalinkToLine;
10675
10676                        workspace.show_toast(
10677                            Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10678                            cx,
10679                        )
10680                    })
10681                }
10682            }
10683        }
10684    }
10685
10686    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10687        let permalink = self.get_permalink_to_line(cx);
10688
10689        match permalink {
10690            Ok(permalink) => {
10691                cx.open_url(permalink.as_ref());
10692            }
10693            Err(err) => {
10694                let message = format!("Failed to open permalink: {err}");
10695
10696                Err::<(), anyhow::Error>(err).log_err();
10697
10698                if let Some(workspace) = self.workspace() {
10699                    workspace.update(cx, |workspace, cx| {
10700                        struct OpenPermalinkToLine;
10701
10702                        workspace.show_toast(
10703                            Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10704                            cx,
10705                        )
10706                    })
10707                }
10708            }
10709        }
10710    }
10711
10712    /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10713    /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10714    /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10715    pub fn highlight_rows<T: 'static>(
10716        &mut self,
10717        rows: RangeInclusive<Anchor>,
10718        color: Option<Hsla>,
10719        should_autoscroll: bool,
10720        cx: &mut ViewContext<Self>,
10721    ) {
10722        let snapshot = self.buffer().read(cx).snapshot(cx);
10723        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10724        let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10725            highlight
10726                .range
10727                .start()
10728                .cmp(&rows.start(), &snapshot)
10729                .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10730        });
10731        match (color, existing_highlight_index) {
10732            (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10733                ix,
10734                RowHighlight {
10735                    index: post_inc(&mut self.highlight_order),
10736                    range: rows,
10737                    should_autoscroll,
10738                    color,
10739                },
10740            ),
10741            (None, Ok(i)) => {
10742                row_highlights.remove(i);
10743            }
10744        }
10745    }
10746
10747    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10748    pub fn clear_row_highlights<T: 'static>(&mut self) {
10749        self.highlighted_rows.remove(&TypeId::of::<T>());
10750    }
10751
10752    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10753    pub fn highlighted_rows<T: 'static>(
10754        &self,
10755    ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10756        Some(
10757            self.highlighted_rows
10758                .get(&TypeId::of::<T>())?
10759                .iter()
10760                .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10761        )
10762    }
10763
10764    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10765    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10766    /// Allows to ignore certain kinds of highlights.
10767    pub fn highlighted_display_rows(
10768        &mut self,
10769        cx: &mut WindowContext,
10770    ) -> BTreeMap<DisplayRow, Hsla> {
10771        let snapshot = self.snapshot(cx);
10772        let mut used_highlight_orders = HashMap::default();
10773        self.highlighted_rows
10774            .iter()
10775            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10776            .fold(
10777                BTreeMap::<DisplayRow, Hsla>::new(),
10778                |mut unique_rows, highlight| {
10779                    let start_row = highlight.range.start().to_display_point(&snapshot).row();
10780                    let end_row = highlight.range.end().to_display_point(&snapshot).row();
10781                    for row in start_row.0..=end_row.0 {
10782                        let used_index =
10783                            used_highlight_orders.entry(row).or_insert(highlight.index);
10784                        if highlight.index >= *used_index {
10785                            *used_index = highlight.index;
10786                            match highlight.color {
10787                                Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10788                                None => unique_rows.remove(&DisplayRow(row)),
10789                            };
10790                        }
10791                    }
10792                    unique_rows
10793                },
10794            )
10795    }
10796
10797    pub fn highlighted_display_row_for_autoscroll(
10798        &self,
10799        snapshot: &DisplaySnapshot,
10800    ) -> Option<DisplayRow> {
10801        self.highlighted_rows
10802            .values()
10803            .flat_map(|highlighted_rows| highlighted_rows.iter())
10804            .filter_map(|highlight| {
10805                if highlight.color.is_none() || !highlight.should_autoscroll {
10806                    return None;
10807                }
10808                Some(highlight.range.start().to_display_point(&snapshot).row())
10809            })
10810            .min()
10811    }
10812
10813    pub fn set_search_within_ranges(
10814        &mut self,
10815        ranges: &[Range<Anchor>],
10816        cx: &mut ViewContext<Self>,
10817    ) {
10818        self.highlight_background::<SearchWithinRange>(
10819            ranges,
10820            |colors| colors.editor_document_highlight_read_background,
10821            cx,
10822        )
10823    }
10824
10825    pub fn set_breadcrumb_header(&mut self, new_header: String) {
10826        self.breadcrumb_header = Some(new_header);
10827    }
10828
10829    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10830        self.clear_background_highlights::<SearchWithinRange>(cx);
10831    }
10832
10833    pub fn highlight_background<T: 'static>(
10834        &mut self,
10835        ranges: &[Range<Anchor>],
10836        color_fetcher: fn(&ThemeColors) -> Hsla,
10837        cx: &mut ViewContext<Self>,
10838    ) {
10839        self.background_highlights
10840            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10841        self.scrollbar_marker_state.dirty = true;
10842        cx.notify();
10843    }
10844
10845    pub fn clear_background_highlights<T: 'static>(
10846        &mut self,
10847        cx: &mut ViewContext<Self>,
10848    ) -> Option<BackgroundHighlight> {
10849        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10850        if !text_highlights.1.is_empty() {
10851            self.scrollbar_marker_state.dirty = true;
10852            cx.notify();
10853        }
10854        Some(text_highlights)
10855    }
10856
10857    pub fn highlight_gutter<T: 'static>(
10858        &mut self,
10859        ranges: &[Range<Anchor>],
10860        color_fetcher: fn(&AppContext) -> Hsla,
10861        cx: &mut ViewContext<Self>,
10862    ) {
10863        self.gutter_highlights
10864            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10865        cx.notify();
10866    }
10867
10868    pub fn clear_gutter_highlights<T: 'static>(
10869        &mut self,
10870        cx: &mut ViewContext<Self>,
10871    ) -> Option<GutterHighlight> {
10872        cx.notify();
10873        self.gutter_highlights.remove(&TypeId::of::<T>())
10874    }
10875
10876    #[cfg(feature = "test-support")]
10877    pub fn all_text_background_highlights(
10878        &mut self,
10879        cx: &mut ViewContext<Self>,
10880    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10881        let snapshot = self.snapshot(cx);
10882        let buffer = &snapshot.buffer_snapshot;
10883        let start = buffer.anchor_before(0);
10884        let end = buffer.anchor_after(buffer.len());
10885        let theme = cx.theme().colors();
10886        self.background_highlights_in_range(start..end, &snapshot, theme)
10887    }
10888
10889    #[cfg(feature = "test-support")]
10890    pub fn search_background_highlights(
10891        &mut self,
10892        cx: &mut ViewContext<Self>,
10893    ) -> Vec<Range<Point>> {
10894        let snapshot = self.buffer().read(cx).snapshot(cx);
10895
10896        let highlights = self
10897            .background_highlights
10898            .get(&TypeId::of::<items::BufferSearchHighlights>());
10899
10900        if let Some((_color, ranges)) = highlights {
10901            ranges
10902                .iter()
10903                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
10904                .collect_vec()
10905        } else {
10906            vec![]
10907        }
10908    }
10909
10910    fn document_highlights_for_position<'a>(
10911        &'a self,
10912        position: Anchor,
10913        buffer: &'a MultiBufferSnapshot,
10914    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
10915        let read_highlights = self
10916            .background_highlights
10917            .get(&TypeId::of::<DocumentHighlightRead>())
10918            .map(|h| &h.1);
10919        let write_highlights = self
10920            .background_highlights
10921            .get(&TypeId::of::<DocumentHighlightWrite>())
10922            .map(|h| &h.1);
10923        let left_position = position.bias_left(buffer);
10924        let right_position = position.bias_right(buffer);
10925        read_highlights
10926            .into_iter()
10927            .chain(write_highlights)
10928            .flat_map(move |ranges| {
10929                let start_ix = match ranges.binary_search_by(|probe| {
10930                    let cmp = probe.end.cmp(&left_position, buffer);
10931                    if cmp.is_ge() {
10932                        Ordering::Greater
10933                    } else {
10934                        Ordering::Less
10935                    }
10936                }) {
10937                    Ok(i) | Err(i) => i,
10938                };
10939
10940                ranges[start_ix..]
10941                    .iter()
10942                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
10943            })
10944    }
10945
10946    pub fn has_background_highlights<T: 'static>(&self) -> bool {
10947        self.background_highlights
10948            .get(&TypeId::of::<T>())
10949            .map_or(false, |(_, highlights)| !highlights.is_empty())
10950    }
10951
10952    pub fn background_highlights_in_range(
10953        &self,
10954        search_range: Range<Anchor>,
10955        display_snapshot: &DisplaySnapshot,
10956        theme: &ThemeColors,
10957    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
10958        let mut results = Vec::new();
10959        for (color_fetcher, ranges) in self.background_highlights.values() {
10960            let color = color_fetcher(theme);
10961            let start_ix = match ranges.binary_search_by(|probe| {
10962                let cmp = probe
10963                    .end
10964                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
10965                if cmp.is_gt() {
10966                    Ordering::Greater
10967                } else {
10968                    Ordering::Less
10969                }
10970            }) {
10971                Ok(i) | Err(i) => i,
10972            };
10973            for range in &ranges[start_ix..] {
10974                if range
10975                    .start
10976                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
10977                    .is_ge()
10978                {
10979                    break;
10980                }
10981
10982                let start = range.start.to_display_point(&display_snapshot);
10983                let end = range.end.to_display_point(&display_snapshot);
10984                results.push((start..end, color))
10985            }
10986        }
10987        results
10988    }
10989
10990    pub fn background_highlight_row_ranges<T: 'static>(
10991        &self,
10992        search_range: Range<Anchor>,
10993        display_snapshot: &DisplaySnapshot,
10994        count: usize,
10995    ) -> Vec<RangeInclusive<DisplayPoint>> {
10996        let mut results = Vec::new();
10997        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
10998            return vec![];
10999        };
11000
11001        let start_ix = match ranges.binary_search_by(|probe| {
11002            let cmp = probe
11003                .end
11004                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11005            if cmp.is_gt() {
11006                Ordering::Greater
11007            } else {
11008                Ordering::Less
11009            }
11010        }) {
11011            Ok(i) | Err(i) => i,
11012        };
11013        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11014            if let (Some(start_display), Some(end_display)) = (start, end) {
11015                results.push(
11016                    start_display.to_display_point(display_snapshot)
11017                        ..=end_display.to_display_point(display_snapshot),
11018                );
11019            }
11020        };
11021        let mut start_row: Option<Point> = None;
11022        let mut end_row: Option<Point> = None;
11023        if ranges.len() > count {
11024            return Vec::new();
11025        }
11026        for range in &ranges[start_ix..] {
11027            if range
11028                .start
11029                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11030                .is_ge()
11031            {
11032                break;
11033            }
11034            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11035            if let Some(current_row) = &end_row {
11036                if end.row == current_row.row {
11037                    continue;
11038                }
11039            }
11040            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11041            if start_row.is_none() {
11042                assert_eq!(end_row, None);
11043                start_row = Some(start);
11044                end_row = Some(end);
11045                continue;
11046            }
11047            if let Some(current_end) = end_row.as_mut() {
11048                if start.row > current_end.row + 1 {
11049                    push_region(start_row, end_row);
11050                    start_row = Some(start);
11051                    end_row = Some(end);
11052                } else {
11053                    // Merge two hunks.
11054                    *current_end = end;
11055                }
11056            } else {
11057                unreachable!();
11058            }
11059        }
11060        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11061        push_region(start_row, end_row);
11062        results
11063    }
11064
11065    pub fn gutter_highlights_in_range(
11066        &self,
11067        search_range: Range<Anchor>,
11068        display_snapshot: &DisplaySnapshot,
11069        cx: &AppContext,
11070    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11071        let mut results = Vec::new();
11072        for (color_fetcher, ranges) in self.gutter_highlights.values() {
11073            let color = color_fetcher(cx);
11074            let start_ix = match ranges.binary_search_by(|probe| {
11075                let cmp = probe
11076                    .end
11077                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11078                if cmp.is_gt() {
11079                    Ordering::Greater
11080                } else {
11081                    Ordering::Less
11082                }
11083            }) {
11084                Ok(i) | Err(i) => i,
11085            };
11086            for range in &ranges[start_ix..] {
11087                if range
11088                    .start
11089                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11090                    .is_ge()
11091                {
11092                    break;
11093                }
11094
11095                let start = range.start.to_display_point(&display_snapshot);
11096                let end = range.end.to_display_point(&display_snapshot);
11097                results.push((start..end, color))
11098            }
11099        }
11100        results
11101    }
11102
11103    /// Get the text ranges corresponding to the redaction query
11104    pub fn redacted_ranges(
11105        &self,
11106        search_range: Range<Anchor>,
11107        display_snapshot: &DisplaySnapshot,
11108        cx: &WindowContext,
11109    ) -> Vec<Range<DisplayPoint>> {
11110        display_snapshot
11111            .buffer_snapshot
11112            .redacted_ranges(search_range, |file| {
11113                if let Some(file) = file {
11114                    file.is_private()
11115                        && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11116                } else {
11117                    false
11118                }
11119            })
11120            .map(|range| {
11121                range.start.to_display_point(display_snapshot)
11122                    ..range.end.to_display_point(display_snapshot)
11123            })
11124            .collect()
11125    }
11126
11127    pub fn highlight_text<T: 'static>(
11128        &mut self,
11129        ranges: Vec<Range<Anchor>>,
11130        style: HighlightStyle,
11131        cx: &mut ViewContext<Self>,
11132    ) {
11133        self.display_map.update(cx, |map, _| {
11134            map.highlight_text(TypeId::of::<T>(), ranges, style)
11135        });
11136        cx.notify();
11137    }
11138
11139    pub(crate) fn highlight_inlays<T: 'static>(
11140        &mut self,
11141        highlights: Vec<InlayHighlight>,
11142        style: HighlightStyle,
11143        cx: &mut ViewContext<Self>,
11144    ) {
11145        self.display_map.update(cx, |map, _| {
11146            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11147        });
11148        cx.notify();
11149    }
11150
11151    pub fn text_highlights<'a, T: 'static>(
11152        &'a self,
11153        cx: &'a AppContext,
11154    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11155        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11156    }
11157
11158    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11159        let cleared = self
11160            .display_map
11161            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11162        if cleared {
11163            cx.notify();
11164        }
11165    }
11166
11167    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11168        (self.read_only(cx) || self.blink_manager.read(cx).visible())
11169            && self.focus_handle.is_focused(cx)
11170    }
11171
11172    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11173        self.show_cursor_when_unfocused = is_enabled;
11174        cx.notify();
11175    }
11176
11177    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11178        cx.notify();
11179    }
11180
11181    fn on_buffer_event(
11182        &mut self,
11183        multibuffer: Model<MultiBuffer>,
11184        event: &multi_buffer::Event,
11185        cx: &mut ViewContext<Self>,
11186    ) {
11187        match event {
11188            multi_buffer::Event::Edited {
11189                singleton_buffer_edited,
11190            } => {
11191                self.scrollbar_marker_state.dirty = true;
11192                self.active_indent_guides_state.dirty = true;
11193                self.refresh_active_diagnostics(cx);
11194                self.refresh_code_actions(cx);
11195                if self.has_active_inline_completion(cx) {
11196                    self.update_visible_inline_completion(cx);
11197                }
11198                cx.emit(EditorEvent::BufferEdited);
11199                cx.emit(SearchEvent::MatchesInvalidated);
11200                if *singleton_buffer_edited {
11201                    if let Some(project) = &self.project {
11202                        let project = project.read(cx);
11203                        #[allow(clippy::mutable_key_type)]
11204                        let languages_affected = multibuffer
11205                            .read(cx)
11206                            .all_buffers()
11207                            .into_iter()
11208                            .filter_map(|buffer| {
11209                                let buffer = buffer.read(cx);
11210                                let language = buffer.language()?;
11211                                if project.is_local()
11212                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
11213                                {
11214                                    None
11215                                } else {
11216                                    Some(language)
11217                                }
11218                            })
11219                            .cloned()
11220                            .collect::<HashSet<_>>();
11221                        if !languages_affected.is_empty() {
11222                            self.refresh_inlay_hints(
11223                                InlayHintRefreshReason::BufferEdited(languages_affected),
11224                                cx,
11225                            );
11226                        }
11227                    }
11228                }
11229
11230                let Some(project) = &self.project else { return };
11231                let telemetry = project.read(cx).client().telemetry().clone();
11232                refresh_linked_ranges(self, cx);
11233                telemetry.log_edit_event("editor");
11234            }
11235            multi_buffer::Event::ExcerptsAdded {
11236                buffer,
11237                predecessor,
11238                excerpts,
11239            } => {
11240                self.tasks_update_task = Some(self.refresh_runnables(cx));
11241                cx.emit(EditorEvent::ExcerptsAdded {
11242                    buffer: buffer.clone(),
11243                    predecessor: *predecessor,
11244                    excerpts: excerpts.clone(),
11245                });
11246                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11247            }
11248            multi_buffer::Event::ExcerptsRemoved { ids } => {
11249                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11250                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11251            }
11252            multi_buffer::Event::ExcerptsEdited { ids } => {
11253                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11254            }
11255            multi_buffer::Event::ExcerptsExpanded { ids } => {
11256                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11257            }
11258            multi_buffer::Event::Reparsed(buffer_id) => {
11259                self.tasks_update_task = Some(self.refresh_runnables(cx));
11260
11261                cx.emit(EditorEvent::Reparsed(*buffer_id));
11262            }
11263            multi_buffer::Event::LanguageChanged(buffer_id) => {
11264                linked_editing_ranges::refresh_linked_ranges(self, cx);
11265                cx.emit(EditorEvent::Reparsed(*buffer_id));
11266                cx.notify();
11267            }
11268            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11269            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11270            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11271                cx.emit(EditorEvent::TitleChanged)
11272            }
11273            multi_buffer::Event::DiffBaseChanged => {
11274                self.scrollbar_marker_state.dirty = true;
11275                cx.emit(EditorEvent::DiffBaseChanged);
11276                cx.notify();
11277            }
11278            multi_buffer::Event::DiffUpdated { buffer } => {
11279                self.sync_expanded_diff_hunks(buffer.clone(), cx);
11280                cx.notify();
11281            }
11282            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11283            multi_buffer::Event::DiagnosticsUpdated => {
11284                self.refresh_active_diagnostics(cx);
11285                self.scrollbar_marker_state.dirty = true;
11286                cx.notify();
11287            }
11288            _ => {}
11289        };
11290    }
11291
11292    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11293        cx.notify();
11294    }
11295
11296    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11297        self.tasks_update_task = Some(self.refresh_runnables(cx));
11298        self.refresh_inline_completion(true, cx);
11299        self.refresh_inlay_hints(
11300            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11301                self.selections.newest_anchor().head(),
11302                &self.buffer.read(cx).snapshot(cx),
11303                cx,
11304            )),
11305            cx,
11306        );
11307        let editor_settings = EditorSettings::get_global(cx);
11308        self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11309        self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11310
11311        let project_settings = ProjectSettings::get_global(cx);
11312        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11313
11314        if self.mode == EditorMode::Full {
11315            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11316            if self.git_blame_inline_enabled != inline_blame_enabled {
11317                self.toggle_git_blame_inline_internal(false, cx);
11318            }
11319        }
11320
11321        cx.notify();
11322    }
11323
11324    pub fn set_searchable(&mut self, searchable: bool) {
11325        self.searchable = searchable;
11326    }
11327
11328    pub fn searchable(&self) -> bool {
11329        self.searchable
11330    }
11331
11332    fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11333        self.open_excerpts_common(true, cx)
11334    }
11335
11336    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11337        self.open_excerpts_common(false, cx)
11338    }
11339
11340    fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11341        let buffer = self.buffer.read(cx);
11342        if buffer.is_singleton() {
11343            cx.propagate();
11344            return;
11345        }
11346
11347        let Some(workspace) = self.workspace() else {
11348            cx.propagate();
11349            return;
11350        };
11351
11352        let mut new_selections_by_buffer = HashMap::default();
11353        for selection in self.selections.all::<usize>(cx) {
11354            for (buffer, mut range, _) in
11355                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11356            {
11357                if selection.reversed {
11358                    mem::swap(&mut range.start, &mut range.end);
11359                }
11360                new_selections_by_buffer
11361                    .entry(buffer)
11362                    .or_insert(Vec::new())
11363                    .push(range)
11364            }
11365        }
11366
11367        // We defer the pane interaction because we ourselves are a workspace item
11368        // and activating a new item causes the pane to call a method on us reentrantly,
11369        // which panics if we're on the stack.
11370        cx.window_context().defer(move |cx| {
11371            workspace.update(cx, |workspace, cx| {
11372                let pane = if split {
11373                    workspace.adjacent_pane(cx)
11374                } else {
11375                    workspace.active_pane().clone()
11376                };
11377
11378                for (buffer, ranges) in new_selections_by_buffer {
11379                    let editor =
11380                        workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11381                    editor.update(cx, |editor, cx| {
11382                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11383                            s.select_ranges(ranges);
11384                        });
11385                    });
11386                }
11387            })
11388        });
11389    }
11390
11391    fn jump(
11392        &mut self,
11393        path: ProjectPath,
11394        position: Point,
11395        anchor: language::Anchor,
11396        offset_from_top: u32,
11397        cx: &mut ViewContext<Self>,
11398    ) {
11399        let workspace = self.workspace();
11400        cx.spawn(|_, mut cx| async move {
11401            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11402            let editor = workspace.update(&mut cx, |workspace, cx| {
11403                // Reset the preview item id before opening the new item
11404                workspace.active_pane().update(cx, |pane, cx| {
11405                    pane.set_preview_item_id(None, cx);
11406                });
11407                workspace.open_path_preview(path, None, true, true, cx)
11408            })?;
11409            let editor = editor
11410                .await?
11411                .downcast::<Editor>()
11412                .ok_or_else(|| anyhow!("opened item was not an editor"))?
11413                .downgrade();
11414            editor.update(&mut cx, |editor, cx| {
11415                let buffer = editor
11416                    .buffer()
11417                    .read(cx)
11418                    .as_singleton()
11419                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11420                let buffer = buffer.read(cx);
11421                let cursor = if buffer.can_resolve(&anchor) {
11422                    language::ToPoint::to_point(&anchor, buffer)
11423                } else {
11424                    buffer.clip_point(position, Bias::Left)
11425                };
11426
11427                let nav_history = editor.nav_history.take();
11428                editor.change_selections(
11429                    Some(Autoscroll::top_relative(offset_from_top as usize)),
11430                    cx,
11431                    |s| {
11432                        s.select_ranges([cursor..cursor]);
11433                    },
11434                );
11435                editor.nav_history = nav_history;
11436
11437                anyhow::Ok(())
11438            })??;
11439
11440            anyhow::Ok(())
11441        })
11442        .detach_and_log_err(cx);
11443    }
11444
11445    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11446        let snapshot = self.buffer.read(cx).read(cx);
11447        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11448        Some(
11449            ranges
11450                .iter()
11451                .map(move |range| {
11452                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11453                })
11454                .collect(),
11455        )
11456    }
11457
11458    fn selection_replacement_ranges(
11459        &self,
11460        range: Range<OffsetUtf16>,
11461        cx: &AppContext,
11462    ) -> Vec<Range<OffsetUtf16>> {
11463        let selections = self.selections.all::<OffsetUtf16>(cx);
11464        let newest_selection = selections
11465            .iter()
11466            .max_by_key(|selection| selection.id)
11467            .unwrap();
11468        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11469        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11470        let snapshot = self.buffer.read(cx).read(cx);
11471        selections
11472            .into_iter()
11473            .map(|mut selection| {
11474                selection.start.0 =
11475                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
11476                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11477                snapshot.clip_offset_utf16(selection.start, Bias::Left)
11478                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11479            })
11480            .collect()
11481    }
11482
11483    fn report_editor_event(
11484        &self,
11485        operation: &'static str,
11486        file_extension: Option<String>,
11487        cx: &AppContext,
11488    ) {
11489        if cfg!(any(test, feature = "test-support")) {
11490            return;
11491        }
11492
11493        let Some(project) = &self.project else { return };
11494
11495        // If None, we are in a file without an extension
11496        let file = self
11497            .buffer
11498            .read(cx)
11499            .as_singleton()
11500            .and_then(|b| b.read(cx).file());
11501        let file_extension = file_extension.or(file
11502            .as_ref()
11503            .and_then(|file| Path::new(file.file_name(cx)).extension())
11504            .and_then(|e| e.to_str())
11505            .map(|a| a.to_string()));
11506
11507        let vim_mode = cx
11508            .global::<SettingsStore>()
11509            .raw_user_settings()
11510            .get("vim_mode")
11511            == Some(&serde_json::Value::Bool(true));
11512
11513        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11514            == language::language_settings::InlineCompletionProvider::Copilot;
11515        let copilot_enabled_for_language = self
11516            .buffer
11517            .read(cx)
11518            .settings_at(0, cx)
11519            .show_inline_completions;
11520
11521        let telemetry = project.read(cx).client().telemetry().clone();
11522        telemetry.report_editor_event(
11523            file_extension,
11524            vim_mode,
11525            operation,
11526            copilot_enabled,
11527            copilot_enabled_for_language,
11528        )
11529    }
11530
11531    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11532    /// with each line being an array of {text, highlight} objects.
11533    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11534        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11535            return;
11536        };
11537
11538        #[derive(Serialize)]
11539        struct Chunk<'a> {
11540            text: String,
11541            highlight: Option<&'a str>,
11542        }
11543
11544        let snapshot = buffer.read(cx).snapshot();
11545        let range = self
11546            .selected_text_range(cx)
11547            .and_then(|selected_range| {
11548                if selected_range.is_empty() {
11549                    None
11550                } else {
11551                    Some(selected_range)
11552                }
11553            })
11554            .unwrap_or_else(|| 0..snapshot.len());
11555
11556        let chunks = snapshot.chunks(range, true);
11557        let mut lines = Vec::new();
11558        let mut line: VecDeque<Chunk> = VecDeque::new();
11559
11560        let Some(style) = self.style.as_ref() else {
11561            return;
11562        };
11563
11564        for chunk in chunks {
11565            let highlight = chunk
11566                .syntax_highlight_id
11567                .and_then(|id| id.name(&style.syntax));
11568            let mut chunk_lines = chunk.text.split('\n').peekable();
11569            while let Some(text) = chunk_lines.next() {
11570                let mut merged_with_last_token = false;
11571                if let Some(last_token) = line.back_mut() {
11572                    if last_token.highlight == highlight {
11573                        last_token.text.push_str(text);
11574                        merged_with_last_token = true;
11575                    }
11576                }
11577
11578                if !merged_with_last_token {
11579                    line.push_back(Chunk {
11580                        text: text.into(),
11581                        highlight,
11582                    });
11583                }
11584
11585                if chunk_lines.peek().is_some() {
11586                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
11587                        line.pop_front();
11588                    }
11589                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
11590                        line.pop_back();
11591                    }
11592
11593                    lines.push(mem::take(&mut line));
11594                }
11595            }
11596        }
11597
11598        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11599            return;
11600        };
11601        cx.write_to_clipboard(ClipboardItem::new(lines));
11602    }
11603
11604    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11605        &self.inlay_hint_cache
11606    }
11607
11608    pub fn replay_insert_event(
11609        &mut self,
11610        text: &str,
11611        relative_utf16_range: Option<Range<isize>>,
11612        cx: &mut ViewContext<Self>,
11613    ) {
11614        if !self.input_enabled {
11615            cx.emit(EditorEvent::InputIgnored { text: text.into() });
11616            return;
11617        }
11618        if let Some(relative_utf16_range) = relative_utf16_range {
11619            let selections = self.selections.all::<OffsetUtf16>(cx);
11620            self.change_selections(None, cx, |s| {
11621                let new_ranges = selections.into_iter().map(|range| {
11622                    let start = OffsetUtf16(
11623                        range
11624                            .head()
11625                            .0
11626                            .saturating_add_signed(relative_utf16_range.start),
11627                    );
11628                    let end = OffsetUtf16(
11629                        range
11630                            .head()
11631                            .0
11632                            .saturating_add_signed(relative_utf16_range.end),
11633                    );
11634                    start..end
11635                });
11636                s.select_ranges(new_ranges);
11637            });
11638        }
11639
11640        self.handle_input(text, cx);
11641    }
11642
11643    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11644        let Some(project) = self.project.as_ref() else {
11645            return false;
11646        };
11647        let project = project.read(cx);
11648
11649        let mut supports = false;
11650        self.buffer().read(cx).for_each_buffer(|buffer| {
11651            if !supports {
11652                supports = project
11653                    .language_servers_for_buffer(buffer.read(cx), cx)
11654                    .any(
11655                        |(_, server)| match server.capabilities().inlay_hint_provider {
11656                            Some(lsp::OneOf::Left(enabled)) => enabled,
11657                            Some(lsp::OneOf::Right(_)) => true,
11658                            None => false,
11659                        },
11660                    )
11661            }
11662        });
11663        supports
11664    }
11665
11666    pub fn focus(&self, cx: &mut WindowContext) {
11667        cx.focus(&self.focus_handle)
11668    }
11669
11670    pub fn is_focused(&self, cx: &WindowContext) -> bool {
11671        self.focus_handle.is_focused(cx)
11672    }
11673
11674    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11675        cx.emit(EditorEvent::Focused);
11676
11677        if let Some(descendant) = self
11678            .last_focused_descendant
11679            .take()
11680            .and_then(|descendant| descendant.upgrade())
11681        {
11682            cx.focus(&descendant);
11683        } else {
11684            if let Some(blame) = self.blame.as_ref() {
11685                blame.update(cx, GitBlame::focus)
11686            }
11687
11688            self.blink_manager.update(cx, BlinkManager::enable);
11689            self.show_cursor_names(cx);
11690            self.buffer.update(cx, |buffer, cx| {
11691                buffer.finalize_last_transaction(cx);
11692                if self.leader_peer_id.is_none() {
11693                    buffer.set_active_selections(
11694                        &self.selections.disjoint_anchors(),
11695                        self.selections.line_mode,
11696                        self.cursor_shape,
11697                        cx,
11698                    );
11699                }
11700            });
11701        }
11702    }
11703
11704    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
11705        cx.emit(EditorEvent::FocusedIn)
11706    }
11707
11708    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11709        if event.blurred != self.focus_handle {
11710            self.last_focused_descendant = Some(event.blurred);
11711        }
11712    }
11713
11714    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11715        self.blink_manager.update(cx, BlinkManager::disable);
11716        self.buffer
11717            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11718
11719        if let Some(blame) = self.blame.as_ref() {
11720            blame.update(cx, GitBlame::blur)
11721        }
11722        if !self.hover_state.focused(cx) {
11723            hide_hover(self, cx);
11724        }
11725
11726        self.hide_context_menu(cx);
11727        cx.emit(EditorEvent::Blurred);
11728        cx.notify();
11729    }
11730
11731    pub fn register_action<A: Action>(
11732        &mut self,
11733        listener: impl Fn(&A, &mut WindowContext) + 'static,
11734    ) -> Subscription {
11735        let id = self.next_editor_action_id.post_inc();
11736        let listener = Arc::new(listener);
11737        self.editor_actions.borrow_mut().insert(
11738            id,
11739            Box::new(move |cx| {
11740                let _view = cx.view().clone();
11741                let cx = cx.window_context();
11742                let listener = listener.clone();
11743                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11744                    let action = action.downcast_ref().unwrap();
11745                    if phase == DispatchPhase::Bubble {
11746                        listener(action, cx)
11747                    }
11748                })
11749            }),
11750        );
11751
11752        let editor_actions = self.editor_actions.clone();
11753        Subscription::new(move || {
11754            editor_actions.borrow_mut().remove(&id);
11755        })
11756    }
11757
11758    pub fn file_header_size(&self) -> u8 {
11759        self.file_header_size
11760    }
11761
11762    pub fn revert(
11763        &mut self,
11764        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
11765        cx: &mut ViewContext<Self>,
11766    ) {
11767        self.buffer().update(cx, |multi_buffer, cx| {
11768            for (buffer_id, changes) in revert_changes {
11769                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
11770                    buffer.update(cx, |buffer, cx| {
11771                        buffer.edit(
11772                            changes.into_iter().map(|(range, text)| {
11773                                (range, text.to_string().map(Arc::<str>::from))
11774                            }),
11775                            None,
11776                            cx,
11777                        );
11778                    });
11779                }
11780            }
11781        });
11782        self.change_selections(None, cx, |selections| selections.refresh());
11783    }
11784
11785    pub fn to_pixel_point(
11786        &mut self,
11787        source: multi_buffer::Anchor,
11788        editor_snapshot: &EditorSnapshot,
11789        cx: &mut ViewContext<Self>,
11790    ) -> Option<gpui::Point<Pixels>> {
11791        let text_layout_details = self.text_layout_details(cx);
11792        let line_height = text_layout_details
11793            .editor_style
11794            .text
11795            .line_height_in_pixels(cx.rem_size());
11796        let source_point = source.to_display_point(editor_snapshot);
11797        let first_visible_line = text_layout_details
11798            .scroll_anchor
11799            .anchor
11800            .to_display_point(editor_snapshot);
11801        if first_visible_line > source_point {
11802            return None;
11803        }
11804        let source_x = editor_snapshot.x_for_display_point(source_point, &text_layout_details);
11805        let source_y = line_height
11806            * ((source_point.row() - first_visible_line.row()).0 as f32
11807                - text_layout_details.scroll_anchor.offset.y);
11808        Some(gpui::Point::new(source_x, source_y))
11809    }
11810
11811    pub fn display_to_pixel_point(
11812        &mut self,
11813        source: DisplayPoint,
11814        editor_snapshot: &EditorSnapshot,
11815        cx: &mut ViewContext<Self>,
11816    ) -> Option<gpui::Point<Pixels>> {
11817        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
11818        let text_layout_details = self.text_layout_details(cx);
11819        let first_visible_line = text_layout_details
11820            .scroll_anchor
11821            .anchor
11822            .to_display_point(editor_snapshot);
11823        if first_visible_line > source {
11824            return None;
11825        }
11826        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
11827        let source_y = line_height * (source.row() - first_visible_line.row()).0 as f32;
11828        Some(gpui::Point::new(source_x, source_y))
11829    }
11830
11831    fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
11832        let bounds = self.last_bounds?;
11833        Some(element::gutter_bounds(bounds, self.gutter_dimensions))
11834    }
11835}
11836
11837fn hunks_for_selections(
11838    multi_buffer_snapshot: &MultiBufferSnapshot,
11839    selections: &[Selection<Anchor>],
11840) -> Vec<DiffHunk<MultiBufferRow>> {
11841    let buffer_rows_for_selections = selections.iter().map(|selection| {
11842        let head = selection.head();
11843        let tail = selection.tail();
11844        let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11845        let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11846        if start > end {
11847            end..start
11848        } else {
11849            start..end
11850        }
11851    });
11852
11853    hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
11854}
11855
11856pub fn hunks_for_rows(
11857    rows: impl Iterator<Item = Range<MultiBufferRow>>,
11858    multi_buffer_snapshot: &MultiBufferSnapshot,
11859) -> Vec<DiffHunk<MultiBufferRow>> {
11860    let mut hunks = Vec::new();
11861    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11862        HashMap::default();
11863    for selected_multi_buffer_rows in rows {
11864        let query_rows =
11865            selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11866        for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11867            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11868            // when the caret is just above or just below the deleted hunk.
11869            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11870            let related_to_selection = if allow_adjacent {
11871                hunk.associated_range.overlaps(&query_rows)
11872                    || hunk.associated_range.start == query_rows.end
11873                    || hunk.associated_range.end == query_rows.start
11874            } else {
11875                // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11876                // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11877                hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11878                    || selected_multi_buffer_rows.end == hunk.associated_range.start
11879            };
11880            if related_to_selection {
11881                if !processed_buffer_rows
11882                    .entry(hunk.buffer_id)
11883                    .or_default()
11884                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
11885                {
11886                    continue;
11887                }
11888                hunks.push(hunk);
11889            }
11890        }
11891    }
11892
11893    hunks
11894}
11895
11896pub trait CollaborationHub {
11897    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
11898    fn user_participant_indices<'a>(
11899        &self,
11900        cx: &'a AppContext,
11901    ) -> &'a HashMap<u64, ParticipantIndex>;
11902    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
11903}
11904
11905impl CollaborationHub for Model<Project> {
11906    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
11907        self.read(cx).collaborators()
11908    }
11909
11910    fn user_participant_indices<'a>(
11911        &self,
11912        cx: &'a AppContext,
11913    ) -> &'a HashMap<u64, ParticipantIndex> {
11914        self.read(cx).user_store().read(cx).participant_indices()
11915    }
11916
11917    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
11918        let this = self.read(cx);
11919        let user_ids = this.collaborators().values().map(|c| c.user_id);
11920        this.user_store().read_with(cx, |user_store, cx| {
11921            user_store.participant_names(user_ids, cx)
11922        })
11923    }
11924}
11925
11926pub trait CompletionProvider {
11927    fn completions(
11928        &self,
11929        buffer: &Model<Buffer>,
11930        buffer_position: text::Anchor,
11931        trigger: CompletionContext,
11932        cx: &mut ViewContext<Editor>,
11933    ) -> Task<Result<Vec<Completion>>>;
11934
11935    fn resolve_completions(
11936        &self,
11937        buffer: Model<Buffer>,
11938        completion_indices: Vec<usize>,
11939        completions: Arc<RwLock<Box<[Completion]>>>,
11940        cx: &mut ViewContext<Editor>,
11941    ) -> Task<Result<bool>>;
11942
11943    fn apply_additional_edits_for_completion(
11944        &self,
11945        buffer: Model<Buffer>,
11946        completion: Completion,
11947        push_to_history: bool,
11948        cx: &mut ViewContext<Editor>,
11949    ) -> Task<Result<Option<language::Transaction>>>;
11950
11951    fn is_completion_trigger(
11952        &self,
11953        buffer: &Model<Buffer>,
11954        position: language::Anchor,
11955        text: &str,
11956        trigger_in_words: bool,
11957        cx: &mut ViewContext<Editor>,
11958    ) -> bool;
11959}
11960
11961fn snippet_completions(
11962    project: &Project,
11963    buffer: &Model<Buffer>,
11964    buffer_position: text::Anchor,
11965    cx: &mut AppContext,
11966) -> Vec<Completion> {
11967    let language = buffer.read(cx).language_at(buffer_position);
11968    let language_name = language.as_ref().map(|language| language.lsp_id());
11969    let snippet_store = project.snippets().read(cx);
11970    let snippets = snippet_store.snippets_for(language_name, cx);
11971
11972    if snippets.is_empty() {
11973        return vec![];
11974    }
11975    let snapshot = buffer.read(cx).text_snapshot();
11976    let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
11977
11978    let mut lines = chunks.lines();
11979    let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
11980        return vec![];
11981    };
11982
11983    let scope = language.map(|language| language.default_scope());
11984    let mut last_word = line_at
11985        .chars()
11986        .rev()
11987        .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
11988        .collect::<String>();
11989    last_word = last_word.chars().rev().collect();
11990    let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
11991    let to_lsp = |point: &text::Anchor| {
11992        let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
11993        point_to_lsp(end)
11994    };
11995    let lsp_end = to_lsp(&buffer_position);
11996    snippets
11997        .into_iter()
11998        .filter_map(|snippet| {
11999            let matching_prefix = snippet
12000                .prefix
12001                .iter()
12002                .find(|prefix| prefix.starts_with(&last_word))?;
12003            let start = as_offset - last_word.len();
12004            let start = snapshot.anchor_before(start);
12005            let range = start..buffer_position;
12006            let lsp_start = to_lsp(&start);
12007            let lsp_range = lsp::Range {
12008                start: lsp_start,
12009                end: lsp_end,
12010            };
12011            Some(Completion {
12012                old_range: range,
12013                new_text: snippet.body.clone(),
12014                label: CodeLabel {
12015                    text: matching_prefix.clone(),
12016                    runs: vec![],
12017                    filter_range: 0..matching_prefix.len(),
12018                },
12019                server_id: LanguageServerId(usize::MAX),
12020                documentation: snippet
12021                    .description
12022                    .clone()
12023                    .map(|description| Documentation::SingleLine(description)),
12024                lsp_completion: lsp::CompletionItem {
12025                    label: snippet.prefix.first().unwrap().clone(),
12026                    kind: Some(CompletionItemKind::SNIPPET),
12027                    label_details: snippet.description.as_ref().map(|description| {
12028                        lsp::CompletionItemLabelDetails {
12029                            detail: Some(description.clone()),
12030                            description: None,
12031                        }
12032                    }),
12033                    insert_text_format: Some(InsertTextFormat::SNIPPET),
12034                    text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12035                        lsp::InsertReplaceEdit {
12036                            new_text: snippet.body.clone(),
12037                            insert: lsp_range,
12038                            replace: lsp_range,
12039                        },
12040                    )),
12041                    filter_text: Some(snippet.body.clone()),
12042                    sort_text: Some(char::MAX.to_string()),
12043                    ..Default::default()
12044                },
12045                confirm: None,
12046                show_new_completions_on_confirm: false,
12047            })
12048        })
12049        .collect()
12050}
12051
12052impl CompletionProvider for Model<Project> {
12053    fn completions(
12054        &self,
12055        buffer: &Model<Buffer>,
12056        buffer_position: text::Anchor,
12057        options: CompletionContext,
12058        cx: &mut ViewContext<Editor>,
12059    ) -> Task<Result<Vec<Completion>>> {
12060        self.update(cx, |project, cx| {
12061            let snippets = snippet_completions(project, buffer, buffer_position, cx);
12062            let project_completions = project.completions(&buffer, buffer_position, options, cx);
12063            cx.background_executor().spawn(async move {
12064                let mut completions = project_completions.await?;
12065                //let snippets = snippets.into_iter().;
12066                completions.extend(snippets);
12067                Ok(completions)
12068            })
12069        })
12070    }
12071
12072    fn resolve_completions(
12073        &self,
12074        buffer: Model<Buffer>,
12075        completion_indices: Vec<usize>,
12076        completions: Arc<RwLock<Box<[Completion]>>>,
12077        cx: &mut ViewContext<Editor>,
12078    ) -> Task<Result<bool>> {
12079        self.update(cx, |project, cx| {
12080            project.resolve_completions(buffer, completion_indices, completions, cx)
12081        })
12082    }
12083
12084    fn apply_additional_edits_for_completion(
12085        &self,
12086        buffer: Model<Buffer>,
12087        completion: Completion,
12088        push_to_history: bool,
12089        cx: &mut ViewContext<Editor>,
12090    ) -> Task<Result<Option<language::Transaction>>> {
12091        self.update(cx, |project, cx| {
12092            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12093        })
12094    }
12095
12096    fn is_completion_trigger(
12097        &self,
12098        buffer: &Model<Buffer>,
12099        position: language::Anchor,
12100        text: &str,
12101        trigger_in_words: bool,
12102        cx: &mut ViewContext<Editor>,
12103    ) -> bool {
12104        if !EditorSettings::get_global(cx).show_completions_on_input {
12105            return false;
12106        }
12107
12108        let mut chars = text.chars();
12109        let char = if let Some(char) = chars.next() {
12110            char
12111        } else {
12112            return false;
12113        };
12114        if chars.next().is_some() {
12115            return false;
12116        }
12117
12118        let buffer = buffer.read(cx);
12119        let scope = buffer.snapshot().language_scope_at(position);
12120        if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
12121            return true;
12122        }
12123
12124        buffer
12125            .completion_triggers()
12126            .iter()
12127            .any(|string| string == text)
12128    }
12129}
12130
12131fn inlay_hint_settings(
12132    location: Anchor,
12133    snapshot: &MultiBufferSnapshot,
12134    cx: &mut ViewContext<'_, Editor>,
12135) -> InlayHintSettings {
12136    let file = snapshot.file_at(location);
12137    let language = snapshot.language_at(location);
12138    let settings = all_language_settings(file, cx);
12139    settings
12140        .language(language.map(|l| l.name()).as_deref())
12141        .inlay_hints
12142}
12143
12144fn consume_contiguous_rows(
12145    contiguous_row_selections: &mut Vec<Selection<Point>>,
12146    selection: &Selection<Point>,
12147    display_map: &DisplaySnapshot,
12148    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12149) -> (MultiBufferRow, MultiBufferRow) {
12150    contiguous_row_selections.push(selection.clone());
12151    let start_row = MultiBufferRow(selection.start.row);
12152    let mut end_row = ending_row(selection, display_map);
12153
12154    while let Some(next_selection) = selections.peek() {
12155        if next_selection.start.row <= end_row.0 {
12156            end_row = ending_row(next_selection, display_map);
12157            contiguous_row_selections.push(selections.next().unwrap().clone());
12158        } else {
12159            break;
12160        }
12161    }
12162    (start_row, end_row)
12163}
12164
12165fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12166    if next_selection.end.column > 0 || next_selection.is_empty() {
12167        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12168    } else {
12169        MultiBufferRow(next_selection.end.row)
12170    }
12171}
12172
12173impl EditorSnapshot {
12174    pub fn remote_selections_in_range<'a>(
12175        &'a self,
12176        range: &'a Range<Anchor>,
12177        collaboration_hub: &dyn CollaborationHub,
12178        cx: &'a AppContext,
12179    ) -> impl 'a + Iterator<Item = RemoteSelection> {
12180        let participant_names = collaboration_hub.user_names(cx);
12181        let participant_indices = collaboration_hub.user_participant_indices(cx);
12182        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12183        let collaborators_by_replica_id = collaborators_by_peer_id
12184            .iter()
12185            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12186            .collect::<HashMap<_, _>>();
12187        self.buffer_snapshot
12188            .selections_in_range(range, false)
12189            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12190                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12191                let participant_index = participant_indices.get(&collaborator.user_id).copied();
12192                let user_name = participant_names.get(&collaborator.user_id).cloned();
12193                Some(RemoteSelection {
12194                    replica_id,
12195                    selection,
12196                    cursor_shape,
12197                    line_mode,
12198                    participant_index,
12199                    peer_id: collaborator.peer_id,
12200                    user_name,
12201                })
12202            })
12203    }
12204
12205    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12206        self.display_snapshot.buffer_snapshot.language_at(position)
12207    }
12208
12209    pub fn is_focused(&self) -> bool {
12210        self.is_focused
12211    }
12212
12213    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12214        self.placeholder_text.as_ref()
12215    }
12216
12217    pub fn scroll_position(&self) -> gpui::Point<f32> {
12218        self.scroll_anchor.scroll_position(&self.display_snapshot)
12219    }
12220
12221    fn gutter_dimensions(
12222        &self,
12223        font_id: FontId,
12224        font_size: Pixels,
12225        em_width: Pixels,
12226        max_line_number_width: Pixels,
12227        cx: &AppContext,
12228    ) -> GutterDimensions {
12229        if !self.show_gutter {
12230            return GutterDimensions::default();
12231        }
12232        let descent = cx.text_system().descent(font_id, font_size);
12233
12234        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12235            matches!(
12236                ProjectSettings::get_global(cx).git.git_gutter,
12237                Some(GitGutterSetting::TrackedFiles)
12238            )
12239        });
12240        let gutter_settings = EditorSettings::get_global(cx).gutter;
12241        let show_line_numbers = self
12242            .show_line_numbers
12243            .unwrap_or(gutter_settings.line_numbers);
12244        let line_gutter_width = if show_line_numbers {
12245            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12246            let min_width_for_number_on_gutter = em_width * 4.0;
12247            max_line_number_width.max(min_width_for_number_on_gutter)
12248        } else {
12249            0.0.into()
12250        };
12251
12252        let show_code_actions = self
12253            .show_code_actions
12254            .unwrap_or(gutter_settings.code_actions);
12255
12256        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12257
12258        let git_blame_entries_width = self
12259            .render_git_blame_gutter
12260            .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12261
12262        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12263        left_padding += if show_code_actions || show_runnables {
12264            em_width * 3.0
12265        } else if show_git_gutter && show_line_numbers {
12266            em_width * 2.0
12267        } else if show_git_gutter || show_line_numbers {
12268            em_width
12269        } else {
12270            px(0.)
12271        };
12272
12273        let right_padding = if gutter_settings.folds && show_line_numbers {
12274            em_width * 4.0
12275        } else if gutter_settings.folds {
12276            em_width * 3.0
12277        } else if show_line_numbers {
12278            em_width
12279        } else {
12280            px(0.)
12281        };
12282
12283        GutterDimensions {
12284            left_padding,
12285            right_padding,
12286            width: line_gutter_width + left_padding + right_padding,
12287            margin: -descent,
12288            git_blame_entries_width,
12289        }
12290    }
12291
12292    pub fn render_fold_toggle(
12293        &self,
12294        buffer_row: MultiBufferRow,
12295        row_contains_cursor: bool,
12296        editor: View<Editor>,
12297        cx: &mut WindowContext,
12298    ) -> Option<AnyElement> {
12299        let folded = self.is_line_folded(buffer_row);
12300
12301        if let Some(crease) = self
12302            .crease_snapshot
12303            .query_row(buffer_row, &self.buffer_snapshot)
12304        {
12305            let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12306                if folded {
12307                    editor.update(cx, |editor, cx| {
12308                        editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12309                    });
12310                } else {
12311                    editor.update(cx, |editor, cx| {
12312                        editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12313                    });
12314                }
12315            });
12316
12317            Some((crease.render_toggle)(
12318                buffer_row,
12319                folded,
12320                toggle_callback,
12321                cx,
12322            ))
12323        } else if folded
12324            || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12325        {
12326            Some(
12327                Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12328                    .selected(folded)
12329                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12330                        if folded {
12331                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
12332                        } else {
12333                            this.fold_at(&FoldAt { buffer_row }, cx);
12334                        }
12335                    }))
12336                    .into_any_element(),
12337            )
12338        } else {
12339            None
12340        }
12341    }
12342
12343    pub fn render_crease_trailer(
12344        &self,
12345        buffer_row: MultiBufferRow,
12346        cx: &mut WindowContext,
12347    ) -> Option<AnyElement> {
12348        let folded = self.is_line_folded(buffer_row);
12349        let crease = self
12350            .crease_snapshot
12351            .query_row(buffer_row, &self.buffer_snapshot)?;
12352        Some((crease.render_trailer)(buffer_row, folded, cx))
12353    }
12354}
12355
12356impl Deref for EditorSnapshot {
12357    type Target = DisplaySnapshot;
12358
12359    fn deref(&self) -> &Self::Target {
12360        &self.display_snapshot
12361    }
12362}
12363
12364#[derive(Clone, Debug, PartialEq, Eq)]
12365pub enum EditorEvent {
12366    InputIgnored {
12367        text: Arc<str>,
12368    },
12369    InputHandled {
12370        utf16_range_to_replace: Option<Range<isize>>,
12371        text: Arc<str>,
12372    },
12373    ExcerptsAdded {
12374        buffer: Model<Buffer>,
12375        predecessor: ExcerptId,
12376        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12377    },
12378    ExcerptsRemoved {
12379        ids: Vec<ExcerptId>,
12380    },
12381    ExcerptsEdited {
12382        ids: Vec<ExcerptId>,
12383    },
12384    ExcerptsExpanded {
12385        ids: Vec<ExcerptId>,
12386    },
12387    BufferEdited,
12388    Edited {
12389        transaction_id: clock::Lamport,
12390    },
12391    Reparsed(BufferId),
12392    Focused,
12393    FocusedIn,
12394    Blurred,
12395    DirtyChanged,
12396    Saved,
12397    TitleChanged,
12398    DiffBaseChanged,
12399    SelectionsChanged {
12400        local: bool,
12401    },
12402    ScrollPositionChanged {
12403        local: bool,
12404        autoscroll: bool,
12405    },
12406    Closed,
12407    TransactionUndone {
12408        transaction_id: clock::Lamport,
12409    },
12410    TransactionBegun {
12411        transaction_id: clock::Lamport,
12412    },
12413}
12414
12415impl EventEmitter<EditorEvent> for Editor {}
12416
12417impl FocusableView for Editor {
12418    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12419        self.focus_handle.clone()
12420    }
12421}
12422
12423impl Render for Editor {
12424    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12425        let settings = ThemeSettings::get_global(cx);
12426
12427        let text_style = match self.mode {
12428            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12429                color: cx.theme().colors().editor_foreground,
12430                font_family: settings.ui_font.family.clone(),
12431                font_features: settings.ui_font.features.clone(),
12432                font_fallbacks: settings.ui_font.fallbacks.clone(),
12433                font_size: rems(0.875).into(),
12434                font_weight: settings.ui_font.weight,
12435                line_height: relative(settings.buffer_line_height.value()),
12436                ..Default::default()
12437            },
12438            EditorMode::Full => TextStyle {
12439                color: cx.theme().colors().editor_foreground,
12440                font_family: settings.buffer_font.family.clone(),
12441                font_features: settings.buffer_font.features.clone(),
12442                font_fallbacks: settings.buffer_font.fallbacks.clone(),
12443                font_size: settings.buffer_font_size(cx).into(),
12444                font_weight: settings.buffer_font.weight,
12445                line_height: relative(settings.buffer_line_height.value()),
12446                ..Default::default()
12447            },
12448        };
12449
12450        let background = match self.mode {
12451            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12452            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12453            EditorMode::Full => cx.theme().colors().editor_background,
12454        };
12455
12456        EditorElement::new(
12457            cx.view(),
12458            EditorStyle {
12459                background,
12460                local_player: cx.theme().players().local(),
12461                text: text_style,
12462                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12463                syntax: cx.theme().syntax().clone(),
12464                status: cx.theme().status().clone(),
12465                inlay_hints_style: HighlightStyle {
12466                    color: Some(cx.theme().status().hint),
12467                    ..HighlightStyle::default()
12468                },
12469                suggestions_style: HighlightStyle {
12470                    color: Some(cx.theme().status().predictive),
12471                    ..HighlightStyle::default()
12472                },
12473            },
12474        )
12475    }
12476}
12477
12478impl ViewInputHandler for Editor {
12479    fn text_for_range(
12480        &mut self,
12481        range_utf16: Range<usize>,
12482        cx: &mut ViewContext<Self>,
12483    ) -> Option<String> {
12484        Some(
12485            self.buffer
12486                .read(cx)
12487                .read(cx)
12488                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12489                .collect(),
12490        )
12491    }
12492
12493    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12494        // Prevent the IME menu from appearing when holding down an alphabetic key
12495        // while input is disabled.
12496        if !self.input_enabled {
12497            return None;
12498        }
12499
12500        let range = self.selections.newest::<OffsetUtf16>(cx).range();
12501        Some(range.start.0..range.end.0)
12502    }
12503
12504    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12505        let snapshot = self.buffer.read(cx).read(cx);
12506        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12507        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12508    }
12509
12510    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12511        self.clear_highlights::<InputComposition>(cx);
12512        self.ime_transaction.take();
12513    }
12514
12515    fn replace_text_in_range(
12516        &mut self,
12517        range_utf16: Option<Range<usize>>,
12518        text: &str,
12519        cx: &mut ViewContext<Self>,
12520    ) {
12521        if !self.input_enabled {
12522            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12523            return;
12524        }
12525
12526        self.transact(cx, |this, cx| {
12527            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12528                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12529                Some(this.selection_replacement_ranges(range_utf16, cx))
12530            } else {
12531                this.marked_text_ranges(cx)
12532            };
12533
12534            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12535                let newest_selection_id = this.selections.newest_anchor().id;
12536                this.selections
12537                    .all::<OffsetUtf16>(cx)
12538                    .iter()
12539                    .zip(ranges_to_replace.iter())
12540                    .find_map(|(selection, range)| {
12541                        if selection.id == newest_selection_id {
12542                            Some(
12543                                (range.start.0 as isize - selection.head().0 as isize)
12544                                    ..(range.end.0 as isize - selection.head().0 as isize),
12545                            )
12546                        } else {
12547                            None
12548                        }
12549                    })
12550            });
12551
12552            cx.emit(EditorEvent::InputHandled {
12553                utf16_range_to_replace: range_to_replace,
12554                text: text.into(),
12555            });
12556
12557            if let Some(new_selected_ranges) = new_selected_ranges {
12558                this.change_selections(None, cx, |selections| {
12559                    selections.select_ranges(new_selected_ranges)
12560                });
12561                this.backspace(&Default::default(), cx);
12562            }
12563
12564            this.handle_input(text, cx);
12565        });
12566
12567        if let Some(transaction) = self.ime_transaction {
12568            self.buffer.update(cx, |buffer, cx| {
12569                buffer.group_until_transaction(transaction, cx);
12570            });
12571        }
12572
12573        self.unmark_text(cx);
12574    }
12575
12576    fn replace_and_mark_text_in_range(
12577        &mut self,
12578        range_utf16: Option<Range<usize>>,
12579        text: &str,
12580        new_selected_range_utf16: Option<Range<usize>>,
12581        cx: &mut ViewContext<Self>,
12582    ) {
12583        if !self.input_enabled {
12584            return;
12585        }
12586
12587        let transaction = self.transact(cx, |this, cx| {
12588            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12589                let snapshot = this.buffer.read(cx).read(cx);
12590                if let Some(relative_range_utf16) = range_utf16.as_ref() {
12591                    for marked_range in &mut marked_ranges {
12592                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12593                        marked_range.start.0 += relative_range_utf16.start;
12594                        marked_range.start =
12595                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12596                        marked_range.end =
12597                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12598                    }
12599                }
12600                Some(marked_ranges)
12601            } else if let Some(range_utf16) = range_utf16 {
12602                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12603                Some(this.selection_replacement_ranges(range_utf16, cx))
12604            } else {
12605                None
12606            };
12607
12608            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12609                let newest_selection_id = this.selections.newest_anchor().id;
12610                this.selections
12611                    .all::<OffsetUtf16>(cx)
12612                    .iter()
12613                    .zip(ranges_to_replace.iter())
12614                    .find_map(|(selection, range)| {
12615                        if selection.id == newest_selection_id {
12616                            Some(
12617                                (range.start.0 as isize - selection.head().0 as isize)
12618                                    ..(range.end.0 as isize - selection.head().0 as isize),
12619                            )
12620                        } else {
12621                            None
12622                        }
12623                    })
12624            });
12625
12626            cx.emit(EditorEvent::InputHandled {
12627                utf16_range_to_replace: range_to_replace,
12628                text: text.into(),
12629            });
12630
12631            if let Some(ranges) = ranges_to_replace {
12632                this.change_selections(None, cx, |s| s.select_ranges(ranges));
12633            }
12634
12635            let marked_ranges = {
12636                let snapshot = this.buffer.read(cx).read(cx);
12637                this.selections
12638                    .disjoint_anchors()
12639                    .iter()
12640                    .map(|selection| {
12641                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12642                    })
12643                    .collect::<Vec<_>>()
12644            };
12645
12646            if text.is_empty() {
12647                this.unmark_text(cx);
12648            } else {
12649                this.highlight_text::<InputComposition>(
12650                    marked_ranges.clone(),
12651                    HighlightStyle {
12652                        underline: Some(UnderlineStyle {
12653                            thickness: px(1.),
12654                            color: None,
12655                            wavy: false,
12656                        }),
12657                        ..Default::default()
12658                    },
12659                    cx,
12660                );
12661            }
12662
12663            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12664            let use_autoclose = this.use_autoclose;
12665            let use_auto_surround = this.use_auto_surround;
12666            this.set_use_autoclose(false);
12667            this.set_use_auto_surround(false);
12668            this.handle_input(text, cx);
12669            this.set_use_autoclose(use_autoclose);
12670            this.set_use_auto_surround(use_auto_surround);
12671
12672            if let Some(new_selected_range) = new_selected_range_utf16 {
12673                let snapshot = this.buffer.read(cx).read(cx);
12674                let new_selected_ranges = marked_ranges
12675                    .into_iter()
12676                    .map(|marked_range| {
12677                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12678                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12679                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12680                        snapshot.clip_offset_utf16(new_start, Bias::Left)
12681                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12682                    })
12683                    .collect::<Vec<_>>();
12684
12685                drop(snapshot);
12686                this.change_selections(None, cx, |selections| {
12687                    selections.select_ranges(new_selected_ranges)
12688                });
12689            }
12690        });
12691
12692        self.ime_transaction = self.ime_transaction.or(transaction);
12693        if let Some(transaction) = self.ime_transaction {
12694            self.buffer.update(cx, |buffer, cx| {
12695                buffer.group_until_transaction(transaction, cx);
12696            });
12697        }
12698
12699        if self.text_highlights::<InputComposition>(cx).is_none() {
12700            self.ime_transaction.take();
12701        }
12702    }
12703
12704    fn bounds_for_range(
12705        &mut self,
12706        range_utf16: Range<usize>,
12707        element_bounds: gpui::Bounds<Pixels>,
12708        cx: &mut ViewContext<Self>,
12709    ) -> Option<gpui::Bounds<Pixels>> {
12710        let text_layout_details = self.text_layout_details(cx);
12711        let style = &text_layout_details.editor_style;
12712        let font_id = cx.text_system().resolve_font(&style.text.font());
12713        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12714        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12715
12716        let em_width = cx
12717            .text_system()
12718            .typographic_bounds(font_id, font_size, 'm')
12719            .unwrap()
12720            .size
12721            .width;
12722
12723        let snapshot = self.snapshot(cx);
12724        let scroll_position = snapshot.scroll_position();
12725        let scroll_left = scroll_position.x * em_width;
12726
12727        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12728        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12729            + self.gutter_dimensions.width;
12730        let y = line_height * (start.row().as_f32() - scroll_position.y);
12731
12732        Some(Bounds {
12733            origin: element_bounds.origin + point(x, y),
12734            size: size(em_width, line_height),
12735        })
12736    }
12737}
12738
12739trait SelectionExt {
12740    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12741    fn spanned_rows(
12742        &self,
12743        include_end_if_at_line_start: bool,
12744        map: &DisplaySnapshot,
12745    ) -> Range<MultiBufferRow>;
12746}
12747
12748impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12749    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12750        let start = self
12751            .start
12752            .to_point(&map.buffer_snapshot)
12753            .to_display_point(map);
12754        let end = self
12755            .end
12756            .to_point(&map.buffer_snapshot)
12757            .to_display_point(map);
12758        if self.reversed {
12759            end..start
12760        } else {
12761            start..end
12762        }
12763    }
12764
12765    fn spanned_rows(
12766        &self,
12767        include_end_if_at_line_start: bool,
12768        map: &DisplaySnapshot,
12769    ) -> Range<MultiBufferRow> {
12770        let start = self.start.to_point(&map.buffer_snapshot);
12771        let mut end = self.end.to_point(&map.buffer_snapshot);
12772        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12773            end.row -= 1;
12774        }
12775
12776        let buffer_start = map.prev_line_boundary(start).0;
12777        let buffer_end = map.next_line_boundary(end).0;
12778        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12779    }
12780}
12781
12782impl<T: InvalidationRegion> InvalidationStack<T> {
12783    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12784    where
12785        S: Clone + ToOffset,
12786    {
12787        while let Some(region) = self.last() {
12788            let all_selections_inside_invalidation_ranges =
12789                if selections.len() == region.ranges().len() {
12790                    selections
12791                        .iter()
12792                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12793                        .all(|(selection, invalidation_range)| {
12794                            let head = selection.head().to_offset(buffer);
12795                            invalidation_range.start <= head && invalidation_range.end >= head
12796                        })
12797                } else {
12798                    false
12799                };
12800
12801            if all_selections_inside_invalidation_ranges {
12802                break;
12803            } else {
12804                self.pop();
12805            }
12806        }
12807    }
12808}
12809
12810impl<T> Default for InvalidationStack<T> {
12811    fn default() -> Self {
12812        Self(Default::default())
12813    }
12814}
12815
12816impl<T> Deref for InvalidationStack<T> {
12817    type Target = Vec<T>;
12818
12819    fn deref(&self) -> &Self::Target {
12820        &self.0
12821    }
12822}
12823
12824impl<T> DerefMut for InvalidationStack<T> {
12825    fn deref_mut(&mut self) -> &mut Self::Target {
12826        &mut self.0
12827    }
12828}
12829
12830impl InvalidationRegion for SnippetState {
12831    fn ranges(&self) -> &[Range<Anchor>] {
12832        &self.ranges[self.active_index]
12833    }
12834}
12835
12836pub fn diagnostic_block_renderer(
12837    diagnostic: Diagnostic,
12838    max_message_rows: Option<u8>,
12839    allow_closing: bool,
12840    _is_valid: bool,
12841) -> RenderBlock {
12842    let (text_without_backticks, code_ranges) =
12843        highlight_diagnostic_message(&diagnostic, max_message_rows);
12844
12845    Box::new(move |cx: &mut BlockContext| {
12846        let group_id: SharedString = cx.block_id.to_string().into();
12847
12848        let mut text_style = cx.text_style().clone();
12849        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
12850        let theme_settings = ThemeSettings::get_global(cx);
12851        text_style.font_family = theme_settings.buffer_font.family.clone();
12852        text_style.font_style = theme_settings.buffer_font.style;
12853        text_style.font_features = theme_settings.buffer_font.features.clone();
12854        text_style.font_weight = theme_settings.buffer_font.weight;
12855
12856        let multi_line_diagnostic = diagnostic.message.contains('\n');
12857
12858        let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
12859            if multi_line_diagnostic {
12860                v_flex()
12861            } else {
12862                h_flex()
12863            }
12864            .when(allow_closing, |div| {
12865                div.children(diagnostic.is_primary.then(|| {
12866                    IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
12867                        .icon_color(Color::Muted)
12868                        .size(ButtonSize::Compact)
12869                        .style(ButtonStyle::Transparent)
12870                        .visible_on_hover(group_id.clone())
12871                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
12872                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
12873                }))
12874            })
12875            .child(
12876                IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
12877                    .icon_color(Color::Muted)
12878                    .size(ButtonSize::Compact)
12879                    .style(ButtonStyle::Transparent)
12880                    .visible_on_hover(group_id.clone())
12881                    .on_click({
12882                        let message = diagnostic.message.clone();
12883                        move |_click, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
12884                    })
12885                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
12886            )
12887        };
12888
12889        let icon_size = buttons(&diagnostic, cx.block_id)
12890            .into_any_element()
12891            .layout_as_root(AvailableSpace::min_size(), cx);
12892
12893        h_flex()
12894            .id(cx.block_id)
12895            .group(group_id.clone())
12896            .relative()
12897            .size_full()
12898            .pl(cx.gutter_dimensions.width)
12899            .w(cx.max_width + cx.gutter_dimensions.width)
12900            .child(
12901                div()
12902                    .flex()
12903                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
12904                    .flex_shrink(),
12905            )
12906            .child(buttons(&diagnostic, cx.block_id))
12907            .child(div().flex().flex_shrink_0().child(
12908                StyledText::new(text_without_backticks.clone()).with_highlights(
12909                    &text_style,
12910                    code_ranges.iter().map(|range| {
12911                        (
12912                            range.clone(),
12913                            HighlightStyle {
12914                                font_weight: Some(FontWeight::BOLD),
12915                                ..Default::default()
12916                            },
12917                        )
12918                    }),
12919                ),
12920            ))
12921            .into_any_element()
12922    })
12923}
12924
12925pub fn highlight_diagnostic_message(
12926    diagnostic: &Diagnostic,
12927    mut max_message_rows: Option<u8>,
12928) -> (SharedString, Vec<Range<usize>>) {
12929    let mut text_without_backticks = String::new();
12930    let mut code_ranges = Vec::new();
12931
12932    if let Some(source) = &diagnostic.source {
12933        text_without_backticks.push_str(&source);
12934        code_ranges.push(0..source.len());
12935        text_without_backticks.push_str(": ");
12936    }
12937
12938    let mut prev_offset = 0;
12939    let mut in_code_block = false;
12940    let has_row_limit = max_message_rows.is_some();
12941    let mut newline_indices = diagnostic
12942        .message
12943        .match_indices('\n')
12944        .filter(|_| has_row_limit)
12945        .map(|(ix, _)| ix)
12946        .fuse()
12947        .peekable();
12948
12949    for (quote_ix, _) in diagnostic
12950        .message
12951        .match_indices('`')
12952        .chain([(diagnostic.message.len(), "")])
12953    {
12954        let mut first_newline_ix = None;
12955        let mut last_newline_ix = None;
12956        while let Some(newline_ix) = newline_indices.peek() {
12957            if *newline_ix < quote_ix {
12958                if first_newline_ix.is_none() {
12959                    first_newline_ix = Some(*newline_ix);
12960                }
12961                last_newline_ix = Some(*newline_ix);
12962
12963                if let Some(rows_left) = &mut max_message_rows {
12964                    if *rows_left == 0 {
12965                        break;
12966                    } else {
12967                        *rows_left -= 1;
12968                    }
12969                }
12970                let _ = newline_indices.next();
12971            } else {
12972                break;
12973            }
12974        }
12975        let prev_len = text_without_backticks.len();
12976        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
12977        text_without_backticks.push_str(new_text);
12978        if in_code_block {
12979            code_ranges.push(prev_len..text_without_backticks.len());
12980        }
12981        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
12982        in_code_block = !in_code_block;
12983        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
12984            text_without_backticks.push_str("...");
12985            break;
12986        }
12987    }
12988
12989    (text_without_backticks.into(), code_ranges)
12990}
12991
12992fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
12993    match severity {
12994        DiagnosticSeverity::ERROR => colors.error,
12995        DiagnosticSeverity::WARNING => colors.warning,
12996        DiagnosticSeverity::INFORMATION => colors.info,
12997        DiagnosticSeverity::HINT => colors.info,
12998        _ => colors.ignored,
12999    }
13000}
13001
13002pub fn styled_runs_for_code_label<'a>(
13003    label: &'a CodeLabel,
13004    syntax_theme: &'a theme::SyntaxTheme,
13005) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13006    let fade_out = HighlightStyle {
13007        fade_out: Some(0.35),
13008        ..Default::default()
13009    };
13010
13011    let mut prev_end = label.filter_range.end;
13012    label
13013        .runs
13014        .iter()
13015        .enumerate()
13016        .flat_map(move |(ix, (range, highlight_id))| {
13017            let style = if let Some(style) = highlight_id.style(syntax_theme) {
13018                style
13019            } else {
13020                return Default::default();
13021            };
13022            let mut muted_style = style;
13023            muted_style.highlight(fade_out);
13024
13025            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13026            if range.start >= label.filter_range.end {
13027                if range.start > prev_end {
13028                    runs.push((prev_end..range.start, fade_out));
13029                }
13030                runs.push((range.clone(), muted_style));
13031            } else if range.end <= label.filter_range.end {
13032                runs.push((range.clone(), style));
13033            } else {
13034                runs.push((range.start..label.filter_range.end, style));
13035                runs.push((label.filter_range.end..range.end, muted_style));
13036            }
13037            prev_end = cmp::max(prev_end, range.end);
13038
13039            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13040                runs.push((prev_end..label.text.len(), fade_out));
13041            }
13042
13043            runs
13044        })
13045}
13046
13047pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13048    let mut prev_index = 0;
13049    let mut prev_codepoint: Option<char> = None;
13050    text.char_indices()
13051        .chain([(text.len(), '\0')])
13052        .filter_map(move |(index, codepoint)| {
13053            let prev_codepoint = prev_codepoint.replace(codepoint)?;
13054            let is_boundary = index == text.len()
13055                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13056                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13057            if is_boundary {
13058                let chunk = &text[prev_index..index];
13059                prev_index = index;
13060                Some(chunk)
13061            } else {
13062                None
13063            }
13064        })
13065}
13066
13067pub trait RangeToAnchorExt: Sized {
13068    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13069
13070    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13071        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13072        anchor_range.start.to_display_point(&snapshot)..anchor_range.end.to_display_point(&snapshot)
13073    }
13074}
13075
13076impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13077    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13078        let start_offset = self.start.to_offset(snapshot);
13079        let end_offset = self.end.to_offset(snapshot);
13080        if start_offset == end_offset {
13081            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13082        } else {
13083            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13084        }
13085    }
13086}
13087
13088pub trait RowExt {
13089    fn as_f32(&self) -> f32;
13090
13091    fn next_row(&self) -> Self;
13092
13093    fn previous_row(&self) -> Self;
13094
13095    fn minus(&self, other: Self) -> u32;
13096}
13097
13098impl RowExt for DisplayRow {
13099    fn as_f32(&self) -> f32 {
13100        self.0 as f32
13101    }
13102
13103    fn next_row(&self) -> Self {
13104        Self(self.0 + 1)
13105    }
13106
13107    fn previous_row(&self) -> Self {
13108        Self(self.0.saturating_sub(1))
13109    }
13110
13111    fn minus(&self, other: Self) -> u32 {
13112        self.0 - other.0
13113    }
13114}
13115
13116impl RowExt for MultiBufferRow {
13117    fn as_f32(&self) -> f32 {
13118        self.0 as f32
13119    }
13120
13121    fn next_row(&self) -> Self {
13122        Self(self.0 + 1)
13123    }
13124
13125    fn previous_row(&self) -> Self {
13126        Self(self.0.saturating_sub(1))
13127    }
13128
13129    fn minus(&self, other: Self) -> u32 {
13130        self.0 - other.0
13131    }
13132}
13133
13134trait RowRangeExt {
13135    type Row;
13136
13137    fn len(&self) -> usize;
13138
13139    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13140}
13141
13142impl RowRangeExt for Range<MultiBufferRow> {
13143    type Row = MultiBufferRow;
13144
13145    fn len(&self) -> usize {
13146        (self.end.0 - self.start.0) as usize
13147    }
13148
13149    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13150        (self.start.0..self.end.0).map(MultiBufferRow)
13151    }
13152}
13153
13154impl RowRangeExt for Range<DisplayRow> {
13155    type Row = DisplayRow;
13156
13157    fn len(&self) -> usize {
13158        (self.end.0 - self.start.0) as usize
13159    }
13160
13161    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13162        (self.start.0..self.end.0).map(DisplayRow)
13163    }
13164}
13165
13166fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13167    if hunk.diff_base_byte_range.is_empty() {
13168        DiffHunkStatus::Added
13169    } else if hunk.associated_range.is_empty() {
13170        DiffHunkStatus::Removed
13171    } else {
13172        DiffHunkStatus::Modified
13173    }
13174}