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 it's behaviour.
  15pub mod actions;
  16mod blink_manager;
  17pub mod display_map;
  18mod editor_settings;
  19mod element;
  20mod inlay_hint_cache;
  21
  22mod git;
  23mod highlight_matching_bracket;
  24mod hover_popover;
  25pub mod items;
  26mod link_go_to_definition;
  27mod mouse_context_menu;
  28pub mod movement;
  29mod persistence;
  30mod rust_analyzer_ext;
  31pub mod scroll;
  32mod selections_collection;
  33
  34#[cfg(test)]
  35mod editor_tests;
  36#[cfg(any(test, feature = "test-support"))]
  37pub mod test;
  38use ::git::diff::DiffHunk;
  39pub(crate) use actions::*;
  40use aho_corasick::AhoCorasick;
  41use anyhow::{anyhow, Context as _, Result};
  42use blink_manager::BlinkManager;
  43use client::{Client, Collaborator, ParticipantIndex};
  44use clock::ReplicaId;
  45use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
  46use convert_case::{Case, Casing};
  47use copilot::Copilot;
  48pub use display_map::DisplayPoint;
  49use display_map::*;
  50pub use editor_settings::EditorSettings;
  51use element::LineWithInvisibles;
  52pub use element::{Cursor, EditorElement, HighlightedRange, HighlightedRangeLine};
  53use futures::FutureExt;
  54use fuzzy::{StringMatch, StringMatchCandidate};
  55use git::diff_hunk_to_display;
  56use gpui::{
  57    div, impl_actions, point, prelude::*, px, relative, rems, size, uniform_list, Action,
  58    AnyElement, AppContext, AsyncWindowContext, BackgroundExecutor, Bounds, ClipboardItem, Context,
  59    DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusableView, FontStyle, FontWeight,
  60    HighlightStyle, Hsla, InputHandler, InteractiveText, KeyContext, Model, MouseButton,
  61    ParentElement, Pixels, Render, SharedString, Styled, StyledText, Subscription, Task, TextStyle,
  62    UniformListScrollHandle, View, ViewContext, VisualContext, WeakView, WhiteSpace, WindowContext,
  63};
  64use highlight_matching_bracket::refresh_matching_bracket_highlights;
  65use hover_popover::{hide_hover, HoverState};
  66use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
  67pub use items::MAX_TAB_TITLE_LEN;
  68use itertools::Itertools;
  69use language::{char_kind, CharKind};
  70use language::{
  71    language_settings::{self, all_language_settings, InlayHintSettings},
  72    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CodeAction,
  73    CodeLabel, Completion, CursorShape, Diagnostic, Documentation, IndentKind, IndentSize,
  74    Language, LanguageRegistry, LanguageServerName, OffsetRangeExt, Point, Selection,
  75    SelectionGoal, TransactionId,
  76};
  77
  78use link_go_to_definition::{GoToDefinitionLink, InlayHighlight, LinkGoToDefinitionState};
  79use lsp::{DiagnosticSeverity, LanguageServerId};
  80use mouse_context_menu::MouseContextMenu;
  81use movement::TextLayoutDetails;
  82use multi_buffer::ToOffsetUtf16;
  83pub use multi_buffer::{
  84    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  85    ToPoint,
  86};
  87use ordered_float::OrderedFloat;
  88use parking_lot::RwLock;
  89use project::{FormatTrigger, Location, Project, ProjectPath, ProjectTransaction};
  90use rand::prelude::*;
  91use rpc::proto::{self, *};
  92use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  93use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
  94use serde::{Deserialize, Serialize};
  95use settings::{Settings, SettingsStore};
  96use smallvec::SmallVec;
  97use snippet::Snippet;
  98use std::{
  99    any::TypeId,
 100    borrow::Cow,
 101    cmp::{self, Ordering, Reverse},
 102    mem,
 103    num::NonZeroU32,
 104    ops::{ControlFlow, Deref, DerefMut, Range, RangeInclusive},
 105    path::Path,
 106    sync::Arc,
 107    sync::Weak,
 108    time::{Duration, Instant},
 109};
 110pub use sum_tree::Bias;
 111use sum_tree::TreeMap;
 112use text::{OffsetUtf16, Rope};
 113use theme::{
 114    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
 115    ThemeColors, ThemeSettings,
 116};
 117use ui::{
 118    h_flex, prelude::*, ButtonSize, ButtonStyle, IconButton, IconName, IconSize, ListItem, Popover,
 119    Tooltip,
 120};
 121use util::{post_inc, RangeExt, ResultExt, TryFutureExt};
 122use workspace::{searchable::SearchEvent, ItemNavHistory, Pane, SplitDirection, ViewId, Workspace};
 123
 124const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
 125const MAX_LINE_LEN: usize = 1024;
 126const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
 127const MAX_SELECTION_HISTORY_LEN: usize = 1024;
 128const COPILOT_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
 129#[doc(hidden)]
 130pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
 131#[doc(hidden)]
 132pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
 133
 134pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
 135
 136pub fn render_parsed_markdown(
 137    element_id: impl Into<ElementId>,
 138    parsed: &language::ParsedMarkdown,
 139    editor_style: &EditorStyle,
 140    workspace: Option<WeakView<Workspace>>,
 141    cx: &mut ViewContext<Editor>,
 142) -> InteractiveText {
 143    let code_span_background_color = cx
 144        .theme()
 145        .colors()
 146        .editor_document_highlight_read_background;
 147
 148    let highlights = gpui::combine_highlights(
 149        parsed.highlights.iter().filter_map(|(range, highlight)| {
 150            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
 151            Some((range.clone(), highlight))
 152        }),
 153        parsed
 154            .regions
 155            .iter()
 156            .zip(&parsed.region_ranges)
 157            .filter_map(|(region, range)| {
 158                if region.code {
 159                    Some((
 160                        range.clone(),
 161                        HighlightStyle {
 162                            background_color: Some(code_span_background_color),
 163                            ..Default::default()
 164                        },
 165                    ))
 166                } else {
 167                    None
 168                }
 169            }),
 170    );
 171
 172    let mut links = Vec::new();
 173    let mut link_ranges = Vec::new();
 174    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
 175        if let Some(link) = region.link.clone() {
 176            links.push(link);
 177            link_ranges.push(range.clone());
 178        }
 179    }
 180
 181    InteractiveText::new(
 182        element_id,
 183        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
 184    )
 185    .on_click(link_ranges, move |clicked_range_ix, cx| {
 186        match &links[clicked_range_ix] {
 187            markdown::Link::Web { url } => cx.open_url(url),
 188            markdown::Link::Path { path } => {
 189                if let Some(workspace) = &workspace {
 190                    _ = workspace.update(cx, |workspace, cx| {
 191                        workspace.open_abs_path(path.clone(), false, cx).detach();
 192                    });
 193                }
 194            }
 195        }
 196    })
 197}
 198
 199#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
 200pub(crate) enum InlayId {
 201    Suggestion(usize),
 202    Hint(usize),
 203}
 204
 205impl InlayId {
 206    fn id(&self) -> usize {
 207        match self {
 208            Self::Suggestion(id) => *id,
 209            Self::Hint(id) => *id,
 210        }
 211    }
 212}
 213
 214enum DocumentHighlightRead {}
 215enum DocumentHighlightWrite {}
 216enum InputComposition {}
 217
 218#[derive(Copy, Clone, PartialEq, Eq)]
 219pub enum Direction {
 220    Prev,
 221    Next,
 222}
 223
 224pub fn init_settings(cx: &mut AppContext) {
 225    EditorSettings::register(cx);
 226}
 227
 228pub fn init(cx: &mut AppContext) {
 229    init_settings(cx);
 230
 231    workspace::register_project_item::<Editor>(cx);
 232    workspace::register_followable_item::<Editor>(cx);
 233    workspace::register_deserializable_item::<Editor>(cx);
 234    cx.observe_new_views(
 235        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
 236            workspace.register_action(Editor::new_file);
 237            workspace.register_action(Editor::new_file_in_direction);
 238        },
 239    )
 240    .detach();
 241
 242    cx.on_action(move |_: &workspace::NewFile, cx| {
 243        let app_state = cx.global::<Weak<workspace::AppState>>();
 244        if let Some(app_state) = app_state.upgrade() {
 245            workspace::open_new(&app_state, cx, |workspace, cx| {
 246                Editor::new_file(workspace, &Default::default(), cx)
 247            })
 248            .detach();
 249        }
 250    });
 251    cx.on_action(move |_: &workspace::NewWindow, cx| {
 252        let app_state = cx.global::<Weak<workspace::AppState>>();
 253        if let Some(app_state) = app_state.upgrade() {
 254            workspace::open_new(&app_state, cx, |workspace, cx| {
 255                Editor::new_file(workspace, &Default::default(), cx)
 256            })
 257            .detach();
 258        }
 259    });
 260}
 261
 262trait InvalidationRegion {
 263    fn ranges(&self) -> &[Range<Anchor>];
 264}
 265
 266#[derive(Clone, Debug, PartialEq)]
 267pub enum SelectPhase {
 268    Begin {
 269        position: DisplayPoint,
 270        add: bool,
 271        click_count: usize,
 272    },
 273    BeginColumnar {
 274        position: DisplayPoint,
 275        goal_column: u32,
 276    },
 277    Extend {
 278        position: DisplayPoint,
 279        click_count: usize,
 280    },
 281    Update {
 282        position: DisplayPoint,
 283        goal_column: u32,
 284        scroll_position: gpui::Point<f32>,
 285    },
 286    End,
 287}
 288
 289#[derive(Clone, Debug)]
 290pub(crate) enum SelectMode {
 291    Character,
 292    Word(Range<Anchor>),
 293    Line(Range<Anchor>),
 294    All,
 295}
 296
 297#[derive(Copy, Clone, PartialEq, Eq, Debug)]
 298pub enum EditorMode {
 299    SingleLine,
 300    AutoHeight { max_lines: usize },
 301    Full,
 302}
 303
 304#[derive(Clone, Debug)]
 305pub enum SoftWrap {
 306    None,
 307    EditorWidth,
 308    Column(u32),
 309}
 310
 311#[derive(Clone)]
 312pub struct EditorStyle {
 313    pub background: Hsla,
 314    pub local_player: PlayerColor,
 315    pub text: TextStyle,
 316    pub scrollbar_width: Pixels,
 317    pub syntax: Arc<SyntaxTheme>,
 318    pub status: StatusColors,
 319    pub inlays_style: HighlightStyle,
 320    pub suggestions_style: HighlightStyle,
 321}
 322
 323impl Default for EditorStyle {
 324    fn default() -> Self {
 325        Self {
 326            background: Hsla::default(),
 327            local_player: PlayerColor::default(),
 328            text: TextStyle::default(),
 329            scrollbar_width: Pixels::default(),
 330            syntax: Default::default(),
 331            // HACK: Status colors don't have a real default.
 332            // We should look into removing the status colors from the editor
 333            // style and retrieve them directly from the theme.
 334            status: StatusColors::dark(),
 335            inlays_style: HighlightStyle::default(),
 336            suggestions_style: HighlightStyle::default(),
 337        }
 338    }
 339}
 340
 341type CompletionId = usize;
 342
 343// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
 344// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
 345
 346type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Vec<Range<Anchor>>);
 347type InlayBackgroundHighlight = (fn(&ThemeColors) -> Hsla, Vec<InlayHighlight>);
 348
 349pub struct Editor {
 350    handle: WeakView<Self>,
 351    focus_handle: FocusHandle,
 352    buffer: Model<MultiBuffer>,
 353    display_map: Model<DisplayMap>,
 354    pub selections: SelectionsCollection,
 355    pub scroll_manager: ScrollManager,
 356    columnar_selection_tail: Option<Anchor>,
 357    add_selections_state: Option<AddSelectionsState>,
 358    select_next_state: Option<SelectNextState>,
 359    select_prev_state: Option<SelectNextState>,
 360    selection_history: SelectionHistory,
 361    autoclose_regions: Vec<AutocloseRegion>,
 362    snippet_stack: InvalidationStack<SnippetState>,
 363    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
 364    ime_transaction: Option<TransactionId>,
 365    active_diagnostics: Option<ActiveDiagnosticGroup>,
 366    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
 367    project: Option<Model<Project>>,
 368    collaboration_hub: Option<Box<dyn CollaborationHub>>,
 369    blink_manager: Model<BlinkManager>,
 370    pub show_local_selections: bool,
 371    mode: EditorMode,
 372    show_gutter: bool,
 373    show_wrap_guides: Option<bool>,
 374    placeholder_text: Option<Arc<str>>,
 375    highlighted_rows: Option<Range<u32>>,
 376    background_highlights: BTreeMap<TypeId, BackgroundHighlight>,
 377    inlay_background_highlights: TreeMap<Option<TypeId>, InlayBackgroundHighlight>,
 378    nav_history: Option<ItemNavHistory>,
 379    context_menu: RwLock<Option<ContextMenu>>,
 380    mouse_context_menu: Option<MouseContextMenu>,
 381    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
 382    next_completion_id: CompletionId,
 383    available_code_actions: Option<(Model<Buffer>, Arc<[CodeAction]>)>,
 384    code_actions_task: Option<Task<()>>,
 385    document_highlights_task: Option<Task<()>>,
 386    pending_rename: Option<RenameState>,
 387    searchable: bool,
 388    cursor_shape: CursorShape,
 389    collapse_matches: bool,
 390    autoindent_mode: Option<AutoindentMode>,
 391    workspace: Option<(WeakView<Workspace>, i64)>,
 392    keymap_context_layers: BTreeMap<TypeId, KeyContext>,
 393    input_enabled: bool,
 394    read_only: bool,
 395    leader_peer_id: Option<PeerId>,
 396    remote_id: Option<ViewId>,
 397    hover_state: HoverState,
 398    gutter_hovered: bool,
 399    link_go_to_definition_state: LinkGoToDefinitionState,
 400    copilot_state: CopilotState,
 401    inlay_hint_cache: InlayHintCache,
 402    next_inlay_id: usize,
 403    _subscriptions: Vec<Subscription>,
 404    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
 405    gutter_width: Pixels,
 406    style: Option<EditorStyle>,
 407    editor_actions: Vec<Box<dyn Fn(&mut ViewContext<Self>)>>,
 408    show_copilot_suggestions: bool,
 409}
 410
 411pub struct EditorSnapshot {
 412    pub mode: EditorMode,
 413    pub show_gutter: bool,
 414    pub display_snapshot: DisplaySnapshot,
 415    pub placeholder_text: Option<Arc<str>>,
 416    is_focused: bool,
 417    scroll_anchor: ScrollAnchor,
 418    ongoing_scroll: OngoingScroll,
 419}
 420
 421pub struct RemoteSelection {
 422    pub replica_id: ReplicaId,
 423    pub selection: Selection<Anchor>,
 424    pub cursor_shape: CursorShape,
 425    pub peer_id: PeerId,
 426    pub line_mode: bool,
 427    pub participant_index: Option<ParticipantIndex>,
 428}
 429
 430#[derive(Clone, Debug)]
 431struct SelectionHistoryEntry {
 432    selections: Arc<[Selection<Anchor>]>,
 433    select_next_state: Option<SelectNextState>,
 434    select_prev_state: Option<SelectNextState>,
 435    add_selections_state: Option<AddSelectionsState>,
 436}
 437
 438enum SelectionHistoryMode {
 439    Normal,
 440    Undoing,
 441    Redoing,
 442}
 443
 444impl Default for SelectionHistoryMode {
 445    fn default() -> Self {
 446        Self::Normal
 447    }
 448}
 449
 450#[derive(Default)]
 451struct SelectionHistory {
 452    #[allow(clippy::type_complexity)]
 453    selections_by_transaction:
 454        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
 455    mode: SelectionHistoryMode,
 456    undo_stack: VecDeque<SelectionHistoryEntry>,
 457    redo_stack: VecDeque<SelectionHistoryEntry>,
 458}
 459
 460impl SelectionHistory {
 461    fn insert_transaction(
 462        &mut self,
 463        transaction_id: TransactionId,
 464        selections: Arc<[Selection<Anchor>]>,
 465    ) {
 466        self.selections_by_transaction
 467            .insert(transaction_id, (selections, None));
 468    }
 469
 470    #[allow(clippy::type_complexity)]
 471    fn transaction(
 472        &self,
 473        transaction_id: TransactionId,
 474    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 475        self.selections_by_transaction.get(&transaction_id)
 476    }
 477
 478    #[allow(clippy::type_complexity)]
 479    fn transaction_mut(
 480        &mut self,
 481        transaction_id: TransactionId,
 482    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
 483        self.selections_by_transaction.get_mut(&transaction_id)
 484    }
 485
 486    fn push(&mut self, entry: SelectionHistoryEntry) {
 487        if !entry.selections.is_empty() {
 488            match self.mode {
 489                SelectionHistoryMode::Normal => {
 490                    self.push_undo(entry);
 491                    self.redo_stack.clear();
 492                }
 493                SelectionHistoryMode::Undoing => self.push_redo(entry),
 494                SelectionHistoryMode::Redoing => self.push_undo(entry),
 495            }
 496        }
 497    }
 498
 499    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
 500        if self
 501            .undo_stack
 502            .back()
 503            .map_or(true, |e| e.selections != entry.selections)
 504        {
 505            self.undo_stack.push_back(entry);
 506            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 507                self.undo_stack.pop_front();
 508            }
 509        }
 510    }
 511
 512    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
 513        if self
 514            .redo_stack
 515            .back()
 516            .map_or(true, |e| e.selections != entry.selections)
 517        {
 518            self.redo_stack.push_back(entry);
 519            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
 520                self.redo_stack.pop_front();
 521            }
 522        }
 523    }
 524}
 525
 526#[derive(Clone, Debug)]
 527struct AddSelectionsState {
 528    above: bool,
 529    stack: Vec<usize>,
 530}
 531
 532#[derive(Clone)]
 533struct SelectNextState {
 534    query: AhoCorasick,
 535    wordwise: bool,
 536    done: bool,
 537}
 538
 539impl std::fmt::Debug for SelectNextState {
 540    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 541        f.debug_struct(std::any::type_name::<Self>())
 542            .field("wordwise", &self.wordwise)
 543            .field("done", &self.done)
 544            .finish()
 545    }
 546}
 547
 548#[derive(Debug)]
 549struct AutocloseRegion {
 550    selection_id: usize,
 551    range: Range<Anchor>,
 552    pair: BracketPair,
 553}
 554
 555#[derive(Debug)]
 556struct SnippetState {
 557    ranges: Vec<Vec<Range<Anchor>>>,
 558    active_index: usize,
 559}
 560
 561#[doc(hidden)]
 562pub struct RenameState {
 563    pub range: Range<Anchor>,
 564    pub old_name: Arc<str>,
 565    pub editor: View<Editor>,
 566    block_id: BlockId,
 567}
 568
 569struct InvalidationStack<T>(Vec<T>);
 570
 571enum ContextMenu {
 572    Completions(CompletionsMenu),
 573    CodeActions(CodeActionsMenu),
 574}
 575
 576impl ContextMenu {
 577    fn select_first(
 578        &mut self,
 579        project: Option<&Model<Project>>,
 580        cx: &mut ViewContext<Editor>,
 581    ) -> bool {
 582        if self.visible() {
 583            match self {
 584                ContextMenu::Completions(menu) => menu.select_first(project, cx),
 585                ContextMenu::CodeActions(menu) => menu.select_first(cx),
 586            }
 587            true
 588        } else {
 589            false
 590        }
 591    }
 592
 593    fn select_prev(
 594        &mut self,
 595        project: Option<&Model<Project>>,
 596        cx: &mut ViewContext<Editor>,
 597    ) -> bool {
 598        if self.visible() {
 599            match self {
 600                ContextMenu::Completions(menu) => menu.select_prev(project, cx),
 601                ContextMenu::CodeActions(menu) => menu.select_prev(cx),
 602            }
 603            true
 604        } else {
 605            false
 606        }
 607    }
 608
 609    fn select_next(
 610        &mut self,
 611        project: Option<&Model<Project>>,
 612        cx: &mut ViewContext<Editor>,
 613    ) -> bool {
 614        if self.visible() {
 615            match self {
 616                ContextMenu::Completions(menu) => menu.select_next(project, cx),
 617                ContextMenu::CodeActions(menu) => menu.select_next(cx),
 618            }
 619            true
 620        } else {
 621            false
 622        }
 623    }
 624
 625    fn select_last(
 626        &mut self,
 627        project: Option<&Model<Project>>,
 628        cx: &mut ViewContext<Editor>,
 629    ) -> bool {
 630        if self.visible() {
 631            match self {
 632                ContextMenu::Completions(menu) => menu.select_last(project, cx),
 633                ContextMenu::CodeActions(menu) => menu.select_last(cx),
 634            }
 635            true
 636        } else {
 637            false
 638        }
 639    }
 640
 641    fn visible(&self) -> bool {
 642        match self {
 643            ContextMenu::Completions(menu) => menu.visible(),
 644            ContextMenu::CodeActions(menu) => menu.visible(),
 645        }
 646    }
 647
 648    fn render(
 649        &self,
 650        cursor_position: DisplayPoint,
 651        style: &EditorStyle,
 652        max_height: Pixels,
 653        workspace: Option<WeakView<Workspace>>,
 654        cx: &mut ViewContext<Editor>,
 655    ) -> (DisplayPoint, AnyElement) {
 656        match self {
 657            ContextMenu::Completions(menu) => (
 658                cursor_position,
 659                menu.render(style, max_height, workspace, cx),
 660            ),
 661            ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
 662        }
 663    }
 664}
 665
 666#[derive(Clone)]
 667struct CompletionsMenu {
 668    id: CompletionId,
 669    initial_position: Anchor,
 670    buffer: Model<Buffer>,
 671    completions: Arc<RwLock<Box<[Completion]>>>,
 672    match_candidates: Arc<[StringMatchCandidate]>,
 673    matches: Arc<[StringMatch]>,
 674    selected_item: usize,
 675    scroll_handle: UniformListScrollHandle,
 676}
 677
 678impl CompletionsMenu {
 679    fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
 680        self.selected_item = 0;
 681        self.scroll_handle.scroll_to_item(self.selected_item);
 682        self.attempt_resolve_selected_completion_documentation(project, cx);
 683        cx.notify();
 684    }
 685
 686    fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
 687        if self.selected_item > 0 {
 688            self.selected_item -= 1;
 689        } else {
 690            self.selected_item = self.matches.len() - 1;
 691        }
 692        self.scroll_handle.scroll_to_item(self.selected_item);
 693        self.attempt_resolve_selected_completion_documentation(project, cx);
 694        cx.notify();
 695    }
 696
 697    fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
 698        if self.selected_item + 1 < self.matches.len() {
 699            self.selected_item += 1;
 700        } else {
 701            self.selected_item = 0;
 702        }
 703        self.scroll_handle.scroll_to_item(self.selected_item);
 704        self.attempt_resolve_selected_completion_documentation(project, cx);
 705        cx.notify();
 706    }
 707
 708    fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
 709        self.selected_item = self.matches.len() - 1;
 710        self.scroll_handle.scroll_to_item(self.selected_item);
 711        self.attempt_resolve_selected_completion_documentation(project, cx);
 712        cx.notify();
 713    }
 714
 715    fn pre_resolve_completion_documentation(
 716        &self,
 717        editor: &Editor,
 718        cx: &mut ViewContext<Editor>,
 719    ) -> Option<Task<()>> {
 720        let settings = EditorSettings::get_global(cx);
 721        if !settings.show_completion_documentation {
 722            return None;
 723        }
 724
 725        let Some(project) = editor.project.clone() else {
 726            return None;
 727        };
 728
 729        let client = project.read(cx).client();
 730        let language_registry = project.read(cx).languages().clone();
 731
 732        let is_remote = project.read(cx).is_remote();
 733        let project_id = project.read(cx).remote_id();
 734
 735        let completions = self.completions.clone();
 736        let completion_indices: Vec<_> = self.matches.iter().map(|m| m.candidate_id).collect();
 737
 738        Some(cx.spawn(move |this, mut cx| async move {
 739            if is_remote {
 740                let Some(project_id) = project_id else {
 741                    log::error!("Remote project without remote_id");
 742                    return;
 743                };
 744
 745                for completion_index in completion_indices {
 746                    let completions_guard = completions.read();
 747                    let completion = &completions_guard[completion_index];
 748                    if completion.documentation.is_some() {
 749                        continue;
 750                    }
 751
 752                    let server_id = completion.server_id;
 753                    let completion = completion.lsp_completion.clone();
 754                    drop(completions_guard);
 755
 756                    Self::resolve_completion_documentation_remote(
 757                        project_id,
 758                        server_id,
 759                        completions.clone(),
 760                        completion_index,
 761                        completion,
 762                        client.clone(),
 763                        language_registry.clone(),
 764                    )
 765                    .await;
 766
 767                    _ = this.update(&mut cx, |_, cx| cx.notify());
 768                }
 769            } else {
 770                for completion_index in completion_indices {
 771                    let completions_guard = completions.read();
 772                    let completion = &completions_guard[completion_index];
 773                    if completion.documentation.is_some() {
 774                        continue;
 775                    }
 776
 777                    let server_id = completion.server_id;
 778                    let completion = completion.lsp_completion.clone();
 779                    drop(completions_guard);
 780
 781                    let server = project
 782                        .read_with(&mut cx, |project, _| {
 783                            project.language_server_for_id(server_id)
 784                        })
 785                        .ok()
 786                        .flatten();
 787                    let Some(server) = server else {
 788                        return;
 789                    };
 790
 791                    Self::resolve_completion_documentation_local(
 792                        server,
 793                        completions.clone(),
 794                        completion_index,
 795                        completion,
 796                        language_registry.clone(),
 797                    )
 798                    .await;
 799
 800                    _ = this.update(&mut cx, |_, cx| cx.notify());
 801                }
 802            }
 803        }))
 804    }
 805
 806    fn attempt_resolve_selected_completion_documentation(
 807        &mut self,
 808        project: Option<&Model<Project>>,
 809        cx: &mut ViewContext<Editor>,
 810    ) {
 811        let settings = EditorSettings::get_global(cx);
 812        if !settings.show_completion_documentation {
 813            return;
 814        }
 815
 816        let completion_index = self.matches[self.selected_item].candidate_id;
 817        let Some(project) = project else {
 818            return;
 819        };
 820        let language_registry = project.read(cx).languages().clone();
 821
 822        let completions = self.completions.clone();
 823        let completions_guard = completions.read();
 824        let completion = &completions_guard[completion_index];
 825        if completion.documentation.is_some() {
 826            return;
 827        }
 828
 829        let server_id = completion.server_id;
 830        let completion = completion.lsp_completion.clone();
 831        drop(completions_guard);
 832
 833        if project.read(cx).is_remote() {
 834            let Some(project_id) = project.read(cx).remote_id() else {
 835                log::error!("Remote project without remote_id");
 836                return;
 837            };
 838
 839            let client = project.read(cx).client();
 840
 841            cx.spawn(move |this, mut cx| async move {
 842                Self::resolve_completion_documentation_remote(
 843                    project_id,
 844                    server_id,
 845                    completions.clone(),
 846                    completion_index,
 847                    completion,
 848                    client,
 849                    language_registry.clone(),
 850                )
 851                .await;
 852
 853                _ = this.update(&mut cx, |_, cx| cx.notify());
 854            })
 855            .detach();
 856        } else {
 857            let Some(server) = project.read(cx).language_server_for_id(server_id) else {
 858                return;
 859            };
 860
 861            cx.spawn(move |this, mut cx| async move {
 862                Self::resolve_completion_documentation_local(
 863                    server,
 864                    completions,
 865                    completion_index,
 866                    completion,
 867                    language_registry,
 868                )
 869                .await;
 870
 871                _ = this.update(&mut cx, |_, cx| cx.notify());
 872            })
 873            .detach();
 874        }
 875    }
 876
 877    async fn resolve_completion_documentation_remote(
 878        project_id: u64,
 879        server_id: LanguageServerId,
 880        completions: Arc<RwLock<Box<[Completion]>>>,
 881        completion_index: usize,
 882        completion: lsp::CompletionItem,
 883        client: Arc<Client>,
 884        language_registry: Arc<LanguageRegistry>,
 885    ) {
 886        let request = proto::ResolveCompletionDocumentation {
 887            project_id,
 888            language_server_id: server_id.0 as u64,
 889            lsp_completion: serde_json::to_string(&completion).unwrap().into_bytes(),
 890        };
 891
 892        let Some(response) = client
 893            .request(request)
 894            .await
 895            .context("completion documentation resolve proto request")
 896            .log_err()
 897        else {
 898            return;
 899        };
 900
 901        if response.text.is_empty() {
 902            let mut completions = completions.write();
 903            let completion = &mut completions[completion_index];
 904            completion.documentation = Some(Documentation::Undocumented);
 905        }
 906
 907        let documentation = if response.is_markdown {
 908            Documentation::MultiLineMarkdown(
 909                markdown::parse_markdown(&response.text, &language_registry, None).await,
 910            )
 911        } else if response.text.lines().count() <= 1 {
 912            Documentation::SingleLine(response.text)
 913        } else {
 914            Documentation::MultiLinePlainText(response.text)
 915        };
 916
 917        let mut completions = completions.write();
 918        let completion = &mut completions[completion_index];
 919        completion.documentation = Some(documentation);
 920    }
 921
 922    async fn resolve_completion_documentation_local(
 923        server: Arc<lsp::LanguageServer>,
 924        completions: Arc<RwLock<Box<[Completion]>>>,
 925        completion_index: usize,
 926        completion: lsp::CompletionItem,
 927        language_registry: Arc<LanguageRegistry>,
 928    ) {
 929        let can_resolve = server
 930            .capabilities()
 931            .completion_provider
 932            .as_ref()
 933            .and_then(|options| options.resolve_provider)
 934            .unwrap_or(false);
 935        if !can_resolve {
 936            return;
 937        }
 938
 939        let request = server.request::<lsp::request::ResolveCompletionItem>(completion);
 940        let Some(completion_item) = request.await.log_err() else {
 941            return;
 942        };
 943
 944        if let Some(lsp_documentation) = completion_item.documentation {
 945            let documentation = language::prepare_completion_documentation(
 946                &lsp_documentation,
 947                &language_registry,
 948                None, // TODO: Try to reasonably work out which language the completion is for
 949            )
 950            .await;
 951
 952            let mut completions = completions.write();
 953            let completion = &mut completions[completion_index];
 954            completion.documentation = Some(documentation);
 955        } else {
 956            let mut completions = completions.write();
 957            let completion = &mut completions[completion_index];
 958            completion.documentation = Some(Documentation::Undocumented);
 959        }
 960    }
 961
 962    fn visible(&self) -> bool {
 963        !self.matches.is_empty()
 964    }
 965
 966    fn render(
 967        &self,
 968        style: &EditorStyle,
 969        max_height: Pixels,
 970        workspace: Option<WeakView<Workspace>>,
 971        cx: &mut ViewContext<Editor>,
 972    ) -> AnyElement {
 973        let settings = EditorSettings::get_global(cx);
 974        let show_completion_documentation = settings.show_completion_documentation;
 975
 976        let widest_completion_ix = self
 977            .matches
 978            .iter()
 979            .enumerate()
 980            .max_by_key(|(_, mat)| {
 981                let completions = self.completions.read();
 982                let completion = &completions[mat.candidate_id];
 983                let documentation = &completion.documentation;
 984
 985                let mut len = completion.label.text.chars().count();
 986                if let Some(Documentation::SingleLine(text)) = documentation {
 987                    if show_completion_documentation {
 988                        len += text.chars().count();
 989                    }
 990                }
 991
 992                len
 993            })
 994            .map(|(ix, _)| ix);
 995
 996        let completions = self.completions.clone();
 997        let matches = self.matches.clone();
 998        let selected_item = self.selected_item;
 999        let style = style.clone();
1000
1001        let multiline_docs = {
1002            let mat = &self.matches[selected_item];
1003            let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1004                Some(Documentation::MultiLinePlainText(text)) => {
1005                    Some(div().child(SharedString::from(text.clone())))
1006                }
1007                Some(Documentation::MultiLineMarkdown(parsed)) => Some(div().child(
1008                    render_parsed_markdown("completions_markdown", parsed, &style, workspace, cx),
1009                )),
1010                _ => None,
1011            };
1012            multiline_docs.map(|div| {
1013                div.id("multiline_docs")
1014                    .max_h(max_height)
1015                    .flex_1()
1016                    .px_1p5()
1017                    .py_1()
1018                    .min_w(px(260.))
1019                    .max_w(px(640.))
1020                    .w(px(500.))
1021                    .overflow_y_scroll()
1022                    // Prevent a mouse down on documentation from being propagated to the editor,
1023                    // because that would move the cursor.
1024                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1025            })
1026        };
1027
1028        let list = uniform_list(
1029            cx.view().clone(),
1030            "completions",
1031            matches.len(),
1032            move |_editor, range, cx| {
1033                let start_ix = range.start;
1034                let completions_guard = completions.read();
1035
1036                matches[range]
1037                    .iter()
1038                    .enumerate()
1039                    .map(|(ix, mat)| {
1040                        let item_ix = start_ix + ix;
1041                        let candidate_id = mat.candidate_id;
1042                        let completion = &completions_guard[candidate_id];
1043
1044                        let documentation = if show_completion_documentation {
1045                            &completion.documentation
1046                        } else {
1047                            &None
1048                        };
1049
1050                        let highlights = gpui::combine_highlights(
1051                            mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1052                            styled_runs_for_code_label(&completion.label, &style.syntax).map(
1053                                |(range, mut highlight)| {
1054                                    // Ignore font weight for syntax highlighting, as we'll use it
1055                                    // for fuzzy matches.
1056                                    highlight.font_weight = None;
1057                                    (range, highlight)
1058                                },
1059                            ),
1060                        );
1061                        let completion_label = StyledText::new(completion.label.text.clone())
1062                            .with_highlights(&style.text, highlights);
1063                        let documentation_label =
1064                            if let Some(Documentation::SingleLine(text)) = documentation {
1065                                if text.trim().is_empty() {
1066                                    None
1067                                } else {
1068                                    Some(
1069                                        h_flex().ml_4().child(
1070                                            Label::new(text.clone())
1071                                                .size(LabelSize::Small)
1072                                                .color(Color::Muted),
1073                                        ),
1074                                    )
1075                                }
1076                            } else {
1077                                None
1078                            };
1079
1080                        div().min_w(px(220.)).max_w(px(540.)).child(
1081                            ListItem::new(mat.candidate_id)
1082                                .inset(true)
1083                                .selected(item_ix == selected_item)
1084                                .on_click(cx.listener(move |editor, _event, cx| {
1085                                    cx.stop_propagation();
1086                                    editor
1087                                        .confirm_completion(
1088                                            &ConfirmCompletion {
1089                                                item_ix: Some(item_ix),
1090                                            },
1091                                            cx,
1092                                        )
1093                                        .map(|task| task.detach_and_log_err(cx));
1094                                }))
1095                                .child(h_flex().overflow_hidden().child(completion_label))
1096                                .end_slot::<Div>(documentation_label),
1097                        )
1098                    })
1099                    .collect()
1100            },
1101        )
1102        .max_h(max_height)
1103        .track_scroll(self.scroll_handle.clone())
1104        .with_width_from_item(widest_completion_ix);
1105
1106        Popover::new()
1107            .child(list)
1108            .when_some(multiline_docs, |popover, multiline_docs| {
1109                popover.aside(multiline_docs)
1110            })
1111            .into_any_element()
1112    }
1113
1114    pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1115        let mut matches = if let Some(query) = query {
1116            fuzzy::match_strings(
1117                &self.match_candidates,
1118                query,
1119                query.chars().any(|c| c.is_uppercase()),
1120                100,
1121                &Default::default(),
1122                executor,
1123            )
1124            .await
1125        } else {
1126            self.match_candidates
1127                .iter()
1128                .enumerate()
1129                .map(|(candidate_id, candidate)| StringMatch {
1130                    candidate_id,
1131                    score: Default::default(),
1132                    positions: Default::default(),
1133                    string: candidate.string.clone(),
1134                })
1135                .collect()
1136        };
1137
1138        // Remove all candidates where the query's start does not match the start of any word in the candidate
1139        if let Some(query) = query {
1140            if let Some(query_start) = query.chars().next() {
1141                matches.retain(|string_match| {
1142                    split_words(&string_match.string).any(|word| {
1143                        // Check that the first codepoint of the word as lowercase matches the first
1144                        // codepoint of the query as lowercase
1145                        word.chars()
1146                            .flat_map(|codepoint| codepoint.to_lowercase())
1147                            .zip(query_start.to_lowercase())
1148                            .all(|(word_cp, query_cp)| word_cp == query_cp)
1149                    })
1150                });
1151            }
1152        }
1153
1154        let completions = self.completions.read();
1155        matches.sort_unstable_by_key(|mat| {
1156            let completion = &completions[mat.candidate_id];
1157            (
1158                completion.lsp_completion.sort_text.as_ref(),
1159                Reverse(OrderedFloat(mat.score)),
1160                completion.sort_key(),
1161            )
1162        });
1163
1164        for mat in &mut matches {
1165            let completion = &completions[mat.candidate_id];
1166            mat.string = completion.label.text.clone();
1167            for position in &mut mat.positions {
1168                *position += completion.label.filter_range.start;
1169            }
1170        }
1171        drop(completions);
1172
1173        self.matches = matches.into();
1174        self.selected_item = 0;
1175    }
1176}
1177
1178#[derive(Clone)]
1179struct CodeActionsMenu {
1180    actions: Arc<[CodeAction]>,
1181    buffer: Model<Buffer>,
1182    selected_item: usize,
1183    scroll_handle: UniformListScrollHandle,
1184    deployed_from_indicator: bool,
1185}
1186
1187impl CodeActionsMenu {
1188    fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1189        self.selected_item = 0;
1190        self.scroll_handle.scroll_to_item(self.selected_item);
1191        cx.notify()
1192    }
1193
1194    fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1195        if self.selected_item > 0 {
1196            self.selected_item -= 1;
1197        } else {
1198            self.selected_item = self.actions.len() - 1;
1199        }
1200        self.scroll_handle.scroll_to_item(self.selected_item);
1201        cx.notify();
1202    }
1203
1204    fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1205        if self.selected_item + 1 < self.actions.len() {
1206            self.selected_item += 1;
1207        } else {
1208            self.selected_item = 0;
1209        }
1210        self.scroll_handle.scroll_to_item(self.selected_item);
1211        cx.notify();
1212    }
1213
1214    fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1215        self.selected_item = self.actions.len() - 1;
1216        self.scroll_handle.scroll_to_item(self.selected_item);
1217        cx.notify()
1218    }
1219
1220    fn visible(&self) -> bool {
1221        !self.actions.is_empty()
1222    }
1223
1224    fn render(
1225        &self,
1226        mut cursor_position: DisplayPoint,
1227        _style: &EditorStyle,
1228        max_height: Pixels,
1229        cx: &mut ViewContext<Editor>,
1230    ) -> (DisplayPoint, AnyElement) {
1231        let actions = self.actions.clone();
1232        let selected_item = self.selected_item;
1233
1234        let element = uniform_list(
1235            cx.view().clone(),
1236            "code_actions_menu",
1237            self.actions.len(),
1238            move |_this, range, cx| {
1239                actions[range.clone()]
1240                    .iter()
1241                    .enumerate()
1242                    .map(|(ix, action)| {
1243                        let item_ix = range.start + ix;
1244                        let selected = selected_item == item_ix;
1245                        let colors = cx.theme().colors();
1246                        div()
1247                            .px_2()
1248                            .text_color(colors.text)
1249                            .when(selected, |style| {
1250                                style
1251                                    .bg(colors.element_active)
1252                                    .text_color(colors.text_accent)
1253                            })
1254                            .hover(|style| {
1255                                style
1256                                    .bg(colors.element_hover)
1257                                    .text_color(colors.text_accent)
1258                            })
1259                            .on_mouse_down(
1260                                MouseButton::Left,
1261                                cx.listener(move |editor, _, cx| {
1262                                    cx.stop_propagation();
1263                                    editor
1264                                        .confirm_code_action(
1265                                            &ConfirmCodeAction {
1266                                                item_ix: Some(item_ix),
1267                                            },
1268                                            cx,
1269                                        )
1270                                        .map(|task| task.detach_and_log_err(cx));
1271                                }),
1272                            )
1273                            // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1274                            .child(SharedString::from(action.lsp_action.title.clone()))
1275                    })
1276                    .collect()
1277            },
1278        )
1279        .elevation_1(cx)
1280        .px_2()
1281        .py_1()
1282        .max_h(max_height)
1283        .track_scroll(self.scroll_handle.clone())
1284        .with_width_from_item(
1285            self.actions
1286                .iter()
1287                .enumerate()
1288                .max_by_key(|(_, action)| action.lsp_action.title.chars().count())
1289                .map(|(ix, _)| ix),
1290        )
1291        .into_any_element();
1292
1293        if self.deployed_from_indicator {
1294            *cursor_position.column_mut() = 0;
1295        }
1296
1297        (cursor_position, element)
1298    }
1299}
1300
1301pub(crate) struct CopilotState {
1302    excerpt_id: Option<ExcerptId>,
1303    pending_refresh: Task<Option<()>>,
1304    pending_cycling_refresh: Task<Option<()>>,
1305    cycled: bool,
1306    completions: Vec<copilot::Completion>,
1307    active_completion_index: usize,
1308    suggestion: Option<Inlay>,
1309}
1310
1311impl Default for CopilotState {
1312    fn default() -> Self {
1313        Self {
1314            excerpt_id: None,
1315            pending_cycling_refresh: Task::ready(Some(())),
1316            pending_refresh: Task::ready(Some(())),
1317            completions: Default::default(),
1318            active_completion_index: 0,
1319            cycled: false,
1320            suggestion: None,
1321        }
1322    }
1323}
1324
1325impl CopilotState {
1326    fn active_completion(&self) -> Option<&copilot::Completion> {
1327        self.completions.get(self.active_completion_index)
1328    }
1329
1330    fn text_for_active_completion(
1331        &self,
1332        cursor: Anchor,
1333        buffer: &MultiBufferSnapshot,
1334    ) -> Option<&str> {
1335        use language::ToOffset as _;
1336
1337        let completion = self.active_completion()?;
1338        let excerpt_id = self.excerpt_id?;
1339        let completion_buffer = buffer.buffer_for_excerpt(excerpt_id)?;
1340        if excerpt_id != cursor.excerpt_id
1341            || !completion.range.start.is_valid(completion_buffer)
1342            || !completion.range.end.is_valid(completion_buffer)
1343        {
1344            return None;
1345        }
1346
1347        let mut completion_range = completion.range.to_offset(&completion_buffer);
1348        let prefix_len = Self::common_prefix(
1349            completion_buffer.chars_for_range(completion_range.clone()),
1350            completion.text.chars(),
1351        );
1352        completion_range.start += prefix_len;
1353        let suffix_len = Self::common_prefix(
1354            completion_buffer.reversed_chars_for_range(completion_range.clone()),
1355            completion.text[prefix_len..].chars().rev(),
1356        );
1357        completion_range.end = completion_range.end.saturating_sub(suffix_len);
1358
1359        if completion_range.is_empty()
1360            && completion_range.start == cursor.text_anchor.to_offset(&completion_buffer)
1361        {
1362            Some(&completion.text[prefix_len..completion.text.len() - suffix_len])
1363        } else {
1364            None
1365        }
1366    }
1367
1368    fn cycle_completions(&mut self, direction: Direction) {
1369        match direction {
1370            Direction::Prev => {
1371                self.active_completion_index = if self.active_completion_index == 0 {
1372                    self.completions.len().saturating_sub(1)
1373                } else {
1374                    self.active_completion_index - 1
1375                };
1376            }
1377            Direction::Next => {
1378                if self.completions.len() == 0 {
1379                    self.active_completion_index = 0
1380                } else {
1381                    self.active_completion_index =
1382                        (self.active_completion_index + 1) % self.completions.len();
1383                }
1384            }
1385        }
1386    }
1387
1388    fn push_completion(&mut self, new_completion: copilot::Completion) {
1389        for completion in &self.completions {
1390            if completion.text == new_completion.text && completion.range == new_completion.range {
1391                return;
1392            }
1393        }
1394        self.completions.push(new_completion);
1395    }
1396
1397    fn common_prefix<T1: Iterator<Item = char>, T2: Iterator<Item = char>>(a: T1, b: T2) -> usize {
1398        a.zip(b)
1399            .take_while(|(a, b)| a == b)
1400            .map(|(a, _)| a.len_utf8())
1401            .sum()
1402    }
1403}
1404
1405#[derive(Debug)]
1406struct ActiveDiagnosticGroup {
1407    primary_range: Range<Anchor>,
1408    primary_message: String,
1409    blocks: HashMap<BlockId, Diagnostic>,
1410    is_valid: bool,
1411}
1412
1413#[derive(Serialize, Deserialize)]
1414pub struct ClipboardSelection {
1415    pub len: usize,
1416    pub is_entire_line: bool,
1417    pub first_line_indent: u32,
1418}
1419
1420#[derive(Debug)]
1421pub(crate) struct NavigationData {
1422    cursor_anchor: Anchor,
1423    cursor_position: Point,
1424    scroll_anchor: ScrollAnchor,
1425    scroll_top_row: u32,
1426}
1427
1428enum GotoDefinitionKind {
1429    Symbol,
1430    Type,
1431}
1432
1433#[derive(Debug, Clone)]
1434enum InlayHintRefreshReason {
1435    Toggle(bool),
1436    SettingsChange(InlayHintSettings),
1437    NewLinesShown,
1438    BufferEdited(HashSet<Arc<Language>>),
1439    RefreshRequested,
1440    ExcerptsRemoved(Vec<ExcerptId>),
1441}
1442impl InlayHintRefreshReason {
1443    fn description(&self) -> &'static str {
1444        match self {
1445            Self::Toggle(_) => "toggle",
1446            Self::SettingsChange(_) => "settings change",
1447            Self::NewLinesShown => "new lines shown",
1448            Self::BufferEdited(_) => "buffer edited",
1449            Self::RefreshRequested => "refresh requested",
1450            Self::ExcerptsRemoved(_) => "excerpts removed",
1451        }
1452    }
1453}
1454
1455impl Editor {
1456    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1457        let buffer = cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), String::new()));
1458        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1459        Self::new(EditorMode::SingleLine, buffer, None, cx)
1460    }
1461
1462    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1463        let buffer = cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), String::new()));
1464        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1465        Self::new(EditorMode::Full, buffer, None, cx)
1466    }
1467
1468    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1469        let buffer = cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), String::new()));
1470        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1471        Self::new(EditorMode::AutoHeight { max_lines }, buffer, None, cx)
1472    }
1473
1474    pub fn for_buffer(
1475        buffer: Model<Buffer>,
1476        project: Option<Model<Project>>,
1477        cx: &mut ViewContext<Self>,
1478    ) -> Self {
1479        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1480        Self::new(EditorMode::Full, buffer, project, cx)
1481    }
1482
1483    pub fn for_multibuffer(
1484        buffer: Model<MultiBuffer>,
1485        project: Option<Model<Project>>,
1486        cx: &mut ViewContext<Self>,
1487    ) -> Self {
1488        Self::new(EditorMode::Full, buffer, project, cx)
1489    }
1490
1491    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1492        let mut clone = Self::new(self.mode, self.buffer.clone(), self.project.clone(), cx);
1493        self.display_map.update(cx, |display_map, cx| {
1494            let snapshot = display_map.snapshot(cx);
1495            clone.display_map.update(cx, |display_map, cx| {
1496                display_map.set_state(&snapshot, cx);
1497            });
1498        });
1499        clone.selections.clone_state(&self.selections);
1500        clone.scroll_manager.clone_state(&self.scroll_manager);
1501        clone.searchable = self.searchable;
1502        clone
1503    }
1504
1505    fn new(
1506        mode: EditorMode,
1507        buffer: Model<MultiBuffer>,
1508        project: Option<Model<Project>>,
1509        cx: &mut ViewContext<Self>,
1510    ) -> Self {
1511        let style = cx.text_style();
1512        let font_size = style.font_size.to_pixels(cx.rem_size());
1513        let display_map = cx.new_model(|cx| {
1514            DisplayMap::new(buffer.clone(), style.font(), font_size, None, 2, 1, cx)
1515        });
1516
1517        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1518
1519        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1520
1521        let soft_wrap_mode_override =
1522            (mode == EditorMode::SingleLine).then(|| language_settings::SoftWrap::None);
1523
1524        let mut project_subscriptions = Vec::new();
1525        if mode == EditorMode::Full {
1526            if let Some(project) = project.as_ref() {
1527                if buffer.read(cx).is_singleton() {
1528                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
1529                        cx.emit(EditorEvent::TitleChanged);
1530                    }));
1531                }
1532                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1533                    if let project::Event::RefreshInlayHints = event {
1534                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1535                    };
1536                }));
1537            }
1538        }
1539
1540        let inlay_hint_settings = inlay_hint_settings(
1541            selections.newest_anchor().head(),
1542            &buffer.read(cx).snapshot(cx),
1543            cx,
1544        );
1545
1546        let focus_handle = cx.focus_handle();
1547        cx.on_focus(&focus_handle, Self::handle_focus).detach();
1548        cx.on_blur(&focus_handle, Self::handle_blur).detach();
1549
1550        let mut this = Self {
1551            handle: cx.view().downgrade(),
1552            focus_handle,
1553            buffer: buffer.clone(),
1554            display_map: display_map.clone(),
1555            selections,
1556            scroll_manager: ScrollManager::new(),
1557            columnar_selection_tail: None,
1558            add_selections_state: None,
1559            select_next_state: None,
1560            select_prev_state: None,
1561            selection_history: Default::default(),
1562            autoclose_regions: Default::default(),
1563            snippet_stack: Default::default(),
1564            select_larger_syntax_node_stack: Vec::new(),
1565            ime_transaction: Default::default(),
1566            active_diagnostics: None,
1567            soft_wrap_mode_override,
1568            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1569            project,
1570            blink_manager: blink_manager.clone(),
1571            show_local_selections: true,
1572            mode,
1573            show_gutter: mode == EditorMode::Full,
1574            show_wrap_guides: None,
1575            placeholder_text: None,
1576            highlighted_rows: None,
1577            background_highlights: Default::default(),
1578            inlay_background_highlights: Default::default(),
1579            nav_history: None,
1580            context_menu: RwLock::new(None),
1581            mouse_context_menu: None,
1582            completion_tasks: Default::default(),
1583            next_completion_id: 0,
1584            next_inlay_id: 0,
1585            available_code_actions: Default::default(),
1586            code_actions_task: Default::default(),
1587            document_highlights_task: Default::default(),
1588            pending_rename: Default::default(),
1589            searchable: true,
1590            cursor_shape: Default::default(),
1591            autoindent_mode: Some(AutoindentMode::EachLine),
1592            collapse_matches: false,
1593            workspace: None,
1594            keymap_context_layers: Default::default(),
1595            input_enabled: true,
1596            read_only: false,
1597            leader_peer_id: None,
1598            remote_id: None,
1599            hover_state: Default::default(),
1600            link_go_to_definition_state: Default::default(),
1601            copilot_state: Default::default(),
1602            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1603            gutter_hovered: false,
1604            pixel_position_of_newest_cursor: None,
1605            gutter_width: Default::default(),
1606            style: None,
1607            editor_actions: Default::default(),
1608            show_copilot_suggestions: mode == EditorMode::Full,
1609            _subscriptions: vec![
1610                cx.observe(&buffer, Self::on_buffer_changed),
1611                cx.subscribe(&buffer, Self::on_buffer_event),
1612                cx.observe(&display_map, Self::on_display_map_changed),
1613                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1614                cx.observe_global::<SettingsStore>(Self::settings_changed),
1615                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1616                cx.observe_window_activation(|editor, cx| {
1617                    let active = cx.is_window_active();
1618                    editor.blink_manager.update(cx, |blink_manager, cx| {
1619                        if active {
1620                            blink_manager.enable(cx);
1621                        } else {
1622                            blink_manager.show_cursor(cx);
1623                            blink_manager.disable(cx);
1624                        }
1625                    });
1626                }),
1627            ],
1628        };
1629
1630        this._subscriptions.extend(project_subscriptions);
1631
1632        this.end_selection(cx);
1633        this.scroll_manager.show_scrollbar(cx);
1634
1635        if mode == EditorMode::Full {
1636            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1637            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1638        }
1639
1640        this.report_editor_event("open", None, cx);
1641        this
1642    }
1643
1644    fn key_context(&self, cx: &AppContext) -> KeyContext {
1645        let mut key_context = KeyContext::default();
1646        key_context.add("Editor");
1647        let mode = match self.mode {
1648            EditorMode::SingleLine => "single_line",
1649            EditorMode::AutoHeight { .. } => "auto_height",
1650            EditorMode::Full => "full",
1651        };
1652        key_context.set("mode", mode);
1653        if self.pending_rename.is_some() {
1654            key_context.add("renaming");
1655        }
1656        if self.context_menu_visible() {
1657            match self.context_menu.read().as_ref() {
1658                Some(ContextMenu::Completions(_)) => {
1659                    key_context.add("menu");
1660                    key_context.add("showing_completions")
1661                }
1662                Some(ContextMenu::CodeActions(_)) => {
1663                    key_context.add("menu");
1664                    key_context.add("showing_code_actions")
1665                }
1666                None => {}
1667            }
1668        }
1669
1670        for layer in self.keymap_context_layers.values() {
1671            key_context.extend(layer);
1672        }
1673
1674        if let Some(extension) = self
1675            .buffer
1676            .read(cx)
1677            .as_singleton()
1678            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
1679        {
1680            key_context.set("extension", extension.to_string());
1681        }
1682
1683        key_context
1684    }
1685
1686    pub fn new_file(
1687        workspace: &mut Workspace,
1688        _: &workspace::NewFile,
1689        cx: &mut ViewContext<Workspace>,
1690    ) {
1691        let project = workspace.project().clone();
1692        if project.read(cx).is_remote() {
1693            cx.propagate();
1694        } else if let Some(buffer) = project
1695            .update(cx, |project, cx| project.create_buffer("", None, cx))
1696            .log_err()
1697        {
1698            workspace.add_item(
1699                Box::new(cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx))),
1700                cx,
1701            );
1702        }
1703    }
1704
1705    pub fn new_file_in_direction(
1706        workspace: &mut Workspace,
1707        action: &workspace::NewFileInDirection,
1708        cx: &mut ViewContext<Workspace>,
1709    ) {
1710        let project = workspace.project().clone();
1711        if project.read(cx).is_remote() {
1712            cx.propagate();
1713        } else if let Some(buffer) = project
1714            .update(cx, |project, cx| project.create_buffer("", None, cx))
1715            .log_err()
1716        {
1717            workspace.split_item(
1718                action.0,
1719                Box::new(cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx))),
1720                cx,
1721            );
1722        }
1723    }
1724
1725    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
1726        self.buffer.read(cx).replica_id()
1727    }
1728
1729    pub fn leader_peer_id(&self) -> Option<PeerId> {
1730        self.leader_peer_id
1731    }
1732
1733    pub fn buffer(&self) -> &Model<MultiBuffer> {
1734        &self.buffer
1735    }
1736
1737    pub fn workspace(&self) -> Option<View<Workspace>> {
1738        self.workspace.as_ref()?.0.upgrade()
1739    }
1740
1741    pub fn pane(&self, cx: &AppContext) -> Option<View<Pane>> {
1742        self.workspace()?.read(cx).pane_for(&self.handle.upgrade()?)
1743    }
1744
1745    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
1746        self.buffer().read(cx).title(cx)
1747    }
1748
1749    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
1750        EditorSnapshot {
1751            mode: self.mode,
1752            show_gutter: self.show_gutter,
1753            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
1754            scroll_anchor: self.scroll_manager.anchor(),
1755            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
1756            placeholder_text: self.placeholder_text.clone(),
1757            is_focused: self.focus_handle.is_focused(cx),
1758        }
1759    }
1760
1761    pub fn language_at<'a, T: ToOffset>(
1762        &self,
1763        point: T,
1764        cx: &'a AppContext,
1765    ) -> Option<Arc<Language>> {
1766        self.buffer.read(cx).language_at(point, cx)
1767    }
1768
1769    pub fn file_at<'a, T: ToOffset>(
1770        &self,
1771        point: T,
1772        cx: &'a AppContext,
1773    ) -> Option<Arc<dyn language::File>> {
1774        self.buffer.read(cx).read(cx).file_at(point).cloned()
1775    }
1776
1777    pub fn active_excerpt(
1778        &self,
1779        cx: &AppContext,
1780    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
1781        self.buffer
1782            .read(cx)
1783            .excerpt_containing(self.selections.newest_anchor().head(), cx)
1784    }
1785
1786    pub fn mode(&self) -> EditorMode {
1787        self.mode
1788    }
1789
1790    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
1791        self.collaboration_hub.as_deref()
1792    }
1793
1794    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
1795        self.collaboration_hub = Some(hub);
1796    }
1797
1798    pub fn placeholder_text(&self) -> Option<&str> {
1799        self.placeholder_text.as_deref()
1800    }
1801
1802    pub fn set_placeholder_text(
1803        &mut self,
1804        placeholder_text: impl Into<Arc<str>>,
1805        cx: &mut ViewContext<Self>,
1806    ) {
1807        let placeholder_text = Some(placeholder_text.into());
1808        if self.placeholder_text != placeholder_text {
1809            self.placeholder_text = placeholder_text;
1810            cx.notify();
1811        }
1812    }
1813
1814    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
1815        self.cursor_shape = cursor_shape;
1816        cx.notify();
1817    }
1818
1819    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
1820        self.collapse_matches = collapse_matches;
1821    }
1822
1823    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
1824        if self.collapse_matches {
1825            return range.start..range.start;
1826        }
1827        range.clone()
1828    }
1829
1830    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
1831        if self.display_map.read(cx).clip_at_line_ends != clip {
1832            self.display_map
1833                .update(cx, |map, _| map.clip_at_line_ends = clip);
1834        }
1835    }
1836
1837    pub fn set_keymap_context_layer<Tag: 'static>(
1838        &mut self,
1839        context: KeyContext,
1840        cx: &mut ViewContext<Self>,
1841    ) {
1842        self.keymap_context_layers
1843            .insert(TypeId::of::<Tag>(), context);
1844        cx.notify();
1845    }
1846
1847    pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
1848        self.keymap_context_layers.remove(&TypeId::of::<Tag>());
1849        cx.notify();
1850    }
1851
1852    pub fn set_input_enabled(&mut self, input_enabled: bool) {
1853        self.input_enabled = input_enabled;
1854    }
1855
1856    pub fn set_autoindent(&mut self, autoindent: bool) {
1857        if autoindent {
1858            self.autoindent_mode = Some(AutoindentMode::EachLine);
1859        } else {
1860            self.autoindent_mode = None;
1861        }
1862    }
1863
1864    pub fn read_only(&self, cx: &AppContext) -> bool {
1865        self.read_only || self.buffer.read(cx).read_only()
1866    }
1867
1868    pub fn set_read_only(&mut self, read_only: bool) {
1869        self.read_only = read_only;
1870    }
1871
1872    pub fn set_show_copilot_suggestions(&mut self, show_copilot_suggestions: bool) {
1873        self.show_copilot_suggestions = show_copilot_suggestions;
1874    }
1875
1876    fn selections_did_change(
1877        &mut self,
1878        local: bool,
1879        old_cursor_position: &Anchor,
1880        cx: &mut ViewContext<Self>,
1881    ) {
1882        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
1883            self.buffer.update(cx, |buffer, cx| {
1884                buffer.set_active_selections(
1885                    &self.selections.disjoint_anchors(),
1886                    self.selections.line_mode,
1887                    self.cursor_shape,
1888                    cx,
1889                )
1890            });
1891        }
1892
1893        let display_map = self
1894            .display_map
1895            .update(cx, |display_map, cx| display_map.snapshot(cx));
1896        let buffer = &display_map.buffer_snapshot;
1897        self.add_selections_state = None;
1898        self.select_next_state = None;
1899        self.select_prev_state = None;
1900        self.select_larger_syntax_node_stack.clear();
1901        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
1902        self.snippet_stack
1903            .invalidate(&self.selections.disjoint_anchors(), buffer);
1904        self.take_rename(false, cx);
1905
1906        let new_cursor_position = self.selections.newest_anchor().head();
1907
1908        self.push_to_nav_history(
1909            old_cursor_position.clone(),
1910            Some(new_cursor_position.to_point(buffer)),
1911            cx,
1912        );
1913
1914        if local {
1915            let new_cursor_position = self.selections.newest_anchor().head();
1916            let mut context_menu = self.context_menu.write();
1917            let completion_menu = match context_menu.as_ref() {
1918                Some(ContextMenu::Completions(menu)) => Some(menu),
1919
1920                _ => {
1921                    *context_menu = None;
1922                    None
1923                }
1924            };
1925
1926            if let Some(completion_menu) = completion_menu {
1927                let cursor_position = new_cursor_position.to_offset(buffer);
1928                let (word_range, kind) =
1929                    buffer.surrounding_word(completion_menu.initial_position.clone());
1930                if kind == Some(CharKind::Word)
1931                    && word_range.to_inclusive().contains(&cursor_position)
1932                {
1933                    let mut completion_menu = completion_menu.clone();
1934                    drop(context_menu);
1935
1936                    let query = Self::completion_query(buffer, cursor_position);
1937                    cx.spawn(move |this, mut cx| async move {
1938                        completion_menu
1939                            .filter(query.as_deref(), cx.background_executor().clone())
1940                            .await;
1941
1942                        this.update(&mut cx, |this, cx| {
1943                            let mut context_menu = this.context_menu.write();
1944                            let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
1945                                return;
1946                            };
1947
1948                            if menu.id > completion_menu.id {
1949                                return;
1950                            }
1951
1952                            *context_menu = Some(ContextMenu::Completions(completion_menu));
1953                            drop(context_menu);
1954                            cx.notify();
1955                        })
1956                    })
1957                    .detach();
1958
1959                    self.show_completions(&ShowCompletions, cx);
1960                } else {
1961                    drop(context_menu);
1962                    self.hide_context_menu(cx);
1963                }
1964            } else {
1965                drop(context_menu);
1966            }
1967
1968            hide_hover(self, cx);
1969
1970            if old_cursor_position.to_display_point(&display_map).row()
1971                != new_cursor_position.to_display_point(&display_map).row()
1972            {
1973                self.available_code_actions.take();
1974            }
1975            self.refresh_code_actions(cx);
1976            self.refresh_document_highlights(cx);
1977            refresh_matching_bracket_highlights(self, cx);
1978            self.discard_copilot_suggestion(cx);
1979        }
1980
1981        self.blink_manager.update(cx, BlinkManager::pause_blinking);
1982        cx.emit(EditorEvent::SelectionsChanged { local });
1983
1984        if self.selections.disjoint_anchors().len() == 1 {
1985            cx.emit(SearchEvent::ActiveMatchChanged)
1986        }
1987
1988        cx.notify();
1989    }
1990
1991    pub fn change_selections<R>(
1992        &mut self,
1993        autoscroll: Option<Autoscroll>,
1994        cx: &mut ViewContext<Self>,
1995        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
1996    ) -> R {
1997        let old_cursor_position = self.selections.newest_anchor().head();
1998        self.push_to_selection_history();
1999
2000        let (changed, result) = self.selections.change_with(cx, change);
2001
2002        if changed {
2003            if let Some(autoscroll) = autoscroll {
2004                self.request_autoscroll(autoscroll, cx);
2005            }
2006            self.selections_did_change(true, &old_cursor_position, cx);
2007        }
2008
2009        result
2010    }
2011
2012    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2013    where
2014        I: IntoIterator<Item = (Range<S>, T)>,
2015        S: ToOffset,
2016        T: Into<Arc<str>>,
2017    {
2018        if self.read_only(cx) {
2019            return;
2020        }
2021
2022        self.buffer
2023            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2024    }
2025
2026    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2027    where
2028        I: IntoIterator<Item = (Range<S>, T)>,
2029        S: ToOffset,
2030        T: Into<Arc<str>>,
2031    {
2032        if self.read_only(cx) {
2033            return;
2034        }
2035
2036        self.buffer.update(cx, |buffer, cx| {
2037            buffer.edit(edits, self.autoindent_mode.clone(), cx)
2038        });
2039    }
2040
2041    pub fn edit_with_block_indent<I, S, T>(
2042        &mut self,
2043        edits: I,
2044        original_indent_columns: Vec<u32>,
2045        cx: &mut ViewContext<Self>,
2046    ) where
2047        I: IntoIterator<Item = (Range<S>, T)>,
2048        S: ToOffset,
2049        T: Into<Arc<str>>,
2050    {
2051        if self.read_only(cx) {
2052            return;
2053        }
2054
2055        self.buffer.update(cx, |buffer, cx| {
2056            buffer.edit(
2057                edits,
2058                Some(AutoindentMode::Block {
2059                    original_indent_columns,
2060                }),
2061                cx,
2062            )
2063        });
2064    }
2065
2066    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2067        self.hide_context_menu(cx);
2068
2069        match phase {
2070            SelectPhase::Begin {
2071                position,
2072                add,
2073                click_count,
2074            } => self.begin_selection(position, add, click_count, cx),
2075            SelectPhase::BeginColumnar {
2076                position,
2077                goal_column,
2078            } => self.begin_columnar_selection(position, goal_column, cx),
2079            SelectPhase::Extend {
2080                position,
2081                click_count,
2082            } => self.extend_selection(position, click_count, cx),
2083            SelectPhase::Update {
2084                position,
2085                goal_column,
2086                scroll_position,
2087            } => self.update_selection(position, goal_column, scroll_position, cx),
2088            SelectPhase::End => self.end_selection(cx),
2089        }
2090    }
2091
2092    fn extend_selection(
2093        &mut self,
2094        position: DisplayPoint,
2095        click_count: usize,
2096        cx: &mut ViewContext<Self>,
2097    ) {
2098        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2099        let tail = self.selections.newest::<usize>(cx).tail();
2100        self.begin_selection(position, false, click_count, cx);
2101
2102        let position = position.to_offset(&display_map, Bias::Left);
2103        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2104
2105        let mut pending_selection = self
2106            .selections
2107            .pending_anchor()
2108            .expect("extend_selection not called with pending selection");
2109        if position >= tail {
2110            pending_selection.start = tail_anchor;
2111        } else {
2112            pending_selection.end = tail_anchor;
2113            pending_selection.reversed = true;
2114        }
2115
2116        let mut pending_mode = self.selections.pending_mode().unwrap();
2117        match &mut pending_mode {
2118            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2119            _ => {}
2120        }
2121
2122        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2123            s.set_pending(pending_selection, pending_mode)
2124        });
2125    }
2126
2127    fn begin_selection(
2128        &mut self,
2129        position: DisplayPoint,
2130        add: bool,
2131        click_count: usize,
2132        cx: &mut ViewContext<Self>,
2133    ) {
2134        if !self.focus_handle.is_focused(cx) {
2135            cx.focus(&self.focus_handle);
2136        }
2137
2138        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2139        let buffer = &display_map.buffer_snapshot;
2140        let newest_selection = self.selections.newest_anchor().clone();
2141        let position = display_map.clip_point(position, Bias::Left);
2142
2143        let start;
2144        let end;
2145        let mode;
2146        let auto_scroll;
2147        match click_count {
2148            1 => {
2149                start = buffer.anchor_before(position.to_point(&display_map));
2150                end = start.clone();
2151                mode = SelectMode::Character;
2152                auto_scroll = true;
2153            }
2154            2 => {
2155                let range = movement::surrounding_word(&display_map, position);
2156                start = buffer.anchor_before(range.start.to_point(&display_map));
2157                end = buffer.anchor_before(range.end.to_point(&display_map));
2158                mode = SelectMode::Word(start.clone()..end.clone());
2159                auto_scroll = true;
2160            }
2161            3 => {
2162                let position = display_map
2163                    .clip_point(position, Bias::Left)
2164                    .to_point(&display_map);
2165                let line_start = display_map.prev_line_boundary(position).0;
2166                let next_line_start = buffer.clip_point(
2167                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
2168                    Bias::Left,
2169                );
2170                start = buffer.anchor_before(line_start);
2171                end = buffer.anchor_before(next_line_start);
2172                mode = SelectMode::Line(start.clone()..end.clone());
2173                auto_scroll = true;
2174            }
2175            _ => {
2176                start = buffer.anchor_before(0);
2177                end = buffer.anchor_before(buffer.len());
2178                mode = SelectMode::All;
2179                auto_scroll = false;
2180            }
2181        }
2182
2183        self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2184            if !add {
2185                s.clear_disjoint();
2186            } else if click_count > 1 {
2187                s.delete(newest_selection.id)
2188            }
2189
2190            s.set_pending_anchor_range(start..end, mode);
2191        });
2192    }
2193
2194    fn begin_columnar_selection(
2195        &mut self,
2196        position: DisplayPoint,
2197        goal_column: u32,
2198        cx: &mut ViewContext<Self>,
2199    ) {
2200        if !self.focus_handle.is_focused(cx) {
2201            cx.focus(&self.focus_handle);
2202        }
2203
2204        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2205        let tail = self.selections.newest::<Point>(cx).tail();
2206        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2207
2208        self.select_columns(
2209            tail.to_display_point(&display_map),
2210            position,
2211            goal_column,
2212            &display_map,
2213            cx,
2214        );
2215    }
2216
2217    fn update_selection(
2218        &mut self,
2219        position: DisplayPoint,
2220        goal_column: u32,
2221        scroll_position: gpui::Point<f32>,
2222        cx: &mut ViewContext<Self>,
2223    ) {
2224        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2225
2226        if let Some(tail) = self.columnar_selection_tail.as_ref() {
2227            let tail = tail.to_display_point(&display_map);
2228            self.select_columns(tail, position, goal_column, &display_map, cx);
2229        } else if let Some(mut pending) = self.selections.pending_anchor() {
2230            let buffer = self.buffer.read(cx).snapshot(cx);
2231            let head;
2232            let tail;
2233            let mode = self.selections.pending_mode().unwrap();
2234            match &mode {
2235                SelectMode::Character => {
2236                    head = position.to_point(&display_map);
2237                    tail = pending.tail().to_point(&buffer);
2238                }
2239                SelectMode::Word(original_range) => {
2240                    let original_display_range = original_range.start.to_display_point(&display_map)
2241                        ..original_range.end.to_display_point(&display_map);
2242                    let original_buffer_range = original_display_range.start.to_point(&display_map)
2243                        ..original_display_range.end.to_point(&display_map);
2244                    if movement::is_inside_word(&display_map, position)
2245                        || original_display_range.contains(&position)
2246                    {
2247                        let word_range = movement::surrounding_word(&display_map, position);
2248                        if word_range.start < original_display_range.start {
2249                            head = word_range.start.to_point(&display_map);
2250                        } else {
2251                            head = word_range.end.to_point(&display_map);
2252                        }
2253                    } else {
2254                        head = position.to_point(&display_map);
2255                    }
2256
2257                    if head <= original_buffer_range.start {
2258                        tail = original_buffer_range.end;
2259                    } else {
2260                        tail = original_buffer_range.start;
2261                    }
2262                }
2263                SelectMode::Line(original_range) => {
2264                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
2265
2266                    let position = display_map
2267                        .clip_point(position, Bias::Left)
2268                        .to_point(&display_map);
2269                    let line_start = display_map.prev_line_boundary(position).0;
2270                    let next_line_start = buffer.clip_point(
2271                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
2272                        Bias::Left,
2273                    );
2274
2275                    if line_start < original_range.start {
2276                        head = line_start
2277                    } else {
2278                        head = next_line_start
2279                    }
2280
2281                    if head <= original_range.start {
2282                        tail = original_range.end;
2283                    } else {
2284                        tail = original_range.start;
2285                    }
2286                }
2287                SelectMode::All => {
2288                    return;
2289                }
2290            };
2291
2292            if head < tail {
2293                pending.start = buffer.anchor_before(head);
2294                pending.end = buffer.anchor_before(tail);
2295                pending.reversed = true;
2296            } else {
2297                pending.start = buffer.anchor_before(tail);
2298                pending.end = buffer.anchor_before(head);
2299                pending.reversed = false;
2300            }
2301
2302            self.change_selections(None, cx, |s| {
2303                s.set_pending(pending, mode);
2304            });
2305        } else {
2306            log::error!("update_selection dispatched with no pending selection");
2307            return;
2308        }
2309
2310        self.set_scroll_position(scroll_position, cx);
2311        cx.notify();
2312    }
2313
2314    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2315        self.columnar_selection_tail.take();
2316        if self.selections.pending_anchor().is_some() {
2317            let selections = self.selections.all::<usize>(cx);
2318            self.change_selections(None, cx, |s| {
2319                s.select(selections);
2320                s.clear_pending();
2321            });
2322        }
2323    }
2324
2325    fn select_columns(
2326        &mut self,
2327        tail: DisplayPoint,
2328        head: DisplayPoint,
2329        goal_column: u32,
2330        display_map: &DisplaySnapshot,
2331        cx: &mut ViewContext<Self>,
2332    ) {
2333        let start_row = cmp::min(tail.row(), head.row());
2334        let end_row = cmp::max(tail.row(), head.row());
2335        let start_column = cmp::min(tail.column(), goal_column);
2336        let end_column = cmp::max(tail.column(), goal_column);
2337        let reversed = start_column < tail.column();
2338
2339        let selection_ranges = (start_row..=end_row)
2340            .filter_map(|row| {
2341                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2342                    let start = display_map
2343                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2344                        .to_point(display_map);
2345                    let end = display_map
2346                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2347                        .to_point(display_map);
2348                    if reversed {
2349                        Some(end..start)
2350                    } else {
2351                        Some(start..end)
2352                    }
2353                } else {
2354                    None
2355                }
2356            })
2357            .collect::<Vec<_>>();
2358
2359        self.change_selections(None, cx, |s| {
2360            s.select_ranges(selection_ranges);
2361        });
2362        cx.notify();
2363    }
2364
2365    pub fn has_pending_nonempty_selection(&self) -> bool {
2366        let pending_nonempty_selection = match self.selections.pending_anchor() {
2367            Some(Selection { start, end, .. }) => start != end,
2368            None => false,
2369        };
2370        pending_nonempty_selection || self.columnar_selection_tail.is_some()
2371    }
2372
2373    pub fn has_pending_selection(&self) -> bool {
2374        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2375    }
2376
2377    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2378        if self.take_rename(false, cx).is_some() {
2379            return;
2380        }
2381
2382        if hide_hover(self, cx) {
2383            return;
2384        }
2385
2386        if self.hide_context_menu(cx).is_some() {
2387            return;
2388        }
2389
2390        if self.discard_copilot_suggestion(cx) {
2391            return;
2392        }
2393
2394        if self.snippet_stack.pop().is_some() {
2395            return;
2396        }
2397
2398        if self.mode == EditorMode::Full {
2399            if self.active_diagnostics.is_some() {
2400                self.dismiss_diagnostics(cx);
2401                return;
2402            }
2403
2404            if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2405                return;
2406            }
2407        }
2408
2409        cx.propagate();
2410    }
2411
2412    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2413        let text: Arc<str> = text.into();
2414
2415        if self.read_only(cx) {
2416            return;
2417        }
2418
2419        let selections = self.selections.all_adjusted(cx);
2420        let mut brace_inserted = false;
2421        let mut edits = Vec::new();
2422        let mut new_selections = Vec::with_capacity(selections.len());
2423        let mut new_autoclose_regions = Vec::new();
2424        let snapshot = self.buffer.read(cx).read(cx);
2425
2426        for (selection, autoclose_region) in
2427            self.selections_with_autoclose_regions(selections, &snapshot)
2428        {
2429            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
2430                // Determine if the inserted text matches the opening or closing
2431                // bracket of any of this language's bracket pairs.
2432                let mut bracket_pair = None;
2433                let mut is_bracket_pair_start = false;
2434                if !text.is_empty() {
2435                    // `text` can be empty when an user is using IME (e.g. Chinese Wubi Simplified)
2436                    //  and they are removing the character that triggered IME popup.
2437                    for (pair, enabled) in scope.brackets() {
2438                        if enabled && pair.close && pair.start.ends_with(text.as_ref()) {
2439                            bracket_pair = Some(pair.clone());
2440                            is_bracket_pair_start = true;
2441                            break;
2442                        } else if pair.end.as_str() == text.as_ref() {
2443                            bracket_pair = Some(pair.clone());
2444                            break;
2445                        }
2446                    }
2447                }
2448
2449                if let Some(bracket_pair) = bracket_pair {
2450                    if selection.is_empty() {
2451                        if is_bracket_pair_start {
2452                            let prefix_len = bracket_pair.start.len() - text.len();
2453
2454                            // If the inserted text is a suffix of an opening bracket and the
2455                            // selection is preceded by the rest of the opening bracket, then
2456                            // insert the closing bracket.
2457                            let following_text_allows_autoclose = snapshot
2458                                .chars_at(selection.start)
2459                                .next()
2460                                .map_or(true, |c| scope.should_autoclose_before(c));
2461                            let preceding_text_matches_prefix = prefix_len == 0
2462                                || (selection.start.column >= (prefix_len as u32)
2463                                    && snapshot.contains_str_at(
2464                                        Point::new(
2465                                            selection.start.row,
2466                                            selection.start.column - (prefix_len as u32),
2467                                        ),
2468                                        &bracket_pair.start[..prefix_len],
2469                                    ));
2470                            if following_text_allows_autoclose && preceding_text_matches_prefix {
2471                                let anchor = snapshot.anchor_before(selection.end);
2472                                new_selections.push((selection.map(|_| anchor), text.len()));
2473                                new_autoclose_regions.push((
2474                                    anchor,
2475                                    text.len(),
2476                                    selection.id,
2477                                    bracket_pair.clone(),
2478                                ));
2479                                edits.push((
2480                                    selection.range(),
2481                                    format!("{}{}", text, bracket_pair.end).into(),
2482                                ));
2483                                brace_inserted = true;
2484                                continue;
2485                            }
2486                        }
2487
2488                        if let Some(region) = autoclose_region {
2489                            // If the selection is followed by an auto-inserted closing bracket,
2490                            // then don't insert that closing bracket again; just move the selection
2491                            // past the closing bracket.
2492                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
2493                                && text.as_ref() == region.pair.end.as_str();
2494                            if should_skip {
2495                                let anchor = snapshot.anchor_after(selection.end);
2496                                new_selections
2497                                    .push((selection.map(|_| anchor), region.pair.end.len()));
2498                                continue;
2499                            }
2500                        }
2501                    }
2502                    // If an opening bracket is 1 character long and is typed while
2503                    // text is selected, then surround that text with the bracket pair.
2504                    else if is_bracket_pair_start && bracket_pair.start.chars().count() == 1 {
2505                        edits.push((selection.start..selection.start, text.clone()));
2506                        edits.push((
2507                            selection.end..selection.end,
2508                            bracket_pair.end.as_str().into(),
2509                        ));
2510                        brace_inserted = true;
2511                        new_selections.push((
2512                            Selection {
2513                                id: selection.id,
2514                                start: snapshot.anchor_after(selection.start),
2515                                end: snapshot.anchor_before(selection.end),
2516                                reversed: selection.reversed,
2517                                goal: selection.goal,
2518                            },
2519                            0,
2520                        ));
2521                        continue;
2522                    }
2523                }
2524            }
2525
2526            // If not handling any auto-close operation, then just replace the selected
2527            // text with the given input and move the selection to the end of the
2528            // newly inserted text.
2529            let anchor = snapshot.anchor_after(selection.end);
2530            new_selections.push((selection.map(|_| anchor), 0));
2531            edits.push((selection.start..selection.end, text.clone()));
2532        }
2533
2534        drop(snapshot);
2535        self.transact(cx, |this, cx| {
2536            this.buffer.update(cx, |buffer, cx| {
2537                buffer.edit(edits, this.autoindent_mode.clone(), cx);
2538            });
2539
2540            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
2541            let new_selection_deltas = new_selections.iter().map(|e| e.1);
2542            let snapshot = this.buffer.read(cx).read(cx);
2543            let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
2544                .zip(new_selection_deltas)
2545                .map(|(selection, delta)| Selection {
2546                    id: selection.id,
2547                    start: selection.start + delta,
2548                    end: selection.end + delta,
2549                    reversed: selection.reversed,
2550                    goal: SelectionGoal::None,
2551                })
2552                .collect::<Vec<_>>();
2553
2554            let mut i = 0;
2555            for (position, delta, selection_id, pair) in new_autoclose_regions {
2556                let position = position.to_offset(&snapshot) + delta;
2557                let start = snapshot.anchor_before(position);
2558                let end = snapshot.anchor_after(position);
2559                while let Some(existing_state) = this.autoclose_regions.get(i) {
2560                    match existing_state.range.start.cmp(&start, &snapshot) {
2561                        Ordering::Less => i += 1,
2562                        Ordering::Greater => break,
2563                        Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
2564                            Ordering::Less => i += 1,
2565                            Ordering::Equal => break,
2566                            Ordering::Greater => break,
2567                        },
2568                    }
2569                }
2570                this.autoclose_regions.insert(
2571                    i,
2572                    AutocloseRegion {
2573                        selection_id,
2574                        range: start..end,
2575                        pair,
2576                    },
2577                );
2578            }
2579
2580            drop(snapshot);
2581            let had_active_copilot_suggestion = this.has_active_copilot_suggestion(cx);
2582            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
2583
2584            if !brace_inserted && EditorSettings::get_global(cx).use_on_type_format {
2585                if let Some(on_type_format_task) =
2586                    this.trigger_on_type_formatting(text.to_string(), cx)
2587                {
2588                    on_type_format_task.detach_and_log_err(cx);
2589                }
2590            }
2591
2592            if had_active_copilot_suggestion {
2593                this.refresh_copilot_suggestions(true, cx);
2594                if !this.has_active_copilot_suggestion(cx) {
2595                    this.trigger_completion_on_input(&text, cx);
2596                }
2597            } else {
2598                this.trigger_completion_on_input(&text, cx);
2599                this.refresh_copilot_suggestions(true, cx);
2600            }
2601        });
2602    }
2603
2604    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
2605        self.transact(cx, |this, cx| {
2606            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
2607                let selections = this.selections.all::<usize>(cx);
2608                let multi_buffer = this.buffer.read(cx);
2609                let buffer = multi_buffer.snapshot(cx);
2610                selections
2611                    .iter()
2612                    .map(|selection| {
2613                        let start_point = selection.start.to_point(&buffer);
2614                        let mut indent = buffer.indent_size_for_line(start_point.row);
2615                        indent.len = cmp::min(indent.len, start_point.column);
2616                        let start = selection.start;
2617                        let end = selection.end;
2618                        let is_cursor = start == end;
2619                        let language_scope = buffer.language_scope_at(start);
2620                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
2621                            &language_scope
2622                        {
2623                            let leading_whitespace_len = buffer
2624                                .reversed_chars_at(start)
2625                                .take_while(|c| c.is_whitespace() && *c != '\n')
2626                                .map(|c| c.len_utf8())
2627                                .sum::<usize>();
2628
2629                            let trailing_whitespace_len = buffer
2630                                .chars_at(end)
2631                                .take_while(|c| c.is_whitespace() && *c != '\n')
2632                                .map(|c| c.len_utf8())
2633                                .sum::<usize>();
2634
2635                            let insert_extra_newline =
2636                                language.brackets().any(|(pair, enabled)| {
2637                                    let pair_start = pair.start.trim_end();
2638                                    let pair_end = pair.end.trim_start();
2639
2640                                    enabled
2641                                        && pair.newline
2642                                        && buffer.contains_str_at(
2643                                            end + trailing_whitespace_len,
2644                                            pair_end,
2645                                        )
2646                                        && buffer.contains_str_at(
2647                                            (start - leading_whitespace_len)
2648                                                .saturating_sub(pair_start.len()),
2649                                            pair_start,
2650                                        )
2651                                });
2652                            // Comment extension on newline is allowed only for cursor selections
2653                            let comment_delimiter = language.line_comment_prefix().filter(|_| {
2654                                let is_comment_extension_enabled =
2655                                    multi_buffer.settings_at(0, cx).extend_comment_on_newline;
2656                                is_cursor && is_comment_extension_enabled
2657                            });
2658                            let comment_delimiter = if let Some(delimiter) = comment_delimiter {
2659                                buffer
2660                                    .buffer_line_for_row(start_point.row)
2661                                    .is_some_and(|(snapshot, range)| {
2662                                        let mut index_of_first_non_whitespace = 0;
2663                                        let line_starts_with_comment = snapshot
2664                                            .chars_for_range(range)
2665                                            .skip_while(|c| {
2666                                                let should_skip = c.is_whitespace();
2667                                                if should_skip {
2668                                                    index_of_first_non_whitespace += 1;
2669                                                }
2670                                                should_skip
2671                                            })
2672                                            .take(delimiter.len())
2673                                            .eq(delimiter.chars());
2674                                        let cursor_is_placed_after_comment_marker =
2675                                            index_of_first_non_whitespace + delimiter.len()
2676                                                <= start_point.column as usize;
2677                                        line_starts_with_comment
2678                                            && cursor_is_placed_after_comment_marker
2679                                    })
2680                                    .then(|| delimiter.clone())
2681                            } else {
2682                                None
2683                            };
2684                            (comment_delimiter, insert_extra_newline)
2685                        } else {
2686                            (None, false)
2687                        };
2688
2689                        let capacity_for_delimiter = comment_delimiter
2690                            .as_deref()
2691                            .map(str::len)
2692                            .unwrap_or_default();
2693                        let mut new_text =
2694                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
2695                        new_text.push_str("\n");
2696                        new_text.extend(indent.chars());
2697                        if let Some(delimiter) = &comment_delimiter {
2698                            new_text.push_str(&delimiter);
2699                        }
2700                        if insert_extra_newline {
2701                            new_text = new_text.repeat(2);
2702                        }
2703
2704                        let anchor = buffer.anchor_after(end);
2705                        let new_selection = selection.map(|_| anchor);
2706                        (
2707                            (start..end, new_text),
2708                            (insert_extra_newline, new_selection),
2709                        )
2710                    })
2711                    .unzip()
2712            };
2713
2714            this.edit_with_autoindent(edits, cx);
2715            let buffer = this.buffer.read(cx).snapshot(cx);
2716            let new_selections = selection_fixup_info
2717                .into_iter()
2718                .map(|(extra_newline_inserted, new_selection)| {
2719                    let mut cursor = new_selection.end.to_point(&buffer);
2720                    if extra_newline_inserted {
2721                        cursor.row -= 1;
2722                        cursor.column = buffer.line_len(cursor.row);
2723                    }
2724                    new_selection.map(|_| cursor)
2725                })
2726                .collect();
2727
2728            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
2729            this.refresh_copilot_suggestions(true, cx);
2730        });
2731    }
2732
2733    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
2734        let buffer = self.buffer.read(cx);
2735        let snapshot = buffer.snapshot(cx);
2736
2737        let mut edits = Vec::new();
2738        let mut rows = Vec::new();
2739        let mut rows_inserted = 0;
2740
2741        for selection in self.selections.all_adjusted(cx) {
2742            let cursor = selection.head();
2743            let row = cursor.row;
2744
2745            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
2746
2747            let newline = "\n".to_string();
2748            edits.push((start_of_line..start_of_line, newline));
2749
2750            rows.push(row + rows_inserted);
2751            rows_inserted += 1;
2752        }
2753
2754        self.transact(cx, |editor, cx| {
2755            editor.edit(edits, cx);
2756
2757            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
2758                let mut index = 0;
2759                s.move_cursors_with(|map, _, _| {
2760                    let row = rows[index];
2761                    index += 1;
2762
2763                    let point = Point::new(row, 0);
2764                    let boundary = map.next_line_boundary(point).1;
2765                    let clipped = map.clip_point(boundary, Bias::Left);
2766
2767                    (clipped, SelectionGoal::None)
2768                });
2769            });
2770
2771            let mut indent_edits = Vec::new();
2772            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
2773            for row in rows {
2774                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
2775                for (row, indent) in indents {
2776                    if indent.len == 0 {
2777                        continue;
2778                    }
2779
2780                    let text = match indent.kind {
2781                        IndentKind::Space => " ".repeat(indent.len as usize),
2782                        IndentKind::Tab => "\t".repeat(indent.len as usize),
2783                    };
2784                    let point = Point::new(row, 0);
2785                    indent_edits.push((point..point, text));
2786                }
2787            }
2788            editor.edit(indent_edits, cx);
2789        });
2790    }
2791
2792    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
2793        let buffer = self.buffer.read(cx);
2794        let snapshot = buffer.snapshot(cx);
2795
2796        let mut edits = Vec::new();
2797        let mut rows = Vec::new();
2798        let mut rows_inserted = 0;
2799
2800        for selection in self.selections.all_adjusted(cx) {
2801            let cursor = selection.head();
2802            let row = cursor.row;
2803
2804            let point = Point::new(row + 1, 0);
2805            let start_of_line = snapshot.clip_point(point, Bias::Left);
2806
2807            let newline = "\n".to_string();
2808            edits.push((start_of_line..start_of_line, newline));
2809
2810            rows_inserted += 1;
2811            rows.push(row + rows_inserted);
2812        }
2813
2814        self.transact(cx, |editor, cx| {
2815            editor.edit(edits, cx);
2816
2817            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
2818                let mut index = 0;
2819                s.move_cursors_with(|map, _, _| {
2820                    let row = rows[index];
2821                    index += 1;
2822
2823                    let point = Point::new(row, 0);
2824                    let boundary = map.next_line_boundary(point).1;
2825                    let clipped = map.clip_point(boundary, Bias::Left);
2826
2827                    (clipped, SelectionGoal::None)
2828                });
2829            });
2830
2831            let mut indent_edits = Vec::new();
2832            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
2833            for row in rows {
2834                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
2835                for (row, indent) in indents {
2836                    if indent.len == 0 {
2837                        continue;
2838                    }
2839
2840                    let text = match indent.kind {
2841                        IndentKind::Space => " ".repeat(indent.len as usize),
2842                        IndentKind::Tab => "\t".repeat(indent.len as usize),
2843                    };
2844                    let point = Point::new(row, 0);
2845                    indent_edits.push((point..point, text));
2846                }
2847            }
2848            editor.edit(indent_edits, cx);
2849        });
2850    }
2851
2852    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2853        self.insert_with_autoindent_mode(
2854            text,
2855            Some(AutoindentMode::Block {
2856                original_indent_columns: Vec::new(),
2857            }),
2858            cx,
2859        );
2860    }
2861
2862    fn insert_with_autoindent_mode(
2863        &mut self,
2864        text: &str,
2865        autoindent_mode: Option<AutoindentMode>,
2866        cx: &mut ViewContext<Self>,
2867    ) {
2868        if self.read_only(cx) {
2869            return;
2870        }
2871
2872        let text: Arc<str> = text.into();
2873        self.transact(cx, |this, cx| {
2874            let old_selections = this.selections.all_adjusted(cx);
2875            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
2876                let anchors = {
2877                    let snapshot = buffer.read(cx);
2878                    old_selections
2879                        .iter()
2880                        .map(|s| {
2881                            let anchor = snapshot.anchor_after(s.head());
2882                            s.map(|_| anchor)
2883                        })
2884                        .collect::<Vec<_>>()
2885                };
2886                buffer.edit(
2887                    old_selections
2888                        .iter()
2889                        .map(|s| (s.start..s.end, text.clone())),
2890                    autoindent_mode,
2891                    cx,
2892                );
2893                anchors
2894            });
2895
2896            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
2897                s.select_anchors(selection_anchors);
2898            })
2899        });
2900    }
2901
2902    fn trigger_completion_on_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
2903        if !EditorSettings::get_global(cx).show_completions_on_input {
2904            return;
2905        }
2906
2907        let selection = self.selections.newest_anchor();
2908        if self
2909            .buffer
2910            .read(cx)
2911            .is_completion_trigger(selection.head(), text, cx)
2912        {
2913            self.show_completions(&ShowCompletions, cx);
2914        } else {
2915            self.hide_context_menu(cx);
2916        }
2917    }
2918
2919    /// If any empty selections is touching the start of its innermost containing autoclose
2920    /// region, expand it to select the brackets.
2921    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
2922        let selections = self.selections.all::<usize>(cx);
2923        let buffer = self.buffer.read(cx).read(cx);
2924        let mut new_selections = Vec::new();
2925        for (mut selection, region) in self.selections_with_autoclose_regions(selections, &buffer) {
2926            if let (Some(region), true) = (region, selection.is_empty()) {
2927                let mut range = region.range.to_offset(&buffer);
2928                if selection.start == range.start {
2929                    if range.start >= region.pair.start.len() {
2930                        range.start -= region.pair.start.len();
2931                        if buffer.contains_str_at(range.start, &region.pair.start) {
2932                            if buffer.contains_str_at(range.end, &region.pair.end) {
2933                                range.end += region.pair.end.len();
2934                                selection.start = range.start;
2935                                selection.end = range.end;
2936                            }
2937                        }
2938                    }
2939                }
2940            }
2941            new_selections.push(selection);
2942        }
2943
2944        drop(buffer);
2945        self.change_selections(None, cx, |selections| selections.select(new_selections));
2946    }
2947
2948    /// Iterate the given selections, and for each one, find the smallest surrounding
2949    /// autoclose region. This uses the ordering of the selections and the autoclose
2950    /// regions to avoid repeated comparisons.
2951    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
2952        &'a self,
2953        selections: impl IntoIterator<Item = Selection<D>>,
2954        buffer: &'a MultiBufferSnapshot,
2955    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
2956        let mut i = 0;
2957        let mut regions = self.autoclose_regions.as_slice();
2958        selections.into_iter().map(move |selection| {
2959            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
2960
2961            let mut enclosing = None;
2962            while let Some(pair_state) = regions.get(i) {
2963                if pair_state.range.end.to_offset(buffer) < range.start {
2964                    regions = &regions[i + 1..];
2965                    i = 0;
2966                } else if pair_state.range.start.to_offset(buffer) > range.end {
2967                    break;
2968                } else {
2969                    if pair_state.selection_id == selection.id {
2970                        enclosing = Some(pair_state);
2971                    }
2972                    i += 1;
2973                }
2974            }
2975
2976            (selection.clone(), enclosing)
2977        })
2978    }
2979
2980    /// Remove any autoclose regions that no longer contain their selection.
2981    fn invalidate_autoclose_regions(
2982        &mut self,
2983        mut selections: &[Selection<Anchor>],
2984        buffer: &MultiBufferSnapshot,
2985    ) {
2986        self.autoclose_regions.retain(|state| {
2987            let mut i = 0;
2988            while let Some(selection) = selections.get(i) {
2989                if selection.end.cmp(&state.range.start, buffer).is_lt() {
2990                    selections = &selections[1..];
2991                    continue;
2992                }
2993                if selection.start.cmp(&state.range.end, buffer).is_gt() {
2994                    break;
2995                }
2996                if selection.id == state.selection_id {
2997                    return true;
2998                } else {
2999                    i += 1;
3000                }
3001            }
3002            false
3003        });
3004    }
3005
3006    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3007        let offset = position.to_offset(buffer);
3008        let (word_range, kind) = buffer.surrounding_word(offset);
3009        if offset > word_range.start && kind == Some(CharKind::Word) {
3010            Some(
3011                buffer
3012                    .text_for_range(word_range.start..offset)
3013                    .collect::<String>(),
3014            )
3015        } else {
3016            None
3017        }
3018    }
3019
3020    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3021        self.refresh_inlay_hints(
3022            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3023            cx,
3024        );
3025    }
3026
3027    pub fn inlay_hints_enabled(&self) -> bool {
3028        self.inlay_hint_cache.enabled
3029    }
3030
3031    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3032        if self.project.is_none() || self.mode != EditorMode::Full {
3033            return;
3034        }
3035
3036        let reason_description = reason.description();
3037        let (invalidate_cache, required_languages) = match reason {
3038            InlayHintRefreshReason::Toggle(enabled) => {
3039                self.inlay_hint_cache.enabled = enabled;
3040                if enabled {
3041                    (InvalidationStrategy::RefreshRequested, None)
3042                } else {
3043                    self.inlay_hint_cache.clear();
3044                    self.splice_inlay_hints(
3045                        self.visible_inlay_hints(cx)
3046                            .iter()
3047                            .map(|inlay| inlay.id)
3048                            .collect(),
3049                        Vec::new(),
3050                        cx,
3051                    );
3052                    return;
3053                }
3054            }
3055            InlayHintRefreshReason::SettingsChange(new_settings) => {
3056                match self.inlay_hint_cache.update_settings(
3057                    &self.buffer,
3058                    new_settings,
3059                    self.visible_inlay_hints(cx),
3060                    cx,
3061                ) {
3062                    ControlFlow::Break(Some(InlaySplice {
3063                        to_remove,
3064                        to_insert,
3065                    })) => {
3066                        self.splice_inlay_hints(to_remove, to_insert, cx);
3067                        return;
3068                    }
3069                    ControlFlow::Break(None) => return,
3070                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3071                }
3072            }
3073            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3074                if let Some(InlaySplice {
3075                    to_remove,
3076                    to_insert,
3077                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3078                {
3079                    self.splice_inlay_hints(to_remove, to_insert, cx);
3080                }
3081                return;
3082            }
3083            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3084            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3085                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3086            }
3087            InlayHintRefreshReason::RefreshRequested => {
3088                (InvalidationStrategy::RefreshRequested, None)
3089            }
3090        };
3091
3092        if let Some(InlaySplice {
3093            to_remove,
3094            to_insert,
3095        }) = self.inlay_hint_cache.spawn_hint_refresh(
3096            reason_description,
3097            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3098            invalidate_cache,
3099            cx,
3100        ) {
3101            self.splice_inlay_hints(to_remove, to_insert, cx);
3102        }
3103    }
3104
3105    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3106        self.display_map
3107            .read(cx)
3108            .current_inlays()
3109            .filter(move |inlay| {
3110                Some(inlay.id) != self.copilot_state.suggestion.as_ref().map(|h| h.id)
3111            })
3112            .cloned()
3113            .collect()
3114    }
3115
3116    pub fn excerpts_for_inlay_hints_query(
3117        &self,
3118        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3119        cx: &mut ViewContext<Editor>,
3120    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3121        let Some(project) = self.project.as_ref() else {
3122            return HashMap::default();
3123        };
3124        let project = project.read(cx);
3125        let multi_buffer = self.buffer().read(cx);
3126        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3127        let multi_buffer_visible_start = self
3128            .scroll_manager
3129            .anchor()
3130            .anchor
3131            .to_point(&multi_buffer_snapshot);
3132        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3133            multi_buffer_visible_start
3134                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3135            Bias::Left,
3136        );
3137        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3138        multi_buffer
3139            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3140            .into_iter()
3141            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3142            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3143                let buffer = buffer_handle.read(cx);
3144                let buffer_file = project::worktree::File::from_dyn(buffer.file())?;
3145                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3146                let worktree_entry = buffer_worktree
3147                    .read(cx)
3148                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3149                if worktree_entry.is_ignored {
3150                    return None;
3151                }
3152
3153                let language = buffer.language()?;
3154                if let Some(restrict_to_languages) = restrict_to_languages {
3155                    if !restrict_to_languages.contains(language) {
3156                        return None;
3157                    }
3158                }
3159                Some((
3160                    excerpt_id,
3161                    (
3162                        buffer_handle,
3163                        buffer.version().clone(),
3164                        excerpt_visible_range,
3165                    ),
3166                ))
3167            })
3168            .collect()
3169    }
3170
3171    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
3172        TextLayoutDetails {
3173            text_system: cx.text_system().clone(),
3174            editor_style: self.style.clone().unwrap(),
3175            rem_size: cx.rem_size(),
3176        }
3177    }
3178
3179    fn splice_inlay_hints(
3180        &self,
3181        to_remove: Vec<InlayId>,
3182        to_insert: Vec<Inlay>,
3183        cx: &mut ViewContext<Self>,
3184    ) {
3185        self.display_map.update(cx, |display_map, cx| {
3186            display_map.splice_inlays(to_remove, to_insert, cx);
3187        });
3188        cx.notify();
3189    }
3190
3191    fn trigger_on_type_formatting(
3192        &self,
3193        input: String,
3194        cx: &mut ViewContext<Self>,
3195    ) -> Option<Task<Result<()>>> {
3196        if input.len() != 1 {
3197            return None;
3198        }
3199
3200        let project = self.project.as_ref()?;
3201        let position = self.selections.newest_anchor().head();
3202        let (buffer, buffer_position) = self
3203            .buffer
3204            .read(cx)
3205            .text_anchor_for_position(position.clone(), cx)?;
3206
3207        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
3208        // hence we do LSP request & edit on host side only — add formats to host's history.
3209        let push_to_lsp_host_history = true;
3210        // If this is not the host, append its history with new edits.
3211        let push_to_client_history = project.read(cx).is_remote();
3212
3213        let on_type_formatting = project.update(cx, |project, cx| {
3214            project.on_type_format(
3215                buffer.clone(),
3216                buffer_position,
3217                input,
3218                push_to_lsp_host_history,
3219                cx,
3220            )
3221        });
3222        Some(cx.spawn(|editor, mut cx| async move {
3223            if let Some(transaction) = on_type_formatting.await? {
3224                if push_to_client_history {
3225                    buffer
3226                        .update(&mut cx, |buffer, _| {
3227                            buffer.push_transaction(transaction, Instant::now());
3228                        })
3229                        .ok();
3230                }
3231                editor.update(&mut cx, |editor, cx| {
3232                    editor.refresh_document_highlights(cx);
3233                })?;
3234            }
3235            Ok(())
3236        }))
3237    }
3238
3239    fn show_completions(&mut self, _: &ShowCompletions, cx: &mut ViewContext<Self>) {
3240        if self.pending_rename.is_some() {
3241            return;
3242        }
3243
3244        let project = if let Some(project) = self.project.clone() {
3245            project
3246        } else {
3247            return;
3248        };
3249
3250        let position = self.selections.newest_anchor().head();
3251        let (buffer, buffer_position) = if let Some(output) = self
3252            .buffer
3253            .read(cx)
3254            .text_anchor_for_position(position.clone(), cx)
3255        {
3256            output
3257        } else {
3258            return;
3259        };
3260
3261        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position.clone());
3262        let completions = project.update(cx, |project, cx| {
3263            project.completions(&buffer, buffer_position, cx)
3264        });
3265
3266        let id = post_inc(&mut self.next_completion_id);
3267        let task = cx.spawn(|this, mut cx| {
3268            async move {
3269                let completions = completions.await.log_err();
3270                let (menu, pre_resolve_task) = if let Some(completions) = completions {
3271                    let mut menu = CompletionsMenu {
3272                        id,
3273                        initial_position: position,
3274                        match_candidates: completions
3275                            .iter()
3276                            .enumerate()
3277                            .map(|(id, completion)| {
3278                                StringMatchCandidate::new(
3279                                    id,
3280                                    completion.label.text[completion.label.filter_range.clone()]
3281                                        .into(),
3282                                )
3283                            })
3284                            .collect(),
3285                        buffer,
3286                        completions: Arc::new(RwLock::new(completions.into())),
3287                        matches: Vec::new().into(),
3288                        selected_item: 0,
3289                        scroll_handle: UniformListScrollHandle::new(),
3290                    };
3291                    menu.filter(query.as_deref(), cx.background_executor().clone())
3292                        .await;
3293
3294                    if menu.matches.is_empty() {
3295                        (None, None)
3296                    } else {
3297                        let pre_resolve_task = this
3298                            .update(&mut cx, |editor, cx| {
3299                                menu.pre_resolve_completion_documentation(editor, cx)
3300                            })
3301                            .ok()
3302                            .flatten();
3303                        (Some(menu), pre_resolve_task)
3304                    }
3305                } else {
3306                    (None, None)
3307                };
3308
3309                this.update(&mut cx, |this, cx| {
3310                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
3311
3312                    let mut context_menu = this.context_menu.write();
3313                    match context_menu.as_ref() {
3314                        None => {}
3315
3316                        Some(ContextMenu::Completions(prev_menu)) => {
3317                            if prev_menu.id > id {
3318                                return;
3319                            }
3320                        }
3321
3322                        _ => return,
3323                    }
3324
3325                    if this.focus_handle.is_focused(cx) && menu.is_some() {
3326                        let menu = menu.unwrap();
3327                        *context_menu = Some(ContextMenu::Completions(menu));
3328                        drop(context_menu);
3329                        this.discard_copilot_suggestion(cx);
3330                        cx.notify();
3331                    } else if this.completion_tasks.len() <= 1 {
3332                        // If there are no more completion tasks and the last menu was
3333                        // empty, we should hide it. If it was already hidden, we should
3334                        // also show the copilot suggestion when available.
3335                        drop(context_menu);
3336                        if this.hide_context_menu(cx).is_none() {
3337                            this.update_visible_copilot_suggestion(cx);
3338                        }
3339                    }
3340                })?;
3341
3342                if let Some(pre_resolve_task) = pre_resolve_task {
3343                    pre_resolve_task.await;
3344                }
3345
3346                Ok::<_, anyhow::Error>(())
3347            }
3348            .log_err()
3349        });
3350
3351        self.completion_tasks.push((id, task));
3352    }
3353
3354    pub fn confirm_completion(
3355        &mut self,
3356        action: &ConfirmCompletion,
3357        cx: &mut ViewContext<Self>,
3358    ) -> Option<Task<Result<()>>> {
3359        use language::ToOffset as _;
3360
3361        let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
3362            menu
3363        } else {
3364            return None;
3365        };
3366
3367        let mat = completions_menu
3368            .matches
3369            .get(action.item_ix.unwrap_or(completions_menu.selected_item))?;
3370        let buffer_handle = completions_menu.buffer;
3371        let completions = completions_menu.completions.read();
3372        let completion = completions.get(mat.candidate_id)?;
3373
3374        let snippet;
3375        let text;
3376        if completion.is_snippet() {
3377            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
3378            text = snippet.as_ref().unwrap().text.clone();
3379        } else {
3380            snippet = None;
3381            text = completion.new_text.clone();
3382        };
3383        let selections = self.selections.all::<usize>(cx);
3384        let buffer = buffer_handle.read(cx);
3385        let old_range = completion.old_range.to_offset(buffer);
3386        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
3387
3388        let newest_selection = self.selections.newest_anchor();
3389        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
3390            return None;
3391        }
3392
3393        let lookbehind = newest_selection
3394            .start
3395            .text_anchor
3396            .to_offset(buffer)
3397            .saturating_sub(old_range.start);
3398        let lookahead = old_range
3399            .end
3400            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
3401        let mut common_prefix_len = old_text
3402            .bytes()
3403            .zip(text.bytes())
3404            .take_while(|(a, b)| a == b)
3405            .count();
3406
3407        let snapshot = self.buffer.read(cx).snapshot(cx);
3408        let mut range_to_replace: Option<Range<isize>> = None;
3409        let mut ranges = Vec::new();
3410        for selection in &selections {
3411            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
3412                let start = selection.start.saturating_sub(lookbehind);
3413                let end = selection.end + lookahead;
3414                if selection.id == newest_selection.id {
3415                    range_to_replace = Some(
3416                        ((start + common_prefix_len) as isize - selection.start as isize)
3417                            ..(end as isize - selection.start as isize),
3418                    );
3419                }
3420                ranges.push(start + common_prefix_len..end);
3421            } else {
3422                common_prefix_len = 0;
3423                ranges.clear();
3424                ranges.extend(selections.iter().map(|s| {
3425                    if s.id == newest_selection.id {
3426                        range_to_replace = Some(
3427                            old_range.start.to_offset_utf16(&snapshot).0 as isize
3428                                - selection.start as isize
3429                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
3430                                    - selection.start as isize,
3431                        );
3432                        old_range.clone()
3433                    } else {
3434                        s.start..s.end
3435                    }
3436                }));
3437                break;
3438            }
3439        }
3440        let text = &text[common_prefix_len..];
3441
3442        cx.emit(EditorEvent::InputHandled {
3443            utf16_range_to_replace: range_to_replace,
3444            text: text.into(),
3445        });
3446
3447        self.transact(cx, |this, cx| {
3448            if let Some(mut snippet) = snippet {
3449                snippet.text = text.to_string();
3450                for tabstop in snippet.tabstops.iter_mut().flatten() {
3451                    tabstop.start -= common_prefix_len as isize;
3452                    tabstop.end -= common_prefix_len as isize;
3453                }
3454
3455                this.insert_snippet(&ranges, snippet, cx).log_err();
3456            } else {
3457                this.buffer.update(cx, |buffer, cx| {
3458                    buffer.edit(
3459                        ranges.iter().map(|range| (range.clone(), text)),
3460                        this.autoindent_mode.clone(),
3461                        cx,
3462                    );
3463                });
3464            }
3465
3466            this.refresh_copilot_suggestions(true, cx);
3467        });
3468
3469        let project = self.project.clone()?;
3470        let apply_edits = project.update(cx, |project, cx| {
3471            project.apply_additional_edits_for_completion(
3472                buffer_handle,
3473                completion.clone(),
3474                true,
3475                cx,
3476            )
3477        });
3478        Some(cx.foreground_executor().spawn(async move {
3479            apply_edits.await?;
3480            Ok(())
3481        }))
3482    }
3483
3484    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
3485        let mut context_menu = self.context_menu.write();
3486        if matches!(context_menu.as_ref(), Some(ContextMenu::CodeActions(_))) {
3487            *context_menu = None;
3488            cx.notify();
3489            return;
3490        }
3491        drop(context_menu);
3492
3493        let deployed_from_indicator = action.deployed_from_indicator;
3494        let mut task = self.code_actions_task.take();
3495        cx.spawn(|this, mut cx| async move {
3496            while let Some(prev_task) = task {
3497                prev_task.await;
3498                task = this.update(&mut cx, |this, _| this.code_actions_task.take())?;
3499            }
3500
3501            this.update(&mut cx, |this, cx| {
3502                if this.focus_handle.is_focused(cx) {
3503                    if let Some((buffer, actions)) = this.available_code_actions.clone() {
3504                        this.completion_tasks.clear();
3505                        this.discard_copilot_suggestion(cx);
3506                        *this.context_menu.write() =
3507                            Some(ContextMenu::CodeActions(CodeActionsMenu {
3508                                buffer,
3509                                actions,
3510                                selected_item: Default::default(),
3511                                scroll_handle: UniformListScrollHandle::default(),
3512                                deployed_from_indicator,
3513                            }));
3514                        cx.notify();
3515                    }
3516                }
3517            })?;
3518
3519            Ok::<_, anyhow::Error>(())
3520        })
3521        .detach_and_log_err(cx);
3522    }
3523
3524    pub fn confirm_code_action(
3525        &mut self,
3526        action: &ConfirmCodeAction,
3527        cx: &mut ViewContext<Self>,
3528    ) -> Option<Task<Result<()>>> {
3529        let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
3530            menu
3531        } else {
3532            return None;
3533        };
3534        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
3535        let action = actions_menu.actions.get(action_ix)?.clone();
3536        let title = action.lsp_action.title.clone();
3537        let buffer = actions_menu.buffer;
3538        let workspace = self.workspace()?;
3539
3540        let apply_code_actions = workspace
3541            .read(cx)
3542            .project()
3543            .clone()
3544            .update(cx, |project, cx| {
3545                project.apply_code_action(buffer, action, true, cx)
3546            });
3547        let workspace = workspace.downgrade();
3548        Some(cx.spawn(|editor, cx| async move {
3549            let project_transaction = apply_code_actions.await?;
3550            Self::open_project_transaction(&editor, workspace, project_transaction, title, cx).await
3551        }))
3552    }
3553
3554    async fn open_project_transaction(
3555        this: &WeakView<Editor>,
3556        workspace: WeakView<Workspace>,
3557        transaction: ProjectTransaction,
3558        title: String,
3559        mut cx: AsyncWindowContext,
3560    ) -> Result<()> {
3561        let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
3562
3563        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
3564        cx.update(|_, cx| {
3565            entries.sort_unstable_by_key(|(buffer, _)| {
3566                buffer.read(cx).file().map(|f| f.path().clone())
3567            });
3568        })?;
3569
3570        // If the project transaction's edits are all contained within this editor, then
3571        // avoid opening a new editor to display them.
3572
3573        if let Some((buffer, transaction)) = entries.first() {
3574            if entries.len() == 1 {
3575                let excerpt = this.update(&mut cx, |editor, cx| {
3576                    editor
3577                        .buffer()
3578                        .read(cx)
3579                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
3580                })?;
3581                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
3582                    if excerpted_buffer == *buffer {
3583                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
3584                            let excerpt_range = excerpt_range.to_offset(buffer);
3585                            buffer
3586                                .edited_ranges_for_transaction::<usize>(transaction)
3587                                .all(|range| {
3588                                    excerpt_range.start <= range.start
3589                                        && excerpt_range.end >= range.end
3590                                })
3591                        })?;
3592
3593                        if all_edits_within_excerpt {
3594                            return Ok(());
3595                        }
3596                    }
3597                }
3598            }
3599        } else {
3600            return Ok(());
3601        }
3602
3603        let mut ranges_to_highlight = Vec::new();
3604        let excerpt_buffer = cx.new_model(|cx| {
3605            let mut multibuffer =
3606                MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
3607            for (buffer_handle, transaction) in &entries {
3608                let buffer = buffer_handle.read(cx);
3609                ranges_to_highlight.extend(
3610                    multibuffer.push_excerpts_with_context_lines(
3611                        buffer_handle.clone(),
3612                        buffer
3613                            .edited_ranges_for_transaction::<usize>(transaction)
3614                            .collect(),
3615                        1,
3616                        cx,
3617                    ),
3618                );
3619            }
3620            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
3621            multibuffer
3622        })?;
3623
3624        workspace.update(&mut cx, |workspace, cx| {
3625            let project = workspace.project().clone();
3626            let editor =
3627                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), cx));
3628            workspace.add_item(Box::new(editor.clone()), cx);
3629            editor.update(cx, |editor, cx| {
3630                editor.highlight_background::<Self>(
3631                    ranges_to_highlight,
3632                    |theme| theme.editor_highlighted_line_background,
3633                    cx,
3634                );
3635            });
3636        })?;
3637
3638        Ok(())
3639    }
3640
3641    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
3642        let project = self.project.clone()?;
3643        let buffer = self.buffer.read(cx);
3644        let newest_selection = self.selections.newest_anchor().clone();
3645        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
3646        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
3647        if start_buffer != end_buffer {
3648            return None;
3649        }
3650
3651        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
3652            cx.background_executor()
3653                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
3654                .await;
3655
3656            let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
3657                project.code_actions(&start_buffer, start..end, cx)
3658            }) {
3659                code_actions.await.log_err()
3660            } else {
3661                None
3662            };
3663
3664            this.update(&mut cx, |this, cx| {
3665                this.available_code_actions = actions.and_then(|actions| {
3666                    if actions.is_empty() {
3667                        None
3668                    } else {
3669                        Some((start_buffer, actions.into()))
3670                    }
3671                });
3672                cx.notify();
3673            })
3674            .log_err();
3675        }));
3676        None
3677    }
3678
3679    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
3680        if self.pending_rename.is_some() {
3681            return None;
3682        }
3683
3684        let project = self.project.clone()?;
3685        let buffer = self.buffer.read(cx);
3686        let newest_selection = self.selections.newest_anchor().clone();
3687        let cursor_position = newest_selection.head();
3688        let (cursor_buffer, cursor_buffer_position) =
3689            buffer.text_anchor_for_position(cursor_position.clone(), cx)?;
3690        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
3691        if cursor_buffer != tail_buffer {
3692            return None;
3693        }
3694
3695        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
3696            cx.background_executor()
3697                .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
3698                .await;
3699
3700            let highlights = if let Some(highlights) = project
3701                .update(&mut cx, |project, cx| {
3702                    project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
3703                })
3704                .log_err()
3705            {
3706                highlights.await.log_err()
3707            } else {
3708                None
3709            };
3710
3711            if let Some(highlights) = highlights {
3712                this.update(&mut cx, |this, cx| {
3713                    if this.pending_rename.is_some() {
3714                        return;
3715                    }
3716
3717                    let buffer_id = cursor_position.buffer_id;
3718                    let buffer = this.buffer.read(cx);
3719                    if !buffer
3720                        .text_anchor_for_position(cursor_position, cx)
3721                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
3722                    {
3723                        return;
3724                    }
3725
3726                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
3727                    let mut write_ranges = Vec::new();
3728                    let mut read_ranges = Vec::new();
3729                    for highlight in highlights {
3730                        for (excerpt_id, excerpt_range) in
3731                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
3732                        {
3733                            let start = highlight
3734                                .range
3735                                .start
3736                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
3737                            let end = highlight
3738                                .range
3739                                .end
3740                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
3741                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
3742                                continue;
3743                            }
3744
3745                            let range = Anchor {
3746                                buffer_id,
3747                                excerpt_id: excerpt_id.clone(),
3748                                text_anchor: start,
3749                            }..Anchor {
3750                                buffer_id,
3751                                excerpt_id,
3752                                text_anchor: end,
3753                            };
3754                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
3755                                write_ranges.push(range);
3756                            } else {
3757                                read_ranges.push(range);
3758                            }
3759                        }
3760                    }
3761
3762                    this.highlight_background::<DocumentHighlightRead>(
3763                        read_ranges,
3764                        |theme| theme.editor_document_highlight_read_background,
3765                        cx,
3766                    );
3767                    this.highlight_background::<DocumentHighlightWrite>(
3768                        write_ranges,
3769                        |theme| theme.editor_document_highlight_write_background,
3770                        cx,
3771                    );
3772                    cx.notify();
3773                })
3774                .log_err();
3775            }
3776        }));
3777        None
3778    }
3779
3780    fn refresh_copilot_suggestions(
3781        &mut self,
3782        debounce: bool,
3783        cx: &mut ViewContext<Self>,
3784    ) -> Option<()> {
3785        let copilot = Copilot::global(cx)?;
3786        if !self.show_copilot_suggestions || !copilot.read(cx).status().is_authorized() {
3787            self.clear_copilot_suggestions(cx);
3788            return None;
3789        }
3790        self.update_visible_copilot_suggestion(cx);
3791
3792        let snapshot = self.buffer.read(cx).snapshot(cx);
3793        let cursor = self.selections.newest_anchor().head();
3794        if !self.is_copilot_enabled_at(cursor, &snapshot, cx) {
3795            self.clear_copilot_suggestions(cx);
3796            return None;
3797        }
3798
3799        let (buffer, buffer_position) =
3800            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
3801        self.copilot_state.pending_refresh = cx.spawn(|this, mut cx| async move {
3802            if debounce {
3803                cx.background_executor()
3804                    .timer(COPILOT_DEBOUNCE_TIMEOUT)
3805                    .await;
3806            }
3807
3808            let completions = copilot
3809                .update(&mut cx, |copilot, cx| {
3810                    copilot.completions(&buffer, buffer_position, cx)
3811                })
3812                .log_err()
3813                .unwrap_or(Task::ready(Ok(Vec::new())))
3814                .await
3815                .log_err()
3816                .into_iter()
3817                .flatten()
3818                .collect_vec();
3819
3820            this.update(&mut cx, |this, cx| {
3821                if !completions.is_empty() {
3822                    this.copilot_state.cycled = false;
3823                    this.copilot_state.pending_cycling_refresh = Task::ready(None);
3824                    this.copilot_state.completions.clear();
3825                    this.copilot_state.active_completion_index = 0;
3826                    this.copilot_state.excerpt_id = Some(cursor.excerpt_id);
3827                    for completion in completions {
3828                        this.copilot_state.push_completion(completion);
3829                    }
3830                    this.update_visible_copilot_suggestion(cx);
3831                }
3832            })
3833            .log_err()?;
3834            Some(())
3835        });
3836
3837        Some(())
3838    }
3839
3840    fn cycle_copilot_suggestions(
3841        &mut self,
3842        direction: Direction,
3843        cx: &mut ViewContext<Self>,
3844    ) -> Option<()> {
3845        let copilot = Copilot::global(cx)?;
3846        if !self.show_copilot_suggestions || !copilot.read(cx).status().is_authorized() {
3847            return None;
3848        }
3849
3850        if self.copilot_state.cycled {
3851            self.copilot_state.cycle_completions(direction);
3852            self.update_visible_copilot_suggestion(cx);
3853        } else {
3854            let cursor = self.selections.newest_anchor().head();
3855            let (buffer, buffer_position) =
3856                self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
3857            self.copilot_state.pending_cycling_refresh = cx.spawn(|this, mut cx| async move {
3858                let completions = copilot
3859                    .update(&mut cx, |copilot, cx| {
3860                        copilot.completions_cycling(&buffer, buffer_position, cx)
3861                    })
3862                    .log_err()?
3863                    .await;
3864
3865                this.update(&mut cx, |this, cx| {
3866                    this.copilot_state.cycled = true;
3867                    for completion in completions.log_err().into_iter().flatten() {
3868                        this.copilot_state.push_completion(completion);
3869                    }
3870                    this.copilot_state.cycle_completions(direction);
3871                    this.update_visible_copilot_suggestion(cx);
3872                })
3873                .log_err()?;
3874
3875                Some(())
3876            });
3877        }
3878
3879        Some(())
3880    }
3881
3882    fn copilot_suggest(&mut self, _: &copilot::Suggest, cx: &mut ViewContext<Self>) {
3883        if !self.has_active_copilot_suggestion(cx) {
3884            self.refresh_copilot_suggestions(false, cx);
3885            return;
3886        }
3887
3888        self.update_visible_copilot_suggestion(cx);
3889    }
3890
3891    fn next_copilot_suggestion(&mut self, _: &copilot::NextSuggestion, cx: &mut ViewContext<Self>) {
3892        if self.has_active_copilot_suggestion(cx) {
3893            self.cycle_copilot_suggestions(Direction::Next, cx);
3894        } else {
3895            let is_copilot_disabled = self.refresh_copilot_suggestions(false, cx).is_none();
3896            if is_copilot_disabled {
3897                cx.propagate();
3898            }
3899        }
3900    }
3901
3902    fn previous_copilot_suggestion(
3903        &mut self,
3904        _: &copilot::PreviousSuggestion,
3905        cx: &mut ViewContext<Self>,
3906    ) {
3907        if self.has_active_copilot_suggestion(cx) {
3908            self.cycle_copilot_suggestions(Direction::Prev, cx);
3909        } else {
3910            let is_copilot_disabled = self.refresh_copilot_suggestions(false, cx).is_none();
3911            if is_copilot_disabled {
3912                cx.propagate();
3913            }
3914        }
3915    }
3916
3917    fn accept_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) -> bool {
3918        if let Some(suggestion) = self.take_active_copilot_suggestion(cx) {
3919            if let Some((copilot, completion)) =
3920                Copilot::global(cx).zip(self.copilot_state.active_completion())
3921            {
3922                copilot
3923                    .update(cx, |copilot, cx| copilot.accept_completion(completion, cx))
3924                    .detach_and_log_err(cx);
3925
3926                self.report_copilot_event(Some(completion.uuid.clone()), true, cx)
3927            }
3928            cx.emit(EditorEvent::InputHandled {
3929                utf16_range_to_replace: None,
3930                text: suggestion.text.to_string().into(),
3931            });
3932            self.insert_with_autoindent_mode(&suggestion.text.to_string(), None, cx);
3933            cx.notify();
3934            true
3935        } else {
3936            false
3937        }
3938    }
3939
3940    fn discard_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) -> bool {
3941        if let Some(suggestion) = self.take_active_copilot_suggestion(cx) {
3942            if let Some(copilot) = Copilot::global(cx) {
3943                copilot
3944                    .update(cx, |copilot, cx| {
3945                        copilot.discard_completions(&self.copilot_state.completions, cx)
3946                    })
3947                    .detach_and_log_err(cx);
3948
3949                self.report_copilot_event(None, false, cx)
3950            }
3951
3952            self.display_map.update(cx, |map, cx| {
3953                map.splice_inlays(vec![suggestion.id], Vec::new(), cx)
3954            });
3955            cx.notify();
3956            true
3957        } else {
3958            false
3959        }
3960    }
3961
3962    fn is_copilot_enabled_at(
3963        &self,
3964        location: Anchor,
3965        snapshot: &MultiBufferSnapshot,
3966        cx: &mut ViewContext<Self>,
3967    ) -> bool {
3968        let file = snapshot.file_at(location);
3969        let language = snapshot.language_at(location);
3970        let settings = all_language_settings(file, cx);
3971        self.show_copilot_suggestions
3972            && settings.copilot_enabled(language, file.map(|f| f.path().as_ref()))
3973    }
3974
3975    fn has_active_copilot_suggestion(&self, cx: &AppContext) -> bool {
3976        if let Some(suggestion) = self.copilot_state.suggestion.as_ref() {
3977            let buffer = self.buffer.read(cx).read(cx);
3978            suggestion.position.is_valid(&buffer)
3979        } else {
3980            false
3981        }
3982    }
3983
3984    fn take_active_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) -> Option<Inlay> {
3985        let suggestion = self.copilot_state.suggestion.take()?;
3986        self.display_map.update(cx, |map, cx| {
3987            map.splice_inlays(vec![suggestion.id], Default::default(), cx);
3988        });
3989        let buffer = self.buffer.read(cx).read(cx);
3990
3991        if suggestion.position.is_valid(&buffer) {
3992            Some(suggestion)
3993        } else {
3994            None
3995        }
3996    }
3997
3998    fn update_visible_copilot_suggestion(&mut self, cx: &mut ViewContext<Self>) {
3999        let snapshot = self.buffer.read(cx).snapshot(cx);
4000        let selection = self.selections.newest_anchor();
4001        let cursor = selection.head();
4002
4003        if self.context_menu.read().is_some()
4004            || !self.completion_tasks.is_empty()
4005            || selection.start != selection.end
4006        {
4007            self.discard_copilot_suggestion(cx);
4008        } else if let Some(text) = self
4009            .copilot_state
4010            .text_for_active_completion(cursor, &snapshot)
4011        {
4012            let text = Rope::from(text);
4013            let mut to_remove = Vec::new();
4014            if let Some(suggestion) = self.copilot_state.suggestion.take() {
4015                to_remove.push(suggestion.id);
4016            }
4017
4018            let suggestion_inlay =
4019                Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
4020            self.copilot_state.suggestion = Some(suggestion_inlay.clone());
4021            self.display_map.update(cx, move |map, cx| {
4022                map.splice_inlays(to_remove, vec![suggestion_inlay], cx)
4023            });
4024            cx.notify();
4025        } else {
4026            self.discard_copilot_suggestion(cx);
4027        }
4028    }
4029
4030    fn clear_copilot_suggestions(&mut self, cx: &mut ViewContext<Self>) {
4031        self.copilot_state = Default::default();
4032        self.discard_copilot_suggestion(cx);
4033    }
4034
4035    pub fn render_code_actions_indicator(
4036        &self,
4037        _style: &EditorStyle,
4038        is_active: bool,
4039        cx: &mut ViewContext<Self>,
4040    ) -> Option<IconButton> {
4041        if self.available_code_actions.is_some() {
4042            Some(
4043                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
4044                    .icon_size(IconSize::Small)
4045                    .icon_color(Color::Muted)
4046                    .selected(is_active)
4047                    .on_click(cx.listener(|editor, _e, cx| {
4048                        editor.toggle_code_actions(
4049                            &ToggleCodeActions {
4050                                deployed_from_indicator: true,
4051                            },
4052                            cx,
4053                        );
4054                    })),
4055            )
4056        } else {
4057            None
4058        }
4059    }
4060
4061    pub fn render_fold_indicators(
4062        &self,
4063        fold_data: Vec<Option<(FoldStatus, u32, bool)>>,
4064        _style: &EditorStyle,
4065        gutter_hovered: bool,
4066        _line_height: Pixels,
4067        _gutter_margin: Pixels,
4068        cx: &mut ViewContext<Self>,
4069    ) -> Vec<Option<IconButton>> {
4070        fold_data
4071            .iter()
4072            .enumerate()
4073            .map(|(ix, fold_data)| {
4074                fold_data
4075                    .map(|(fold_status, buffer_row, active)| {
4076                        (active || gutter_hovered || fold_status == FoldStatus::Folded).then(|| {
4077                            IconButton::new(ix as usize, ui::IconName::ChevronDown)
4078                                .on_click(cx.listener(move |editor, _e, cx| match fold_status {
4079                                    FoldStatus::Folded => {
4080                                        editor.unfold_at(&UnfoldAt { buffer_row }, cx);
4081                                    }
4082                                    FoldStatus::Foldable => {
4083                                        editor.fold_at(&FoldAt { buffer_row }, cx);
4084                                    }
4085                                }))
4086                                .icon_color(ui::Color::Muted)
4087                                .icon_size(ui::IconSize::Small)
4088                                .selected(fold_status == FoldStatus::Folded)
4089                                .selected_icon(ui::IconName::ChevronRight)
4090                                .size(ui::ButtonSize::None)
4091                        })
4092                    })
4093                    .flatten()
4094            })
4095            .collect()
4096    }
4097
4098    pub fn context_menu_visible(&self) -> bool {
4099        self.context_menu
4100            .read()
4101            .as_ref()
4102            .map_or(false, |menu| menu.visible())
4103    }
4104
4105    pub fn render_context_menu(
4106        &self,
4107        cursor_position: DisplayPoint,
4108        style: &EditorStyle,
4109        max_height: Pixels,
4110        cx: &mut ViewContext<Editor>,
4111    ) -> Option<(DisplayPoint, AnyElement)> {
4112        self.context_menu.read().as_ref().map(|menu| {
4113            menu.render(
4114                cursor_position,
4115                style,
4116                max_height,
4117                self.workspace.as_ref().map(|(w, _)| w.clone()),
4118                cx,
4119            )
4120        })
4121    }
4122
4123    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
4124        cx.notify();
4125        self.completion_tasks.clear();
4126        let context_menu = self.context_menu.write().take();
4127        if context_menu.is_some() {
4128            self.update_visible_copilot_suggestion(cx);
4129        }
4130        context_menu
4131    }
4132
4133    pub fn insert_snippet(
4134        &mut self,
4135        insertion_ranges: &[Range<usize>],
4136        snippet: Snippet,
4137        cx: &mut ViewContext<Self>,
4138    ) -> Result<()> {
4139        let tabstops = self.buffer.update(cx, |buffer, cx| {
4140            let snippet_text: Arc<str> = snippet.text.clone().into();
4141            buffer.edit(
4142                insertion_ranges
4143                    .iter()
4144                    .cloned()
4145                    .map(|range| (range, snippet_text.clone())),
4146                Some(AutoindentMode::EachLine),
4147                cx,
4148            );
4149
4150            let snapshot = &*buffer.read(cx);
4151            let snippet = &snippet;
4152            snippet
4153                .tabstops
4154                .iter()
4155                .map(|tabstop| {
4156                    let mut tabstop_ranges = tabstop
4157                        .iter()
4158                        .flat_map(|tabstop_range| {
4159                            let mut delta = 0_isize;
4160                            insertion_ranges.iter().map(move |insertion_range| {
4161                                let insertion_start = insertion_range.start as isize + delta;
4162                                delta +=
4163                                    snippet.text.len() as isize - insertion_range.len() as isize;
4164
4165                                let start = snapshot.anchor_before(
4166                                    (insertion_start + tabstop_range.start) as usize,
4167                                );
4168                                let end = snapshot
4169                                    .anchor_after((insertion_start + tabstop_range.end) as usize);
4170                                start..end
4171                            })
4172                        })
4173                        .collect::<Vec<_>>();
4174                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
4175                    tabstop_ranges
4176                })
4177                .collect::<Vec<_>>()
4178        });
4179
4180        if let Some(tabstop) = tabstops.first() {
4181            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
4182                s.select_ranges(tabstop.iter().cloned());
4183            });
4184            self.snippet_stack.push(SnippetState {
4185                active_index: 0,
4186                ranges: tabstops,
4187            });
4188        }
4189
4190        Ok(())
4191    }
4192
4193    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
4194        self.move_to_snippet_tabstop(Bias::Right, cx)
4195    }
4196
4197    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
4198        self.move_to_snippet_tabstop(Bias::Left, cx)
4199    }
4200
4201    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
4202        if let Some(mut snippet) = self.snippet_stack.pop() {
4203            match bias {
4204                Bias::Left => {
4205                    if snippet.active_index > 0 {
4206                        snippet.active_index -= 1;
4207                    } else {
4208                        self.snippet_stack.push(snippet);
4209                        return false;
4210                    }
4211                }
4212                Bias::Right => {
4213                    if snippet.active_index + 1 < snippet.ranges.len() {
4214                        snippet.active_index += 1;
4215                    } else {
4216                        self.snippet_stack.push(snippet);
4217                        return false;
4218                    }
4219                }
4220            }
4221            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
4222                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
4223                    s.select_anchor_ranges(current_ranges.iter().cloned())
4224                });
4225                // If snippet state is not at the last tabstop, push it back on the stack
4226                if snippet.active_index + 1 < snippet.ranges.len() {
4227                    self.snippet_stack.push(snippet);
4228                }
4229                return true;
4230            }
4231        }
4232
4233        false
4234    }
4235
4236    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
4237        self.transact(cx, |this, cx| {
4238            this.select_all(&SelectAll, cx);
4239            this.insert("", cx);
4240        });
4241    }
4242
4243    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
4244        self.transact(cx, |this, cx| {
4245            this.select_autoclose_pair(cx);
4246            let mut selections = this.selections.all::<Point>(cx);
4247            if !this.selections.line_mode {
4248                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
4249                for selection in &mut selections {
4250                    if selection.is_empty() {
4251                        let old_head = selection.head();
4252                        let mut new_head =
4253                            movement::left(&display_map, old_head.to_display_point(&display_map))
4254                                .to_point(&display_map);
4255                        if let Some((buffer, line_buffer_range)) = display_map
4256                            .buffer_snapshot
4257                            .buffer_line_for_row(old_head.row)
4258                        {
4259                            let indent_size =
4260                                buffer.indent_size_for_line(line_buffer_range.start.row);
4261                            let indent_len = match indent_size.kind {
4262                                IndentKind::Space => {
4263                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
4264                                }
4265                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
4266                            };
4267                            if old_head.column <= indent_size.len && old_head.column > 0 {
4268                                let indent_len = indent_len.get();
4269                                new_head = cmp::min(
4270                                    new_head,
4271                                    Point::new(
4272                                        old_head.row,
4273                                        ((old_head.column - 1) / indent_len) * indent_len,
4274                                    ),
4275                                );
4276                            }
4277                        }
4278
4279                        selection.set_head(new_head, SelectionGoal::None);
4280                    }
4281                }
4282            }
4283
4284            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4285            this.insert("", cx);
4286            this.refresh_copilot_suggestions(true, cx);
4287        });
4288    }
4289
4290    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
4291        self.transact(cx, |this, cx| {
4292            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4293                let line_mode = s.line_mode;
4294                s.move_with(|map, selection| {
4295                    if selection.is_empty() && !line_mode {
4296                        let cursor = movement::right(map, selection.head());
4297                        selection.end = cursor;
4298                        selection.reversed = true;
4299                        selection.goal = SelectionGoal::None;
4300                    }
4301                })
4302            });
4303            this.insert("", cx);
4304            this.refresh_copilot_suggestions(true, cx);
4305        });
4306    }
4307
4308    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
4309        if self.move_to_prev_snippet_tabstop(cx) {
4310            return;
4311        }
4312
4313        self.outdent(&Outdent, cx);
4314    }
4315
4316    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
4317        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
4318            return;
4319        }
4320
4321        let mut selections = self.selections.all_adjusted(cx);
4322        let buffer = self.buffer.read(cx);
4323        let snapshot = buffer.snapshot(cx);
4324        let rows_iter = selections.iter().map(|s| s.head().row);
4325        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
4326
4327        let mut edits = Vec::new();
4328        let mut prev_edited_row = 0;
4329        let mut row_delta = 0;
4330        for selection in &mut selections {
4331            if selection.start.row != prev_edited_row {
4332                row_delta = 0;
4333            }
4334            prev_edited_row = selection.end.row;
4335
4336            // If the selection is non-empty, then increase the indentation of the selected lines.
4337            if !selection.is_empty() {
4338                row_delta =
4339                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
4340                continue;
4341            }
4342
4343            // If the selection is empty and the cursor is in the leading whitespace before the
4344            // suggested indentation, then auto-indent the line.
4345            let cursor = selection.head();
4346            let current_indent = snapshot.indent_size_for_line(cursor.row);
4347            if let Some(suggested_indent) = suggested_indents.get(&cursor.row).copied() {
4348                if cursor.column < suggested_indent.len
4349                    && cursor.column <= current_indent.len
4350                    && current_indent.len <= suggested_indent.len
4351                {
4352                    selection.start = Point::new(cursor.row, suggested_indent.len);
4353                    selection.end = selection.start;
4354                    if row_delta == 0 {
4355                        edits.extend(Buffer::edit_for_indent_size_adjustment(
4356                            cursor.row,
4357                            current_indent,
4358                            suggested_indent,
4359                        ));
4360                        row_delta = suggested_indent.len - current_indent.len;
4361                    }
4362                    continue;
4363                }
4364            }
4365
4366            // Accept copilot suggestion if there is only one selection and the cursor is not
4367            // in the leading whitespace.
4368            if self.selections.count() == 1
4369                && cursor.column >= current_indent.len
4370                && self.has_active_copilot_suggestion(cx)
4371            {
4372                self.accept_copilot_suggestion(cx);
4373                return;
4374            }
4375
4376            // Otherwise, insert a hard or soft tab.
4377            let settings = buffer.settings_at(cursor, cx);
4378            let tab_size = if settings.hard_tabs {
4379                IndentSize::tab()
4380            } else {
4381                let tab_size = settings.tab_size.get();
4382                let char_column = snapshot
4383                    .text_for_range(Point::new(cursor.row, 0)..cursor)
4384                    .flat_map(str::chars)
4385                    .count()
4386                    + row_delta as usize;
4387                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
4388                IndentSize::spaces(chars_to_next_tab_stop)
4389            };
4390            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
4391            selection.end = selection.start;
4392            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
4393            row_delta += tab_size.len;
4394        }
4395
4396        self.transact(cx, |this, cx| {
4397            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
4398            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4399            this.refresh_copilot_suggestions(true, cx);
4400        });
4401    }
4402
4403    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
4404        let mut selections = self.selections.all::<Point>(cx);
4405        let mut prev_edited_row = 0;
4406        let mut row_delta = 0;
4407        let mut edits = Vec::new();
4408        let buffer = self.buffer.read(cx);
4409        let snapshot = buffer.snapshot(cx);
4410        for selection in &mut selections {
4411            if selection.start.row != prev_edited_row {
4412                row_delta = 0;
4413            }
4414            prev_edited_row = selection.end.row;
4415
4416            row_delta =
4417                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
4418        }
4419
4420        self.transact(cx, |this, cx| {
4421            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
4422            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4423        });
4424    }
4425
4426    fn indent_selection(
4427        buffer: &MultiBuffer,
4428        snapshot: &MultiBufferSnapshot,
4429        selection: &mut Selection<Point>,
4430        edits: &mut Vec<(Range<Point>, String)>,
4431        delta_for_start_row: u32,
4432        cx: &AppContext,
4433    ) -> u32 {
4434        let settings = buffer.settings_at(selection.start, cx);
4435        let tab_size = settings.tab_size.get();
4436        let indent_kind = if settings.hard_tabs {
4437            IndentKind::Tab
4438        } else {
4439            IndentKind::Space
4440        };
4441        let mut start_row = selection.start.row;
4442        let mut end_row = selection.end.row + 1;
4443
4444        // If a selection ends at the beginning of a line, don't indent
4445        // that last line.
4446        if selection.end.column == 0 {
4447            end_row -= 1;
4448        }
4449
4450        // Avoid re-indenting a row that has already been indented by a
4451        // previous selection, but still update this selection's column
4452        // to reflect that indentation.
4453        if delta_for_start_row > 0 {
4454            start_row += 1;
4455            selection.start.column += delta_for_start_row;
4456            if selection.end.row == selection.start.row {
4457                selection.end.column += delta_for_start_row;
4458            }
4459        }
4460
4461        let mut delta_for_end_row = 0;
4462        for row in start_row..end_row {
4463            let current_indent = snapshot.indent_size_for_line(row);
4464            let indent_delta = match (current_indent.kind, indent_kind) {
4465                (IndentKind::Space, IndentKind::Space) => {
4466                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
4467                    IndentSize::spaces(columns_to_next_tab_stop)
4468                }
4469                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
4470                (_, IndentKind::Tab) => IndentSize::tab(),
4471            };
4472
4473            let row_start = Point::new(row, 0);
4474            edits.push((
4475                row_start..row_start,
4476                indent_delta.chars().collect::<String>(),
4477            ));
4478
4479            // Update this selection's endpoints to reflect the indentation.
4480            if row == selection.start.row {
4481                selection.start.column += indent_delta.len;
4482            }
4483            if row == selection.end.row {
4484                selection.end.column += indent_delta.len;
4485                delta_for_end_row = indent_delta.len;
4486            }
4487        }
4488
4489        if selection.start.row == selection.end.row {
4490            delta_for_start_row + delta_for_end_row
4491        } else {
4492            delta_for_end_row
4493        }
4494    }
4495
4496    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
4497        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4498        let selections = self.selections.all::<Point>(cx);
4499        let mut deletion_ranges = Vec::new();
4500        let mut last_outdent = None;
4501        {
4502            let buffer = self.buffer.read(cx);
4503            let snapshot = buffer.snapshot(cx);
4504            for selection in &selections {
4505                let settings = buffer.settings_at(selection.start, cx);
4506                let tab_size = settings.tab_size.get();
4507                let mut rows = selection.spanned_rows(false, &display_map);
4508
4509                // Avoid re-outdenting a row that has already been outdented by a
4510                // previous selection.
4511                if let Some(last_row) = last_outdent {
4512                    if last_row == rows.start {
4513                        rows.start += 1;
4514                    }
4515                }
4516
4517                for row in rows {
4518                    let indent_size = snapshot.indent_size_for_line(row);
4519                    if indent_size.len > 0 {
4520                        let deletion_len = match indent_size.kind {
4521                            IndentKind::Space => {
4522                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
4523                                if columns_to_prev_tab_stop == 0 {
4524                                    tab_size
4525                                } else {
4526                                    columns_to_prev_tab_stop
4527                                }
4528                            }
4529                            IndentKind::Tab => 1,
4530                        };
4531                        deletion_ranges.push(Point::new(row, 0)..Point::new(row, deletion_len));
4532                        last_outdent = Some(row);
4533                    }
4534                }
4535            }
4536        }
4537
4538        self.transact(cx, |this, cx| {
4539            this.buffer.update(cx, |buffer, cx| {
4540                let empty_str: Arc<str> = "".into();
4541                buffer.edit(
4542                    deletion_ranges
4543                        .into_iter()
4544                        .map(|range| (range, empty_str.clone())),
4545                    None,
4546                    cx,
4547                );
4548            });
4549            let selections = this.selections.all::<usize>(cx);
4550            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
4551        });
4552    }
4553
4554    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
4555        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4556        let selections = self.selections.all::<Point>(cx);
4557
4558        let mut new_cursors = Vec::new();
4559        let mut edit_ranges = Vec::new();
4560        let mut selections = selections.iter().peekable();
4561        while let Some(selection) = selections.next() {
4562            let mut rows = selection.spanned_rows(false, &display_map);
4563            let goal_display_column = selection.head().to_display_point(&display_map).column();
4564
4565            // Accumulate contiguous regions of rows that we want to delete.
4566            while let Some(next_selection) = selections.peek() {
4567                let next_rows = next_selection.spanned_rows(false, &display_map);
4568                if next_rows.start <= rows.end {
4569                    rows.end = next_rows.end;
4570                    selections.next().unwrap();
4571                } else {
4572                    break;
4573                }
4574            }
4575
4576            let buffer = &display_map.buffer_snapshot;
4577            let mut edit_start = Point::new(rows.start, 0).to_offset(buffer);
4578            let edit_end;
4579            let cursor_buffer_row;
4580            if buffer.max_point().row >= rows.end {
4581                // If there's a line after the range, delete the \n from the end of the row range
4582                // and position the cursor on the next line.
4583                edit_end = Point::new(rows.end, 0).to_offset(buffer);
4584                cursor_buffer_row = rows.end;
4585            } else {
4586                // If there isn't a line after the range, delete the \n from the line before the
4587                // start of the row range and position the cursor there.
4588                edit_start = edit_start.saturating_sub(1);
4589                edit_end = buffer.len();
4590                cursor_buffer_row = rows.start.saturating_sub(1);
4591            }
4592
4593            let mut cursor = Point::new(cursor_buffer_row, 0).to_display_point(&display_map);
4594            *cursor.column_mut() =
4595                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
4596
4597            new_cursors.push((
4598                selection.id,
4599                buffer.anchor_after(cursor.to_point(&display_map)),
4600            ));
4601            edit_ranges.push(edit_start..edit_end);
4602        }
4603
4604        self.transact(cx, |this, cx| {
4605            let buffer = this.buffer.update(cx, |buffer, cx| {
4606                let empty_str: Arc<str> = "".into();
4607                buffer.edit(
4608                    edit_ranges
4609                        .into_iter()
4610                        .map(|range| (range, empty_str.clone())),
4611                    None,
4612                    cx,
4613                );
4614                buffer.snapshot(cx)
4615            });
4616            let new_selections = new_cursors
4617                .into_iter()
4618                .map(|(id, cursor)| {
4619                    let cursor = cursor.to_point(&buffer);
4620                    Selection {
4621                        id,
4622                        start: cursor,
4623                        end: cursor,
4624                        reversed: false,
4625                        goal: SelectionGoal::None,
4626                    }
4627                })
4628                .collect();
4629
4630            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4631                s.select(new_selections);
4632            });
4633        });
4634    }
4635
4636    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
4637        let mut row_ranges = Vec::<Range<u32>>::new();
4638        for selection in self.selections.all::<Point>(cx) {
4639            let start = selection.start.row;
4640            let end = if selection.start.row == selection.end.row {
4641                selection.start.row + 1
4642            } else {
4643                selection.end.row
4644            };
4645
4646            if let Some(last_row_range) = row_ranges.last_mut() {
4647                if start <= last_row_range.end {
4648                    last_row_range.end = end;
4649                    continue;
4650                }
4651            }
4652            row_ranges.push(start..end);
4653        }
4654
4655        let snapshot = self.buffer.read(cx).snapshot(cx);
4656        let mut cursor_positions = Vec::new();
4657        for row_range in &row_ranges {
4658            let anchor = snapshot.anchor_before(Point::new(
4659                row_range.end - 1,
4660                snapshot.line_len(row_range.end - 1),
4661            ));
4662            cursor_positions.push(anchor.clone()..anchor);
4663        }
4664
4665        self.transact(cx, |this, cx| {
4666            for row_range in row_ranges.into_iter().rev() {
4667                for row in row_range.rev() {
4668                    let end_of_line = Point::new(row, snapshot.line_len(row));
4669                    let indent = snapshot.indent_size_for_line(row + 1);
4670                    let start_of_next_line = Point::new(row + 1, indent.len);
4671
4672                    let replace = if snapshot.line_len(row + 1) > indent.len {
4673                        " "
4674                    } else {
4675                        ""
4676                    };
4677
4678                    this.buffer.update(cx, |buffer, cx| {
4679                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
4680                    });
4681                }
4682            }
4683
4684            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4685                s.select_anchor_ranges(cursor_positions)
4686            });
4687        });
4688    }
4689
4690    pub fn sort_lines_case_sensitive(
4691        &mut self,
4692        _: &SortLinesCaseSensitive,
4693        cx: &mut ViewContext<Self>,
4694    ) {
4695        self.manipulate_lines(cx, |lines| lines.sort())
4696    }
4697
4698    pub fn sort_lines_case_insensitive(
4699        &mut self,
4700        _: &SortLinesCaseInsensitive,
4701        cx: &mut ViewContext<Self>,
4702    ) {
4703        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
4704    }
4705
4706    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
4707        self.manipulate_lines(cx, |lines| lines.reverse())
4708    }
4709
4710    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
4711        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
4712    }
4713
4714    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
4715    where
4716        Fn: FnMut(&mut [&str]),
4717    {
4718        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4719        let buffer = self.buffer.read(cx).snapshot(cx);
4720
4721        let mut edits = Vec::new();
4722
4723        let selections = self.selections.all::<Point>(cx);
4724        let mut selections = selections.iter().peekable();
4725        let mut contiguous_row_selections = Vec::new();
4726        let mut new_selections = Vec::new();
4727
4728        while let Some(selection) = selections.next() {
4729            let (start_row, end_row) = consume_contiguous_rows(
4730                &mut contiguous_row_selections,
4731                selection,
4732                &display_map,
4733                &mut selections,
4734            );
4735
4736            let start_point = Point::new(start_row, 0);
4737            let end_point = Point::new(end_row - 1, buffer.line_len(end_row - 1));
4738            let text = buffer
4739                .text_for_range(start_point..end_point)
4740                .collect::<String>();
4741            let mut lines = text.split("\n").collect_vec();
4742
4743            let lines_len = lines.len();
4744            callback(&mut lines);
4745
4746            // This is a current limitation with selections.
4747            // If we wanted to support removing or adding lines, we'd need to fix the logic associated with selections.
4748            debug_assert!(
4749                lines.len() == lines_len,
4750                "callback should not change the number of lines"
4751            );
4752
4753            edits.push((start_point..end_point, lines.join("\n")));
4754            let start_anchor = buffer.anchor_after(start_point);
4755            let end_anchor = buffer.anchor_before(end_point);
4756
4757            // Make selection and push
4758            new_selections.push(Selection {
4759                id: selection.id,
4760                start: start_anchor.to_offset(&buffer),
4761                end: end_anchor.to_offset(&buffer),
4762                goal: SelectionGoal::None,
4763                reversed: selection.reversed,
4764            });
4765        }
4766
4767        self.transact(cx, |this, cx| {
4768            this.buffer.update(cx, |buffer, cx| {
4769                buffer.edit(edits, None, cx);
4770            });
4771
4772            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4773                s.select(new_selections);
4774            });
4775
4776            this.request_autoscroll(Autoscroll::fit(), cx);
4777        });
4778    }
4779
4780    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
4781        self.manipulate_text(cx, |text| text.to_uppercase())
4782    }
4783
4784    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
4785        self.manipulate_text(cx, |text| text.to_lowercase())
4786    }
4787
4788    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
4789        self.manipulate_text(cx, |text| {
4790            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
4791            // https://github.com/rutrum/convert-case/issues/16
4792            text.split("\n")
4793                .map(|line| line.to_case(Case::Title))
4794                .join("\n")
4795        })
4796    }
4797
4798    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
4799        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
4800    }
4801
4802    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
4803        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
4804    }
4805
4806    pub fn convert_to_upper_camel_case(
4807        &mut self,
4808        _: &ConvertToUpperCamelCase,
4809        cx: &mut ViewContext<Self>,
4810    ) {
4811        self.manipulate_text(cx, |text| {
4812            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
4813            // https://github.com/rutrum/convert-case/issues/16
4814            text.split("\n")
4815                .map(|line| line.to_case(Case::UpperCamel))
4816                .join("\n")
4817        })
4818    }
4819
4820    pub fn convert_to_lower_camel_case(
4821        &mut self,
4822        _: &ConvertToLowerCamelCase,
4823        cx: &mut ViewContext<Self>,
4824    ) {
4825        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
4826    }
4827
4828    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
4829    where
4830        Fn: FnMut(&str) -> String,
4831    {
4832        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4833        let buffer = self.buffer.read(cx).snapshot(cx);
4834
4835        let mut new_selections = Vec::new();
4836        let mut edits = Vec::new();
4837        let mut selection_adjustment = 0i32;
4838
4839        for selection in self.selections.all::<usize>(cx) {
4840            let selection_is_empty = selection.is_empty();
4841
4842            let (start, end) = if selection_is_empty {
4843                let word_range = movement::surrounding_word(
4844                    &display_map,
4845                    selection.start.to_display_point(&display_map),
4846                );
4847                let start = word_range.start.to_offset(&display_map, Bias::Left);
4848                let end = word_range.end.to_offset(&display_map, Bias::Left);
4849                (start, end)
4850            } else {
4851                (selection.start, selection.end)
4852            };
4853
4854            let text = buffer.text_for_range(start..end).collect::<String>();
4855            let old_length = text.len() as i32;
4856            let text = callback(&text);
4857
4858            new_selections.push(Selection {
4859                start: (start as i32 - selection_adjustment) as usize,
4860                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
4861                goal: SelectionGoal::None,
4862                ..selection
4863            });
4864
4865            selection_adjustment += old_length - text.len() as i32;
4866
4867            edits.push((start..end, text));
4868        }
4869
4870        self.transact(cx, |this, cx| {
4871            this.buffer.update(cx, |buffer, cx| {
4872                buffer.edit(edits, None, cx);
4873            });
4874
4875            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
4876                s.select(new_selections);
4877            });
4878
4879            this.request_autoscroll(Autoscroll::fit(), cx);
4880        });
4881    }
4882
4883    pub fn duplicate_line(&mut self, _: &DuplicateLine, cx: &mut ViewContext<Self>) {
4884        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4885        let buffer = &display_map.buffer_snapshot;
4886        let selections = self.selections.all::<Point>(cx);
4887
4888        let mut edits = Vec::new();
4889        let mut selections_iter = selections.iter().peekable();
4890        while let Some(selection) = selections_iter.next() {
4891            // Avoid duplicating the same lines twice.
4892            let mut rows = selection.spanned_rows(false, &display_map);
4893
4894            while let Some(next_selection) = selections_iter.peek() {
4895                let next_rows = next_selection.spanned_rows(false, &display_map);
4896                if next_rows.start < rows.end {
4897                    rows.end = next_rows.end;
4898                    selections_iter.next().unwrap();
4899                } else {
4900                    break;
4901                }
4902            }
4903
4904            // Copy the text from the selected row region and splice it at the start of the region.
4905            let start = Point::new(rows.start, 0);
4906            let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
4907            let text = buffer
4908                .text_for_range(start..end)
4909                .chain(Some("\n"))
4910                .collect::<String>();
4911            edits.push((start..start, text));
4912        }
4913
4914        self.transact(cx, |this, cx| {
4915            this.buffer.update(cx, |buffer, cx| {
4916                buffer.edit(edits, None, cx);
4917            });
4918
4919            this.request_autoscroll(Autoscroll::fit(), cx);
4920        });
4921    }
4922
4923    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
4924        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
4925        let buffer = self.buffer.read(cx).snapshot(cx);
4926
4927        let mut edits = Vec::new();
4928        let mut unfold_ranges = Vec::new();
4929        let mut refold_ranges = Vec::new();
4930
4931        let selections = self.selections.all::<Point>(cx);
4932        let mut selections = selections.iter().peekable();
4933        let mut contiguous_row_selections = Vec::new();
4934        let mut new_selections = Vec::new();
4935
4936        while let Some(selection) = selections.next() {
4937            // Find all the selections that span a contiguous row range
4938            let (start_row, end_row) = consume_contiguous_rows(
4939                &mut contiguous_row_selections,
4940                selection,
4941                &display_map,
4942                &mut selections,
4943            );
4944
4945            // Move the text spanned by the row range to be before the line preceding the row range
4946            if start_row > 0 {
4947                let range_to_move = Point::new(start_row - 1, buffer.line_len(start_row - 1))
4948                    ..Point::new(end_row - 1, buffer.line_len(end_row - 1));
4949                let insertion_point = display_map
4950                    .prev_line_boundary(Point::new(start_row - 1, 0))
4951                    .0;
4952
4953                // Don't move lines across excerpts
4954                if buffer
4955                    .excerpt_boundaries_in_range((
4956                        Bound::Excluded(insertion_point),
4957                        Bound::Included(range_to_move.end),
4958                    ))
4959                    .next()
4960                    .is_none()
4961                {
4962                    let text = buffer
4963                        .text_for_range(range_to_move.clone())
4964                        .flat_map(|s| s.chars())
4965                        .skip(1)
4966                        .chain(['\n'])
4967                        .collect::<String>();
4968
4969                    edits.push((
4970                        buffer.anchor_after(range_to_move.start)
4971                            ..buffer.anchor_before(range_to_move.end),
4972                        String::new(),
4973                    ));
4974                    let insertion_anchor = buffer.anchor_after(insertion_point);
4975                    edits.push((insertion_anchor..insertion_anchor, text));
4976
4977                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
4978
4979                    // Move selections up
4980                    new_selections.extend(contiguous_row_selections.drain(..).map(
4981                        |mut selection| {
4982                            selection.start.row -= row_delta;
4983                            selection.end.row -= row_delta;
4984                            selection
4985                        },
4986                    ));
4987
4988                    // Move folds up
4989                    unfold_ranges.push(range_to_move.clone());
4990                    for fold in display_map.folds_in_range(
4991                        buffer.anchor_before(range_to_move.start)
4992                            ..buffer.anchor_after(range_to_move.end),
4993                    ) {
4994                        let mut start = fold.range.start.to_point(&buffer);
4995                        let mut end = fold.range.end.to_point(&buffer);
4996                        start.row -= row_delta;
4997                        end.row -= row_delta;
4998                        refold_ranges.push(start..end);
4999                    }
5000                }
5001            }
5002
5003            // If we didn't move line(s), preserve the existing selections
5004            new_selections.append(&mut contiguous_row_selections);
5005        }
5006
5007        self.transact(cx, |this, cx| {
5008            this.unfold_ranges(unfold_ranges, true, true, cx);
5009            this.buffer.update(cx, |buffer, cx| {
5010                for (range, text) in edits {
5011                    buffer.edit([(range, text)], None, cx);
5012                }
5013            });
5014            this.fold_ranges(refold_ranges, true, cx);
5015            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5016                s.select(new_selections);
5017            })
5018        });
5019    }
5020
5021    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
5022        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5023        let buffer = self.buffer.read(cx).snapshot(cx);
5024
5025        let mut edits = Vec::new();
5026        let mut unfold_ranges = Vec::new();
5027        let mut refold_ranges = Vec::new();
5028
5029        let selections = self.selections.all::<Point>(cx);
5030        let mut selections = selections.iter().peekable();
5031        let mut contiguous_row_selections = Vec::new();
5032        let mut new_selections = Vec::new();
5033
5034        while let Some(selection) = selections.next() {
5035            // Find all the selections that span a contiguous row range
5036            let (start_row, end_row) = consume_contiguous_rows(
5037                &mut contiguous_row_selections,
5038                selection,
5039                &display_map,
5040                &mut selections,
5041            );
5042
5043            // Move the text spanned by the row range to be after the last line of the row range
5044            if end_row <= buffer.max_point().row {
5045                let range_to_move = Point::new(start_row, 0)..Point::new(end_row, 0);
5046                let insertion_point = display_map.next_line_boundary(Point::new(end_row, 0)).0;
5047
5048                // Don't move lines across excerpt boundaries
5049                if buffer
5050                    .excerpt_boundaries_in_range((
5051                        Bound::Excluded(range_to_move.start),
5052                        Bound::Included(insertion_point),
5053                    ))
5054                    .next()
5055                    .is_none()
5056                {
5057                    let mut text = String::from("\n");
5058                    text.extend(buffer.text_for_range(range_to_move.clone()));
5059                    text.pop(); // Drop trailing newline
5060                    edits.push((
5061                        buffer.anchor_after(range_to_move.start)
5062                            ..buffer.anchor_before(range_to_move.end),
5063                        String::new(),
5064                    ));
5065                    let insertion_anchor = buffer.anchor_after(insertion_point);
5066                    edits.push((insertion_anchor..insertion_anchor, text));
5067
5068                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
5069
5070                    // Move selections down
5071                    new_selections.extend(contiguous_row_selections.drain(..).map(
5072                        |mut selection| {
5073                            selection.start.row += row_delta;
5074                            selection.end.row += row_delta;
5075                            selection
5076                        },
5077                    ));
5078
5079                    // Move folds down
5080                    unfold_ranges.push(range_to_move.clone());
5081                    for fold in display_map.folds_in_range(
5082                        buffer.anchor_before(range_to_move.start)
5083                            ..buffer.anchor_after(range_to_move.end),
5084                    ) {
5085                        let mut start = fold.range.start.to_point(&buffer);
5086                        let mut end = fold.range.end.to_point(&buffer);
5087                        start.row += row_delta;
5088                        end.row += row_delta;
5089                        refold_ranges.push(start..end);
5090                    }
5091                }
5092            }
5093
5094            // If we didn't move line(s), preserve the existing selections
5095            new_selections.append(&mut contiguous_row_selections);
5096        }
5097
5098        self.transact(cx, |this, cx| {
5099            this.unfold_ranges(unfold_ranges, true, true, cx);
5100            this.buffer.update(cx, |buffer, cx| {
5101                for (range, text) in edits {
5102                    buffer.edit([(range, text)], None, cx);
5103                }
5104            });
5105            this.fold_ranges(refold_ranges, true, cx);
5106            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
5107        });
5108    }
5109
5110    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
5111        let text_layout_details = &self.text_layout_details(cx);
5112        self.transact(cx, |this, cx| {
5113            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5114                let mut edits: Vec<(Range<usize>, String)> = Default::default();
5115                let line_mode = s.line_mode;
5116                s.move_with(|display_map, selection| {
5117                    if !selection.is_empty() || line_mode {
5118                        return;
5119                    }
5120
5121                    let mut head = selection.head();
5122                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
5123                    if head.column() == display_map.line_len(head.row()) {
5124                        transpose_offset = display_map
5125                            .buffer_snapshot
5126                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
5127                    }
5128
5129                    if transpose_offset == 0 {
5130                        return;
5131                    }
5132
5133                    *head.column_mut() += 1;
5134                    head = display_map.clip_point(head, Bias::Right);
5135                    let goal = SelectionGoal::HorizontalPosition(
5136                        display_map
5137                            .x_for_display_point(head, &text_layout_details)
5138                            .into(),
5139                    );
5140                    selection.collapse_to(head, goal);
5141
5142                    let transpose_start = display_map
5143                        .buffer_snapshot
5144                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
5145                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
5146                        let transpose_end = display_map
5147                            .buffer_snapshot
5148                            .clip_offset(transpose_offset + 1, Bias::Right);
5149                        if let Some(ch) =
5150                            display_map.buffer_snapshot.chars_at(transpose_start).next()
5151                        {
5152                            edits.push((transpose_start..transpose_offset, String::new()));
5153                            edits.push((transpose_end..transpose_end, ch.to_string()));
5154                        }
5155                    }
5156                });
5157                edits
5158            });
5159            this.buffer
5160                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
5161            let selections = this.selections.all::<usize>(cx);
5162            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5163                s.select(selections);
5164            });
5165        });
5166    }
5167
5168    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
5169        let mut text = String::new();
5170        let buffer = self.buffer.read(cx).snapshot(cx);
5171        let mut selections = self.selections.all::<Point>(cx);
5172        let mut clipboard_selections = Vec::with_capacity(selections.len());
5173        {
5174            let max_point = buffer.max_point();
5175            let mut is_first = true;
5176            for selection in &mut selections {
5177                let is_entire_line = selection.is_empty() || self.selections.line_mode;
5178                if is_entire_line {
5179                    selection.start = Point::new(selection.start.row, 0);
5180                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
5181                    selection.goal = SelectionGoal::None;
5182                }
5183                if is_first {
5184                    is_first = false;
5185                } else {
5186                    text += "\n";
5187                }
5188                let mut len = 0;
5189                for chunk in buffer.text_for_range(selection.start..selection.end) {
5190                    text.push_str(chunk);
5191                    len += chunk.len();
5192                }
5193                clipboard_selections.push(ClipboardSelection {
5194                    len,
5195                    is_entire_line,
5196                    first_line_indent: buffer.indent_size_for_line(selection.start.row).len,
5197                });
5198            }
5199        }
5200
5201        self.transact(cx, |this, cx| {
5202            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5203                s.select(selections);
5204            });
5205            this.insert("", cx);
5206            cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
5207        });
5208    }
5209
5210    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
5211        let selections = self.selections.all::<Point>(cx);
5212        let buffer = self.buffer.read(cx).read(cx);
5213        let mut text = String::new();
5214
5215        let mut clipboard_selections = Vec::with_capacity(selections.len());
5216        {
5217            let max_point = buffer.max_point();
5218            let mut is_first = true;
5219            for selection in selections.iter() {
5220                let mut start = selection.start;
5221                let mut end = selection.end;
5222                let is_entire_line = selection.is_empty() || self.selections.line_mode;
5223                if is_entire_line {
5224                    start = Point::new(start.row, 0);
5225                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
5226                }
5227                if is_first {
5228                    is_first = false;
5229                } else {
5230                    text += "\n";
5231                }
5232                let mut len = 0;
5233                for chunk in buffer.text_for_range(start..end) {
5234                    text.push_str(chunk);
5235                    len += chunk.len();
5236                }
5237                clipboard_selections.push(ClipboardSelection {
5238                    len,
5239                    is_entire_line,
5240                    first_line_indent: buffer.indent_size_for_line(start.row).len,
5241                });
5242            }
5243        }
5244
5245        cx.write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
5246    }
5247
5248    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
5249        if self.read_only(cx) {
5250            return;
5251        }
5252
5253        self.transact(cx, |this, cx| {
5254            if let Some(item) = cx.read_from_clipboard() {
5255                let clipboard_text = Cow::Borrowed(item.text());
5256                if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
5257                    let old_selections = this.selections.all::<usize>(cx);
5258                    let all_selections_were_entire_line =
5259                        clipboard_selections.iter().all(|s| s.is_entire_line);
5260                    let first_selection_indent_column =
5261                        clipboard_selections.first().map(|s| s.first_line_indent);
5262                    if clipboard_selections.len() != old_selections.len() {
5263                        clipboard_selections.drain(..);
5264                    }
5265
5266                    this.buffer.update(cx, |buffer, cx| {
5267                        let snapshot = buffer.read(cx);
5268                        let mut start_offset = 0;
5269                        let mut edits = Vec::new();
5270                        let mut original_indent_columns = Vec::new();
5271                        let line_mode = this.selections.line_mode;
5272                        for (ix, selection) in old_selections.iter().enumerate() {
5273                            let to_insert;
5274                            let entire_line;
5275                            let original_indent_column;
5276                            if let Some(clipboard_selection) = clipboard_selections.get(ix) {
5277                                let end_offset = start_offset + clipboard_selection.len;
5278                                to_insert = &clipboard_text[start_offset..end_offset];
5279                                entire_line = clipboard_selection.is_entire_line;
5280                                start_offset = end_offset + 1;
5281                                original_indent_column =
5282                                    Some(clipboard_selection.first_line_indent);
5283                            } else {
5284                                to_insert = clipboard_text.as_str();
5285                                entire_line = all_selections_were_entire_line;
5286                                original_indent_column = first_selection_indent_column
5287                            }
5288
5289                            // If the corresponding selection was empty when this slice of the
5290                            // clipboard text was written, then the entire line containing the
5291                            // selection was copied. If this selection is also currently empty,
5292                            // then paste the line before the current line of the buffer.
5293                            let range = if selection.is_empty() && !line_mode && entire_line {
5294                                let column = selection.start.to_point(&snapshot).column as usize;
5295                                let line_start = selection.start - column;
5296                                line_start..line_start
5297                            } else {
5298                                selection.range()
5299                            };
5300
5301                            edits.push((range, to_insert));
5302                            original_indent_columns.extend(original_indent_column);
5303                        }
5304                        drop(snapshot);
5305
5306                        buffer.edit(
5307                            edits,
5308                            Some(AutoindentMode::Block {
5309                                original_indent_columns,
5310                            }),
5311                            cx,
5312                        );
5313                    });
5314
5315                    let selections = this.selections.all::<usize>(cx);
5316                    this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5317                } else {
5318                    this.insert(&clipboard_text, cx);
5319                }
5320            }
5321        });
5322    }
5323
5324    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
5325        if self.read_only(cx) {
5326            return;
5327        }
5328
5329        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
5330            if let Some((selections, _)) = self.selection_history.transaction(tx_id).cloned() {
5331                self.change_selections(None, cx, |s| {
5332                    s.select_anchors(selections.to_vec());
5333                });
5334            }
5335            self.request_autoscroll(Autoscroll::fit(), cx);
5336            self.unmark_text(cx);
5337            self.refresh_copilot_suggestions(true, cx);
5338            cx.emit(EditorEvent::Edited);
5339        }
5340    }
5341
5342    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
5343        if self.read_only(cx) {
5344            return;
5345        }
5346
5347        if let Some(tx_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
5348            if let Some((_, Some(selections))) = self.selection_history.transaction(tx_id).cloned()
5349            {
5350                self.change_selections(None, cx, |s| {
5351                    s.select_anchors(selections.to_vec());
5352                });
5353            }
5354            self.request_autoscroll(Autoscroll::fit(), cx);
5355            self.unmark_text(cx);
5356            self.refresh_copilot_suggestions(true, cx);
5357            cx.emit(EditorEvent::Edited);
5358        }
5359    }
5360
5361    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
5362        self.buffer
5363            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
5364    }
5365
5366    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
5367        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5368            let line_mode = s.line_mode;
5369            s.move_with(|map, selection| {
5370                let cursor = if selection.is_empty() && !line_mode {
5371                    movement::left(map, selection.start)
5372                } else {
5373                    selection.start
5374                };
5375                selection.collapse_to(cursor, SelectionGoal::None);
5376            });
5377        })
5378    }
5379
5380    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
5381        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5382            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
5383        })
5384    }
5385
5386    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
5387        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5388            let line_mode = s.line_mode;
5389            s.move_with(|map, selection| {
5390                let cursor = if selection.is_empty() && !line_mode {
5391                    movement::right(map, selection.end)
5392                } else {
5393                    selection.end
5394                };
5395                selection.collapse_to(cursor, SelectionGoal::None)
5396            });
5397        })
5398    }
5399
5400    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
5401        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5402            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
5403        })
5404    }
5405
5406    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
5407        if self.take_rename(true, cx).is_some() {
5408            return;
5409        }
5410
5411        if matches!(self.mode, EditorMode::SingleLine) {
5412            cx.propagate();
5413            return;
5414        }
5415
5416        let text_layout_details = &self.text_layout_details(cx);
5417
5418        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5419            let line_mode = s.line_mode;
5420            s.move_with(|map, selection| {
5421                if !selection.is_empty() && !line_mode {
5422                    selection.goal = SelectionGoal::None;
5423                }
5424                let (cursor, goal) = movement::up(
5425                    map,
5426                    selection.start,
5427                    selection.goal,
5428                    false,
5429                    &text_layout_details,
5430                );
5431                selection.collapse_to(cursor, goal);
5432            });
5433        })
5434    }
5435
5436    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
5437        if self.take_rename(true, cx).is_some() {
5438            return;
5439        }
5440
5441        if matches!(self.mode, EditorMode::SingleLine) {
5442            cx.propagate();
5443            return;
5444        }
5445
5446        let row_count = if let Some(row_count) = self.visible_line_count() {
5447            row_count as u32 - 1
5448        } else {
5449            return;
5450        };
5451
5452        let autoscroll = if action.center_cursor {
5453            Autoscroll::center()
5454        } else {
5455            Autoscroll::fit()
5456        };
5457
5458        let text_layout_details = &self.text_layout_details(cx);
5459
5460        self.change_selections(Some(autoscroll), cx, |s| {
5461            let line_mode = s.line_mode;
5462            s.move_with(|map, selection| {
5463                if !selection.is_empty() && !line_mode {
5464                    selection.goal = SelectionGoal::None;
5465                }
5466                let (cursor, goal) = movement::up_by_rows(
5467                    map,
5468                    selection.end,
5469                    row_count,
5470                    selection.goal,
5471                    false,
5472                    &text_layout_details,
5473                );
5474                selection.collapse_to(cursor, goal);
5475            });
5476        });
5477    }
5478
5479    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
5480        let text_layout_details = &self.text_layout_details(cx);
5481        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5482            s.move_heads_with(|map, head, goal| {
5483                movement::up(map, head, goal, false, &text_layout_details)
5484            })
5485        })
5486    }
5487
5488    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
5489        self.take_rename(true, cx);
5490
5491        if self.mode == EditorMode::SingleLine {
5492            cx.propagate();
5493            return;
5494        }
5495
5496        let text_layout_details = &self.text_layout_details(cx);
5497        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5498            let line_mode = s.line_mode;
5499            s.move_with(|map, selection| {
5500                if !selection.is_empty() && !line_mode {
5501                    selection.goal = SelectionGoal::None;
5502                }
5503                let (cursor, goal) = movement::down(
5504                    map,
5505                    selection.end,
5506                    selection.goal,
5507                    false,
5508                    &text_layout_details,
5509                );
5510                selection.collapse_to(cursor, goal);
5511            });
5512        });
5513    }
5514
5515    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
5516        if self.take_rename(true, cx).is_some() {
5517            return;
5518        }
5519
5520        if self
5521            .context_menu
5522            .write()
5523            .as_mut()
5524            .map(|menu| menu.select_last(self.project.as_ref(), cx))
5525            .unwrap_or(false)
5526        {
5527            return;
5528        }
5529
5530        if matches!(self.mode, EditorMode::SingleLine) {
5531            cx.propagate();
5532            return;
5533        }
5534
5535        let row_count = if let Some(row_count) = self.visible_line_count() {
5536            row_count as u32 - 1
5537        } else {
5538            return;
5539        };
5540
5541        let autoscroll = if action.center_cursor {
5542            Autoscroll::center()
5543        } else {
5544            Autoscroll::fit()
5545        };
5546
5547        let text_layout_details = &self.text_layout_details(cx);
5548        self.change_selections(Some(autoscroll), cx, |s| {
5549            let line_mode = s.line_mode;
5550            s.move_with(|map, selection| {
5551                if !selection.is_empty() && !line_mode {
5552                    selection.goal = SelectionGoal::None;
5553                }
5554                let (cursor, goal) = movement::down_by_rows(
5555                    map,
5556                    selection.end,
5557                    row_count,
5558                    selection.goal,
5559                    false,
5560                    &text_layout_details,
5561                );
5562                selection.collapse_to(cursor, goal);
5563            });
5564        });
5565    }
5566
5567    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
5568        let text_layout_details = &self.text_layout_details(cx);
5569        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5570            s.move_heads_with(|map, head, goal| {
5571                movement::down(map, head, goal, false, &text_layout_details)
5572            })
5573        });
5574    }
5575
5576    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
5577        if let Some(context_menu) = self.context_menu.write().as_mut() {
5578            context_menu.select_first(self.project.as_ref(), cx);
5579        }
5580    }
5581
5582    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
5583        if let Some(context_menu) = self.context_menu.write().as_mut() {
5584            context_menu.select_prev(self.project.as_ref(), cx);
5585        }
5586    }
5587
5588    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
5589        if let Some(context_menu) = self.context_menu.write().as_mut() {
5590            context_menu.select_next(self.project.as_ref(), cx);
5591        }
5592    }
5593
5594    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
5595        if let Some(context_menu) = self.context_menu.write().as_mut() {
5596            context_menu.select_last(self.project.as_ref(), cx);
5597        }
5598    }
5599
5600    pub fn move_to_previous_word_start(
5601        &mut self,
5602        _: &MoveToPreviousWordStart,
5603        cx: &mut ViewContext<Self>,
5604    ) {
5605        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5606            s.move_cursors_with(|map, head, _| {
5607                (
5608                    movement::previous_word_start(map, head),
5609                    SelectionGoal::None,
5610                )
5611            });
5612        })
5613    }
5614
5615    pub fn move_to_previous_subword_start(
5616        &mut self,
5617        _: &MoveToPreviousSubwordStart,
5618        cx: &mut ViewContext<Self>,
5619    ) {
5620        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5621            s.move_cursors_with(|map, head, _| {
5622                (
5623                    movement::previous_subword_start(map, head),
5624                    SelectionGoal::None,
5625                )
5626            });
5627        })
5628    }
5629
5630    pub fn select_to_previous_word_start(
5631        &mut self,
5632        _: &SelectToPreviousWordStart,
5633        cx: &mut ViewContext<Self>,
5634    ) {
5635        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5636            s.move_heads_with(|map, head, _| {
5637                (
5638                    movement::previous_word_start(map, head),
5639                    SelectionGoal::None,
5640                )
5641            });
5642        })
5643    }
5644
5645    pub fn select_to_previous_subword_start(
5646        &mut self,
5647        _: &SelectToPreviousSubwordStart,
5648        cx: &mut ViewContext<Self>,
5649    ) {
5650        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5651            s.move_heads_with(|map, head, _| {
5652                (
5653                    movement::previous_subword_start(map, head),
5654                    SelectionGoal::None,
5655                )
5656            });
5657        })
5658    }
5659
5660    pub fn delete_to_previous_word_start(
5661        &mut self,
5662        _: &DeleteToPreviousWordStart,
5663        cx: &mut ViewContext<Self>,
5664    ) {
5665        self.transact(cx, |this, cx| {
5666            this.select_autoclose_pair(cx);
5667            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5668                let line_mode = s.line_mode;
5669                s.move_with(|map, selection| {
5670                    if selection.is_empty() && !line_mode {
5671                        let cursor = movement::previous_word_start(map, selection.head());
5672                        selection.set_head(cursor, SelectionGoal::None);
5673                    }
5674                });
5675            });
5676            this.insert("", cx);
5677        });
5678    }
5679
5680    pub fn delete_to_previous_subword_start(
5681        &mut self,
5682        _: &DeleteToPreviousSubwordStart,
5683        cx: &mut ViewContext<Self>,
5684    ) {
5685        self.transact(cx, |this, cx| {
5686            this.select_autoclose_pair(cx);
5687            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5688                let line_mode = s.line_mode;
5689                s.move_with(|map, selection| {
5690                    if selection.is_empty() && !line_mode {
5691                        let cursor = movement::previous_subword_start(map, selection.head());
5692                        selection.set_head(cursor, SelectionGoal::None);
5693                    }
5694                });
5695            });
5696            this.insert("", cx);
5697        });
5698    }
5699
5700    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
5701        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5702            s.move_cursors_with(|map, head, _| {
5703                (movement::next_word_end(map, head), SelectionGoal::None)
5704            });
5705        })
5706    }
5707
5708    pub fn move_to_next_subword_end(
5709        &mut self,
5710        _: &MoveToNextSubwordEnd,
5711        cx: &mut ViewContext<Self>,
5712    ) {
5713        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5714            s.move_cursors_with(|map, head, _| {
5715                (movement::next_subword_end(map, head), SelectionGoal::None)
5716            });
5717        })
5718    }
5719
5720    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
5721        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5722            s.move_heads_with(|map, head, _| {
5723                (movement::next_word_end(map, head), SelectionGoal::None)
5724            });
5725        })
5726    }
5727
5728    pub fn select_to_next_subword_end(
5729        &mut self,
5730        _: &SelectToNextSubwordEnd,
5731        cx: &mut ViewContext<Self>,
5732    ) {
5733        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5734            s.move_heads_with(|map, head, _| {
5735                (movement::next_subword_end(map, head), SelectionGoal::None)
5736            });
5737        })
5738    }
5739
5740    pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
5741        self.transact(cx, |this, cx| {
5742            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5743                let line_mode = s.line_mode;
5744                s.move_with(|map, selection| {
5745                    if selection.is_empty() && !line_mode {
5746                        let cursor = movement::next_word_end(map, selection.head());
5747                        selection.set_head(cursor, SelectionGoal::None);
5748                    }
5749                });
5750            });
5751            this.insert("", cx);
5752        });
5753    }
5754
5755    pub fn delete_to_next_subword_end(
5756        &mut self,
5757        _: &DeleteToNextSubwordEnd,
5758        cx: &mut ViewContext<Self>,
5759    ) {
5760        self.transact(cx, |this, cx| {
5761            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5762                s.move_with(|map, selection| {
5763                    if selection.is_empty() {
5764                        let cursor = movement::next_subword_end(map, selection.head());
5765                        selection.set_head(cursor, SelectionGoal::None);
5766                    }
5767                });
5768            });
5769            this.insert("", cx);
5770        });
5771    }
5772
5773    pub fn move_to_beginning_of_line(
5774        &mut self,
5775        _: &MoveToBeginningOfLine,
5776        cx: &mut ViewContext<Self>,
5777    ) {
5778        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5779            s.move_cursors_with(|map, head, _| {
5780                (
5781                    movement::indented_line_beginning(map, head, true),
5782                    SelectionGoal::None,
5783                )
5784            });
5785        })
5786    }
5787
5788    pub fn select_to_beginning_of_line(
5789        &mut self,
5790        action: &SelectToBeginningOfLine,
5791        cx: &mut ViewContext<Self>,
5792    ) {
5793        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5794            s.move_heads_with(|map, head, _| {
5795                (
5796                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
5797                    SelectionGoal::None,
5798                )
5799            });
5800        });
5801    }
5802
5803    pub fn delete_to_beginning_of_line(
5804        &mut self,
5805        _: &DeleteToBeginningOfLine,
5806        cx: &mut ViewContext<Self>,
5807    ) {
5808        self.transact(cx, |this, cx| {
5809            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5810                s.move_with(|_, selection| {
5811                    selection.reversed = true;
5812                });
5813            });
5814
5815            this.select_to_beginning_of_line(
5816                &SelectToBeginningOfLine {
5817                    stop_at_soft_wraps: false,
5818                },
5819                cx,
5820            );
5821            this.backspace(&Backspace, cx);
5822        });
5823    }
5824
5825    pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
5826        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5827            s.move_cursors_with(|map, head, _| {
5828                (movement::line_end(map, head, true), SelectionGoal::None)
5829            });
5830        })
5831    }
5832
5833    pub fn select_to_end_of_line(
5834        &mut self,
5835        action: &SelectToEndOfLine,
5836        cx: &mut ViewContext<Self>,
5837    ) {
5838        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5839            s.move_heads_with(|map, head, _| {
5840                (
5841                    movement::line_end(map, head, action.stop_at_soft_wraps),
5842                    SelectionGoal::None,
5843                )
5844            });
5845        })
5846    }
5847
5848    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
5849        self.transact(cx, |this, cx| {
5850            this.select_to_end_of_line(
5851                &SelectToEndOfLine {
5852                    stop_at_soft_wraps: false,
5853                },
5854                cx,
5855            );
5856            this.delete(&Delete, cx);
5857        });
5858    }
5859
5860    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
5861        self.transact(cx, |this, cx| {
5862            this.select_to_end_of_line(
5863                &SelectToEndOfLine {
5864                    stop_at_soft_wraps: false,
5865                },
5866                cx,
5867            );
5868            this.cut(&Cut, cx);
5869        });
5870    }
5871
5872    pub fn move_to_start_of_paragraph(
5873        &mut self,
5874        _: &MoveToStartOfParagraph,
5875        cx: &mut ViewContext<Self>,
5876    ) {
5877        if matches!(self.mode, EditorMode::SingleLine) {
5878            cx.propagate();
5879            return;
5880        }
5881
5882        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5883            s.move_with(|map, selection| {
5884                selection.collapse_to(
5885                    movement::start_of_paragraph(map, selection.head(), 1),
5886                    SelectionGoal::None,
5887                )
5888            });
5889        })
5890    }
5891
5892    pub fn move_to_end_of_paragraph(
5893        &mut self,
5894        _: &MoveToEndOfParagraph,
5895        cx: &mut ViewContext<Self>,
5896    ) {
5897        if matches!(self.mode, EditorMode::SingleLine) {
5898            cx.propagate();
5899            return;
5900        }
5901
5902        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5903            s.move_with(|map, selection| {
5904                selection.collapse_to(
5905                    movement::end_of_paragraph(map, selection.head(), 1),
5906                    SelectionGoal::None,
5907                )
5908            });
5909        })
5910    }
5911
5912    pub fn select_to_start_of_paragraph(
5913        &mut self,
5914        _: &SelectToStartOfParagraph,
5915        cx: &mut ViewContext<Self>,
5916    ) {
5917        if matches!(self.mode, EditorMode::SingleLine) {
5918            cx.propagate();
5919            return;
5920        }
5921
5922        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5923            s.move_heads_with(|map, head, _| {
5924                (
5925                    movement::start_of_paragraph(map, head, 1),
5926                    SelectionGoal::None,
5927                )
5928            });
5929        })
5930    }
5931
5932    pub fn select_to_end_of_paragraph(
5933        &mut self,
5934        _: &SelectToEndOfParagraph,
5935        cx: &mut ViewContext<Self>,
5936    ) {
5937        if matches!(self.mode, EditorMode::SingleLine) {
5938            cx.propagate();
5939            return;
5940        }
5941
5942        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5943            s.move_heads_with(|map, head, _| {
5944                (
5945                    movement::end_of_paragraph(map, head, 1),
5946                    SelectionGoal::None,
5947                )
5948            });
5949        })
5950    }
5951
5952    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
5953        if matches!(self.mode, EditorMode::SingleLine) {
5954            cx.propagate();
5955            return;
5956        }
5957
5958        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5959            s.select_ranges(vec![0..0]);
5960        });
5961    }
5962
5963    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
5964        let mut selection = self.selections.last::<Point>(cx);
5965        selection.set_head(Point::zero(), SelectionGoal::None);
5966
5967        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5968            s.select(vec![selection]);
5969        });
5970    }
5971
5972    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
5973        if matches!(self.mode, EditorMode::SingleLine) {
5974            cx.propagate();
5975            return;
5976        }
5977
5978        let cursor = self.buffer.read(cx).read(cx).len();
5979        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5980            s.select_ranges(vec![cursor..cursor])
5981        });
5982    }
5983
5984    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
5985        self.nav_history = nav_history;
5986    }
5987
5988    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
5989        self.nav_history.as_ref()
5990    }
5991
5992    fn push_to_nav_history(
5993        &mut self,
5994        cursor_anchor: Anchor,
5995        new_position: Option<Point>,
5996        cx: &mut ViewContext<Self>,
5997    ) {
5998        if let Some(nav_history) = self.nav_history.as_mut() {
5999            let buffer = self.buffer.read(cx).read(cx);
6000            let cursor_position = cursor_anchor.to_point(&buffer);
6001            let scroll_state = self.scroll_manager.anchor();
6002            let scroll_top_row = scroll_state.top_row(&buffer);
6003            drop(buffer);
6004
6005            if let Some(new_position) = new_position {
6006                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
6007                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
6008                    return;
6009                }
6010            }
6011
6012            nav_history.push(
6013                Some(NavigationData {
6014                    cursor_anchor,
6015                    cursor_position,
6016                    scroll_anchor: scroll_state,
6017                    scroll_top_row,
6018                }),
6019                cx,
6020            );
6021        }
6022    }
6023
6024    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
6025        let buffer = self.buffer.read(cx).snapshot(cx);
6026        let mut selection = self.selections.first::<usize>(cx);
6027        selection.set_head(buffer.len(), SelectionGoal::None);
6028        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6029            s.select(vec![selection]);
6030        });
6031    }
6032
6033    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
6034        let end = self.buffer.read(cx).read(cx).len();
6035        self.change_selections(None, cx, |s| {
6036            s.select_ranges(vec![0..end]);
6037        });
6038    }
6039
6040    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
6041        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6042        let mut selections = self.selections.all::<Point>(cx);
6043        let max_point = display_map.buffer_snapshot.max_point();
6044        for selection in &mut selections {
6045            let rows = selection.spanned_rows(true, &display_map);
6046            selection.start = Point::new(rows.start, 0);
6047            selection.end = cmp::min(max_point, Point::new(rows.end, 0));
6048            selection.reversed = false;
6049        }
6050        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6051            s.select(selections);
6052        });
6053    }
6054
6055    pub fn split_selection_into_lines(
6056        &mut self,
6057        _: &SplitSelectionIntoLines,
6058        cx: &mut ViewContext<Self>,
6059    ) {
6060        let mut to_unfold = Vec::new();
6061        let mut new_selection_ranges = Vec::new();
6062        {
6063            let selections = self.selections.all::<Point>(cx);
6064            let buffer = self.buffer.read(cx).read(cx);
6065            for selection in selections {
6066                for row in selection.start.row..selection.end.row {
6067                    let cursor = Point::new(row, buffer.line_len(row));
6068                    new_selection_ranges.push(cursor..cursor);
6069                }
6070                new_selection_ranges.push(selection.end..selection.end);
6071                to_unfold.push(selection.start..selection.end);
6072            }
6073        }
6074        self.unfold_ranges(to_unfold, true, true, cx);
6075        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6076            s.select_ranges(new_selection_ranges);
6077        });
6078    }
6079
6080    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
6081        self.add_selection(true, cx);
6082    }
6083
6084    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
6085        self.add_selection(false, cx);
6086    }
6087
6088    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
6089        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6090        let mut selections = self.selections.all::<Point>(cx);
6091        let text_layout_details = self.text_layout_details(cx);
6092        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
6093            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
6094            let range = oldest_selection.display_range(&display_map).sorted();
6095
6096            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
6097            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
6098            let positions = start_x.min(end_x)..start_x.max(end_x);
6099
6100            selections.clear();
6101            let mut stack = Vec::new();
6102            for row in range.start.row()..=range.end.row() {
6103                if let Some(selection) = self.selections.build_columnar_selection(
6104                    &display_map,
6105                    row,
6106                    &positions,
6107                    oldest_selection.reversed,
6108                    &text_layout_details,
6109                ) {
6110                    stack.push(selection.id);
6111                    selections.push(selection);
6112                }
6113            }
6114
6115            if above {
6116                stack.reverse();
6117            }
6118
6119            AddSelectionsState { above, stack }
6120        });
6121
6122        let last_added_selection = *state.stack.last().unwrap();
6123        let mut new_selections = Vec::new();
6124        if above == state.above {
6125            let end_row = if above {
6126                0
6127            } else {
6128                display_map.max_point().row()
6129            };
6130
6131            'outer: for selection in selections {
6132                if selection.id == last_added_selection {
6133                    let range = selection.display_range(&display_map).sorted();
6134                    debug_assert_eq!(range.start.row(), range.end.row());
6135                    let mut row = range.start.row();
6136                    let positions =
6137                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
6138                            px(start)..px(end)
6139                        } else {
6140                            let start_x =
6141                                display_map.x_for_display_point(range.start, &text_layout_details);
6142                            let end_x =
6143                                display_map.x_for_display_point(range.end, &text_layout_details);
6144                            start_x.min(end_x)..start_x.max(end_x)
6145                        };
6146
6147                    while row != end_row {
6148                        if above {
6149                            row -= 1;
6150                        } else {
6151                            row += 1;
6152                        }
6153
6154                        if let Some(new_selection) = self.selections.build_columnar_selection(
6155                            &display_map,
6156                            row,
6157                            &positions,
6158                            selection.reversed,
6159                            &text_layout_details,
6160                        ) {
6161                            state.stack.push(new_selection.id);
6162                            if above {
6163                                new_selections.push(new_selection);
6164                                new_selections.push(selection);
6165                            } else {
6166                                new_selections.push(selection);
6167                                new_selections.push(new_selection);
6168                            }
6169
6170                            continue 'outer;
6171                        }
6172                    }
6173                }
6174
6175                new_selections.push(selection);
6176            }
6177        } else {
6178            new_selections = selections;
6179            new_selections.retain(|s| s.id != last_added_selection);
6180            state.stack.pop();
6181        }
6182
6183        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6184            s.select(new_selections);
6185        });
6186        if state.stack.len() > 1 {
6187            self.add_selections_state = Some(state);
6188        }
6189    }
6190
6191    pub fn select_next_match_internal(
6192        &mut self,
6193        display_map: &DisplaySnapshot,
6194        replace_newest: bool,
6195        autoscroll: Option<Autoscroll>,
6196        cx: &mut ViewContext<Self>,
6197    ) -> Result<()> {
6198        fn select_next_match_ranges(
6199            this: &mut Editor,
6200            range: Range<usize>,
6201            replace_newest: bool,
6202            auto_scroll: Option<Autoscroll>,
6203            cx: &mut ViewContext<Editor>,
6204        ) {
6205            this.unfold_ranges([range.clone()], false, true, cx);
6206            this.change_selections(auto_scroll, cx, |s| {
6207                if replace_newest {
6208                    s.delete(s.newest_anchor().id);
6209                }
6210                s.insert_range(range.clone());
6211            });
6212        }
6213
6214        let buffer = &display_map.buffer_snapshot;
6215        let mut selections = self.selections.all::<usize>(cx);
6216        if let Some(mut select_next_state) = self.select_next_state.take() {
6217            let query = &select_next_state.query;
6218            if !select_next_state.done {
6219                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
6220                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
6221                let mut next_selected_range = None;
6222
6223                let bytes_after_last_selection =
6224                    buffer.bytes_in_range(last_selection.end..buffer.len());
6225                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
6226                let query_matches = query
6227                    .stream_find_iter(bytes_after_last_selection)
6228                    .map(|result| (last_selection.end, result))
6229                    .chain(
6230                        query
6231                            .stream_find_iter(bytes_before_first_selection)
6232                            .map(|result| (0, result)),
6233                    );
6234
6235                for (start_offset, query_match) in query_matches {
6236                    let query_match = query_match.unwrap(); // can only fail due to I/O
6237                    let offset_range =
6238                        start_offset + query_match.start()..start_offset + query_match.end();
6239                    let display_range = offset_range.start.to_display_point(&display_map)
6240                        ..offset_range.end.to_display_point(&display_map);
6241
6242                    if !select_next_state.wordwise
6243                        || (!movement::is_inside_word(&display_map, display_range.start)
6244                            && !movement::is_inside_word(&display_map, display_range.end))
6245                    {
6246                        if selections
6247                            .iter()
6248                            .find(|selection| selection.range().overlaps(&offset_range))
6249                            .is_none()
6250                        {
6251                            next_selected_range = Some(offset_range);
6252                            break;
6253                        }
6254                    }
6255                }
6256
6257                if let Some(next_selected_range) = next_selected_range {
6258                    select_next_match_ranges(
6259                        self,
6260                        next_selected_range,
6261                        replace_newest,
6262                        autoscroll,
6263                        cx,
6264                    );
6265                } else {
6266                    select_next_state.done = true;
6267                }
6268            }
6269
6270            self.select_next_state = Some(select_next_state);
6271        } else {
6272            let mut only_carets = true;
6273            let mut same_text_selected = true;
6274            let mut selected_text = None;
6275
6276            let mut selections_iter = selections.iter().peekable();
6277            while let Some(selection) = selections_iter.next() {
6278                if selection.start != selection.end {
6279                    only_carets = false;
6280                }
6281
6282                if same_text_selected {
6283                    if selected_text.is_none() {
6284                        selected_text =
6285                            Some(buffer.text_for_range(selection.range()).collect::<String>());
6286                    }
6287
6288                    if let Some(next_selection) = selections_iter.peek() {
6289                        if next_selection.range().len() == selection.range().len() {
6290                            let next_selected_text = buffer
6291                                .text_for_range(next_selection.range())
6292                                .collect::<String>();
6293                            if Some(next_selected_text) != selected_text {
6294                                same_text_selected = false;
6295                                selected_text = None;
6296                            }
6297                        } else {
6298                            same_text_selected = false;
6299                            selected_text = None;
6300                        }
6301                    }
6302                }
6303            }
6304
6305            if only_carets {
6306                for selection in &mut selections {
6307                    let word_range = movement::surrounding_word(
6308                        &display_map,
6309                        selection.start.to_display_point(&display_map),
6310                    );
6311                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
6312                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
6313                    selection.goal = SelectionGoal::None;
6314                    selection.reversed = false;
6315                    select_next_match_ranges(
6316                        self,
6317                        selection.start..selection.end,
6318                        replace_newest,
6319                        autoscroll,
6320                        cx,
6321                    );
6322                }
6323
6324                if selections.len() == 1 {
6325                    let selection = selections
6326                        .last()
6327                        .expect("ensured that there's only one selection");
6328                    let query = buffer
6329                        .text_for_range(selection.start..selection.end)
6330                        .collect::<String>();
6331                    let is_empty = query.is_empty();
6332                    let select_state = SelectNextState {
6333                        query: AhoCorasick::new(&[query])?,
6334                        wordwise: true,
6335                        done: is_empty,
6336                    };
6337                    self.select_next_state = Some(select_state);
6338                } else {
6339                    self.select_next_state = None;
6340                }
6341            } else if let Some(selected_text) = selected_text {
6342                self.select_next_state = Some(SelectNextState {
6343                    query: AhoCorasick::new(&[selected_text])?,
6344                    wordwise: false,
6345                    done: false,
6346                });
6347                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
6348            }
6349        }
6350        Ok(())
6351    }
6352
6353    pub fn select_all_matches(
6354        &mut self,
6355        action: &SelectAllMatches,
6356        cx: &mut ViewContext<Self>,
6357    ) -> Result<()> {
6358        self.push_to_selection_history();
6359        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6360
6361        loop {
6362            self.select_next_match_internal(&display_map, action.replace_newest, None, cx)?;
6363
6364            if self
6365                .select_next_state
6366                .as_ref()
6367                .map(|selection_state| selection_state.done)
6368                .unwrap_or(true)
6369            {
6370                break;
6371            }
6372        }
6373
6374        Ok(())
6375    }
6376
6377    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
6378        self.push_to_selection_history();
6379        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6380        self.select_next_match_internal(
6381            &display_map,
6382            action.replace_newest,
6383            Some(Autoscroll::newest()),
6384            cx,
6385        )?;
6386        Ok(())
6387    }
6388
6389    pub fn select_previous(
6390        &mut self,
6391        action: &SelectPrevious,
6392        cx: &mut ViewContext<Self>,
6393    ) -> Result<()> {
6394        self.push_to_selection_history();
6395        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6396        let buffer = &display_map.buffer_snapshot;
6397        let mut selections = self.selections.all::<usize>(cx);
6398        if let Some(mut select_prev_state) = self.select_prev_state.take() {
6399            let query = &select_prev_state.query;
6400            if !select_prev_state.done {
6401                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
6402                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
6403                let mut next_selected_range = None;
6404                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
6405                let bytes_before_last_selection =
6406                    buffer.reversed_bytes_in_range(0..last_selection.start);
6407                let bytes_after_first_selection =
6408                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
6409                let query_matches = query
6410                    .stream_find_iter(bytes_before_last_selection)
6411                    .map(|result| (last_selection.start, result))
6412                    .chain(
6413                        query
6414                            .stream_find_iter(bytes_after_first_selection)
6415                            .map(|result| (buffer.len(), result)),
6416                    );
6417                for (end_offset, query_match) in query_matches {
6418                    let query_match = query_match.unwrap(); // can only fail due to I/O
6419                    let offset_range =
6420                        end_offset - query_match.end()..end_offset - query_match.start();
6421                    let display_range = offset_range.start.to_display_point(&display_map)
6422                        ..offset_range.end.to_display_point(&display_map);
6423
6424                    if !select_prev_state.wordwise
6425                        || (!movement::is_inside_word(&display_map, display_range.start)
6426                            && !movement::is_inside_word(&display_map, display_range.end))
6427                    {
6428                        next_selected_range = Some(offset_range);
6429                        break;
6430                    }
6431                }
6432
6433                if let Some(next_selected_range) = next_selected_range {
6434                    self.unfold_ranges([next_selected_range.clone()], false, true, cx);
6435                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
6436                        if action.replace_newest {
6437                            s.delete(s.newest_anchor().id);
6438                        }
6439                        s.insert_range(next_selected_range);
6440                    });
6441                } else {
6442                    select_prev_state.done = true;
6443                }
6444            }
6445
6446            self.select_prev_state = Some(select_prev_state);
6447        } else {
6448            let mut only_carets = true;
6449            let mut same_text_selected = true;
6450            let mut selected_text = None;
6451
6452            let mut selections_iter = selections.iter().peekable();
6453            while let Some(selection) = selections_iter.next() {
6454                if selection.start != selection.end {
6455                    only_carets = false;
6456                }
6457
6458                if same_text_selected {
6459                    if selected_text.is_none() {
6460                        selected_text =
6461                            Some(buffer.text_for_range(selection.range()).collect::<String>());
6462                    }
6463
6464                    if let Some(next_selection) = selections_iter.peek() {
6465                        if next_selection.range().len() == selection.range().len() {
6466                            let next_selected_text = buffer
6467                                .text_for_range(next_selection.range())
6468                                .collect::<String>();
6469                            if Some(next_selected_text) != selected_text {
6470                                same_text_selected = false;
6471                                selected_text = None;
6472                            }
6473                        } else {
6474                            same_text_selected = false;
6475                            selected_text = None;
6476                        }
6477                    }
6478                }
6479            }
6480
6481            if only_carets {
6482                for selection in &mut selections {
6483                    let word_range = movement::surrounding_word(
6484                        &display_map,
6485                        selection.start.to_display_point(&display_map),
6486                    );
6487                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
6488                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
6489                    selection.goal = SelectionGoal::None;
6490                    selection.reversed = false;
6491                }
6492                if selections.len() == 1 {
6493                    let selection = selections
6494                        .last()
6495                        .expect("ensured that there's only one selection");
6496                    let query = buffer
6497                        .text_for_range(selection.start..selection.end)
6498                        .collect::<String>();
6499                    let is_empty = query.is_empty();
6500                    let select_state = SelectNextState {
6501                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
6502                        wordwise: true,
6503                        done: is_empty,
6504                    };
6505                    self.select_prev_state = Some(select_state);
6506                } else {
6507                    self.select_prev_state = None;
6508                }
6509
6510                self.unfold_ranges(
6511                    selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
6512                    false,
6513                    true,
6514                    cx,
6515                );
6516                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
6517                    s.select(selections);
6518                });
6519            } else if let Some(selected_text) = selected_text {
6520                self.select_prev_state = Some(SelectNextState {
6521                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
6522                    wordwise: false,
6523                    done: false,
6524                });
6525                self.select_previous(action, cx)?;
6526            }
6527        }
6528        Ok(())
6529    }
6530
6531    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
6532        let text_layout_details = &self.text_layout_details(cx);
6533        self.transact(cx, |this, cx| {
6534            let mut selections = this.selections.all::<Point>(cx);
6535            let mut edits = Vec::new();
6536            let mut selection_edit_ranges = Vec::new();
6537            let mut last_toggled_row = None;
6538            let snapshot = this.buffer.read(cx).read(cx);
6539            let empty_str: Arc<str> = "".into();
6540            let mut suffixes_inserted = Vec::new();
6541
6542            fn comment_prefix_range(
6543                snapshot: &MultiBufferSnapshot,
6544                row: u32,
6545                comment_prefix: &str,
6546                comment_prefix_whitespace: &str,
6547            ) -> Range<Point> {
6548                let start = Point::new(row, snapshot.indent_size_for_line(row).len);
6549
6550                let mut line_bytes = snapshot
6551                    .bytes_in_range(start..snapshot.max_point())
6552                    .flatten()
6553                    .copied();
6554
6555                // If this line currently begins with the line comment prefix, then record
6556                // the range containing the prefix.
6557                if line_bytes
6558                    .by_ref()
6559                    .take(comment_prefix.len())
6560                    .eq(comment_prefix.bytes())
6561                {
6562                    // Include any whitespace that matches the comment prefix.
6563                    let matching_whitespace_len = line_bytes
6564                        .zip(comment_prefix_whitespace.bytes())
6565                        .take_while(|(a, b)| a == b)
6566                        .count() as u32;
6567                    let end = Point::new(
6568                        start.row,
6569                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
6570                    );
6571                    start..end
6572                } else {
6573                    start..start
6574                }
6575            }
6576
6577            fn comment_suffix_range(
6578                snapshot: &MultiBufferSnapshot,
6579                row: u32,
6580                comment_suffix: &str,
6581                comment_suffix_has_leading_space: bool,
6582            ) -> Range<Point> {
6583                let end = Point::new(row, snapshot.line_len(row));
6584                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
6585
6586                let mut line_end_bytes = snapshot
6587                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
6588                    .flatten()
6589                    .copied();
6590
6591                let leading_space_len = if suffix_start_column > 0
6592                    && line_end_bytes.next() == Some(b' ')
6593                    && comment_suffix_has_leading_space
6594                {
6595                    1
6596                } else {
6597                    0
6598                };
6599
6600                // If this line currently begins with the line comment prefix, then record
6601                // the range containing the prefix.
6602                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
6603                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
6604                    start..end
6605                } else {
6606                    end..end
6607                }
6608            }
6609
6610            // TODO: Handle selections that cross excerpts
6611            for selection in &mut selections {
6612                let start_column = snapshot.indent_size_for_line(selection.start.row).len;
6613                let language = if let Some(language) =
6614                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
6615                {
6616                    language
6617                } else {
6618                    continue;
6619                };
6620
6621                selection_edit_ranges.clear();
6622
6623                // If multiple selections contain a given row, avoid processing that
6624                // row more than once.
6625                let mut start_row = selection.start.row;
6626                if last_toggled_row == Some(start_row) {
6627                    start_row += 1;
6628                }
6629                let end_row =
6630                    if selection.end.row > selection.start.row && selection.end.column == 0 {
6631                        selection.end.row - 1
6632                    } else {
6633                        selection.end.row
6634                    };
6635                last_toggled_row = Some(end_row);
6636
6637                if start_row > end_row {
6638                    continue;
6639                }
6640
6641                // If the language has line comments, toggle those.
6642                if let Some(full_comment_prefix) = language.line_comment_prefix() {
6643                    // Split the comment prefix's trailing whitespace into a separate string,
6644                    // as that portion won't be used for detecting if a line is a comment.
6645                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
6646                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
6647                    let mut all_selection_lines_are_comments = true;
6648
6649                    for row in start_row..=end_row {
6650                        if snapshot.is_line_blank(row) && start_row < end_row {
6651                            continue;
6652                        }
6653
6654                        let prefix_range = comment_prefix_range(
6655                            snapshot.deref(),
6656                            row,
6657                            comment_prefix,
6658                            comment_prefix_whitespace,
6659                        );
6660                        if prefix_range.is_empty() {
6661                            all_selection_lines_are_comments = false;
6662                        }
6663                        selection_edit_ranges.push(prefix_range);
6664                    }
6665
6666                    if all_selection_lines_are_comments {
6667                        edits.extend(
6668                            selection_edit_ranges
6669                                .iter()
6670                                .cloned()
6671                                .map(|range| (range, empty_str.clone())),
6672                        );
6673                    } else {
6674                        let min_column = selection_edit_ranges
6675                            .iter()
6676                            .map(|r| r.start.column)
6677                            .min()
6678                            .unwrap_or(0);
6679                        edits.extend(selection_edit_ranges.iter().map(|range| {
6680                            let position = Point::new(range.start.row, min_column);
6681                            (position..position, full_comment_prefix.clone())
6682                        }));
6683                    }
6684                } else if let Some((full_comment_prefix, comment_suffix)) =
6685                    language.block_comment_delimiters()
6686                {
6687                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
6688                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
6689                    let prefix_range = comment_prefix_range(
6690                        snapshot.deref(),
6691                        start_row,
6692                        comment_prefix,
6693                        comment_prefix_whitespace,
6694                    );
6695                    let suffix_range = comment_suffix_range(
6696                        snapshot.deref(),
6697                        end_row,
6698                        comment_suffix.trim_start_matches(' '),
6699                        comment_suffix.starts_with(' '),
6700                    );
6701
6702                    if prefix_range.is_empty() || suffix_range.is_empty() {
6703                        edits.push((
6704                            prefix_range.start..prefix_range.start,
6705                            full_comment_prefix.clone(),
6706                        ));
6707                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
6708                        suffixes_inserted.push((end_row, comment_suffix.len()));
6709                    } else {
6710                        edits.push((prefix_range, empty_str.clone()));
6711                        edits.push((suffix_range, empty_str.clone()));
6712                    }
6713                } else {
6714                    continue;
6715                }
6716            }
6717
6718            drop(snapshot);
6719            this.buffer.update(cx, |buffer, cx| {
6720                buffer.edit(edits, None, cx);
6721            });
6722
6723            // Adjust selections so that they end before any comment suffixes that
6724            // were inserted.
6725            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
6726            let mut selections = this.selections.all::<Point>(cx);
6727            let snapshot = this.buffer.read(cx).read(cx);
6728            for selection in &mut selections {
6729                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
6730                    match row.cmp(&selection.end.row) {
6731                        Ordering::Less => {
6732                            suffixes_inserted.next();
6733                            continue;
6734                        }
6735                        Ordering::Greater => break,
6736                        Ordering::Equal => {
6737                            if selection.end.column == snapshot.line_len(row) {
6738                                if selection.is_empty() {
6739                                    selection.start.column -= suffix_len as u32;
6740                                }
6741                                selection.end.column -= suffix_len as u32;
6742                            }
6743                            break;
6744                        }
6745                    }
6746                }
6747            }
6748
6749            drop(snapshot);
6750            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6751
6752            let selections = this.selections.all::<Point>(cx);
6753            let selections_on_single_row = selections.windows(2).all(|selections| {
6754                selections[0].start.row == selections[1].start.row
6755                    && selections[0].end.row == selections[1].end.row
6756                    && selections[0].start.row == selections[0].end.row
6757            });
6758            let selections_selecting = selections
6759                .iter()
6760                .any(|selection| selection.start != selection.end);
6761            let advance_downwards = action.advance_downwards
6762                && selections_on_single_row
6763                && !selections_selecting
6764                && this.mode != EditorMode::SingleLine;
6765
6766            if advance_downwards {
6767                let snapshot = this.buffer.read(cx).snapshot(cx);
6768
6769                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6770                    s.move_cursors_with(|display_snapshot, display_point, _| {
6771                        let mut point = display_point.to_point(display_snapshot);
6772                        point.row += 1;
6773                        point = snapshot.clip_point(point, Bias::Left);
6774                        let display_point = point.to_display_point(display_snapshot);
6775                        let goal = SelectionGoal::HorizontalPosition(
6776                            display_snapshot
6777                                .x_for_display_point(display_point, &text_layout_details)
6778                                .into(),
6779                        );
6780                        (display_point, goal)
6781                    })
6782                });
6783            }
6784        });
6785    }
6786
6787    pub fn select_larger_syntax_node(
6788        &mut self,
6789        _: &SelectLargerSyntaxNode,
6790        cx: &mut ViewContext<Self>,
6791    ) {
6792        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6793        let buffer = self.buffer.read(cx).snapshot(cx);
6794        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
6795
6796        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
6797        let mut selected_larger_node = false;
6798        let new_selections = old_selections
6799            .iter()
6800            .map(|selection| {
6801                let old_range = selection.start..selection.end;
6802                let mut new_range = old_range.clone();
6803                while let Some(containing_range) =
6804                    buffer.range_for_syntax_ancestor(new_range.clone())
6805                {
6806                    new_range = containing_range;
6807                    if !display_map.intersects_fold(new_range.start)
6808                        && !display_map.intersects_fold(new_range.end)
6809                    {
6810                        break;
6811                    }
6812                }
6813
6814                selected_larger_node |= new_range != old_range;
6815                Selection {
6816                    id: selection.id,
6817                    start: new_range.start,
6818                    end: new_range.end,
6819                    goal: SelectionGoal::None,
6820                    reversed: selection.reversed,
6821                }
6822            })
6823            .collect::<Vec<_>>();
6824
6825        if selected_larger_node {
6826            stack.push(old_selections);
6827            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6828                s.select(new_selections);
6829            });
6830        }
6831        self.select_larger_syntax_node_stack = stack;
6832    }
6833
6834    pub fn select_smaller_syntax_node(
6835        &mut self,
6836        _: &SelectSmallerSyntaxNode,
6837        cx: &mut ViewContext<Self>,
6838    ) {
6839        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
6840        if let Some(selections) = stack.pop() {
6841            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6842                s.select(selections.to_vec());
6843            });
6844        }
6845        self.select_larger_syntax_node_stack = stack;
6846    }
6847
6848    pub fn move_to_enclosing_bracket(
6849        &mut self,
6850        _: &MoveToEnclosingBracket,
6851        cx: &mut ViewContext<Self>,
6852    ) {
6853        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6854            s.move_offsets_with(|snapshot, selection| {
6855                let Some(enclosing_bracket_ranges) =
6856                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
6857                else {
6858                    return;
6859                };
6860
6861                let mut best_length = usize::MAX;
6862                let mut best_inside = false;
6863                let mut best_in_bracket_range = false;
6864                let mut best_destination = None;
6865                for (open, close) in enclosing_bracket_ranges {
6866                    let close = close.to_inclusive();
6867                    let length = close.end() - open.start;
6868                    let inside = selection.start >= open.end && selection.end <= *close.start();
6869                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
6870                        || close.contains(&selection.head());
6871
6872                    // If best is next to a bracket and current isn't, skip
6873                    if !in_bracket_range && best_in_bracket_range {
6874                        continue;
6875                    }
6876
6877                    // Prefer smaller lengths unless best is inside and current isn't
6878                    if length > best_length && (best_inside || !inside) {
6879                        continue;
6880                    }
6881
6882                    best_length = length;
6883                    best_inside = inside;
6884                    best_in_bracket_range = in_bracket_range;
6885                    best_destination = Some(
6886                        if close.contains(&selection.start) && close.contains(&selection.end) {
6887                            if inside {
6888                                open.end
6889                            } else {
6890                                open.start
6891                            }
6892                        } else {
6893                            if inside {
6894                                *close.start()
6895                            } else {
6896                                *close.end()
6897                            }
6898                        },
6899                    );
6900                }
6901
6902                if let Some(destination) = best_destination {
6903                    selection.collapse_to(destination, SelectionGoal::None);
6904                }
6905            })
6906        });
6907    }
6908
6909    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
6910        self.end_selection(cx);
6911        self.selection_history.mode = SelectionHistoryMode::Undoing;
6912        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
6913            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
6914            self.select_next_state = entry.select_next_state;
6915            self.select_prev_state = entry.select_prev_state;
6916            self.add_selections_state = entry.add_selections_state;
6917            self.request_autoscroll(Autoscroll::newest(), cx);
6918        }
6919        self.selection_history.mode = SelectionHistoryMode::Normal;
6920    }
6921
6922    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
6923        self.end_selection(cx);
6924        self.selection_history.mode = SelectionHistoryMode::Redoing;
6925        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
6926            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
6927            self.select_next_state = entry.select_next_state;
6928            self.select_prev_state = entry.select_prev_state;
6929            self.add_selections_state = entry.add_selections_state;
6930            self.request_autoscroll(Autoscroll::newest(), cx);
6931        }
6932        self.selection_history.mode = SelectionHistoryMode::Normal;
6933    }
6934
6935    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
6936        self.go_to_diagnostic_impl(Direction::Next, cx)
6937    }
6938
6939    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
6940        self.go_to_diagnostic_impl(Direction::Prev, cx)
6941    }
6942
6943    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
6944        let buffer = self.buffer.read(cx).snapshot(cx);
6945        let selection = self.selections.newest::<usize>(cx);
6946
6947        // If there is an active Diagnostic Popover jump to its diagnostic instead.
6948        if direction == Direction::Next {
6949            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
6950                let (group_id, jump_to) = popover.activation_info();
6951                if self.activate_diagnostics(group_id, cx) {
6952                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6953                        let mut new_selection = s.newest_anchor().clone();
6954                        new_selection.collapse_to(jump_to, SelectionGoal::None);
6955                        s.select_anchors(vec![new_selection.clone()]);
6956                    });
6957                }
6958                return;
6959            }
6960        }
6961
6962        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
6963            active_diagnostics
6964                .primary_range
6965                .to_offset(&buffer)
6966                .to_inclusive()
6967        });
6968        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
6969            if active_primary_range.contains(&selection.head()) {
6970                *active_primary_range.end()
6971            } else {
6972                selection.head()
6973            }
6974        } else {
6975            selection.head()
6976        };
6977
6978        loop {
6979            let mut diagnostics = if direction == Direction::Prev {
6980                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
6981            } else {
6982                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
6983            };
6984            let group = diagnostics.find_map(|entry| {
6985                if entry.diagnostic.is_primary
6986                    && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
6987                    && !entry.range.is_empty()
6988                    && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
6989                    && !entry.range.contains(&search_start)
6990                {
6991                    Some((entry.range, entry.diagnostic.group_id))
6992                } else {
6993                    None
6994                }
6995            });
6996
6997            if let Some((primary_range, group_id)) = group {
6998                if self.activate_diagnostics(group_id, cx) {
6999                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7000                        s.select(vec![Selection {
7001                            id: selection.id,
7002                            start: primary_range.start,
7003                            end: primary_range.start,
7004                            reversed: false,
7005                            goal: SelectionGoal::None,
7006                        }]);
7007                    });
7008                }
7009                break;
7010            } else {
7011                // Cycle around to the start of the buffer, potentially moving back to the start of
7012                // the currently active diagnostic.
7013                active_primary_range.take();
7014                if direction == Direction::Prev {
7015                    if search_start == buffer.len() {
7016                        break;
7017                    } else {
7018                        search_start = buffer.len();
7019                    }
7020                } else if search_start == 0 {
7021                    break;
7022                } else {
7023                    search_start = 0;
7024                }
7025            }
7026        }
7027    }
7028
7029    fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
7030        let snapshot = self
7031            .display_map
7032            .update(cx, |display_map, cx| display_map.snapshot(cx));
7033        let selection = self.selections.newest::<Point>(cx);
7034
7035        if !self.seek_in_direction(
7036            &snapshot,
7037            selection.head(),
7038            false,
7039            snapshot
7040                .buffer_snapshot
7041                .git_diff_hunks_in_range((selection.head().row + 1)..u32::MAX),
7042            cx,
7043        ) {
7044            let wrapped_point = Point::zero();
7045            self.seek_in_direction(
7046                &snapshot,
7047                wrapped_point,
7048                true,
7049                snapshot
7050                    .buffer_snapshot
7051                    .git_diff_hunks_in_range((wrapped_point.row + 1)..u32::MAX),
7052                cx,
7053            );
7054        }
7055    }
7056
7057    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
7058        let snapshot = self
7059            .display_map
7060            .update(cx, |display_map, cx| display_map.snapshot(cx));
7061        let selection = self.selections.newest::<Point>(cx);
7062
7063        if !self.seek_in_direction(
7064            &snapshot,
7065            selection.head(),
7066            false,
7067            snapshot
7068                .buffer_snapshot
7069                .git_diff_hunks_in_range_rev(0..selection.head().row),
7070            cx,
7071        ) {
7072            let wrapped_point = snapshot.buffer_snapshot.max_point();
7073            self.seek_in_direction(
7074                &snapshot,
7075                wrapped_point,
7076                true,
7077                snapshot
7078                    .buffer_snapshot
7079                    .git_diff_hunks_in_range_rev(0..wrapped_point.row),
7080                cx,
7081            );
7082        }
7083    }
7084
7085    fn seek_in_direction(
7086        &mut self,
7087        snapshot: &DisplaySnapshot,
7088        initial_point: Point,
7089        is_wrapped: bool,
7090        hunks: impl Iterator<Item = DiffHunk<u32>>,
7091        cx: &mut ViewContext<Editor>,
7092    ) -> bool {
7093        let display_point = initial_point.to_display_point(snapshot);
7094        let mut hunks = hunks
7095            .map(|hunk| diff_hunk_to_display(hunk, &snapshot))
7096            .filter(|hunk| {
7097                if is_wrapped {
7098                    true
7099                } else {
7100                    !hunk.contains_display_row(display_point.row())
7101                }
7102            })
7103            .dedup();
7104
7105        if let Some(hunk) = hunks.next() {
7106            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7107                let row = hunk.start_display_row();
7108                let point = DisplayPoint::new(row, 0);
7109                s.select_display_ranges([point..point]);
7110            });
7111
7112            true
7113        } else {
7114            false
7115        }
7116    }
7117
7118    pub fn go_to_definition(&mut self, _: &GoToDefinition, cx: &mut ViewContext<Self>) {
7119        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
7120    }
7121
7122    pub fn go_to_type_definition(&mut self, _: &GoToTypeDefinition, cx: &mut ViewContext<Self>) {
7123        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx);
7124    }
7125
7126    pub fn go_to_definition_split(&mut self, _: &GoToDefinitionSplit, cx: &mut ViewContext<Self>) {
7127        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx);
7128    }
7129
7130    pub fn go_to_type_definition_split(
7131        &mut self,
7132        _: &GoToTypeDefinitionSplit,
7133        cx: &mut ViewContext<Self>,
7134    ) {
7135        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx);
7136    }
7137
7138    fn go_to_definition_of_kind(
7139        &mut self,
7140        kind: GotoDefinitionKind,
7141        split: bool,
7142        cx: &mut ViewContext<Self>,
7143    ) {
7144        let Some(workspace) = self.workspace() else {
7145            return;
7146        };
7147        let buffer = self.buffer.read(cx);
7148        let head = self.selections.newest::<usize>(cx).head();
7149        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
7150            text_anchor
7151        } else {
7152            return;
7153        };
7154
7155        let project = workspace.read(cx).project().clone();
7156        let definitions = project.update(cx, |project, cx| match kind {
7157            GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
7158            GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
7159        });
7160
7161        cx.spawn(|editor, mut cx| async move {
7162            let definitions = definitions.await?;
7163            editor.update(&mut cx, |editor, cx| {
7164                editor.navigate_to_definitions(
7165                    definitions
7166                        .into_iter()
7167                        .map(GoToDefinitionLink::Text)
7168                        .collect(),
7169                    split,
7170                    cx,
7171                );
7172            })?;
7173            Ok::<(), anyhow::Error>(())
7174        })
7175        .detach_and_log_err(cx);
7176    }
7177
7178    pub fn navigate_to_definitions(
7179        &mut self,
7180        mut definitions: Vec<GoToDefinitionLink>,
7181        split: bool,
7182        cx: &mut ViewContext<Editor>,
7183    ) {
7184        let Some(workspace) = self.workspace() else {
7185            return;
7186        };
7187        let pane = workspace.read(cx).active_pane().clone();
7188        // If there is one definition, just open it directly
7189        if definitions.len() == 1 {
7190            let definition = definitions.pop().unwrap();
7191            let target_task = match definition {
7192                GoToDefinitionLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
7193                GoToDefinitionLink::InlayHint(lsp_location, server_id) => {
7194                    self.compute_target_location(lsp_location, server_id, cx)
7195                }
7196            };
7197            cx.spawn(|editor, mut cx| async move {
7198                let target = target_task.await.context("target resolution task")?;
7199                if let Some(target) = target {
7200                    editor.update(&mut cx, |editor, cx| {
7201                        let range = target.range.to_offset(target.buffer.read(cx));
7202                        let range = editor.range_for_match(&range);
7203                        if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
7204                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
7205                                s.select_ranges([range]);
7206                            });
7207                        } else {
7208                            cx.window_context().defer(move |cx| {
7209                                let target_editor: View<Self> =
7210                                    workspace.update(cx, |workspace, cx| {
7211                                        if split {
7212                                            workspace.split_project_item(target.buffer.clone(), cx)
7213                                        } else {
7214                                            workspace.open_project_item(target.buffer.clone(), cx)
7215                                        }
7216                                    });
7217                                target_editor.update(cx, |target_editor, cx| {
7218                                    // When selecting a definition in a different buffer, disable the nav history
7219                                    // to avoid creating a history entry at the previous cursor location.
7220                                    pane.update(cx, |pane, _| pane.disable_history());
7221                                    target_editor.change_selections(
7222                                        Some(Autoscroll::fit()),
7223                                        cx,
7224                                        |s| {
7225                                            s.select_ranges([range]);
7226                                        },
7227                                    );
7228                                    pane.update(cx, |pane, _| pane.enable_history());
7229                                });
7230                            });
7231                        }
7232                    })
7233                } else {
7234                    Ok(())
7235                }
7236            })
7237            .detach_and_log_err(cx);
7238        } else if !definitions.is_empty() {
7239            let replica_id = self.replica_id(cx);
7240            cx.spawn(|editor, mut cx| async move {
7241                let (title, location_tasks) = editor
7242                    .update(&mut cx, |editor, cx| {
7243                        let title = definitions
7244                            .iter()
7245                            .find_map(|definition| match definition {
7246                                GoToDefinitionLink::Text(link) => {
7247                                    link.origin.as_ref().map(|origin| {
7248                                        let buffer = origin.buffer.read(cx);
7249                                        format!(
7250                                            "Definitions for {}",
7251                                            buffer
7252                                                .text_for_range(origin.range.clone())
7253                                                .collect::<String>()
7254                                        )
7255                                    })
7256                                }
7257                                GoToDefinitionLink::InlayHint(_, _) => None,
7258                            })
7259                            .unwrap_or("Definitions".to_string());
7260                        let location_tasks = definitions
7261                            .into_iter()
7262                            .map(|definition| match definition {
7263                                GoToDefinitionLink::Text(link) => {
7264                                    Task::Ready(Some(Ok(Some(link.target))))
7265                                }
7266                                GoToDefinitionLink::InlayHint(lsp_location, server_id) => {
7267                                    editor.compute_target_location(lsp_location, server_id, cx)
7268                                }
7269                            })
7270                            .collect::<Vec<_>>();
7271                        (title, location_tasks)
7272                    })
7273                    .context("location tasks preparation")?;
7274
7275                let locations = futures::future::join_all(location_tasks)
7276                    .await
7277                    .into_iter()
7278                    .filter_map(|location| location.transpose())
7279                    .collect::<Result<_>>()
7280                    .context("location tasks")?;
7281                workspace
7282                    .update(&mut cx, |workspace, cx| {
7283                        Self::open_locations_in_multibuffer(
7284                            workspace, locations, replica_id, title, split, cx,
7285                        )
7286                    })
7287                    .ok();
7288
7289                anyhow::Ok(())
7290            })
7291            .detach_and_log_err(cx);
7292        }
7293    }
7294
7295    fn compute_target_location(
7296        &self,
7297        lsp_location: lsp::Location,
7298        server_id: LanguageServerId,
7299        cx: &mut ViewContext<Editor>,
7300    ) -> Task<anyhow::Result<Option<Location>>> {
7301        let Some(project) = self.project.clone() else {
7302            return Task::Ready(Some(Ok(None)));
7303        };
7304
7305        cx.spawn(move |editor, mut cx| async move {
7306            let location_task = editor.update(&mut cx, |editor, cx| {
7307                project.update(cx, |project, cx| {
7308                    let language_server_name =
7309                        editor.buffer.read(cx).as_singleton().and_then(|buffer| {
7310                            project
7311                                .language_server_for_buffer(buffer.read(cx), server_id, cx)
7312                                .map(|(_, lsp_adapter)| {
7313                                    LanguageServerName(Arc::from(lsp_adapter.name()))
7314                                })
7315                        });
7316                    language_server_name.map(|language_server_name| {
7317                        project.open_local_buffer_via_lsp(
7318                            lsp_location.uri.clone(),
7319                            server_id,
7320                            language_server_name,
7321                            cx,
7322                        )
7323                    })
7324                })
7325            })?;
7326            let location = match location_task {
7327                Some(task) => Some({
7328                    let target_buffer_handle = task.await.context("open local buffer")?;
7329                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
7330                        let target_start = target_buffer
7331                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
7332                        let target_end = target_buffer
7333                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
7334                        target_buffer.anchor_after(target_start)
7335                            ..target_buffer.anchor_before(target_end)
7336                    })?;
7337                    Location {
7338                        buffer: target_buffer_handle,
7339                        range,
7340                    }
7341                }),
7342                None => None,
7343            };
7344            Ok(location)
7345        })
7346    }
7347
7348    pub fn find_all_references(
7349        &mut self,
7350        _: &FindAllReferences,
7351        cx: &mut ViewContext<Self>,
7352    ) -> Option<Task<Result<()>>> {
7353        let buffer = self.buffer.read(cx);
7354        let head = self.selections.newest::<usize>(cx).head();
7355        let (buffer, head) = buffer.text_anchor_for_position(head, cx)?;
7356        let replica_id = self.replica_id(cx);
7357
7358        let workspace = self.workspace()?;
7359        let project = workspace.read(cx).project().clone();
7360        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
7361        Some(cx.spawn(|_, mut cx| async move {
7362            let locations = references.await?;
7363            if locations.is_empty() {
7364                return Ok(());
7365            }
7366
7367            workspace.update(&mut cx, |workspace, cx| {
7368                let title = locations
7369                    .first()
7370                    .as_ref()
7371                    .map(|location| {
7372                        let buffer = location.buffer.read(cx);
7373                        format!(
7374                            "References to `{}`",
7375                            buffer
7376                                .text_for_range(location.range.clone())
7377                                .collect::<String>()
7378                        )
7379                    })
7380                    .unwrap();
7381                Self::open_locations_in_multibuffer(
7382                    workspace, locations, replica_id, title, false, cx,
7383                );
7384            })?;
7385
7386            Ok(())
7387        }))
7388    }
7389
7390    /// Opens a multibuffer with the given project locations in it
7391    pub fn open_locations_in_multibuffer(
7392        workspace: &mut Workspace,
7393        mut locations: Vec<Location>,
7394        replica_id: ReplicaId,
7395        title: String,
7396        split: bool,
7397        cx: &mut ViewContext<Workspace>,
7398    ) {
7399        // If there are multiple definitions, open them in a multibuffer
7400        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
7401        let mut locations = locations.into_iter().peekable();
7402        let mut ranges_to_highlight = Vec::new();
7403        let capability = workspace.project().read(cx).capability();
7404
7405        let excerpt_buffer = cx.new_model(|cx| {
7406            let mut multibuffer = MultiBuffer::new(replica_id, capability);
7407            while let Some(location) = locations.next() {
7408                let buffer = location.buffer.read(cx);
7409                let mut ranges_for_buffer = Vec::new();
7410                let range = location.range.to_offset(buffer);
7411                ranges_for_buffer.push(range.clone());
7412
7413                while let Some(next_location) = locations.peek() {
7414                    if next_location.buffer == location.buffer {
7415                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
7416                        locations.next();
7417                    } else {
7418                        break;
7419                    }
7420                }
7421
7422                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
7423                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
7424                    location.buffer.clone(),
7425                    ranges_for_buffer,
7426                    1,
7427                    cx,
7428                ))
7429            }
7430
7431            multibuffer.with_title(title)
7432        });
7433
7434        let editor = cx.new_view(|cx| {
7435            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), cx)
7436        });
7437        editor.update(cx, |editor, cx| {
7438            editor.highlight_background::<Self>(
7439                ranges_to_highlight,
7440                |theme| theme.editor_highlighted_line_background,
7441                cx,
7442            );
7443        });
7444        if split {
7445            workspace.split_item(SplitDirection::Right, Box::new(editor), cx);
7446        } else {
7447            workspace.add_item(Box::new(editor), cx);
7448        }
7449    }
7450
7451    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
7452        use language::ToOffset as _;
7453
7454        let project = self.project.clone()?;
7455        let selection = self.selections.newest_anchor().clone();
7456        let (cursor_buffer, cursor_buffer_position) = self
7457            .buffer
7458            .read(cx)
7459            .text_anchor_for_position(selection.head(), cx)?;
7460        let (tail_buffer, _) = self
7461            .buffer
7462            .read(cx)
7463            .text_anchor_for_position(selection.tail(), cx)?;
7464        if tail_buffer != cursor_buffer {
7465            return None;
7466        }
7467
7468        let snapshot = cursor_buffer.read(cx).snapshot();
7469        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
7470        let prepare_rename = project.update(cx, |project, cx| {
7471            project.prepare_rename(cursor_buffer, cursor_buffer_offset, cx)
7472        });
7473
7474        Some(cx.spawn(|this, mut cx| async move {
7475            let rename_range = if let Some(range) = prepare_rename.await? {
7476                Some(range)
7477            } else {
7478                this.update(&mut cx, |this, cx| {
7479                    let buffer = this.buffer.read(cx).snapshot(cx);
7480                    let mut buffer_highlights = this
7481                        .document_highlights_for_position(selection.head(), &buffer)
7482                        .filter(|highlight| {
7483                            highlight.start.excerpt_id == selection.head().excerpt_id
7484                                && highlight.end.excerpt_id == selection.head().excerpt_id
7485                        });
7486                    buffer_highlights
7487                        .next()
7488                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
7489                })?
7490            };
7491            if let Some(rename_range) = rename_range {
7492                let rename_buffer_range = rename_range.to_offset(&snapshot);
7493                let cursor_offset_in_rename_range =
7494                    cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
7495
7496                this.update(&mut cx, |this, cx| {
7497                    this.take_rename(false, cx);
7498                    let buffer = this.buffer.read(cx).read(cx);
7499                    let cursor_offset = selection.head().to_offset(&buffer);
7500                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
7501                    let rename_end = rename_start + rename_buffer_range.len();
7502                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
7503                    let mut old_highlight_id = None;
7504                    let old_name: Arc<str> = buffer
7505                        .chunks(rename_start..rename_end, true)
7506                        .map(|chunk| {
7507                            if old_highlight_id.is_none() {
7508                                old_highlight_id = chunk.syntax_highlight_id;
7509                            }
7510                            chunk.text
7511                        })
7512                        .collect::<String>()
7513                        .into();
7514
7515                    drop(buffer);
7516
7517                    // Position the selection in the rename editor so that it matches the current selection.
7518                    this.show_local_selections = false;
7519                    let rename_editor = cx.new_view(|cx| {
7520                        let mut editor = Editor::single_line(cx);
7521                        editor.buffer.update(cx, |buffer, cx| {
7522                            buffer.edit([(0..0, old_name.clone())], None, cx)
7523                        });
7524                        editor.select_all(&SelectAll, cx);
7525                        editor
7526                    });
7527
7528                    let ranges = this
7529                        .clear_background_highlights::<DocumentHighlightWrite>(cx)
7530                        .into_iter()
7531                        .flat_map(|(_, ranges)| ranges.into_iter())
7532                        .chain(
7533                            this.clear_background_highlights::<DocumentHighlightRead>(cx)
7534                                .into_iter()
7535                                .flat_map(|(_, ranges)| ranges.into_iter()),
7536                        )
7537                        .collect();
7538
7539                    this.highlight_text::<Rename>(
7540                        ranges,
7541                        HighlightStyle {
7542                            fade_out: Some(0.6),
7543                            ..Default::default()
7544                        },
7545                        cx,
7546                    );
7547                    let rename_focus_handle = rename_editor.focus_handle(cx);
7548                    cx.focus(&rename_focus_handle);
7549                    let block_id = this.insert_blocks(
7550                        [BlockProperties {
7551                            style: BlockStyle::Flex,
7552                            position: range.start.clone(),
7553                            height: 1,
7554                            render: Arc::new({
7555                                let rename_editor = rename_editor.clone();
7556                                move |cx: &mut BlockContext| {
7557                                    let mut text_style = cx.editor_style.text.clone();
7558                                    if let Some(highlight_style) = old_highlight_id
7559                                        .and_then(|h| h.style(&cx.editor_style.syntax))
7560                                    {
7561                                        text_style = text_style.highlight(highlight_style);
7562                                    }
7563                                    div()
7564                                        .pl(cx.anchor_x)
7565                                        .child(EditorElement::new(
7566                                            &rename_editor,
7567                                            EditorStyle {
7568                                                background: cx.theme().system().transparent,
7569                                                local_player: cx.editor_style.local_player,
7570                                                text: text_style,
7571                                                scrollbar_width: cx.editor_style.scrollbar_width,
7572                                                syntax: cx.editor_style.syntax.clone(),
7573                                                status: cx.editor_style.status.clone(),
7574                                                inlays_style: HighlightStyle {
7575                                                    color: Some(cx.theme().status().hint),
7576                                                    font_weight: Some(FontWeight::BOLD),
7577                                                    ..HighlightStyle::default()
7578                                                },
7579                                                suggestions_style: HighlightStyle {
7580                                                    color: Some(cx.theme().status().predictive),
7581                                                    ..HighlightStyle::default()
7582                                                },
7583                                            },
7584                                        ))
7585                                        .into_any_element()
7586                                }
7587                            }),
7588                            disposition: BlockDisposition::Below,
7589                        }],
7590                        Some(Autoscroll::fit()),
7591                        cx,
7592                    )[0];
7593                    this.pending_rename = Some(RenameState {
7594                        range,
7595                        old_name,
7596                        editor: rename_editor,
7597                        block_id,
7598                    });
7599                })?;
7600            }
7601
7602            Ok(())
7603        }))
7604    }
7605
7606    pub fn confirm_rename(
7607        &mut self,
7608        _: &ConfirmRename,
7609        cx: &mut ViewContext<Self>,
7610    ) -> Option<Task<Result<()>>> {
7611        let rename = self.take_rename(false, cx)?;
7612        let workspace = self.workspace()?;
7613        let (start_buffer, start) = self
7614            .buffer
7615            .read(cx)
7616            .text_anchor_for_position(rename.range.start.clone(), cx)?;
7617        let (end_buffer, end) = self
7618            .buffer
7619            .read(cx)
7620            .text_anchor_for_position(rename.range.end.clone(), cx)?;
7621        if start_buffer != end_buffer {
7622            return None;
7623        }
7624
7625        let buffer = start_buffer;
7626        let range = start..end;
7627        let old_name = rename.old_name;
7628        let new_name = rename.editor.read(cx).text(cx);
7629
7630        let rename = workspace
7631            .read(cx)
7632            .project()
7633            .clone()
7634            .update(cx, |project, cx| {
7635                project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
7636            });
7637        let workspace = workspace.downgrade();
7638
7639        Some(cx.spawn(|editor, mut cx| async move {
7640            let project_transaction = rename.await?;
7641            Self::open_project_transaction(
7642                &editor,
7643                workspace,
7644                project_transaction,
7645                format!("Rename: {}{}", old_name, new_name),
7646                cx.clone(),
7647            )
7648            .await?;
7649
7650            editor.update(&mut cx, |editor, cx| {
7651                editor.refresh_document_highlights(cx);
7652            })?;
7653            Ok(())
7654        }))
7655    }
7656
7657    fn take_rename(
7658        &mut self,
7659        moving_cursor: bool,
7660        cx: &mut ViewContext<Self>,
7661    ) -> Option<RenameState> {
7662        let rename = self.pending_rename.take()?;
7663        if rename.editor.focus_handle(cx).is_focused(cx) {
7664            cx.focus(&self.focus_handle);
7665        }
7666
7667        self.remove_blocks(
7668            [rename.block_id].into_iter().collect(),
7669            Some(Autoscroll::fit()),
7670            cx,
7671        );
7672        self.clear_highlights::<Rename>(cx);
7673        self.show_local_selections = true;
7674
7675        if moving_cursor {
7676            let rename_editor = rename.editor.read(cx);
7677            let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
7678
7679            // Update the selection to match the position of the selection inside
7680            // the rename editor.
7681            let snapshot = self.buffer.read(cx).read(cx);
7682            let rename_range = rename.range.to_offset(&snapshot);
7683            let cursor_in_editor = snapshot
7684                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
7685                .min(rename_range.end);
7686            drop(snapshot);
7687
7688            self.change_selections(None, cx, |s| {
7689                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
7690            });
7691        } else {
7692            self.refresh_document_highlights(cx);
7693        }
7694
7695        Some(rename)
7696    }
7697
7698    #[cfg(any(test, feature = "test-support"))]
7699    pub fn pending_rename(&self) -> Option<&RenameState> {
7700        self.pending_rename.as_ref()
7701    }
7702
7703    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
7704        let project = match &self.project {
7705            Some(project) => project.clone(),
7706            None => return None,
7707        };
7708
7709        Some(self.perform_format(project, FormatTrigger::Manual, cx))
7710    }
7711
7712    fn perform_format(
7713        &mut self,
7714        project: Model<Project>,
7715        trigger: FormatTrigger,
7716        cx: &mut ViewContext<Self>,
7717    ) -> Task<Result<()>> {
7718        let buffer = self.buffer().clone();
7719        let buffers = buffer.read(cx).all_buffers();
7720
7721        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
7722        let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
7723
7724        cx.spawn(|_, mut cx| async move {
7725            let transaction = futures::select_biased! {
7726                _ = timeout => {
7727                    log::warn!("timed out waiting for formatting");
7728                    None
7729                }
7730                transaction = format.log_err().fuse() => transaction,
7731            };
7732
7733            buffer
7734                .update(&mut cx, |buffer, cx| {
7735                    if let Some(transaction) = transaction {
7736                        if !buffer.is_singleton() {
7737                            buffer.push_transaction(&transaction.0, cx);
7738                        }
7739                    }
7740
7741                    cx.notify();
7742                })
7743                .ok();
7744
7745            Ok(())
7746        })
7747    }
7748
7749    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
7750        if let Some(project) = self.project.clone() {
7751            self.buffer.update(cx, |multi_buffer, cx| {
7752                project.update(cx, |project, cx| {
7753                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
7754                });
7755            })
7756        }
7757    }
7758
7759    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
7760        cx.show_character_palette();
7761    }
7762
7763    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
7764        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
7765            let buffer = self.buffer.read(cx).snapshot(cx);
7766            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
7767            let is_valid = buffer
7768                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
7769                .any(|entry| {
7770                    entry.diagnostic.is_primary
7771                        && !entry.range.is_empty()
7772                        && entry.range.start == primary_range_start
7773                        && entry.diagnostic.message == active_diagnostics.primary_message
7774                });
7775
7776            if is_valid != active_diagnostics.is_valid {
7777                active_diagnostics.is_valid = is_valid;
7778                let mut new_styles = HashMap::default();
7779                for (block_id, diagnostic) in &active_diagnostics.blocks {
7780                    new_styles.insert(
7781                        *block_id,
7782                        diagnostic_block_renderer(diagnostic.clone(), is_valid),
7783                    );
7784                }
7785                self.display_map
7786                    .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
7787            }
7788        }
7789    }
7790
7791    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
7792        self.dismiss_diagnostics(cx);
7793        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
7794            let buffer = self.buffer.read(cx).snapshot(cx);
7795
7796            let mut primary_range = None;
7797            let mut primary_message = None;
7798            let mut group_end = Point::zero();
7799            let diagnostic_group = buffer
7800                .diagnostic_group::<Point>(group_id)
7801                .map(|entry| {
7802                    if entry.range.end > group_end {
7803                        group_end = entry.range.end;
7804                    }
7805                    if entry.diagnostic.is_primary {
7806                        primary_range = Some(entry.range.clone());
7807                        primary_message = Some(entry.diagnostic.message.clone());
7808                    }
7809                    entry
7810                })
7811                .collect::<Vec<_>>();
7812            let primary_range = primary_range?;
7813            let primary_message = primary_message?;
7814            let primary_range =
7815                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
7816
7817            let blocks = display_map
7818                .insert_blocks(
7819                    diagnostic_group.iter().map(|entry| {
7820                        let diagnostic = entry.diagnostic.clone();
7821                        let message_height = diagnostic.message.lines().count() as u8;
7822                        BlockProperties {
7823                            style: BlockStyle::Fixed,
7824                            position: buffer.anchor_after(entry.range.start),
7825                            height: message_height,
7826                            render: diagnostic_block_renderer(diagnostic, true),
7827                            disposition: BlockDisposition::Below,
7828                        }
7829                    }),
7830                    cx,
7831                )
7832                .into_iter()
7833                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
7834                .collect();
7835
7836            Some(ActiveDiagnosticGroup {
7837                primary_range,
7838                primary_message,
7839                blocks,
7840                is_valid: true,
7841            })
7842        });
7843        self.active_diagnostics.is_some()
7844    }
7845
7846    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
7847        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
7848            self.display_map.update(cx, |display_map, cx| {
7849                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
7850            });
7851            cx.notify();
7852        }
7853    }
7854
7855    pub fn set_selections_from_remote(
7856        &mut self,
7857        selections: Vec<Selection<Anchor>>,
7858        pending_selection: Option<Selection<Anchor>>,
7859        cx: &mut ViewContext<Self>,
7860    ) {
7861        let old_cursor_position = self.selections.newest_anchor().head();
7862        self.selections.change_with(cx, |s| {
7863            s.select_anchors(selections);
7864            if let Some(pending_selection) = pending_selection {
7865                s.set_pending(pending_selection, SelectMode::Character);
7866            } else {
7867                s.clear_pending();
7868            }
7869        });
7870        self.selections_did_change(false, &old_cursor_position, cx);
7871    }
7872
7873    fn push_to_selection_history(&mut self) {
7874        self.selection_history.push(SelectionHistoryEntry {
7875            selections: self.selections.disjoint_anchors(),
7876            select_next_state: self.select_next_state.clone(),
7877            select_prev_state: self.select_prev_state.clone(),
7878            add_selections_state: self.add_selections_state.clone(),
7879        });
7880    }
7881
7882    pub fn transact(
7883        &mut self,
7884        cx: &mut ViewContext<Self>,
7885        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
7886    ) -> Option<TransactionId> {
7887        self.start_transaction_at(Instant::now(), cx);
7888        update(self, cx);
7889        self.end_transaction_at(Instant::now(), cx)
7890    }
7891
7892    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
7893        self.end_selection(cx);
7894        if let Some(tx_id) = self
7895            .buffer
7896            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
7897        {
7898            self.selection_history
7899                .insert_transaction(tx_id, self.selections.disjoint_anchors());
7900        }
7901    }
7902
7903    fn end_transaction_at(
7904        &mut self,
7905        now: Instant,
7906        cx: &mut ViewContext<Self>,
7907    ) -> Option<TransactionId> {
7908        if let Some(tx_id) = self
7909            .buffer
7910            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
7911        {
7912            if let Some((_, end_selections)) = self.selection_history.transaction_mut(tx_id) {
7913                *end_selections = Some(self.selections.disjoint_anchors());
7914            } else {
7915                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
7916            }
7917
7918            cx.emit(EditorEvent::Edited);
7919            Some(tx_id)
7920        } else {
7921            None
7922        }
7923    }
7924
7925    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
7926        let mut fold_ranges = Vec::new();
7927
7928        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7929
7930        let selections = self.selections.all_adjusted(cx);
7931        for selection in selections {
7932            let range = selection.range().sorted();
7933            let buffer_start_row = range.start.row;
7934
7935            for row in (0..=range.end.row).rev() {
7936                let fold_range = display_map.foldable_range(row);
7937
7938                if let Some(fold_range) = fold_range {
7939                    if fold_range.end.row >= buffer_start_row {
7940                        fold_ranges.push(fold_range);
7941                        if row <= range.start.row {
7942                            break;
7943                        }
7944                    }
7945                }
7946            }
7947        }
7948
7949        self.fold_ranges(fold_ranges, true, cx);
7950    }
7951
7952    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
7953        let buffer_row = fold_at.buffer_row;
7954        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7955
7956        if let Some(fold_range) = display_map.foldable_range(buffer_row) {
7957            let autoscroll = self
7958                .selections
7959                .all::<Point>(cx)
7960                .iter()
7961                .any(|selection| fold_range.overlaps(&selection.range()));
7962
7963            self.fold_ranges(std::iter::once(fold_range), autoscroll, cx);
7964        }
7965    }
7966
7967    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
7968        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7969        let buffer = &display_map.buffer_snapshot;
7970        let selections = self.selections.all::<Point>(cx);
7971        let ranges = selections
7972            .iter()
7973            .map(|s| {
7974                let range = s.display_range(&display_map).sorted();
7975                let mut start = range.start.to_point(&display_map);
7976                let mut end = range.end.to_point(&display_map);
7977                start.column = 0;
7978                end.column = buffer.line_len(end.row);
7979                start..end
7980            })
7981            .collect::<Vec<_>>();
7982
7983        self.unfold_ranges(ranges, true, true, cx);
7984    }
7985
7986    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
7987        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7988
7989        let intersection_range = Point::new(unfold_at.buffer_row, 0)
7990            ..Point::new(
7991                unfold_at.buffer_row,
7992                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
7993            );
7994
7995        let autoscroll = self
7996            .selections
7997            .all::<Point>(cx)
7998            .iter()
7999            .any(|selection| selection.range().overlaps(&intersection_range));
8000
8001        self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
8002    }
8003
8004    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
8005        let selections = self.selections.all::<Point>(cx);
8006        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8007        let line_mode = self.selections.line_mode;
8008        let ranges = selections.into_iter().map(|s| {
8009            if line_mode {
8010                let start = Point::new(s.start.row, 0);
8011                let end = Point::new(s.end.row, display_map.buffer_snapshot.line_len(s.end.row));
8012                start..end
8013            } else {
8014                s.start..s.end
8015            }
8016        });
8017        self.fold_ranges(ranges, true, cx);
8018    }
8019
8020    pub fn fold_ranges<T: ToOffset + Clone>(
8021        &mut self,
8022        ranges: impl IntoIterator<Item = Range<T>>,
8023        auto_scroll: bool,
8024        cx: &mut ViewContext<Self>,
8025    ) {
8026        let mut ranges = ranges.into_iter().peekable();
8027        if ranges.peek().is_some() {
8028            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
8029
8030            if auto_scroll {
8031                self.request_autoscroll(Autoscroll::fit(), cx);
8032            }
8033
8034            cx.notify();
8035        }
8036    }
8037
8038    pub fn unfold_ranges<T: ToOffset + Clone>(
8039        &mut self,
8040        ranges: impl IntoIterator<Item = Range<T>>,
8041        inclusive: bool,
8042        auto_scroll: bool,
8043        cx: &mut ViewContext<Self>,
8044    ) {
8045        let mut ranges = ranges.into_iter().peekable();
8046        if ranges.peek().is_some() {
8047            self.display_map
8048                .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
8049            if auto_scroll {
8050                self.request_autoscroll(Autoscroll::fit(), cx);
8051            }
8052
8053            cx.notify();
8054        }
8055    }
8056
8057    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
8058        if hovered != self.gutter_hovered {
8059            self.gutter_hovered = hovered;
8060            cx.notify();
8061        }
8062    }
8063
8064    pub fn insert_blocks(
8065        &mut self,
8066        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
8067        autoscroll: Option<Autoscroll>,
8068        cx: &mut ViewContext<Self>,
8069    ) -> Vec<BlockId> {
8070        let blocks = self
8071            .display_map
8072            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
8073        if let Some(autoscroll) = autoscroll {
8074            self.request_autoscroll(autoscroll, cx);
8075        }
8076        blocks
8077    }
8078
8079    pub fn replace_blocks(
8080        &mut self,
8081        blocks: HashMap<BlockId, RenderBlock>,
8082        autoscroll: Option<Autoscroll>,
8083        cx: &mut ViewContext<Self>,
8084    ) {
8085        self.display_map
8086            .update(cx, |display_map, _| display_map.replace_blocks(blocks));
8087        if let Some(autoscroll) = autoscroll {
8088            self.request_autoscroll(autoscroll, cx);
8089        }
8090    }
8091
8092    pub fn remove_blocks(
8093        &mut self,
8094        block_ids: HashSet<BlockId>,
8095        autoscroll: Option<Autoscroll>,
8096        cx: &mut ViewContext<Self>,
8097    ) {
8098        self.display_map.update(cx, |display_map, cx| {
8099            display_map.remove_blocks(block_ids, cx)
8100        });
8101        if let Some(autoscroll) = autoscroll {
8102            self.request_autoscroll(autoscroll, cx);
8103        }
8104    }
8105
8106    pub fn longest_row(&self, cx: &mut AppContext) -> u32 {
8107        self.display_map
8108            .update(cx, |map, cx| map.snapshot(cx))
8109            .longest_row()
8110    }
8111
8112    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
8113        self.display_map
8114            .update(cx, |map, cx| map.snapshot(cx))
8115            .max_point()
8116    }
8117
8118    pub fn text(&self, cx: &AppContext) -> String {
8119        self.buffer.read(cx).read(cx).text()
8120    }
8121
8122    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
8123        let text = self.text(cx);
8124        let text = text.trim();
8125
8126        if text.is_empty() {
8127            return None;
8128        }
8129
8130        Some(text.to_string())
8131    }
8132
8133    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
8134        self.transact(cx, |this, cx| {
8135            this.buffer
8136                .read(cx)
8137                .as_singleton()
8138                .expect("you can only call set_text on editors for singleton buffers")
8139                .update(cx, |buffer, cx| buffer.set_text(text, cx));
8140        });
8141    }
8142
8143    pub fn display_text(&self, cx: &mut AppContext) -> String {
8144        self.display_map
8145            .update(cx, |map, cx| map.snapshot(cx))
8146            .text()
8147    }
8148
8149    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
8150        let mut wrap_guides = smallvec::smallvec![];
8151
8152        if self.show_wrap_guides == Some(false) {
8153            return wrap_guides;
8154        }
8155
8156        let settings = self.buffer.read(cx).settings_at(0, cx);
8157        if settings.show_wrap_guides {
8158            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
8159                wrap_guides.push((soft_wrap as usize, true));
8160            }
8161            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
8162        }
8163
8164        wrap_guides
8165    }
8166
8167    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
8168        let settings = self.buffer.read(cx).settings_at(0, cx);
8169        let mode = self
8170            .soft_wrap_mode_override
8171            .unwrap_or_else(|| settings.soft_wrap);
8172        match mode {
8173            language_settings::SoftWrap::None => SoftWrap::None,
8174            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
8175            language_settings::SoftWrap::PreferredLineLength => {
8176                SoftWrap::Column(settings.preferred_line_length)
8177            }
8178        }
8179    }
8180
8181    pub fn set_soft_wrap_mode(
8182        &mut self,
8183        mode: language_settings::SoftWrap,
8184        cx: &mut ViewContext<Self>,
8185    ) {
8186        self.soft_wrap_mode_override = Some(mode);
8187        cx.notify();
8188    }
8189
8190    pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
8191        let rem_size = cx.rem_size();
8192        self.display_map.update(cx, |map, cx| {
8193            map.set_font(
8194                style.text.font(),
8195                style.text.font_size.to_pixels(rem_size),
8196                cx,
8197            )
8198        });
8199        self.style = Some(style);
8200    }
8201
8202    #[cfg(any(test, feature = "test-support"))]
8203    pub fn style(&self) -> Option<&EditorStyle> {
8204        self.style.as_ref()
8205    }
8206
8207    // Called by the element. This method is not designed to be called outside of the editor
8208    // element's layout code because it does not notify when rewrapping is computed synchronously.
8209    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
8210        self.display_map
8211            .update(cx, |map, cx| map.set_wrap_width(width, cx))
8212    }
8213
8214    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
8215        if self.soft_wrap_mode_override.is_some() {
8216            self.soft_wrap_mode_override.take();
8217        } else {
8218            let soft_wrap = match self.soft_wrap_mode(cx) {
8219                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
8220                SoftWrap::EditorWidth | SoftWrap::Column(_) => language_settings::SoftWrap::None,
8221            };
8222            self.soft_wrap_mode_override = Some(soft_wrap);
8223        }
8224        cx.notify();
8225    }
8226
8227    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
8228        self.show_gutter = show_gutter;
8229        cx.notify();
8230    }
8231
8232    pub fn set_show_wrap_guides(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
8233        self.show_wrap_guides = Some(show_gutter);
8234        cx.notify();
8235    }
8236
8237    pub fn reveal_in_finder(&mut self, _: &RevealInFinder, cx: &mut ViewContext<Self>) {
8238        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
8239            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
8240                cx.reveal_path(&file.abs_path(cx));
8241            }
8242        }
8243    }
8244
8245    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
8246        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
8247            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
8248                if let Some(path) = file.abs_path(cx).to_str() {
8249                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
8250                }
8251            }
8252        }
8253    }
8254
8255    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
8256        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
8257            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
8258                if let Some(path) = file.path().to_str() {
8259                    cx.write_to_clipboard(ClipboardItem::new(path.to_string()));
8260                }
8261            }
8262        }
8263    }
8264
8265    pub fn highlight_rows(&mut self, rows: Option<Range<u32>>) {
8266        self.highlighted_rows = rows;
8267    }
8268
8269    pub fn highlighted_rows(&self) -> Option<Range<u32>> {
8270        self.highlighted_rows.clone()
8271    }
8272
8273    pub fn highlight_background<T: 'static>(
8274        &mut self,
8275        ranges: Vec<Range<Anchor>>,
8276        color_fetcher: fn(&ThemeColors) -> Hsla,
8277        cx: &mut ViewContext<Self>,
8278    ) {
8279        self.background_highlights
8280            .insert(TypeId::of::<T>(), (color_fetcher, ranges));
8281        cx.notify();
8282    }
8283
8284    pub(crate) fn highlight_inlay_background<T: 'static>(
8285        &mut self,
8286        ranges: Vec<InlayHighlight>,
8287        color_fetcher: fn(&ThemeColors) -> Hsla,
8288        cx: &mut ViewContext<Self>,
8289    ) {
8290        // TODO: no actual highlights happen for inlays currently, find a way to do that
8291        self.inlay_background_highlights
8292            .insert(Some(TypeId::of::<T>()), (color_fetcher, ranges));
8293        cx.notify();
8294    }
8295
8296    pub fn clear_background_highlights<T: 'static>(
8297        &mut self,
8298        cx: &mut ViewContext<Self>,
8299    ) -> Option<BackgroundHighlight> {
8300        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>());
8301        let inlay_highlights = self
8302            .inlay_background_highlights
8303            .remove(&Some(TypeId::of::<T>()));
8304        if text_highlights.is_some() || inlay_highlights.is_some() {
8305            cx.notify();
8306        }
8307        text_highlights
8308    }
8309
8310    #[cfg(feature = "test-support")]
8311    pub fn all_text_background_highlights(
8312        &mut self,
8313        cx: &mut ViewContext<Self>,
8314    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
8315        let snapshot = self.snapshot(cx);
8316        let buffer = &snapshot.buffer_snapshot;
8317        let start = buffer.anchor_before(0);
8318        let end = buffer.anchor_after(buffer.len());
8319        let theme = cx.theme().colors();
8320        self.background_highlights_in_range(start..end, &snapshot, theme)
8321    }
8322
8323    fn document_highlights_for_position<'a>(
8324        &'a self,
8325        position: Anchor,
8326        buffer: &'a MultiBufferSnapshot,
8327    ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
8328        let read_highlights = self
8329            .background_highlights
8330            .get(&TypeId::of::<DocumentHighlightRead>())
8331            .map(|h| &h.1);
8332        let write_highlights = self
8333            .background_highlights
8334            .get(&TypeId::of::<DocumentHighlightWrite>())
8335            .map(|h| &h.1);
8336        let left_position = position.bias_left(buffer);
8337        let right_position = position.bias_right(buffer);
8338        read_highlights
8339            .into_iter()
8340            .chain(write_highlights)
8341            .flat_map(move |ranges| {
8342                let start_ix = match ranges.binary_search_by(|probe| {
8343                    let cmp = probe.end.cmp(&left_position, buffer);
8344                    if cmp.is_ge() {
8345                        Ordering::Greater
8346                    } else {
8347                        Ordering::Less
8348                    }
8349                }) {
8350                    Ok(i) | Err(i) => i,
8351                };
8352
8353                let right_position = right_position.clone();
8354                ranges[start_ix..]
8355                    .iter()
8356                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
8357            })
8358    }
8359
8360    pub fn has_background_highlights<T: 'static>(&self) -> bool {
8361        self.background_highlights
8362            .get(&TypeId::of::<T>())
8363            .map_or(false, |(_, highlights)| !highlights.is_empty())
8364    }
8365
8366    pub fn background_highlights_in_range(
8367        &self,
8368        search_range: Range<Anchor>,
8369        display_snapshot: &DisplaySnapshot,
8370        theme: &ThemeColors,
8371    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
8372        let mut results = Vec::new();
8373        for (color_fetcher, ranges) in self.background_highlights.values() {
8374            let color = color_fetcher(theme);
8375            let start_ix = match ranges.binary_search_by(|probe| {
8376                let cmp = probe
8377                    .end
8378                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
8379                if cmp.is_gt() {
8380                    Ordering::Greater
8381                } else {
8382                    Ordering::Less
8383                }
8384            }) {
8385                Ok(i) | Err(i) => i,
8386            };
8387            for range in &ranges[start_ix..] {
8388                if range
8389                    .start
8390                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
8391                    .is_ge()
8392                {
8393                    break;
8394                }
8395
8396                let start = range.start.to_display_point(&display_snapshot);
8397                let end = range.end.to_display_point(&display_snapshot);
8398                results.push((start..end, color))
8399            }
8400        }
8401        results
8402    }
8403
8404    pub fn background_highlight_row_ranges<T: 'static>(
8405        &self,
8406        search_range: Range<Anchor>,
8407        display_snapshot: &DisplaySnapshot,
8408        count: usize,
8409    ) -> Vec<RangeInclusive<DisplayPoint>> {
8410        let mut results = Vec::new();
8411        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
8412            return vec![];
8413        };
8414
8415        let start_ix = match ranges.binary_search_by(|probe| {
8416            let cmp = probe
8417                .end
8418                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
8419            if cmp.is_gt() {
8420                Ordering::Greater
8421            } else {
8422                Ordering::Less
8423            }
8424        }) {
8425            Ok(i) | Err(i) => i,
8426        };
8427        let mut push_region = |start: Option<Point>, end: Option<Point>| {
8428            if let (Some(start_display), Some(end_display)) = (start, end) {
8429                results.push(
8430                    start_display.to_display_point(display_snapshot)
8431                        ..=end_display.to_display_point(display_snapshot),
8432                );
8433            }
8434        };
8435        let mut start_row: Option<Point> = None;
8436        let mut end_row: Option<Point> = None;
8437        if ranges.len() > count {
8438            return Vec::new();
8439        }
8440        for range in &ranges[start_ix..] {
8441            if range
8442                .start
8443                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
8444                .is_ge()
8445            {
8446                break;
8447            }
8448            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
8449            if let Some(current_row) = &end_row {
8450                if end.row == current_row.row {
8451                    continue;
8452                }
8453            }
8454            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
8455            if start_row.is_none() {
8456                assert_eq!(end_row, None);
8457                start_row = Some(start);
8458                end_row = Some(end);
8459                continue;
8460            }
8461            if let Some(current_end) = end_row.as_mut() {
8462                if start.row > current_end.row + 1 {
8463                    push_region(start_row, end_row);
8464                    start_row = Some(start);
8465                    end_row = Some(end);
8466                } else {
8467                    // Merge two hunks.
8468                    *current_end = end;
8469                }
8470            } else {
8471                unreachable!();
8472            }
8473        }
8474        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
8475        push_region(start_row, end_row);
8476        results
8477    }
8478
8479    pub fn highlight_text<T: 'static>(
8480        &mut self,
8481        ranges: Vec<Range<Anchor>>,
8482        style: HighlightStyle,
8483        cx: &mut ViewContext<Self>,
8484    ) {
8485        self.display_map.update(cx, |map, _| {
8486            map.highlight_text(TypeId::of::<T>(), ranges, style)
8487        });
8488        cx.notify();
8489    }
8490
8491    pub(crate) fn highlight_inlays<T: 'static>(
8492        &mut self,
8493        highlights: Vec<InlayHighlight>,
8494        style: HighlightStyle,
8495        cx: &mut ViewContext<Self>,
8496    ) {
8497        self.display_map.update(cx, |map, _| {
8498            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
8499        });
8500        cx.notify();
8501    }
8502
8503    pub fn text_highlights<'a, T: 'static>(
8504        &'a self,
8505        cx: &'a AppContext,
8506    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
8507        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
8508    }
8509
8510    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
8511        let cleared = self
8512            .display_map
8513            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
8514        if cleared {
8515            cx.notify();
8516        }
8517    }
8518
8519    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
8520        (self.read_only(cx) || self.blink_manager.read(cx).visible())
8521            && self.focus_handle.is_focused(cx)
8522    }
8523
8524    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
8525        cx.notify();
8526    }
8527
8528    fn on_buffer_event(
8529        &mut self,
8530        multibuffer: Model<MultiBuffer>,
8531        event: &multi_buffer::Event,
8532        cx: &mut ViewContext<Self>,
8533    ) {
8534        match event {
8535            multi_buffer::Event::Edited {
8536                singleton_buffer_edited,
8537            } => {
8538                self.refresh_active_diagnostics(cx);
8539                self.refresh_code_actions(cx);
8540                if self.has_active_copilot_suggestion(cx) {
8541                    self.update_visible_copilot_suggestion(cx);
8542                }
8543                cx.emit(EditorEvent::BufferEdited);
8544                cx.emit(SearchEvent::MatchesInvalidated);
8545
8546                if *singleton_buffer_edited {
8547                    if let Some(project) = &self.project {
8548                        let project = project.read(cx);
8549                        let languages_affected = multibuffer
8550                            .read(cx)
8551                            .all_buffers()
8552                            .into_iter()
8553                            .filter_map(|buffer| {
8554                                let buffer = buffer.read(cx);
8555                                let language = buffer.language()?;
8556                                if project.is_local()
8557                                    && project.language_servers_for_buffer(buffer, cx).count() == 0
8558                                {
8559                                    None
8560                                } else {
8561                                    Some(language)
8562                                }
8563                            })
8564                            .cloned()
8565                            .collect::<HashSet<_>>();
8566                        if !languages_affected.is_empty() {
8567                            self.refresh_inlay_hints(
8568                                InlayHintRefreshReason::BufferEdited(languages_affected),
8569                                cx,
8570                            );
8571                        }
8572                    }
8573                }
8574
8575                let Some(project) = &self.project else { return };
8576                let telemetry = project.read(cx).client().telemetry().clone();
8577                telemetry.log_edit_event("editor");
8578            }
8579            multi_buffer::Event::ExcerptsAdded {
8580                buffer,
8581                predecessor,
8582                excerpts,
8583            } => {
8584                cx.emit(EditorEvent::ExcerptsAdded {
8585                    buffer: buffer.clone(),
8586                    predecessor: *predecessor,
8587                    excerpts: excerpts.clone(),
8588                });
8589                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
8590            }
8591            multi_buffer::Event::ExcerptsRemoved { ids } => {
8592                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
8593                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
8594            }
8595            multi_buffer::Event::Reparsed => cx.emit(EditorEvent::Reparsed),
8596            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
8597            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
8598            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
8599                cx.emit(EditorEvent::TitleChanged)
8600            }
8601            multi_buffer::Event::DiffBaseChanged => cx.emit(EditorEvent::DiffBaseChanged),
8602            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
8603            multi_buffer::Event::DiagnosticsUpdated => {
8604                self.refresh_active_diagnostics(cx);
8605            }
8606            _ => {}
8607        };
8608    }
8609
8610    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
8611        cx.notify();
8612    }
8613
8614    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
8615        self.refresh_copilot_suggestions(true, cx);
8616        self.refresh_inlay_hints(
8617            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
8618                self.selections.newest_anchor().head(),
8619                &self.buffer.read(cx).snapshot(cx),
8620                cx,
8621            )),
8622            cx,
8623        );
8624        cx.notify();
8625    }
8626
8627    pub fn set_searchable(&mut self, searchable: bool) {
8628        self.searchable = searchable;
8629    }
8630
8631    pub fn searchable(&self) -> bool {
8632        self.searchable
8633    }
8634
8635    fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
8636        let buffer = self.buffer.read(cx);
8637        if buffer.is_singleton() {
8638            cx.propagate();
8639            return;
8640        }
8641
8642        let Some(workspace) = self.workspace() else {
8643            cx.propagate();
8644            return;
8645        };
8646
8647        let mut new_selections_by_buffer = HashMap::default();
8648        for selection in self.selections.all::<usize>(cx) {
8649            for (buffer, mut range, _) in
8650                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
8651            {
8652                if selection.reversed {
8653                    mem::swap(&mut range.start, &mut range.end);
8654                }
8655                new_selections_by_buffer
8656                    .entry(buffer)
8657                    .or_insert(Vec::new())
8658                    .push(range)
8659            }
8660        }
8661
8662        self.push_to_nav_history(self.selections.newest_anchor().head(), None, cx);
8663
8664        // We defer the pane interaction because we ourselves are a workspace item
8665        // and activating a new item causes the pane to call a method on us reentrantly,
8666        // which panics if we're on the stack.
8667        cx.window_context().defer(move |cx| {
8668            workspace.update(cx, |workspace, cx| {
8669                let pane = workspace.active_pane().clone();
8670                pane.update(cx, |pane, _| pane.disable_history());
8671
8672                for (buffer, ranges) in new_selections_by_buffer.into_iter() {
8673                    let editor = workspace.open_project_item::<Self>(buffer, cx);
8674                    editor.update(cx, |editor, cx| {
8675                        editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
8676                            s.select_ranges(ranges);
8677                        });
8678                    });
8679                }
8680
8681                pane.update(cx, |pane, _| pane.enable_history());
8682            })
8683        });
8684    }
8685
8686    fn jump(
8687        &mut self,
8688        path: ProjectPath,
8689        position: Point,
8690        anchor: language::Anchor,
8691        cx: &mut ViewContext<Self>,
8692    ) {
8693        let workspace = self.workspace();
8694        cx.spawn(|_, mut cx| async move {
8695            let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
8696            let editor = workspace.update(&mut cx, |workspace, cx| {
8697                workspace.open_path(path, None, true, cx)
8698            })?;
8699            let editor = editor
8700                .await?
8701                .downcast::<Editor>()
8702                .ok_or_else(|| anyhow!("opened item was not an editor"))?
8703                .downgrade();
8704            editor.update(&mut cx, |editor, cx| {
8705                let buffer = editor
8706                    .buffer()
8707                    .read(cx)
8708                    .as_singleton()
8709                    .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
8710                let buffer = buffer.read(cx);
8711                let cursor = if buffer.can_resolve(&anchor) {
8712                    language::ToPoint::to_point(&anchor, buffer)
8713                } else {
8714                    buffer.clip_point(position, Bias::Left)
8715                };
8716
8717                let nav_history = editor.nav_history.take();
8718                editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
8719                    s.select_ranges([cursor..cursor]);
8720                });
8721                editor.nav_history = nav_history;
8722
8723                anyhow::Ok(())
8724            })??;
8725
8726            anyhow::Ok(())
8727        })
8728        .detach_and_log_err(cx);
8729    }
8730
8731    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
8732        let snapshot = self.buffer.read(cx).read(cx);
8733        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
8734        Some(
8735            ranges
8736                .iter()
8737                .map(move |range| {
8738                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
8739                })
8740                .collect(),
8741        )
8742    }
8743
8744    fn selection_replacement_ranges(
8745        &self,
8746        range: Range<OffsetUtf16>,
8747        cx: &AppContext,
8748    ) -> Vec<Range<OffsetUtf16>> {
8749        let selections = self.selections.all::<OffsetUtf16>(cx);
8750        let newest_selection = selections
8751            .iter()
8752            .max_by_key(|selection| selection.id)
8753            .unwrap();
8754        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
8755        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
8756        let snapshot = self.buffer.read(cx).read(cx);
8757        selections
8758            .into_iter()
8759            .map(|mut selection| {
8760                selection.start.0 =
8761                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
8762                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
8763                snapshot.clip_offset_utf16(selection.start, Bias::Left)
8764                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
8765            })
8766            .collect()
8767    }
8768
8769    fn report_copilot_event(
8770        &self,
8771        suggestion_id: Option<String>,
8772        suggestion_accepted: bool,
8773        cx: &AppContext,
8774    ) {
8775        let Some(project) = &self.project else { return };
8776
8777        // If None, we are either getting suggestions in a new, unsaved file, or in a file without an extension
8778        let file_extension = self
8779            .buffer
8780            .read(cx)
8781            .as_singleton()
8782            .and_then(|b| b.read(cx).file())
8783            .and_then(|file| Path::new(file.file_name(cx)).extension())
8784            .and_then(|e| e.to_str())
8785            .map(|a| a.to_string());
8786
8787        let telemetry = project.read(cx).client().telemetry().clone();
8788
8789        telemetry.report_copilot_event(suggestion_id, suggestion_accepted, file_extension)
8790    }
8791
8792    #[cfg(any(test, feature = "test-support"))]
8793    fn report_editor_event(
8794        &self,
8795        _operation: &'static str,
8796        _file_extension: Option<String>,
8797        _cx: &AppContext,
8798    ) {
8799    }
8800
8801    #[cfg(not(any(test, feature = "test-support")))]
8802    fn report_editor_event(
8803        &self,
8804        operation: &'static str,
8805        file_extension: Option<String>,
8806        cx: &AppContext,
8807    ) {
8808        let Some(project) = &self.project else { return };
8809
8810        // If None, we are in a file without an extension
8811        let file = self
8812            .buffer
8813            .read(cx)
8814            .as_singleton()
8815            .and_then(|b| b.read(cx).file());
8816        let file_extension = file_extension.or(file
8817            .as_ref()
8818            .and_then(|file| Path::new(file.file_name(cx)).extension())
8819            .and_then(|e| e.to_str())
8820            .map(|a| a.to_string()));
8821
8822        let vim_mode = cx
8823            .global::<SettingsStore>()
8824            .raw_user_settings()
8825            .get("vim_mode")
8826            == Some(&serde_json::Value::Bool(true));
8827        let copilot_enabled = all_language_settings(file, cx).copilot_enabled(None, None);
8828        let copilot_enabled_for_language = self
8829            .buffer
8830            .read(cx)
8831            .settings_at(0, cx)
8832            .show_copilot_suggestions;
8833
8834        let telemetry = project.read(cx).client().telemetry().clone();
8835        telemetry.report_editor_event(
8836            file_extension,
8837            vim_mode,
8838            operation,
8839            copilot_enabled,
8840            copilot_enabled_for_language,
8841        )
8842    }
8843
8844    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
8845    /// with each line being an array of {text, highlight} objects.
8846    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
8847        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
8848            return;
8849        };
8850
8851        #[derive(Serialize)]
8852        struct Chunk<'a> {
8853            text: String,
8854            highlight: Option<&'a str>,
8855        }
8856
8857        let snapshot = buffer.read(cx).snapshot();
8858        let range = self
8859            .selected_text_range(cx)
8860            .and_then(|selected_range| {
8861                if selected_range.is_empty() {
8862                    None
8863                } else {
8864                    Some(selected_range)
8865                }
8866            })
8867            .unwrap_or_else(|| 0..snapshot.len());
8868
8869        let chunks = snapshot.chunks(range, true);
8870        let mut lines = Vec::new();
8871        let mut line: VecDeque<Chunk> = VecDeque::new();
8872
8873        let Some(style) = self.style.as_ref() else {
8874            return;
8875        };
8876
8877        for chunk in chunks {
8878            let highlight = chunk
8879                .syntax_highlight_id
8880                .and_then(|id| id.name(&style.syntax));
8881            let mut chunk_lines = chunk.text.split("\n").peekable();
8882            while let Some(text) = chunk_lines.next() {
8883                let mut merged_with_last_token = false;
8884                if let Some(last_token) = line.back_mut() {
8885                    if last_token.highlight == highlight {
8886                        last_token.text.push_str(text);
8887                        merged_with_last_token = true;
8888                    }
8889                }
8890
8891                if !merged_with_last_token {
8892                    line.push_back(Chunk {
8893                        text: text.into(),
8894                        highlight,
8895                    });
8896                }
8897
8898                if chunk_lines.peek().is_some() {
8899                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
8900                        line.pop_front();
8901                    }
8902                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
8903                        line.pop_back();
8904                    }
8905
8906                    lines.push(mem::take(&mut line));
8907                }
8908            }
8909        }
8910
8911        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
8912            return;
8913        };
8914        cx.write_to_clipboard(ClipboardItem::new(lines));
8915    }
8916
8917    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
8918        &self.inlay_hint_cache
8919    }
8920
8921    pub fn replay_insert_event(
8922        &mut self,
8923        text: &str,
8924        relative_utf16_range: Option<Range<isize>>,
8925        cx: &mut ViewContext<Self>,
8926    ) {
8927        if !self.input_enabled {
8928            cx.emit(EditorEvent::InputIgnored { text: text.into() });
8929            return;
8930        }
8931        if let Some(relative_utf16_range) = relative_utf16_range {
8932            let selections = self.selections.all::<OffsetUtf16>(cx);
8933            self.change_selections(None, cx, |s| {
8934                let new_ranges = selections.into_iter().map(|range| {
8935                    let start = OffsetUtf16(
8936                        range
8937                            .head()
8938                            .0
8939                            .saturating_add_signed(relative_utf16_range.start),
8940                    );
8941                    let end = OffsetUtf16(
8942                        range
8943                            .head()
8944                            .0
8945                            .saturating_add_signed(relative_utf16_range.end),
8946                    );
8947                    start..end
8948                });
8949                s.select_ranges(new_ranges);
8950            });
8951        }
8952
8953        self.handle_input(text, cx);
8954    }
8955
8956    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
8957        let Some(project) = self.project.as_ref() else {
8958            return false;
8959        };
8960        let project = project.read(cx);
8961
8962        let mut supports = false;
8963        self.buffer().read(cx).for_each_buffer(|buffer| {
8964            if !supports {
8965                supports = project
8966                    .language_servers_for_buffer(buffer.read(cx), cx)
8967                    .any(
8968                        |(_, server)| match server.capabilities().inlay_hint_provider {
8969                            Some(lsp::OneOf::Left(enabled)) => enabled,
8970                            Some(lsp::OneOf::Right(_)) => true,
8971                            None => false,
8972                        },
8973                    )
8974            }
8975        });
8976        supports
8977    }
8978
8979    pub fn focus(&self, cx: &mut WindowContext) {
8980        cx.focus(&self.focus_handle)
8981    }
8982
8983    pub fn is_focused(&self, cx: &WindowContext) -> bool {
8984        self.focus_handle.is_focused(cx)
8985    }
8986
8987    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
8988        cx.emit(EditorEvent::Focused);
8989
8990        if let Some(rename) = self.pending_rename.as_ref() {
8991            let rename_editor_focus_handle = rename.editor.read(cx).focus_handle.clone();
8992            cx.focus(&rename_editor_focus_handle);
8993        } else {
8994            self.blink_manager.update(cx, BlinkManager::enable);
8995            self.buffer.update(cx, |buffer, cx| {
8996                buffer.finalize_last_transaction(cx);
8997                if self.leader_peer_id.is_none() {
8998                    buffer.set_active_selections(
8999                        &self.selections.disjoint_anchors(),
9000                        self.selections.line_mode,
9001                        self.cursor_shape,
9002                        cx,
9003                    );
9004                }
9005            });
9006        }
9007    }
9008
9009    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
9010        self.blink_manager.update(cx, BlinkManager::disable);
9011        self.buffer
9012            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
9013        self.hide_context_menu(cx);
9014        hide_hover(self, cx);
9015        cx.emit(EditorEvent::Blurred);
9016        cx.notify();
9017    }
9018
9019    pub fn register_action<A: Action>(
9020        &mut self,
9021        listener: impl Fn(&A, &mut WindowContext) + 'static,
9022    ) -> &mut Self {
9023        let listener = Arc::new(listener);
9024
9025        self.editor_actions.push(Box::new(move |cx| {
9026            let _view = cx.view().clone();
9027            let cx = cx.window_context();
9028            let listener = listener.clone();
9029            cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
9030                let action = action.downcast_ref().unwrap();
9031                if phase == DispatchPhase::Bubble {
9032                    listener(action, cx)
9033                }
9034            })
9035        }));
9036        self
9037    }
9038}
9039
9040pub trait CollaborationHub {
9041    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
9042    fn user_participant_indices<'a>(
9043        &self,
9044        cx: &'a AppContext,
9045    ) -> &'a HashMap<u64, ParticipantIndex>;
9046}
9047
9048impl CollaborationHub for Model<Project> {
9049    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
9050        self.read(cx).collaborators()
9051    }
9052
9053    fn user_participant_indices<'a>(
9054        &self,
9055        cx: &'a AppContext,
9056    ) -> &'a HashMap<u64, ParticipantIndex> {
9057        self.read(cx).user_store().read(cx).participant_indices()
9058    }
9059}
9060
9061fn inlay_hint_settings(
9062    location: Anchor,
9063    snapshot: &MultiBufferSnapshot,
9064    cx: &mut ViewContext<'_, Editor>,
9065) -> InlayHintSettings {
9066    let file = snapshot.file_at(location);
9067    let language = snapshot.language_at(location);
9068    let settings = all_language_settings(file, cx);
9069    settings
9070        .language(language.map(|l| l.name()).as_deref())
9071        .inlay_hints
9072}
9073
9074fn consume_contiguous_rows(
9075    contiguous_row_selections: &mut Vec<Selection<Point>>,
9076    selection: &Selection<Point>,
9077    display_map: &DisplaySnapshot,
9078    selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
9079) -> (u32, u32) {
9080    contiguous_row_selections.push(selection.clone());
9081    let start_row = selection.start.row;
9082    let mut end_row = ending_row(selection, display_map);
9083
9084    while let Some(next_selection) = selections.peek() {
9085        if next_selection.start.row <= end_row {
9086            end_row = ending_row(next_selection, display_map);
9087            contiguous_row_selections.push(selections.next().unwrap().clone());
9088        } else {
9089            break;
9090        }
9091    }
9092    (start_row, end_row)
9093}
9094
9095fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> u32 {
9096    if next_selection.end.column > 0 || next_selection.is_empty() {
9097        display_map.next_line_boundary(next_selection.end).0.row + 1
9098    } else {
9099        next_selection.end.row
9100    }
9101}
9102
9103impl EditorSnapshot {
9104    pub fn remote_selections_in_range<'a>(
9105        &'a self,
9106        range: &'a Range<Anchor>,
9107        collaboration_hub: &dyn CollaborationHub,
9108        cx: &'a AppContext,
9109    ) -> impl 'a + Iterator<Item = RemoteSelection> {
9110        let participant_indices = collaboration_hub.user_participant_indices(cx);
9111        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
9112        let collaborators_by_replica_id = collaborators_by_peer_id
9113            .iter()
9114            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
9115            .collect::<HashMap<_, _>>();
9116        self.buffer_snapshot
9117            .remote_selections_in_range(range)
9118            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
9119                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
9120                let participant_index = participant_indices.get(&collaborator.user_id).copied();
9121                Some(RemoteSelection {
9122                    replica_id,
9123                    selection,
9124                    cursor_shape,
9125                    line_mode,
9126                    participant_index,
9127                    peer_id: collaborator.peer_id,
9128                })
9129            })
9130    }
9131
9132    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
9133        self.display_snapshot.buffer_snapshot.language_at(position)
9134    }
9135
9136    pub fn is_focused(&self) -> bool {
9137        self.is_focused
9138    }
9139
9140    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
9141        self.placeholder_text.as_ref()
9142    }
9143
9144    pub fn scroll_position(&self) -> gpui::Point<f32> {
9145        self.scroll_anchor.scroll_position(&self.display_snapshot)
9146    }
9147}
9148
9149impl Deref for EditorSnapshot {
9150    type Target = DisplaySnapshot;
9151
9152    fn deref(&self) -> &Self::Target {
9153        &self.display_snapshot
9154    }
9155}
9156
9157#[derive(Clone, Debug, PartialEq, Eq)]
9158pub enum EditorEvent {
9159    InputIgnored {
9160        text: Arc<str>,
9161    },
9162    InputHandled {
9163        utf16_range_to_replace: Option<Range<isize>>,
9164        text: Arc<str>,
9165    },
9166    ExcerptsAdded {
9167        buffer: Model<Buffer>,
9168        predecessor: ExcerptId,
9169        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
9170    },
9171    ExcerptsRemoved {
9172        ids: Vec<ExcerptId>,
9173    },
9174    BufferEdited,
9175    Edited,
9176    Reparsed,
9177    Focused,
9178    Blurred,
9179    DirtyChanged,
9180    Saved,
9181    TitleChanged,
9182    DiffBaseChanged,
9183    SelectionsChanged {
9184        local: bool,
9185    },
9186    ScrollPositionChanged {
9187        local: bool,
9188        autoscroll: bool,
9189    },
9190    Closed,
9191}
9192
9193impl EventEmitter<EditorEvent> for Editor {}
9194
9195impl FocusableView for Editor {
9196    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
9197        self.focus_handle.clone()
9198    }
9199}
9200
9201impl Render for Editor {
9202    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
9203        let settings = ThemeSettings::get_global(cx);
9204        let text_style = match self.mode {
9205            EditorMode::SingleLine | EditorMode::AutoHeight { .. } => TextStyle {
9206                color: cx.theme().colors().editor_foreground,
9207                font_family: settings.ui_font.family.clone(),
9208                font_features: settings.ui_font.features,
9209                font_size: rems(0.875).into(),
9210                font_weight: FontWeight::NORMAL,
9211                font_style: FontStyle::Normal,
9212                line_height: relative(settings.buffer_line_height.value()),
9213                background_color: None,
9214                underline: None,
9215                white_space: WhiteSpace::Normal,
9216            },
9217
9218            EditorMode::Full => TextStyle {
9219                color: cx.theme().colors().editor_foreground,
9220                font_family: settings.buffer_font.family.clone(),
9221                font_features: settings.buffer_font.features,
9222                font_size: settings.buffer_font_size(cx).into(),
9223                font_weight: FontWeight::NORMAL,
9224                font_style: FontStyle::Normal,
9225                line_height: relative(settings.buffer_line_height.value()),
9226                background_color: None,
9227                underline: None,
9228                white_space: WhiteSpace::Normal,
9229            },
9230        };
9231
9232        let background = match self.mode {
9233            EditorMode::SingleLine => cx.theme().system().transparent,
9234            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
9235            EditorMode::Full => cx.theme().colors().editor_background,
9236        };
9237
9238        EditorElement::new(
9239            cx.view(),
9240            EditorStyle {
9241                background,
9242                local_player: cx.theme().players().local(),
9243                text: text_style,
9244                scrollbar_width: px(12.),
9245                syntax: cx.theme().syntax().clone(),
9246                status: cx.theme().status().clone(),
9247                inlays_style: HighlightStyle {
9248                    color: Some(cx.theme().status().hint),
9249                    font_weight: Some(FontWeight::BOLD),
9250                    ..HighlightStyle::default()
9251                },
9252                suggestions_style: HighlightStyle {
9253                    color: Some(cx.theme().status().predictive),
9254                    ..HighlightStyle::default()
9255                },
9256            },
9257        )
9258    }
9259}
9260
9261impl InputHandler for Editor {
9262    fn text_for_range(
9263        &mut self,
9264        range_utf16: Range<usize>,
9265        cx: &mut ViewContext<Self>,
9266    ) -> Option<String> {
9267        Some(
9268            self.buffer
9269                .read(cx)
9270                .read(cx)
9271                .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
9272                .collect(),
9273        )
9274    }
9275
9276    fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
9277        // Prevent the IME menu from appearing when holding down an alphabetic key
9278        // while input is disabled.
9279        if !self.input_enabled {
9280            return None;
9281        }
9282
9283        let range = self.selections.newest::<OffsetUtf16>(cx).range();
9284        Some(range.start.0..range.end.0)
9285    }
9286
9287    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
9288        let snapshot = self.buffer.read(cx).read(cx);
9289        let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
9290        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
9291    }
9292
9293    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
9294        self.clear_highlights::<InputComposition>(cx);
9295        self.ime_transaction.take();
9296    }
9297
9298    fn replace_text_in_range(
9299        &mut self,
9300        range_utf16: Option<Range<usize>>,
9301        text: &str,
9302        cx: &mut ViewContext<Self>,
9303    ) {
9304        if !self.input_enabled {
9305            cx.emit(EditorEvent::InputIgnored { text: text.into() });
9306            return;
9307        }
9308
9309        self.transact(cx, |this, cx| {
9310            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
9311                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
9312                Some(this.selection_replacement_ranges(range_utf16, cx))
9313            } else {
9314                this.marked_text_ranges(cx)
9315            };
9316
9317            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
9318                let newest_selection_id = this.selections.newest_anchor().id;
9319                this.selections
9320                    .all::<OffsetUtf16>(cx)
9321                    .iter()
9322                    .zip(ranges_to_replace.iter())
9323                    .find_map(|(selection, range)| {
9324                        if selection.id == newest_selection_id {
9325                            Some(
9326                                (range.start.0 as isize - selection.head().0 as isize)
9327                                    ..(range.end.0 as isize - selection.head().0 as isize),
9328                            )
9329                        } else {
9330                            None
9331                        }
9332                    })
9333            });
9334
9335            cx.emit(EditorEvent::InputHandled {
9336                utf16_range_to_replace: range_to_replace,
9337                text: text.into(),
9338            });
9339
9340            if let Some(new_selected_ranges) = new_selected_ranges {
9341                this.change_selections(None, cx, |selections| {
9342                    selections.select_ranges(new_selected_ranges)
9343                });
9344            }
9345
9346            this.handle_input(text, cx);
9347        });
9348
9349        if let Some(transaction) = self.ime_transaction {
9350            self.buffer.update(cx, |buffer, cx| {
9351                buffer.group_until_transaction(transaction, cx);
9352            });
9353        }
9354
9355        self.unmark_text(cx);
9356    }
9357
9358    fn replace_and_mark_text_in_range(
9359        &mut self,
9360        range_utf16: Option<Range<usize>>,
9361        text: &str,
9362        new_selected_range_utf16: Option<Range<usize>>,
9363        cx: &mut ViewContext<Self>,
9364    ) {
9365        if !self.input_enabled {
9366            cx.emit(EditorEvent::InputIgnored { text: text.into() });
9367            return;
9368        }
9369
9370        let transaction = self.transact(cx, |this, cx| {
9371            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
9372                let snapshot = this.buffer.read(cx).read(cx);
9373                if let Some(relative_range_utf16) = range_utf16.as_ref() {
9374                    for marked_range in &mut marked_ranges {
9375                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
9376                        marked_range.start.0 += relative_range_utf16.start;
9377                        marked_range.start =
9378                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
9379                        marked_range.end =
9380                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
9381                    }
9382                }
9383                Some(marked_ranges)
9384            } else if let Some(range_utf16) = range_utf16 {
9385                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
9386                Some(this.selection_replacement_ranges(range_utf16, cx))
9387            } else {
9388                None
9389            };
9390
9391            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
9392                let newest_selection_id = this.selections.newest_anchor().id;
9393                this.selections
9394                    .all::<OffsetUtf16>(cx)
9395                    .iter()
9396                    .zip(ranges_to_replace.iter())
9397                    .find_map(|(selection, range)| {
9398                        if selection.id == newest_selection_id {
9399                            Some(
9400                                (range.start.0 as isize - selection.head().0 as isize)
9401                                    ..(range.end.0 as isize - selection.head().0 as isize),
9402                            )
9403                        } else {
9404                            None
9405                        }
9406                    })
9407            });
9408
9409            cx.emit(EditorEvent::InputHandled {
9410                utf16_range_to_replace: range_to_replace,
9411                text: text.into(),
9412            });
9413
9414            if let Some(ranges) = ranges_to_replace {
9415                this.change_selections(None, cx, |s| s.select_ranges(ranges));
9416            }
9417
9418            let marked_ranges = {
9419                let snapshot = this.buffer.read(cx).read(cx);
9420                this.selections
9421                    .disjoint_anchors()
9422                    .iter()
9423                    .map(|selection| {
9424                        selection.start.bias_left(&*snapshot)..selection.end.bias_right(&*snapshot)
9425                    })
9426                    .collect::<Vec<_>>()
9427            };
9428
9429            if text.is_empty() {
9430                this.unmark_text(cx);
9431            } else {
9432                this.highlight_text::<InputComposition>(
9433                    marked_ranges.clone(),
9434                    HighlightStyle::default(), // todo!() this.style(cx).composition_mark,
9435                    cx,
9436                );
9437            }
9438
9439            this.handle_input(text, cx);
9440
9441            if let Some(new_selected_range) = new_selected_range_utf16 {
9442                let snapshot = this.buffer.read(cx).read(cx);
9443                let new_selected_ranges = marked_ranges
9444                    .into_iter()
9445                    .map(|marked_range| {
9446                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
9447                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
9448                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
9449                        snapshot.clip_offset_utf16(new_start, Bias::Left)
9450                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
9451                    })
9452                    .collect::<Vec<_>>();
9453
9454                drop(snapshot);
9455                this.change_selections(None, cx, |selections| {
9456                    selections.select_ranges(new_selected_ranges)
9457                });
9458            }
9459        });
9460
9461        self.ime_transaction = self.ime_transaction.or(transaction);
9462        if let Some(transaction) = self.ime_transaction {
9463            self.buffer.update(cx, |buffer, cx| {
9464                buffer.group_until_transaction(transaction, cx);
9465            });
9466        }
9467
9468        if self.text_highlights::<InputComposition>(cx).is_none() {
9469            self.ime_transaction.take();
9470        }
9471    }
9472
9473    fn bounds_for_range(
9474        &mut self,
9475        range_utf16: Range<usize>,
9476        element_bounds: gpui::Bounds<Pixels>,
9477        cx: &mut ViewContext<Self>,
9478    ) -> Option<gpui::Bounds<Pixels>> {
9479        let text_layout_details = self.text_layout_details(cx);
9480        let style = &text_layout_details.editor_style;
9481        let font_id = cx.text_system().resolve_font(&style.text.font());
9482        let font_size = style.text.font_size.to_pixels(cx.rem_size());
9483        let line_height = style.text.line_height_in_pixels(cx.rem_size());
9484        let em_width = cx
9485            .text_system()
9486            .typographic_bounds(font_id, font_size, 'm')
9487            .unwrap()
9488            .size
9489            .width;
9490
9491        let snapshot = self.snapshot(cx);
9492        let scroll_position = snapshot.scroll_position();
9493        let scroll_left = scroll_position.x * em_width;
9494
9495        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
9496        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
9497            + self.gutter_width;
9498        let y = line_height * (start.row() as f32 - scroll_position.y);
9499
9500        Some(Bounds {
9501            origin: element_bounds.origin + point(x, y),
9502            size: size(em_width, line_height),
9503        })
9504    }
9505}
9506
9507trait SelectionExt {
9508    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize>;
9509    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point>;
9510    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
9511    fn spanned_rows(&self, include_end_if_at_line_start: bool, map: &DisplaySnapshot)
9512        -> Range<u32>;
9513}
9514
9515impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
9516    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
9517        let start = self.start.to_point(buffer);
9518        let end = self.end.to_point(buffer);
9519        if self.reversed {
9520            end..start
9521        } else {
9522            start..end
9523        }
9524    }
9525
9526    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
9527        let start = self.start.to_offset(buffer);
9528        let end = self.end.to_offset(buffer);
9529        if self.reversed {
9530            end..start
9531        } else {
9532            start..end
9533        }
9534    }
9535
9536    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
9537        let start = self
9538            .start
9539            .to_point(&map.buffer_snapshot)
9540            .to_display_point(map);
9541        let end = self
9542            .end
9543            .to_point(&map.buffer_snapshot)
9544            .to_display_point(map);
9545        if self.reversed {
9546            end..start
9547        } else {
9548            start..end
9549        }
9550    }
9551
9552    fn spanned_rows(
9553        &self,
9554        include_end_if_at_line_start: bool,
9555        map: &DisplaySnapshot,
9556    ) -> Range<u32> {
9557        let start = self.start.to_point(&map.buffer_snapshot);
9558        let mut end = self.end.to_point(&map.buffer_snapshot);
9559        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
9560            end.row -= 1;
9561        }
9562
9563        let buffer_start = map.prev_line_boundary(start).0;
9564        let buffer_end = map.next_line_boundary(end).0;
9565        buffer_start.row..buffer_end.row + 1
9566    }
9567}
9568
9569impl<T: InvalidationRegion> InvalidationStack<T> {
9570    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
9571    where
9572        S: Clone + ToOffset,
9573    {
9574        while let Some(region) = self.last() {
9575            let all_selections_inside_invalidation_ranges =
9576                if selections.len() == region.ranges().len() {
9577                    selections
9578                        .iter()
9579                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
9580                        .all(|(selection, invalidation_range)| {
9581                            let head = selection.head().to_offset(buffer);
9582                            invalidation_range.start <= head && invalidation_range.end >= head
9583                        })
9584                } else {
9585                    false
9586                };
9587
9588            if all_selections_inside_invalidation_ranges {
9589                break;
9590            } else {
9591                self.pop();
9592            }
9593        }
9594    }
9595}
9596
9597impl<T> Default for InvalidationStack<T> {
9598    fn default() -> Self {
9599        Self(Default::default())
9600    }
9601}
9602
9603impl<T> Deref for InvalidationStack<T> {
9604    type Target = Vec<T>;
9605
9606    fn deref(&self) -> &Self::Target {
9607        &self.0
9608    }
9609}
9610
9611impl<T> DerefMut for InvalidationStack<T> {
9612    fn deref_mut(&mut self) -> &mut Self::Target {
9613        &mut self.0
9614    }
9615}
9616
9617impl InvalidationRegion for SnippetState {
9618    fn ranges(&self) -> &[Range<Anchor>] {
9619        &self.ranges[self.active_index]
9620    }
9621}
9622
9623pub fn diagnostic_block_renderer(diagnostic: Diagnostic, _is_valid: bool) -> RenderBlock {
9624    let (text_without_backticks, code_ranges) = highlight_diagnostic_message(&diagnostic);
9625
9626    Arc::new(move |cx: &mut BlockContext| {
9627        let color = Some(cx.theme().colors().text_accent);
9628        let group_id: SharedString = cx.block_id.to_string().into();
9629        // TODO: Nate: We should tint the background of the block with the severity color
9630        // We need to extend the theme before we can do this
9631        h_flex()
9632            .id(cx.block_id)
9633            .group(group_id.clone())
9634            .relative()
9635            .pl(cx.anchor_x)
9636            .size_full()
9637            .gap_2()
9638            .child(
9639                StyledText::new(text_without_backticks.clone()).with_highlights(
9640                    &cx.text_style(),
9641                    code_ranges.iter().map(|range| {
9642                        (
9643                            range.clone(),
9644                            HighlightStyle {
9645                                color,
9646                                ..Default::default()
9647                            },
9648                        )
9649                    }),
9650                ),
9651            )
9652            .child(
9653                IconButton::new(("copy-block", cx.block_id), IconName::Copy)
9654                    .icon_color(Color::Muted)
9655                    .size(ButtonSize::Compact)
9656                    .style(ButtonStyle::Transparent)
9657                    .visible_on_hover(group_id)
9658                    .on_click(cx.listener({
9659                        let message = diagnostic.message.clone();
9660                        move |_, _, cx| cx.write_to_clipboard(ClipboardItem::new(message.clone()))
9661                    }))
9662                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
9663            )
9664            .into_any_element()
9665    })
9666}
9667
9668pub fn highlight_diagnostic_message(diagnostic: &Diagnostic) -> (SharedString, Vec<Range<usize>>) {
9669    let mut text_without_backticks = String::new();
9670    let mut code_ranges = Vec::new();
9671
9672    if let Some(source) = &diagnostic.source {
9673        text_without_backticks.push_str(&source);
9674        code_ranges.push(0..source.len());
9675        text_without_backticks.push_str(": ");
9676    }
9677
9678    let mut prev_offset = 0;
9679    let mut in_code_block = false;
9680    for (ix, _) in diagnostic
9681        .message
9682        .match_indices('`')
9683        .chain([(diagnostic.message.len(), "")])
9684    {
9685        let prev_len = text_without_backticks.len();
9686        text_without_backticks.push_str(&diagnostic.message[prev_offset..ix]);
9687        prev_offset = ix + 1;
9688        if in_code_block {
9689            code_ranges.push(prev_len..text_without_backticks.len());
9690            in_code_block = false;
9691        } else {
9692            in_code_block = true;
9693        }
9694    }
9695
9696    (text_without_backticks.into(), code_ranges)
9697}
9698
9699fn diagnostic_style(severity: DiagnosticSeverity, valid: bool, colors: &StatusColors) -> Hsla {
9700    match (severity, valid) {
9701        (DiagnosticSeverity::ERROR, true) => colors.error,
9702        (DiagnosticSeverity::ERROR, false) => colors.error,
9703        (DiagnosticSeverity::WARNING, true) => colors.warning,
9704        (DiagnosticSeverity::WARNING, false) => colors.warning,
9705        (DiagnosticSeverity::INFORMATION, true) => colors.info,
9706        (DiagnosticSeverity::INFORMATION, false) => colors.info,
9707        (DiagnosticSeverity::HINT, true) => colors.info,
9708        (DiagnosticSeverity::HINT, false) => colors.info,
9709        _ => colors.ignored,
9710    }
9711}
9712
9713pub fn styled_runs_for_code_label<'a>(
9714    label: &'a CodeLabel,
9715    syntax_theme: &'a theme::SyntaxTheme,
9716) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
9717    let fade_out = HighlightStyle {
9718        fade_out: Some(0.35),
9719        ..Default::default()
9720    };
9721
9722    let mut prev_end = label.filter_range.end;
9723    label
9724        .runs
9725        .iter()
9726        .enumerate()
9727        .flat_map(move |(ix, (range, highlight_id))| {
9728            let style = if let Some(style) = highlight_id.style(syntax_theme) {
9729                style
9730            } else {
9731                return Default::default();
9732            };
9733            let mut muted_style = style;
9734            muted_style.highlight(fade_out);
9735
9736            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
9737            if range.start >= label.filter_range.end {
9738                if range.start > prev_end {
9739                    runs.push((prev_end..range.start, fade_out));
9740                }
9741                runs.push((range.clone(), muted_style));
9742            } else if range.end <= label.filter_range.end {
9743                runs.push((range.clone(), style));
9744            } else {
9745                runs.push((range.start..label.filter_range.end, style));
9746                runs.push((label.filter_range.end..range.end, muted_style));
9747            }
9748            prev_end = cmp::max(prev_end, range.end);
9749
9750            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
9751                runs.push((prev_end..label.text.len(), fade_out));
9752            }
9753
9754            runs
9755        })
9756}
9757
9758pub(crate) fn split_words<'a>(text: &'a str) -> impl std::iter::Iterator<Item = &'a str> + 'a {
9759    let mut index = 0;
9760    let mut codepoints = text.char_indices().peekable();
9761
9762    std::iter::from_fn(move || {
9763        let start_index = index;
9764        while let Some((new_index, codepoint)) = codepoints.next() {
9765            index = new_index + codepoint.len_utf8();
9766            let current_upper = codepoint.is_uppercase();
9767            let next_upper = codepoints
9768                .peek()
9769                .map(|(_, c)| c.is_uppercase())
9770                .unwrap_or(false);
9771
9772            if !current_upper && next_upper {
9773                return Some(&text[start_index..index]);
9774            }
9775        }
9776
9777        index = text.len();
9778        if start_index < text.len() {
9779            return Some(&text[start_index..]);
9780        }
9781        None
9782    })
9783    .flat_map(|word| word.split_inclusive('_'))
9784    .flat_map(|word| word.split_inclusive('-'))
9785}
9786
9787trait RangeToAnchorExt {
9788    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
9789}
9790
9791impl<T: ToOffset> RangeToAnchorExt for Range<T> {
9792    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
9793        snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
9794    }
9795}