editor.rs

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