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