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    pub 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, is_valid, cx.anchor_x)
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, true, cx.anchor_x)
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(
3645    diagnostic: Diagnostic,
3646    style: &EditorStyle,
3647    valid: bool,
3648    anchor_x: f32,
3649) -> ElementBox {
3650    let mut text_style = style.text.clone();
3651    text_style.color = diagnostic_style(diagnostic.severity, valid, &style).text;
3652    Text::new(diagnostic.message, text_style)
3653        .contained()
3654        .with_margin_left(anchor_x)
3655        .boxed()
3656}
3657
3658pub fn diagnostic_style(
3659    severity: DiagnosticSeverity,
3660    valid: bool,
3661    style: &EditorStyle,
3662) -> DiagnosticStyle {
3663    match (severity, valid) {
3664        (DiagnosticSeverity::ERROR, true) => style.error_diagnostic,
3665        (DiagnosticSeverity::ERROR, false) => style.invalid_error_diagnostic,
3666        (DiagnosticSeverity::WARNING, true) => style.warning_diagnostic,
3667        (DiagnosticSeverity::WARNING, false) => style.invalid_warning_diagnostic,
3668        (DiagnosticSeverity::INFORMATION, true) => style.information_diagnostic,
3669        (DiagnosticSeverity::INFORMATION, false) => style.invalid_information_diagnostic,
3670        (DiagnosticSeverity::HINT, true) => style.hint_diagnostic,
3671        (DiagnosticSeverity::HINT, false) => style.invalid_hint_diagnostic,
3672        _ => Default::default(),
3673    }
3674}
3675
3676#[cfg(test)]
3677mod tests {
3678    use super::*;
3679    use crate::test::sample_text;
3680    use text::Point;
3681    use unindent::Unindent;
3682
3683    #[gpui::test]
3684    fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
3685        let buffer = cx.add_model(|cx| Buffer::new(0, "aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx));
3686        let settings = EditorSettings::test(cx);
3687        let (_, editor) =
3688            cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3689
3690        editor.update(cx, |view, cx| {
3691            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
3692        });
3693
3694        assert_eq!(
3695            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3696            [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
3697        );
3698
3699        editor.update(cx, |view, cx| {
3700            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
3701        });
3702
3703        assert_eq!(
3704            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3705            [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3706        );
3707
3708        editor.update(cx, |view, cx| {
3709            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
3710        });
3711
3712        assert_eq!(
3713            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3714            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
3715        );
3716
3717        editor.update(cx, |view, cx| {
3718            view.end_selection(cx);
3719            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
3720        });
3721
3722        assert_eq!(
3723            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3724            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
3725        );
3726
3727        editor.update(cx, |view, cx| {
3728            view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
3729            view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
3730        });
3731
3732        assert_eq!(
3733            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3734            [
3735                DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
3736                DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
3737            ]
3738        );
3739
3740        editor.update(cx, |view, cx| {
3741            view.end_selection(cx);
3742        });
3743
3744        assert_eq!(
3745            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3746            [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
3747        );
3748    }
3749
3750    #[gpui::test]
3751    fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
3752        let buffer = cx.add_model(|cx| Buffer::new(0, "aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx));
3753        let settings = EditorSettings::test(cx);
3754        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3755
3756        view.update(cx, |view, cx| {
3757            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
3758            assert_eq!(
3759                view.selection_ranges(cx),
3760                [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
3761            );
3762        });
3763
3764        view.update(cx, |view, cx| {
3765            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
3766            assert_eq!(
3767                view.selection_ranges(cx),
3768                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3769            );
3770        });
3771
3772        view.update(cx, |view, cx| {
3773            view.cancel(&Cancel, cx);
3774            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
3775            assert_eq!(
3776                view.selection_ranges(cx),
3777                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3778            );
3779        });
3780    }
3781
3782    #[gpui::test]
3783    fn test_cancel(cx: &mut gpui::MutableAppContext) {
3784        let buffer = cx.add_model(|cx| Buffer::new(0, "aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx));
3785        let settings = EditorSettings::test(cx);
3786        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3787
3788        view.update(cx, |view, cx| {
3789            view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
3790            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
3791            view.end_selection(cx);
3792
3793            view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
3794            view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
3795            view.end_selection(cx);
3796            assert_eq!(
3797                view.selection_ranges(cx),
3798                [
3799                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
3800                    DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
3801                ]
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(3, 4)..DisplayPoint::new(1, 1)]
3810            );
3811        });
3812
3813        view.update(cx, |view, cx| {
3814            view.cancel(&Cancel, cx);
3815            assert_eq!(
3816                view.selection_ranges(cx),
3817                [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
3818            );
3819        });
3820    }
3821
3822    #[gpui::test]
3823    fn test_fold(cx: &mut gpui::MutableAppContext) {
3824        let buffer = cx.add_model(|cx| {
3825            Buffer::new(
3826                0,
3827                "
3828                    impl Foo {
3829                        // Hello!
3830
3831                        fn a() {
3832                            1
3833                        }
3834
3835                        fn b() {
3836                            2
3837                        }
3838
3839                        fn c() {
3840                            3
3841                        }
3842                    }
3843                "
3844                .unindent(),
3845                cx,
3846            )
3847        });
3848        let settings = EditorSettings::test(&cx);
3849        let (_, view) = cx.add_window(Default::default(), |cx| {
3850            build_editor(buffer.clone(), settings, cx)
3851        });
3852
3853        view.update(cx, |view, cx| {
3854            view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx)
3855                .unwrap();
3856            view.fold(&Fold, cx);
3857            assert_eq!(
3858                view.display_text(cx),
3859                "
3860                    impl Foo {
3861                        // Hello!
3862
3863                        fn a() {
3864                            1
3865                        }
3866
3867                        fn b() {…
3868                        }
3869
3870                        fn c() {…
3871                        }
3872                    }
3873                "
3874                .unindent(),
3875            );
3876
3877            view.fold(&Fold, cx);
3878            assert_eq!(
3879                view.display_text(cx),
3880                "
3881                    impl Foo {…
3882                    }
3883                "
3884                .unindent(),
3885            );
3886
3887            view.unfold(&Unfold, cx);
3888            assert_eq!(
3889                view.display_text(cx),
3890                "
3891                    impl Foo {
3892                        // Hello!
3893
3894                        fn a() {
3895                            1
3896                        }
3897
3898                        fn b() {…
3899                        }
3900
3901                        fn c() {…
3902                        }
3903                    }
3904                "
3905                .unindent(),
3906            );
3907
3908            view.unfold(&Unfold, cx);
3909            assert_eq!(view.display_text(cx), buffer.read(cx).text());
3910        });
3911    }
3912
3913    #[gpui::test]
3914    fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
3915        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6), cx));
3916        let settings = EditorSettings::test(&cx);
3917        let (_, view) = cx.add_window(Default::default(), |cx| {
3918            build_editor(buffer.clone(), settings, cx)
3919        });
3920
3921        buffer.update(cx, |buffer, cx| {
3922            buffer.edit(
3923                vec![
3924                    Point::new(1, 0)..Point::new(1, 0),
3925                    Point::new(1, 1)..Point::new(1, 1),
3926                ],
3927                "\t",
3928                cx,
3929            );
3930        });
3931
3932        view.update(cx, |view, cx| {
3933            assert_eq!(
3934                view.selection_ranges(cx),
3935                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
3936            );
3937
3938            view.move_down(&MoveDown, cx);
3939            assert_eq!(
3940                view.selection_ranges(cx),
3941                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
3942            );
3943
3944            view.move_right(&MoveRight, cx);
3945            assert_eq!(
3946                view.selection_ranges(cx),
3947                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
3948            );
3949
3950            view.move_left(&MoveLeft, cx);
3951            assert_eq!(
3952                view.selection_ranges(cx),
3953                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
3954            );
3955
3956            view.move_up(&MoveUp, cx);
3957            assert_eq!(
3958                view.selection_ranges(cx),
3959                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
3960            );
3961
3962            view.move_to_end(&MoveToEnd, cx);
3963            assert_eq!(
3964                view.selection_ranges(cx),
3965                &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
3966            );
3967
3968            view.move_to_beginning(&MoveToBeginning, cx);
3969            assert_eq!(
3970                view.selection_ranges(cx),
3971                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
3972            );
3973
3974            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx)
3975                .unwrap();
3976            view.select_to_beginning(&SelectToBeginning, cx);
3977            assert_eq!(
3978                view.selection_ranges(cx),
3979                &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
3980            );
3981
3982            view.select_to_end(&SelectToEnd, cx);
3983            assert_eq!(
3984                view.selection_ranges(cx),
3985                &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
3986            );
3987        });
3988    }
3989
3990    #[gpui::test]
3991    fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
3992        let buffer = cx.add_model(|cx| Buffer::new(0, "ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx));
3993        let settings = EditorSettings::test(&cx);
3994        let (_, view) = cx.add_window(Default::default(), |cx| {
3995            build_editor(buffer.clone(), settings, cx)
3996        });
3997
3998        assert_eq!('ⓐ'.len_utf8(), 3);
3999        assert_eq!('α'.len_utf8(), 2);
4000
4001        view.update(cx, |view, cx| {
4002            view.fold_ranges(
4003                vec![
4004                    Point::new(0, 6)..Point::new(0, 12),
4005                    Point::new(1, 2)..Point::new(1, 4),
4006                    Point::new(2, 4)..Point::new(2, 8),
4007                ],
4008                cx,
4009            );
4010            assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
4011
4012            view.move_right(&MoveRight, cx);
4013            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "".len())]);
4014            view.move_right(&MoveRight, cx);
4015            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ".len())]);
4016            view.move_right(&MoveRight, cx);
4017            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…".len())]);
4018
4019            view.move_down(&MoveDown, cx);
4020            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab…".len())]);
4021            view.move_left(&MoveLeft, cx);
4022            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab".len())]);
4023            view.move_left(&MoveLeft, cx);
4024            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "a".len())]);
4025
4026            view.move_down(&MoveDown, cx);
4027            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "α".len())]);
4028            view.move_right(&MoveRight, cx);
4029            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ".len())]);
4030            view.move_right(&MoveRight, cx);
4031            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ…".len())]);
4032            view.move_right(&MoveRight, cx);
4033            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ…ε".len())]);
4034
4035            view.move_up(&MoveUp, cx);
4036            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab…e".len())]);
4037            view.move_up(&MoveUp, cx);
4038            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…ⓔ".len())]);
4039            view.move_left(&MoveLeft, cx);
4040            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…".len())]);
4041            view.move_left(&MoveLeft, cx);
4042            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ".len())]);
4043            view.move_left(&MoveLeft, cx);
4044            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "".len())]);
4045        });
4046    }
4047
4048    #[gpui::test]
4049    fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
4050        let buffer = cx.add_model(|cx| Buffer::new(0, "ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx));
4051        let settings = EditorSettings::test(&cx);
4052        let (_, view) = cx.add_window(Default::default(), |cx| {
4053            build_editor(buffer.clone(), settings, cx)
4054        });
4055        view.update(cx, |view, cx| {
4056            view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx)
4057                .unwrap();
4058
4059            view.move_down(&MoveDown, cx);
4060            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "abcd".len())]);
4061
4062            view.move_down(&MoveDown, cx);
4063            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβγ".len())]);
4064
4065            view.move_down(&MoveDown, cx);
4066            assert_eq!(view.selection_ranges(cx), &[empty_range(3, "abcd".len())]);
4067
4068            view.move_down(&MoveDown, cx);
4069            assert_eq!(view.selection_ranges(cx), &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]);
4070
4071            view.move_up(&MoveUp, cx);
4072            assert_eq!(view.selection_ranges(cx), &[empty_range(3, "abcd".len())]);
4073
4074            view.move_up(&MoveUp, cx);
4075            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβγ".len())]);
4076        });
4077    }
4078
4079    #[gpui::test]
4080    fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
4081        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\n  def", cx));
4082        let settings = EditorSettings::test(&cx);
4083        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4084        view.update(cx, |view, cx| {
4085            view.select_display_ranges(
4086                &[
4087                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4088                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4089                ],
4090                cx,
4091            )
4092            .unwrap();
4093        });
4094
4095        view.update(cx, |view, cx| {
4096            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4097            assert_eq!(
4098                view.selection_ranges(cx),
4099                &[
4100                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4101                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4102                ]
4103            );
4104        });
4105
4106        view.update(cx, |view, cx| {
4107            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4108            assert_eq!(
4109                view.selection_ranges(cx),
4110                &[
4111                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4112                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4113                ]
4114            );
4115        });
4116
4117        view.update(cx, |view, cx| {
4118            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4119            assert_eq!(
4120                view.selection_ranges(cx),
4121                &[
4122                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4123                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4124                ]
4125            );
4126        });
4127
4128        view.update(cx, |view, cx| {
4129            view.move_to_end_of_line(&MoveToEndOfLine, cx);
4130            assert_eq!(
4131                view.selection_ranges(cx),
4132                &[
4133                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4134                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4135                ]
4136            );
4137        });
4138
4139        // Moving to the end of line again is a no-op.
4140        view.update(cx, |view, cx| {
4141            view.move_to_end_of_line(&MoveToEndOfLine, cx);
4142            assert_eq!(
4143                view.selection_ranges(cx),
4144                &[
4145                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4146                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4147                ]
4148            );
4149        });
4150
4151        view.update(cx, |view, cx| {
4152            view.move_left(&MoveLeft, cx);
4153            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4154            assert_eq!(
4155                view.selection_ranges(cx),
4156                &[
4157                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4158                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4159                ]
4160            );
4161        });
4162
4163        view.update(cx, |view, cx| {
4164            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4165            assert_eq!(
4166                view.selection_ranges(cx),
4167                &[
4168                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4169                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
4170                ]
4171            );
4172        });
4173
4174        view.update(cx, |view, cx| {
4175            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4176            assert_eq!(
4177                view.selection_ranges(cx),
4178                &[
4179                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4180                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4181                ]
4182            );
4183        });
4184
4185        view.update(cx, |view, cx| {
4186            view.select_to_end_of_line(&SelectToEndOfLine, cx);
4187            assert_eq!(
4188                view.selection_ranges(cx),
4189                &[
4190                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
4191                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
4192                ]
4193            );
4194        });
4195
4196        view.update(cx, |view, cx| {
4197            view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
4198            assert_eq!(view.display_text(cx), "ab\n  de");
4199            assert_eq!(
4200                view.selection_ranges(cx),
4201                &[
4202                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4203                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4204                ]
4205            );
4206        });
4207
4208        view.update(cx, |view, cx| {
4209            view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
4210            assert_eq!(view.display_text(cx), "\n");
4211            assert_eq!(
4212                view.selection_ranges(cx),
4213                &[
4214                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4215                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4216                ]
4217            );
4218        });
4219    }
4220
4221    #[gpui::test]
4222    fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
4223        let buffer =
4224            cx.add_model(|cx| Buffer::new(0, "use std::str::{foo, bar}\n\n  {baz.qux()}", cx));
4225        let settings = EditorSettings::test(&cx);
4226        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4227        view.update(cx, |view, cx| {
4228            view.select_display_ranges(
4229                &[
4230                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
4231                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
4232                ],
4233                cx,
4234            )
4235            .unwrap();
4236        });
4237
4238        view.update(cx, |view, cx| {
4239            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4240            assert_eq!(
4241                view.selection_ranges(cx),
4242                &[
4243                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4244                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4245                ]
4246            );
4247        });
4248
4249        view.update(cx, |view, cx| {
4250            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4251            assert_eq!(
4252                view.selection_ranges(cx),
4253                &[
4254                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4255                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
4256                ]
4257            );
4258        });
4259
4260        view.update(cx, |view, cx| {
4261            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4262            assert_eq!(
4263                view.selection_ranges(cx),
4264                &[
4265                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
4266                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
4267                ]
4268            );
4269        });
4270
4271        view.update(cx, |view, cx| {
4272            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4273            assert_eq!(
4274                view.selection_ranges(cx),
4275                &[
4276                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4277                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4278                ]
4279            );
4280        });
4281
4282        view.update(cx, |view, cx| {
4283            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4284            assert_eq!(
4285                view.selection_ranges(cx),
4286                &[
4287                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4288                    DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
4289                ]
4290            );
4291        });
4292
4293        view.update(cx, |view, cx| {
4294            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4295            assert_eq!(
4296                view.selection_ranges(cx),
4297                &[
4298                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4299                    DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
4300                ]
4301            );
4302        });
4303
4304        view.update(cx, |view, cx| {
4305            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4306            assert_eq!(
4307                view.selection_ranges(cx),
4308                &[
4309                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4310                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4311                ]
4312            );
4313        });
4314
4315        view.update(cx, |view, cx| {
4316            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4317            assert_eq!(
4318                view.selection_ranges(cx),
4319                &[
4320                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4321                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4322                ]
4323            );
4324        });
4325
4326        view.update(cx, |view, cx| {
4327            view.move_right(&MoveRight, cx);
4328            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4329            assert_eq!(
4330                view.selection_ranges(cx),
4331                &[
4332                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
4333                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
4334                ]
4335            );
4336        });
4337
4338        view.update(cx, |view, cx| {
4339            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4340            assert_eq!(
4341                view.selection_ranges(cx),
4342                &[
4343                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
4344                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
4345                ]
4346            );
4347        });
4348
4349        view.update(cx, |view, cx| {
4350            view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
4351            assert_eq!(
4352                view.selection_ranges(cx),
4353                &[
4354                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
4355                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
4356                ]
4357            );
4358        });
4359    }
4360
4361    #[gpui::test]
4362    fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
4363        let buffer =
4364            cx.add_model(|cx| Buffer::new(0, "use one::{\n    two::three::four::five\n};", cx));
4365        let settings = EditorSettings::test(&cx);
4366        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4367
4368        view.update(cx, |view, cx| {
4369            view.set_wrap_width(Some(140.), cx);
4370            assert_eq!(
4371                view.display_text(cx),
4372                "use one::{\n    two::three::\n    four::five\n};"
4373            );
4374
4375            view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx)
4376                .unwrap();
4377
4378            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4379            assert_eq!(
4380                view.selection_ranges(cx),
4381                &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
4382            );
4383
4384            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4385            assert_eq!(
4386                view.selection_ranges(cx),
4387                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
4388            );
4389
4390            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4391            assert_eq!(
4392                view.selection_ranges(cx),
4393                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
4394            );
4395
4396            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4397            assert_eq!(
4398                view.selection_ranges(cx),
4399                &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
4400            );
4401
4402            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4403            assert_eq!(
4404                view.selection_ranges(cx),
4405                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
4406            );
4407
4408            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4409            assert_eq!(
4410                view.selection_ranges(cx),
4411                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
4412            );
4413        });
4414    }
4415
4416    #[gpui::test]
4417    fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
4418        let buffer = cx.add_model(|cx| Buffer::new(0, "one two three four", cx));
4419        let settings = EditorSettings::test(&cx);
4420        let (_, view) = cx.add_window(Default::default(), |cx| {
4421            build_editor(buffer.clone(), settings, cx)
4422        });
4423
4424        view.update(cx, |view, cx| {
4425            view.select_display_ranges(
4426                &[
4427                    // an empty selection - the preceding word fragment is deleted
4428                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4429                    // characters selected - they are deleted
4430                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
4431                ],
4432                cx,
4433            )
4434            .unwrap();
4435            view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
4436        });
4437
4438        assert_eq!(buffer.read(cx).text(), "e two te four");
4439
4440        view.update(cx, |view, cx| {
4441            view.select_display_ranges(
4442                &[
4443                    // an empty selection - the following word fragment is deleted
4444                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4445                    // characters selected - they are deleted
4446                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
4447                ],
4448                cx,
4449            )
4450            .unwrap();
4451            view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
4452        });
4453
4454        assert_eq!(buffer.read(cx).text(), "e t te our");
4455    }
4456
4457    #[gpui::test]
4458    fn test_newline(cx: &mut gpui::MutableAppContext) {
4459        let buffer = cx.add_model(|cx| Buffer::new(0, "aaaa\n    bbbb\n", cx));
4460        let settings = EditorSettings::test(&cx);
4461        let (_, view) = cx.add_window(Default::default(), |cx| {
4462            build_editor(buffer.clone(), settings, cx)
4463        });
4464
4465        view.update(cx, |view, cx| {
4466            view.select_display_ranges(
4467                &[
4468                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4469                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4470                    DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
4471                ],
4472                cx,
4473            )
4474            .unwrap();
4475
4476            view.newline(&Newline, cx);
4477            assert_eq!(view.text(cx), "aa\naa\n  \n    bb\n    bb\n");
4478        });
4479    }
4480
4481    #[gpui::test]
4482    fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
4483        let buffer = cx.add_model(|cx| Buffer::new(0, "  one two\nthree\n four", cx));
4484        let settings = EditorSettings::test(&cx);
4485        let (_, view) = cx.add_window(Default::default(), |cx| {
4486            build_editor(buffer.clone(), settings, cx)
4487        });
4488
4489        view.update(cx, |view, cx| {
4490            // two selections on the same line
4491            view.select_display_ranges(
4492                &[
4493                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
4494                    DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
4495                ],
4496                cx,
4497            )
4498            .unwrap();
4499
4500            // indent from mid-tabstop to full tabstop
4501            view.tab(&Tab, cx);
4502            assert_eq!(view.text(cx), "    one two\nthree\n four");
4503            assert_eq!(
4504                view.selection_ranges(cx),
4505                &[
4506                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
4507                    DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
4508                ]
4509            );
4510
4511            // outdent from 1 tabstop to 0 tabstops
4512            view.outdent(&Outdent, cx);
4513            assert_eq!(view.text(cx), "one two\nthree\n four");
4514            assert_eq!(
4515                view.selection_ranges(cx),
4516                &[
4517                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
4518                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
4519                ]
4520            );
4521
4522            // select across line ending
4523            view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx)
4524                .unwrap();
4525
4526            // indent and outdent affect only the preceding line
4527            view.tab(&Tab, cx);
4528            assert_eq!(view.text(cx), "one two\n    three\n four");
4529            assert_eq!(
4530                view.selection_ranges(cx),
4531                &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
4532            );
4533            view.outdent(&Outdent, cx);
4534            assert_eq!(view.text(cx), "one two\nthree\n four");
4535            assert_eq!(
4536                view.selection_ranges(cx),
4537                &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
4538            );
4539        });
4540    }
4541
4542    #[gpui::test]
4543    fn test_backspace(cx: &mut gpui::MutableAppContext) {
4544        let buffer = cx.add_model(|cx| {
4545            Buffer::new(
4546                0,
4547                "one two three\nfour five six\nseven eight nine\nten\n",
4548                cx,
4549            )
4550        });
4551        let settings = EditorSettings::test(&cx);
4552        let (_, view) = cx.add_window(Default::default(), |cx| {
4553            build_editor(buffer.clone(), settings, cx)
4554        });
4555
4556        view.update(cx, |view, cx| {
4557            view.select_display_ranges(
4558                &[
4559                    // an empty selection - the preceding character is deleted
4560                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4561                    // one character selected - it is deleted
4562                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4563                    // a line suffix selected - it is deleted
4564                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
4565                ],
4566                cx,
4567            )
4568            .unwrap();
4569            view.backspace(&Backspace, cx);
4570        });
4571
4572        assert_eq!(
4573            buffer.read(cx).text(),
4574            "oe two three\nfou five six\nseven ten\n"
4575        );
4576    }
4577
4578    #[gpui::test]
4579    fn test_delete(cx: &mut gpui::MutableAppContext) {
4580        let buffer = cx.add_model(|cx| {
4581            Buffer::new(
4582                0,
4583                "one two three\nfour five six\nseven eight nine\nten\n",
4584                cx,
4585            )
4586        });
4587        let settings = EditorSettings::test(&cx);
4588        let (_, view) = cx.add_window(Default::default(), |cx| {
4589            build_editor(buffer.clone(), settings, cx)
4590        });
4591
4592        view.update(cx, |view, cx| {
4593            view.select_display_ranges(
4594                &[
4595                    // an empty selection - the following character is deleted
4596                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4597                    // one character selected - it is deleted
4598                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4599                    // a line suffix selected - it is deleted
4600                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
4601                ],
4602                cx,
4603            )
4604            .unwrap();
4605            view.delete(&Delete, cx);
4606        });
4607
4608        assert_eq!(
4609            buffer.read(cx).text(),
4610            "on two three\nfou five six\nseven ten\n"
4611        );
4612    }
4613
4614    #[gpui::test]
4615    fn test_delete_line(cx: &mut gpui::MutableAppContext) {
4616        let settings = EditorSettings::test(&cx);
4617        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
4618        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4619        view.update(cx, |view, cx| {
4620            view.select_display_ranges(
4621                &[
4622                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4623                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
4624                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4625                ],
4626                cx,
4627            )
4628            .unwrap();
4629            view.delete_line(&DeleteLine, cx);
4630            assert_eq!(view.display_text(cx), "ghi");
4631            assert_eq!(
4632                view.selection_ranges(cx),
4633                vec![
4634                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4635                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
4636                ]
4637            );
4638        });
4639
4640        let settings = EditorSettings::test(&cx);
4641        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
4642        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4643        view.update(cx, |view, cx| {
4644            view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx)
4645                .unwrap();
4646            view.delete_line(&DeleteLine, cx);
4647            assert_eq!(view.display_text(cx), "ghi\n");
4648            assert_eq!(
4649                view.selection_ranges(cx),
4650                vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
4651            );
4652        });
4653    }
4654
4655    #[gpui::test]
4656    fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
4657        let settings = EditorSettings::test(&cx);
4658        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
4659        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4660        view.update(cx, |view, cx| {
4661            view.select_display_ranges(
4662                &[
4663                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4664                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4665                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4666                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4667                ],
4668                cx,
4669            )
4670            .unwrap();
4671            view.duplicate_line(&DuplicateLine, cx);
4672            assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
4673            assert_eq!(
4674                view.selection_ranges(cx),
4675                vec![
4676                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
4677                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4678                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4679                    DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
4680                ]
4681            );
4682        });
4683
4684        let settings = EditorSettings::test(&cx);
4685        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
4686        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4687        view.update(cx, |view, cx| {
4688            view.select_display_ranges(
4689                &[
4690                    DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
4691                    DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
4692                ],
4693                cx,
4694            )
4695            .unwrap();
4696            view.duplicate_line(&DuplicateLine, cx);
4697            assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
4698            assert_eq!(
4699                view.selection_ranges(cx),
4700                vec![
4701                    DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
4702                    DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
4703                ]
4704            );
4705        });
4706    }
4707
4708    #[gpui::test]
4709    fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
4710        let settings = EditorSettings::test(&cx);
4711        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(10, 5), cx));
4712        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4713        view.update(cx, |view, cx| {
4714            view.fold_ranges(
4715                vec![
4716                    Point::new(0, 2)..Point::new(1, 2),
4717                    Point::new(2, 3)..Point::new(4, 1),
4718                    Point::new(7, 0)..Point::new(8, 4),
4719                ],
4720                cx,
4721            );
4722            view.select_display_ranges(
4723                &[
4724                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4725                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
4726                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
4727                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
4728                ],
4729                cx,
4730            )
4731            .unwrap();
4732            assert_eq!(
4733                view.display_text(cx),
4734                "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
4735            );
4736
4737            view.move_line_up(&MoveLineUp, cx);
4738            assert_eq!(
4739                view.display_text(cx),
4740                "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
4741            );
4742            assert_eq!(
4743                view.selection_ranges(cx),
4744                vec![
4745                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4746                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4747                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
4748                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
4749                ]
4750            );
4751        });
4752
4753        view.update(cx, |view, cx| {
4754            view.move_line_down(&MoveLineDown, cx);
4755            assert_eq!(
4756                view.display_text(cx),
4757                "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
4758            );
4759            assert_eq!(
4760                view.selection_ranges(cx),
4761                vec![
4762                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4763                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
4764                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
4765                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
4766                ]
4767            );
4768        });
4769
4770        view.update(cx, |view, cx| {
4771            view.move_line_down(&MoveLineDown, cx);
4772            assert_eq!(
4773                view.display_text(cx),
4774                "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
4775            );
4776            assert_eq!(
4777                view.selection_ranges(cx),
4778                vec![
4779                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4780                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
4781                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
4782                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
4783                ]
4784            );
4785        });
4786
4787        view.update(cx, |view, cx| {
4788            view.move_line_up(&MoveLineUp, cx);
4789            assert_eq!(
4790                view.display_text(cx),
4791                "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
4792            );
4793            assert_eq!(
4794                view.selection_ranges(cx),
4795                vec![
4796                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4797                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4798                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
4799                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
4800                ]
4801            );
4802        });
4803    }
4804
4805    #[gpui::test]
4806    fn test_clipboard(cx: &mut gpui::MutableAppContext) {
4807        let buffer = cx.add_model(|cx| Buffer::new(0, "one✅ two three four five six ", cx));
4808        let settings = EditorSettings::test(&cx);
4809        let view = cx
4810            .add_window(Default::default(), |cx| {
4811                build_editor(buffer.clone(), settings, cx)
4812            })
4813            .1;
4814
4815        // Cut with three selections. Clipboard text is divided into three slices.
4816        view.update(cx, |view, cx| {
4817            view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
4818            view.cut(&Cut, cx);
4819            assert_eq!(view.display_text(cx), "two four six ");
4820        });
4821
4822        // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
4823        view.update(cx, |view, cx| {
4824            view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
4825            view.paste(&Paste, cx);
4826            assert_eq!(view.display_text(cx), "two one✅ four three six five ");
4827            assert_eq!(
4828                view.selection_ranges(cx),
4829                &[
4830                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
4831                    DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
4832                    DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
4833                ]
4834            );
4835        });
4836
4837        // Paste again but with only two cursors. Since the number of cursors doesn't
4838        // match the number of slices in the clipboard, the entire clipboard text
4839        // is pasted at each cursor.
4840        view.update(cx, |view, cx| {
4841            view.select_ranges(vec![0..0, 31..31], None, cx);
4842            view.handle_input(&Input("( ".into()), cx);
4843            view.paste(&Paste, cx);
4844            view.handle_input(&Input(") ".into()), cx);
4845            assert_eq!(
4846                view.display_text(cx),
4847                "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
4848            );
4849        });
4850
4851        view.update(cx, |view, cx| {
4852            view.select_ranges(vec![0..0], None, cx);
4853            view.handle_input(&Input("123\n4567\n89\n".into()), cx);
4854            assert_eq!(
4855                view.display_text(cx),
4856                "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
4857            );
4858        });
4859
4860        // Cut with three selections, one of which is full-line.
4861        view.update(cx, |view, cx| {
4862            view.select_display_ranges(
4863                &[
4864                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
4865                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4866                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
4867                ],
4868                cx,
4869            )
4870            .unwrap();
4871            view.cut(&Cut, cx);
4872            assert_eq!(
4873                view.display_text(cx),
4874                "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
4875            );
4876        });
4877
4878        // Paste with three selections, noticing how the copied selection that was full-line
4879        // gets inserted before the second cursor.
4880        view.update(cx, |view, cx| {
4881            view.select_display_ranges(
4882                &[
4883                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4884                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4885                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
4886                ],
4887                cx,
4888            )
4889            .unwrap();
4890            view.paste(&Paste, cx);
4891            assert_eq!(
4892                view.display_text(cx),
4893                "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
4894            );
4895            assert_eq!(
4896                view.selection_ranges(cx),
4897                &[
4898                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4899                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4900                    DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
4901                ]
4902            );
4903        });
4904
4905        // Copy with a single cursor only, which writes the whole line into the clipboard.
4906        view.update(cx, |view, cx| {
4907            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx)
4908                .unwrap();
4909            view.copy(&Copy, cx);
4910        });
4911
4912        // Paste with three selections, noticing how the copied full-line selection is inserted
4913        // before the empty selections but replaces the selection that is non-empty.
4914        view.update(cx, |view, cx| {
4915            view.select_display_ranges(
4916                &[
4917                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4918                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
4919                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4920                ],
4921                cx,
4922            )
4923            .unwrap();
4924            view.paste(&Paste, cx);
4925            assert_eq!(
4926                view.display_text(cx),
4927                "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
4928            );
4929            assert_eq!(
4930                view.selection_ranges(cx),
4931                &[
4932                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4933                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4934                    DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
4935                ]
4936            );
4937        });
4938    }
4939
4940    #[gpui::test]
4941    fn test_select_all(cx: &mut gpui::MutableAppContext) {
4942        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\nde\nfgh", cx));
4943        let settings = EditorSettings::test(&cx);
4944        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4945        view.update(cx, |view, cx| {
4946            view.select_all(&SelectAll, cx);
4947            assert_eq!(
4948                view.selection_ranges(cx),
4949                &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
4950            );
4951        });
4952    }
4953
4954    #[gpui::test]
4955    fn test_select_line(cx: &mut gpui::MutableAppContext) {
4956        let settings = EditorSettings::test(&cx);
4957        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 5), cx));
4958        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4959        view.update(cx, |view, cx| {
4960            view.select_display_ranges(
4961                &[
4962                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4963                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4964                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4965                    DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
4966                ],
4967                cx,
4968            )
4969            .unwrap();
4970            view.select_line(&SelectLine, cx);
4971            assert_eq!(
4972                view.selection_ranges(cx),
4973                vec![
4974                    DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
4975                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
4976                ]
4977            );
4978        });
4979
4980        view.update(cx, |view, cx| {
4981            view.select_line(&SelectLine, cx);
4982            assert_eq!(
4983                view.selection_ranges(cx),
4984                vec![
4985                    DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
4986                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
4987                ]
4988            );
4989        });
4990
4991        view.update(cx, |view, cx| {
4992            view.select_line(&SelectLine, cx);
4993            assert_eq!(
4994                view.selection_ranges(cx),
4995                vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
4996            );
4997        });
4998    }
4999
5000    #[gpui::test]
5001    fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
5002        let settings = EditorSettings::test(&cx);
5003        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(9, 5), cx));
5004        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5005        view.update(cx, |view, cx| {
5006            view.fold_ranges(
5007                vec![
5008                    Point::new(0, 2)..Point::new(1, 2),
5009                    Point::new(2, 3)..Point::new(4, 1),
5010                    Point::new(7, 0)..Point::new(8, 4),
5011                ],
5012                cx,
5013            );
5014            view.select_display_ranges(
5015                &[
5016                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5017                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5018                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5019                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
5020                ],
5021                cx,
5022            )
5023            .unwrap();
5024            assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
5025        });
5026
5027        view.update(cx, |view, cx| {
5028            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5029            assert_eq!(
5030                view.display_text(cx),
5031                "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
5032            );
5033            assert_eq!(
5034                view.selection_ranges(cx),
5035                [
5036                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5037                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5038                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
5039                    DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
5040                ]
5041            );
5042        });
5043
5044        view.update(cx, |view, cx| {
5045            view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx)
5046                .unwrap();
5047            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5048            assert_eq!(
5049                view.display_text(cx),
5050                "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
5051            );
5052            assert_eq!(
5053                view.selection_ranges(cx),
5054                [
5055                    DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
5056                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
5057                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
5058                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
5059                    DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
5060                    DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
5061                    DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
5062                    DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
5063                ]
5064            );
5065        });
5066    }
5067
5068    #[gpui::test]
5069    fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
5070        let settings = EditorSettings::test(&cx);
5071        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndefghi\n\njk\nlmno\n", cx));
5072        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5073
5074        view.update(cx, |view, cx| {
5075            view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx)
5076                .unwrap();
5077        });
5078        view.update(cx, |view, cx| {
5079            view.add_selection_above(&AddSelectionAbove, cx);
5080            assert_eq!(
5081                view.selection_ranges(cx),
5082                vec![
5083                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5084                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5085                ]
5086            );
5087        });
5088
5089        view.update(cx, |view, cx| {
5090            view.add_selection_above(&AddSelectionAbove, cx);
5091            assert_eq!(
5092                view.selection_ranges(cx),
5093                vec![
5094                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5095                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5096                ]
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![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
5105            );
5106        });
5107
5108        view.update(cx, |view, cx| {
5109            view.add_selection_below(&AddSelectionBelow, cx);
5110            assert_eq!(
5111                view.selection_ranges(cx),
5112                vec![
5113                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5114                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5115                ]
5116            );
5117        });
5118
5119        view.update(cx, |view, cx| {
5120            view.add_selection_below(&AddSelectionBelow, cx);
5121            assert_eq!(
5122                view.selection_ranges(cx),
5123                vec![
5124                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5125                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5126                ]
5127            );
5128        });
5129
5130        view.update(cx, |view, cx| {
5131            view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx)
5132                .unwrap();
5133        });
5134        view.update(cx, |view, cx| {
5135            view.add_selection_below(&AddSelectionBelow, cx);
5136            assert_eq!(
5137                view.selection_ranges(cx),
5138                vec![
5139                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5140                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5141                ]
5142            );
5143        });
5144
5145        view.update(cx, |view, cx| {
5146            view.add_selection_below(&AddSelectionBelow, cx);
5147            assert_eq!(
5148                view.selection_ranges(cx),
5149                vec![
5150                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5151                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5152                ]
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.add_selection_above(&AddSelectionAbove, cx);
5166            assert_eq!(
5167                view.selection_ranges(cx),
5168                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5169            );
5170        });
5171
5172        view.update(cx, |view, cx| {
5173            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx)
5174                .unwrap();
5175            view.add_selection_below(&AddSelectionBelow, cx);
5176            assert_eq!(
5177                view.selection_ranges(cx),
5178                vec![
5179                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5180                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5181                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5182                ]
5183            );
5184        });
5185
5186        view.update(cx, |view, cx| {
5187            view.add_selection_below(&AddSelectionBelow, cx);
5188            assert_eq!(
5189                view.selection_ranges(cx),
5190                vec![
5191                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5192                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5193                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5194                    DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
5195                ]
5196            );
5197        });
5198
5199        view.update(cx, |view, cx| {
5200            view.add_selection_above(&AddSelectionAbove, cx);
5201            assert_eq!(
5202                view.selection_ranges(cx),
5203                vec![
5204                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5205                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5206                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5207                ]
5208            );
5209        });
5210
5211        view.update(cx, |view, cx| {
5212            view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx)
5213                .unwrap();
5214        });
5215        view.update(cx, |view, cx| {
5216            view.add_selection_above(&AddSelectionAbove, cx);
5217            assert_eq!(
5218                view.selection_ranges(cx),
5219                vec![
5220                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
5221                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5222                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5223                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5224                ]
5225            );
5226        });
5227
5228        view.update(cx, |view, cx| {
5229            view.add_selection_below(&AddSelectionBelow, cx);
5230            assert_eq!(
5231                view.selection_ranges(cx),
5232                vec![
5233                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5234                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5235                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5236                ]
5237            );
5238        });
5239    }
5240
5241    #[gpui::test]
5242    async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
5243        let settings = cx.read(EditorSettings::test);
5244        let language = Some(Arc::new(Language::new(
5245            LanguageConfig::default(),
5246            Some(tree_sitter_rust::language()),
5247        )));
5248
5249        let text = r#"
5250            use mod1::mod2::{mod3, mod4};
5251
5252            fn fn_1(param1: bool, param2: &str) {
5253                let var1 = "text";
5254            }
5255        "#
5256        .unindent();
5257
5258        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5259        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5260        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing())
5261            .await;
5262
5263        view.update(&mut cx, |view, cx| {
5264            view.select_display_ranges(
5265                &[
5266                    DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5267                    DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5268                    DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5269                ],
5270                cx,
5271            )
5272            .unwrap();
5273            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5274        });
5275        assert_eq!(
5276            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5277            &[
5278                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5279                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5280                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5281            ]
5282        );
5283
5284        view.update(&mut cx, |view, cx| {
5285            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5286        });
5287        assert_eq!(
5288            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5289            &[
5290                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5291                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5292            ]
5293        );
5294
5295        view.update(&mut cx, |view, cx| {
5296            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5297        });
5298        assert_eq!(
5299            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5300            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5301        );
5302
5303        // Trying to expand the selected syntax node one more time has no effect.
5304        view.update(&mut cx, |view, cx| {
5305            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5306        });
5307        assert_eq!(
5308            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5309            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5310        );
5311
5312        view.update(&mut cx, |view, cx| {
5313            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5314        });
5315        assert_eq!(
5316            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5317            &[
5318                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5319                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5320            ]
5321        );
5322
5323        view.update(&mut cx, |view, cx| {
5324            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5325        });
5326        assert_eq!(
5327            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5328            &[
5329                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5330                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5331                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5332            ]
5333        );
5334
5335        view.update(&mut cx, |view, cx| {
5336            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5337        });
5338        assert_eq!(
5339            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5340            &[
5341                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5342                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5343                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5344            ]
5345        );
5346
5347        // Trying to shrink the selected syntax node one more time has no effect.
5348        view.update(&mut cx, |view, cx| {
5349            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5350        });
5351        assert_eq!(
5352            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5353            &[
5354                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5355                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5356                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5357            ]
5358        );
5359
5360        // Ensure that we keep expanding the selection if the larger selection starts or ends within
5361        // a fold.
5362        view.update(&mut cx, |view, cx| {
5363            view.fold_ranges(
5364                vec![
5365                    Point::new(0, 21)..Point::new(0, 24),
5366                    Point::new(3, 20)..Point::new(3, 22),
5367                ],
5368                cx,
5369            );
5370            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5371        });
5372        assert_eq!(
5373            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
5374            &[
5375                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5376                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5377                DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
5378            ]
5379        );
5380    }
5381
5382    #[gpui::test]
5383    async fn test_autoclose_pairs(mut cx: gpui::TestAppContext) {
5384        let settings = cx.read(EditorSettings::test);
5385        let language = Some(Arc::new(Language::new(
5386            LanguageConfig {
5387                brackets: vec![
5388                    BracketPair {
5389                        start: "{".to_string(),
5390                        end: "}".to_string(),
5391                        close: true,
5392                        newline: true,
5393                    },
5394                    BracketPair {
5395                        start: "/*".to_string(),
5396                        end: " */".to_string(),
5397                        close: true,
5398                        newline: true,
5399                    },
5400                ],
5401                ..Default::default()
5402            },
5403            Some(tree_sitter_rust::language()),
5404        )));
5405
5406        let text = r#"
5407            a
5408
5409            /
5410
5411        "#
5412        .unindent();
5413
5414        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5415        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5416        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing())
5417            .await;
5418
5419        view.update(&mut cx, |view, cx| {
5420            view.select_display_ranges(
5421                &[
5422                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5423                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5424                ],
5425                cx,
5426            )
5427            .unwrap();
5428            view.handle_input(&Input("{".to_string()), cx);
5429            view.handle_input(&Input("{".to_string()), cx);
5430            view.handle_input(&Input("{".to_string()), cx);
5431            assert_eq!(
5432                view.text(cx),
5433                "
5434                {{{}}}
5435                {{{}}}
5436                /
5437
5438                "
5439                .unindent()
5440            );
5441
5442            view.move_right(&MoveRight, cx);
5443            view.handle_input(&Input("}".to_string()), cx);
5444            view.handle_input(&Input("}".to_string()), cx);
5445            view.handle_input(&Input("}".to_string()), cx);
5446            assert_eq!(
5447                view.text(cx),
5448                "
5449                {{{}}}}
5450                {{{}}}}
5451                /
5452
5453                "
5454                .unindent()
5455            );
5456
5457            view.undo(&Undo, cx);
5458            view.handle_input(&Input("/".to_string()), cx);
5459            view.handle_input(&Input("*".to_string()), cx);
5460            assert_eq!(
5461                view.text(cx),
5462                "
5463                /* */
5464                /* */
5465                /
5466
5467                "
5468                .unindent()
5469            );
5470
5471            view.undo(&Undo, cx);
5472            view.select_display_ranges(
5473                &[
5474                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5475                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5476                ],
5477                cx,
5478            )
5479            .unwrap();
5480            view.handle_input(&Input("*".to_string()), cx);
5481            assert_eq!(
5482                view.text(cx),
5483                "
5484                a
5485
5486                /*
5487                *
5488                "
5489                .unindent()
5490            );
5491        });
5492    }
5493
5494    #[gpui::test]
5495    async fn test_toggle_comment(mut cx: gpui::TestAppContext) {
5496        let settings = cx.read(EditorSettings::test);
5497        let language = Some(Arc::new(Language::new(
5498            LanguageConfig {
5499                line_comment: Some("// ".to_string()),
5500                ..Default::default()
5501            },
5502            Some(tree_sitter_rust::language()),
5503        )));
5504
5505        let text = "
5506            fn a() {
5507                //b();
5508                // c();
5509                //  d();
5510            }
5511        "
5512        .unindent();
5513
5514        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5515        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5516
5517        view.update(&mut cx, |editor, cx| {
5518            // If multiple selections intersect a line, the line is only
5519            // toggled once.
5520            editor
5521                .select_display_ranges(
5522                    &[
5523                        DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
5524                        DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
5525                    ],
5526                    cx,
5527                )
5528                .unwrap();
5529            editor.toggle_comments(&ToggleComments, cx);
5530            assert_eq!(
5531                editor.text(cx),
5532                "
5533                    fn a() {
5534                        b();
5535                        c();
5536                         d();
5537                    }
5538                "
5539                .unindent()
5540            );
5541
5542            // The comment prefix is inserted at the same column for every line
5543            // in a selection.
5544            editor
5545                .select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx)
5546                .unwrap();
5547            editor.toggle_comments(&ToggleComments, cx);
5548            assert_eq!(
5549                editor.text(cx),
5550                "
5551                    fn a() {
5552                        // b();
5553                        // c();
5554                        //  d();
5555                    }
5556                "
5557                .unindent()
5558            );
5559
5560            // If a selection ends at the beginning of a line, that line is not toggled.
5561            editor
5562                .select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx)
5563                .unwrap();
5564            editor.toggle_comments(&ToggleComments, cx);
5565            assert_eq!(
5566                editor.text(cx),
5567                "
5568                        fn a() {
5569                            // b();
5570                            c();
5571                            //  d();
5572                        }
5573                    "
5574                .unindent()
5575            );
5576        });
5577    }
5578
5579    #[gpui::test]
5580    async fn test_extra_newline_insertion(mut cx: gpui::TestAppContext) {
5581        let settings = cx.read(EditorSettings::test);
5582        let language = Some(Arc::new(Language::new(
5583            LanguageConfig {
5584                brackets: vec![
5585                    BracketPair {
5586                        start: "{".to_string(),
5587                        end: "}".to_string(),
5588                        close: true,
5589                        newline: true,
5590                    },
5591                    BracketPair {
5592                        start: "/* ".to_string(),
5593                        end: " */".to_string(),
5594                        close: true,
5595                        newline: true,
5596                    },
5597                ],
5598                ..Default::default()
5599            },
5600            Some(tree_sitter_rust::language()),
5601        )));
5602
5603        let text = concat!(
5604            "{   }\n",     // Suppress rustfmt
5605            "  x\n",       //
5606            "  /*   */\n", //
5607            "x\n",         //
5608            "{{} }\n",     //
5609        );
5610
5611        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
5612        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5613        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing())
5614            .await;
5615
5616        view.update(&mut cx, |view, cx| {
5617            view.select_display_ranges(
5618                &[
5619                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
5620                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
5621                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
5622                ],
5623                cx,
5624            )
5625            .unwrap();
5626            view.newline(&Newline, cx);
5627
5628            assert_eq!(
5629                view.buffer().read(cx).text(),
5630                concat!(
5631                    "{ \n",    // Suppress rustfmt
5632                    "\n",      //
5633                    "}\n",     //
5634                    "  x\n",   //
5635                    "  /* \n", //
5636                    "  \n",    //
5637                    "  */\n",  //
5638                    "x\n",     //
5639                    "{{} \n",  //
5640                    "}\n",     //
5641                )
5642            );
5643        });
5644    }
5645
5646    impl Editor {
5647        fn selection_ranges(&self, cx: &mut MutableAppContext) -> Vec<Range<DisplayPoint>> {
5648            self.intersecting_selections(
5649                self.selection_set_id,
5650                DisplayPoint::zero()..self.max_point(cx),
5651                cx,
5652            )
5653            .into_iter()
5654            .map(|s| {
5655                if s.reversed {
5656                    s.end..s.start
5657                } else {
5658                    s.start..s.end
5659                }
5660            })
5661            .collect()
5662        }
5663    }
5664
5665    fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
5666        let point = DisplayPoint::new(row as u32, column as u32);
5667        point..point
5668    }
5669
5670    fn build_editor(
5671        buffer: ModelHandle<Buffer>,
5672        settings: EditorSettings,
5673        cx: &mut ViewContext<Editor>,
5674    ) -> Editor {
5675        Editor::for_buffer(buffer, move |_| settings.clone(), cx)
5676    }
5677}
5678
5679trait RangeExt<T> {
5680    fn sorted(&self) -> Range<T>;
5681    fn to_inclusive(&self) -> RangeInclusive<T>;
5682}
5683
5684impl<T: Ord + Clone> RangeExt<T> for Range<T> {
5685    fn sorted(&self) -> Self {
5686        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
5687    }
5688
5689    fn to_inclusive(&self) -> RangeInclusive<T> {
5690        self.start.clone()..=self.end.clone()
5691    }
5692}