editor.rs

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