lib.rs

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