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