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