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