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