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