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