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