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