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.set_active_selections(&self.selections, cx)
3956        });
3957    }
3958
3959    fn on_blur(&mut self, cx: &mut ViewContext<Self>) {
3960        self.focused = false;
3961        self.show_local_cursors = false;
3962        self.buffer
3963            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
3964        cx.emit(Event::Blurred);
3965        cx.notify();
3966    }
3967
3968    fn keymap_context(&self, _: &AppContext) -> gpui::keymap::Context {
3969        let mut cx = Self::default_keymap_context();
3970        let mode = match self.mode {
3971            EditorMode::SingleLine => "single_line",
3972            EditorMode::AutoHeight { .. } => "auto_height",
3973            EditorMode::Full => "full",
3974        };
3975        cx.map.insert("mode".into(), mode.into());
3976        cx
3977    }
3978}
3979
3980impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
3981    fn point_range(&self, buffer: &MultiBufferSnapshot) -> Range<Point> {
3982        let start = self.start.to_point(buffer);
3983        let end = self.end.to_point(buffer);
3984        if self.reversed {
3985            end..start
3986        } else {
3987            start..end
3988        }
3989    }
3990
3991    fn offset_range(&self, buffer: &MultiBufferSnapshot) -> Range<usize> {
3992        let start = self.start.to_offset(buffer);
3993        let end = self.end.to_offset(buffer);
3994        if self.reversed {
3995            end..start
3996        } else {
3997            start..end
3998        }
3999    }
4000
4001    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
4002        let start = self
4003            .start
4004            .to_point(&map.buffer_snapshot)
4005            .to_display_point(map);
4006        let end = self
4007            .end
4008            .to_point(&map.buffer_snapshot)
4009            .to_display_point(map);
4010        if self.reversed {
4011            end..start
4012        } else {
4013            start..end
4014        }
4015    }
4016
4017    fn spanned_rows(
4018        &self,
4019        include_end_if_at_line_start: bool,
4020        map: &DisplaySnapshot,
4021    ) -> Range<u32> {
4022        let start = self.start.to_point(&map.buffer_snapshot);
4023        let mut end = self.end.to_point(&map.buffer_snapshot);
4024        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
4025            end.row -= 1;
4026        }
4027
4028        let buffer_start = map.prev_line_boundary(start).0;
4029        let buffer_end = map.next_line_boundary(end).0;
4030        buffer_start.row..buffer_end.row + 1
4031    }
4032}
4033
4034pub fn diagnostic_block_renderer(
4035    diagnostic: Diagnostic,
4036    is_valid: bool,
4037    build_settings: BuildSettings,
4038) -> RenderBlock {
4039    let mut highlighted_lines = Vec::new();
4040    for line in diagnostic.message.lines() {
4041        highlighted_lines.push(highlight_diagnostic_message(line));
4042    }
4043
4044    Arc::new(move |cx: &BlockContext| {
4045        let settings = build_settings(cx);
4046        let style = diagnostic_style(diagnostic.severity, is_valid, &settings.style);
4047        let font_size = (style.text_scale_factor * settings.style.text.font_size).round();
4048        Flex::column()
4049            .with_children(highlighted_lines.iter().map(|(line, highlights)| {
4050                Label::new(
4051                    line.clone(),
4052                    style.message.clone().with_font_size(font_size),
4053                )
4054                .with_highlights(highlights.clone())
4055                .contained()
4056                .with_margin_left(cx.anchor_x)
4057                .boxed()
4058            }))
4059            .aligned()
4060            .left()
4061            .boxed()
4062    })
4063}
4064
4065pub fn highlight_diagnostic_message(message: &str) -> (String, Vec<usize>) {
4066    let mut message_without_backticks = String::new();
4067    let mut prev_offset = 0;
4068    let mut inside_block = false;
4069    let mut highlights = Vec::new();
4070    for (match_ix, (offset, _)) in message
4071        .match_indices('`')
4072        .chain([(message.len(), "")])
4073        .enumerate()
4074    {
4075        message_without_backticks.push_str(&message[prev_offset..offset]);
4076        if inside_block {
4077            highlights.extend(prev_offset - match_ix..offset - match_ix);
4078        }
4079
4080        inside_block = !inside_block;
4081        prev_offset = offset + 1;
4082    }
4083
4084    (message_without_backticks, highlights)
4085}
4086
4087pub fn diagnostic_style(
4088    severity: DiagnosticSeverity,
4089    valid: bool,
4090    style: &EditorStyle,
4091) -> DiagnosticStyle {
4092    match (severity, valid) {
4093        (DiagnosticSeverity::ERROR, true) => style.error_diagnostic.clone(),
4094        (DiagnosticSeverity::ERROR, false) => style.invalid_error_diagnostic.clone(),
4095        (DiagnosticSeverity::WARNING, true) => style.warning_diagnostic.clone(),
4096        (DiagnosticSeverity::WARNING, false) => style.invalid_warning_diagnostic.clone(),
4097        (DiagnosticSeverity::INFORMATION, true) => style.information_diagnostic.clone(),
4098        (DiagnosticSeverity::INFORMATION, false) => style.invalid_information_diagnostic.clone(),
4099        (DiagnosticSeverity::HINT, true) => style.hint_diagnostic.clone(),
4100        (DiagnosticSeverity::HINT, false) => style.invalid_hint_diagnostic.clone(),
4101        _ => DiagnosticStyle {
4102            message: style.text.clone().into(),
4103            header: Default::default(),
4104            text_scale_factor: 1.,
4105        },
4106    }
4107}
4108
4109pub fn settings_builder(
4110    buffer: WeakModelHandle<MultiBuffer>,
4111    settings: watch::Receiver<workspace::Settings>,
4112) -> BuildSettings {
4113    Arc::new(move |cx| {
4114        let settings = settings.borrow();
4115        let font_cache = cx.font_cache();
4116        let font_family_id = settings.buffer_font_family;
4117        let font_family_name = cx.font_cache().family_name(font_family_id).unwrap();
4118        let font_properties = Default::default();
4119        let font_id = font_cache
4120            .select_font(font_family_id, &font_properties)
4121            .unwrap();
4122        let font_size = settings.buffer_font_size;
4123
4124        let mut theme = settings.theme.editor.clone();
4125        theme.text = TextStyle {
4126            color: theme.text.color,
4127            font_family_name,
4128            font_family_id,
4129            font_id,
4130            font_size,
4131            font_properties,
4132            underline: None,
4133        };
4134        let language = buffer.upgrade(cx).and_then(|buf| buf.read(cx).language(cx));
4135        let soft_wrap = match settings.soft_wrap(language) {
4136            workspace::settings::SoftWrap::None => SoftWrap::None,
4137            workspace::settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
4138            workspace::settings::SoftWrap::PreferredLineLength => {
4139                SoftWrap::Column(settings.preferred_line_length(language).saturating_sub(1))
4140            }
4141        };
4142
4143        EditorSettings {
4144            tab_size: settings.tab_size,
4145            soft_wrap,
4146            style: theme,
4147        }
4148    })
4149}
4150
4151#[cfg(test)]
4152mod tests {
4153    use super::*;
4154    use language::LanguageConfig;
4155    use std::{cell::RefCell, rc::Rc, time::Instant};
4156    use text::Point;
4157    use unindent::Unindent;
4158    use util::test::sample_text;
4159
4160    #[gpui::test]
4161    fn test_undo_redo_with_selection_restoration(cx: &mut MutableAppContext) {
4162        let mut now = Instant::now();
4163        let buffer = cx.add_model(|cx| language::Buffer::new(0, "123456", cx));
4164        let group_interval = buffer.read(cx).transaction_group_interval();
4165        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
4166        let settings = EditorSettings::test(cx);
4167        let (_, editor) = cx.add_window(Default::default(), |cx| {
4168            build_editor(buffer.clone(), settings, cx)
4169        });
4170
4171        editor.update(cx, |editor, cx| {
4172            editor.start_transaction_at(now, cx);
4173            editor.select_ranges([2..4], None, cx);
4174            editor.insert("cd", cx);
4175            editor.end_transaction_at(now, cx);
4176            assert_eq!(editor.text(cx), "12cd56");
4177            assert_eq!(editor.selected_ranges(cx), vec![4..4]);
4178
4179            editor.start_transaction_at(now, cx);
4180            editor.select_ranges([4..5], None, cx);
4181            editor.insert("e", cx);
4182            editor.end_transaction_at(now, cx);
4183            assert_eq!(editor.text(cx), "12cde6");
4184            assert_eq!(editor.selected_ranges(cx), vec![5..5]);
4185
4186            now += group_interval + Duration::from_millis(1);
4187            editor.select_ranges([2..2], None, cx);
4188
4189            // Simulate an edit in another editor
4190            buffer.update(cx, |buffer, cx| {
4191                buffer.start_transaction_at(now, cx);
4192                buffer.edit([0..1], "a", cx);
4193                buffer.edit([1..1], "b", cx);
4194                buffer.end_transaction_at(now, cx);
4195            });
4196
4197            assert_eq!(editor.text(cx), "ab2cde6");
4198            assert_eq!(editor.selected_ranges(cx), vec![3..3]);
4199
4200            // Last transaction happened past the group interval in a different editor.
4201            // Undo it individually and don't restore selections.
4202            editor.undo(&Undo, cx);
4203            assert_eq!(editor.text(cx), "12cde6");
4204            assert_eq!(editor.selected_ranges(cx), vec![2..2]);
4205
4206            // First two transactions happened within the group interval in this editor.
4207            // Undo them together and restore selections.
4208            editor.undo(&Undo, cx);
4209            editor.undo(&Undo, cx); // Undo stack is empty here, so this is a no-op.
4210            assert_eq!(editor.text(cx), "123456");
4211            assert_eq!(editor.selected_ranges(cx), vec![0..0]);
4212
4213            // Redo the first two transactions together.
4214            editor.redo(&Redo, cx);
4215            assert_eq!(editor.text(cx), "12cde6");
4216            assert_eq!(editor.selected_ranges(cx), vec![5..5]);
4217
4218            // Redo the last transaction on its own.
4219            editor.redo(&Redo, cx);
4220            assert_eq!(editor.text(cx), "ab2cde6");
4221            assert_eq!(editor.selected_ranges(cx), vec![6..6]);
4222
4223            // Test empty transactions.
4224            editor.start_transaction_at(now, cx);
4225            editor.end_transaction_at(now, cx);
4226            editor.undo(&Undo, cx);
4227            assert_eq!(editor.text(cx), "12cde6");
4228        });
4229    }
4230
4231    #[gpui::test]
4232    fn test_selection_with_mouse(cx: &mut gpui::MutableAppContext) {
4233        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
4234        let settings = EditorSettings::test(cx);
4235        let (_, editor) =
4236            cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4237
4238        editor.update(cx, |view, cx| {
4239            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
4240        });
4241
4242        assert_eq!(
4243            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4244            [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
4245        );
4246
4247        editor.update(cx, |view, cx| {
4248            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
4249        });
4250
4251        assert_eq!(
4252            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4253            [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
4254        );
4255
4256        editor.update(cx, |view, cx| {
4257            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
4258        });
4259
4260        assert_eq!(
4261            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4262            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
4263        );
4264
4265        editor.update(cx, |view, cx| {
4266            view.end_selection(cx);
4267            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
4268        });
4269
4270        assert_eq!(
4271            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4272            [DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1)]
4273        );
4274
4275        editor.update(cx, |view, cx| {
4276            view.begin_selection(DisplayPoint::new(3, 3), true, 1, cx);
4277            view.update_selection(DisplayPoint::new(0, 0), 0, Vector2F::zero(), cx);
4278        });
4279
4280        assert_eq!(
4281            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4282            [
4283                DisplayPoint::new(2, 2)..DisplayPoint::new(1, 1),
4284                DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)
4285            ]
4286        );
4287
4288        editor.update(cx, |view, cx| {
4289            view.end_selection(cx);
4290        });
4291
4292        assert_eq!(
4293            editor.update(cx, |view, cx| view.selected_display_ranges(cx)),
4294            [DisplayPoint::new(3, 3)..DisplayPoint::new(0, 0)]
4295        );
4296    }
4297
4298    #[gpui::test]
4299    fn test_canceling_pending_selection(cx: &mut gpui::MutableAppContext) {
4300        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
4301        let settings = EditorSettings::test(cx);
4302        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4303
4304        view.update(cx, |view, cx| {
4305            view.begin_selection(DisplayPoint::new(2, 2), false, 1, cx);
4306            assert_eq!(
4307                view.selected_display_ranges(cx),
4308                [DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2)]
4309            );
4310        });
4311
4312        view.update(cx, |view, cx| {
4313            view.update_selection(DisplayPoint::new(3, 3), 0, Vector2F::zero(), cx);
4314            assert_eq!(
4315                view.selected_display_ranges(cx),
4316                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
4317            );
4318        });
4319
4320        view.update(cx, |view, cx| {
4321            view.cancel(&Cancel, cx);
4322            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
4323            assert_eq!(
4324                view.selected_display_ranges(cx),
4325                [DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3)]
4326            );
4327        });
4328    }
4329
4330    #[gpui::test]
4331    fn test_navigation_history(cx: &mut gpui::MutableAppContext) {
4332        cx.add_window(Default::default(), |cx| {
4333            use workspace::ItemView;
4334            let nav_history = Rc::new(RefCell::new(workspace::NavHistory::default()));
4335            let settings = EditorSettings::test(&cx);
4336            let buffer = MultiBuffer::build_simple(&sample_text(30, 5, 'a'), cx);
4337            let mut editor = build_editor(buffer.clone(), settings, cx);
4338            editor.nav_history = Some(ItemNavHistory::new(nav_history.clone(), &cx.handle()));
4339
4340            // Move the cursor a small distance.
4341            // Nothing is added to the navigation history.
4342            editor.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
4343            editor.select_display_ranges(&[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)], cx);
4344            assert!(nav_history.borrow_mut().pop_backward().is_none());
4345
4346            // Move the cursor a large distance.
4347            // The history can jump back to the previous position.
4348            editor.select_display_ranges(&[DisplayPoint::new(13, 0)..DisplayPoint::new(13, 3)], cx);
4349            let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
4350            editor.navigate(nav_entry.data.unwrap(), cx);
4351            assert_eq!(nav_entry.item_view.id(), cx.view_id());
4352            assert_eq!(
4353                editor.selected_display_ranges(cx),
4354                &[DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0)]
4355            );
4356
4357            // Move the cursor a small distance via the mouse.
4358            // Nothing is added to the navigation history.
4359            editor.begin_selection(DisplayPoint::new(5, 0), false, 1, cx);
4360            editor.end_selection(cx);
4361            assert_eq!(
4362                editor.selected_display_ranges(cx),
4363                &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
4364            );
4365            assert!(nav_history.borrow_mut().pop_backward().is_none());
4366
4367            // Move the cursor a large distance via the mouse.
4368            // The history can jump back to the previous position.
4369            editor.begin_selection(DisplayPoint::new(15, 0), false, 1, cx);
4370            editor.end_selection(cx);
4371            assert_eq!(
4372                editor.selected_display_ranges(cx),
4373                &[DisplayPoint::new(15, 0)..DisplayPoint::new(15, 0)]
4374            );
4375            let nav_entry = nav_history.borrow_mut().pop_backward().unwrap();
4376            editor.navigate(nav_entry.data.unwrap(), cx);
4377            assert_eq!(nav_entry.item_view.id(), cx.view_id());
4378            assert_eq!(
4379                editor.selected_display_ranges(cx),
4380                &[DisplayPoint::new(5, 0)..DisplayPoint::new(5, 0)]
4381            );
4382
4383            editor
4384        });
4385    }
4386
4387    #[gpui::test]
4388    fn test_cancel(cx: &mut gpui::MutableAppContext) {
4389        let buffer = MultiBuffer::build_simple("aaaaaa\nbbbbbb\ncccccc\ndddddd\n", cx);
4390        let settings = EditorSettings::test(cx);
4391        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4392
4393        view.update(cx, |view, cx| {
4394            view.begin_selection(DisplayPoint::new(3, 4), false, 1, cx);
4395            view.update_selection(DisplayPoint::new(1, 1), 0, Vector2F::zero(), cx);
4396            view.end_selection(cx);
4397
4398            view.begin_selection(DisplayPoint::new(0, 1), true, 1, cx);
4399            view.update_selection(DisplayPoint::new(0, 3), 0, Vector2F::zero(), cx);
4400            view.end_selection(cx);
4401            assert_eq!(
4402                view.selected_display_ranges(cx),
4403                [
4404                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
4405                    DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1),
4406                ]
4407            );
4408        });
4409
4410        view.update(cx, |view, cx| {
4411            view.cancel(&Cancel, cx);
4412            assert_eq!(
4413                view.selected_display_ranges(cx),
4414                [DisplayPoint::new(3, 4)..DisplayPoint::new(1, 1)]
4415            );
4416        });
4417
4418        view.update(cx, |view, cx| {
4419            view.cancel(&Cancel, cx);
4420            assert_eq!(
4421                view.selected_display_ranges(cx),
4422                [DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1)]
4423            );
4424        });
4425    }
4426
4427    #[gpui::test]
4428    fn test_fold(cx: &mut gpui::MutableAppContext) {
4429        let buffer = MultiBuffer::build_simple(
4430            &"
4431                impl Foo {
4432                    // Hello!
4433
4434                    fn a() {
4435                        1
4436                    }
4437
4438                    fn b() {
4439                        2
4440                    }
4441
4442                    fn c() {
4443                        3
4444                    }
4445                }
4446            "
4447            .unindent(),
4448            cx,
4449        );
4450        let settings = EditorSettings::test(&cx);
4451        let (_, view) = cx.add_window(Default::default(), |cx| {
4452            build_editor(buffer.clone(), settings, cx)
4453        });
4454
4455        view.update(cx, |view, cx| {
4456            view.select_display_ranges(&[DisplayPoint::new(8, 0)..DisplayPoint::new(12, 0)], cx);
4457            view.fold(&Fold, cx);
4458            assert_eq!(
4459                view.display_text(cx),
4460                "
4461                    impl Foo {
4462                        // Hello!
4463
4464                        fn a() {
4465                            1
4466                        }
4467
4468                        fn b() {…
4469                        }
4470
4471                        fn c() {…
4472                        }
4473                    }
4474                "
4475                .unindent(),
4476            );
4477
4478            view.fold(&Fold, cx);
4479            assert_eq!(
4480                view.display_text(cx),
4481                "
4482                    impl Foo {…
4483                    }
4484                "
4485                .unindent(),
4486            );
4487
4488            view.unfold(&Unfold, cx);
4489            assert_eq!(
4490                view.display_text(cx),
4491                "
4492                    impl Foo {
4493                        // Hello!
4494
4495                        fn a() {
4496                            1
4497                        }
4498
4499                        fn b() {…
4500                        }
4501
4502                        fn c() {…
4503                        }
4504                    }
4505                "
4506                .unindent(),
4507            );
4508
4509            view.unfold(&Unfold, cx);
4510            assert_eq!(view.display_text(cx), buffer.read(cx).read(cx).text());
4511        });
4512    }
4513
4514    #[gpui::test]
4515    fn test_move_cursor(cx: &mut gpui::MutableAppContext) {
4516        let buffer = MultiBuffer::build_simple(&sample_text(6, 6, 'a'), cx);
4517        let settings = EditorSettings::test(&cx);
4518        let (_, view) = cx.add_window(Default::default(), |cx| {
4519            build_editor(buffer.clone(), settings, cx)
4520        });
4521
4522        buffer.update(cx, |buffer, cx| {
4523            buffer.edit(
4524                vec![
4525                    Point::new(1, 0)..Point::new(1, 0),
4526                    Point::new(1, 1)..Point::new(1, 1),
4527                ],
4528                "\t",
4529                cx,
4530            );
4531        });
4532
4533        view.update(cx, |view, cx| {
4534            assert_eq!(
4535                view.selected_display_ranges(cx),
4536                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4537            );
4538
4539            view.move_down(&MoveDown, cx);
4540            assert_eq!(
4541                view.selected_display_ranges(cx),
4542                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
4543            );
4544
4545            view.move_right(&MoveRight, cx);
4546            assert_eq!(
4547                view.selected_display_ranges(cx),
4548                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
4549            );
4550
4551            view.move_left(&MoveLeft, cx);
4552            assert_eq!(
4553                view.selected_display_ranges(cx),
4554                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
4555            );
4556
4557            view.move_up(&MoveUp, cx);
4558            assert_eq!(
4559                view.selected_display_ranges(cx),
4560                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4561            );
4562
4563            view.move_to_end(&MoveToEnd, cx);
4564            assert_eq!(
4565                view.selected_display_ranges(cx),
4566                &[DisplayPoint::new(5, 6)..DisplayPoint::new(5, 6)]
4567            );
4568
4569            view.move_to_beginning(&MoveToBeginning, cx);
4570            assert_eq!(
4571                view.selected_display_ranges(cx),
4572                &[DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0)]
4573            );
4574
4575            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2)], cx);
4576            view.select_to_beginning(&SelectToBeginning, cx);
4577            assert_eq!(
4578                view.selected_display_ranges(cx),
4579                &[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 0)]
4580            );
4581
4582            view.select_to_end(&SelectToEnd, cx);
4583            assert_eq!(
4584                view.selected_display_ranges(cx),
4585                &[DisplayPoint::new(0, 1)..DisplayPoint::new(5, 6)]
4586            );
4587        });
4588    }
4589
4590    #[gpui::test]
4591    fn test_move_cursor_multibyte(cx: &mut gpui::MutableAppContext) {
4592        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcde\nαβγδε\n", cx);
4593        let settings = EditorSettings::test(&cx);
4594        let (_, view) = cx.add_window(Default::default(), |cx| {
4595            build_editor(buffer.clone(), settings, cx)
4596        });
4597
4598        assert_eq!('ⓐ'.len_utf8(), 3);
4599        assert_eq!('α'.len_utf8(), 2);
4600
4601        view.update(cx, |view, cx| {
4602            view.fold_ranges(
4603                vec![
4604                    Point::new(0, 6)..Point::new(0, 12),
4605                    Point::new(1, 2)..Point::new(1, 4),
4606                    Point::new(2, 4)..Point::new(2, 8),
4607                ],
4608                cx,
4609            );
4610            assert_eq!(view.display_text(cx), "ⓐⓑ…ⓔ\nab…e\nαβ…ε\n");
4611
4612            view.move_right(&MoveRight, cx);
4613            assert_eq!(
4614                view.selected_display_ranges(cx),
4615                &[empty_range(0, "".len())]
4616            );
4617            view.move_right(&MoveRight, cx);
4618            assert_eq!(
4619                view.selected_display_ranges(cx),
4620                &[empty_range(0, "ⓐⓑ".len())]
4621            );
4622            view.move_right(&MoveRight, cx);
4623            assert_eq!(
4624                view.selected_display_ranges(cx),
4625                &[empty_range(0, "ⓐⓑ…".len())]
4626            );
4627
4628            view.move_down(&MoveDown, cx);
4629            assert_eq!(
4630                view.selected_display_ranges(cx),
4631                &[empty_range(1, "ab…".len())]
4632            );
4633            view.move_left(&MoveLeft, cx);
4634            assert_eq!(
4635                view.selected_display_ranges(cx),
4636                &[empty_range(1, "ab".len())]
4637            );
4638            view.move_left(&MoveLeft, cx);
4639            assert_eq!(
4640                view.selected_display_ranges(cx),
4641                &[empty_range(1, "a".len())]
4642            );
4643
4644            view.move_down(&MoveDown, cx);
4645            assert_eq!(
4646                view.selected_display_ranges(cx),
4647                &[empty_range(2, "α".len())]
4648            );
4649            view.move_right(&MoveRight, cx);
4650            assert_eq!(
4651                view.selected_display_ranges(cx),
4652                &[empty_range(2, "αβ".len())]
4653            );
4654            view.move_right(&MoveRight, cx);
4655            assert_eq!(
4656                view.selected_display_ranges(cx),
4657                &[empty_range(2, "αβ…".len())]
4658            );
4659            view.move_right(&MoveRight, cx);
4660            assert_eq!(
4661                view.selected_display_ranges(cx),
4662                &[empty_range(2, "αβ…ε".len())]
4663            );
4664
4665            view.move_up(&MoveUp, cx);
4666            assert_eq!(
4667                view.selected_display_ranges(cx),
4668                &[empty_range(1, "ab…e".len())]
4669            );
4670            view.move_up(&MoveUp, cx);
4671            assert_eq!(
4672                view.selected_display_ranges(cx),
4673                &[empty_range(0, "ⓐⓑ…ⓔ".len())]
4674            );
4675            view.move_left(&MoveLeft, cx);
4676            assert_eq!(
4677                view.selected_display_ranges(cx),
4678                &[empty_range(0, "ⓐⓑ…".len())]
4679            );
4680            view.move_left(&MoveLeft, cx);
4681            assert_eq!(
4682                view.selected_display_ranges(cx),
4683                &[empty_range(0, "ⓐⓑ".len())]
4684            );
4685            view.move_left(&MoveLeft, cx);
4686            assert_eq!(
4687                view.selected_display_ranges(cx),
4688                &[empty_range(0, "".len())]
4689            );
4690        });
4691    }
4692
4693    #[gpui::test]
4694    fn test_move_cursor_different_line_lengths(cx: &mut gpui::MutableAppContext) {
4695        let buffer = MultiBuffer::build_simple("ⓐⓑⓒⓓⓔ\nabcd\nαβγ\nabcd\nⓐⓑⓒⓓⓔ\n", cx);
4696        let settings = EditorSettings::test(&cx);
4697        let (_, view) = cx.add_window(Default::default(), |cx| {
4698            build_editor(buffer.clone(), settings, cx)
4699        });
4700        view.update(cx, |view, cx| {
4701            view.select_display_ranges(&[empty_range(0, "ⓐⓑⓒⓓⓔ".len())], cx);
4702            view.move_down(&MoveDown, cx);
4703            assert_eq!(
4704                view.selected_display_ranges(cx),
4705                &[empty_range(1, "abcd".len())]
4706            );
4707
4708            view.move_down(&MoveDown, cx);
4709            assert_eq!(
4710                view.selected_display_ranges(cx),
4711                &[empty_range(2, "αβγ".len())]
4712            );
4713
4714            view.move_down(&MoveDown, cx);
4715            assert_eq!(
4716                view.selected_display_ranges(cx),
4717                &[empty_range(3, "abcd".len())]
4718            );
4719
4720            view.move_down(&MoveDown, cx);
4721            assert_eq!(
4722                view.selected_display_ranges(cx),
4723                &[empty_range(4, "ⓐⓑⓒⓓⓔ".len())]
4724            );
4725
4726            view.move_up(&MoveUp, cx);
4727            assert_eq!(
4728                view.selected_display_ranges(cx),
4729                &[empty_range(3, "abcd".len())]
4730            );
4731
4732            view.move_up(&MoveUp, cx);
4733            assert_eq!(
4734                view.selected_display_ranges(cx),
4735                &[empty_range(2, "αβγ".len())]
4736            );
4737        });
4738    }
4739
4740    #[gpui::test]
4741    fn test_beginning_end_of_line(cx: &mut gpui::MutableAppContext) {
4742        let buffer = MultiBuffer::build_simple("abc\n  def", cx);
4743        let settings = EditorSettings::test(&cx);
4744        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4745        view.update(cx, |view, cx| {
4746            view.select_display_ranges(
4747                &[
4748                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
4749                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4750                ],
4751                cx,
4752            );
4753        });
4754
4755        view.update(cx, |view, cx| {
4756            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4757            assert_eq!(
4758                view.selected_display_ranges(cx),
4759                &[
4760                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4761                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4762                ]
4763            );
4764        });
4765
4766        view.update(cx, |view, cx| {
4767            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4768            assert_eq!(
4769                view.selected_display_ranges(cx),
4770                &[
4771                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4772                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4773                ]
4774            );
4775        });
4776
4777        view.update(cx, |view, cx| {
4778            view.move_to_beginning_of_line(&MoveToBeginningOfLine, cx);
4779            assert_eq!(
4780                view.selected_display_ranges(cx),
4781                &[
4782                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4783                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
4784                ]
4785            );
4786        });
4787
4788        view.update(cx, |view, cx| {
4789            view.move_to_end_of_line(&MoveToEndOfLine, cx);
4790            assert_eq!(
4791                view.selected_display_ranges(cx),
4792                &[
4793                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4794                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4795                ]
4796            );
4797        });
4798
4799        // Moving to the end of line again is a no-op.
4800        view.update(cx, |view, cx| {
4801            view.move_to_end_of_line(&MoveToEndOfLine, cx);
4802            assert_eq!(
4803                view.selected_display_ranges(cx),
4804                &[
4805                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4806                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
4807                ]
4808            );
4809        });
4810
4811        view.update(cx, |view, cx| {
4812            view.move_left(&MoveLeft, cx);
4813            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4814            assert_eq!(
4815                view.selected_display_ranges(cx),
4816                &[
4817                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4818                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4819                ]
4820            );
4821        });
4822
4823        view.update(cx, |view, cx| {
4824            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4825            assert_eq!(
4826                view.selected_display_ranges(cx),
4827                &[
4828                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4829                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 0),
4830                ]
4831            );
4832        });
4833
4834        view.update(cx, |view, cx| {
4835            view.select_to_beginning_of_line(&SelectToBeginningOfLine(true), cx);
4836            assert_eq!(
4837                view.selected_display_ranges(cx),
4838                &[
4839                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 0),
4840                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 2),
4841                ]
4842            );
4843        });
4844
4845        view.update(cx, |view, cx| {
4846            view.select_to_end_of_line(&SelectToEndOfLine, cx);
4847            assert_eq!(
4848                view.selected_display_ranges(cx),
4849                &[
4850                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
4851                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 5),
4852                ]
4853            );
4854        });
4855
4856        view.update(cx, |view, cx| {
4857            view.delete_to_end_of_line(&DeleteToEndOfLine, cx);
4858            assert_eq!(view.display_text(cx), "ab\n  de");
4859            assert_eq!(
4860                view.selected_display_ranges(cx),
4861                &[
4862                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
4863                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4),
4864                ]
4865            );
4866        });
4867
4868        view.update(cx, |view, cx| {
4869            view.delete_to_beginning_of_line(&DeleteToBeginningOfLine, cx);
4870            assert_eq!(view.display_text(cx), "\n");
4871            assert_eq!(
4872                view.selected_display_ranges(cx),
4873                &[
4874                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4875                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4876                ]
4877            );
4878        });
4879    }
4880
4881    #[gpui::test]
4882    fn test_prev_next_word_boundary(cx: &mut gpui::MutableAppContext) {
4883        let buffer = MultiBuffer::build_simple("use std::str::{foo, bar}\n\n  {baz.qux()}", cx);
4884        let settings = EditorSettings::test(&cx);
4885        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
4886        view.update(cx, |view, cx| {
4887            view.select_display_ranges(
4888                &[
4889                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
4890                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4),
4891                ],
4892                cx,
4893            );
4894        });
4895
4896        view.update(cx, |view, cx| {
4897            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4898            assert_eq!(
4899                view.selected_display_ranges(cx),
4900                &[
4901                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4902                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4903                ]
4904            );
4905        });
4906
4907        view.update(cx, |view, cx| {
4908            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4909            assert_eq!(
4910                view.selected_display_ranges(cx),
4911                &[
4912                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4913                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 2),
4914                ]
4915            );
4916        });
4917
4918        view.update(cx, |view, cx| {
4919            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4920            assert_eq!(
4921                view.selected_display_ranges(cx),
4922                &[
4923                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 4),
4924                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
4925                ]
4926            );
4927        });
4928
4929        view.update(cx, |view, cx| {
4930            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4931            assert_eq!(
4932                view.selected_display_ranges(cx),
4933                &[
4934                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4935                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4936                ]
4937            );
4938        });
4939
4940        view.update(cx, |view, cx| {
4941            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
4942            assert_eq!(
4943                view.selected_display_ranges(cx),
4944                &[
4945                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
4946                    DisplayPoint::new(0, 23)..DisplayPoint::new(0, 23),
4947                ]
4948            );
4949        });
4950
4951        view.update(cx, |view, cx| {
4952            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4953            assert_eq!(
4954                view.selected_display_ranges(cx),
4955                &[
4956                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
4957                    DisplayPoint::new(0, 24)..DisplayPoint::new(0, 24),
4958                ]
4959            );
4960        });
4961
4962        view.update(cx, |view, cx| {
4963            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4964            assert_eq!(
4965                view.selected_display_ranges(cx),
4966                &[
4967                    DisplayPoint::new(0, 7)..DisplayPoint::new(0, 7),
4968                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
4969                ]
4970            );
4971        });
4972
4973        view.update(cx, |view, cx| {
4974            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
4975            assert_eq!(
4976                view.selected_display_ranges(cx),
4977                &[
4978                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 9),
4979                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
4980                ]
4981            );
4982        });
4983
4984        view.update(cx, |view, cx| {
4985            view.move_right(&MoveRight, cx);
4986            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4987            assert_eq!(
4988                view.selected_display_ranges(cx),
4989                &[
4990                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
4991                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
4992                ]
4993            );
4994        });
4995
4996        view.update(cx, |view, cx| {
4997            view.select_to_previous_word_boundary(&SelectToPreviousWordBoundary, cx);
4998            assert_eq!(
4999                view.selected_display_ranges(cx),
5000                &[
5001                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 7),
5002                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 2),
5003                ]
5004            );
5005        });
5006
5007        view.update(cx, |view, cx| {
5008            view.select_to_next_word_boundary(&SelectToNextWordBoundary, cx);
5009            assert_eq!(
5010                view.selected_display_ranges(cx),
5011                &[
5012                    DisplayPoint::new(0, 10)..DisplayPoint::new(0, 9),
5013                    DisplayPoint::new(2, 4)..DisplayPoint::new(2, 3),
5014                ]
5015            );
5016        });
5017    }
5018
5019    #[gpui::test]
5020    fn test_prev_next_word_bounds_with_soft_wrap(cx: &mut gpui::MutableAppContext) {
5021        let buffer = MultiBuffer::build_simple("use one::{\n    two::three::four::five\n};", cx);
5022        let settings = EditorSettings::test(&cx);
5023        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5024
5025        view.update(cx, |view, cx| {
5026            view.set_wrap_width(Some(140.), cx);
5027            assert_eq!(
5028                view.display_text(cx),
5029                "use one::{\n    two::three::\n    four::five\n};"
5030            );
5031
5032            view.select_display_ranges(&[DisplayPoint::new(1, 7)..DisplayPoint::new(1, 7)], cx);
5033
5034            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
5035            assert_eq!(
5036                view.selected_display_ranges(cx),
5037                &[DisplayPoint::new(1, 9)..DisplayPoint::new(1, 9)]
5038            );
5039
5040            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
5041            assert_eq!(
5042                view.selected_display_ranges(cx),
5043                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
5044            );
5045
5046            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
5047            assert_eq!(
5048                view.selected_display_ranges(cx),
5049                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
5050            );
5051
5052            view.move_to_next_word_boundary(&MoveToNextWordBoundary, cx);
5053            assert_eq!(
5054                view.selected_display_ranges(cx),
5055                &[DisplayPoint::new(2, 8)..DisplayPoint::new(2, 8)]
5056            );
5057
5058            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
5059            assert_eq!(
5060                view.selected_display_ranges(cx),
5061                &[DisplayPoint::new(2, 4)..DisplayPoint::new(2, 4)]
5062            );
5063
5064            view.move_to_previous_word_boundary(&MoveToPreviousWordBoundary, cx);
5065            assert_eq!(
5066                view.selected_display_ranges(cx),
5067                &[DisplayPoint::new(1, 14)..DisplayPoint::new(1, 14)]
5068            );
5069        });
5070    }
5071
5072    #[gpui::test]
5073    fn test_delete_to_word_boundary(cx: &mut gpui::MutableAppContext) {
5074        let buffer = MultiBuffer::build_simple("one two three four", cx);
5075        let settings = EditorSettings::test(&cx);
5076        let (_, view) = cx.add_window(Default::default(), |cx| {
5077            build_editor(buffer.clone(), settings, cx)
5078        });
5079
5080        view.update(cx, |view, cx| {
5081            view.select_display_ranges(
5082                &[
5083                    // an empty selection - the preceding word fragment is deleted
5084                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5085                    // characters selected - they are deleted
5086                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 12),
5087                ],
5088                cx,
5089            );
5090            view.delete_to_previous_word_boundary(&DeleteToPreviousWordBoundary, cx);
5091        });
5092
5093        assert_eq!(buffer.read(cx).read(cx).text(), "e two te four");
5094
5095        view.update(cx, |view, cx| {
5096            view.select_display_ranges(
5097                &[
5098                    // an empty selection - the following word fragment is deleted
5099                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5100                    // characters selected - they are deleted
5101                    DisplayPoint::new(0, 9)..DisplayPoint::new(0, 10),
5102                ],
5103                cx,
5104            );
5105            view.delete_to_next_word_boundary(&DeleteToNextWordBoundary, cx);
5106        });
5107
5108        assert_eq!(buffer.read(cx).read(cx).text(), "e t te our");
5109    }
5110
5111    #[gpui::test]
5112    fn test_newline(cx: &mut gpui::MutableAppContext) {
5113        let buffer = MultiBuffer::build_simple("aaaa\n    bbbb\n", cx);
5114        let settings = EditorSettings::test(&cx);
5115        let (_, view) = cx.add_window(Default::default(), |cx| {
5116            build_editor(buffer.clone(), settings, cx)
5117        });
5118
5119        view.update(cx, |view, cx| {
5120            view.select_display_ranges(
5121                &[
5122                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5123                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
5124                    DisplayPoint::new(1, 6)..DisplayPoint::new(1, 6),
5125                ],
5126                cx,
5127            );
5128
5129            view.newline(&Newline, cx);
5130            assert_eq!(view.text(cx), "aa\naa\n  \n    bb\n    bb\n");
5131        });
5132    }
5133
5134    #[gpui::test]
5135    fn test_indent_outdent(cx: &mut gpui::MutableAppContext) {
5136        let buffer = MultiBuffer::build_simple("  one two\nthree\n four", cx);
5137        let settings = EditorSettings::test(&cx);
5138        let (_, view) = cx.add_window(Default::default(), |cx| {
5139            build_editor(buffer.clone(), settings, cx)
5140        });
5141
5142        view.update(cx, |view, cx| {
5143            // two selections on the same line
5144            view.select_display_ranges(
5145                &[
5146                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 5),
5147                    DisplayPoint::new(0, 6)..DisplayPoint::new(0, 9),
5148                ],
5149                cx,
5150            );
5151
5152            // indent from mid-tabstop to full tabstop
5153            view.tab(&Tab, cx);
5154            assert_eq!(view.text(cx), "    one two\nthree\n four");
5155            assert_eq!(
5156                view.selected_display_ranges(cx),
5157                &[
5158                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
5159                    DisplayPoint::new(0, 8)..DisplayPoint::new(0, 11),
5160                ]
5161            );
5162
5163            // outdent from 1 tabstop to 0 tabstops
5164            view.outdent(&Outdent, cx);
5165            assert_eq!(view.text(cx), "one two\nthree\n four");
5166            assert_eq!(
5167                view.selected_display_ranges(cx),
5168                &[
5169                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 3),
5170                    DisplayPoint::new(0, 4)..DisplayPoint::new(0, 7),
5171                ]
5172            );
5173
5174            // select across line ending
5175            view.select_display_ranges(&[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)], cx);
5176
5177            // indent and outdent affect only the preceding line
5178            view.tab(&Tab, cx);
5179            assert_eq!(view.text(cx), "one two\n    three\n four");
5180            assert_eq!(
5181                view.selected_display_ranges(cx),
5182                &[DisplayPoint::new(1, 5)..DisplayPoint::new(2, 0)]
5183            );
5184            view.outdent(&Outdent, cx);
5185            assert_eq!(view.text(cx), "one two\nthree\n four");
5186            assert_eq!(
5187                view.selected_display_ranges(cx),
5188                &[DisplayPoint::new(1, 1)..DisplayPoint::new(2, 0)]
5189            );
5190
5191            // Ensure that indenting/outdenting works when the cursor is at column 0.
5192            view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
5193            view.tab(&Tab, cx);
5194            assert_eq!(view.text(cx), "one two\n    three\n four");
5195            assert_eq!(
5196                view.selected_display_ranges(cx),
5197                &[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 4)]
5198            );
5199
5200            view.select_display_ranges(&[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)], cx);
5201            view.outdent(&Outdent, cx);
5202            assert_eq!(view.text(cx), "one two\nthree\n four");
5203            assert_eq!(
5204                view.selected_display_ranges(cx),
5205                &[DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0)]
5206            );
5207        });
5208    }
5209
5210    #[gpui::test]
5211    fn test_backspace(cx: &mut gpui::MutableAppContext) {
5212        let buffer =
5213            MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
5214        let settings = EditorSettings::test(&cx);
5215        let (_, view) = cx.add_window(Default::default(), |cx| {
5216            build_editor(buffer.clone(), settings, cx)
5217        });
5218
5219        view.update(cx, |view, cx| {
5220            view.select_display_ranges(
5221                &[
5222                    // an empty selection - the preceding character is deleted
5223                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5224                    // one character selected - it is deleted
5225                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5226                    // a line suffix selected - it is deleted
5227                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
5228                ],
5229                cx,
5230            );
5231            view.backspace(&Backspace, cx);
5232        });
5233
5234        assert_eq!(
5235            buffer.read(cx).read(cx).text(),
5236            "oe two three\nfou five six\nseven ten\n"
5237        );
5238    }
5239
5240    #[gpui::test]
5241    fn test_delete(cx: &mut gpui::MutableAppContext) {
5242        let buffer =
5243            MultiBuffer::build_simple("one two three\nfour five six\nseven eight nine\nten\n", cx);
5244        let settings = EditorSettings::test(&cx);
5245        let (_, view) = cx.add_window(Default::default(), |cx| {
5246            build_editor(buffer.clone(), settings, cx)
5247        });
5248
5249        view.update(cx, |view, cx| {
5250            view.select_display_ranges(
5251                &[
5252                    // an empty selection - the following character is deleted
5253                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5254                    // one character selected - it is deleted
5255                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5256                    // a line suffix selected - it is deleted
5257                    DisplayPoint::new(2, 6)..DisplayPoint::new(3, 0),
5258                ],
5259                cx,
5260            );
5261            view.delete(&Delete, cx);
5262        });
5263
5264        assert_eq!(
5265            buffer.read(cx).read(cx).text(),
5266            "on two three\nfou five six\nseven ten\n"
5267        );
5268    }
5269
5270    #[gpui::test]
5271    fn test_delete_line(cx: &mut gpui::MutableAppContext) {
5272        let settings = EditorSettings::test(&cx);
5273        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
5274        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5275        view.update(cx, |view, cx| {
5276            view.select_display_ranges(
5277                &[
5278                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5279                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
5280                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5281                ],
5282                cx,
5283            );
5284            view.delete_line(&DeleteLine, cx);
5285            assert_eq!(view.display_text(cx), "ghi");
5286            assert_eq!(
5287                view.selected_display_ranges(cx),
5288                vec![
5289                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
5290                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
5291                ]
5292            );
5293        });
5294
5295        let settings = EditorSettings::test(&cx);
5296        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
5297        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5298        view.update(cx, |view, cx| {
5299            view.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(0, 1)], cx);
5300            view.delete_line(&DeleteLine, cx);
5301            assert_eq!(view.display_text(cx), "ghi\n");
5302            assert_eq!(
5303                view.selected_display_ranges(cx),
5304                vec![DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)]
5305            );
5306        });
5307    }
5308
5309    #[gpui::test]
5310    fn test_duplicate_line(cx: &mut gpui::MutableAppContext) {
5311        let settings = EditorSettings::test(&cx);
5312        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
5313        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5314        view.update(cx, |view, cx| {
5315            view.select_display_ranges(
5316                &[
5317                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5318                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5319                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5320                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5321                ],
5322                cx,
5323            );
5324            view.duplicate_line(&DuplicateLine, cx);
5325            assert_eq!(view.display_text(cx), "abc\nabc\ndef\ndef\nghi\n\n");
5326            assert_eq!(
5327                view.selected_display_ranges(cx),
5328                vec![
5329                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 1),
5330                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
5331                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5332                    DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
5333                ]
5334            );
5335        });
5336
5337        let settings = EditorSettings::test(&cx);
5338        let buffer = MultiBuffer::build_simple("abc\ndef\nghi\n", cx);
5339        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5340        view.update(cx, |view, cx| {
5341            view.select_display_ranges(
5342                &[
5343                    DisplayPoint::new(0, 1)..DisplayPoint::new(1, 1),
5344                    DisplayPoint::new(1, 2)..DisplayPoint::new(2, 1),
5345                ],
5346                cx,
5347            );
5348            view.duplicate_line(&DuplicateLine, cx);
5349            assert_eq!(view.display_text(cx), "abc\ndef\nghi\nabc\ndef\nghi\n");
5350            assert_eq!(
5351                view.selected_display_ranges(cx),
5352                vec![
5353                    DisplayPoint::new(3, 1)..DisplayPoint::new(4, 1),
5354                    DisplayPoint::new(4, 2)..DisplayPoint::new(5, 1),
5355                ]
5356            );
5357        });
5358    }
5359
5360    #[gpui::test]
5361    fn test_move_line_up_down(cx: &mut gpui::MutableAppContext) {
5362        let settings = EditorSettings::test(&cx);
5363        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
5364        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5365        view.update(cx, |view, cx| {
5366            view.fold_ranges(
5367                vec![
5368                    Point::new(0, 2)..Point::new(1, 2),
5369                    Point::new(2, 3)..Point::new(4, 1),
5370                    Point::new(7, 0)..Point::new(8, 4),
5371                ],
5372                cx,
5373            );
5374            view.select_display_ranges(
5375                &[
5376                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5377                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5378                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5379                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2),
5380                ],
5381                cx,
5382            );
5383            assert_eq!(
5384                view.display_text(cx),
5385                "aa…bbb\nccc…eeee\nfffff\nggggg\n…i\njjjjj"
5386            );
5387
5388            view.move_line_up(&MoveLineUp, cx);
5389            assert_eq!(
5390                view.display_text(cx),
5391                "aa…bbb\nccc…eeee\nggggg\n…i\njjjjj\nfffff"
5392            );
5393            assert_eq!(
5394                view.selected_display_ranges(cx),
5395                vec![
5396                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5397                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5398                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
5399                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
5400                ]
5401            );
5402        });
5403
5404        view.update(cx, |view, cx| {
5405            view.move_line_down(&MoveLineDown, cx);
5406            assert_eq!(
5407                view.display_text(cx),
5408                "ccc…eeee\naa…bbb\nfffff\nggggg\n…i\njjjjj"
5409            );
5410            assert_eq!(
5411                view.selected_display_ranges(cx),
5412                vec![
5413                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5414                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5415                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5416                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
5417                ]
5418            );
5419        });
5420
5421        view.update(cx, |view, cx| {
5422            view.move_line_down(&MoveLineDown, cx);
5423            assert_eq!(
5424                view.display_text(cx),
5425                "ccc…eeee\nfffff\naa…bbb\nggggg\n…i\njjjjj"
5426            );
5427            assert_eq!(
5428                view.selected_display_ranges(cx),
5429                vec![
5430                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5431                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 1),
5432                    DisplayPoint::new(3, 2)..DisplayPoint::new(4, 3),
5433                    DisplayPoint::new(5, 0)..DisplayPoint::new(5, 2)
5434                ]
5435            );
5436        });
5437
5438        view.update(cx, |view, cx| {
5439            view.move_line_up(&MoveLineUp, cx);
5440            assert_eq!(
5441                view.display_text(cx),
5442                "ccc…eeee\naa…bbb\nggggg\n…i\njjjjj\nfffff"
5443            );
5444            assert_eq!(
5445                view.selected_display_ranges(cx),
5446                vec![
5447                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5448                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5449                    DisplayPoint::new(2, 2)..DisplayPoint::new(3, 3),
5450                    DisplayPoint::new(4, 0)..DisplayPoint::new(4, 2)
5451                ]
5452            );
5453        });
5454    }
5455
5456    #[gpui::test]
5457    fn test_move_line_up_down_with_blocks(cx: &mut gpui::MutableAppContext) {
5458        let settings = EditorSettings::test(&cx);
5459        let buffer = MultiBuffer::build_simple(&sample_text(10, 5, 'a'), cx);
5460        let snapshot = buffer.read(cx).snapshot(cx);
5461        let (_, editor) =
5462            cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5463        editor.update(cx, |editor, cx| {
5464            editor.insert_blocks(
5465                [BlockProperties {
5466                    position: snapshot.anchor_after(Point::new(2, 0)),
5467                    disposition: BlockDisposition::Below,
5468                    height: 1,
5469                    render: Arc::new(|_| Empty::new().boxed()),
5470                }],
5471                cx,
5472            );
5473            editor.select_ranges([Point::new(2, 0)..Point::new(2, 0)], None, cx);
5474            editor.move_line_down(&MoveLineDown, cx);
5475        });
5476    }
5477
5478    #[gpui::test]
5479    fn test_clipboard(cx: &mut gpui::MutableAppContext) {
5480        let buffer = MultiBuffer::build_simple("one✅ two three four five six ", cx);
5481        let settings = EditorSettings::test(&cx);
5482        let view = cx
5483            .add_window(Default::default(), |cx| {
5484                build_editor(buffer.clone(), settings, cx)
5485            })
5486            .1;
5487
5488        // Cut with three selections. Clipboard text is divided into three slices.
5489        view.update(cx, |view, cx| {
5490            view.select_ranges(vec![0..7, 11..17, 22..27], None, cx);
5491            view.cut(&Cut, cx);
5492            assert_eq!(view.display_text(cx), "two four six ");
5493        });
5494
5495        // Paste with three cursors. Each cursor pastes one slice of the clipboard text.
5496        view.update(cx, |view, cx| {
5497            view.select_ranges(vec![4..4, 9..9, 13..13], None, cx);
5498            view.paste(&Paste, cx);
5499            assert_eq!(view.display_text(cx), "two one✅ four three six five ");
5500            assert_eq!(
5501                view.selected_display_ranges(cx),
5502                &[
5503                    DisplayPoint::new(0, 11)..DisplayPoint::new(0, 11),
5504                    DisplayPoint::new(0, 22)..DisplayPoint::new(0, 22),
5505                    DisplayPoint::new(0, 31)..DisplayPoint::new(0, 31)
5506                ]
5507            );
5508        });
5509
5510        // Paste again but with only two cursors. Since the number of cursors doesn't
5511        // match the number of slices in the clipboard, the entire clipboard text
5512        // is pasted at each cursor.
5513        view.update(cx, |view, cx| {
5514            view.select_ranges(vec![0..0, 31..31], None, cx);
5515            view.handle_input(&Input("( ".into()), cx);
5516            view.paste(&Paste, cx);
5517            view.handle_input(&Input(") ".into()), cx);
5518            assert_eq!(
5519                view.display_text(cx),
5520                "( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5521            );
5522        });
5523
5524        view.update(cx, |view, cx| {
5525            view.select_ranges(vec![0..0], None, cx);
5526            view.handle_input(&Input("123\n4567\n89\n".into()), cx);
5527            assert_eq!(
5528                view.display_text(cx),
5529                "123\n4567\n89\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5530            );
5531        });
5532
5533        // Cut with three selections, one of which is full-line.
5534        view.update(cx, |view, cx| {
5535            view.select_display_ranges(
5536                &[
5537                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 2),
5538                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5539                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 1),
5540                ],
5541                cx,
5542            );
5543            view.cut(&Cut, cx);
5544            assert_eq!(
5545                view.display_text(cx),
5546                "13\n9\n( one✅ three five ) two one✅ four three six five ( one✅ three five ) "
5547            );
5548        });
5549
5550        // Paste with three selections, noticing how the copied selection that was full-line
5551        // gets inserted before the second cursor.
5552        view.update(cx, |view, cx| {
5553            view.select_display_ranges(
5554                &[
5555                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5556                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5557                    DisplayPoint::new(2, 2)..DisplayPoint::new(2, 3),
5558                ],
5559                cx,
5560            );
5561            view.paste(&Paste, cx);
5562            assert_eq!(
5563                view.display_text(cx),
5564                "123\n4567\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
5565            );
5566            assert_eq!(
5567                view.selected_display_ranges(cx),
5568                &[
5569                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5570                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5571                    DisplayPoint::new(3, 3)..DisplayPoint::new(3, 3),
5572                ]
5573            );
5574        });
5575
5576        // Copy with a single cursor only, which writes the whole line into the clipboard.
5577        view.update(cx, |view, cx| {
5578            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)], cx);
5579            view.copy(&Copy, cx);
5580        });
5581
5582        // Paste with three selections, noticing how the copied full-line selection is inserted
5583        // before the empty selections but replaces the selection that is non-empty.
5584        view.update(cx, |view, cx| {
5585            view.select_display_ranges(
5586                &[
5587                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5588                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 2),
5589                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
5590                ],
5591                cx,
5592            );
5593            view.paste(&Paste, cx);
5594            assert_eq!(
5595                view.display_text(cx),
5596                "123\n123\n123\n67\n123\n9\n( 8ne✅ three five ) two one✅ four three six five ( one✅ three five ) "
5597            );
5598            assert_eq!(
5599                view.selected_display_ranges(cx),
5600                &[
5601                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
5602                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
5603                    DisplayPoint::new(5, 1)..DisplayPoint::new(5, 1),
5604                ]
5605            );
5606        });
5607    }
5608
5609    #[gpui::test]
5610    fn test_select_all(cx: &mut gpui::MutableAppContext) {
5611        let buffer = MultiBuffer::build_simple("abc\nde\nfgh", cx);
5612        let settings = EditorSettings::test(&cx);
5613        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5614        view.update(cx, |view, cx| {
5615            view.select_all(&SelectAll, cx);
5616            assert_eq!(
5617                view.selected_display_ranges(cx),
5618                &[DisplayPoint::new(0, 0)..DisplayPoint::new(2, 3)]
5619            );
5620        });
5621    }
5622
5623    #[gpui::test]
5624    fn test_select_line(cx: &mut gpui::MutableAppContext) {
5625        let settings = EditorSettings::test(&cx);
5626        let buffer = MultiBuffer::build_simple(&sample_text(6, 5, 'a'), cx);
5627        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5628        view.update(cx, |view, cx| {
5629            view.select_display_ranges(
5630                &[
5631                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5632                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5633                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5634                    DisplayPoint::new(4, 2)..DisplayPoint::new(4, 2),
5635                ],
5636                cx,
5637            );
5638            view.select_line(&SelectLine, cx);
5639            assert_eq!(
5640                view.selected_display_ranges(cx),
5641                vec![
5642                    DisplayPoint::new(0, 0)..DisplayPoint::new(2, 0),
5643                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 0),
5644                ]
5645            );
5646        });
5647
5648        view.update(cx, |view, cx| {
5649            view.select_line(&SelectLine, cx);
5650            assert_eq!(
5651                view.selected_display_ranges(cx),
5652                vec![
5653                    DisplayPoint::new(0, 0)..DisplayPoint::new(3, 0),
5654                    DisplayPoint::new(4, 0)..DisplayPoint::new(5, 5),
5655                ]
5656            );
5657        });
5658
5659        view.update(cx, |view, cx| {
5660            view.select_line(&SelectLine, cx);
5661            assert_eq!(
5662                view.selected_display_ranges(cx),
5663                vec![DisplayPoint::new(0, 0)..DisplayPoint::new(5, 5)]
5664            );
5665        });
5666    }
5667
5668    #[gpui::test]
5669    fn test_split_selection_into_lines(cx: &mut gpui::MutableAppContext) {
5670        let settings = EditorSettings::test(&cx);
5671        let buffer = MultiBuffer::build_simple(&sample_text(9, 5, 'a'), cx);
5672        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5673        view.update(cx, |view, cx| {
5674            view.fold_ranges(
5675                vec![
5676                    Point::new(0, 2)..Point::new(1, 2),
5677                    Point::new(2, 3)..Point::new(4, 1),
5678                    Point::new(7, 0)..Point::new(8, 4),
5679                ],
5680                cx,
5681            );
5682            view.select_display_ranges(
5683                &[
5684                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
5685                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5686                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
5687                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
5688                ],
5689                cx,
5690            );
5691            assert_eq!(view.display_text(cx), "aa…bbb\nccc…eeee\nfffff\nggggg\n…i");
5692        });
5693
5694        view.update(cx, |view, cx| {
5695            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5696            assert_eq!(
5697                view.display_text(cx),
5698                "aaaaa\nbbbbb\nccc…eeee\nfffff\nggggg\n…i"
5699            );
5700            assert_eq!(
5701                view.selected_display_ranges(cx),
5702                [
5703                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
5704                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 2),
5705                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
5706                    DisplayPoint::new(5, 4)..DisplayPoint::new(5, 4)
5707                ]
5708            );
5709        });
5710
5711        view.update(cx, |view, cx| {
5712            view.select_display_ranges(&[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 1)], cx);
5713            view.split_selection_into_lines(&SplitSelectionIntoLines, cx);
5714            assert_eq!(
5715                view.display_text(cx),
5716                "aaaaa\nbbbbb\nccccc\nddddd\neeeee\nfffff\nggggg\nhhhhh\niiiii"
5717            );
5718            assert_eq!(
5719                view.selected_display_ranges(cx),
5720                [
5721                    DisplayPoint::new(0, 5)..DisplayPoint::new(0, 5),
5722                    DisplayPoint::new(1, 5)..DisplayPoint::new(1, 5),
5723                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
5724                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 5),
5725                    DisplayPoint::new(4, 5)..DisplayPoint::new(4, 5),
5726                    DisplayPoint::new(5, 5)..DisplayPoint::new(5, 5),
5727                    DisplayPoint::new(6, 5)..DisplayPoint::new(6, 5),
5728                    DisplayPoint::new(7, 0)..DisplayPoint::new(7, 0)
5729                ]
5730            );
5731        });
5732    }
5733
5734    #[gpui::test]
5735    fn test_add_selection_above_below(cx: &mut gpui::MutableAppContext) {
5736        let settings = EditorSettings::test(&cx);
5737        let buffer = MultiBuffer::build_simple("abc\ndefghi\n\njk\nlmno\n", cx);
5738        let (_, view) = cx.add_window(Default::default(), |cx| build_editor(buffer, settings, cx));
5739
5740        view.update(cx, |view, cx| {
5741            view.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)], cx);
5742        });
5743        view.update(cx, |view, cx| {
5744            view.add_selection_above(&AddSelectionAbove, cx);
5745            assert_eq!(
5746                view.selected_display_ranges(cx),
5747                vec![
5748                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5749                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5750                ]
5751            );
5752        });
5753
5754        view.update(cx, |view, cx| {
5755            view.add_selection_above(&AddSelectionAbove, cx);
5756            assert_eq!(
5757                view.selected_display_ranges(cx),
5758                vec![
5759                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3),
5760                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)
5761                ]
5762            );
5763        });
5764
5765        view.update(cx, |view, cx| {
5766            view.add_selection_below(&AddSelectionBelow, cx);
5767            assert_eq!(
5768                view.selected_display_ranges(cx),
5769                vec![DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3)]
5770            );
5771        });
5772
5773        view.update(cx, |view, cx| {
5774            view.add_selection_below(&AddSelectionBelow, cx);
5775            assert_eq!(
5776                view.selected_display_ranges(cx),
5777                vec![
5778                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5779                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5780                ]
5781            );
5782        });
5783
5784        view.update(cx, |view, cx| {
5785            view.add_selection_below(&AddSelectionBelow, cx);
5786            assert_eq!(
5787                view.selected_display_ranges(cx),
5788                vec![
5789                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
5790                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 3)
5791                ]
5792            );
5793        });
5794
5795        view.update(cx, |view, cx| {
5796            view.select_display_ranges(&[DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)], cx);
5797        });
5798        view.update(cx, |view, cx| {
5799            view.add_selection_below(&AddSelectionBelow, cx);
5800            assert_eq!(
5801                view.selected_display_ranges(cx),
5802                vec![
5803                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5804                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5805                ]
5806            );
5807        });
5808
5809        view.update(cx, |view, cx| {
5810            view.add_selection_below(&AddSelectionBelow, cx);
5811            assert_eq!(
5812                view.selected_display_ranges(cx),
5813                vec![
5814                    DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3),
5815                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 3)
5816                ]
5817            );
5818        });
5819
5820        view.update(cx, |view, cx| {
5821            view.add_selection_above(&AddSelectionAbove, cx);
5822            assert_eq!(
5823                view.selected_display_ranges(cx),
5824                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5825            );
5826        });
5827
5828        view.update(cx, |view, cx| {
5829            view.add_selection_above(&AddSelectionAbove, cx);
5830            assert_eq!(
5831                view.selected_display_ranges(cx),
5832                vec![DisplayPoint::new(1, 4)..DisplayPoint::new(1, 3)]
5833            );
5834        });
5835
5836        view.update(cx, |view, cx| {
5837            view.select_display_ranges(&[DisplayPoint::new(0, 1)..DisplayPoint::new(1, 4)], cx);
5838            view.add_selection_below(&AddSelectionBelow, cx);
5839            assert_eq!(
5840                view.selected_display_ranges(cx),
5841                vec![
5842                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5843                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5844                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5845                ]
5846            );
5847        });
5848
5849        view.update(cx, |view, cx| {
5850            view.add_selection_below(&AddSelectionBelow, cx);
5851            assert_eq!(
5852                view.selected_display_ranges(cx),
5853                vec![
5854                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5855                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5856                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5857                    DisplayPoint::new(4, 1)..DisplayPoint::new(4, 4),
5858                ]
5859            );
5860        });
5861
5862        view.update(cx, |view, cx| {
5863            view.add_selection_above(&AddSelectionAbove, cx);
5864            assert_eq!(
5865                view.selected_display_ranges(cx),
5866                vec![
5867                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 3),
5868                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 4),
5869                    DisplayPoint::new(3, 1)..DisplayPoint::new(3, 2),
5870                ]
5871            );
5872        });
5873
5874        view.update(cx, |view, cx| {
5875            view.select_display_ranges(&[DisplayPoint::new(4, 3)..DisplayPoint::new(1, 1)], cx);
5876        });
5877        view.update(cx, |view, cx| {
5878            view.add_selection_above(&AddSelectionAbove, cx);
5879            assert_eq!(
5880                view.selected_display_ranges(cx),
5881                vec![
5882                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 1),
5883                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5884                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5885                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5886                ]
5887            );
5888        });
5889
5890        view.update(cx, |view, cx| {
5891            view.add_selection_below(&AddSelectionBelow, cx);
5892            assert_eq!(
5893                view.selected_display_ranges(cx),
5894                vec![
5895                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 1),
5896                    DisplayPoint::new(3, 2)..DisplayPoint::new(3, 1),
5897                    DisplayPoint::new(4, 3)..DisplayPoint::new(4, 1),
5898                ]
5899            );
5900        });
5901    }
5902
5903    #[gpui::test]
5904    async fn test_select_larger_smaller_syntax_node(mut cx: gpui::TestAppContext) {
5905        let settings = cx.read(EditorSettings::test);
5906        let language = Arc::new(Language::new(
5907            LanguageConfig::default(),
5908            Some(tree_sitter_rust::language()),
5909        ));
5910
5911        let text = r#"
5912            use mod1::mod2::{mod3, mod4};
5913
5914            fn fn_1(param1: bool, param2: &str) {
5915                let var1 = "text";
5916            }
5917        "#
5918        .unindent();
5919
5920        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
5921        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
5922        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
5923        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
5924            .await;
5925
5926        view.update(&mut cx, |view, cx| {
5927            view.select_display_ranges(
5928                &[
5929                    DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
5930                    DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
5931                    DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
5932                ],
5933                cx,
5934            );
5935            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5936        });
5937        assert_eq!(
5938            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5939            &[
5940                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5941                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5942                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5943            ]
5944        );
5945
5946        view.update(&mut cx, |view, cx| {
5947            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5948        });
5949        assert_eq!(
5950            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5951            &[
5952                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5953                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5954            ]
5955        );
5956
5957        view.update(&mut cx, |view, cx| {
5958            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5959        });
5960        assert_eq!(
5961            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5962            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5963        );
5964
5965        // Trying to expand the selected syntax node one more time has no effect.
5966        view.update(&mut cx, |view, cx| {
5967            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
5968        });
5969        assert_eq!(
5970            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5971            &[DisplayPoint::new(5, 0)..DisplayPoint::new(0, 0)]
5972        );
5973
5974        view.update(&mut cx, |view, cx| {
5975            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5976        });
5977        assert_eq!(
5978            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5979            &[
5980                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
5981                DisplayPoint::new(4, 1)..DisplayPoint::new(2, 0),
5982            ]
5983        );
5984
5985        view.update(&mut cx, |view, cx| {
5986            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5987        });
5988        assert_eq!(
5989            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
5990            &[
5991                DisplayPoint::new(0, 23)..DisplayPoint::new(0, 27),
5992                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
5993                DisplayPoint::new(3, 15)..DisplayPoint::new(3, 21),
5994            ]
5995        );
5996
5997        view.update(&mut cx, |view, cx| {
5998            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
5999        });
6000        assert_eq!(
6001            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
6002            &[
6003                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
6004                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
6005                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
6006            ]
6007        );
6008
6009        // Trying to shrink the selected syntax node one more time has no effect.
6010        view.update(&mut cx, |view, cx| {
6011            view.select_smaller_syntax_node(&SelectSmallerSyntaxNode, cx);
6012        });
6013        assert_eq!(
6014            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
6015            &[
6016                DisplayPoint::new(0, 25)..DisplayPoint::new(0, 25),
6017                DisplayPoint::new(2, 24)..DisplayPoint::new(2, 12),
6018                DisplayPoint::new(3, 18)..DisplayPoint::new(3, 18),
6019            ]
6020        );
6021
6022        // Ensure that we keep expanding the selection if the larger selection starts or ends within
6023        // a fold.
6024        view.update(&mut cx, |view, cx| {
6025            view.fold_ranges(
6026                vec![
6027                    Point::new(0, 21)..Point::new(0, 24),
6028                    Point::new(3, 20)..Point::new(3, 22),
6029                ],
6030                cx,
6031            );
6032            view.select_larger_syntax_node(&SelectLargerSyntaxNode, cx);
6033        });
6034        assert_eq!(
6035            view.update(&mut cx, |view, cx| view.selected_display_ranges(cx)),
6036            &[
6037                DisplayPoint::new(0, 16)..DisplayPoint::new(0, 28),
6038                DisplayPoint::new(2, 35)..DisplayPoint::new(2, 7),
6039                DisplayPoint::new(3, 4)..DisplayPoint::new(3, 23),
6040            ]
6041        );
6042    }
6043
6044    #[gpui::test]
6045    async fn test_autoindent_selections(mut cx: gpui::TestAppContext) {
6046        let settings = cx.read(EditorSettings::test);
6047        let language = Arc::new(
6048            Language::new(
6049                LanguageConfig {
6050                    brackets: vec![
6051                        BracketPair {
6052                            start: "{".to_string(),
6053                            end: "}".to_string(),
6054                            close: false,
6055                            newline: true,
6056                        },
6057                        BracketPair {
6058                            start: "(".to_string(),
6059                            end: ")".to_string(),
6060                            close: false,
6061                            newline: true,
6062                        },
6063                    ],
6064                    ..Default::default()
6065                },
6066                Some(tree_sitter_rust::language()),
6067            )
6068            .with_indents_query(
6069                r#"
6070                (_ "(" ")" @end) @indent
6071                (_ "{" "}" @end) @indent
6072                "#,
6073            )
6074            .unwrap(),
6075        );
6076
6077        let text = "fn a() {}";
6078
6079        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
6080        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
6081        let (_, editor) = cx.add_window(|cx| build_editor(buffer, settings, cx));
6082        editor
6083            .condition(&cx, |editor, cx| !editor.buffer.read(cx).is_parsing(cx))
6084            .await;
6085
6086        editor.update(&mut cx, |editor, cx| {
6087            editor.select_ranges([5..5, 8..8, 9..9], None, cx);
6088            editor.newline(&Newline, cx);
6089            assert_eq!(editor.text(cx), "fn a(\n    \n) {\n    \n}\n");
6090            assert_eq!(
6091                editor.selected_ranges(cx),
6092                &[
6093                    Point::new(1, 4)..Point::new(1, 4),
6094                    Point::new(3, 4)..Point::new(3, 4),
6095                    Point::new(5, 0)..Point::new(5, 0)
6096                ]
6097            );
6098        });
6099    }
6100
6101    #[gpui::test]
6102    async fn test_autoclose_pairs(mut cx: gpui::TestAppContext) {
6103        let settings = cx.read(EditorSettings::test);
6104        let language = Arc::new(Language::new(
6105            LanguageConfig {
6106                brackets: vec![
6107                    BracketPair {
6108                        start: "{".to_string(),
6109                        end: "}".to_string(),
6110                        close: true,
6111                        newline: true,
6112                    },
6113                    BracketPair {
6114                        start: "/*".to_string(),
6115                        end: " */".to_string(),
6116                        close: true,
6117                        newline: true,
6118                    },
6119                ],
6120                ..Default::default()
6121            },
6122            Some(tree_sitter_rust::language()),
6123        ));
6124
6125        let text = r#"
6126            a
6127
6128            /
6129
6130        "#
6131        .unindent();
6132
6133        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
6134        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
6135        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
6136        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
6137            .await;
6138
6139        view.update(&mut cx, |view, cx| {
6140            view.select_display_ranges(
6141                &[
6142                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 1),
6143                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6144                ],
6145                cx,
6146            );
6147            view.handle_input(&Input("{".to_string()), cx);
6148            view.handle_input(&Input("{".to_string()), cx);
6149            view.handle_input(&Input("{".to_string()), cx);
6150            assert_eq!(
6151                view.text(cx),
6152                "
6153                {{{}}}
6154                {{{}}}
6155                /
6156
6157                "
6158                .unindent()
6159            );
6160
6161            view.move_right(&MoveRight, cx);
6162            view.handle_input(&Input("}".to_string()), cx);
6163            view.handle_input(&Input("}".to_string()), cx);
6164            view.handle_input(&Input("}".to_string()), cx);
6165            assert_eq!(
6166                view.text(cx),
6167                "
6168                {{{}}}}
6169                {{{}}}}
6170                /
6171
6172                "
6173                .unindent()
6174            );
6175
6176            view.undo(&Undo, cx);
6177            view.handle_input(&Input("/".to_string()), cx);
6178            view.handle_input(&Input("*".to_string()), cx);
6179            assert_eq!(
6180                view.text(cx),
6181                "
6182                /* */
6183                /* */
6184                /
6185
6186                "
6187                .unindent()
6188            );
6189
6190            view.undo(&Undo, cx);
6191            view.select_display_ranges(
6192                &[
6193                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
6194                    DisplayPoint::new(3, 0)..DisplayPoint::new(3, 0),
6195                ],
6196                cx,
6197            );
6198            view.handle_input(&Input("*".to_string()), cx);
6199            assert_eq!(
6200                view.text(cx),
6201                "
6202                a
6203
6204                /*
6205                *
6206                "
6207                .unindent()
6208            );
6209        });
6210    }
6211
6212    #[gpui::test]
6213    async fn test_toggle_comment(mut cx: gpui::TestAppContext) {
6214        let settings = cx.read(EditorSettings::test);
6215        let language = Arc::new(Language::new(
6216            LanguageConfig {
6217                line_comment: Some("// ".to_string()),
6218                ..Default::default()
6219            },
6220            Some(tree_sitter_rust::language()),
6221        ));
6222
6223        let text = "
6224            fn a() {
6225                //b();
6226                // c();
6227                //  d();
6228            }
6229        "
6230        .unindent();
6231
6232        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
6233        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
6234        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
6235
6236        view.update(&mut cx, |editor, cx| {
6237            // If multiple selections intersect a line, the line is only
6238            // toggled once.
6239            editor.select_display_ranges(
6240                &[
6241                    DisplayPoint::new(1, 3)..DisplayPoint::new(2, 3),
6242                    DisplayPoint::new(3, 5)..DisplayPoint::new(3, 6),
6243                ],
6244                cx,
6245            );
6246            editor.toggle_comments(&ToggleComments, cx);
6247            assert_eq!(
6248                editor.text(cx),
6249                "
6250                    fn a() {
6251                        b();
6252                        c();
6253                         d();
6254                    }
6255                "
6256                .unindent()
6257            );
6258
6259            // The comment prefix is inserted at the same column for every line
6260            // in a selection.
6261            editor.select_display_ranges(&[DisplayPoint::new(1, 3)..DisplayPoint::new(3, 6)], cx);
6262            editor.toggle_comments(&ToggleComments, cx);
6263            assert_eq!(
6264                editor.text(cx),
6265                "
6266                    fn a() {
6267                        // b();
6268                        // c();
6269                        //  d();
6270                    }
6271                "
6272                .unindent()
6273            );
6274
6275            // If a selection ends at the beginning of a line, that line is not toggled.
6276            editor.select_display_ranges(&[DisplayPoint::new(2, 0)..DisplayPoint::new(3, 0)], cx);
6277            editor.toggle_comments(&ToggleComments, cx);
6278            assert_eq!(
6279                editor.text(cx),
6280                "
6281                        fn a() {
6282                            // b();
6283                            c();
6284                            //  d();
6285                        }
6286                    "
6287                .unindent()
6288            );
6289        });
6290    }
6291
6292    #[gpui::test]
6293    fn test_editing_disjoint_excerpts(cx: &mut gpui::MutableAppContext) {
6294        let settings = EditorSettings::test(cx);
6295        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
6296        let multibuffer = cx.add_model(|cx| {
6297            let mut multibuffer = MultiBuffer::new(0);
6298            multibuffer.push_excerpt(
6299                ExcerptProperties {
6300                    buffer: &buffer,
6301                    range: Point::new(0, 0)..Point::new(0, 4),
6302                },
6303                cx,
6304            );
6305            multibuffer.push_excerpt(
6306                ExcerptProperties {
6307                    buffer: &buffer,
6308                    range: Point::new(1, 0)..Point::new(1, 4),
6309                },
6310                cx,
6311            );
6312            multibuffer
6313        });
6314
6315        assert_eq!(multibuffer.read(cx).read(cx).text(), "aaaa\nbbbb");
6316
6317        let (_, view) = cx.add_window(Default::default(), |cx| {
6318            build_editor(multibuffer, settings, cx)
6319        });
6320        view.update(cx, |view, cx| {
6321            view.select_display_ranges(
6322                &[
6323                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6324                    DisplayPoint::new(1, 0)..DisplayPoint::new(1, 0),
6325                ],
6326                cx,
6327            );
6328
6329            view.handle_input(&Input("X".to_string()), cx);
6330            assert_eq!(view.text(cx), "Xaaaa\nXbbbb");
6331            assert_eq!(
6332                view.selected_display_ranges(cx),
6333                &[
6334                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6335                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6336                ]
6337            )
6338        });
6339    }
6340
6341    #[gpui::test]
6342    fn test_editing_overlapping_excerpts(cx: &mut gpui::MutableAppContext) {
6343        let settings = EditorSettings::test(cx);
6344        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
6345        let multibuffer = cx.add_model(|cx| {
6346            let mut multibuffer = MultiBuffer::new(0);
6347            multibuffer.push_excerpt(
6348                ExcerptProperties {
6349                    buffer: &buffer,
6350                    range: Point::new(0, 0)..Point::new(1, 4),
6351                },
6352                cx,
6353            );
6354            multibuffer.push_excerpt(
6355                ExcerptProperties {
6356                    buffer: &buffer,
6357                    range: Point::new(1, 0)..Point::new(2, 4),
6358                },
6359                cx,
6360            );
6361            multibuffer
6362        });
6363
6364        assert_eq!(
6365            multibuffer.read(cx).read(cx).text(),
6366            "aaaa\nbbbb\nbbbb\ncccc"
6367        );
6368
6369        let (_, view) = cx.add_window(Default::default(), |cx| {
6370            build_editor(multibuffer, settings, cx)
6371        });
6372        view.update(cx, |view, cx| {
6373            view.select_display_ranges(
6374                &[
6375                    DisplayPoint::new(1, 1)..DisplayPoint::new(1, 1),
6376                    DisplayPoint::new(2, 3)..DisplayPoint::new(2, 3),
6377                ],
6378                cx,
6379            );
6380
6381            view.handle_input(&Input("X".to_string()), cx);
6382            assert_eq!(view.text(cx), "aaaa\nbXbbXb\nbXbbXb\ncccc");
6383            assert_eq!(
6384                view.selected_display_ranges(cx),
6385                &[
6386                    DisplayPoint::new(1, 2)..DisplayPoint::new(1, 2),
6387                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
6388                ]
6389            );
6390
6391            view.newline(&Newline, cx);
6392            assert_eq!(view.text(cx), "aaaa\nbX\nbbX\nb\nbX\nbbX\nb\ncccc");
6393            assert_eq!(
6394                view.selected_display_ranges(cx),
6395                &[
6396                    DisplayPoint::new(2, 0)..DisplayPoint::new(2, 0),
6397                    DisplayPoint::new(6, 0)..DisplayPoint::new(6, 0),
6398                ]
6399            );
6400        });
6401    }
6402
6403    #[gpui::test]
6404    fn test_refresh_selections(cx: &mut gpui::MutableAppContext) {
6405        let settings = EditorSettings::test(cx);
6406        let buffer = cx.add_model(|cx| Buffer::new(0, sample_text(3, 4, 'a'), cx));
6407        let mut excerpt1_id = None;
6408        let multibuffer = cx.add_model(|cx| {
6409            let mut multibuffer = MultiBuffer::new(0);
6410            excerpt1_id = Some(multibuffer.push_excerpt(
6411                ExcerptProperties {
6412                    buffer: &buffer,
6413                    range: Point::new(0, 0)..Point::new(1, 4),
6414                },
6415                cx,
6416            ));
6417            multibuffer.push_excerpt(
6418                ExcerptProperties {
6419                    buffer: &buffer,
6420                    range: Point::new(1, 0)..Point::new(2, 4),
6421                },
6422                cx,
6423            );
6424            multibuffer
6425        });
6426        assert_eq!(
6427            multibuffer.read(cx).read(cx).text(),
6428            "aaaa\nbbbb\nbbbb\ncccc"
6429        );
6430        let (_, editor) = cx.add_window(Default::default(), |cx| {
6431            let mut editor = build_editor(multibuffer.clone(), settings, cx);
6432            editor.select_display_ranges(
6433                &[
6434                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
6435                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
6436                ],
6437                cx,
6438            );
6439            editor
6440        });
6441
6442        // Refreshing selections is a no-op when excerpts haven't changed.
6443        editor.update(cx, |editor, cx| {
6444            editor.refresh_selections(cx);
6445            assert_eq!(
6446                editor.selected_display_ranges(cx),
6447                [
6448                    DisplayPoint::new(1, 3)..DisplayPoint::new(1, 3),
6449                    DisplayPoint::new(2, 1)..DisplayPoint::new(2, 1),
6450                ]
6451            );
6452        });
6453
6454        multibuffer.update(cx, |multibuffer, cx| {
6455            multibuffer.remove_excerpts([&excerpt1_id.unwrap()], cx);
6456        });
6457        editor.update(cx, |editor, cx| {
6458            // Removing an excerpt causes the first selection to become degenerate.
6459            assert_eq!(
6460                editor.selected_display_ranges(cx),
6461                [
6462                    DisplayPoint::new(0, 0)..DisplayPoint::new(0, 0),
6463                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1)
6464                ]
6465            );
6466
6467            // Refreshing selections will relocate the first selection to the original buffer
6468            // location.
6469            editor.refresh_selections(cx);
6470            assert_eq!(
6471                editor.selected_display_ranges(cx),
6472                [
6473                    DisplayPoint::new(0, 1)..DisplayPoint::new(0, 1),
6474                    DisplayPoint::new(0, 3)..DisplayPoint::new(0, 3)
6475                ]
6476            );
6477        });
6478    }
6479
6480    #[gpui::test]
6481    async fn test_extra_newline_insertion(mut cx: gpui::TestAppContext) {
6482        let settings = cx.read(EditorSettings::test);
6483        let language = Arc::new(Language::new(
6484            LanguageConfig {
6485                brackets: vec![
6486                    BracketPair {
6487                        start: "{".to_string(),
6488                        end: "}".to_string(),
6489                        close: true,
6490                        newline: true,
6491                    },
6492                    BracketPair {
6493                        start: "/* ".to_string(),
6494                        end: " */".to_string(),
6495                        close: true,
6496                        newline: true,
6497                    },
6498                ],
6499                ..Default::default()
6500            },
6501            Some(tree_sitter_rust::language()),
6502        ));
6503
6504        let text = concat!(
6505            "{   }\n",     // Suppress rustfmt
6506            "  x\n",       //
6507            "  /*   */\n", //
6508            "x\n",         //
6509            "{{} }\n",     //
6510        );
6511
6512        let buffer = cx.add_model(|cx| Buffer::new(0, text, cx).with_language(language, cx));
6513        let buffer = cx.add_model(|cx| MultiBuffer::singleton(buffer, cx));
6514        let (_, view) = cx.add_window(|cx| build_editor(buffer, settings, cx));
6515        view.condition(&cx, |view, cx| !view.buffer.read(cx).is_parsing(cx))
6516            .await;
6517
6518        view.update(&mut cx, |view, cx| {
6519            view.select_display_ranges(
6520                &[
6521                    DisplayPoint::new(0, 2)..DisplayPoint::new(0, 3),
6522                    DisplayPoint::new(2, 5)..DisplayPoint::new(2, 5),
6523                    DisplayPoint::new(4, 4)..DisplayPoint::new(4, 4),
6524                ],
6525                cx,
6526            );
6527            view.newline(&Newline, cx);
6528
6529            assert_eq!(
6530                view.buffer().read(cx).read(cx).text(),
6531                concat!(
6532                    "{ \n",    // Suppress rustfmt
6533                    "\n",      //
6534                    "}\n",     //
6535                    "  x\n",   //
6536                    "  /* \n", //
6537                    "  \n",    //
6538                    "  */\n",  //
6539                    "x\n",     //
6540                    "{{} \n",  //
6541                    "}\n",     //
6542                )
6543            );
6544        });
6545    }
6546
6547    fn empty_range(row: usize, column: usize) -> Range<DisplayPoint> {
6548        let point = DisplayPoint::new(row as u32, column as u32);
6549        point..point
6550    }
6551
6552    fn build_editor(
6553        buffer: ModelHandle<MultiBuffer>,
6554        settings: EditorSettings,
6555        cx: &mut ViewContext<Editor>,
6556    ) -> Editor {
6557        Editor::for_buffer(buffer, Arc::new(move |_| settings.clone()), cx)
6558    }
6559}
6560
6561trait RangeExt<T> {
6562    fn sorted(&self) -> Range<T>;
6563    fn to_inclusive(&self) -> RangeInclusive<T>;
6564}
6565
6566impl<T: Ord + Clone> RangeExt<T> for Range<T> {
6567    fn sorted(&self) -> Self {
6568        cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone()
6569    }
6570
6571    fn to_inclusive(&self) -> RangeInclusive<T> {
6572        self.start.clone()..=self.end.clone()
6573    }
6574}