editor.rs

   1pub mod display_map;
   2mod element;
   3pub mod items;
   4pub mod movement;
   5
   6#[cfg(test)]
   7mod test;
   8
   9use aho_corasick::AhoCorasick;
  10use clock::ReplicaId;
  11pub use display_map::DisplayPoint;
  12use display_map::*;
  13pub use element::*;
  14use gpui::{
  15    action,
  16    elements::Text,
  17    geometry::vector::{vec2f, Vector2F},
  18    keymap::Binding,
  19    text_layout, AppContext, ClipboardItem, Element, ElementBox, Entity, ModelHandle,
  20    MutableAppContext, RenderContext, View, ViewContext, WeakViewHandle,
  21};
  22use items::BufferItemHandle;
  23use language::{
  24    multi_buffer::{
  25        Anchor, AnchorRangeExt, MultiBuffer, MultiBufferSnapshot, SelectionSet, ToOffset, ToPoint,
  26    },
  27    BracketPair, Buffer, Diagnostic, DiagnosticSeverity, Language, Point, Selection, SelectionGoal,
  28    SelectionSetId,
  29};
  30use serde::{Deserialize, Serialize};
  31use smallvec::SmallVec;
  32use smol::Timer;
  33use std::{
  34    cell::RefCell,
  35    cmp,
  36    collections::HashMap,
  37    iter, mem,
  38    ops::{Deref, Range, RangeInclusive, Sub},
  39    rc::Rc,
  40    sync::Arc,
  41    time::Duration,
  42};
  43use sum_tree::Bias;
  44use text::rope::TextDimension;
  45use theme::{DiagnosticStyle, EditorStyle};
  46use util::post_inc;
  47use workspace::{EntryOpener, Workspace};
  48
  49const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  50const MAX_LINE_LEN: usize = 1024;
  51
  52action!(Cancel);
  53action!(Backspace);
  54action!(Delete);
  55action!(Input, String);
  56action!(Newline);
  57action!(Tab);
  58action!(Outdent);
  59action!(DeleteLine);
  60action!(DeleteToPreviousWordBoundary);
  61action!(DeleteToNextWordBoundary);
  62action!(DeleteToBeginningOfLine);
  63action!(DeleteToEndOfLine);
  64action!(CutToEndOfLine);
  65action!(DuplicateLine);
  66action!(MoveLineUp);
  67action!(MoveLineDown);
  68action!(Cut);
  69action!(Copy);
  70action!(Paste);
  71action!(Undo);
  72action!(Redo);
  73action!(MoveUp);
  74action!(MoveDown);
  75action!(MoveLeft);
  76action!(MoveRight);
  77action!(MoveToPreviousWordBoundary);
  78action!(MoveToNextWordBoundary);
  79action!(MoveToBeginningOfLine);
  80action!(MoveToEndOfLine);
  81action!(MoveToBeginning);
  82action!(MoveToEnd);
  83action!(SelectUp);
  84action!(SelectDown);
  85action!(SelectLeft);
  86action!(SelectRight);
  87action!(SelectToPreviousWordBoundary);
  88action!(SelectToNextWordBoundary);
  89action!(SelectToBeginningOfLine, bool);
  90action!(SelectToEndOfLine);
  91action!(SelectToBeginning);
  92action!(SelectToEnd);
  93action!(SelectAll);
  94action!(SelectLine);
  95action!(SplitSelectionIntoLines);
  96action!(AddSelectionAbove);
  97action!(AddSelectionBelow);
  98action!(SelectNext, bool);
  99action!(ToggleComments);
 100action!(SelectLargerSyntaxNode);
 101action!(SelectSmallerSyntaxNode);
 102action!(MoveToEnclosingBracket);
 103action!(ShowNextDiagnostic);
 104action!(PageUp);
 105action!(PageDown);
 106action!(Fold);
 107action!(Unfold);
 108action!(FoldSelectedRanges);
 109action!(Scroll, Vector2F);
 110action!(Select, SelectPhase);
 111
 112pub fn init(cx: &mut MutableAppContext, entry_openers: &mut Vec<Box<dyn EntryOpener>>) {
 113    entry_openers.push(Box::new(items::BufferOpener));
 114    cx.add_bindings(vec![
 115        Binding::new("escape", Cancel, Some("Editor")),
 116        Binding::new("backspace", Backspace, Some("Editor")),
 117        Binding::new("ctrl-h", Backspace, Some("Editor")),
 118        Binding::new("delete", Delete, Some("Editor")),
 119        Binding::new("ctrl-d", Delete, Some("Editor")),
 120        Binding::new("enter", Newline, Some("Editor && mode == full")),
 121        Binding::new(
 122            "alt-enter",
 123            Input("\n".into()),
 124            Some("Editor && mode == auto_height"),
 125        ),
 126        Binding::new("tab", Tab, Some("Editor")),
 127        Binding::new("shift-tab", Outdent, Some("Editor")),
 128        Binding::new("ctrl-shift-K", DeleteLine, Some("Editor")),
 129        Binding::new(
 130            "alt-backspace",
 131            DeleteToPreviousWordBoundary,
 132            Some("Editor"),
 133        ),
 134        Binding::new("alt-h", DeleteToPreviousWordBoundary, Some("Editor")),
 135        Binding::new("alt-delete", DeleteToNextWordBoundary, Some("Editor")),
 136        Binding::new("alt-d", DeleteToNextWordBoundary, Some("Editor")),
 137        Binding::new("cmd-backspace", DeleteToBeginningOfLine, Some("Editor")),
 138        Binding::new("cmd-delete", DeleteToEndOfLine, Some("Editor")),
 139        Binding::new("ctrl-k", CutToEndOfLine, Some("Editor")),
 140        Binding::new("cmd-shift-D", DuplicateLine, Some("Editor")),
 141        Binding::new("ctrl-cmd-up", MoveLineUp, Some("Editor")),
 142        Binding::new("ctrl-cmd-down", MoveLineDown, Some("Editor")),
 143        Binding::new("cmd-x", Cut, Some("Editor")),
 144        Binding::new("cmd-c", Copy, Some("Editor")),
 145        Binding::new("cmd-v", Paste, Some("Editor")),
 146        Binding::new("cmd-z", Undo, Some("Editor")),
 147        Binding::new("cmd-shift-Z", Redo, Some("Editor")),
 148        Binding::new("up", MoveUp, Some("Editor")),
 149        Binding::new("down", MoveDown, Some("Editor")),
 150        Binding::new("left", MoveLeft, Some("Editor")),
 151        Binding::new("right", MoveRight, Some("Editor")),
 152        Binding::new("ctrl-p", MoveUp, Some("Editor")),
 153        Binding::new("ctrl-n", MoveDown, Some("Editor")),
 154        Binding::new("ctrl-b", MoveLeft, Some("Editor")),
 155        Binding::new("ctrl-f", MoveRight, Some("Editor")),
 156        Binding::new("alt-left", MoveToPreviousWordBoundary, Some("Editor")),
 157        Binding::new("alt-b", MoveToPreviousWordBoundary, Some("Editor")),
 158        Binding::new("alt-right", MoveToNextWordBoundary, Some("Editor")),
 159        Binding::new("alt-f", MoveToNextWordBoundary, Some("Editor")),
 160        Binding::new("cmd-left", MoveToBeginningOfLine, Some("Editor")),
 161        Binding::new("ctrl-a", MoveToBeginningOfLine, Some("Editor")),
 162        Binding::new("cmd-right", MoveToEndOfLine, Some("Editor")),
 163        Binding::new("ctrl-e", MoveToEndOfLine, Some("Editor")),
 164        Binding::new("cmd-up", MoveToBeginning, Some("Editor")),
 165        Binding::new("cmd-down", MoveToEnd, Some("Editor")),
 166        Binding::new("shift-up", SelectUp, Some("Editor")),
 167        Binding::new("ctrl-shift-P", SelectUp, Some("Editor")),
 168        Binding::new("shift-down", SelectDown, Some("Editor")),
 169        Binding::new("ctrl-shift-N", SelectDown, Some("Editor")),
 170        Binding::new("shift-left", SelectLeft, Some("Editor")),
 171        Binding::new("ctrl-shift-B", SelectLeft, Some("Editor")),
 172        Binding::new("shift-right", SelectRight, Some("Editor")),
 173        Binding::new("ctrl-shift-F", SelectRight, Some("Editor")),
 174        Binding::new(
 175            "alt-shift-left",
 176            SelectToPreviousWordBoundary,
 177            Some("Editor"),
 178        ),
 179        Binding::new("alt-shift-B", SelectToPreviousWordBoundary, Some("Editor")),
 180        Binding::new("alt-shift-right", SelectToNextWordBoundary, Some("Editor")),
 181        Binding::new("alt-shift-F", SelectToNextWordBoundary, Some("Editor")),
 182        Binding::new(
 183            "cmd-shift-left",
 184            SelectToBeginningOfLine(true),
 185            Some("Editor"),
 186        ),
 187        Binding::new(
 188            "ctrl-shift-A",
 189            SelectToBeginningOfLine(true),
 190            Some("Editor"),
 191        ),
 192        Binding::new("cmd-shift-right", SelectToEndOfLine, Some("Editor")),
 193        Binding::new("ctrl-shift-E", SelectToEndOfLine, Some("Editor")),
 194        Binding::new("cmd-shift-up", SelectToBeginning, Some("Editor")),
 195        Binding::new("cmd-shift-down", SelectToEnd, Some("Editor")),
 196        Binding::new("cmd-a", SelectAll, Some("Editor")),
 197        Binding::new("cmd-l", SelectLine, Some("Editor")),
 198        Binding::new("cmd-shift-L", SplitSelectionIntoLines, Some("Editor")),
 199        Binding::new("cmd-alt-up", AddSelectionAbove, Some("Editor")),
 200        Binding::new("cmd-ctrl-p", AddSelectionAbove, Some("Editor")),
 201        Binding::new("cmd-alt-down", AddSelectionBelow, Some("Editor")),
 202        Binding::new("cmd-ctrl-n", AddSelectionBelow, Some("Editor")),
 203        Binding::new("cmd-d", SelectNext(false), Some("Editor")),
 204        Binding::new("cmd-k cmd-d", SelectNext(true), Some("Editor")),
 205        Binding::new("cmd-/", ToggleComments, Some("Editor")),
 206        Binding::new("alt-up", SelectLargerSyntaxNode, Some("Editor")),
 207        Binding::new("ctrl-w", SelectLargerSyntaxNode, Some("Editor")),
 208        Binding::new("alt-down", SelectSmallerSyntaxNode, Some("Editor")),
 209        Binding::new("ctrl-shift-W", SelectSmallerSyntaxNode, Some("Editor")),
 210        Binding::new("f8", ShowNextDiagnostic, Some("Editor")),
 211        Binding::new("ctrl-m", MoveToEnclosingBracket, Some("Editor")),
 212        Binding::new("pageup", PageUp, Some("Editor")),
 213        Binding::new("pagedown", PageDown, Some("Editor")),
 214        Binding::new("alt-cmd-[", Fold, Some("Editor")),
 215        Binding::new("alt-cmd-]", Unfold, Some("Editor")),
 216        Binding::new("alt-cmd-f", FoldSelectedRanges, Some("Editor")),
 217    ]);
 218
 219    cx.add_action(Editor::open_new);
 220    cx.add_action(|this: &mut Editor, action: &Scroll, cx| this.set_scroll_position(action.0, cx));
 221    cx.add_action(Editor::select);
 222    cx.add_action(Editor::cancel);
 223    cx.add_action(Editor::handle_input);
 224    cx.add_action(Editor::newline);
 225    cx.add_action(Editor::backspace);
 226    cx.add_action(Editor::delete);
 227    cx.add_action(Editor::tab);
 228    cx.add_action(Editor::outdent);
 229    cx.add_action(Editor::delete_line);
 230    cx.add_action(Editor::delete_to_previous_word_boundary);
 231    cx.add_action(Editor::delete_to_next_word_boundary);
 232    cx.add_action(Editor::delete_to_beginning_of_line);
 233    cx.add_action(Editor::delete_to_end_of_line);
 234    cx.add_action(Editor::cut_to_end_of_line);
 235    cx.add_action(Editor::duplicate_line);
 236    cx.add_action(Editor::move_line_up);
 237    cx.add_action(Editor::move_line_down);
 238    cx.add_action(Editor::cut);
 239    cx.add_action(Editor::copy);
 240    cx.add_action(Editor::paste);
 241    cx.add_action(Editor::undo);
 242    cx.add_action(Editor::redo);
 243    cx.add_action(Editor::move_up);
 244    cx.add_action(Editor::move_down);
 245    cx.add_action(Editor::move_left);
 246    cx.add_action(Editor::move_right);
 247    cx.add_action(Editor::move_to_previous_word_boundary);
 248    cx.add_action(Editor::move_to_next_word_boundary);
 249    cx.add_action(Editor::move_to_beginning_of_line);
 250    cx.add_action(Editor::move_to_end_of_line);
 251    cx.add_action(Editor::move_to_beginning);
 252    cx.add_action(Editor::move_to_end);
 253    cx.add_action(Editor::select_up);
 254    cx.add_action(Editor::select_down);
 255    cx.add_action(Editor::select_left);
 256    cx.add_action(Editor::select_right);
 257    cx.add_action(Editor::select_to_previous_word_boundary);
 258    cx.add_action(Editor::select_to_next_word_boundary);
 259    cx.add_action(Editor::select_to_beginning_of_line);
 260    cx.add_action(Editor::select_to_end_of_line);
 261    cx.add_action(Editor::select_to_beginning);
 262    cx.add_action(Editor::select_to_end);
 263    cx.add_action(Editor::select_all);
 264    cx.add_action(Editor::select_line);
 265    cx.add_action(Editor::split_selection_into_lines);
 266    cx.add_action(Editor::add_selection_above);
 267    cx.add_action(Editor::add_selection_below);
 268    cx.add_action(Editor::select_next);
 269    cx.add_action(Editor::toggle_comments);
 270    cx.add_action(Editor::select_larger_syntax_node);
 271    cx.add_action(Editor::select_smaller_syntax_node);
 272    cx.add_action(Editor::move_to_enclosing_bracket);
 273    cx.add_action(Editor::show_next_diagnostic);
 274    cx.add_action(Editor::page_up);
 275    cx.add_action(Editor::page_down);
 276    cx.add_action(Editor::fold);
 277    cx.add_action(Editor::unfold);
 278    cx.add_action(Editor::fold_selected_ranges);
 279}
 280
 281trait SelectionExt {
 282    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize>;
 283    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point>;
 284    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
 285    fn spanned_rows(
 286        &self,
 287        include_end_if_at_line_start: bool,
 288        map: &DisplaySnapshot,
 289    ) -> SpannedRows;
 290}
 291
 292struct SpannedRows {
 293    buffer_rows: Range<u32>,
 294    display_rows: Range<u32>,
 295}
 296
 297#[derive(Clone, Debug)]
 298pub enum SelectPhase {
 299    Begin {
 300        position: DisplayPoint,
 301        add: bool,
 302        click_count: usize,
 303    },
 304    BeginColumnar {
 305        position: DisplayPoint,
 306        overshoot: u32,
 307    },
 308    Extend {
 309        position: DisplayPoint,
 310        click_count: usize,
 311    },
 312    Update {
 313        position: DisplayPoint,
 314        overshoot: u32,
 315        scroll_position: Vector2F,
 316    },
 317    End,
 318}
 319
 320#[derive(Clone, Debug)]
 321enum SelectMode {
 322    Character,
 323    Word(Range<Anchor>),
 324    Line(Range<Anchor>),
 325    All,
 326}
 327
 328#[derive(PartialEq, Eq)]
 329pub enum Autoscroll {
 330    Fit,
 331    Center,
 332    Newest,
 333}
 334
 335#[derive(Copy, Clone, PartialEq, Eq)]
 336pub enum EditorMode {
 337    SingleLine,
 338    AutoHeight { max_lines: usize },
 339    Full,
 340}
 341
 342#[derive(Clone)]
 343pub struct EditorSettings {
 344    pub tab_size: usize,
 345    pub soft_wrap: SoftWrap,
 346    pub style: EditorStyle,
 347}
 348
 349#[derive(Clone)]
 350pub enum SoftWrap {
 351    None,
 352    EditorWidth,
 353    Column(u32),
 354}
 355
 356pub struct Editor {
 357    handle: WeakViewHandle<Self>,
 358    buffer: ModelHandle<MultiBuffer>,
 359    display_map: ModelHandle<DisplayMap>,
 360    selection_set_id: SelectionSetId,
 361    pending_selection: Option<PendingSelection>,
 362    columnar_selection_tail: Option<Anchor>,
 363    next_selection_id: usize,
 364    add_selections_state: Option<AddSelectionsState>,
 365    select_next_state: Option<SelectNextState>,
 366    autoclose_stack: Vec<BracketPairState>,
 367    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
 368    active_diagnostics: Option<ActiveDiagnosticGroup>,
 369    scroll_position: Vector2F,
 370    scroll_top_anchor: Anchor,
 371    autoscroll_request: Option<Autoscroll>,
 372    build_settings: Rc<RefCell<dyn Fn(&AppContext) -> EditorSettings>>,
 373    focused: bool,
 374    show_local_cursors: bool,
 375    blink_epoch: usize,
 376    blinking_paused: bool,
 377    mode: EditorMode,
 378    placeholder_text: Option<Arc<str>>,
 379    highlighted_row: Option<u32>,
 380}
 381
 382pub struct EditorSnapshot {
 383    pub mode: EditorMode,
 384    pub display_snapshot: DisplaySnapshot,
 385    pub placeholder_text: Option<Arc<str>>,
 386    is_focused: bool,
 387    scroll_position: Vector2F,
 388    scroll_top_anchor: Anchor,
 389}
 390
 391struct PendingSelection {
 392    selection: Selection<Anchor>,
 393    mode: SelectMode,
 394}
 395
 396struct AddSelectionsState {
 397    above: bool,
 398    stack: Vec<usize>,
 399}
 400
 401struct SelectNextState {
 402    query: AhoCorasick,
 403    wordwise: bool,
 404    done: bool,
 405}
 406
 407#[derive(Debug)]
 408struct BracketPairState {
 409    ranges: Vec<Range<Anchor>>,
 410    pair: BracketPair,
 411}
 412
 413#[derive(Debug)]
 414struct ActiveDiagnosticGroup {
 415    primary_range: Range<Anchor>,
 416    primary_message: String,
 417    blocks: HashMap<BlockId, Diagnostic>,
 418    is_valid: bool,
 419}
 420
 421#[derive(Serialize, Deserialize)]
 422struct ClipboardSelection {
 423    len: usize,
 424    is_entire_line: bool,
 425}
 426
 427impl Editor {
 428    pub fn single_line(
 429        build_settings: impl 'static + Fn(&AppContext) -> EditorSettings,
 430        cx: &mut ViewContext<Self>,
 431    ) -> Self {
 432        let buffer = cx.add_model(|cx| Buffer::new(0, String::new(), cx));
 433        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
 434        let mut view = Self::for_buffer(buffer, build_settings, cx);
 435        view.mode = EditorMode::SingleLine;
 436        view
 437    }
 438
 439    pub fn auto_height(
 440        max_lines: usize,
 441        build_settings: impl 'static + Fn(&AppContext) -> EditorSettings,
 442        cx: &mut ViewContext<Self>,
 443    ) -> Self {
 444        let buffer = cx.add_model(|cx| Buffer::new(0, String::new(), cx));
 445        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
 446        let mut view = Self::for_buffer(buffer, build_settings, cx);
 447        view.mode = EditorMode::AutoHeight { max_lines };
 448        view
 449    }
 450
 451    pub fn for_buffer(
 452        buffer: ModelHandle<MultiBuffer>,
 453        build_settings: impl 'static + Fn(&AppContext) -> EditorSettings,
 454        cx: &mut ViewContext<Self>,
 455    ) -> Self {
 456        Self::new(buffer, Rc::new(RefCell::new(build_settings)), cx)
 457    }
 458
 459    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 460        let mut clone = Self::new(self.buffer.clone(), self.build_settings.clone(), cx);
 461        clone.scroll_position = self.scroll_position;
 462        clone.scroll_top_anchor = self.scroll_top_anchor.clone();
 463        clone
 464    }
 465
 466    pub fn new(
 467        buffer: ModelHandle<MultiBuffer>,
 468        build_settings: Rc<RefCell<dyn Fn(&AppContext) -> EditorSettings>>,
 469        cx: &mut ViewContext<Self>,
 470    ) -> Self {
 471        let settings = build_settings.borrow_mut()(cx);
 472        let display_map = cx.add_model(|cx| {
 473            DisplayMap::new(
 474                buffer.clone(),
 475                settings.tab_size,
 476                settings.style.text.font_id,
 477                settings.style.text.font_size,
 478                None,
 479                cx,
 480            )
 481        });
 482        cx.observe(&buffer, Self::on_buffer_changed).detach();
 483        cx.subscribe(&buffer, Self::on_buffer_event).detach();
 484        cx.observe(&display_map, Self::on_display_map_changed)
 485            .detach();
 486
 487        let mut next_selection_id = 0;
 488        let selection_set_id = buffer.update(cx, |buffer, cx| {
 489            buffer.add_selection_set(
 490                &[Selection {
 491                    id: post_inc(&mut next_selection_id),
 492                    start: 0,
 493                    end: 0,
 494                    reversed: false,
 495                    goal: SelectionGoal::None,
 496                }],
 497                cx,
 498            )
 499        });
 500        Self {
 501            handle: cx.weak_handle(),
 502            buffer,
 503            display_map,
 504            selection_set_id,
 505            pending_selection: None,
 506            columnar_selection_tail: None,
 507            next_selection_id,
 508            add_selections_state: None,
 509            select_next_state: None,
 510            autoclose_stack: Default::default(),
 511            select_larger_syntax_node_stack: Vec::new(),
 512            active_diagnostics: None,
 513            build_settings,
 514            scroll_position: Vector2F::zero(),
 515            scroll_top_anchor: Anchor::min(),
 516            autoscroll_request: None,
 517            focused: false,
 518            show_local_cursors: false,
 519            blink_epoch: 0,
 520            blinking_paused: false,
 521            mode: EditorMode::Full,
 522            placeholder_text: None,
 523            highlighted_row: None,
 524        }
 525    }
 526
 527    pub fn open_new(
 528        workspace: &mut Workspace,
 529        _: &workspace::OpenNew,
 530        cx: &mut ViewContext<Workspace>,
 531    ) {
 532        let buffer = cx.add_model(|cx| {
 533            Buffer::new(0, "", cx).with_language(Some(language::PLAIN_TEXT.clone()), None, cx)
 534        });
 535        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
 536        workspace.add_item(BufferItemHandle(buffer), cx);
 537    }
 538
 539    pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
 540        self.buffer.read(cx).replica_id()
 541    }
 542
 543    pub fn buffer(&self) -> &ModelHandle<MultiBuffer> {
 544        &self.buffer
 545    }
 546
 547    pub fn snapshot(&mut self, cx: &mut MutableAppContext) -> EditorSnapshot {
 548        EditorSnapshot {
 549            mode: self.mode,
 550            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 551            scroll_position: self.scroll_position,
 552            scroll_top_anchor: self.scroll_top_anchor.clone(),
 553            placeholder_text: self.placeholder_text.clone(),
 554            is_focused: self
 555                .handle
 556                .upgrade(cx)
 557                .map_or(false, |handle| handle.is_focused(cx)),
 558        }
 559    }
 560
 561    pub fn language<'a>(&self, cx: &'a AppContext) -> Option<&'a Arc<Language>> {
 562        self.buffer.read(cx).language(cx)
 563    }
 564
 565    pub fn set_placeholder_text(
 566        &mut self,
 567        placeholder_text: impl Into<Arc<str>>,
 568        cx: &mut ViewContext<Self>,
 569    ) {
 570        self.placeholder_text = Some(placeholder_text.into());
 571        cx.notify();
 572    }
 573
 574    pub fn set_scroll_position(&mut self, scroll_position: Vector2F, cx: &mut ViewContext<Self>) {
 575        let map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 576        let scroll_top_buffer_offset =
 577            DisplayPoint::new(scroll_position.y() as u32, 0).to_offset(&map, Bias::Right);
 578        self.scroll_top_anchor = map
 579            .buffer_snapshot
 580            .anchor_at(scroll_top_buffer_offset, Bias::Right);
 581        self.scroll_position = vec2f(
 582            scroll_position.x(),
 583            scroll_position.y() - self.scroll_top_anchor.to_display_point(&map).row() as f32,
 584        );
 585
 586        debug_assert_eq!(
 587            compute_scroll_position(&map, self.scroll_position, &self.scroll_top_anchor),
 588            scroll_position
 589        );
 590
 591        cx.notify();
 592    }
 593
 594    pub fn scroll_position(&self, cx: &mut ViewContext<Self>) -> Vector2F {
 595        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 596        compute_scroll_position(&display_map, self.scroll_position, &self.scroll_top_anchor)
 597    }
 598
 599    pub fn clamp_scroll_left(&mut self, max: f32) -> bool {
 600        if max < self.scroll_position.x() {
 601            self.scroll_position.set_x(max);
 602            true
 603        } else {
 604            false
 605        }
 606    }
 607
 608    pub fn autoscroll_vertically(
 609        &mut self,
 610        viewport_height: f32,
 611        line_height: f32,
 612        cx: &mut ViewContext<Self>,
 613    ) -> bool {
 614        let visible_lines = viewport_height / line_height;
 615        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 616        let mut scroll_position =
 617            compute_scroll_position(&display_map, self.scroll_position, &self.scroll_top_anchor);
 618        let max_scroll_top = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
 619            (display_map.max_point().row() as f32 - visible_lines + 1.).max(0.)
 620        } else {
 621            display_map.max_point().row().saturating_sub(1) as f32
 622        };
 623        if scroll_position.y() > max_scroll_top {
 624            scroll_position.set_y(max_scroll_top);
 625            self.set_scroll_position(scroll_position, cx);
 626        }
 627
 628        let autoscroll = if let Some(autoscroll) = self.autoscroll_request.take() {
 629            autoscroll
 630        } else {
 631            return false;
 632        };
 633
 634        let first_cursor_top;
 635        let last_cursor_bottom;
 636        if autoscroll == Autoscroll::Newest {
 637            let newest_selection = self.newest_selection::<Point>(cx);
 638            first_cursor_top = newest_selection.head().to_display_point(&display_map).row() as f32;
 639            last_cursor_bottom = first_cursor_top + 1.;
 640        } else {
 641            let selections = self.selections::<Point>(cx);
 642            first_cursor_top = selections
 643                .first()
 644                .unwrap()
 645                .head()
 646                .to_display_point(&display_map)
 647                .row() as f32;
 648            last_cursor_bottom = selections
 649                .last()
 650                .unwrap()
 651                .head()
 652                .to_display_point(&display_map)
 653                .row() as f32
 654                + 1.0;
 655        }
 656
 657        let margin = if matches!(self.mode, EditorMode::AutoHeight { .. }) {
 658            0.
 659        } else {
 660            ((visible_lines - (last_cursor_bottom - first_cursor_top)) / 2.0).floor()
 661        };
 662        if margin < 0.0 {
 663            return false;
 664        }
 665
 666        match autoscroll {
 667            Autoscroll::Fit | Autoscroll::Newest => {
 668                let margin = margin.min(3.0);
 669                let target_top = (first_cursor_top - margin).max(0.0);
 670                let target_bottom = last_cursor_bottom + margin;
 671                let start_row = scroll_position.y();
 672                let end_row = start_row + visible_lines;
 673
 674                if target_top < start_row {
 675                    scroll_position.set_y(target_top);
 676                    self.set_scroll_position(scroll_position, cx);
 677                } else if target_bottom >= end_row {
 678                    scroll_position.set_y(target_bottom - visible_lines);
 679                    self.set_scroll_position(scroll_position, cx);
 680                }
 681            }
 682            Autoscroll::Center => {
 683                scroll_position.set_y((first_cursor_top - margin).max(0.0));
 684                self.set_scroll_position(scroll_position, cx);
 685            }
 686        }
 687
 688        true
 689    }
 690
 691    pub fn autoscroll_horizontally(
 692        &mut self,
 693        start_row: u32,
 694        viewport_width: f32,
 695        scroll_width: f32,
 696        max_glyph_width: f32,
 697        layouts: &[text_layout::Line],
 698        cx: &mut ViewContext<Self>,
 699    ) -> bool {
 700        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 701        let selections = self.selections::<Point>(cx);
 702        let mut target_left = std::f32::INFINITY;
 703        let mut target_right = 0.0_f32;
 704        for selection in selections {
 705            let head = selection.head().to_display_point(&display_map);
 706            if head.row() >= start_row && head.row() < start_row + layouts.len() as u32 {
 707                let start_column = head.column().saturating_sub(3);
 708                let end_column = cmp::min(display_map.line_len(head.row()), head.column() + 3);
 709                target_left = target_left.min(
 710                    layouts[(head.row() - start_row) as usize].x_for_index(start_column as usize),
 711                );
 712                target_right = target_right.max(
 713                    layouts[(head.row() - start_row) as usize].x_for_index(end_column as usize)
 714                        + max_glyph_width,
 715                );
 716            }
 717        }
 718        target_right = target_right.min(scroll_width);
 719
 720        if target_right - target_left > viewport_width {
 721            return false;
 722        }
 723
 724        let scroll_left = self.scroll_position.x() * max_glyph_width;
 725        let scroll_right = scroll_left + viewport_width;
 726
 727        if target_left < scroll_left {
 728            self.scroll_position.set_x(target_left / max_glyph_width);
 729            true
 730        } else if target_right > scroll_right {
 731            self.scroll_position
 732                .set_x((target_right - viewport_width) / max_glyph_width);
 733            true
 734        } else {
 735            false
 736        }
 737    }
 738
 739    fn select(&mut self, Select(phase): &Select, cx: &mut ViewContext<Self>) {
 740        match phase {
 741            SelectPhase::Begin {
 742                position,
 743                add,
 744                click_count,
 745            } => self.begin_selection(*position, *add, *click_count, cx),
 746            SelectPhase::BeginColumnar {
 747                position,
 748                overshoot,
 749            } => self.begin_columnar_selection(*position, *overshoot, cx),
 750            SelectPhase::Extend {
 751                position,
 752                click_count,
 753            } => self.extend_selection(*position, *click_count, cx),
 754            SelectPhase::Update {
 755                position,
 756                overshoot,
 757                scroll_position,
 758            } => self.update_selection(*position, *overshoot, *scroll_position, cx),
 759            SelectPhase::End => self.end_selection(cx),
 760        }
 761    }
 762
 763    fn extend_selection(
 764        &mut self,
 765        position: DisplayPoint,
 766        click_count: usize,
 767        cx: &mut ViewContext<Self>,
 768    ) {
 769        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 770        let tail = self.newest_selection::<usize>(cx).tail();
 771        self.begin_selection(position, false, click_count, cx);
 772
 773        let position = position.to_offset(&display_map, Bias::Left);
 774        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 775        let pending = self.pending_selection.as_mut().unwrap();
 776
 777        if position >= tail {
 778            pending.selection.start = tail_anchor.clone();
 779        } else {
 780            pending.selection.end = tail_anchor.clone();
 781            pending.selection.reversed = true;
 782        }
 783
 784        match &mut pending.mode {
 785            SelectMode::Word(range) | SelectMode::Line(range) => {
 786                *range = tail_anchor.clone()..tail_anchor
 787            }
 788            _ => {}
 789        }
 790    }
 791
 792    fn begin_selection(
 793        &mut self,
 794        position: DisplayPoint,
 795        add: bool,
 796        click_count: usize,
 797        cx: &mut ViewContext<Self>,
 798    ) {
 799        if !self.focused {
 800            cx.focus_self();
 801            cx.emit(Event::Activate);
 802        }
 803
 804        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 805        let buffer = &display_map.buffer_snapshot;
 806        let start;
 807        let end;
 808        let mode;
 809        match click_count {
 810            1 => {
 811                start = buffer.anchor_before(position.to_point(&display_map));
 812                end = start.clone();
 813                mode = SelectMode::Character;
 814            }
 815            2 => {
 816                let range = movement::surrounding_word(&display_map, position);
 817                start = buffer.anchor_before(range.start.to_point(&display_map));
 818                end = buffer.anchor_before(range.end.to_point(&display_map));
 819                mode = SelectMode::Word(start.clone()..end.clone());
 820            }
 821            3 => {
 822                let position = display_map.clip_point(position, Bias::Left);
 823                let line_start = movement::line_beginning(&display_map, position, false);
 824                let mut next_line_start = line_start.clone();
 825                *next_line_start.row_mut() += 1;
 826                *next_line_start.column_mut() = 0;
 827                next_line_start = display_map.clip_point(next_line_start, Bias::Right);
 828
 829                start = buffer.anchor_before(line_start.to_point(&display_map));
 830                end = buffer.anchor_before(next_line_start.to_point(&display_map));
 831                mode = SelectMode::Line(start.clone()..end.clone());
 832            }
 833            _ => {
 834                start = buffer.anchor_before(0);
 835                end = buffer.anchor_before(buffer.len());
 836                mode = SelectMode::All;
 837            }
 838        }
 839
 840        let selection = Selection {
 841            id: post_inc(&mut self.next_selection_id),
 842            start,
 843            end,
 844            reversed: false,
 845            goal: SelectionGoal::None,
 846        };
 847
 848        if !add {
 849            self.update_selections::<usize>(Vec::new(), None, cx);
 850        } else if click_count > 1 {
 851            // Remove the newest selection since it was only added as part of this multi-click.
 852            let newest_selection = self.newest_selection::<usize>(cx);
 853            let mut selections = self.selections(cx);
 854            selections.retain(|selection| selection.id != newest_selection.id);
 855            self.update_selections::<usize>(selections, None, cx)
 856        }
 857
 858        self.pending_selection = Some(PendingSelection { selection, mode });
 859
 860        cx.notify();
 861    }
 862
 863    fn begin_columnar_selection(
 864        &mut self,
 865        position: DisplayPoint,
 866        overshoot: u32,
 867        cx: &mut ViewContext<Self>,
 868    ) {
 869        if !self.focused {
 870            cx.focus_self();
 871            cx.emit(Event::Activate);
 872        }
 873
 874        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 875        let tail = self.newest_selection::<Point>(cx).tail();
 876        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 877
 878        self.select_columns(
 879            tail.to_display_point(&display_map),
 880            position,
 881            overshoot,
 882            &display_map,
 883            cx,
 884        );
 885    }
 886
 887    fn update_selection(
 888        &mut self,
 889        position: DisplayPoint,
 890        overshoot: u32,
 891        scroll_position: Vector2F,
 892        cx: &mut ViewContext<Self>,
 893    ) {
 894        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 895
 896        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 897            let tail = tail.to_display_point(&display_map);
 898            self.select_columns(tail, position, overshoot, &display_map, cx);
 899        } else if let Some(PendingSelection { selection, mode }) = self.pending_selection.as_mut() {
 900            let buffer = self.buffer.read(cx).snapshot(cx);
 901            let head;
 902            let tail;
 903            match mode {
 904                SelectMode::Character => {
 905                    head = position.to_point(&display_map);
 906                    tail = selection.tail().to_point(&buffer);
 907                }
 908                SelectMode::Word(original_range) => {
 909                    let original_display_range = original_range.start.to_display_point(&display_map)
 910                        ..original_range.end.to_display_point(&display_map);
 911                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 912                        ..original_display_range.end.to_point(&display_map);
 913                    if movement::is_inside_word(&display_map, position)
 914                        || original_display_range.contains(&position)
 915                    {
 916                        let word_range = movement::surrounding_word(&display_map, position);
 917                        if word_range.start < original_display_range.start {
 918                            head = word_range.start.to_point(&display_map);
 919                        } else {
 920                            head = word_range.end.to_point(&display_map);
 921                        }
 922                    } else {
 923                        head = position.to_point(&display_map);
 924                    }
 925
 926                    if head <= original_buffer_range.start {
 927                        tail = original_buffer_range.end;
 928                    } else {
 929                        tail = original_buffer_range.start;
 930                    }
 931                }
 932                SelectMode::Line(original_range) => {
 933                    let original_display_range = original_range.start.to_display_point(&display_map)
 934                        ..original_range.end.to_display_point(&display_map);
 935                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 936                        ..original_display_range.end.to_point(&display_map);
 937                    let line_start = movement::line_beginning(&display_map, position, false);
 938                    let mut next_line_start = line_start.clone();
 939                    *next_line_start.row_mut() += 1;
 940                    *next_line_start.column_mut() = 0;
 941                    next_line_start = display_map.clip_point(next_line_start, Bias::Right);
 942
 943                    if line_start < original_display_range.start {
 944                        head = line_start.to_point(&display_map);
 945                    } else {
 946                        head = next_line_start.to_point(&display_map);
 947                    }
 948
 949                    if head <= original_buffer_range.start {
 950                        tail = original_buffer_range.end;
 951                    } else {
 952                        tail = original_buffer_range.start;
 953                    }
 954                }
 955                SelectMode::All => {
 956                    return;
 957                }
 958            };
 959
 960            if head < tail {
 961                selection.start = buffer.anchor_before(head);
 962                selection.end = buffer.anchor_before(tail);
 963                selection.reversed = true;
 964            } else {
 965                selection.start = buffer.anchor_before(tail);
 966                selection.end = buffer.anchor_before(head);
 967                selection.reversed = false;
 968            }
 969        } else {
 970            log::error!("update_selection dispatched with no pending selection");
 971            return;
 972        }
 973
 974        self.set_scroll_position(scroll_position, cx);
 975        cx.notify();
 976    }
 977
 978    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 979        self.columnar_selection_tail.take();
 980        if self.pending_selection.is_some() {
 981            let selections = self.selections::<usize>(cx);
 982            self.update_selections(selections, None, cx);
 983        }
 984    }
 985
 986    fn select_columns(
 987        &mut self,
 988        tail: DisplayPoint,
 989        head: DisplayPoint,
 990        overshoot: u32,
 991        display_map: &DisplaySnapshot,
 992        cx: &mut ViewContext<Self>,
 993    ) {
 994        let start_row = cmp::min(tail.row(), head.row());
 995        let end_row = cmp::max(tail.row(), head.row());
 996        let start_column = cmp::min(tail.column(), head.column() + overshoot);
 997        let end_column = cmp::max(tail.column(), head.column() + overshoot);
 998        let reversed = start_column < tail.column();
 999
1000        let selections = (start_row..=end_row)
1001            .filter_map(|row| {
1002                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
1003                    let start = display_map
1004                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
1005                        .to_point(&display_map);
1006                    let end = display_map
1007                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
1008                        .to_point(&display_map);
1009                    Some(Selection {
1010                        id: post_inc(&mut self.next_selection_id),
1011                        start,
1012                        end,
1013                        reversed,
1014                        goal: SelectionGoal::None,
1015                    })
1016                } else {
1017                    None
1018                }
1019            })
1020            .collect::<Vec<_>>();
1021
1022        self.update_selections(selections, None, cx);
1023        cx.notify();
1024    }
1025
1026    pub fn is_selecting(&self) -> bool {
1027        self.pending_selection.is_some() || self.columnar_selection_tail.is_some()
1028    }
1029
1030    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
1031        if self.active_diagnostics.is_some() {
1032            self.dismiss_diagnostics(cx);
1033        } else if let Some(PendingSelection { selection, .. }) = self.pending_selection.take() {
1034            let buffer = self.buffer.read(cx).snapshot(cx);
1035            let selection = Selection {
1036                id: selection.id,
1037                start: selection.start.to_point(&buffer),
1038                end: selection.end.to_point(&buffer),
1039                reversed: selection.reversed,
1040                goal: selection.goal,
1041            };
1042            if self.selections::<Point>(cx).is_empty() {
1043                self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
1044            }
1045        } else {
1046            let buffer = self.buffer.read(cx).snapshot(cx);
1047            let mut oldest_selection = self.oldest_selection::<usize>(&buffer, cx);
1048            if self.selection_count(cx) == 1 {
1049                oldest_selection.start = oldest_selection.head().clone();
1050                oldest_selection.end = oldest_selection.head().clone();
1051            }
1052            self.update_selections(vec![oldest_selection], Some(Autoscroll::Fit), cx);
1053        }
1054    }
1055
1056    pub fn select_ranges<I, T>(
1057        &mut self,
1058        ranges: I,
1059        autoscroll: Option<Autoscroll>,
1060        cx: &mut ViewContext<Self>,
1061    ) where
1062        I: IntoIterator<Item = Range<T>>,
1063        T: ToOffset,
1064    {
1065        let buffer = self.buffer.read(cx).snapshot(cx);
1066        let selections = ranges
1067            .into_iter()
1068            .map(|range| {
1069                let mut start = range.start.to_offset(&buffer);
1070                let mut end = range.end.to_offset(&buffer);
1071                let reversed = if start > end {
1072                    mem::swap(&mut start, &mut end);
1073                    true
1074                } else {
1075                    false
1076                };
1077                Selection {
1078                    id: post_inc(&mut self.next_selection_id),
1079                    start,
1080                    end,
1081                    reversed,
1082                    goal: SelectionGoal::None,
1083                }
1084            })
1085            .collect();
1086        self.update_selections(selections, autoscroll, cx);
1087    }
1088
1089    #[cfg(test)]
1090    fn select_display_ranges<'a, T>(
1091        &mut self,
1092        ranges: T,
1093        cx: &mut ViewContext<Self>,
1094    ) -> anyhow::Result<()>
1095    where
1096        T: IntoIterator<Item = &'a Range<DisplayPoint>>,
1097    {
1098        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1099        let selections = ranges
1100            .into_iter()
1101            .map(|range| {
1102                let mut start = range.start;
1103                let mut end = range.end;
1104                let reversed = if start > end {
1105                    mem::swap(&mut start, &mut end);
1106                    true
1107                } else {
1108                    false
1109                };
1110                Selection {
1111                    id: post_inc(&mut self.next_selection_id),
1112                    start: start.to_point(&display_map),
1113                    end: end.to_point(&display_map),
1114                    reversed,
1115                    goal: SelectionGoal::None,
1116                }
1117            })
1118            .collect();
1119        self.update_selections(selections, None, cx);
1120        Ok(())
1121    }
1122
1123    pub fn handle_input(&mut self, action: &Input, cx: &mut ViewContext<Self>) {
1124        let text = action.0.as_ref();
1125        if !self.skip_autoclose_end(text, cx) {
1126            self.start_transaction(cx);
1127            self.insert(text, cx);
1128            self.autoclose_pairs(cx);
1129            self.end_transaction(cx);
1130        }
1131    }
1132
1133    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
1134        self.start_transaction(cx);
1135        let mut old_selections = SmallVec::<[_; 32]>::new();
1136        {
1137            let selections = self.selections::<Point>(cx);
1138            let buffer = self.buffer.read(cx).snapshot(cx);
1139            for selection in selections.iter() {
1140                let start_point = selection.start;
1141                let indent = buffer
1142                    .indent_column_for_line(start_point.row)
1143                    .min(start_point.column);
1144                let start = selection.start.to_offset(&buffer);
1145                let end = selection.end.to_offset(&buffer);
1146
1147                let mut insert_extra_newline = false;
1148                if let Some(language) = buffer.language() {
1149                    let leading_whitespace_len = buffer
1150                        .reversed_chars_at(start)
1151                        .take_while(|c| c.is_whitespace() && *c != '\n')
1152                        .map(|c| c.len_utf8())
1153                        .sum::<usize>();
1154
1155                    let trailing_whitespace_len = buffer
1156                        .chars_at(end)
1157                        .take_while(|c| c.is_whitespace() && *c != '\n')
1158                        .map(|c| c.len_utf8())
1159                        .sum::<usize>();
1160
1161                    insert_extra_newline = language.brackets().iter().any(|pair| {
1162                        let pair_start = pair.start.trim_end();
1163                        let pair_end = pair.end.trim_start();
1164
1165                        pair.newline
1166                            && buffer.contains_str_at(end + trailing_whitespace_len, pair_end)
1167                            && buffer.contains_str_at(
1168                                (start - leading_whitespace_len).saturating_sub(pair_start.len()),
1169                                pair_start,
1170                            )
1171                    });
1172                }
1173
1174                old_selections.push((selection.id, start..end, indent, insert_extra_newline));
1175            }
1176        }
1177
1178        let mut new_selections = Vec::with_capacity(old_selections.len());
1179        self.buffer.update(cx, |buffer, cx| {
1180            let mut delta = 0_isize;
1181            let mut pending_edit: Option<PendingEdit> = None;
1182            for (_, range, indent, insert_extra_newline) in &old_selections {
1183                if pending_edit.as_ref().map_or(false, |pending| {
1184                    pending.indent != *indent
1185                        || pending.insert_extra_newline != *insert_extra_newline
1186                }) {
1187                    let pending = pending_edit.take().unwrap();
1188                    let mut new_text = String::with_capacity(1 + pending.indent as usize);
1189                    new_text.push('\n');
1190                    new_text.extend(iter::repeat(' ').take(pending.indent as usize));
1191                    if pending.insert_extra_newline {
1192                        new_text = new_text.repeat(2);
1193                    }
1194                    buffer.edit_with_autoindent(pending.ranges, new_text, cx);
1195                    delta += pending.delta;
1196                }
1197
1198                let start = (range.start as isize + delta) as usize;
1199                let end = (range.end as isize + delta) as usize;
1200                let mut text_len = *indent as usize + 1;
1201                if *insert_extra_newline {
1202                    text_len *= 2;
1203                }
1204
1205                let pending = pending_edit.get_or_insert_with(Default::default);
1206                pending.delta += text_len as isize - (end - start) as isize;
1207                pending.indent = *indent;
1208                pending.insert_extra_newline = *insert_extra_newline;
1209                pending.ranges.push(start..end);
1210            }
1211
1212            let pending = pending_edit.unwrap();
1213            let mut new_text = String::with_capacity(1 + pending.indent as usize);
1214            new_text.push('\n');
1215            new_text.extend(iter::repeat(' ').take(pending.indent as usize));
1216            if pending.insert_extra_newline {
1217                new_text = new_text.repeat(2);
1218            }
1219            buffer.edit_with_autoindent(pending.ranges, new_text, cx);
1220
1221            let mut delta = 0_isize;
1222            new_selections.extend(old_selections.into_iter().map(
1223                |(id, range, indent, insert_extra_newline)| {
1224                    let start = (range.start as isize + delta) as usize;
1225                    let end = (range.end as isize + delta) as usize;
1226                    let text_before_cursor_len = indent as usize + 1;
1227                    let cursor = start + text_before_cursor_len;
1228                    let text_len = if insert_extra_newline {
1229                        text_before_cursor_len * 2
1230                    } else {
1231                        text_before_cursor_len
1232                    };
1233                    delta += text_len as isize - (end - start) as isize;
1234                    Selection {
1235                        id,
1236                        start: cursor,
1237                        end: cursor,
1238                        reversed: false,
1239                        goal: SelectionGoal::None,
1240                    }
1241                },
1242            ))
1243        });
1244
1245        self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
1246        self.end_transaction(cx);
1247
1248        #[derive(Default)]
1249        struct PendingEdit {
1250            indent: u32,
1251            insert_extra_newline: bool,
1252            delta: isize,
1253            ranges: SmallVec<[Range<usize>; 32]>,
1254        }
1255    }
1256
1257    fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
1258        self.start_transaction(cx);
1259        let old_selections = self.selections::<usize>(cx);
1260        let mut new_selections = Vec::new();
1261        self.buffer.update(cx, |buffer, cx| {
1262            let edit_ranges = old_selections.iter().map(|s| s.start..s.end);
1263            buffer.edit_with_autoindent(edit_ranges, text, cx);
1264            let text_len = text.len() as isize;
1265            let mut delta = 0_isize;
1266            new_selections = old_selections
1267                .into_iter()
1268                .map(|selection| {
1269                    let start = selection.start as isize;
1270                    let end = selection.end as isize;
1271                    let cursor = (start + delta + text_len) as usize;
1272                    let deleted_count = end - start;
1273                    delta += text_len - deleted_count;
1274                    Selection {
1275                        id: selection.id,
1276                        start: cursor,
1277                        end: cursor,
1278                        reversed: false,
1279                        goal: SelectionGoal::None,
1280                    }
1281                })
1282                .collect();
1283        });
1284
1285        self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
1286        self.end_transaction(cx);
1287    }
1288
1289    fn autoclose_pairs(&mut self, cx: &mut ViewContext<Self>) {
1290        let selections = self.selections::<usize>(cx);
1291        let new_autoclose_pair = self.buffer.update(cx, |buffer, cx| {
1292            let snapshot = buffer.snapshot(cx);
1293            let autoclose_pair = snapshot.language().and_then(|language| {
1294                let first_selection_start = selections.first().unwrap().start;
1295                let pair = language.brackets().iter().find(|pair| {
1296                    snapshot.contains_str_at(
1297                        first_selection_start.saturating_sub(pair.start.len()),
1298                        &pair.start,
1299                    )
1300                });
1301                pair.and_then(|pair| {
1302                    let should_autoclose = selections[1..].iter().all(|selection| {
1303                        snapshot.contains_str_at(
1304                            selection.start.saturating_sub(pair.start.len()),
1305                            &pair.start,
1306                        )
1307                    });
1308
1309                    if should_autoclose {
1310                        Some(pair.clone())
1311                    } else {
1312                        None
1313                    }
1314                })
1315            });
1316
1317            autoclose_pair.and_then(|pair| {
1318                let selection_ranges = selections
1319                    .iter()
1320                    .map(|selection| {
1321                        let start = selection.start.to_offset(&snapshot);
1322                        start..start
1323                    })
1324                    .collect::<SmallVec<[_; 32]>>();
1325
1326                buffer.edit(selection_ranges, &pair.end, cx);
1327                let snapshot = buffer.snapshot(cx);
1328
1329                if pair.end.len() == 1 {
1330                    let mut delta = 0;
1331                    Some(BracketPairState {
1332                        ranges: selections
1333                            .iter()
1334                            .map(move |selection| {
1335                                let offset = selection.start + delta;
1336                                delta += 1;
1337                                snapshot.anchor_before(offset)..snapshot.anchor_after(offset)
1338                            })
1339                            .collect(),
1340                        pair,
1341                    })
1342                } else {
1343                    None
1344                }
1345            })
1346        });
1347        self.autoclose_stack.extend(new_autoclose_pair);
1348    }
1349
1350    fn skip_autoclose_end(&mut self, text: &str, cx: &mut ViewContext<Self>) -> bool {
1351        let old_selections = self.selections::<usize>(cx);
1352        let autoclose_pair = if let Some(autoclose_pair) = self.autoclose_stack.last() {
1353            autoclose_pair
1354        } else {
1355            return false;
1356        };
1357        if text != autoclose_pair.pair.end {
1358            return false;
1359        }
1360
1361        debug_assert_eq!(old_selections.len(), autoclose_pair.ranges.len());
1362
1363        let buffer = self.buffer.read(cx).snapshot(cx);
1364        if old_selections
1365            .iter()
1366            .zip(autoclose_pair.ranges.iter().map(|r| r.to_offset(&buffer)))
1367            .all(|(selection, autoclose_range)| {
1368                let autoclose_range_end = autoclose_range.end.to_offset(&buffer);
1369                selection.is_empty() && selection.start == autoclose_range_end
1370            })
1371        {
1372            let new_selections = old_selections
1373                .into_iter()
1374                .map(|selection| {
1375                    let cursor = selection.start + 1;
1376                    Selection {
1377                        id: selection.id,
1378                        start: cursor,
1379                        end: cursor,
1380                        reversed: false,
1381                        goal: SelectionGoal::None,
1382                    }
1383                })
1384                .collect();
1385            self.autoclose_stack.pop();
1386            self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
1387            true
1388        } else {
1389            false
1390        }
1391    }
1392
1393    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
1394        self.start_transaction(cx);
1395        self.select_all(&SelectAll, cx);
1396        self.insert("", cx);
1397        self.end_transaction(cx);
1398    }
1399
1400    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
1401        self.start_transaction(cx);
1402        let mut selections = self.selections::<Point>(cx);
1403        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1404        for selection in &mut selections {
1405            if selection.is_empty() {
1406                let head = selection.head().to_display_point(&display_map);
1407                let cursor = movement::left(&display_map, head)
1408                    .unwrap()
1409                    .to_point(&display_map);
1410                selection.set_head(cursor);
1411                selection.goal = SelectionGoal::None;
1412            }
1413        }
1414        self.update_selections(selections, Some(Autoscroll::Fit), cx);
1415        self.insert("", cx);
1416        self.end_transaction(cx);
1417    }
1418
1419    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
1420        self.start_transaction(cx);
1421        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1422        let mut selections = self.selections::<Point>(cx);
1423        for selection in &mut selections {
1424            if selection.is_empty() {
1425                let head = selection.head().to_display_point(&display_map);
1426                let cursor = movement::right(&display_map, head)
1427                    .unwrap()
1428                    .to_point(&display_map);
1429                selection.set_head(cursor);
1430                selection.goal = SelectionGoal::None;
1431            }
1432        }
1433        self.update_selections(selections, Some(Autoscroll::Fit), cx);
1434        self.insert(&"", cx);
1435        self.end_transaction(cx);
1436    }
1437
1438    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
1439        self.start_transaction(cx);
1440        let tab_size = self.build_settings.borrow()(cx).tab_size;
1441        let mut selections = self.selections::<Point>(cx);
1442        let mut last_indent = None;
1443        self.buffer.update(cx, |buffer, cx| {
1444            for selection in &mut selections {
1445                if selection.is_empty() {
1446                    let char_column = buffer
1447                        .read(cx)
1448                        .text_for_range(Point::new(selection.start.row, 0)..selection.start)
1449                        .flat_map(str::chars)
1450                        .count();
1451                    let chars_to_next_tab_stop = tab_size - (char_column % tab_size);
1452                    buffer.edit(
1453                        [selection.start..selection.start],
1454                        " ".repeat(chars_to_next_tab_stop),
1455                        cx,
1456                    );
1457                    selection.start.column += chars_to_next_tab_stop as u32;
1458                    selection.end = selection.start;
1459                } else {
1460                    let mut start_row = selection.start.row;
1461                    let mut end_row = selection.end.row + 1;
1462
1463                    // If a selection ends at the beginning of a line, don't indent
1464                    // that last line.
1465                    if selection.end.column == 0 {
1466                        end_row -= 1;
1467                    }
1468
1469                    // Avoid re-indenting a row that has already been indented by a
1470                    // previous selection, but still update this selection's column
1471                    // to reflect that indentation.
1472                    if let Some((last_indent_row, last_indent_len)) = last_indent {
1473                        if last_indent_row == selection.start.row {
1474                            selection.start.column += last_indent_len;
1475                            start_row += 1;
1476                        }
1477                        if last_indent_row == selection.end.row {
1478                            selection.end.column += last_indent_len;
1479                        }
1480                    }
1481
1482                    for row in start_row..end_row {
1483                        let indent_column = buffer.read(cx).indent_column_for_line(row) as usize;
1484                        let columns_to_next_tab_stop = tab_size - (indent_column % tab_size);
1485                        let row_start = Point::new(row, 0);
1486                        buffer.edit(
1487                            [row_start..row_start],
1488                            " ".repeat(columns_to_next_tab_stop),
1489                            cx,
1490                        );
1491
1492                        // Update this selection's endpoints to reflect the indentation.
1493                        if row == selection.start.row {
1494                            selection.start.column += columns_to_next_tab_stop as u32;
1495                        }
1496                        if row == selection.end.row {
1497                            selection.end.column += columns_to_next_tab_stop as u32;
1498                        }
1499
1500                        last_indent = Some((row, columns_to_next_tab_stop as u32));
1501                    }
1502                }
1503            }
1504        });
1505
1506        self.update_selections(selections, Some(Autoscroll::Fit), cx);
1507        self.end_transaction(cx);
1508    }
1509
1510    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
1511        self.start_transaction(cx);
1512        let tab_size = self.build_settings.borrow()(cx).tab_size;
1513        let selections = self.selections::<Point>(cx);
1514        let mut deletion_ranges = Vec::new();
1515        let mut last_outdent = None;
1516        {
1517            let buffer = self.buffer.read(cx).read(cx);
1518            for selection in &selections {
1519                let mut start_row = selection.start.row;
1520                let mut end_row = selection.end.row + 1;
1521
1522                // If a selection ends at the beginning of a line, don't indent
1523                // that last line.
1524                if selection.end.column == 0 {
1525                    end_row -= 1;
1526                }
1527
1528                // Avoid re-outdenting a row that has already been outdented by a
1529                // previous selection.
1530                if let Some(last_row) = last_outdent {
1531                    if last_row == selection.start.row {
1532                        start_row += 1;
1533                    }
1534                }
1535
1536                for row in start_row..end_row {
1537                    let column = buffer.indent_column_for_line(row) as usize;
1538                    if column > 0 {
1539                        let mut deletion_len = (column % tab_size) as u32;
1540                        if deletion_len == 0 {
1541                            deletion_len = tab_size as u32;
1542                        }
1543                        deletion_ranges.push(Point::new(row, 0)..Point::new(row, deletion_len));
1544                        last_outdent = Some(row);
1545                    }
1546                }
1547            }
1548        }
1549        self.buffer.update(cx, |buffer, cx| {
1550            buffer.edit(deletion_ranges, "", cx);
1551        });
1552
1553        self.update_selections(self.selections::<usize>(cx), Some(Autoscroll::Fit), cx);
1554        self.end_transaction(cx);
1555    }
1556
1557    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
1558        self.start_transaction(cx);
1559
1560        let selections = self.selections::<Point>(cx);
1561        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1562        let buffer = self.buffer.read(cx).snapshot(cx);
1563
1564        let mut row_delta = 0;
1565        let mut new_cursors = Vec::new();
1566        let mut edit_ranges = Vec::new();
1567        let mut selections = selections.iter().peekable();
1568        while let Some(selection) = selections.next() {
1569            let mut rows = selection.spanned_rows(false, &display_map).buffer_rows;
1570            let goal_display_column = selection.head().to_display_point(&display_map).column();
1571
1572            // Accumulate contiguous regions of rows that we want to delete.
1573            while let Some(next_selection) = selections.peek() {
1574                let next_rows = next_selection.spanned_rows(false, &display_map).buffer_rows;
1575                if next_rows.start <= rows.end {
1576                    rows.end = next_rows.end;
1577                    selections.next().unwrap();
1578                } else {
1579                    break;
1580                }
1581            }
1582
1583            let mut edit_start = Point::new(rows.start, 0).to_offset(&buffer);
1584            let edit_end;
1585            let cursor_buffer_row;
1586            if buffer.max_point().row >= rows.end {
1587                // If there's a line after the range, delete the \n from the end of the row range
1588                // and position the cursor on the next line.
1589                edit_end = Point::new(rows.end, 0).to_offset(&buffer);
1590                cursor_buffer_row = rows.start;
1591            } else {
1592                // If there isn't a line after the range, delete the \n from the line before the
1593                // start of the row range and position the cursor there.
1594                edit_start = edit_start.saturating_sub(1);
1595                edit_end = buffer.len();
1596                cursor_buffer_row = rows.start.saturating_sub(1);
1597            }
1598
1599            let mut cursor =
1600                Point::new(cursor_buffer_row - row_delta, 0).to_display_point(&display_map);
1601            *cursor.column_mut() =
1602                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
1603            row_delta += rows.len() as u32;
1604
1605            new_cursors.push((selection.id, cursor.to_point(&display_map)));
1606            edit_ranges.push(edit_start..edit_end);
1607        }
1608
1609        new_cursors.sort_unstable_by_key(|(_, point)| point.clone());
1610        let new_selections = new_cursors
1611            .into_iter()
1612            .map(|(id, cursor)| Selection {
1613                id,
1614                start: cursor,
1615                end: cursor,
1616                reversed: false,
1617                goal: SelectionGoal::None,
1618            })
1619            .collect();
1620        self.buffer
1621            .update(cx, |buffer, cx| buffer.edit(edit_ranges, "", cx));
1622        self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
1623        self.end_transaction(cx);
1624    }
1625
1626    pub fn duplicate_line(&mut self, _: &DuplicateLine, cx: &mut ViewContext<Self>) {
1627        self.start_transaction(cx);
1628
1629        let mut selections = self.selections::<Point>(cx);
1630        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1631        let buffer = &display_map.buffer_snapshot;
1632
1633        let mut edits = Vec::new();
1634        let mut selections_iter = selections.iter().peekable();
1635        while let Some(selection) = selections_iter.next() {
1636            // Avoid duplicating the same lines twice.
1637            let mut rows = selection.spanned_rows(false, &display_map).buffer_rows;
1638
1639            while let Some(next_selection) = selections_iter.peek() {
1640                let next_rows = next_selection.spanned_rows(false, &display_map).buffer_rows;
1641                if next_rows.start <= rows.end - 1 {
1642                    rows.end = next_rows.end;
1643                    selections_iter.next().unwrap();
1644                } else {
1645                    break;
1646                }
1647            }
1648
1649            // Copy the text from the selected row region and splice it at the start of the region.
1650            let start = Point::new(rows.start, 0);
1651            let end = Point::new(rows.end - 1, buffer.line_len(rows.end - 1));
1652            let text = buffer
1653                .text_for_range(start..end)
1654                .chain(Some("\n"))
1655                .collect::<String>();
1656            edits.push((start, text, rows.len() as u32));
1657        }
1658
1659        let mut edits_iter = edits.iter().peekable();
1660        let mut row_delta = 0;
1661        for selection in selections.iter_mut() {
1662            while let Some((point, _, line_count)) = edits_iter.peek() {
1663                if *point <= selection.start {
1664                    row_delta += line_count;
1665                    edits_iter.next();
1666                } else {
1667                    break;
1668                }
1669            }
1670            selection.start.row += row_delta;
1671            selection.end.row += row_delta;
1672        }
1673
1674        self.buffer.update(cx, |buffer, cx| {
1675            for (point, text, _) in edits.into_iter().rev() {
1676                buffer.edit(Some(point..point), text, cx);
1677            }
1678        });
1679
1680        self.update_selections(selections, Some(Autoscroll::Fit), cx);
1681        self.end_transaction(cx);
1682    }
1683
1684    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
1685        self.start_transaction(cx);
1686
1687        let selections = self.selections::<Point>(cx);
1688        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1689        let buffer = self.buffer.read(cx).snapshot(cx);
1690
1691        let mut edits = Vec::new();
1692        let mut new_selection_ranges = Vec::new();
1693        let mut old_folds = Vec::new();
1694        let mut new_folds = Vec::new();
1695
1696        let mut selections = selections.iter().peekable();
1697        let mut contiguous_selections = Vec::new();
1698        while let Some(selection) = selections.next() {
1699            // Accumulate contiguous regions of rows that we want to move.
1700            contiguous_selections.push(selection.point_range(&buffer));
1701            let SpannedRows {
1702                mut buffer_rows,
1703                mut display_rows,
1704            } = selection.spanned_rows(false, &display_map);
1705
1706            while let Some(next_selection) = selections.peek() {
1707                let SpannedRows {
1708                    buffer_rows: next_buffer_rows,
1709                    display_rows: next_display_rows,
1710                } = next_selection.spanned_rows(false, &display_map);
1711                if next_buffer_rows.start <= buffer_rows.end {
1712                    buffer_rows.end = next_buffer_rows.end;
1713                    display_rows.end = next_display_rows.end;
1714                    contiguous_selections.push(next_selection.point_range(&buffer));
1715                    selections.next().unwrap();
1716                } else {
1717                    break;
1718                }
1719            }
1720
1721            // Cut the text from the selected rows and paste it at the start of the previous line.
1722            if display_rows.start != 0 {
1723                let start = Point::new(buffer_rows.start, 0).to_offset(&buffer);
1724                let end = Point::new(buffer_rows.end - 1, buffer.line_len(buffer_rows.end - 1))
1725                    .to_offset(&buffer);
1726
1727                let prev_row_display_start = DisplayPoint::new(display_rows.start - 1, 0);
1728                let prev_row_buffer_start = display_map.prev_row_boundary(prev_row_display_start).1;
1729                let prev_row_buffer_start_offset = prev_row_buffer_start.to_offset(&buffer);
1730
1731                let mut text = String::new();
1732                text.extend(buffer.text_for_range(start..end));
1733                text.push('\n');
1734                edits.push((
1735                    prev_row_buffer_start_offset..prev_row_buffer_start_offset,
1736                    text,
1737                ));
1738                edits.push((start - 1..end, String::new()));
1739
1740                let row_delta = buffer_rows.start - prev_row_buffer_start.row;
1741
1742                // Move selections up.
1743                for range in &mut contiguous_selections {
1744                    range.start.row -= row_delta;
1745                    range.end.row -= row_delta;
1746                }
1747
1748                // Move folds up.
1749                old_folds.push(start..end);
1750                for fold in display_map.folds_in_range(start..end) {
1751                    let mut start = fold.start.to_point(&buffer);
1752                    let mut end = fold.end.to_point(&buffer);
1753                    start.row -= row_delta;
1754                    end.row -= row_delta;
1755                    new_folds.push(start..end);
1756                }
1757            }
1758
1759            new_selection_ranges.extend(contiguous_selections.drain(..));
1760        }
1761
1762        self.unfold_ranges(old_folds, cx);
1763        self.buffer.update(cx, |buffer, cx| {
1764            for (range, text) in edits.into_iter().rev() {
1765                buffer.edit(Some(range), text, cx);
1766            }
1767        });
1768        self.fold_ranges(new_folds, cx);
1769        self.select_ranges(new_selection_ranges, Some(Autoscroll::Fit), cx);
1770
1771        self.end_transaction(cx);
1772    }
1773
1774    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
1775        self.start_transaction(cx);
1776
1777        let selections = self.selections::<Point>(cx);
1778        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1779        let buffer = self.buffer.read(cx).snapshot(cx);
1780
1781        let mut edits = Vec::new();
1782        let mut new_selection_ranges = Vec::new();
1783        let mut old_folds = Vec::new();
1784        let mut new_folds = Vec::new();
1785
1786        let mut selections = selections.iter().peekable();
1787        let mut contiguous_selections = Vec::new();
1788        while let Some(selection) = selections.next() {
1789            // Accumulate contiguous regions of rows that we want to move.
1790            contiguous_selections.push(selection.point_range(&buffer));
1791            let SpannedRows {
1792                mut buffer_rows,
1793                mut display_rows,
1794            } = selection.spanned_rows(false, &display_map);
1795            while let Some(next_selection) = selections.peek() {
1796                let SpannedRows {
1797                    buffer_rows: next_buffer_rows,
1798                    display_rows: next_display_rows,
1799                } = next_selection.spanned_rows(false, &display_map);
1800                if next_buffer_rows.start <= buffer_rows.end {
1801                    buffer_rows.end = next_buffer_rows.end;
1802                    display_rows.end = next_display_rows.end;
1803                    contiguous_selections.push(next_selection.point_range(&buffer));
1804                    selections.next().unwrap();
1805                } else {
1806                    break;
1807                }
1808            }
1809
1810            // Cut the text from the selected rows and paste it at the end of the next line.
1811            if display_rows.end <= display_map.max_point().row() {
1812                let start = Point::new(buffer_rows.start, 0).to_offset(&buffer);
1813                let end = Point::new(buffer_rows.end - 1, buffer.line_len(buffer_rows.end - 1))
1814                    .to_offset(&buffer);
1815
1816                let next_row_display_end =
1817                    DisplayPoint::new(display_rows.end, display_map.line_len(display_rows.end));
1818                let next_row_buffer_end = display_map.next_row_boundary(next_row_display_end).1;
1819                let next_row_buffer_end_offset = next_row_buffer_end.to_offset(&buffer);
1820
1821                let mut text = String::new();
1822                text.push('\n');
1823                text.extend(buffer.text_for_range(start..end));
1824                edits.push((start..end + 1, String::new()));
1825                edits.push((next_row_buffer_end_offset..next_row_buffer_end_offset, text));
1826
1827                let row_delta = next_row_buffer_end.row - buffer_rows.end + 1;
1828
1829                // Move selections down.
1830                for range in &mut contiguous_selections {
1831                    range.start.row += row_delta;
1832                    range.end.row += row_delta;
1833                }
1834
1835                // Move folds down.
1836                old_folds.push(start..end);
1837                for fold in display_map.folds_in_range(start..end) {
1838                    let mut start = fold.start.to_point(&buffer);
1839                    let mut end = fold.end.to_point(&buffer);
1840                    start.row += row_delta;
1841                    end.row += row_delta;
1842                    new_folds.push(start..end);
1843                }
1844            }
1845
1846            new_selection_ranges.extend(contiguous_selections.drain(..));
1847        }
1848
1849        self.unfold_ranges(old_folds, cx);
1850        self.buffer.update(cx, |buffer, cx| {
1851            for (range, text) in edits.into_iter().rev() {
1852                buffer.edit(Some(range), text, cx);
1853            }
1854        });
1855        self.fold_ranges(new_folds, cx);
1856        self.select_ranges(new_selection_ranges, Some(Autoscroll::Fit), cx);
1857
1858        self.end_transaction(cx);
1859    }
1860
1861    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
1862        self.start_transaction(cx);
1863        let mut text = String::new();
1864        let mut selections = self.selections::<Point>(cx);
1865        let mut clipboard_selections = Vec::with_capacity(selections.len());
1866        {
1867            let buffer = self.buffer.read(cx).read(cx);
1868            let max_point = buffer.max_point();
1869            for selection in &mut selections {
1870                let is_entire_line = selection.is_empty();
1871                if is_entire_line {
1872                    selection.start = Point::new(selection.start.row, 0);
1873                    selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
1874                }
1875                let mut len = 0;
1876                for chunk in buffer.text_for_range(selection.start..selection.end) {
1877                    text.push_str(chunk);
1878                    len += chunk.len();
1879                }
1880                clipboard_selections.push(ClipboardSelection {
1881                    len,
1882                    is_entire_line,
1883                });
1884            }
1885        }
1886        self.update_selections(selections, Some(Autoscroll::Fit), cx);
1887        self.insert("", cx);
1888        self.end_transaction(cx);
1889
1890        cx.as_mut()
1891            .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
1892    }
1893
1894    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
1895        let selections = self.selections::<Point>(cx);
1896        let mut text = String::new();
1897        let mut clipboard_selections = Vec::with_capacity(selections.len());
1898        {
1899            let buffer = self.buffer.read(cx).read(cx);
1900            let max_point = buffer.max_point();
1901            for selection in selections.iter() {
1902                let mut start = selection.start;
1903                let mut end = selection.end;
1904                let is_entire_line = selection.is_empty();
1905                if is_entire_line {
1906                    start = Point::new(start.row, 0);
1907                    end = cmp::min(max_point, Point::new(start.row + 1, 0));
1908                }
1909                let mut len = 0;
1910                for chunk in buffer.text_for_range(start..end) {
1911                    text.push_str(chunk);
1912                    len += chunk.len();
1913                }
1914                clipboard_selections.push(ClipboardSelection {
1915                    len,
1916                    is_entire_line,
1917                });
1918            }
1919        }
1920
1921        cx.as_mut()
1922            .write_to_clipboard(ClipboardItem::new(text).with_metadata(clipboard_selections));
1923    }
1924
1925    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
1926        if let Some(item) = cx.as_mut().read_from_clipboard() {
1927            let clipboard_text = item.text();
1928            if let Some(mut clipboard_selections) = item.metadata::<Vec<ClipboardSelection>>() {
1929                let mut selections = self.selections::<usize>(cx);
1930                let all_selections_were_entire_line =
1931                    clipboard_selections.iter().all(|s| s.is_entire_line);
1932                if clipboard_selections.len() != selections.len() {
1933                    clipboard_selections.clear();
1934                }
1935
1936                let mut delta = 0_isize;
1937                let mut start_offset = 0;
1938                for (i, selection) in selections.iter_mut().enumerate() {
1939                    let to_insert;
1940                    let entire_line;
1941                    if let Some(clipboard_selection) = clipboard_selections.get(i) {
1942                        let end_offset = start_offset + clipboard_selection.len;
1943                        to_insert = &clipboard_text[start_offset..end_offset];
1944                        entire_line = clipboard_selection.is_entire_line;
1945                        start_offset = end_offset
1946                    } else {
1947                        to_insert = clipboard_text.as_str();
1948                        entire_line = all_selections_were_entire_line;
1949                    }
1950
1951                    selection.start = (selection.start as isize + delta) as usize;
1952                    selection.end = (selection.end as isize + delta) as usize;
1953
1954                    self.buffer.update(cx, |buffer, cx| {
1955                        // If the corresponding selection was empty when this slice of the
1956                        // clipboard text was written, then the entire line containing the
1957                        // selection was copied. If this selection is also currently empty,
1958                        // then paste the line before the current line of the buffer.
1959                        let range = if selection.is_empty() && entire_line {
1960                            let column = selection.start.to_point(&buffer.read(cx)).column as usize;
1961                            let line_start = selection.start - column;
1962                            line_start..line_start
1963                        } else {
1964                            selection.start..selection.end
1965                        };
1966
1967                        delta += to_insert.len() as isize - range.len() as isize;
1968                        buffer.edit([range], to_insert, cx);
1969                        selection.start += to_insert.len();
1970                        selection.end = selection.start;
1971                    });
1972                }
1973                self.update_selections(selections, Some(Autoscroll::Fit), cx);
1974            } else {
1975                self.insert(clipboard_text, cx);
1976            }
1977        }
1978    }
1979
1980    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
1981        self.buffer.update(cx, |buffer, cx| buffer.undo(cx));
1982        self.request_autoscroll(Autoscroll::Fit, cx);
1983    }
1984
1985    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
1986        self.buffer.update(cx, |buffer, cx| buffer.redo(cx));
1987        self.request_autoscroll(Autoscroll::Fit, cx);
1988    }
1989
1990    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
1991        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
1992        let mut selections = self.selections::<Point>(cx);
1993        for selection in &mut selections {
1994            let start = selection.start.to_display_point(&display_map);
1995            let end = selection.end.to_display_point(&display_map);
1996
1997            if start != end {
1998                selection.end = selection.start.clone();
1999            } else {
2000                let cursor = movement::left(&display_map, start)
2001                    .unwrap()
2002                    .to_point(&display_map);
2003                selection.start = cursor.clone();
2004                selection.end = cursor;
2005            }
2006            selection.reversed = false;
2007            selection.goal = SelectionGoal::None;
2008        }
2009        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2010    }
2011
2012    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
2013        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2014        let mut selections = self.selections::<Point>(cx);
2015        for selection in &mut selections {
2016            let head = selection.head().to_display_point(&display_map);
2017            let cursor = movement::left(&display_map, head)
2018                .unwrap()
2019                .to_point(&display_map);
2020            selection.set_head(cursor);
2021            selection.goal = SelectionGoal::None;
2022        }
2023        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2024    }
2025
2026    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
2027        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2028        let mut selections = self.selections::<Point>(cx);
2029        for selection in &mut selections {
2030            let start = selection.start.to_display_point(&display_map);
2031            let end = selection.end.to_display_point(&display_map);
2032
2033            if start != end {
2034                selection.start = selection.end.clone();
2035            } else {
2036                let cursor = movement::right(&display_map, end)
2037                    .unwrap()
2038                    .to_point(&display_map);
2039                selection.start = cursor;
2040                selection.end = cursor;
2041            }
2042            selection.reversed = false;
2043            selection.goal = SelectionGoal::None;
2044        }
2045        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2046    }
2047
2048    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
2049        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2050        let mut selections = self.selections::<Point>(cx);
2051        for selection in &mut selections {
2052            let head = selection.head().to_display_point(&display_map);
2053            let cursor = movement::right(&display_map, head)
2054                .unwrap()
2055                .to_point(&display_map);
2056            selection.set_head(cursor);
2057            selection.goal = SelectionGoal::None;
2058        }
2059        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2060    }
2061
2062    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
2063        if matches!(self.mode, EditorMode::SingleLine) {
2064            cx.propagate_action();
2065            return;
2066        }
2067
2068        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2069        let mut selections = self.selections::<Point>(cx);
2070        for selection in &mut selections {
2071            let start = selection.start.to_display_point(&display_map);
2072            let end = selection.end.to_display_point(&display_map);
2073            if start != end {
2074                selection.goal = SelectionGoal::None;
2075            }
2076
2077            let (start, goal) = movement::up(&display_map, start, selection.goal).unwrap();
2078            let cursor = start.to_point(&display_map);
2079            selection.start = cursor;
2080            selection.end = cursor;
2081            selection.goal = goal;
2082            selection.reversed = false;
2083        }
2084        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2085    }
2086
2087    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
2088        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2089        let mut selections = self.selections::<Point>(cx);
2090        for selection in &mut selections {
2091            let head = selection.head().to_display_point(&display_map);
2092            let (head, goal) = movement::up(&display_map, head, selection.goal).unwrap();
2093            let cursor = head.to_point(&display_map);
2094            selection.set_head(cursor);
2095            selection.goal = goal;
2096        }
2097        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2098    }
2099
2100    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
2101        if matches!(self.mode, EditorMode::SingleLine) {
2102            cx.propagate_action();
2103            return;
2104        }
2105
2106        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2107        let mut selections = self.selections::<Point>(cx);
2108        for selection in &mut selections {
2109            let start = selection.start.to_display_point(&display_map);
2110            let end = selection.end.to_display_point(&display_map);
2111            if start != end {
2112                selection.goal = SelectionGoal::None;
2113            }
2114
2115            let (start, goal) = movement::down(&display_map, end, selection.goal).unwrap();
2116            let cursor = start.to_point(&display_map);
2117            selection.start = cursor;
2118            selection.end = cursor;
2119            selection.goal = goal;
2120            selection.reversed = false;
2121        }
2122        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2123    }
2124
2125    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
2126        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2127        let mut selections = self.selections::<Point>(cx);
2128        for selection in &mut selections {
2129            let head = selection.head().to_display_point(&display_map);
2130            let (head, goal) = movement::down(&display_map, head, selection.goal).unwrap();
2131            let cursor = head.to_point(&display_map);
2132            selection.set_head(cursor);
2133            selection.goal = goal;
2134        }
2135        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2136    }
2137
2138    pub fn move_to_previous_word_boundary(
2139        &mut self,
2140        _: &MoveToPreviousWordBoundary,
2141        cx: &mut ViewContext<Self>,
2142    ) {
2143        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2144        let mut selections = self.selections::<Point>(cx);
2145        for selection in &mut selections {
2146            let head = selection.head().to_display_point(&display_map);
2147            let cursor = movement::prev_word_boundary(&display_map, head).to_point(&display_map);
2148            selection.start = cursor.clone();
2149            selection.end = cursor;
2150            selection.reversed = false;
2151            selection.goal = SelectionGoal::None;
2152        }
2153        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2154    }
2155
2156    pub fn select_to_previous_word_boundary(
2157        &mut self,
2158        _: &SelectToPreviousWordBoundary,
2159        cx: &mut ViewContext<Self>,
2160    ) {
2161        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2162        let mut selections = self.selections::<Point>(cx);
2163        for selection in &mut selections {
2164            let head = selection.head().to_display_point(&display_map);
2165            let cursor = movement::prev_word_boundary(&display_map, head).to_point(&display_map);
2166            selection.set_head(cursor);
2167            selection.goal = SelectionGoal::None;
2168        }
2169        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2170    }
2171
2172    pub fn delete_to_previous_word_boundary(
2173        &mut self,
2174        _: &DeleteToPreviousWordBoundary,
2175        cx: &mut ViewContext<Self>,
2176    ) {
2177        self.start_transaction(cx);
2178        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2179        let mut selections = self.selections::<Point>(cx);
2180        for selection in &mut selections {
2181            if selection.is_empty() {
2182                let head = selection.head().to_display_point(&display_map);
2183                let cursor =
2184                    movement::prev_word_boundary(&display_map, head).to_point(&display_map);
2185                selection.set_head(cursor);
2186                selection.goal = SelectionGoal::None;
2187            }
2188        }
2189        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2190        self.insert("", cx);
2191        self.end_transaction(cx);
2192    }
2193
2194    pub fn move_to_next_word_boundary(
2195        &mut self,
2196        _: &MoveToNextWordBoundary,
2197        cx: &mut ViewContext<Self>,
2198    ) {
2199        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2200        let mut selections = self.selections::<Point>(cx);
2201        for selection in &mut selections {
2202            let head = selection.head().to_display_point(&display_map);
2203            let cursor = movement::next_word_boundary(&display_map, head).to_point(&display_map);
2204            selection.start = cursor;
2205            selection.end = cursor;
2206            selection.reversed = false;
2207            selection.goal = SelectionGoal::None;
2208        }
2209        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2210    }
2211
2212    pub fn select_to_next_word_boundary(
2213        &mut self,
2214        _: &SelectToNextWordBoundary,
2215        cx: &mut ViewContext<Self>,
2216    ) {
2217        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2218        let mut selections = self.selections::<Point>(cx);
2219        for selection in &mut selections {
2220            let head = selection.head().to_display_point(&display_map);
2221            let cursor = movement::next_word_boundary(&display_map, head).to_point(&display_map);
2222            selection.set_head(cursor);
2223            selection.goal = SelectionGoal::None;
2224        }
2225        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2226    }
2227
2228    pub fn delete_to_next_word_boundary(
2229        &mut self,
2230        _: &DeleteToNextWordBoundary,
2231        cx: &mut ViewContext<Self>,
2232    ) {
2233        self.start_transaction(cx);
2234        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2235        let mut selections = self.selections::<Point>(cx);
2236        for selection in &mut selections {
2237            if selection.is_empty() {
2238                let head = selection.head().to_display_point(&display_map);
2239                let cursor =
2240                    movement::next_word_boundary(&display_map, head).to_point(&display_map);
2241                selection.set_head(cursor);
2242                selection.goal = SelectionGoal::None;
2243            }
2244        }
2245        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2246        self.insert("", cx);
2247        self.end_transaction(cx);
2248    }
2249
2250    pub fn move_to_beginning_of_line(
2251        &mut self,
2252        _: &MoveToBeginningOfLine,
2253        cx: &mut ViewContext<Self>,
2254    ) {
2255        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2256        let mut selections = self.selections::<Point>(cx);
2257        for selection in &mut selections {
2258            let head = selection.head().to_display_point(&display_map);
2259            let new_head = movement::line_beginning(&display_map, head, true);
2260            let cursor = new_head.to_point(&display_map);
2261            selection.start = cursor;
2262            selection.end = cursor;
2263            selection.reversed = false;
2264            selection.goal = SelectionGoal::None;
2265        }
2266        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2267    }
2268
2269    pub fn select_to_beginning_of_line(
2270        &mut self,
2271        SelectToBeginningOfLine(toggle_indent): &SelectToBeginningOfLine,
2272        cx: &mut ViewContext<Self>,
2273    ) {
2274        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2275        let mut selections = self.selections::<Point>(cx);
2276        for selection in &mut selections {
2277            let head = selection.head().to_display_point(&display_map);
2278            let new_head = movement::line_beginning(&display_map, head, *toggle_indent);
2279            selection.set_head(new_head.to_point(&display_map));
2280            selection.goal = SelectionGoal::None;
2281        }
2282        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2283    }
2284
2285    pub fn delete_to_beginning_of_line(
2286        &mut self,
2287        _: &DeleteToBeginningOfLine,
2288        cx: &mut ViewContext<Self>,
2289    ) {
2290        self.start_transaction(cx);
2291        self.select_to_beginning_of_line(&SelectToBeginningOfLine(false), cx);
2292        self.backspace(&Backspace, cx);
2293        self.end_transaction(cx);
2294    }
2295
2296    pub fn move_to_end_of_line(&mut self, _: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
2297        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2298        let mut selections = self.selections::<Point>(cx);
2299        {
2300            for selection in &mut selections {
2301                let head = selection.head().to_display_point(&display_map);
2302                let new_head = movement::line_end(&display_map, head);
2303                let anchor = new_head.to_point(&display_map);
2304                selection.start = anchor.clone();
2305                selection.end = anchor;
2306                selection.reversed = false;
2307                selection.goal = SelectionGoal::None;
2308            }
2309        }
2310        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2311    }
2312
2313    pub fn select_to_end_of_line(&mut self, _: &SelectToEndOfLine, cx: &mut ViewContext<Self>) {
2314        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2315        let mut selections = self.selections::<Point>(cx);
2316        for selection in &mut selections {
2317            let head = selection.head().to_display_point(&display_map);
2318            let new_head = movement::line_end(&display_map, head);
2319            selection.set_head(new_head.to_point(&display_map));
2320            selection.goal = SelectionGoal::None;
2321        }
2322        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2323    }
2324
2325    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
2326        self.start_transaction(cx);
2327        self.select_to_end_of_line(&SelectToEndOfLine, cx);
2328        self.delete(&Delete, cx);
2329        self.end_transaction(cx);
2330    }
2331
2332    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
2333        self.start_transaction(cx);
2334        self.select_to_end_of_line(&SelectToEndOfLine, cx);
2335        self.cut(&Cut, cx);
2336        self.end_transaction(cx);
2337    }
2338
2339    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
2340        let selection = Selection {
2341            id: post_inc(&mut self.next_selection_id),
2342            start: 0,
2343            end: 0,
2344            reversed: false,
2345            goal: SelectionGoal::None,
2346        };
2347        self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2348    }
2349
2350    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
2351        let mut selection = self.selections::<Point>(cx).last().unwrap().clone();
2352        selection.set_head(Point::zero());
2353        self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2354    }
2355
2356    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
2357        let cursor = self.buffer.read(cx).read(cx).len();
2358        let selection = Selection {
2359            id: post_inc(&mut self.next_selection_id),
2360            start: cursor,
2361            end: cursor,
2362            reversed: false,
2363            goal: SelectionGoal::None,
2364        };
2365        self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2366    }
2367
2368    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
2369        let mut selection = self.selections::<usize>(cx).first().unwrap().clone();
2370        selection.set_head(self.buffer.read(cx).read(cx).len());
2371        self.update_selections(vec![selection], Some(Autoscroll::Fit), cx);
2372    }
2373
2374    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
2375        let selection = Selection {
2376            id: post_inc(&mut self.next_selection_id),
2377            start: 0,
2378            end: self.buffer.read(cx).read(cx).len(),
2379            reversed: false,
2380            goal: SelectionGoal::None,
2381        };
2382        self.update_selections(vec![selection], None, cx);
2383    }
2384
2385    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
2386        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2387        let mut selections = self.selections::<Point>(cx);
2388        let max_point = display_map.buffer_snapshot.max_point();
2389        for selection in &mut selections {
2390            let rows = selection.spanned_rows(true, &display_map).buffer_rows;
2391            selection.start = Point::new(rows.start, 0);
2392            selection.end = cmp::min(max_point, Point::new(rows.end, 0));
2393            selection.reversed = false;
2394        }
2395        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2396    }
2397
2398    pub fn split_selection_into_lines(
2399        &mut self,
2400        _: &SplitSelectionIntoLines,
2401        cx: &mut ViewContext<Self>,
2402    ) {
2403        let mut to_unfold = Vec::new();
2404        let mut new_selections = Vec::new();
2405        {
2406            let selections = self.selections::<Point>(cx);
2407            let buffer = self.buffer.read(cx).read(cx);
2408            for selection in selections {
2409                for row in selection.start.row..selection.end.row {
2410                    let cursor = Point::new(row, buffer.line_len(row));
2411                    new_selections.push(Selection {
2412                        id: post_inc(&mut self.next_selection_id),
2413                        start: cursor,
2414                        end: cursor,
2415                        reversed: false,
2416                        goal: SelectionGoal::None,
2417                    });
2418                }
2419                new_selections.push(Selection {
2420                    id: selection.id,
2421                    start: selection.end,
2422                    end: selection.end,
2423                    reversed: false,
2424                    goal: SelectionGoal::None,
2425                });
2426                to_unfold.push(selection.start..selection.end);
2427            }
2428        }
2429        self.unfold_ranges(to_unfold, cx);
2430        self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2431    }
2432
2433    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
2434        self.add_selection(true, cx);
2435    }
2436
2437    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
2438        self.add_selection(false, cx);
2439    }
2440
2441    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
2442        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2443        let mut selections = self.selections::<Point>(cx);
2444        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
2445            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
2446            let range = oldest_selection.display_range(&display_map).sorted();
2447            let columns = cmp::min(range.start.column(), range.end.column())
2448                ..cmp::max(range.start.column(), range.end.column());
2449
2450            selections.clear();
2451            let mut stack = Vec::new();
2452            for row in range.start.row()..=range.end.row() {
2453                if let Some(selection) = self.build_columnar_selection(
2454                    &display_map,
2455                    row,
2456                    &columns,
2457                    oldest_selection.reversed,
2458                ) {
2459                    stack.push(selection.id);
2460                    selections.push(selection);
2461                }
2462            }
2463
2464            if above {
2465                stack.reverse();
2466            }
2467
2468            AddSelectionsState { above, stack }
2469        });
2470
2471        let last_added_selection = *state.stack.last().unwrap();
2472        let mut new_selections = Vec::new();
2473        if above == state.above {
2474            let end_row = if above {
2475                0
2476            } else {
2477                display_map.max_point().row()
2478            };
2479
2480            'outer: for selection in selections {
2481                if selection.id == last_added_selection {
2482                    let range = selection.display_range(&display_map).sorted();
2483                    debug_assert_eq!(range.start.row(), range.end.row());
2484                    let mut row = range.start.row();
2485                    let columns = if let SelectionGoal::ColumnRange { start, end } = selection.goal
2486                    {
2487                        start..end
2488                    } else {
2489                        cmp::min(range.start.column(), range.end.column())
2490                            ..cmp::max(range.start.column(), range.end.column())
2491                    };
2492
2493                    while row != end_row {
2494                        if above {
2495                            row -= 1;
2496                        } else {
2497                            row += 1;
2498                        }
2499
2500                        if let Some(new_selection) = self.build_columnar_selection(
2501                            &display_map,
2502                            row,
2503                            &columns,
2504                            selection.reversed,
2505                        ) {
2506                            state.stack.push(new_selection.id);
2507                            if above {
2508                                new_selections.push(new_selection);
2509                                new_selections.push(selection);
2510                            } else {
2511                                new_selections.push(selection);
2512                                new_selections.push(new_selection);
2513                            }
2514
2515                            continue 'outer;
2516                        }
2517                    }
2518                }
2519
2520                new_selections.push(selection);
2521            }
2522        } else {
2523            new_selections = selections;
2524            new_selections.retain(|s| s.id != last_added_selection);
2525            state.stack.pop();
2526        }
2527
2528        self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2529        if state.stack.len() > 1 {
2530            self.add_selections_state = Some(state);
2531        }
2532    }
2533
2534    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) {
2535        let replace_newest = action.0;
2536        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2537        let buffer = &display_map.buffer_snapshot;
2538        let mut selections = self.selections::<usize>(cx);
2539        if let Some(mut select_next_state) = self.select_next_state.take() {
2540            let query = &select_next_state.query;
2541            if !select_next_state.done {
2542                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
2543                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
2544                let mut next_selected_range = None;
2545
2546                let bytes_after_last_selection =
2547                    buffer.bytes_in_range(last_selection.end..buffer.len());
2548                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
2549                let query_matches = query
2550                    .stream_find_iter(bytes_after_last_selection)
2551                    .map(|result| (last_selection.end, result))
2552                    .chain(
2553                        query
2554                            .stream_find_iter(bytes_before_first_selection)
2555                            .map(|result| (0, result)),
2556                    );
2557                for (start_offset, query_match) in query_matches {
2558                    let query_match = query_match.unwrap(); // can only fail due to I/O
2559                    let offset_range =
2560                        start_offset + query_match.start()..start_offset + query_match.end();
2561                    let display_range = offset_range.start.to_display_point(&display_map)
2562                        ..offset_range.end.to_display_point(&display_map);
2563
2564                    if !select_next_state.wordwise
2565                        || (!movement::is_inside_word(&display_map, display_range.start)
2566                            && !movement::is_inside_word(&display_map, display_range.end))
2567                    {
2568                        next_selected_range = Some(offset_range);
2569                        break;
2570                    }
2571                }
2572
2573                if let Some(next_selected_range) = next_selected_range {
2574                    if replace_newest {
2575                        if let Some(newest_id) =
2576                            selections.iter().max_by_key(|s| s.id).map(|s| s.id)
2577                        {
2578                            selections.retain(|s| s.id != newest_id);
2579                        }
2580                    }
2581                    selections.push(Selection {
2582                        id: post_inc(&mut self.next_selection_id),
2583                        start: next_selected_range.start,
2584                        end: next_selected_range.end,
2585                        reversed: false,
2586                        goal: SelectionGoal::None,
2587                    });
2588                    selections.sort_unstable_by_key(|s| s.start);
2589                    self.update_selections(selections, Some(Autoscroll::Newest), cx);
2590                } else {
2591                    select_next_state.done = true;
2592                }
2593            }
2594
2595            self.select_next_state = Some(select_next_state);
2596        } else if selections.len() == 1 {
2597            let selection = selections.last_mut().unwrap();
2598            if selection.start == selection.end {
2599                let word_range = movement::surrounding_word(
2600                    &display_map,
2601                    selection.start.to_display_point(&display_map),
2602                );
2603                selection.start = word_range.start.to_offset(&display_map, Bias::Left);
2604                selection.end = word_range.end.to_offset(&display_map, Bias::Left);
2605                selection.goal = SelectionGoal::None;
2606                selection.reversed = false;
2607
2608                let query = buffer
2609                    .text_for_range(selection.start..selection.end)
2610                    .collect::<String>();
2611                let select_state = SelectNextState {
2612                    query: AhoCorasick::new_auto_configured(&[query]),
2613                    wordwise: true,
2614                    done: false,
2615                };
2616                self.update_selections(selections, Some(Autoscroll::Newest), cx);
2617                self.select_next_state = Some(select_state);
2618            } else {
2619                let query = buffer
2620                    .text_for_range(selection.start..selection.end)
2621                    .collect::<String>();
2622                self.select_next_state = Some(SelectNextState {
2623                    query: AhoCorasick::new_auto_configured(&[query]),
2624                    wordwise: false,
2625                    done: false,
2626                });
2627                self.select_next(action, cx);
2628            }
2629        }
2630    }
2631
2632    pub fn toggle_comments(&mut self, _: &ToggleComments, cx: &mut ViewContext<Self>) {
2633        // Get the line comment prefix. Split its trailing whitespace into a separate string,
2634        // as that portion won't be used for detecting if a line is a comment.
2635        let full_comment_prefix =
2636            if let Some(prefix) = self.language(cx).and_then(|l| l.line_comment_prefix()) {
2637                prefix.to_string()
2638            } else {
2639                return;
2640            };
2641        let comment_prefix = full_comment_prefix.trim_end_matches(' ');
2642        let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
2643
2644        self.start_transaction(cx);
2645        let mut selections = self.selections::<Point>(cx);
2646        let mut all_selection_lines_are_comments = true;
2647        let mut edit_ranges = Vec::new();
2648        let mut last_toggled_row = None;
2649        self.buffer.update(cx, |buffer, cx| {
2650            for selection in &mut selections {
2651                edit_ranges.clear();
2652                let snapshot = buffer.snapshot(cx);
2653
2654                let end_row =
2655                    if selection.end.row > selection.start.row && selection.end.column == 0 {
2656                        selection.end.row
2657                    } else {
2658                        selection.end.row + 1
2659                    };
2660
2661                for row in selection.start.row..end_row {
2662                    // If multiple selections contain a given row, avoid processing that
2663                    // row more than once.
2664                    if last_toggled_row == Some(row) {
2665                        continue;
2666                    } else {
2667                        last_toggled_row = Some(row);
2668                    }
2669
2670                    if snapshot.is_line_blank(row) {
2671                        continue;
2672                    }
2673
2674                    let start = Point::new(row, snapshot.indent_column_for_line(row));
2675                    let mut line_bytes = snapshot
2676                        .bytes_in_range(start..snapshot.max_point())
2677                        .flatten()
2678                        .copied();
2679
2680                    // If this line currently begins with the line comment prefix, then record
2681                    // the range containing the prefix.
2682                    if all_selection_lines_are_comments
2683                        && line_bytes
2684                            .by_ref()
2685                            .take(comment_prefix.len())
2686                            .eq(comment_prefix.bytes())
2687                    {
2688                        // Include any whitespace that matches the comment prefix.
2689                        let matching_whitespace_len = line_bytes
2690                            .zip(comment_prefix_whitespace.bytes())
2691                            .take_while(|(a, b)| a == b)
2692                            .count() as u32;
2693                        let end = Point::new(
2694                            row,
2695                            start.column + comment_prefix.len() as u32 + matching_whitespace_len,
2696                        );
2697                        edit_ranges.push(start..end);
2698                    }
2699                    // If this line does not begin with the line comment prefix, then record
2700                    // the position where the prefix should be inserted.
2701                    else {
2702                        all_selection_lines_are_comments = false;
2703                        edit_ranges.push(start..start);
2704                    }
2705                }
2706
2707                if !edit_ranges.is_empty() {
2708                    if all_selection_lines_are_comments {
2709                        buffer.edit(edit_ranges.iter().cloned(), "", cx);
2710                    } else {
2711                        let min_column = edit_ranges.iter().map(|r| r.start.column).min().unwrap();
2712                        let edit_ranges = edit_ranges.iter().map(|range| {
2713                            let position = Point::new(range.start.row, min_column);
2714                            position..position
2715                        });
2716                        buffer.edit(edit_ranges, &full_comment_prefix, cx);
2717                    }
2718                }
2719            }
2720        });
2721
2722        self.update_selections(self.selections::<usize>(cx), Some(Autoscroll::Fit), cx);
2723        self.end_transaction(cx);
2724    }
2725
2726    pub fn select_larger_syntax_node(
2727        &mut self,
2728        _: &SelectLargerSyntaxNode,
2729        cx: &mut ViewContext<Self>,
2730    ) {
2731        let old_selections = self.selections::<usize>(cx).into_boxed_slice();
2732        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2733        let buffer = self.buffer.read(cx).snapshot(cx);
2734
2735        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
2736        let mut selected_larger_node = false;
2737        let mut new_selections = old_selections
2738            .iter()
2739            .map(|selection| {
2740                let old_range = selection.start..selection.end;
2741                let mut new_range = old_range.clone();
2742                while let Some(containing_range) =
2743                    buffer.range_for_syntax_ancestor(new_range.clone())
2744                {
2745                    new_range = containing_range;
2746                    if !display_map.intersects_fold(new_range.start)
2747                        && !display_map.intersects_fold(new_range.end)
2748                    {
2749                        break;
2750                    }
2751                }
2752
2753                selected_larger_node |= new_range != old_range;
2754                Selection {
2755                    id: selection.id,
2756                    start: new_range.start,
2757                    end: new_range.end,
2758                    goal: SelectionGoal::None,
2759                    reversed: selection.reversed,
2760                }
2761            })
2762            .collect::<Vec<_>>();
2763
2764        if selected_larger_node {
2765            stack.push(old_selections);
2766            new_selections.sort_unstable_by_key(|selection| selection.start);
2767            self.update_selections(new_selections, Some(Autoscroll::Fit), cx);
2768        }
2769        self.select_larger_syntax_node_stack = stack;
2770    }
2771
2772    pub fn select_smaller_syntax_node(
2773        &mut self,
2774        _: &SelectSmallerSyntaxNode,
2775        cx: &mut ViewContext<Self>,
2776    ) {
2777        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
2778        if let Some(selections) = stack.pop() {
2779            self.update_selections(selections.to_vec(), Some(Autoscroll::Fit), cx);
2780        }
2781        self.select_larger_syntax_node_stack = stack;
2782    }
2783
2784    pub fn move_to_enclosing_bracket(
2785        &mut self,
2786        _: &MoveToEnclosingBracket,
2787        cx: &mut ViewContext<Self>,
2788    ) {
2789        let mut selections = self.selections::<usize>(cx);
2790        let buffer = self.buffer.read(cx).snapshot(cx);
2791        for selection in &mut selections {
2792            if let Some((open_range, close_range)) =
2793                buffer.enclosing_bracket_ranges(selection.start..selection.end)
2794            {
2795                let close_range = close_range.to_inclusive();
2796                let destination = if close_range.contains(&selection.start)
2797                    && close_range.contains(&selection.end)
2798                {
2799                    open_range.end
2800                } else {
2801                    *close_range.start()
2802                };
2803                selection.start = destination;
2804                selection.end = destination;
2805            }
2806        }
2807
2808        self.update_selections(selections, Some(Autoscroll::Fit), cx);
2809    }
2810
2811    pub fn show_next_diagnostic(&mut self, _: &ShowNextDiagnostic, cx: &mut ViewContext<Self>) {
2812        let buffer = self.buffer.read(cx).snapshot(cx);
2813        let selection = self.newest_selection::<usize>(cx);
2814        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
2815            active_diagnostics
2816                .primary_range
2817                .to_offset(&buffer)
2818                .to_inclusive()
2819        });
2820        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
2821            if active_primary_range.contains(&selection.head()) {
2822                *active_primary_range.end()
2823            } else {
2824                selection.head()
2825            }
2826        } else {
2827            selection.head()
2828        };
2829
2830        loop {
2831            let next_group = buffer
2832                .diagnostics_in_range::<_, usize>(search_start..buffer.len())
2833                .find_map(|entry| {
2834                    if entry.diagnostic.is_primary
2835                        && !entry.range.is_empty()
2836                        && Some(entry.range.end) != active_primary_range.as_ref().map(|r| *r.end())
2837                    {
2838                        Some((entry.range, entry.diagnostic.group_id))
2839                    } else {
2840                        None
2841                    }
2842                });
2843
2844            if let Some((primary_range, group_id)) = next_group {
2845                self.activate_diagnostics(group_id, cx);
2846                self.update_selections(
2847                    vec![Selection {
2848                        id: selection.id,
2849                        start: primary_range.start,
2850                        end: primary_range.start,
2851                        reversed: false,
2852                        goal: SelectionGoal::None,
2853                    }],
2854                    Some(Autoscroll::Center),
2855                    cx,
2856                );
2857                break;
2858            } else if search_start == 0 {
2859                break;
2860            } else {
2861                // Cycle around to the start of the buffer.
2862                search_start = 0;
2863            }
2864        }
2865    }
2866
2867    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
2868        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
2869            let buffer = self.buffer.read(cx).snapshot(cx);
2870            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
2871            let is_valid = buffer
2872                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
2873                .any(|entry| {
2874                    entry.diagnostic.is_primary
2875                        && !entry.range.is_empty()
2876                        && entry.range.start == primary_range_start
2877                        && entry.diagnostic.message == active_diagnostics.primary_message
2878                });
2879
2880            if is_valid != active_diagnostics.is_valid {
2881                active_diagnostics.is_valid = is_valid;
2882                let mut new_styles = HashMap::new();
2883                for (block_id, diagnostic) in &active_diagnostics.blocks {
2884                    let build_settings = self.build_settings.clone();
2885                    let diagnostic = diagnostic.clone();
2886                    new_styles.insert(*block_id, move |cx: &BlockContext| {
2887                        let diagnostic = diagnostic.clone();
2888                        let settings = build_settings.borrow()(cx.cx);
2889                        render_diagnostic(diagnostic, &settings.style, is_valid, cx.anchor_x)
2890                    });
2891                }
2892                self.display_map
2893                    .update(cx, |display_map, _| display_map.replace_blocks(new_styles));
2894            }
2895        }
2896    }
2897
2898    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
2899        self.dismiss_diagnostics(cx);
2900        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
2901            let buffer = self.buffer.read(cx).snapshot(cx);
2902
2903            let mut primary_range = None;
2904            let mut primary_message = None;
2905            let mut group_end = Point::zero();
2906            let diagnostic_group = buffer
2907                .diagnostic_group::<Point>(group_id)
2908                .map(|entry| {
2909                    if entry.range.end > group_end {
2910                        group_end = entry.range.end;
2911                    }
2912                    if entry.diagnostic.is_primary {
2913                        primary_range = Some(entry.range.clone());
2914                        primary_message = Some(entry.diagnostic.message.clone());
2915                    }
2916                    entry
2917                })
2918                .collect::<Vec<_>>();
2919            let primary_range = primary_range.unwrap();
2920            let primary_message = primary_message.unwrap();
2921            let primary_range =
2922                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
2923
2924            let blocks = display_map
2925                .insert_blocks(
2926                    diagnostic_group.iter().map(|entry| {
2927                        let build_settings = self.build_settings.clone();
2928                        let diagnostic = entry.diagnostic.clone();
2929                        let message_height = diagnostic.message.lines().count() as u8;
2930
2931                        BlockProperties {
2932                            position: entry.range.start,
2933                            height: message_height,
2934                            render: Arc::new(move |cx| {
2935                                let settings = build_settings.borrow()(cx.cx);
2936                                let diagnostic = diagnostic.clone();
2937                                render_diagnostic(diagnostic, &settings.style, true, cx.anchor_x)
2938                            }),
2939                            disposition: BlockDisposition::Below,
2940                        }
2941                    }),
2942                    cx,
2943                )
2944                .into_iter()
2945                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
2946                .collect();
2947
2948            Some(ActiveDiagnosticGroup {
2949                primary_range,
2950                primary_message,
2951                blocks,
2952                is_valid: true,
2953            })
2954        });
2955    }
2956
2957    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
2958        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
2959            self.display_map.update(cx, |display_map, cx| {
2960                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
2961            });
2962            cx.notify();
2963        }
2964    }
2965
2966    fn build_columnar_selection(
2967        &mut self,
2968        display_map: &DisplaySnapshot,
2969        row: u32,
2970        columns: &Range<u32>,
2971        reversed: bool,
2972    ) -> Option<Selection<Point>> {
2973        let is_empty = columns.start == columns.end;
2974        let line_len = display_map.line_len(row);
2975        if columns.start < line_len || (is_empty && columns.start == line_len) {
2976            let start = DisplayPoint::new(row, columns.start);
2977            let end = DisplayPoint::new(row, cmp::min(columns.end, line_len));
2978            Some(Selection {
2979                id: post_inc(&mut self.next_selection_id),
2980                start: start.to_point(display_map),
2981                end: end.to_point(display_map),
2982                reversed,
2983                goal: SelectionGoal::ColumnRange {
2984                    start: columns.start,
2985                    end: columns.end,
2986                },
2987            })
2988        } else {
2989            None
2990        }
2991    }
2992
2993    pub fn active_selection_sets<'a>(
2994        &'a self,
2995        cx: &'a AppContext,
2996    ) -> impl 'a + Iterator<Item = SelectionSetId> {
2997        let buffer = self.buffer.read(cx);
2998        let replica_id = buffer.replica_id();
2999        buffer
3000            .selection_sets(cx)
3001            .filter(move |(set_id, set)| {
3002                set.active && (set_id.replica_id != replica_id || **set_id == self.selection_set_id)
3003            })
3004            .map(|(set_id, _)| *set_id)
3005    }
3006
3007    pub fn intersecting_selections<'a>(
3008        &'a self,
3009        set_id: SelectionSetId,
3010        range: Range<DisplayPoint>,
3011        cx: &'a mut MutableAppContext,
3012    ) -> Vec<Selection<DisplayPoint>> {
3013        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3014        let buffer = self.buffer.read(cx);
3015
3016        let pending_selection = if set_id == self.selection_set_id {
3017            self.pending_selection.as_ref().and_then(|pending| {
3018                let selection_start = pending.selection.start.to_display_point(&display_map);
3019                let selection_end = pending.selection.end.to_display_point(&display_map);
3020                if selection_start <= range.end || selection_end <= range.end {
3021                    Some(Selection {
3022                        id: pending.selection.id,
3023                        start: selection_start,
3024                        end: selection_end,
3025                        reversed: pending.selection.reversed,
3026                        goal: pending.selection.goal,
3027                    })
3028                } else {
3029                    None
3030                }
3031            })
3032        } else {
3033            None
3034        };
3035
3036        let range = (range.start.to_offset(&display_map, Bias::Left), Bias::Left)
3037            ..(range.end.to_offset(&display_map, Bias::Left), Bias::Right);
3038        buffer
3039            .selection_set(set_id, cx)
3040            .unwrap()
3041            .intersecting_selections::<Point, _>(range, &buffer.read(cx))
3042            .map(move |s| Selection {
3043                id: s.id,
3044                start: s.start.to_display_point(&display_map),
3045                end: s.end.to_display_point(&display_map),
3046                reversed: s.reversed,
3047                goal: s.goal,
3048            })
3049            .chain(pending_selection)
3050            .collect()
3051    }
3052
3053    pub fn selections<'a, D>(&self, cx: &'a AppContext) -> Vec<Selection<D>>
3054    where
3055        D: 'a + TextDimension + Ord + Sub<D, Output = D>,
3056    {
3057        let buffer = self.buffer.read(cx).snapshot(cx);
3058        let mut selections = self.selection_set(cx).selections::<D>(&buffer).peekable();
3059        let mut pending_selection = self.pending_selection(cx);
3060
3061        iter::from_fn(move || {
3062            if let Some(pending) = pending_selection.as_mut() {
3063                while let Some(next_selection) = selections.peek() {
3064                    if pending.start <= next_selection.end && pending.end >= next_selection.start {
3065                        let next_selection = selections.next().unwrap();
3066                        if next_selection.start < pending.start {
3067                            pending.start = next_selection.start;
3068                        }
3069                        if next_selection.end > pending.end {
3070                            pending.end = next_selection.end;
3071                        }
3072                    } else if next_selection.end < pending.start {
3073                        return selections.next();
3074                    } else {
3075                        break;
3076                    }
3077                }
3078
3079                pending_selection.take()
3080            } else {
3081                selections.next()
3082            }
3083        })
3084        .collect()
3085    }
3086
3087    fn pending_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3088        &self,
3089        cx: &AppContext,
3090    ) -> Option<Selection<D>> {
3091        let buffer = self.buffer.read(cx).read(cx);
3092        self.pending_selection.as_ref().map(|pending| Selection {
3093            id: pending.selection.id,
3094            start: pending.selection.start.summary::<D>(&buffer),
3095            end: pending.selection.end.summary::<D>(&buffer),
3096            reversed: pending.selection.reversed,
3097            goal: pending.selection.goal,
3098        })
3099    }
3100
3101    fn selection_count<'a>(&self, cx: &'a AppContext) -> usize {
3102        let mut selection_count = self.selection_set(cx).len();
3103        if self.pending_selection.is_some() {
3104            selection_count += 1;
3105        }
3106        selection_count
3107    }
3108
3109    pub fn oldest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3110        &self,
3111        snapshot: &MultiBufferSnapshot,
3112        cx: &AppContext,
3113    ) -> Selection<D> {
3114        self.selection_set(cx)
3115            .oldest_selection(snapshot)
3116            .or_else(|| self.pending_selection(cx))
3117            .unwrap()
3118    }
3119
3120    pub fn newest_selection<D: TextDimension + Ord + Sub<D, Output = D>>(
3121        &self,
3122        cx: &AppContext,
3123    ) -> Selection<D> {
3124        self.pending_selection(cx)
3125            .or_else(|| {
3126                self.selection_set(cx)
3127                    .newest_selection(&self.buffer.read(cx).read(cx))
3128            })
3129            .unwrap()
3130    }
3131
3132    fn selection_set<'a>(&self, cx: &'a AppContext) -> &'a SelectionSet {
3133        self.buffer
3134            .read(cx)
3135            .selection_set(self.selection_set_id, cx)
3136            .unwrap()
3137    }
3138
3139    pub fn update_selections<T>(
3140        &mut self,
3141        mut selections: Vec<Selection<T>>,
3142        autoscroll: Option<Autoscroll>,
3143        cx: &mut ViewContext<Self>,
3144    ) where
3145        T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
3146    {
3147        // Merge overlapping selections.
3148        let buffer = self.buffer.read(cx).snapshot(cx);
3149        let mut i = 1;
3150        while i < selections.len() {
3151            if selections[i - 1].end >= selections[i].start {
3152                let removed = selections.remove(i);
3153                if removed.start < selections[i - 1].start {
3154                    selections[i - 1].start = removed.start;
3155                }
3156                if removed.end > selections[i - 1].end {
3157                    selections[i - 1].end = removed.end;
3158                }
3159            } else {
3160                i += 1;
3161            }
3162        }
3163
3164        self.pending_selection = None;
3165        self.add_selections_state = None;
3166        self.select_next_state = None;
3167        self.select_larger_syntax_node_stack.clear();
3168        while let Some(autoclose_pair) = self.autoclose_stack.last() {
3169            let all_selections_inside_autoclose_ranges =
3170                if selections.len() == autoclose_pair.ranges.len() {
3171                    selections
3172                        .iter()
3173                        .zip(autoclose_pair.ranges.iter().map(|r| r.to_point(&buffer)))
3174                        .all(|(selection, autoclose_range)| {
3175                            let head = selection.head().to_point(&buffer);
3176                            autoclose_range.start <= head && autoclose_range.end >= head
3177                        })
3178                } else {
3179                    false
3180                };
3181
3182            if all_selections_inside_autoclose_ranges {
3183                break;
3184            } else {
3185                self.autoclose_stack.pop();
3186            }
3187        }
3188
3189        if let Some(autoscroll) = autoscroll {
3190            self.request_autoscroll(autoscroll, cx);
3191        }
3192        self.pause_cursor_blinking(cx);
3193
3194        self.buffer.update(cx, |buffer, cx| {
3195            buffer
3196                .update_selection_set(self.selection_set_id, &selections, cx)
3197                .unwrap();
3198        });
3199    }
3200
3201    fn request_autoscroll(&mut self, autoscroll: Autoscroll, cx: &mut ViewContext<Self>) {
3202        self.autoscroll_request = Some(autoscroll);
3203        cx.notify();
3204    }
3205
3206    fn start_transaction(&mut self, cx: &mut ViewContext<Self>) {
3207        self.end_selection(cx);
3208        self.buffer.update(cx, |buffer, cx| {
3209            buffer
3210                .start_transaction([self.selection_set_id], cx)
3211                .unwrap()
3212        });
3213    }
3214
3215    fn end_transaction(&self, cx: &mut ViewContext<Self>) {
3216        self.buffer.update(cx, |buffer, cx| {
3217            buffer.end_transaction([self.selection_set_id], cx).unwrap()
3218        });
3219    }
3220
3221    pub fn page_up(&mut self, _: &PageUp, _: &mut ViewContext<Self>) {
3222        log::info!("Editor::page_up");
3223    }
3224
3225    pub fn page_down(&mut self, _: &PageDown, _: &mut ViewContext<Self>) {
3226        log::info!("Editor::page_down");
3227    }
3228
3229    pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
3230        let mut fold_ranges = Vec::new();
3231
3232        let selections = self.selections::<Point>(cx);
3233        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3234        for selection in selections {
3235            let range = selection.display_range(&display_map).sorted();
3236            let buffer_start_row = range.start.to_point(&display_map).row;
3237
3238            for row in (0..=range.end.row()).rev() {
3239                if self.is_line_foldable(&display_map, row) && !display_map.is_line_folded(row) {
3240                    let fold_range = self.foldable_range_for_line(&display_map, row);
3241                    if fold_range.end.row >= buffer_start_row {
3242                        fold_ranges.push(fold_range);
3243                        if row <= range.start.row() {
3244                            break;
3245                        }
3246                    }
3247                }
3248            }
3249        }
3250
3251        self.fold_ranges(fold_ranges, cx);
3252    }
3253
3254    pub fn unfold(&mut self, _: &Unfold, cx: &mut ViewContext<Self>) {
3255        let selections = self.selections::<Point>(cx);
3256        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
3257        let buffer = &display_map.buffer_snapshot;
3258        let ranges = selections
3259            .iter()
3260            .map(|s| {
3261                let range = s.display_range(&display_map).sorted();
3262                let mut start = range.start.to_point(&display_map);
3263                let mut end = range.end.to_point(&display_map);
3264                start.column = 0;
3265                end.column = buffer.line_len(end.row);
3266                start..end
3267            })
3268            .collect::<Vec<_>>();
3269        self.unfold_ranges(ranges, cx);
3270    }
3271
3272    fn is_line_foldable(&self, display_map: &DisplaySnapshot, display_row: u32) -> bool {
3273        let max_point = display_map.max_point();
3274        if display_row >= max_point.row() {
3275            false
3276        } else {
3277            let (start_indent, is_blank) = display_map.line_indent(display_row);
3278            if is_blank {
3279                false
3280            } else {
3281                for display_row in display_row + 1..=max_point.row() {
3282                    let (indent, is_blank) = display_map.line_indent(display_row);
3283                    if !is_blank {
3284                        return indent > start_indent;
3285                    }
3286                }
3287                false
3288            }
3289        }
3290    }
3291
3292    fn foldable_range_for_line(
3293        &self,
3294        display_map: &DisplaySnapshot,
3295        start_row: u32,
3296    ) -> Range<Point> {
3297        let max_point = display_map.max_point();
3298
3299        let (start_indent, _) = display_map.line_indent(start_row);
3300        let start = DisplayPoint::new(start_row, display_map.line_len(start_row));
3301        let mut end = None;
3302        for row in start_row + 1..=max_point.row() {
3303            let (indent, is_blank) = display_map.line_indent(row);
3304            if !is_blank && indent <= start_indent {
3305                end = Some(DisplayPoint::new(row - 1, display_map.line_len(row - 1)));
3306                break;
3307            }
3308        }
3309
3310        let end = end.unwrap_or(max_point);
3311        return start.to_point(display_map)..end.to_point(display_map);
3312    }
3313
3314    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
3315        let selections = self.selections::<Point>(cx);
3316        let ranges = selections.into_iter().map(|s| s.start..s.end);
3317        self.fold_ranges(ranges, cx);
3318    }
3319
3320    fn fold_ranges<T: ToOffset>(
3321        &mut self,
3322        ranges: impl IntoIterator<Item = Range<T>>,
3323        cx: &mut ViewContext<Self>,
3324    ) {
3325        let mut ranges = ranges.into_iter().peekable();
3326        if ranges.peek().is_some() {
3327            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
3328            self.request_autoscroll(Autoscroll::Fit, cx);
3329            cx.notify();
3330        }
3331    }
3332
3333    fn unfold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
3334        if !ranges.is_empty() {
3335            self.display_map
3336                .update(cx, |map, cx| map.unfold(ranges, cx));
3337            self.request_autoscroll(Autoscroll::Fit, cx);
3338            cx.notify();
3339        }
3340    }
3341
3342    pub fn longest_row(&self, cx: &mut MutableAppContext) -> u32 {
3343        self.display_map
3344            .update(cx, |map, cx| map.snapshot(cx))
3345            .longest_row()
3346    }
3347
3348    pub fn max_point(&self, cx: &mut MutableAppContext) -> DisplayPoint {
3349        self.display_map
3350            .update(cx, |map, cx| map.snapshot(cx))
3351            .max_point()
3352    }
3353
3354    pub fn text(&self, cx: &AppContext) -> String {
3355        self.buffer.read(cx).read(cx).text()
3356    }
3357
3358    pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
3359        self.display_map
3360            .update(cx, |map, cx| map.snapshot(cx))
3361            .text()
3362    }
3363
3364    pub fn set_wrap_width(&self, width: Option<f32>, cx: &mut MutableAppContext) -> bool {
3365        self.display_map
3366            .update(cx, |map, cx| map.set_wrap_width(width, cx))
3367    }
3368
3369    pub fn set_highlighted_row(&mut self, row: Option<u32>) {
3370        self.highlighted_row = row;
3371    }
3372
3373    pub fn highlighted_row(&mut self) -> Option<u32> {
3374        self.highlighted_row
3375    }
3376
3377    fn next_blink_epoch(&mut self) -> usize {
3378        self.blink_epoch += 1;
3379        self.blink_epoch
3380    }
3381
3382    fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
3383        self.show_local_cursors = true;
3384        cx.notify();
3385
3386        let epoch = self.next_blink_epoch();
3387        cx.spawn(|this, mut cx| {
3388            let this = this.downgrade();
3389            async move {
3390                Timer::after(CURSOR_BLINK_INTERVAL).await;
3391                if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
3392                    this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
3393                }
3394            }
3395        })
3396        .detach();
3397    }
3398
3399    fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
3400        if epoch == self.blink_epoch {
3401            self.blinking_paused = false;
3402            self.blink_cursors(epoch, cx);
3403        }
3404    }
3405
3406    fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
3407        if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
3408            self.show_local_cursors = !self.show_local_cursors;
3409            cx.notify();
3410
3411            let epoch = self.next_blink_epoch();
3412            cx.spawn(|this, mut cx| {
3413                let this = this.downgrade();
3414                async move {
3415                    Timer::after(CURSOR_BLINK_INTERVAL).await;
3416                    if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
3417                        this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
3418                    }
3419                }
3420            })
3421            .detach();
3422        }
3423    }
3424
3425    pub fn show_local_cursors(&self) -> bool {
3426        self.show_local_cursors
3427    }
3428
3429    fn on_buffer_changed(&mut self, _: ModelHandle<MultiBuffer>, cx: &mut ViewContext<Self>) {
3430        self.refresh_active_diagnostics(cx);
3431        cx.notify();
3432    }
3433
3434    fn on_buffer_event(
3435        &mut self,
3436        _: ModelHandle<MultiBuffer>,
3437        event: &language::Event,
3438        cx: &mut ViewContext<Self>,
3439    ) {
3440        match event {
3441            language::Event::Edited => cx.emit(Event::Edited),
3442            language::Event::Dirtied => cx.emit(Event::Dirtied),
3443            language::Event::Saved => cx.emit(Event::Saved),
3444            language::Event::FileHandleChanged => cx.emit(Event::FileHandleChanged),
3445            language::Event::Reloaded => cx.emit(Event::FileHandleChanged),
3446            language::Event::Closed => cx.emit(Event::Closed),
3447            _ => {}
3448        }
3449    }
3450
3451    fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
3452        cx.notify();
3453    }
3454}
3455
3456impl EditorSnapshot {
3457    pub fn is_focused(&self) -> bool {
3458        self.is_focused
3459    }
3460
3461    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
3462        self.placeholder_text.as_ref()
3463    }
3464
3465    pub fn scroll_position(&self) -> Vector2F {
3466        compute_scroll_position(
3467            &self.display_snapshot,
3468            self.scroll_position,
3469            &self.scroll_top_anchor,
3470        )
3471    }
3472}
3473
3474impl Deref for EditorSnapshot {
3475    type Target = DisplaySnapshot;
3476
3477    fn deref(&self) -> &Self::Target {
3478        &self.display_snapshot
3479    }
3480}
3481
3482impl EditorSettings {
3483    #[cfg(any(test, feature = "test-support"))]
3484    pub fn test(cx: &AppContext) -> Self {
3485        Self {
3486            tab_size: 4,
3487            soft_wrap: SoftWrap::None,
3488            style: {
3489                let font_cache: &gpui::FontCache = cx.font_cache();
3490                let font_family_name = Arc::from("Monaco");
3491                let font_properties = Default::default();
3492                let font_family_id = font_cache.load_family(&[&font_family_name]).unwrap();
3493                let font_id = font_cache
3494                    .select_font(font_family_id, &font_properties)
3495                    .unwrap();
3496                EditorStyle {
3497                    text: gpui::fonts::TextStyle {
3498                        font_family_name,
3499                        font_family_id,
3500                        font_id,
3501                        font_size: 14.,
3502                        color: gpui::color::Color::from_u32(0xff0000ff),
3503                        font_properties,
3504                        underline: None,
3505                    },
3506                    placeholder_text: None,
3507                    background: Default::default(),
3508                    gutter_background: Default::default(),
3509                    active_line_background: Default::default(),
3510                    highlighted_line_background: Default::default(),
3511                    line_number: Default::default(),
3512                    line_number_active: Default::default(),
3513                    selection: Default::default(),
3514                    guest_selections: Default::default(),
3515                    syntax: Default::default(),
3516                    error_diagnostic: Default::default(),
3517                    invalid_error_diagnostic: Default::default(),
3518                    warning_diagnostic: Default::default(),
3519                    invalid_warning_diagnostic: Default::default(),
3520                    information_diagnostic: Default::default(),
3521                    invalid_information_diagnostic: Default::default(),
3522                    hint_diagnostic: Default::default(),
3523                    invalid_hint_diagnostic: Default::default(),
3524                }
3525            },
3526        }
3527    }
3528}
3529
3530fn compute_scroll_position(
3531    snapshot: &DisplaySnapshot,
3532    mut scroll_position: Vector2F,
3533    scroll_top_anchor: &Anchor,
3534) -> Vector2F {
3535    let scroll_top = scroll_top_anchor.to_display_point(snapshot).row() as f32;
3536    scroll_position.set_y(scroll_top + scroll_position.y());
3537    scroll_position
3538}
3539
3540pub enum Event {
3541    Activate,
3542    Edited,
3543    Blurred,
3544    Dirtied,
3545    Saved,
3546    FileHandleChanged,
3547    Closed,
3548}
3549
3550impl Entity for Editor {
3551    type Event = Event;
3552
3553    fn release(&mut self, cx: &mut MutableAppContext) {
3554        self.buffer.update(cx, |buffer, cx| {
3555            buffer
3556                .remove_selection_set(self.selection_set_id, cx)
3557                .unwrap();
3558        });
3559    }
3560}
3561
3562impl View for Editor {
3563    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
3564        let settings = self.build_settings.borrow_mut()(cx);
3565        self.display_map.update(cx, |map, cx| {
3566            map.set_font(
3567                settings.style.text.font_id,
3568                settings.style.text.font_size,
3569                cx,
3570            )
3571        });
3572        EditorElement::new(self.handle.clone(), settings).boxed()
3573    }
3574
3575    fn ui_name() -> &'static str {
3576        "Editor"
3577    }
3578
3579    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
3580        self.focused = true;
3581        self.blink_cursors(self.blink_epoch, cx);
3582        self.buffer.update(cx, |buffer, cx| {
3583            buffer
3584                .set_active_selection_set(Some(self.selection_set_id), cx)
3585                .unwrap();
3586        });
3587    }
3588
3589    fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
3590        self.focused = false;
3591        self.show_local_cursors = false;
3592        self.buffer.update(cx, |buffer, cx| {
3593            buffer.set_active_selection_set(None, cx).unwrap();
3594        });
3595        cx.emit(Event::Blurred);
3596        cx.notify();
3597    }
3598
3599    fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
3600        let mut cx = Self::default_keymap_context();
3601        let mode = match self.mode {
3602            EditorMode::SingleLine => "single_line",
3603            EditorMode::AutoHeight { .. } => "auto_height",
3604            EditorMode::Full => "full",
3605        };
3606        cx.map.insert("mode".into(), mode.into());
3607        cx
3608    }
3609}
3610
3611impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
3612    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
3613        let start = self.start.to_point(buffer);
3614        let end = self.end.to_point(buffer);
3615        if self.reversed {
3616            end..start
3617        } else {
3618            start..end
3619        }
3620    }
3621
3622    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
3623        let start = self.start.to_offset(buffer);
3624        let end = self.end.to_offset(buffer);
3625        if self.reversed {
3626            end..start
3627        } else {
3628            start..end
3629        }
3630    }
3631
3632    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
3633        let start = self
3634            .start
3635            .to_point(&map.buffer_snapshot)
3636            .to_display_point(map);
3637        let end = self
3638            .end
3639            .to_point(&map.buffer_snapshot)
3640            .to_display_point(map);
3641        if self.reversed {
3642            end..start
3643        } else {
3644            start..end
3645        }
3646    }
3647
3648    fn spanned_rows(
3649        &self,
3650        include_end_if_at_line_start: bool,
3651        map: &DisplaySnapshot,
3652    ) -> SpannedRows {
3653        let display_start = self
3654            .start
3655            .to_point(&map.buffer_snapshot)
3656            .to_display_point(map);
3657        let mut display_end = self
3658            .end
3659            .to_point(&map.buffer_snapshot)
3660            .to_display_point(map);
3661        if !include_end_if_at_line_start
3662            && display_end.row() != map.max_point().row()
3663            && display_start.row() != display_end.row()
3664            && display_end.column() == 0
3665        {
3666            *display_end.row_mut() -= 1;
3667        }
3668
3669        let (display_start, buffer_start) = map.prev_row_boundary(display_start);
3670        let (display_end, buffer_end) = map.next_row_boundary(display_end);
3671
3672        SpannedRows {
3673            buffer_rows: buffer_start.row..buffer_end.row + 1,
3674            display_rows: display_start.row()..display_end.row() + 1,
3675        }
3676    }
3677}
3678
3679fn render_diagnostic(
3680    diagnostic: Diagnostic,
3681    style: &EditorStyle,
3682    valid: bool,
3683    anchor_x: f32,
3684) -> ElementBox {
3685    let mut text_style = style.text.clone();
3686    text_style.color = diagnostic_style(diagnostic.severity, valid, &style).text;
3687    Text::new(diagnostic.message, text_style)
3688        .contained()
3689        .with_margin_left(anchor_x)
3690        .boxed()
3691}
3692
3693pub fn diagnostic_style(
3694    severity: DiagnosticSeverity,
3695    valid: bool,
3696    style: &EditorStyle,
3697) -> DiagnosticStyle {
3698    match (severity, valid) {
3699        (DiagnosticSeverity::ERROR, true) => style.error_diagnostic,
3700        (DiagnosticSeverity::ERROR, false) => style.invalid_error_diagnostic,
3701        (DiagnosticSeverity::WARNING, true) => style.warning_diagnostic,
3702        (DiagnosticSeverity::WARNING, false) => style.invalid_warning_diagnostic,
3703        (DiagnosticSeverity::INFORMATION, true) => style.information_diagnostic,
3704        (DiagnosticSeverity::INFORMATION, false) => style.invalid_information_diagnostic,
3705        (DiagnosticSeverity::HINT, true) => style.hint_diagnostic,
3706        (DiagnosticSeverity::HINT, false) => style.invalid_hint_diagnostic,
3707        _ => Default::default(),
3708    }
3709}
3710
3711#[cfg(test)]
3712mod tests {
3713    use super::*;
3714    use language::LanguageConfig;
3715    use text::Point;
3716    use unindent::Unindent;
3717    use util::test::sample_text;
3718
3719    #[gpui::test]
3720    fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
3721        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
3722        let settings = EditorSettings::test(cx);
3723        let (_, editor) =
3724            cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3725
3726        editor.update(cx, |view, cx| {
3727            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
3728        });
3729
3730        assert_eq!(
3731            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3732            [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
3733        );
3734
3735        editor.update(cx, |view, cx| {
3736            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
3737        });
3738
3739        assert_eq!(
3740            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3741            [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3742        );
3743
3744        editor.update(cx, |view, cx| {
3745            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
3746        });
3747
3748        assert_eq!(
3749            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3750            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
3751        );
3752
3753        editor.update(cx, |view, cx| {
3754            view.end_selection(cx);
3755            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
3756        });
3757
3758        assert_eq!(
3759            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3760            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
3761        );
3762
3763        editor.update(cx, |view, cx| {
3764            view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
3765            view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
3766        });
3767
3768        assert_eq!(
3769            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3770            [
3771                DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
3772                DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
3773            ]
3774        );
3775
3776        editor.update(cx, |view, cx| {
3777            view.end_selection(cx);
3778        });
3779
3780        assert_eq!(
3781            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3782            [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
3783        );
3784    }
3785
3786    #[gpui::test]
3787    fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
3788        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
3789        let settings = EditorSettings::test(cx);
3790        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3791
3792        view.update(cx, |view, cx| {
3793            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
3794            assert_eq!(
3795                view.selection_ranges(cx),
3796                [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
3797            );
3798        });
3799
3800        view.update(cx, |view, cx| {
3801            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
3802            assert_eq!(
3803                view.selection_ranges(cx),
3804                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3805            );
3806        });
3807
3808        view.update(cx, |view, cx| {
3809            view.cancel(&Cancel, cx);
3810            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
3811            assert_eq!(
3812                view.selection_ranges(cx),
3813                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3814            );
3815        });
3816    }
3817
3818    #[gpui::test]
3819    fn test_cancel(cx: &mut gpui::MutableAppContext) {
3820        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
3821        let settings = EditorSettings::test(cx);
3822        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3823
3824        view.update(cx, |view, cx| {
3825            view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
3826            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
3827            view.end_selection(cx);
3828
3829            view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
3830            view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
3831            view.end_selection(cx);
3832            assert_eq!(
3833                view.selection_ranges(cx),
3834                [
3835                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
3836                    DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
3837                ]
3838            );
3839        });
3840
3841        view.update(cx, |view, cx| {
3842            view.cancel(&Cancel, cx);
3843            assert_eq!(
3844                view.selection_ranges(cx),
3845                [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
3846            );
3847        });
3848
3849        view.update(cx, |view, cx| {
3850            view.cancel(&Cancel, cx);
3851            assert_eq!(
3852                view.selection_ranges(cx),
3853                [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
3854            );
3855        });
3856    }
3857
3858    #[gpui::test]
3859    fn test_fold(cx: &mut gpui::MutableAppContext) {
3860        let buffer = MultiBuffer::build_simple(
3861            &"
3862                impl Foo {
3863                    // Hello!
3864
3865                    fn a() {
3866                        1
3867                    }
3868
3869                    fn b() {
3870                        2
3871                    }
3872
3873                    fn c() {
3874                        3
3875                    }
3876                }
3877            "
3878            .unindent(),
3879            cx,
3880        );
3881        let settings = EditorSettings::test(&cx);
3882        let (_, view) = cx.add_window(Default::default(), |cx| {
3883            build_editor(buffer.clone(), settings, cx)
3884        });
3885
3886        view.update(cx, |view, cx| {
3887            view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx)
3888                .unwrap();
3889            view.fold(&Fold, cx);
3890            assert_eq!(
3891                view.display_text(cx),
3892                "
3893                    impl Foo {
3894                        // Hello!
3895
3896                        fn a() {
3897                            1
3898                        }
3899
3900                        fn b() {…
3901                        }
3902
3903                        fn c() {…
3904                        }
3905                    }
3906                "
3907                .unindent(),
3908            );
3909
3910            view.fold(&Fold, cx);
3911            assert_eq!(
3912                view.display_text(cx),
3913                "
3914                    impl Foo {…
3915                    }
3916                "
3917                .unindent(),
3918            );
3919
3920            view.unfold(&Unfold, cx);
3921            assert_eq!(
3922                view.display_text(cx),
3923                "
3924                    impl Foo {
3925                        // Hello!
3926
3927                        fn a() {
3928                            1
3929                        }
3930
3931                        fn b() {…
3932                        }
3933
3934                        fn c() {…
3935                        }
3936                    }
3937                "
3938                .unindent(),
3939            );
3940
3941            view.unfold(&Unfold, cx);
3942            assert_eq!(view.display_text(cx), buffer.read(cx).read(cx).text());
3943        });
3944    }
3945
3946    #[gpui::test]
3947    fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
3948        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
3949        let settings = EditorSettings::test(&cx);
3950        let (_, view) = cx.add_window(Default::default(), |cx| {
3951            build_editor(buffer.clone(), settings, cx)
3952        });
3953
3954        buffer.update(cx, |buffer, cx| {
3955            buffer.edit(
3956                vec![
3957                    Point::new(1, 0)..Point::new(1, 0),
3958                    Point::new(1, 1)..Point::new(1, 1),
3959                ],
3960                "\t",
3961                cx,
3962            );
3963        });
3964
3965        view.update(cx, |view, cx| {
3966            assert_eq!(
3967                view.selection_ranges(cx),
3968                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
3969            );
3970
3971            view.move_down(&MoveDown, cx);
3972            assert_eq!(
3973                view.selection_ranges(cx),
3974                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
3975            );
3976
3977            view.move_right(&MoveRight, cx);
3978            assert_eq!(
3979                view.selection_ranges(cx),
3980                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
3981            );
3982
3983            view.move_left(&MoveLeft, cx);
3984            assert_eq!(
3985                view.selection_ranges(cx),
3986                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
3987            );
3988
3989            view.move_up(&MoveUp, cx);
3990            assert_eq!(
3991                view.selection_ranges(cx),
3992                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
3993            );
3994
3995            view.move_to_end(&MoveToEnd, cx);
3996            assert_eq!(
3997                view.selection_ranges(cx),
3998                &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
3999            );
4000
4001            view.move_to_beginning(&MoveToBeginning, cx);
4002            assert_eq!(
4003                view.selection_ranges(cx),
4004                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4005            );
4006
4007            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx)
4008                .unwrap();
4009            view.select_to_beginning(&SelectToBeginning, cx);
4010            assert_eq!(
4011                view.selection_ranges(cx),
4012                &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
4013            );
4014
4015            view.select_to_end(&SelectToEnd, cx);
4016            assert_eq!(
4017                view.selection_ranges(cx),
4018                &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
4019            );
4020        });
4021    }
4022
4023    #[gpui::test]
4024    fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
4025        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx);
4026        let settings = EditorSettings::test(&cx);
4027        let (_, view) = cx.add_window(Default::default(), |cx| {
4028            build_editor(buffer.clone(), settings, cx)
4029        });
4030
4031        assert_eq!('ⓐ'.len_utf8(), 3);
4032        assert_eq!('α'.len_utf8(), 2);
4033
4034        view.update(cx, |view, cx| {
4035            view.fold_ranges(
4036                vec![
4037                    Point::new(0, 6)..Point::new(0, 12),
4038                    Point::new(1, 2)..Point::new(1, 4),
4039                    Point::new(2, 4)..Point::new(2, 8),
4040                ],
4041                cx,
4042            );
4043            assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
4044
4045            view.move_right(&MoveRight, cx);
4046            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "".len())]);
4047            view.move_right(&MoveRight, cx);
4048            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ".len())]);
4049            view.move_right(&MoveRight, cx);
4050            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…".len())]);
4051
4052            view.move_down(&MoveDown, cx);
4053            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab…".len())]);
4054            view.move_left(&MoveLeft, cx);
4055            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab".len())]);
4056            view.move_left(&MoveLeft, cx);
4057            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "a".len())]);
4058
4059            view.move_down(&MoveDown, cx);
4060            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "α".len())]);
4061            view.move_right(&MoveRight, cx);
4062            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ".len())]);
4063            view.move_right(&MoveRight, cx);
4064            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ…".len())]);
4065            view.move_right(&MoveRight, cx);
4066            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ…ε".len())]);
4067
4068            view.move_up(&MoveUp, cx);
4069            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab…e".len())]);
4070            view.move_up(&MoveUp, cx);
4071            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…ⓔ".len())]);
4072            view.move_left(&MoveLeft, cx);
4073            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…".len())]);
4074            view.move_left(&MoveLeft, cx);
4075            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ".len())]);
4076            view.move_left(&MoveLeft, cx);
4077            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "".len())]);
4078        });
4079    }
4080
4081    #[gpui::test]
4082    fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
4083        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
4084        let settings = EditorSettings::test(&cx);
4085        let (_, view) = cx.add_window(Default::default(), |cx| {
4086            build_editor(buffer.clone(), settings, cx)
4087        });
4088        view.update(cx, |view, cx| {
4089            view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx)
4090                .unwrap();
4091
4092            view.move_down(&MoveDown, cx);
4093            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "abcd".len())]);
4094
4095            view.move_down(&MoveDown, cx);
4096            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβγ".len())]);
4097
4098            view.move_down(&MoveDown, cx);
4099            assert_eq!(view.selection_ranges(cx), &[empty_range(3, "abcd".len())]);
4100
4101            view.move_down(&MoveDown, cx);
4102            assert_eq!(view.selection_ranges(cx), &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]);
4103
4104            view.move_up(&MoveUp, cx);
4105            assert_eq!(view.selection_ranges(cx), &[empty_range(3, "abcd".len())]);
4106
4107            view.move_up(&MoveUp, cx);
4108            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβγ".len())]);
4109        });
4110    }
4111
4112    #[gpui::test]
4113    fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
4114        let buffer = MultiBuffer::build_simple("abc\n  def", cx);
4115        let settings = EditorSettings::test(&cx);
4116        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4117        view.update(cx, |view, cx| {
4118            view.select_display_ranges(
4119                &[
4120                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4121                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4122                ],
4123                cx,
4124            )
4125            .unwrap();
4126        });
4127
4128        view.update(cx, |view, cx| {
4129            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4130            assert_eq!(
4131                view.selection_ranges(cx),
4132                &[
4133                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4134                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4135                ]
4136            );
4137        });
4138
4139        view.update(cx, |view, cx| {
4140            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4141            assert_eq!(
4142                view.selection_ranges(cx),
4143                &[
4144                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4145                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4146                ]
4147            );
4148        });
4149
4150        view.update(cx, |view, cx| {
4151            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4152            assert_eq!(
4153                view.selection_ranges(cx),
4154                &[
4155                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4156                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4157                ]
4158            );
4159        });
4160
4161        view.update(cx, |view, cx| {
4162            view.move_to_end_of_line(&MoveToEndOfLine, cx);
4163            assert_eq!(
4164                view.selection_ranges(cx),
4165                &[
4166                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4167                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4168                ]
4169            );
4170        });
4171
4172        // Moving to the end of line again is a no-op.
4173        view.update(cx, |view, cx| {
4174            view.move_to_end_of_line(&MoveToEndOfLine, cx);
4175            assert_eq!(
4176                view.selection_ranges(cx),
4177                &[
4178                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4179                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4180                ]
4181            );
4182        });
4183
4184        view.update(cx, |view, cx| {
4185            view.move_left(&MoveLeft, cx);
4186            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4187            assert_eq!(
4188                view.selection_ranges(cx),
4189                &[
4190                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4191                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4192                ]
4193            );
4194        });
4195
4196        view.update(cx, |view, cx| {
4197            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4198            assert_eq!(
4199                view.selection_ranges(cx),
4200                &[
4201                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4202                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
4203                ]
4204            );
4205        });
4206
4207        view.update(cx, |view, cx| {
4208            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4209            assert_eq!(
4210                view.selection_ranges(cx),
4211                &[
4212                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4213                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4214                ]
4215            );
4216        });
4217
4218        view.update(cx, |view, cx| {
4219            view.select_to_end_of_line(&SelectToEndOfLine, cx);
4220            assert_eq!(
4221                view.selection_ranges(cx),
4222                &[
4223                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
4224                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
4225                ]
4226            );
4227        });
4228
4229        view.update(cx, |view, cx| {
4230            view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
4231            assert_eq!(view.display_text(cx), "ab\n  de");
4232            assert_eq!(
4233                view.selection_ranges(cx),
4234                &[
4235                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4236                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4237                ]
4238            );
4239        });
4240
4241        view.update(cx, |view, cx| {
4242            view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
4243            assert_eq!(view.display_text(cx), "\n");
4244            assert_eq!(
4245                view.selection_ranges(cx),
4246                &[
4247                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4248                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4249                ]
4250            );
4251        });
4252    }
4253
4254    #[gpui::test]
4255    fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
4256        let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n  {baz.qux()}", cx);
4257        let settings = EditorSettings::test(&cx);
4258        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4259        view.update(cx, |view, cx| {
4260            view.select_display_ranges(
4261                &[
4262                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
4263                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
4264                ],
4265                cx,
4266            )
4267            .unwrap();
4268        });
4269
4270        view.update(cx, |view, cx| {
4271            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4272            assert_eq!(
4273                view.selection_ranges(cx),
4274                &[
4275                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4276                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4277                ]
4278            );
4279        });
4280
4281        view.update(cx, |view, cx| {
4282            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4283            assert_eq!(
4284                view.selection_ranges(cx),
4285                &[
4286                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4287                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
4288                ]
4289            );
4290        });
4291
4292        view.update(cx, |view, cx| {
4293            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4294            assert_eq!(
4295                view.selection_ranges(cx),
4296                &[
4297                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
4298                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
4299                ]
4300            );
4301        });
4302
4303        view.update(cx, |view, cx| {
4304            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4305            assert_eq!(
4306                view.selection_ranges(cx),
4307                &[
4308                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4309                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4310                ]
4311            );
4312        });
4313
4314        view.update(cx, |view, cx| {
4315            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4316            assert_eq!(
4317                view.selection_ranges(cx),
4318                &[
4319                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4320                    DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
4321                ]
4322            );
4323        });
4324
4325        view.update(cx, |view, cx| {
4326            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4327            assert_eq!(
4328                view.selection_ranges(cx),
4329                &[
4330                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4331                    DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
4332                ]
4333            );
4334        });
4335
4336        view.update(cx, |view, cx| {
4337            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4338            assert_eq!(
4339                view.selection_ranges(cx),
4340                &[
4341                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4342                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4343                ]
4344            );
4345        });
4346
4347        view.update(cx, |view, cx| {
4348            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4349            assert_eq!(
4350                view.selection_ranges(cx),
4351                &[
4352                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4353                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4354                ]
4355            );
4356        });
4357
4358        view.update(cx, |view, cx| {
4359            view.move_right(&MoveRight, cx);
4360            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4361            assert_eq!(
4362                view.selection_ranges(cx),
4363                &[
4364                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
4365                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
4366                ]
4367            );
4368        });
4369
4370        view.update(cx, |view, cx| {
4371            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4372            assert_eq!(
4373                view.selection_ranges(cx),
4374                &[
4375                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
4376                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
4377                ]
4378            );
4379        });
4380
4381        view.update(cx, |view, cx| {
4382            view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
4383            assert_eq!(
4384                view.selection_ranges(cx),
4385                &[
4386                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
4387                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
4388                ]
4389            );
4390        });
4391    }
4392
4393    #[gpui::test]
4394    fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
4395        let buffer = MultiBuffer::build_simple("use one::{\n    two::three::four::five\n};", cx);
4396        let settings = EditorSettings::test(&cx);
4397        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4398
4399        view.update(cx, |view, cx| {
4400            view.set_wrap_width(Some(140.), cx);
4401            assert_eq!(
4402                view.display_text(cx),
4403                "use one::{\n    two::three::\n    four::five\n};"
4404            );
4405
4406            view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx)
4407                .unwrap();
4408
4409            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4410            assert_eq!(
4411                view.selection_ranges(cx),
4412                &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
4413            );
4414
4415            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4416            assert_eq!(
4417                view.selection_ranges(cx),
4418                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
4419            );
4420
4421            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4422            assert_eq!(
4423                view.selection_ranges(cx),
4424                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
4425            );
4426
4427            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4428            assert_eq!(
4429                view.selection_ranges(cx),
4430                &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
4431            );
4432
4433            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4434            assert_eq!(
4435                view.selection_ranges(cx),
4436                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
4437            );
4438
4439            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4440            assert_eq!(
4441                view.selection_ranges(cx),
4442                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
4443            );
4444        });
4445    }
4446
4447    #[gpui::test]
4448    fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
4449        let buffer = MultiBuffer::build_simple("one two three four", cx);
4450        let settings = EditorSettings::test(&cx);
4451        let (_, view) = cx.add_window(Default::default(), |cx| {
4452            build_editor(buffer.clone(), settings, cx)
4453        });
4454
4455        view.update(cx, |view, cx| {
4456            view.select_display_ranges(
4457                &[
4458                    // an empty selection - the preceding word fragment is deleted
4459                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4460                    // characters selected - they are deleted
4461                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
4462                ],
4463                cx,
4464            )
4465            .unwrap();
4466            view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
4467        });
4468
4469        assert_eq!(buffer.read(cx).read(cx).text(), "e two te four");
4470
4471        view.update(cx, |view, cx| {
4472            view.select_display_ranges(
4473                &[
4474                    // an empty selection - the following word fragment is deleted
4475                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4476                    // characters selected - they are deleted
4477                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
4478                ],
4479                cx,
4480            )
4481            .unwrap();
4482            view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
4483        });
4484
4485        assert_eq!(buffer.read(cx).read(cx).text(), "e t te our");
4486    }
4487
4488    #[gpui::test]
4489    fn test_newline(cx: &mut gpui::MutableAppContext) {
4490        let buffer = MultiBuffer::build_simple("aaaa\n    bbbb\n", cx);
4491        let settings = EditorSettings::test(&cx);
4492        let (_, view) = cx.add_window(Default::default(), |cx| {
4493            build_editor(buffer.clone(), settings, cx)
4494        });
4495
4496        view.update(cx, |view, cx| {
4497            view.select_display_ranges(
4498                &[
4499                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4500                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4501                    DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
4502                ],
4503                cx,
4504            )
4505            .unwrap();
4506
4507            view.newline(&Newline, cx);
4508            assert_eq!(view.text(cx), "aa\naa\n  \n    bb\n    bb\n");
4509        });
4510    }
4511
4512    #[gpui::test]
4513    fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
4514        let buffer = MultiBuffer::build_simple("  one two\nthree\n four", cx);
4515        let settings = EditorSettings::test(&cx);
4516        let (_, view) = cx.add_window(Default::default(), |cx| {
4517            build_editor(buffer.clone(), settings, cx)
4518        });
4519
4520        view.update(cx, |view, cx| {
4521            // two selections on the same line
4522            view.select_display_ranges(
4523                &[
4524                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
4525                    DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
4526                ],
4527                cx,
4528            )
4529            .unwrap();
4530
4531            // indent from mid-tabstop to full tabstop
4532            view.tab(&Tab, cx);
4533            assert_eq!(view.text(cx), "    one two\nthree\n four");
4534            assert_eq!(
4535                view.selection_ranges(cx),
4536                &[
4537                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
4538                    DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
4539                ]
4540            );
4541
4542            // outdent from 1 tabstop to 0 tabstops
4543            view.outdent(&Outdent, cx);
4544            assert_eq!(view.text(cx), "one two\nthree\n four");
4545            assert_eq!(
4546                view.selection_ranges(cx),
4547                &[
4548                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
4549                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
4550                ]
4551            );
4552
4553            // select across line ending
4554            view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx)
4555                .unwrap();
4556
4557            // indent and outdent affect only the preceding line
4558            view.tab(&Tab, cx);
4559            assert_eq!(view.text(cx), "one two\n    three\n four");
4560            assert_eq!(
4561                view.selection_ranges(cx),
4562                &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
4563            );
4564            view.outdent(&Outdent, cx);
4565            assert_eq!(view.text(cx), "one two\nthree\n four");
4566            assert_eq!(
4567                view.selection_ranges(cx),
4568                &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
4569            );
4570        });
4571    }
4572
4573    #[gpui::test]
4574    fn test_backspace(cx: &mut gpui::MutableAppContext) {
4575        let buffer =
4576            MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
4577        let settings = EditorSettings::test(&cx);
4578        let (_, view) = cx.add_window(Default::default(), |cx| {
4579            build_editor(buffer.clone(), settings, cx)
4580        });
4581
4582        view.update(cx, |view, cx| {
4583            view.select_display_ranges(
4584                &[
4585                    // an empty selection - the preceding character is deleted
4586                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4587                    // one character selected - it is deleted
4588                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4589                    // a line suffix selected - it is deleted
4590                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
4591                ],
4592                cx,
4593            )
4594            .unwrap();
4595            view.backspace(&Backspace, cx);
4596        });
4597
4598        assert_eq!(
4599            buffer.read(cx).read(cx).text(),
4600            "oe two three\nfou five six\nseven ten\n"
4601        );
4602    }
4603
4604    #[gpui::test]
4605    fn test_delete(cx: &mut gpui::MutableAppContext) {
4606        let buffer =
4607            MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
4608        let settings = EditorSettings::test(&cx);
4609        let (_, view) = cx.add_window(Default::default(), |cx| {
4610            build_editor(buffer.clone(), settings, cx)
4611        });
4612
4613        view.update(cx, |view, cx| {
4614            view.select_display_ranges(
4615                &[
4616                    // an empty selection - the following character is deleted
4617                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4618                    // one character selected - it is deleted
4619                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4620                    // a line suffix selected - it is deleted
4621                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
4622                ],
4623                cx,
4624            )
4625            .unwrap();
4626            view.delete(&Delete, cx);
4627        });
4628
4629        assert_eq!(
4630            buffer.read(cx).read(cx).text(),
4631            "on two three\nfou five six\nseven ten\n"
4632        );
4633    }
4634
4635    #[gpui::test]
4636    fn test_delete_line(cx: &mut gpui::MutableAppContext) {
4637        let settings = EditorSettings::test(&cx);
4638        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
4639        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4640        view.update(cx, |view, cx| {
4641            view.select_display_ranges(
4642                &[
4643                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4644                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
4645                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4646                ],
4647                cx,
4648            )
4649            .unwrap();
4650            view.delete_line(&DeleteLine, cx);
4651            assert_eq!(view.display_text(cx), "ghi");
4652            assert_eq!(
4653                view.selection_ranges(cx),
4654                vec![
4655                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4656                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
4657                ]
4658            );
4659        });
4660
4661        let settings = EditorSettings::test(&cx);
4662        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
4663        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4664        view.update(cx, |view, cx| {
4665            view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx)
4666                .unwrap();
4667            view.delete_line(&DeleteLine, cx);
4668            assert_eq!(view.display_text(cx), "ghi\n");
4669            assert_eq!(
4670                view.selection_ranges(cx),
4671                vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
4672            );
4673        });
4674    }
4675
4676    #[gpui::test]
4677    fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
4678        let settings = EditorSettings::test(&cx);
4679        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
4680        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4681        view.update(cx, |view, cx| {
4682            view.select_display_ranges(
4683                &[
4684                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4685                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4686                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4687                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4688                ],
4689                cx,
4690            )
4691            .unwrap();
4692            view.duplicate_line(&DuplicateLine, cx);
4693            assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
4694            assert_eq!(
4695                view.selection_ranges(cx),
4696                vec![
4697                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
4698                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4699                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4700                    DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
4701                ]
4702            );
4703        });
4704
4705        let settings = EditorSettings::test(&cx);
4706        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
4707        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4708        view.update(cx, |view, cx| {
4709            view.select_display_ranges(
4710                &[
4711                    DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
4712                    DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
4713                ],
4714                cx,
4715            )
4716            .unwrap();
4717            view.duplicate_line(&DuplicateLine, cx);
4718            assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
4719            assert_eq!(
4720                view.selection_ranges(cx),
4721                vec![
4722                    DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
4723                    DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
4724                ]
4725            );
4726        });
4727    }
4728
4729    #[gpui::test]
4730    fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
4731        let settings = EditorSettings::test(&cx);
4732        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
4733        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4734        view.update(cx, |view, cx| {
4735            view.fold_ranges(
4736                vec![
4737                    Point::new(0, 2)..Point::new(1, 2),
4738                    Point::new(2, 3)..Point::new(4, 1),
4739                    Point::new(7, 0)..Point::new(8, 4),
4740                ],
4741                cx,
4742            );
4743            view.select_display_ranges(
4744                &[
4745                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4746                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
4747                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
4748                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
4749                ],
4750                cx,
4751            )
4752            .unwrap();
4753            assert_eq!(
4754                view.display_text(cx),
4755                "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
4756            );
4757
4758            view.move_line_up(&MoveLineUp, cx);
4759            assert_eq!(
4760                view.display_text(cx),
4761                "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
4762            );
4763            assert_eq!(
4764                view.selection_ranges(cx),
4765                vec![
4766                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4767                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4768                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
4769                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
4770                ]
4771            );
4772        });
4773
4774        view.update(cx, |view, cx| {
4775            view.move_line_down(&MoveLineDown, cx);
4776            assert_eq!(
4777                view.display_text(cx),
4778                "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
4779            );
4780            assert_eq!(
4781                view.selection_ranges(cx),
4782                vec![
4783                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4784                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
4785                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
4786                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
4787                ]
4788            );
4789        });
4790
4791        view.update(cx, |view, cx| {
4792            view.move_line_down(&MoveLineDown, cx);
4793            assert_eq!(
4794                view.display_text(cx),
4795                "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
4796            );
4797            assert_eq!(
4798                view.selection_ranges(cx),
4799                vec![
4800                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4801                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
4802                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
4803                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
4804                ]
4805            );
4806        });
4807
4808        view.update(cx, |view, cx| {
4809            view.move_line_up(&MoveLineUp, cx);
4810            assert_eq!(
4811                view.display_text(cx),
4812                "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
4813            );
4814            assert_eq!(
4815                view.selection_ranges(cx),
4816                vec![
4817                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4818                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4819                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
4820                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
4821                ]
4822            );
4823        });
4824    }
4825
4826    #[gpui::test]
4827    fn test_clipboard(cx: &mut gpui::MutableAppContext) {
4828        let buffer = MultiBuffer::build_simple("one✅ two three four five six ", cx);
4829        let settings = EditorSettings::test(&cx);
4830        let view = cx
4831            .add_window(Default::default(), |cx| {
4832                build_editor(buffer.clone(), settings, cx)
4833            })
4834            .1;
4835
4836        // Cut with three selections. Clipboard text is divided into three slices.
4837        view.update(cx, |view, cx| {
4838            view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
4839            view.cut(&Cut, cx);
4840            assert_eq!(view.display_text(cx), "two four six ");
4841        });
4842
4843        // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
4844        view.update(cx, |view, cx| {
4845            view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
4846            view.paste(&Paste, cx);
4847            assert_eq!(view.display_text(cx), "two one✅ four three six five ");
4848            assert_eq!(
4849                view.selection_ranges(cx),
4850                &[
4851                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
4852                    DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
4853                    DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
4854                ]
4855            );
4856        });
4857
4858        // Paste again but with only two cursors. Since the number of cursors doesn't
4859        // match the number of slices in the clipboard, the entire clipboard text
4860        // is pasted at each cursor.
4861        view.update(cx, |view, cx| {
4862            view.select_ranges(vec![0..0, 31..31], None, cx);
4863            view.handle_input(&Input("( ".into()), cx);
4864            view.paste(&Paste, cx);
4865            view.handle_input(&Input(") ".into()), cx);
4866            assert_eq!(
4867                view.display_text(cx),
4868                "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
4869            );
4870        });
4871
4872        view.update(cx, |view, cx| {
4873            view.select_ranges(vec![0..0], None, cx);
4874            view.handle_input(&Input("123\n4567\n89\n".into()), cx);
4875            assert_eq!(
4876                view.display_text(cx),
4877                "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
4878            );
4879        });
4880
4881        // Cut with three selections, one of which is full-line.
4882        view.update(cx, |view, cx| {
4883            view.select_display_ranges(
4884                &[
4885                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
4886                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4887                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
4888                ],
4889                cx,
4890            )
4891            .unwrap();
4892            view.cut(&Cut, cx);
4893            assert_eq!(
4894                view.display_text(cx),
4895                "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
4896            );
4897        });
4898
4899        // Paste with three selections, noticing how the copied selection that was full-line
4900        // gets inserted before the second cursor.
4901        view.update(cx, |view, cx| {
4902            view.select_display_ranges(
4903                &[
4904                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4905                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4906                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
4907                ],
4908                cx,
4909            )
4910            .unwrap();
4911            view.paste(&Paste, cx);
4912            assert_eq!(
4913                view.display_text(cx),
4914                "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
4915            );
4916            assert_eq!(
4917                view.selection_ranges(cx),
4918                &[
4919                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4920                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4921                    DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
4922                ]
4923            );
4924        });
4925
4926        // Copy with a single cursor only, which writes the whole line into the clipboard.
4927        view.update(cx, |view, cx| {
4928            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx)
4929                .unwrap();
4930            view.copy(&Copy, cx);
4931        });
4932
4933        // Paste with three selections, noticing how the copied full-line selection is inserted
4934        // before the empty selections but replaces the selection that is non-empty.
4935        view.update(cx, |view, cx| {
4936            view.select_display_ranges(
4937                &[
4938                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4939                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
4940                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4941                ],
4942                cx,
4943            )
4944            .unwrap();
4945            view.paste(&Paste, cx);
4946            assert_eq!(
4947                view.display_text(cx),
4948                "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
4949            );
4950            assert_eq!(
4951                view.selection_ranges(cx),
4952                &[
4953                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4954                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4955                    DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
4956                ]
4957            );
4958        });
4959    }
4960
4961    #[gpui::test]
4962    fn test_select_all(cx: &mut gpui::MutableAppContext) {
4963        let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
4964        let settings = EditorSettings::test(&cx);
4965        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4966        view.update(cx, |view, cx| {
4967            view.select_all(&SelectAll, cx);
4968            assert_eq!(
4969                view.selection_ranges(cx),
4970                &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
4971            );
4972        });
4973    }
4974
4975    #[gpui::test]
4976    fn test_select_line(cx: &mut gpui::MutableAppContext) {
4977        let settings = EditorSettings::test(&cx);
4978        let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
4979        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4980        view.update(cx, |view, cx| {
4981            view.select_display_ranges(
4982                &[
4983                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4984                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4985                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4986                    DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
4987                ],
4988                cx,
4989            )
4990            .unwrap();
4991            view.select_line(&SelectLine, cx);
4992            assert_eq!(
4993                view.selection_ranges(cx),
4994                vec![
4995                    DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
4996                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
4997                ]
4998            );
4999        });
5000
5001        view.update(cx, |view, cx| {
5002            view.select_line(&SelectLine, cx);
5003            assert_eq!(
5004                view.selection_ranges(cx),
5005                vec![
5006                    DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
5007                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
5008                ]
5009            );
5010        });
5011
5012        view.update(cx, |view, cx| {
5013            view.select_line(&SelectLine, cx);
5014            assert_eq!(
5015                view.selection_ranges(cx),
5016                vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
5017            );
5018        });
5019    }
5020
5021    #[gpui::test]
5022    fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
5023        let settings = EditorSettings::test(&cx);
5024        let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
5025        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5026        view.update(cx, |view, cx| {
5027            view.fold_ranges(
5028                vec![
5029                    Point::new(0, 2)..Point::new(1, 2),
5030                    Point::new(2, 3)..Point::new(4, 1),
5031                    Point::new(7, 0)..Point::new(8, 4),
5032                ],
5033                cx,
5034            );
5035            view.select_display_ranges(
5036                &[
5037                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5038                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5039                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5040                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
5041                ],
5042                cx,
5043            )
5044            .unwrap();
5045            assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
5046        });
5047
5048        view.update(cx, |view, cx| {
5049            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5050            assert_eq!(
5051                view.display_text(cx),
5052                "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
5053            );
5054            assert_eq!(
5055                view.selection_ranges(cx),
5056                [
5057                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5058                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5059                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
5060                    DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
5061                ]
5062            );
5063        });
5064
5065        view.update(cx, |view, cx| {
5066            view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx)
5067                .unwrap();
5068            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5069            assert_eq!(
5070                view.display_text(cx),
5071                "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
5072            );
5073            assert_eq!(
5074                view.selection_ranges(cx),
5075                [
5076                    DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
5077                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
5078                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
5079                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
5080                    DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
5081                    DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
5082                    DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
5083                    DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
5084                ]
5085            );
5086        });
5087    }
5088
5089    #[gpui::test]
5090    fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
5091        let settings = EditorSettings::test(&cx);
5092        let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
5093        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5094
5095        view.update(cx, |view, cx| {
5096            view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx)
5097                .unwrap();
5098        });
5099        view.update(cx, |view, cx| {
5100            view.add_selection_above(&AddSelectionAbove, cx);
5101            assert_eq!(
5102                view.selection_ranges(cx),
5103                vec![
5104                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5105                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5106                ]
5107            );
5108        });
5109
5110        view.update(cx, |view, cx| {
5111            view.add_selection_above(&AddSelectionAbove, cx);
5112            assert_eq!(
5113                view.selection_ranges(cx),
5114                vec![
5115                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5116                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5117                ]
5118            );
5119        });
5120
5121        view.update(cx, |view, cx| {
5122            view.add_selection_below(&AddSelectionBelow, cx);
5123            assert_eq!(
5124                view.selection_ranges(cx),
5125                vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
5126            );
5127        });
5128
5129        view.update(cx, |view, cx| {
5130            view.add_selection_below(&AddSelectionBelow, cx);
5131            assert_eq!(
5132                view.selection_ranges(cx),
5133                vec![
5134                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5135                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5136                ]
5137            );
5138        });
5139
5140        view.update(cx, |view, cx| {
5141            view.add_selection_below(&AddSelectionBelow, cx);
5142            assert_eq!(
5143                view.selection_ranges(cx),
5144                vec![
5145                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5146                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5147                ]
5148            );
5149        });
5150
5151        view.update(cx, |view, cx| {
5152            view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx)
5153                .unwrap();
5154        });
5155        view.update(cx, |view, cx| {
5156            view.add_selection_below(&AddSelectionBelow, cx);
5157            assert_eq!(
5158                view.selection_ranges(cx),
5159                vec![
5160                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5161                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5162                ]
5163            );
5164        });
5165
5166        view.update(cx, |view, cx| {
5167            view.add_selection_below(&AddSelectionBelow, cx);
5168            assert_eq!(
5169                view.selection_ranges(cx),
5170                vec![
5171                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5172                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5173                ]
5174            );
5175        });
5176
5177        view.update(cx, |view, cx| {
5178            view.add_selection_above(&AddSelectionAbove, cx);
5179            assert_eq!(
5180                view.selection_ranges(cx),
5181                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5182            );
5183        });
5184
5185        view.update(cx, |view, cx| {
5186            view.add_selection_above(&AddSelectionAbove, cx);
5187            assert_eq!(
5188                view.selection_ranges(cx),
5189                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5190            );
5191        });
5192
5193        view.update(cx, |view, cx| {
5194            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx)
5195                .unwrap();
5196            view.add_selection_below(&AddSelectionBelow, cx);
5197            assert_eq!(
5198                view.selection_ranges(cx),
5199                vec![
5200                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5201                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5202                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5203                ]
5204            );
5205        });
5206
5207        view.update(cx, |view, cx| {
5208            view.add_selection_below(&AddSelectionBelow, cx);
5209            assert_eq!(
5210                view.selection_ranges(cx),
5211                vec![
5212                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5213                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5214                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5215                    DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
5216                ]
5217            );
5218        });
5219
5220        view.update(cx, |view, cx| {
5221            view.add_selection_above(&AddSelectionAbove, cx);
5222            assert_eq!(
5223                view.selection_ranges(cx),
5224                vec![
5225                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5226                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5227                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5228                ]
5229            );
5230        });
5231
5232        view.update(cx, |view, cx| {
5233            view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx)
5234                .unwrap();
5235        });
5236        view.update(cx, |view, cx| {
5237            view.add_selection_above(&AddSelectionAbove, cx);
5238            assert_eq!(
5239                view.selection_ranges(cx),
5240                vec![
5241                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
5242                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5243                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5244                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5245                ]
5246            );
5247        });
5248
5249        view.update(cx, |view, cx| {
5250            view.add_selection_below(&AddSelectionBelow, cx);
5251            assert_eq!(
5252                view.selection_ranges(cx),
5253                vec![
5254                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5255                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5256                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5257                ]
5258            );
5259        });
5260    }
5261
5262    #[gpui::test]
5263    async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
5264        let settings = cx.read(EditorSettings::test);
5265        let language = Some(Arc::new(Language::new(
5266            LanguageConfig::default(),
5267            Some(tree_sitter_rust::language()),
5268        )));
5269
5270        let text = r#"
5271            use mod1::mod2::{mod3, mod4};
5272
5273            fn fn_1(param1: bool, param2: &str) {
5274                let var1 = "text";
5275            }
5276        "#
5277        .unindent();
5278
5279        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5280        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5281        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5282        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
5283            .await;
5284
5285        view.update(&mut cx, |view, cx| {
5286            view.select_display_ranges(
5287                &[
5288                    DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5289                    DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5290                    DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5291                ],
5292                cx,
5293            )
5294            .unwrap();
5295            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5296        });
5297        assert_eq!(
5298            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5299            &[
5300                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5301                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5302                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5303            ]
5304        );
5305
5306        view.update(&mut cx, |view, cx| {
5307            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5308        });
5309        assert_eq!(
5310            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5311            &[
5312                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5313                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5314            ]
5315        );
5316
5317        view.update(&mut cx, |view, cx| {
5318            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5319        });
5320        assert_eq!(
5321            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5322            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5323        );
5324
5325        // Trying to expand the selected syntax node one more time has no effect.
5326        view.update(&mut cx, |view, cx| {
5327            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5328        });
5329        assert_eq!(
5330            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5331            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5332        );
5333
5334        view.update(&mut cx, |view, cx| {
5335            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5336        });
5337        assert_eq!(
5338            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5339            &[
5340                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5341                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5342            ]
5343        );
5344
5345        view.update(&mut cx, |view, cx| {
5346            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5347        });
5348        assert_eq!(
5349            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5350            &[
5351                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5352                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5353                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5354            ]
5355        );
5356
5357        view.update(&mut cx, |view, cx| {
5358            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5359        });
5360        assert_eq!(
5361            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5362            &[
5363                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5364                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5365                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5366            ]
5367        );
5368
5369        // Trying to shrink the selected syntax node one more time has no effect.
5370        view.update(&mut cx, |view, cx| {
5371            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5372        });
5373        assert_eq!(
5374            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5375            &[
5376                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5377                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5378                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5379            ]
5380        );
5381
5382        // Ensure that we keep expanding the selection if the larger selection starts or ends within
5383        // a fold.
5384        view.update(&mut cx, |view, cx| {
5385            view.fold_ranges(
5386                vec![
5387                    Point::new(0, 21)..Point::new(0, 24),
5388                    Point::new(3, 20)..Point::new(3, 22),
5389                ],
5390                cx,
5391            );
5392            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5393        });
5394        assert_eq!(
5395            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5396            &[
5397                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5398                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5399                DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
5400            ]
5401        );
5402    }
5403
5404    #[gpui::test]
5405    async fn test_autoclose_pairs(mut cx: gpui::TestAppContext) {
5406        let settings = cx.read(EditorSettings::test);
5407        let language = Some(Arc::new(Language::new(
5408            LanguageConfig {
5409                brackets: vec![
5410                    BracketPair {
5411                        start: "{".to_string(),
5412                        end: "}".to_string(),
5413                        close: true,
5414                        newline: true,
5415                    },
5416                    BracketPair {
5417                        start: "/*".to_string(),
5418                        end: " */".to_string(),
5419                        close: true,
5420                        newline: true,
5421                    },
5422                ],
5423                ..Default::default()
5424            },
5425            Some(tree_sitter_rust::language()),
5426        )));
5427
5428        let text = r#"
5429            a
5430
5431            /
5432
5433        "#
5434        .unindent();
5435
5436        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5437        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5438        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5439        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
5440            .await;
5441
5442        view.update(&mut cx, |view, cx| {
5443            view.select_display_ranges(
5444                &[
5445                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5446                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5447                ],
5448                cx,
5449            )
5450            .unwrap();
5451            view.handle_input(&Input("{".to_string()), cx);
5452            view.handle_input(&Input("{".to_string()), cx);
5453            view.handle_input(&Input("{".to_string()), cx);
5454            assert_eq!(
5455                view.text(cx),
5456                "
5457                {{{}}}
5458                {{{}}}
5459                /
5460
5461                "
5462                .unindent()
5463            );
5464
5465            view.move_right(&MoveRight, cx);
5466            view.handle_input(&Input("}".to_string()), cx);
5467            view.handle_input(&Input("}".to_string()), cx);
5468            view.handle_input(&Input("}".to_string()), cx);
5469            assert_eq!(
5470                view.text(cx),
5471                "
5472                {{{}}}}
5473                {{{}}}}
5474                /
5475
5476                "
5477                .unindent()
5478            );
5479
5480            view.undo(&Undo, cx);
5481            view.handle_input(&Input("/".to_string()), cx);
5482            view.handle_input(&Input("*".to_string()), cx);
5483            assert_eq!(
5484                view.text(cx),
5485                "
5486                /* */
5487                /* */
5488                /
5489
5490                "
5491                .unindent()
5492            );
5493
5494            view.undo(&Undo, cx);
5495            view.select_display_ranges(
5496                &[
5497                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5498                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5499                ],
5500                cx,
5501            )
5502            .unwrap();
5503            view.handle_input(&Input("*".to_string()), cx);
5504            assert_eq!(
5505                view.text(cx),
5506                "
5507                a
5508
5509                /*
5510                *
5511                "
5512                .unindent()
5513            );
5514        });
5515    }
5516
5517    #[gpui::test]
5518    async fn test_toggle_comment(mut cx: gpui::TestAppContext) {
5519        let settings = cx.read(EditorSettings::test);
5520        let language = Some(Arc::new(Language::new(
5521            LanguageConfig {
5522                line_comment: Some("// ".to_string()),
5523                ..Default::default()
5524            },
5525            Some(tree_sitter_rust::language()),
5526        )));
5527
5528        let text = "
5529            fn a() {
5530                //b();
5531                // c();
5532                //  d();
5533            }
5534        "
5535        .unindent();
5536
5537        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5538        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5539        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5540
5541        view.update(&mut cx, |editor, cx| {
5542            // If multiple selections intersect a line, the line is only
5543            // toggled once.
5544            editor
5545                .select_display_ranges(
5546                    &[
5547                        DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
5548                        DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
5549                    ],
5550                    cx,
5551                )
5552                .unwrap();
5553            editor.toggle_comments(&ToggleComments, cx);
5554            assert_eq!(
5555                editor.text(cx),
5556                "
5557                    fn a() {
5558                        b();
5559                        c();
5560                         d();
5561                    }
5562                "
5563                .unindent()
5564            );
5565
5566            // The comment prefix is inserted at the same column for every line
5567            // in a selection.
5568            editor
5569                .select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx)
5570                .unwrap();
5571            editor.toggle_comments(&ToggleComments, cx);
5572            assert_eq!(
5573                editor.text(cx),
5574                "
5575                    fn a() {
5576                        // b();
5577                        // c();
5578                        //  d();
5579                    }
5580                "
5581                .unindent()
5582            );
5583
5584            // If a selection ends at the beginning of a line, that line is not toggled.
5585            editor
5586                .select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx)
5587                .unwrap();
5588            editor.toggle_comments(&ToggleComments, cx);
5589            assert_eq!(
5590                editor.text(cx),
5591                "
5592                        fn a() {
5593                            // b();
5594                            c();
5595                            //  d();
5596                        }
5597                    "
5598                .unindent()
5599            );
5600        });
5601    }
5602
5603    #[gpui::test]
5604    async fn test_extra_newline_insertion(mut cx: gpui::TestAppContext) {
5605        let settings = cx.read(EditorSettings::test);
5606        let language = Some(Arc::new(Language::new(
5607            LanguageConfig {
5608                brackets: vec![
5609                    BracketPair {
5610                        start: "{".to_string(),
5611                        end: "}".to_string(),
5612                        close: true,
5613                        newline: true,
5614                    },
5615                    BracketPair {
5616                        start: "/* ".to_string(),
5617                        end: " */".to_string(),
5618                        close: true,
5619                        newline: true,
5620                    },
5621                ],
5622                ..Default::default()
5623            },
5624            Some(tree_sitter_rust::language()),
5625        )));
5626
5627        let text = concat!(
5628            "{   }\n",     // Suppress rustfmt
5629            "  x\n",       //
5630            "  /*   */\n", //
5631            "x\n",         //
5632            "{{} }\n",     //
5633        );
5634
5635        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5636        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5637        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5638        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
5639            .await;
5640
5641        view.update(&mut cx, |view, cx| {
5642            view.select_display_ranges(
5643                &[
5644                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
5645                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
5646                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
5647                ],
5648                cx,
5649            )
5650            .unwrap();
5651            view.newline(&Newline, cx);
5652
5653            assert_eq!(
5654                view.buffer().read(cx).read(cx).text(),
5655                concat!(
5656                    "{ \n",    // Suppress rustfmt
5657                    "\n",      //
5658                    "}\n",     //
5659                    "  x\n",   //
5660                    "  /* \n", //
5661                    "  \n",    //
5662                    "  */\n",  //
5663                    "x\n",     //
5664                    "{{} \n",  //
5665                    "}\n",     //
5666                )
5667            );
5668        });
5669    }
5670
5671    impl Editor {
5672        fn selection_ranges(&self, cx: &mut MutableAppContext) -> Vec<Range<DisplayPoint>> {
5673            self.intersecting_selections(
5674                self.selection_set_id,
5675                DisplayPoint::zero()..self.max_point(cx),
5676                cx,
5677            )
5678            .into_iter()
5679            .map(|s| {
5680                if s.reversed {
5681                    s.end..s.start
5682                } else {
5683                    s.start..s.end
5684                }
5685            })
5686            .collect()
5687        }
5688    }
5689
5690    fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
5691        let point = DisplayPoint::new(row as u32, column as u32);
5692        point..point
5693    }
5694
5695    fn build_editor(
5696        buffer: ModelHandle<MultiBuffer>,
5697        settings: EditorSettings,
5698        cx: &mut ViewContext<Editor>,
5699    ) -> Editor {
5700        Editor::for_buffer(buffer, move |_| settings.clone(), cx)
5701    }
5702}
5703
5704trait RangeExt<T> {
5705    fn sorted(&self) -> Range<T>;
5706    fn to_inclusive(&self) -> RangeInclusive<T>;
5707}
5708
5709impl<T: Ord + Clone> RangeExt<T> for Range<T> {
5710    fn sorted(&self) -> Self {
5711        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
5712    }
5713
5714    fn to_inclusive(&self) -> RangeInclusive<T> {
5715        self.start.clone()..=self.end.clone()
5716    }
5717}