lib.rs

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