lib.rs

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