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