editor.rs

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