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