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