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                        && !range.is_empty()
2246                        && Some(range.end) != active_primary_range.as_ref().map(|r| *r.end())
2247                    {
2248                        Some((range, diagnostic.group_id))
2249                    } else {
2250                        None
2251                    }
2252                });
2253
2254            if let Some((primary_range, group_id)) = next_group {
2255                self.activate_diagnostics(group_id, cx);
2256                self.update_selections(
2257                    vec![Selection {
2258                        id: selection.id,
2259                        start: primary_range.start,
2260                        end: primary_range.start,
2261                        reversed: false,
2262                        goal: SelectionGoal::None,
2263                    }],
2264                    true,
2265                    cx,
2266                );
2267                break;
2268            } else if search_start == 0 {
2269                break;
2270            } else {
2271                // Cycle around to the start of the buffer.
2272                search_start = 0;
2273            }
2274        }
2275    }
2276
2277    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
2278        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
2279            let buffer = self.buffer.read(cx);
2280            let update_count = buffer.diagnostics_update_count();
2281            if update_count > active_diagnostics.update_count {
2282                active_diagnostics.update_count = update_count;
2283                let primary_range_start = active_diagnostics.primary_range.start.to_offset(buffer);
2284                let is_valid = buffer
2285                    .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone())
2286                    .any(|(range, diagnostic)| {
2287                        diagnostic.is_primary
2288                            && range.start == primary_range_start
2289                            && diagnostic.message == active_diagnostics.primary_message
2290                    });
2291
2292                if is_valid != active_diagnostics.is_valid {
2293                    active_diagnostics.is_valid = is_valid;
2294                    let mut new_styles = HashMap::new();
2295                    for (block_id, diagnostic) in &active_diagnostics.blocks {
2296                        let severity = diagnostic.severity;
2297                        let message_len = diagnostic.message.len();
2298                        new_styles.insert(
2299                            *block_id,
2300                            (
2301                                Some({
2302                                    let build_settings = self.build_settings.clone();
2303                                    move |cx: &AppContext| {
2304                                        let settings = build_settings.borrow()(cx);
2305                                        vec![(
2306                                            message_len,
2307                                            diagnostic_style(severity, is_valid, &settings.style)
2308                                                .text
2309                                                .into(),
2310                                        )]
2311                                    }
2312                                }),
2313                                Some({
2314                                    let build_settings = self.build_settings.clone();
2315                                    move |cx: &AppContext| {
2316                                        let settings = build_settings.borrow()(cx);
2317                                        diagnostic_style(severity, is_valid, &settings.style).block
2318                                    }
2319                                }),
2320                            ),
2321                        );
2322                    }
2323                    self.display_map
2324                        .update(cx, |display_map, _| display_map.restyle_blocks(new_styles));
2325                }
2326            }
2327        }
2328    }
2329
2330    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) {
2331        self.dismiss_diagnostics(cx);
2332        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
2333            let buffer = self.buffer.read(cx);
2334
2335            let update_count = buffer.diagnostics_update_count();
2336            let mut primary_range = None;
2337            let mut primary_message = None;
2338            let mut group_end = Point::zero();
2339            let diagnostic_group = buffer
2340                .diagnostic_group::<Point>(group_id)
2341                .map(|(range, diagnostic)| {
2342                    if range.end > group_end {
2343                        group_end = range.end;
2344                    }
2345                    if diagnostic.is_primary {
2346                        primary_range = Some(range.clone());
2347                        primary_message = Some(diagnostic.message.clone());
2348                    }
2349                    (range, diagnostic.clone())
2350                })
2351                .collect::<Vec<_>>();
2352            let primary_range = primary_range.unwrap();
2353            let primary_message = primary_message.unwrap();
2354            let primary_range =
2355                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
2356
2357            let blocks = display_map
2358                .insert_blocks(
2359                    diagnostic_group.iter().map(|(range, diagnostic)| {
2360                        let build_settings = self.build_settings.clone();
2361                        let message_len = diagnostic.message.len();
2362                        let severity = diagnostic.severity;
2363                        BlockProperties {
2364                            position: range.start,
2365                            text: diagnostic.message.as_str(),
2366                            build_runs: Some(Arc::new({
2367                                let build_settings = build_settings.clone();
2368                                move |cx| {
2369                                    let settings = build_settings.borrow()(cx);
2370                                    vec![(
2371                                        message_len,
2372                                        diagnostic_style(severity, true, &settings.style)
2373                                            .text
2374                                            .into(),
2375                                    )]
2376                                }
2377                            })),
2378                            build_style: Some(Arc::new({
2379                                let build_settings = build_settings.clone();
2380                                move |cx| {
2381                                    let settings = build_settings.borrow()(cx);
2382                                    diagnostic_style(severity, true, &settings.style).block
2383                                }
2384                            })),
2385                            disposition: BlockDisposition::Below,
2386                        }
2387                    }),
2388                    cx,
2389                )
2390                .into_iter()
2391                .zip(
2392                    diagnostic_group
2393                        .into_iter()
2394                        .map(|(_, diagnostic)| diagnostic),
2395                )
2396                .collect();
2397
2398            Some(ActiveDiagnosticGroup {
2399                primary_range,
2400                primary_message,
2401                blocks,
2402                is_valid: true,
2403                update_count,
2404            })
2405        });
2406    }
2407
2408    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
2409        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
2410            self.display_map.update(cx, |display_map, cx| {
2411                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
2412            });
2413            cx.notify();
2414        }
2415    }
2416
2417    fn build_columnar_selection(
2418        &mut self,
2419        display_map: &DisplayMapSnapshot,
2420        row: u32,
2421        columns: &Range<u32>,
2422        reversed: bool,
2423    ) -> Option<Selection<Point>> {
2424        let is_empty = columns.start == columns.end;
2425        let line_len = display_map.line_len(row);
2426        if columns.start < line_len || (is_empty && columns.start == line_len) {
2427            let start = DisplayPoint::new(row, columns.start);
2428            let end = DisplayPoint::new(row, cmp::min(columns.end, line_len));
2429            Some(Selection {
2430                id: post_inc(&mut self.next_selection_id),
2431                start: start.to_point(display_map),
2432                end: end.to_point(display_map),
2433                reversed,
2434                goal: SelectionGoal::ColumnRange {
2435                    start: columns.start,
2436                    end: columns.end,
2437                },
2438            })
2439        } else {
2440            None
2441        }
2442    }
2443
2444    pub fn active_selection_sets<'a>(
2445        &'a self,
2446        cx: &'a AppContext,
2447    ) -> impl 'a + Iterator<Item = SelectionSetId> {
2448        let buffer = self.buffer.read(cx);
2449        let replica_id = buffer.replica_id();
2450        buffer
2451            .selection_sets()
2452            .filter(move |(set_id, set)| {
2453                set.active && (set_id.replica_id != replica_id || **set_id == self.selection_set_id)
2454            })
2455            .map(|(set_id, _)| *set_id)
2456    }
2457
2458    pub fn selections_in_range<'a>(
2459        &'a self,
2460        set_id: SelectionSetId,
2461        range: Range<DisplayPoint>,
2462        cx: &'a mut MutableAppContext,
2463    ) -> impl 'a + Iterator<Item = Range<DisplayPoint>> {
2464        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2465        let buffer = self.buffer.read(cx);
2466        let selections = self
2467            .selection_set(cx)
2468            .selections::<Point, _>(buffer)
2469            .collect::<Vec<_>>();
2470        let start = range.start.to_point(&display_map);
2471        let start_index = self.selection_insertion_index(&selections, start);
2472        let pending_selection = if set_id.replica_id == self.buffer.read(cx).replica_id() {
2473            self.pending_selection.as_ref().and_then(|pending| {
2474                let mut selection_start = pending.start.to_display_point(&display_map);
2475                let mut selection_end = pending.end.to_display_point(&display_map);
2476                if pending.reversed {
2477                    mem::swap(&mut selection_start, &mut selection_end);
2478                }
2479                if selection_start <= range.end || selection_end <= range.end {
2480                    Some(selection_start..selection_end)
2481                } else {
2482                    None
2483                }
2484            })
2485        } else {
2486            None
2487        };
2488        selections
2489            .into_iter()
2490            .skip(start_index)
2491            .map(move |s| s.display_range(&display_map))
2492            .take_while(move |r| r.start <= range.end || r.end <= range.end)
2493            .chain(pending_selection)
2494    }
2495
2496    fn selection_insertion_index(&self, selections: &[Selection<Point>], start: Point) -> usize {
2497        match selections.binary_search_by_key(&start, |probe| probe.start) {
2498            Ok(index) => index,
2499            Err(index) => {
2500                if index > 0 && selections[index - 1].end > start {
2501                    index - 1
2502                } else {
2503                    index
2504                }
2505            }
2506        }
2507    }
2508
2509    pub fn selections<'a, D>(&self, cx: &'a AppContext) -> impl 'a + Iterator<Item = Selection<D>>
2510    where
2511        D: 'a + TextDimension<'a> + Ord,
2512    {
2513        let buffer = self.buffer.read(cx);
2514        let mut selections = self.selection_set(cx).selections::<D, _>(buffer).peekable();
2515        let mut pending_selection = self.pending_selection(cx);
2516        iter::from_fn(move || {
2517            if let Some(pending) = pending_selection.as_mut() {
2518                while let Some(next_selection) = selections.peek() {
2519                    if pending.start <= next_selection.end && pending.end >= next_selection.start {
2520                        let next_selection = selections.next().unwrap();
2521                        if next_selection.start < pending.start {
2522                            pending.start = next_selection.start;
2523                        }
2524                        if next_selection.end > pending.end {
2525                            pending.end = next_selection.end;
2526                        }
2527                    } else if next_selection.end < pending.start {
2528                        return selections.next();
2529                    } else {
2530                        break;
2531                    }
2532                }
2533
2534                pending_selection.take()
2535            } else {
2536                selections.next()
2537            }
2538        })
2539    }
2540
2541    fn pending_selection<'a, D>(&self, cx: &'a AppContext) -> Option<Selection<D>>
2542    where
2543        D: 'a + TextDimension<'a>,
2544    {
2545        let buffer = self.buffer.read(cx);
2546        self.pending_selection.as_ref().map(|selection| Selection {
2547            id: selection.id,
2548            start: selection.start.summary::<D, _>(buffer),
2549            end: selection.end.summary::<D, _>(buffer),
2550            reversed: selection.reversed,
2551            goal: selection.goal,
2552        })
2553    }
2554
2555    fn selection_count<'a>(&self, cx: &'a AppContext) -> usize {
2556        let mut selection_count = self.selection_set(cx).len();
2557        if self.pending_selection.is_some() {
2558            selection_count += 1;
2559        }
2560        selection_count
2561    }
2562
2563    pub fn oldest_selection<'a, T>(&self, cx: &'a AppContext) -> Selection<T>
2564    where
2565        T: 'a + TextDimension<'a>,
2566    {
2567        let buffer = self.buffer.read(cx);
2568        self.selection_set(cx)
2569            .oldest_selection(buffer)
2570            .or_else(|| self.pending_selection(cx))
2571            .unwrap()
2572    }
2573
2574    pub fn newest_selection<'a, T>(&self, cx: &'a AppContext) -> Selection<T>
2575    where
2576        T: 'a + TextDimension<'a>,
2577    {
2578        let buffer = self.buffer.read(cx);
2579        self.pending_selection(cx)
2580            .or_else(|| self.selection_set(cx).newest_selection(buffer))
2581            .unwrap()
2582    }
2583
2584    fn selection_set<'a>(&self, cx: &'a AppContext) -> &'a SelectionSet {
2585        self.buffer
2586            .read(cx)
2587            .selection_set(self.selection_set_id)
2588            .unwrap()
2589    }
2590
2591    fn update_selections<T>(
2592        &mut self,
2593        mut selections: Vec<Selection<T>>,
2594        autoscroll: bool,
2595        cx: &mut ViewContext<Self>,
2596    ) where
2597        T: ToOffset + ToPoint + Ord + std::marker::Copy + std::fmt::Debug,
2598    {
2599        // Merge overlapping selections.
2600        let buffer = self.buffer.read(cx);
2601        let mut i = 1;
2602        while i < selections.len() {
2603            if selections[i - 1].end >= selections[i].start {
2604                let removed = selections.remove(i);
2605                if removed.start < selections[i - 1].start {
2606                    selections[i - 1].start = removed.start;
2607                }
2608                if removed.end > selections[i - 1].end {
2609                    selections[i - 1].end = removed.end;
2610                }
2611            } else {
2612                i += 1;
2613            }
2614        }
2615
2616        self.pending_selection = None;
2617        self.add_selections_state = None;
2618        self.select_larger_syntax_node_stack.clear();
2619        while let Some(autoclose_pair_state) = self.autoclose_stack.last() {
2620            let all_selections_inside_autoclose_ranges =
2621                if selections.len() == autoclose_pair_state.ranges.len() {
2622                    selections
2623                        .iter()
2624                        .zip(autoclose_pair_state.ranges.ranges::<Point, _>(buffer))
2625                        .all(|(selection, autoclose_range)| {
2626                            let head = selection.head().to_point(&*buffer);
2627                            autoclose_range.start <= head && autoclose_range.end >= head
2628                        })
2629                } else {
2630                    false
2631                };
2632
2633            if all_selections_inside_autoclose_ranges {
2634                break;
2635            } else {
2636                self.autoclose_stack.pop();
2637            }
2638        }
2639
2640        if autoscroll {
2641            self.request_autoscroll(cx);
2642        }
2643        self.pause_cursor_blinking(cx);
2644
2645        self.buffer.update(cx, |buffer, cx| {
2646            buffer
2647                .update_selection_set(self.selection_set_id, &selections, cx)
2648                .unwrap();
2649        });
2650    }
2651
2652    fn request_autoscroll(&mut self, cx: &mut ViewContext<Self>) {
2653        self.autoscroll_requested = true;
2654        cx.notify();
2655    }
2656
2657    fn start_transaction(&mut self, cx: &mut ViewContext<Self>) {
2658        self.end_selection(cx);
2659        self.buffer.update(cx, |buffer, _| {
2660            buffer
2661                .start_transaction(Some(self.selection_set_id))
2662                .unwrap()
2663        });
2664    }
2665
2666    fn end_transaction(&self, cx: &mut ViewContext<Self>) {
2667        self.buffer.update(cx, |buffer, cx| {
2668            buffer
2669                .end_transaction(Some(self.selection_set_id), cx)
2670                .unwrap()
2671        });
2672    }
2673
2674    pub fn page_up(&mut self, _: &PageUp, _: &mut ViewContext<Self>) {
2675        log::info!("Editor::page_up");
2676    }
2677
2678    pub fn page_down(&mut self, _: &PageDown, _: &mut ViewContext<Self>) {
2679        log::info!("Editor::page_down");
2680    }
2681
2682    pub fn fold(&mut self, _: &Fold, cx: &mut ViewContext<Self>) {
2683        let mut fold_ranges = Vec::new();
2684
2685        let selections = self.selections::<Point>(cx).collect::<Vec<_>>();
2686        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2687        for selection in selections {
2688            let range = selection.display_range(&display_map).sorted();
2689            let buffer_start_row = range.start.to_point(&display_map).row;
2690
2691            for row in (0..=range.end.row()).rev() {
2692                if self.is_line_foldable(&display_map, row) && !display_map.is_line_folded(row) {
2693                    let fold_range = self.foldable_range_for_line(&display_map, row);
2694                    if fold_range.end.row >= buffer_start_row {
2695                        fold_ranges.push(fold_range);
2696                        if row <= range.start.row() {
2697                            break;
2698                        }
2699                    }
2700                }
2701            }
2702        }
2703
2704        self.fold_ranges(fold_ranges, cx);
2705    }
2706
2707    pub fn unfold(&mut self, _: &Unfold, cx: &mut ViewContext<Self>) {
2708        let selections = self.selections::<Point>(cx).collect::<Vec<_>>();
2709        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2710        let buffer = self.buffer.read(cx);
2711        let ranges = selections
2712            .iter()
2713            .map(|s| {
2714                let range = s.display_range(&display_map).sorted();
2715                let mut start = range.start.to_point(&display_map);
2716                let mut end = range.end.to_point(&display_map);
2717                start.column = 0;
2718                end.column = buffer.line_len(end.row);
2719                start..end
2720            })
2721            .collect::<Vec<_>>();
2722        self.unfold_ranges(ranges, cx);
2723    }
2724
2725    fn is_line_foldable(&self, display_map: &DisplayMapSnapshot, display_row: u32) -> bool {
2726        let max_point = display_map.max_point();
2727        if display_row >= max_point.row() {
2728            false
2729        } else {
2730            let (start_indent, is_blank) = display_map.line_indent(display_row);
2731            if is_blank {
2732                false
2733            } else {
2734                for display_row in display_row + 1..=max_point.row() {
2735                    let (indent, is_blank) = display_map.line_indent(display_row);
2736                    if !is_blank {
2737                        return indent > start_indent;
2738                    }
2739                }
2740                false
2741            }
2742        }
2743    }
2744
2745    fn foldable_range_for_line(
2746        &self,
2747        display_map: &DisplayMapSnapshot,
2748        start_row: u32,
2749    ) -> Range<Point> {
2750        let max_point = display_map.max_point();
2751
2752        let (start_indent, _) = display_map.line_indent(start_row);
2753        let start = DisplayPoint::new(start_row, display_map.line_len(start_row));
2754        let mut end = None;
2755        for row in start_row + 1..=max_point.row() {
2756            let (indent, is_blank) = display_map.line_indent(row);
2757            if !is_blank && indent <= start_indent {
2758                end = Some(DisplayPoint::new(row - 1, display_map.line_len(row - 1)));
2759                break;
2760            }
2761        }
2762
2763        let end = end.unwrap_or(max_point);
2764        return start.to_point(display_map)..end.to_point(display_map);
2765    }
2766
2767    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
2768        let selections = self.selections::<Point>(cx);
2769        let ranges = selections.map(|s| s.start..s.end).collect();
2770        self.fold_ranges(ranges, cx);
2771    }
2772
2773    fn fold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
2774        if !ranges.is_empty() {
2775            self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
2776            self.autoscroll_requested = true;
2777            cx.notify();
2778        }
2779    }
2780
2781    fn unfold_ranges<T: ToOffset>(&mut self, ranges: Vec<Range<T>>, cx: &mut ViewContext<Self>) {
2782        if !ranges.is_empty() {
2783            self.display_map
2784                .update(cx, |map, cx| map.unfold(ranges, cx));
2785            self.autoscroll_requested = true;
2786            cx.notify();
2787        }
2788    }
2789
2790    pub fn longest_row(&self, cx: &mut MutableAppContext) -> u32 {
2791        self.display_map
2792            .update(cx, |map, cx| map.snapshot(cx))
2793            .longest_row()
2794    }
2795
2796    pub fn max_point(&self, cx: &mut MutableAppContext) -> DisplayPoint {
2797        self.display_map
2798            .update(cx, |map, cx| map.snapshot(cx))
2799            .max_point()
2800    }
2801
2802    pub fn text(&self, cx: &AppContext) -> String {
2803        self.buffer.read(cx).text()
2804    }
2805
2806    pub fn display_text(&self, cx: &mut MutableAppContext) -> String {
2807        self.display_map
2808            .update(cx, |map, cx| map.snapshot(cx))
2809            .text()
2810    }
2811
2812    // pub fn font_size(&self) -> f32 {
2813    //     self.settings.font_size
2814    // }
2815
2816    pub fn set_wrap_width(&self, width: f32, cx: &mut MutableAppContext) -> bool {
2817        self.display_map
2818            .update(cx, |map, cx| map.set_wrap_width(Some(width), cx))
2819    }
2820
2821    fn next_blink_epoch(&mut self) -> usize {
2822        self.blink_epoch += 1;
2823        self.blink_epoch
2824    }
2825
2826    fn pause_cursor_blinking(&mut self, cx: &mut ViewContext<Self>) {
2827        self.show_local_cursors = true;
2828        cx.notify();
2829
2830        let epoch = self.next_blink_epoch();
2831        cx.spawn(|this, mut cx| {
2832            let this = this.downgrade();
2833            async move {
2834                Timer::after(CURSOR_BLINK_INTERVAL).await;
2835                if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
2836                    this.update(&mut cx, |this, cx| this.resume_cursor_blinking(epoch, cx))
2837                }
2838            }
2839        })
2840        .detach();
2841    }
2842
2843    fn resume_cursor_blinking(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
2844        if epoch == self.blink_epoch {
2845            self.blinking_paused = false;
2846            self.blink_cursors(epoch, cx);
2847        }
2848    }
2849
2850    fn blink_cursors(&mut self, epoch: usize, cx: &mut ViewContext<Self>) {
2851        if epoch == self.blink_epoch && self.focused && !self.blinking_paused {
2852            self.show_local_cursors = !self.show_local_cursors;
2853            cx.notify();
2854
2855            let epoch = self.next_blink_epoch();
2856            cx.spawn(|this, mut cx| {
2857                let this = this.downgrade();
2858                async move {
2859                    Timer::after(CURSOR_BLINK_INTERVAL).await;
2860                    if let Some(this) = cx.read(|cx| this.upgrade(cx)) {
2861                        this.update(&mut cx, |this, cx| this.blink_cursors(epoch, cx));
2862                    }
2863                }
2864            })
2865            .detach();
2866        }
2867    }
2868
2869    pub fn show_local_cursors(&self) -> bool {
2870        self.show_local_cursors
2871    }
2872
2873    fn on_buffer_changed(&mut self, _: ModelHandle<Buffer>, cx: &mut ViewContext<Self>) {
2874        self.refresh_active_diagnostics(cx);
2875        cx.notify();
2876    }
2877
2878    fn on_buffer_event(
2879        &mut self,
2880        _: ModelHandle<Buffer>,
2881        event: &language::Event,
2882        cx: &mut ViewContext<Self>,
2883    ) {
2884        match event {
2885            language::Event::Edited => cx.emit(Event::Edited),
2886            language::Event::Dirtied => cx.emit(Event::Dirtied),
2887            language::Event::Saved => cx.emit(Event::Saved),
2888            language::Event::FileHandleChanged => cx.emit(Event::FileHandleChanged),
2889            language::Event::Reloaded => cx.emit(Event::FileHandleChanged),
2890            language::Event::Closed => cx.emit(Event::Closed),
2891            language::Event::Reparsed => {}
2892        }
2893    }
2894
2895    fn on_display_map_changed(&mut self, _: ModelHandle<DisplayMap>, cx: &mut ViewContext<Self>) {
2896        cx.notify();
2897    }
2898}
2899
2900impl Snapshot {
2901    pub fn is_empty(&self) -> bool {
2902        self.display_snapshot.is_empty()
2903    }
2904
2905    pub fn is_focused(&self) -> bool {
2906        self.is_focused
2907    }
2908
2909    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
2910        self.placeholder_text.as_ref()
2911    }
2912
2913    pub fn buffer_row_count(&self) -> u32 {
2914        self.display_snapshot.buffer_row_count()
2915    }
2916
2917    pub fn buffer_rows<'a>(&'a self, start_row: u32, cx: &'a AppContext) -> BufferRows<'a> {
2918        self.display_snapshot.buffer_rows(start_row, Some(cx))
2919    }
2920
2921    pub fn chunks<'a>(
2922        &'a self,
2923        display_rows: Range<u32>,
2924        theme: Option<&'a SyntaxTheme>,
2925        cx: &'a AppContext,
2926    ) -> display_map::Chunks<'a> {
2927        self.display_snapshot.chunks(display_rows, theme, cx)
2928    }
2929
2930    pub fn scroll_position(&self) -> Vector2F {
2931        compute_scroll_position(
2932            &self.display_snapshot,
2933            self.scroll_position,
2934            &self.scroll_top_anchor,
2935        )
2936    }
2937
2938    pub fn max_point(&self) -> DisplayPoint {
2939        self.display_snapshot.max_point()
2940    }
2941
2942    pub fn longest_row(&self) -> u32 {
2943        self.display_snapshot.longest_row()
2944    }
2945
2946    pub fn line_len(&self, display_row: u32) -> u32 {
2947        self.display_snapshot.line_len(display_row)
2948    }
2949
2950    pub fn line(&self, display_row: u32) -> String {
2951        self.display_snapshot.line(display_row)
2952    }
2953
2954    pub fn prev_row_boundary(&self, point: DisplayPoint) -> (DisplayPoint, Point) {
2955        self.display_snapshot.prev_row_boundary(point)
2956    }
2957
2958    pub fn next_row_boundary(&self, point: DisplayPoint) -> (DisplayPoint, Point) {
2959        self.display_snapshot.next_row_boundary(point)
2960    }
2961}
2962
2963impl EditorSettings {
2964    #[cfg(any(test, feature = "test-support"))]
2965    pub fn test(cx: &AppContext) -> Self {
2966        Self {
2967            tab_size: 4,
2968            style: {
2969                let font_cache: &gpui::FontCache = cx.font_cache();
2970                let font_family_name = Arc::from("Monaco");
2971                let font_properties = Default::default();
2972                let font_family_id = font_cache.load_family(&[&font_family_name]).unwrap();
2973                let font_id = font_cache
2974                    .select_font(font_family_id, &font_properties)
2975                    .unwrap();
2976                EditorStyle {
2977                    text: gpui::fonts::TextStyle {
2978                        font_family_name,
2979                        font_family_id,
2980                        font_id,
2981                        font_size: 14.,
2982                        color: gpui::color::Color::from_u32(0xff0000ff),
2983                        font_properties,
2984                        underline: None,
2985                    },
2986                    placeholder_text: None,
2987                    background: Default::default(),
2988                    gutter_background: Default::default(),
2989                    active_line_background: Default::default(),
2990                    line_number: Default::default(),
2991                    line_number_active: Default::default(),
2992                    selection: Default::default(),
2993                    guest_selections: Default::default(),
2994                    syntax: Default::default(),
2995                    error_diagnostic: Default::default(),
2996                    invalid_error_diagnostic: Default::default(),
2997                    warning_diagnostic: Default::default(),
2998                    invalid_warning_diagnostic: Default::default(),
2999                    information_diagnostic: Default::default(),
3000                    invalid_information_diagnostic: Default::default(),
3001                    hint_diagnostic: Default::default(),
3002                    invalid_hint_diagnostic: Default::default(),
3003                }
3004            },
3005        }
3006    }
3007}
3008
3009fn compute_scroll_position(
3010    snapshot: &DisplayMapSnapshot,
3011    mut scroll_position: Vector2F,
3012    scroll_top_anchor: &Anchor,
3013) -> Vector2F {
3014    let scroll_top = scroll_top_anchor.to_display_point(snapshot).row() as f32;
3015    scroll_position.set_y(scroll_top + scroll_position.y());
3016    scroll_position
3017}
3018
3019pub enum Event {
3020    Activate,
3021    Edited,
3022    Blurred,
3023    Dirtied,
3024    Saved,
3025    FileHandleChanged,
3026    Closed,
3027}
3028
3029impl Entity for Editor {
3030    type Event = Event;
3031
3032    fn release(&mut self, cx: &mut MutableAppContext) {
3033        self.buffer.update(cx, |buffer, cx| {
3034            buffer
3035                .remove_selection_set(self.selection_set_id, cx)
3036                .unwrap();
3037        });
3038    }
3039}
3040
3041impl View for Editor {
3042    fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
3043        let settings = self.build_settings.borrow_mut()(cx);
3044        self.display_map.update(cx, |map, cx| {
3045            map.set_font(
3046                settings.style.text.font_id,
3047                settings.style.text.font_size,
3048                cx,
3049            )
3050        });
3051        EditorElement::new(self.handle.clone(), settings).boxed()
3052    }
3053
3054    fn ui_name() -> &'static str {
3055        "Editor"
3056    }
3057
3058    fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
3059        self.focused = true;
3060        self.blink_cursors(self.blink_epoch, cx);
3061        self.buffer.update(cx, |buffer, cx| {
3062            buffer
3063                .set_active_selection_set(Some(self.selection_set_id), cx)
3064                .unwrap();
3065        });
3066    }
3067
3068    fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
3069        self.focused = false;
3070        self.show_local_cursors = false;
3071        self.buffer.update(cx, |buffer, cx| {
3072            buffer.set_active_selection_set(None, cx).unwrap();
3073        });
3074        cx.emit(Event::Blurred);
3075        cx.notify();
3076    }
3077
3078    fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
3079        let mut cx = Self::default_keymap_context();
3080        let mode = match self.mode {
3081            EditorMode::SingleLine => "single_line",
3082            EditorMode::AutoHeight { .. } => "auto_height",
3083            EditorMode::Full => "full",
3084        };
3085        cx.map.insert("mode".into(), mode.into());
3086        cx
3087    }
3088}
3089
3090impl SelectionExt for Selection<Point> {
3091    fn display_range(&self, map: &DisplayMapSnapshot) -> Range<DisplayPoint> {
3092        let start = self.start.to_display_point(map);
3093        let end = self.end.to_display_point(map);
3094        if self.reversed {
3095            end..start
3096        } else {
3097            start..end
3098        }
3099    }
3100
3101    fn spanned_rows(
3102        &self,
3103        include_end_if_at_line_start: bool,
3104        map: &DisplayMapSnapshot,
3105    ) -> SpannedRows {
3106        let display_start = self.start.to_display_point(map);
3107        let mut display_end = self.end.to_display_point(map);
3108        if !include_end_if_at_line_start
3109            && display_end.row() != map.max_point().row()
3110            && display_start.row() != display_end.row()
3111            && display_end.column() == 0
3112        {
3113            *display_end.row_mut() -= 1;
3114        }
3115
3116        let (display_start, buffer_start) = map.prev_row_boundary(display_start);
3117        let (display_end, buffer_end) = map.next_row_boundary(display_end);
3118
3119        SpannedRows {
3120            buffer_rows: buffer_start.row..buffer_end.row + 1,
3121            display_rows: display_start.row()..display_end.row() + 1,
3122        }
3123    }
3124}
3125
3126pub fn diagnostic_style(
3127    severity: DiagnosticSeverity,
3128    valid: bool,
3129    style: &EditorStyle,
3130) -> DiagnosticStyle {
3131    match (severity, valid) {
3132        (DiagnosticSeverity::ERROR, true) => style.error_diagnostic,
3133        (DiagnosticSeverity::ERROR, false) => style.invalid_error_diagnostic,
3134        (DiagnosticSeverity::WARNING, true) => style.warning_diagnostic,
3135        (DiagnosticSeverity::WARNING, false) => style.invalid_warning_diagnostic,
3136        (DiagnosticSeverity::INFORMATION, true) => style.information_diagnostic,
3137        (DiagnosticSeverity::INFORMATION, false) => style.invalid_information_diagnostic,
3138        (DiagnosticSeverity::HINT, true) => style.hint_diagnostic,
3139        (DiagnosticSeverity::HINT, false) => style.invalid_hint_diagnostic,
3140        _ => Default::default(),
3141    }
3142}
3143
3144#[cfg(test)]
3145mod tests {
3146    use super::*;
3147    use crate::test::sample_text;
3148    use buffer::Point;
3149    use unindent::Unindent;
3150
3151    #[gpui::test]
3152    fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
3153        let buffer = cx.add_model(|cx| Buffer::new(0, "aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx));
3154        let settings = EditorSettings::test(cx);
3155        let (_, editor) =
3156            cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3157
3158        editor.update(cx, |view, cx| {
3159            view.begin_selection(DisplayPoint::new(2, 2), false, cx);
3160        });
3161
3162        assert_eq!(
3163            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3164            [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
3165        );
3166
3167        editor.update(cx, |view, cx| {
3168            view.update_selection(DisplayPoint::new(3, 3), Vector2F::zero(), cx);
3169        });
3170
3171        assert_eq!(
3172            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3173            [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3174        );
3175
3176        editor.update(cx, |view, cx| {
3177            view.update_selection(DisplayPoint::new(1, 1), Vector2F::zero(), cx);
3178        });
3179
3180        assert_eq!(
3181            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3182            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
3183        );
3184
3185        editor.update(cx, |view, cx| {
3186            view.end_selection(cx);
3187            view.update_selection(DisplayPoint::new(3, 3), Vector2F::zero(), cx);
3188        });
3189
3190        assert_eq!(
3191            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3192            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
3193        );
3194
3195        editor.update(cx, |view, cx| {
3196            view.begin_selection(DisplayPoint::new(3, 3), true, cx);
3197            view.update_selection(DisplayPoint::new(0, 0), Vector2F::zero(), cx);
3198        });
3199
3200        assert_eq!(
3201            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3202            [
3203                DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
3204                DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
3205            ]
3206        );
3207
3208        editor.update(cx, |view, cx| {
3209            view.end_selection(cx);
3210        });
3211
3212        assert_eq!(
3213            editor.update(cx, |view, cx| view.selection_ranges(cx)),
3214            [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
3215        );
3216    }
3217
3218    #[gpui::test]
3219    fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
3220        let buffer = cx.add_model(|cx| Buffer::new(0, "aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx));
3221        let settings = EditorSettings::test(cx);
3222        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3223
3224        view.update(cx, |view, cx| {
3225            view.begin_selection(DisplayPoint::new(2, 2), false, cx);
3226            assert_eq!(
3227                view.selection_ranges(cx),
3228                [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
3229            );
3230        });
3231
3232        view.update(cx, |view, cx| {
3233            view.update_selection(DisplayPoint::new(3, 3), Vector2F::zero(), cx);
3234            assert_eq!(
3235                view.selection_ranges(cx),
3236                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3237            );
3238        });
3239
3240        view.update(cx, |view, cx| {
3241            view.cancel(&Cancel, cx);
3242            view.update_selection(DisplayPoint::new(1, 1), Vector2F::zero(), cx);
3243            assert_eq!(
3244                view.selection_ranges(cx),
3245                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
3246            );
3247        });
3248    }
3249
3250    #[gpui::test]
3251    fn test_cancel(cx: &mut gpui::MutableAppContext) {
3252        let buffer = cx.add_model(|cx| Buffer::new(0, "aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx));
3253        let settings = EditorSettings::test(cx);
3254        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3255
3256        view.update(cx, |view, cx| {
3257            view.begin_selection(DisplayPoint::new(3, 4), false, cx);
3258            view.update_selection(DisplayPoint::new(1, 1), Vector2F::zero(), cx);
3259            view.end_selection(cx);
3260
3261            view.begin_selection(DisplayPoint::new(0, 1), true, cx);
3262            view.update_selection(DisplayPoint::new(0, 3), Vector2F::zero(), cx);
3263            view.end_selection(cx);
3264            assert_eq!(
3265                view.selection_ranges(cx),
3266                [
3267                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
3268                    DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
3269                ]
3270            );
3271        });
3272
3273        view.update(cx, |view, cx| {
3274            view.cancel(&Cancel, cx);
3275            assert_eq!(
3276                view.selection_ranges(cx),
3277                [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
3278            );
3279        });
3280
3281        view.update(cx, |view, cx| {
3282            view.cancel(&Cancel, cx);
3283            assert_eq!(
3284                view.selection_ranges(cx),
3285                [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
3286            );
3287        });
3288    }
3289
3290    #[gpui::test]
3291    fn test_fold(cx: &mut gpui::MutableAppContext) {
3292        let buffer = cx.add_model(|cx| {
3293            Buffer::new(
3294                0,
3295                "
3296                    impl Foo {
3297                        // Hello!
3298
3299                        fn a() {
3300                            1
3301                        }
3302
3303                        fn b() {
3304                            2
3305                        }
3306
3307                        fn c() {
3308                            3
3309                        }
3310                    }
3311                "
3312                .unindent(),
3313                cx,
3314            )
3315        });
3316        let settings = EditorSettings::test(&cx);
3317        let (_, view) = cx.add_window(Default::default(), |cx| {
3318            build_editor(buffer.clone(), settings, cx)
3319        });
3320
3321        view.update(cx, |view, cx| {
3322            view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx)
3323                .unwrap();
3324            view.fold(&Fold, cx);
3325            assert_eq!(
3326                view.display_text(cx),
3327                "
3328                    impl Foo {
3329                        // Hello!
3330
3331                        fn a() {
3332                            1
3333                        }
3334
3335                        fn b() {…
3336                        }
3337
3338                        fn c() {…
3339                        }
3340                    }
3341                "
3342                .unindent(),
3343            );
3344
3345            view.fold(&Fold, cx);
3346            assert_eq!(
3347                view.display_text(cx),
3348                "
3349                    impl Foo {…
3350                    }
3351                "
3352                .unindent(),
3353            );
3354
3355            view.unfold(&Unfold, cx);
3356            assert_eq!(
3357                view.display_text(cx),
3358                "
3359                    impl Foo {
3360                        // Hello!
3361
3362                        fn a() {
3363                            1
3364                        }
3365
3366                        fn b() {…
3367                        }
3368
3369                        fn c() {…
3370                        }
3371                    }
3372                "
3373                .unindent(),
3374            );
3375
3376            view.unfold(&Unfold, cx);
3377            assert_eq!(view.display_text(cx), buffer.read(cx).text());
3378        });
3379    }
3380
3381    #[gpui::test]
3382    fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
3383        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 6), cx));
3384        let settings = EditorSettings::test(&cx);
3385        let (_, view) = cx.add_window(Default::default(), |cx| {
3386            build_editor(buffer.clone(), settings, cx)
3387        });
3388
3389        buffer.update(cx, |buffer, cx| {
3390            buffer.edit(
3391                vec![
3392                    Point::new(1, 0)..Point::new(1, 0),
3393                    Point::new(1, 1)..Point::new(1, 1),
3394                ],
3395                "\t",
3396                cx,
3397            );
3398        });
3399
3400        view.update(cx, |view, cx| {
3401            assert_eq!(
3402                view.selection_ranges(cx),
3403                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
3404            );
3405
3406            view.move_down(&MoveDown, cx);
3407            assert_eq!(
3408                view.selection_ranges(cx),
3409                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
3410            );
3411
3412            view.move_right(&MoveRight, cx);
3413            assert_eq!(
3414                view.selection_ranges(cx),
3415                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
3416            );
3417
3418            view.move_left(&MoveLeft, cx);
3419            assert_eq!(
3420                view.selection_ranges(cx),
3421                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
3422            );
3423
3424            view.move_up(&MoveUp, cx);
3425            assert_eq!(
3426                view.selection_ranges(cx),
3427                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
3428            );
3429
3430            view.move_to_end(&MoveToEnd, cx);
3431            assert_eq!(
3432                view.selection_ranges(cx),
3433                &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
3434            );
3435
3436            view.move_to_beginning(&MoveToBeginning, cx);
3437            assert_eq!(
3438                view.selection_ranges(cx),
3439                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
3440            );
3441
3442            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx)
3443                .unwrap();
3444            view.select_to_beginning(&SelectToBeginning, cx);
3445            assert_eq!(
3446                view.selection_ranges(cx),
3447                &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
3448            );
3449
3450            view.select_to_end(&SelectToEnd, cx);
3451            assert_eq!(
3452                view.selection_ranges(cx),
3453                &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
3454            );
3455        });
3456    }
3457
3458    #[gpui::test]
3459    fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
3460        let buffer = cx.add_model(|cx| Buffer::new(0, "ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx));
3461        let settings = EditorSettings::test(&cx);
3462        let (_, view) = cx.add_window(Default::default(), |cx| {
3463            build_editor(buffer.clone(), settings, cx)
3464        });
3465
3466        assert_eq!('ⓐ'.len_utf8(), 3);
3467        assert_eq!('α'.len_utf8(), 2);
3468
3469        view.update(cx, |view, cx| {
3470            view.fold_ranges(
3471                vec![
3472                    Point::new(0, 6)..Point::new(0, 12),
3473                    Point::new(1, 2)..Point::new(1, 4),
3474                    Point::new(2, 4)..Point::new(2, 8),
3475                ],
3476                cx,
3477            );
3478            assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
3479
3480            view.move_right(&MoveRight, cx);
3481            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "".len())]);
3482            view.move_right(&MoveRight, cx);
3483            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ".len())]);
3484            view.move_right(&MoveRight, cx);
3485            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…".len())]);
3486
3487            view.move_down(&MoveDown, cx);
3488            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab…".len())]);
3489            view.move_left(&MoveLeft, cx);
3490            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab".len())]);
3491            view.move_left(&MoveLeft, cx);
3492            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "a".len())]);
3493
3494            view.move_down(&MoveDown, cx);
3495            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "α".len())]);
3496            view.move_right(&MoveRight, cx);
3497            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ".len())]);
3498            view.move_right(&MoveRight, cx);
3499            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ…".len())]);
3500            view.move_right(&MoveRight, cx);
3501            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβ…ε".len())]);
3502
3503            view.move_up(&MoveUp, cx);
3504            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "ab…e".len())]);
3505            view.move_up(&MoveUp, cx);
3506            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…ⓔ".len())]);
3507            view.move_left(&MoveLeft, cx);
3508            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ…".len())]);
3509            view.move_left(&MoveLeft, cx);
3510            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "ⓐⓑ".len())]);
3511            view.move_left(&MoveLeft, cx);
3512            assert_eq!(view.selection_ranges(cx), &[empty_range(0, "".len())]);
3513        });
3514    }
3515
3516    #[gpui::test]
3517    fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
3518        let buffer = cx.add_model(|cx| Buffer::new(0, "ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx));
3519        let settings = EditorSettings::test(&cx);
3520        let (_, view) = cx.add_window(Default::default(), |cx| {
3521            build_editor(buffer.clone(), settings, cx)
3522        });
3523        view.update(cx, |view, cx| {
3524            view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx)
3525                .unwrap();
3526
3527            view.move_down(&MoveDown, cx);
3528            assert_eq!(view.selection_ranges(cx), &[empty_range(1, "abcd".len())]);
3529
3530            view.move_down(&MoveDown, cx);
3531            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβγ".len())]);
3532
3533            view.move_down(&MoveDown, cx);
3534            assert_eq!(view.selection_ranges(cx), &[empty_range(3, "abcd".len())]);
3535
3536            view.move_down(&MoveDown, cx);
3537            assert_eq!(view.selection_ranges(cx), &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]);
3538
3539            view.move_up(&MoveUp, cx);
3540            assert_eq!(view.selection_ranges(cx), &[empty_range(3, "abcd".len())]);
3541
3542            view.move_up(&MoveUp, cx);
3543            assert_eq!(view.selection_ranges(cx), &[empty_range(2, "αβγ".len())]);
3544        });
3545    }
3546
3547    #[gpui::test]
3548    fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
3549        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\n  def", cx));
3550        let settings = EditorSettings::test(&cx);
3551        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3552        view.update(cx, |view, cx| {
3553            view.select_display_ranges(
3554                &[
3555                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
3556                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
3557                ],
3558                cx,
3559            )
3560            .unwrap();
3561        });
3562
3563        view.update(cx, |view, cx| {
3564            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
3565            assert_eq!(
3566                view.selection_ranges(cx),
3567                &[
3568                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3569                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
3570                ]
3571            );
3572        });
3573
3574        view.update(cx, |view, cx| {
3575            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
3576            assert_eq!(
3577                view.selection_ranges(cx),
3578                &[
3579                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3580                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3581                ]
3582            );
3583        });
3584
3585        view.update(cx, |view, cx| {
3586            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
3587            assert_eq!(
3588                view.selection_ranges(cx),
3589                &[
3590                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3591                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
3592                ]
3593            );
3594        });
3595
3596        view.update(cx, |view, cx| {
3597            view.move_to_end_of_line(&MoveToEndOfLine, cx);
3598            assert_eq!(
3599                view.selection_ranges(cx),
3600                &[
3601                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3602                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
3603                ]
3604            );
3605        });
3606
3607        // Moving to the end of line again is a no-op.
3608        view.update(cx, |view, cx| {
3609            view.move_to_end_of_line(&MoveToEndOfLine, cx);
3610            assert_eq!(
3611                view.selection_ranges(cx),
3612                &[
3613                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3614                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
3615                ]
3616            );
3617        });
3618
3619        view.update(cx, |view, cx| {
3620            view.move_left(&MoveLeft, cx);
3621            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
3622            assert_eq!(
3623                view.selection_ranges(cx),
3624                &[
3625                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
3626                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
3627                ]
3628            );
3629        });
3630
3631        view.update(cx, |view, cx| {
3632            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
3633            assert_eq!(
3634                view.selection_ranges(cx),
3635                &[
3636                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
3637                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
3638                ]
3639            );
3640        });
3641
3642        view.update(cx, |view, cx| {
3643            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
3644            assert_eq!(
3645                view.selection_ranges(cx),
3646                &[
3647                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
3648                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
3649                ]
3650            );
3651        });
3652
3653        view.update(cx, |view, cx| {
3654            view.select_to_end_of_line(&SelectToEndOfLine, cx);
3655            assert_eq!(
3656                view.selection_ranges(cx),
3657                &[
3658                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
3659                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
3660                ]
3661            );
3662        });
3663
3664        view.update(cx, |view, cx| {
3665            view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
3666            assert_eq!(view.display_text(cx), "ab\n  de");
3667            assert_eq!(
3668                view.selection_ranges(cx),
3669                &[
3670                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3671                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
3672                ]
3673            );
3674        });
3675
3676        view.update(cx, |view, cx| {
3677            view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
3678            assert_eq!(view.display_text(cx), "\n");
3679            assert_eq!(
3680                view.selection_ranges(cx),
3681                &[
3682                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3683                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3684                ]
3685            );
3686        });
3687    }
3688
3689    #[gpui::test]
3690    fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
3691        let buffer =
3692            cx.add_model(|cx| Buffer::new(0, "use std::str::{foo, bar}\n\n  {baz.qux()}", cx));
3693        let settings = EditorSettings::test(&cx);
3694        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3695        view.update(cx, |view, cx| {
3696            view.select_display_ranges(
3697                &[
3698                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
3699                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
3700                ],
3701                cx,
3702            )
3703            .unwrap();
3704        });
3705
3706        view.update(cx, |view, cx| {
3707            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3708            assert_eq!(
3709                view.selection_ranges(cx),
3710                &[
3711                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
3712                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
3713                ]
3714            );
3715        });
3716
3717        view.update(cx, |view, cx| {
3718            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3719            assert_eq!(
3720                view.selection_ranges(cx),
3721                &[
3722                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
3723                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
3724                ]
3725            );
3726        });
3727
3728        view.update(cx, |view, cx| {
3729            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3730            assert_eq!(
3731                view.selection_ranges(cx),
3732                &[
3733                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
3734                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
3735                ]
3736            );
3737        });
3738
3739        view.update(cx, |view, cx| {
3740            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3741            assert_eq!(
3742                view.selection_ranges(cx),
3743                &[
3744                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3745                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3746                ]
3747            );
3748        });
3749
3750        view.update(cx, |view, cx| {
3751            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3752            assert_eq!(
3753                view.selection_ranges(cx),
3754                &[
3755                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
3756                    DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
3757                ]
3758            );
3759        });
3760
3761        view.update(cx, |view, cx| {
3762            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3763            assert_eq!(
3764                view.selection_ranges(cx),
3765                &[
3766                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3767                    DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
3768                ]
3769            );
3770        });
3771
3772        view.update(cx, |view, cx| {
3773            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3774            assert_eq!(
3775                view.selection_ranges(cx),
3776                &[
3777                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
3778                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
3779                ]
3780            );
3781        });
3782
3783        view.update(cx, |view, cx| {
3784            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3785            assert_eq!(
3786                view.selection_ranges(cx),
3787                &[
3788                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
3789                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
3790                ]
3791            );
3792        });
3793
3794        view.update(cx, |view, cx| {
3795            view.move_right(&MoveRight, cx);
3796            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
3797            assert_eq!(
3798                view.selection_ranges(cx),
3799                &[
3800                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
3801                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
3802                ]
3803            );
3804        });
3805
3806        view.update(cx, |view, cx| {
3807            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
3808            assert_eq!(
3809                view.selection_ranges(cx),
3810                &[
3811                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
3812                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
3813                ]
3814            );
3815        });
3816
3817        view.update(cx, |view, cx| {
3818            view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
3819            assert_eq!(
3820                view.selection_ranges(cx),
3821                &[
3822                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
3823                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
3824                ]
3825            );
3826        });
3827    }
3828
3829    #[gpui::test]
3830    fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
3831        let buffer =
3832            cx.add_model(|cx| Buffer::new(0, "use one::{\n    two::three::four::five\n};", cx));
3833        let settings = EditorSettings::test(&cx);
3834        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
3835
3836        view.update(cx, |view, cx| {
3837            view.set_wrap_width(140., cx);
3838            assert_eq!(
3839                view.display_text(cx),
3840                "use one::{\n    two::three::\n    four::five\n};"
3841            );
3842
3843            view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx)
3844                .unwrap();
3845
3846            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3847            assert_eq!(
3848                view.selection_ranges(cx),
3849                &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
3850            );
3851
3852            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3853            assert_eq!(
3854                view.selection_ranges(cx),
3855                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
3856            );
3857
3858            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3859            assert_eq!(
3860                view.selection_ranges(cx),
3861                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
3862            );
3863
3864            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
3865            assert_eq!(
3866                view.selection_ranges(cx),
3867                &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
3868            );
3869
3870            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3871            assert_eq!(
3872                view.selection_ranges(cx),
3873                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
3874            );
3875
3876            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
3877            assert_eq!(
3878                view.selection_ranges(cx),
3879                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
3880            );
3881        });
3882    }
3883
3884    #[gpui::test]
3885    fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
3886        let buffer = cx.add_model(|cx| Buffer::new(0, "one two three four", cx));
3887        let settings = EditorSettings::test(&cx);
3888        let (_, view) = cx.add_window(Default::default(), |cx| {
3889            build_editor(buffer.clone(), settings, cx)
3890        });
3891
3892        view.update(cx, |view, cx| {
3893            view.select_display_ranges(
3894                &[
3895                    // an empty selection - the preceding word fragment is deleted
3896                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3897                    // characters selected - they are deleted
3898                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
3899                ],
3900                cx,
3901            )
3902            .unwrap();
3903            view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
3904        });
3905
3906        assert_eq!(buffer.read(cx).text(), "e two te four");
3907
3908        view.update(cx, |view, cx| {
3909            view.select_display_ranges(
3910                &[
3911                    // an empty selection - the following word fragment is deleted
3912                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
3913                    // characters selected - they are deleted
3914                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
3915                ],
3916                cx,
3917            )
3918            .unwrap();
3919            view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
3920        });
3921
3922        assert_eq!(buffer.read(cx).text(), "e t te our");
3923    }
3924
3925    #[gpui::test]
3926    fn test_newline(cx: &mut gpui::MutableAppContext) {
3927        let buffer = cx.add_model(|cx| Buffer::new(0, "aaaa\n    bbbb\n", cx));
3928        let settings = EditorSettings::test(&cx);
3929        let (_, view) = cx.add_window(Default::default(), |cx| {
3930            build_editor(buffer.clone(), settings, cx)
3931        });
3932
3933        view.update(cx, |view, cx| {
3934            view.select_display_ranges(
3935                &[
3936                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3937                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
3938                    DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
3939                ],
3940                cx,
3941            )
3942            .unwrap();
3943
3944            view.newline(&Newline, cx);
3945            assert_eq!(view.text(cx), "aa\naa\n  \n    bb\n    bb\n");
3946        });
3947    }
3948
3949    #[gpui::test]
3950    fn test_backspace(cx: &mut gpui::MutableAppContext) {
3951        let buffer = cx.add_model(|cx| {
3952            Buffer::new(
3953                0,
3954                "one two three\nfour five six\nseven eight nine\nten\n",
3955                cx,
3956            )
3957        });
3958        let settings = EditorSettings::test(&cx);
3959        let (_, view) = cx.add_window(Default::default(), |cx| {
3960            build_editor(buffer.clone(), settings, cx)
3961        });
3962
3963        view.update(cx, |view, cx| {
3964            view.select_display_ranges(
3965                &[
3966                    // an empty selection - the preceding character is deleted
3967                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
3968                    // one character selected - it is deleted
3969                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
3970                    // a line suffix selected - it is deleted
3971                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
3972                ],
3973                cx,
3974            )
3975            .unwrap();
3976            view.backspace(&Backspace, cx);
3977        });
3978
3979        assert_eq!(
3980            buffer.read(cx).text(),
3981            "oe two three\nfou five six\nseven ten\n"
3982        );
3983    }
3984
3985    #[gpui::test]
3986    fn test_delete(cx: &mut gpui::MutableAppContext) {
3987        let buffer = cx.add_model(|cx| {
3988            Buffer::new(
3989                0,
3990                "one two three\nfour five six\nseven eight nine\nten\n",
3991                cx,
3992            )
3993        });
3994        let settings = EditorSettings::test(&cx);
3995        let (_, view) = cx.add_window(Default::default(), |cx| {
3996            build_editor(buffer.clone(), settings, cx)
3997        });
3998
3999        view.update(cx, |view, cx| {
4000            view.select_display_ranges(
4001                &[
4002                    // an empty selection - the following character is deleted
4003                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4004                    // one character selected - it is deleted
4005                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4006                    // a line suffix selected - it is deleted
4007                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
4008                ],
4009                cx,
4010            )
4011            .unwrap();
4012            view.delete(&Delete, cx);
4013        });
4014
4015        assert_eq!(
4016            buffer.read(cx).text(),
4017            "on two three\nfou five six\nseven ten\n"
4018        );
4019    }
4020
4021    #[gpui::test]
4022    fn test_delete_line(cx: &mut gpui::MutableAppContext) {
4023        let settings = EditorSettings::test(&cx);
4024        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
4025        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4026        view.update(cx, |view, cx| {
4027            view.select_display_ranges(
4028                &[
4029                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4030                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
4031                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4032                ],
4033                cx,
4034            )
4035            .unwrap();
4036            view.delete_line(&DeleteLine, cx);
4037            assert_eq!(view.display_text(cx), "ghi");
4038            assert_eq!(
4039                view.selection_ranges(cx),
4040                vec![
4041                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4042                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
4043                ]
4044            );
4045        });
4046
4047        let settings = EditorSettings::test(&cx);
4048        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
4049        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4050        view.update(cx, |view, cx| {
4051            view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx)
4052                .unwrap();
4053            view.delete_line(&DeleteLine, cx);
4054            assert_eq!(view.display_text(cx), "ghi\n");
4055            assert_eq!(
4056                view.selection_ranges(cx),
4057                vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
4058            );
4059        });
4060    }
4061
4062    #[gpui::test]
4063    fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
4064        let settings = EditorSettings::test(&cx);
4065        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
4066        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4067        view.update(cx, |view, cx| {
4068            view.select_display_ranges(
4069                &[
4070                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4071                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4072                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4073                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4074                ],
4075                cx,
4076            )
4077            .unwrap();
4078            view.duplicate_line(&DuplicateLine, cx);
4079            assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
4080            assert_eq!(
4081                view.selection_ranges(cx),
4082                vec![
4083                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
4084                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4085                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4086                    DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
4087                ]
4088            );
4089        });
4090
4091        let settings = EditorSettings::test(&cx);
4092        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndef\nghi\n", cx));
4093        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4094        view.update(cx, |view, cx| {
4095            view.select_display_ranges(
4096                &[
4097                    DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
4098                    DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
4099                ],
4100                cx,
4101            )
4102            .unwrap();
4103            view.duplicate_line(&DuplicateLine, cx);
4104            assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
4105            assert_eq!(
4106                view.selection_ranges(cx),
4107                vec![
4108                    DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
4109                    DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
4110                ]
4111            );
4112        });
4113    }
4114
4115    #[gpui::test]
4116    fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
4117        let settings = EditorSettings::test(&cx);
4118        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(10, 5), cx));
4119        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4120        view.update(cx, |view, cx| {
4121            view.fold_ranges(
4122                vec![
4123                    Point::new(0, 2)..Point::new(1, 2),
4124                    Point::new(2, 3)..Point::new(4, 1),
4125                    Point::new(7, 0)..Point::new(8, 4),
4126                ],
4127                cx,
4128            );
4129            view.select_display_ranges(
4130                &[
4131                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4132                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
4133                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
4134                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
4135                ],
4136                cx,
4137            )
4138            .unwrap();
4139            assert_eq!(
4140                view.display_text(cx),
4141                "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
4142            );
4143
4144            view.move_line_up(&MoveLineUp, cx);
4145            assert_eq!(
4146                view.display_text(cx),
4147                "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
4148            );
4149            assert_eq!(
4150                view.selection_ranges(cx),
4151                vec![
4152                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4153                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4154                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
4155                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
4156                ]
4157            );
4158        });
4159
4160        view.update(cx, |view, cx| {
4161            view.move_line_down(&MoveLineDown, cx);
4162            assert_eq!(
4163                view.display_text(cx),
4164                "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
4165            );
4166            assert_eq!(
4167                view.selection_ranges(cx),
4168                vec![
4169                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4170                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
4171                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
4172                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
4173                ]
4174            );
4175        });
4176
4177        view.update(cx, |view, cx| {
4178            view.move_line_down(&MoveLineDown, cx);
4179            assert_eq!(
4180                view.display_text(cx),
4181                "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
4182            );
4183            assert_eq!(
4184                view.selection_ranges(cx),
4185                vec![
4186                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4187                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
4188                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
4189                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
4190                ]
4191            );
4192        });
4193
4194        view.update(cx, |view, cx| {
4195            view.move_line_up(&MoveLineUp, cx);
4196            assert_eq!(
4197                view.display_text(cx),
4198                "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
4199            );
4200            assert_eq!(
4201                view.selection_ranges(cx),
4202                vec![
4203                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4204                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4205                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
4206                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
4207                ]
4208            );
4209        });
4210    }
4211
4212    #[gpui::test]
4213    fn test_clipboard(cx: &mut gpui::MutableAppContext) {
4214        let buffer = cx.add_model(|cx| Buffer::new(0, "one✅ two three four five six ", cx));
4215        let settings = EditorSettings::test(&cx);
4216        let view = cx
4217            .add_window(Default::default(), |cx| {
4218                build_editor(buffer.clone(), settings, cx)
4219            })
4220            .1;
4221
4222        // Cut with three selections. Clipboard text is divided into three slices.
4223        view.update(cx, |view, cx| {
4224            view.select_ranges(vec![0..7, 11..17, 22..27], false, cx);
4225            view.cut(&Cut, cx);
4226            assert_eq!(view.display_text(cx), "two four six ");
4227        });
4228
4229        // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
4230        view.update(cx, |view, cx| {
4231            view.select_ranges(vec![4..4, 9..9, 13..13], false, cx);
4232            view.paste(&Paste, cx);
4233            assert_eq!(view.display_text(cx), "two one✅ four three six five ");
4234            assert_eq!(
4235                view.selection_ranges(cx),
4236                &[
4237                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
4238                    DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
4239                    DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
4240                ]
4241            );
4242        });
4243
4244        // Paste again but with only two cursors. Since the number of cursors doesn't
4245        // match the number of slices in the clipboard, the entire clipboard text
4246        // is pasted at each cursor.
4247        view.update(cx, |view, cx| {
4248            view.select_ranges(vec![0..0, 31..31], false, cx);
4249            view.handle_input(&Input("( ".into()), cx);
4250            view.paste(&Paste, cx);
4251            view.handle_input(&Input(") ".into()), cx);
4252            assert_eq!(
4253                view.display_text(cx),
4254                "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
4255            );
4256        });
4257
4258        view.update(cx, |view, cx| {
4259            view.select_ranges(vec![0..0], false, cx);
4260            view.handle_input(&Input("123\n4567\n89\n".into()), cx);
4261            assert_eq!(
4262                view.display_text(cx),
4263                "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
4264            );
4265        });
4266
4267        // Cut with three selections, one of which is full-line.
4268        view.update(cx, |view, cx| {
4269            view.select_display_ranges(
4270                &[
4271                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
4272                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4273                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
4274                ],
4275                cx,
4276            )
4277            .unwrap();
4278            view.cut(&Cut, cx);
4279            assert_eq!(
4280                view.display_text(cx),
4281                "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
4282            );
4283        });
4284
4285        // Paste with three selections, noticing how the copied selection that was full-line
4286        // gets inserted before the second cursor.
4287        view.update(cx, |view, cx| {
4288            view.select_display_ranges(
4289                &[
4290                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4291                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4292                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
4293                ],
4294                cx,
4295            )
4296            .unwrap();
4297            view.paste(&Paste, cx);
4298            assert_eq!(
4299                view.display_text(cx),
4300                "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
4301            );
4302            assert_eq!(
4303                view.selection_ranges(cx),
4304                &[
4305                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4306                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4307                    DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
4308                ]
4309            );
4310        });
4311
4312        // Copy with a single cursor only, which writes the whole line into the clipboard.
4313        view.update(cx, |view, cx| {
4314            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx)
4315                .unwrap();
4316            view.copy(&Copy, cx);
4317        });
4318
4319        // Paste with three selections, noticing how the copied full-line selection is inserted
4320        // before the empty selections but replaces the selection that is non-empty.
4321        view.update(cx, |view, cx| {
4322            view.select_display_ranges(
4323                &[
4324                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4325                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
4326                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4327                ],
4328                cx,
4329            )
4330            .unwrap();
4331            view.paste(&Paste, cx);
4332            assert_eq!(
4333                view.display_text(cx),
4334                "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
4335            );
4336            assert_eq!(
4337                view.selection_ranges(cx),
4338                &[
4339                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
4340                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4341                    DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
4342                ]
4343            );
4344        });
4345    }
4346
4347    #[gpui::test]
4348    fn test_select_all(cx: &mut gpui::MutableAppContext) {
4349        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\nde\nfgh", cx));
4350        let settings = EditorSettings::test(&cx);
4351        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4352        view.update(cx, |view, cx| {
4353            view.select_all(&SelectAll, cx);
4354            assert_eq!(
4355                view.selection_ranges(cx),
4356                &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
4357            );
4358        });
4359    }
4360
4361    #[gpui::test]
4362    fn test_select_line(cx: &mut gpui::MutableAppContext) {
4363        let settings = EditorSettings::test(&cx);
4364        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(6, 5), cx));
4365        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4366        view.update(cx, |view, cx| {
4367            view.select_display_ranges(
4368                &[
4369                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4370                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4371                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4372                    DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
4373                ],
4374                cx,
4375            )
4376            .unwrap();
4377            view.select_line(&SelectLine, cx);
4378            assert_eq!(
4379                view.selection_ranges(cx),
4380                vec![
4381                    DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
4382                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
4383                ]
4384            );
4385        });
4386
4387        view.update(cx, |view, cx| {
4388            view.select_line(&SelectLine, cx);
4389            assert_eq!(
4390                view.selection_ranges(cx),
4391                vec![
4392                    DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
4393                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
4394                ]
4395            );
4396        });
4397
4398        view.update(cx, |view, cx| {
4399            view.select_line(&SelectLine, cx);
4400            assert_eq!(
4401                view.selection_ranges(cx),
4402                vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
4403            );
4404        });
4405    }
4406
4407    #[gpui::test]
4408    fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
4409        let settings = EditorSettings::test(&cx);
4410        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(9, 5), cx));
4411        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4412        view.update(cx, |view, cx| {
4413            view.fold_ranges(
4414                vec![
4415                    Point::new(0, 2)..Point::new(1, 2),
4416                    Point::new(2, 3)..Point::new(4, 1),
4417                    Point::new(7, 0)..Point::new(8, 4),
4418                ],
4419                cx,
4420            );
4421            view.select_display_ranges(
4422                &[
4423                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4424                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4425                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4426                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
4427                ],
4428                cx,
4429            )
4430            .unwrap();
4431            assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
4432        });
4433
4434        view.update(cx, |view, cx| {
4435            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
4436            assert_eq!(
4437                view.display_text(cx),
4438                "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
4439            );
4440            assert_eq!(
4441                view.selection_ranges(cx),
4442                [
4443                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4444                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4445                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
4446                    DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
4447                ]
4448            );
4449        });
4450
4451        view.update(cx, |view, cx| {
4452            view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx)
4453                .unwrap();
4454            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
4455            assert_eq!(
4456                view.display_text(cx),
4457                "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
4458            );
4459            assert_eq!(
4460                view.selection_ranges(cx),
4461                [
4462                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4463                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4464                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
4465                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
4466                    DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
4467                    DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
4468                    DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
4469                    DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
4470                ]
4471            );
4472        });
4473    }
4474
4475    #[gpui::test]
4476    fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
4477        let settings = EditorSettings::test(&cx);
4478        let buffer = cx.add_model(|cx| Buffer::new(0, "abc\ndefghi\n\njk\nlmno\n", cx));
4479        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4480
4481        view.update(cx, |view, cx| {
4482            view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx)
4483                .unwrap();
4484        });
4485        view.update(cx, |view, cx| {
4486            view.add_selection_above(&AddSelectionAbove, cx);
4487            assert_eq!(
4488                view.selection_ranges(cx),
4489                vec![
4490                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4491                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
4492                ]
4493            );
4494        });
4495
4496        view.update(cx, |view, cx| {
4497            view.add_selection_above(&AddSelectionAbove, cx);
4498            assert_eq!(
4499                view.selection_ranges(cx),
4500                vec![
4501                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4502                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
4503                ]
4504            );
4505        });
4506
4507        view.update(cx, |view, cx| {
4508            view.add_selection_below(&AddSelectionBelow, cx);
4509            assert_eq!(
4510                view.selection_ranges(cx),
4511                vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
4512            );
4513        });
4514
4515        view.update(cx, |view, cx| {
4516            view.add_selection_below(&AddSelectionBelow, cx);
4517            assert_eq!(
4518                view.selection_ranges(cx),
4519                vec![
4520                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
4521                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
4522                ]
4523            );
4524        });
4525
4526        view.update(cx, |view, cx| {
4527            view.add_selection_below(&AddSelectionBelow, cx);
4528            assert_eq!(
4529                view.selection_ranges(cx),
4530                vec![
4531                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
4532                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
4533                ]
4534            );
4535        });
4536
4537        view.update(cx, |view, cx| {
4538            view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx)
4539                .unwrap();
4540        });
4541        view.update(cx, |view, cx| {
4542            view.add_selection_below(&AddSelectionBelow, cx);
4543            assert_eq!(
4544                view.selection_ranges(cx),
4545                vec![
4546                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4547                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
4548                ]
4549            );
4550        });
4551
4552        view.update(cx, |view, cx| {
4553            view.add_selection_below(&AddSelectionBelow, cx);
4554            assert_eq!(
4555                view.selection_ranges(cx),
4556                vec![
4557                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
4558                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
4559                ]
4560            );
4561        });
4562
4563        view.update(cx, |view, cx| {
4564            view.add_selection_above(&AddSelectionAbove, cx);
4565            assert_eq!(
4566                view.selection_ranges(cx),
4567                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
4568            );
4569        });
4570
4571        view.update(cx, |view, cx| {
4572            view.add_selection_above(&AddSelectionAbove, cx);
4573            assert_eq!(
4574                view.selection_ranges(cx),
4575                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
4576            );
4577        });
4578
4579        view.update(cx, |view, cx| {
4580            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx)
4581                .unwrap();
4582            view.add_selection_below(&AddSelectionBelow, cx);
4583            assert_eq!(
4584                view.selection_ranges(cx),
4585                vec![
4586                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4587                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
4588                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
4589                ]
4590            );
4591        });
4592
4593        view.update(cx, |view, cx| {
4594            view.add_selection_below(&AddSelectionBelow, cx);
4595            assert_eq!(
4596                view.selection_ranges(cx),
4597                vec![
4598                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4599                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
4600                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
4601                    DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
4602                ]
4603            );
4604        });
4605
4606        view.update(cx, |view, cx| {
4607            view.add_selection_above(&AddSelectionAbove, cx);
4608            assert_eq!(
4609                view.selection_ranges(cx),
4610                vec![
4611                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4612                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
4613                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
4614                ]
4615            );
4616        });
4617
4618        view.update(cx, |view, cx| {
4619            view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx)
4620                .unwrap();
4621        });
4622        view.update(cx, |view, cx| {
4623            view.add_selection_above(&AddSelectionAbove, cx);
4624            assert_eq!(
4625                view.selection_ranges(cx),
4626                vec![
4627                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
4628                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
4629                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
4630                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
4631                ]
4632            );
4633        });
4634
4635        view.update(cx, |view, cx| {
4636            view.add_selection_below(&AddSelectionBelow, cx);
4637            assert_eq!(
4638                view.selection_ranges(cx),
4639                vec![
4640                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
4641                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
4642                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
4643                ]
4644            );
4645        });
4646    }
4647
4648    #[gpui::test]
4649    async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
4650        let settings = cx.read(EditorSettings::test);
4651        let language = Some(Arc::new(Language::new(
4652            LanguageConfig::default(),
4653            tree_sitter_rust::language(),
4654        )));
4655
4656        let text = r#"
4657            use mod1::mod2::{mod3, mod4};
4658
4659            fn fn_1(param1: bool, param2: &str) {
4660                let var1 = "text";
4661            }
4662        "#
4663        .unindent();
4664
4665        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
4666        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
4667        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing())
4668            .await;
4669
4670        view.update(&mut cx, |view, cx| {
4671            view.select_display_ranges(
4672                &[
4673                    DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
4674                    DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
4675                    DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
4676                ],
4677                cx,
4678            )
4679            .unwrap();
4680            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4681        });
4682        assert_eq!(
4683            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4684            &[
4685                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
4686                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
4687                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
4688            ]
4689        );
4690
4691        view.update(&mut cx, |view, cx| {
4692            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4693        });
4694        assert_eq!(
4695            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4696            &[
4697                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
4698                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
4699            ]
4700        );
4701
4702        view.update(&mut cx, |view, cx| {
4703            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4704        });
4705        assert_eq!(
4706            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4707            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
4708        );
4709
4710        // Trying to expand the selected syntax node one more time has no effect.
4711        view.update(&mut cx, |view, cx| {
4712            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4713        });
4714        assert_eq!(
4715            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4716            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
4717        );
4718
4719        view.update(&mut cx, |view, cx| {
4720            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
4721        });
4722        assert_eq!(
4723            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4724            &[
4725                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
4726                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
4727            ]
4728        );
4729
4730        view.update(&mut cx, |view, cx| {
4731            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
4732        });
4733        assert_eq!(
4734            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4735            &[
4736                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
4737                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
4738                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
4739            ]
4740        );
4741
4742        view.update(&mut cx, |view, cx| {
4743            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
4744        });
4745        assert_eq!(
4746            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4747            &[
4748                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
4749                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
4750                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
4751            ]
4752        );
4753
4754        // Trying to shrink the selected syntax node one more time has no effect.
4755        view.update(&mut cx, |view, cx| {
4756            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
4757        });
4758        assert_eq!(
4759            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4760            &[
4761                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
4762                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
4763                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
4764            ]
4765        );
4766
4767        // Ensure that we keep expanding the selection if the larger selection starts or ends within
4768        // a fold.
4769        view.update(&mut cx, |view, cx| {
4770            view.fold_ranges(
4771                vec![
4772                    Point::new(0, 21)..Point::new(0, 24),
4773                    Point::new(3, 20)..Point::new(3, 22),
4774                ],
4775                cx,
4776            );
4777            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
4778        });
4779        assert_eq!(
4780            view.update(&mut cx, |view, cx| view.selection_ranges(cx)),
4781            &[
4782                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
4783                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
4784                DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
4785            ]
4786        );
4787    }
4788
4789    #[gpui::test]
4790    async fn test_autoclose_pairs(mut cx: gpui::TestAppContext) {
4791        let settings = cx.read(EditorSettings::test);
4792        let language = Some(Arc::new(Language::new(
4793            LanguageConfig {
4794                brackets: vec![
4795                    BracketPair {
4796                        start: "{".to_string(),
4797                        end: "}".to_string(),
4798                        close: true,
4799                        newline: true,
4800                    },
4801                    BracketPair {
4802                        start: "/*".to_string(),
4803                        end: " */".to_string(),
4804                        close: true,
4805                        newline: true,
4806                    },
4807                ],
4808                ..Default::default()
4809            },
4810            tree_sitter_rust::language(),
4811        )));
4812
4813        let text = r#"
4814            a
4815
4816            /
4817
4818        "#
4819        .unindent();
4820
4821        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
4822        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
4823        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing())
4824            .await;
4825
4826        view.update(&mut cx, |view, cx| {
4827            view.select_display_ranges(
4828                &[
4829                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
4830                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4831                ],
4832                cx,
4833            )
4834            .unwrap();
4835            view.handle_input(&Input("{".to_string()), cx);
4836            view.handle_input(&Input("{".to_string()), cx);
4837            view.handle_input(&Input("{".to_string()), cx);
4838            assert_eq!(
4839                view.text(cx),
4840                "
4841                {{{}}}
4842                {{{}}}
4843                /
4844
4845                "
4846                .unindent()
4847            );
4848
4849            view.move_right(&MoveRight, cx);
4850            view.handle_input(&Input("}".to_string()), cx);
4851            view.handle_input(&Input("}".to_string()), cx);
4852            view.handle_input(&Input("}".to_string()), cx);
4853            assert_eq!(
4854                view.text(cx),
4855                "
4856                {{{}}}}
4857                {{{}}}}
4858                /
4859
4860                "
4861                .unindent()
4862            );
4863
4864            view.undo(&Undo, cx);
4865            view.handle_input(&Input("/".to_string()), cx);
4866            view.handle_input(&Input("*".to_string()), cx);
4867            assert_eq!(
4868                view.text(cx),
4869                "
4870                /* */
4871                /* */
4872                /
4873
4874                "
4875                .unindent()
4876            );
4877
4878            view.undo(&Undo, cx);
4879            view.select_display_ranges(
4880                &[
4881                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
4882                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
4883                ],
4884                cx,
4885            )
4886            .unwrap();
4887            view.handle_input(&Input("*".to_string()), cx);
4888            assert_eq!(
4889                view.text(cx),
4890                "
4891                a
4892
4893                /*
4894                *
4895                "
4896                .unindent()
4897            );
4898        });
4899    }
4900
4901    #[gpui::test]
4902    async fn test_extra_newline_insertion(mut cx: gpui::TestAppContext) {
4903        let settings = cx.read(EditorSettings::test);
4904        let language = Some(Arc::new(Language::new(
4905            LanguageConfig {
4906                brackets: vec![
4907                    BracketPair {
4908                        start: "{".to_string(),
4909                        end: "}".to_string(),
4910                        close: true,
4911                        newline: true,
4912                    },
4913                    BracketPair {
4914                        start: "/* ".to_string(),
4915                        end: " */".to_string(),
4916                        close: true,
4917                        newline: true,
4918                    },
4919                ],
4920                ..Default::default()
4921            },
4922            tree_sitter_rust::language(),
4923        )));
4924
4925        let text = concat!(
4926            "{   }\n",     // Suppress rustfmt
4927            "  x\n",       //
4928            "  /*   */\n", //
4929            "x\n",         //
4930            "{{} }\n",     //
4931        );
4932
4933        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, None, cx));
4934        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
4935        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing())
4936            .await;
4937
4938        view.update(&mut cx, |view, cx| {
4939            view.select_display_ranges(
4940                &[
4941                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
4942                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
4943                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
4944                ],
4945                cx,
4946            )
4947            .unwrap();
4948            view.newline(&Newline, cx);
4949
4950            assert_eq!(
4951                view.buffer().read(cx).text(),
4952                concat!(
4953                    "{ \n",    // Suppress rustfmt
4954                    "\n",      //
4955                    "}\n",     //
4956                    "  x\n",   //
4957                    "  /* \n", //
4958                    "  \n",    //
4959                    "  */\n",  //
4960                    "x\n",     //
4961                    "{{} \n",  //
4962                    "}\n",     //
4963                )
4964            );
4965        });
4966    }
4967
4968    impl Editor {
4969        fn selection_ranges(&self, cx: &mut MutableAppContext) -> Vec<Range<DisplayPoint>> {
4970            self.selections_in_range(
4971                self.selection_set_id,
4972                DisplayPoint::zero()..self.max_point(cx),
4973                cx,
4974            )
4975            .collect::<Vec<_>>()
4976        }
4977    }
4978
4979    fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
4980        let point = DisplayPoint::new(row as u32, column as u32);
4981        point..point
4982    }
4983
4984    fn build_editor(
4985        buffer: ModelHandle<Buffer>,
4986        settings: EditorSettings,
4987        cx: &mut ViewContext<Editor>,
4988    ) -> Editor {
4989        Editor::for_buffer(buffer, move |_| settings.clone(), cx)
4990    }
4991}
4992
4993trait RangeExt<T> {
4994    fn sorted(&self) -> Range<T>;
4995    fn to_inclusive(&self) -> RangeInclusive<T>;
4996}
4997
4998impl<T: Ord + Clone> RangeExt<T> for Range<T> {
4999    fn sorted(&self) -> Self {
5000        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
5001    }
5002
5003    fn to_inclusive(&self) -> RangeInclusive<T> {
5004        self.start.clone()..=self.end.clone()
5005    }
5006}