editor.rs

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