editor.rs

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