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