lib.rs

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