multi_buffer_tests.rs

   1use super::*;
   2use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind};
   3use gpui::{App, TestAppContext};
   4use indoc::indoc;
   5use language::{Buffer, Rope};
   6use parking_lot::RwLock;
   7use rand::prelude::*;
   8use settings::SettingsStore;
   9use std::env;
  10use util::test::sample_text;
  11
  12#[ctor::ctor]
  13fn init_logger() {
  14    if std::env::var("RUST_LOG").is_ok() {
  15        env_logger::init();
  16    }
  17}
  18
  19#[gpui::test]
  20fn test_empty_singleton(cx: &mut App) {
  21    let buffer = cx.new(|cx| Buffer::local("", cx));
  22    let buffer_id = buffer.read(cx).remote_id();
  23    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
  24    let snapshot = multibuffer.read(cx).snapshot(cx);
  25    assert_eq!(snapshot.text(), "");
  26    assert_eq!(
  27        snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>(),
  28        [RowInfo {
  29            buffer_id: Some(buffer_id),
  30            buffer_row: Some(0),
  31            multibuffer_row: Some(MultiBufferRow(0)),
  32            diff_status: None,
  33            expand_info: None,
  34        }]
  35    );
  36}
  37
  38#[gpui::test]
  39fn test_singleton(cx: &mut App) {
  40    let buffer = cx.new(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
  41    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
  42
  43    let snapshot = multibuffer.read(cx).snapshot(cx);
  44    assert_eq!(snapshot.text(), buffer.read(cx).text());
  45
  46    assert_eq!(
  47        snapshot
  48            .row_infos(MultiBufferRow(0))
  49            .map(|info| info.buffer_row)
  50            .collect::<Vec<_>>(),
  51        (0..buffer.read(cx).row_count())
  52            .map(Some)
  53            .collect::<Vec<_>>()
  54    );
  55    assert_consistent_line_numbers(&snapshot);
  56
  57    buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
  58    let snapshot = multibuffer.read(cx).snapshot(cx);
  59
  60    assert_eq!(snapshot.text(), buffer.read(cx).text());
  61    assert_eq!(
  62        snapshot
  63            .row_infos(MultiBufferRow(0))
  64            .map(|info| info.buffer_row)
  65            .collect::<Vec<_>>(),
  66        (0..buffer.read(cx).row_count())
  67            .map(Some)
  68            .collect::<Vec<_>>()
  69    );
  70    assert_consistent_line_numbers(&snapshot);
  71}
  72
  73#[gpui::test]
  74fn test_remote(cx: &mut App) {
  75    let host_buffer = cx.new(|cx| Buffer::local("a", cx));
  76    let guest_buffer = cx.new(|cx| {
  77        let state = host_buffer.read(cx).to_proto(cx);
  78        let ops = cx
  79            .background_executor()
  80            .block(host_buffer.read(cx).serialize_ops(None, cx));
  81        let mut buffer = Buffer::from_proto(1, Capability::ReadWrite, state, None).unwrap();
  82        buffer.apply_ops(
  83            ops.into_iter()
  84                .map(|op| language::proto::deserialize_operation(op).unwrap()),
  85            cx,
  86        );
  87        buffer
  88    });
  89    let multibuffer = cx.new(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
  90    let snapshot = multibuffer.read(cx).snapshot(cx);
  91    assert_eq!(snapshot.text(), "a");
  92
  93    guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
  94    let snapshot = multibuffer.read(cx).snapshot(cx);
  95    assert_eq!(snapshot.text(), "ab");
  96
  97    guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
  98    let snapshot = multibuffer.read(cx).snapshot(cx);
  99    assert_eq!(snapshot.text(), "abc");
 100}
 101
 102#[gpui::test]
 103fn test_excerpt_boundaries_and_clipping(cx: &mut App) {
 104    let buffer_1 = cx.new(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
 105    let buffer_2 = cx.new(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
 106    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
 107
 108    let events = Arc::new(RwLock::new(Vec::<Event>::new()));
 109    multibuffer.update(cx, |_, cx| {
 110        let events = events.clone();
 111        cx.subscribe(&multibuffer, move |_, _, event, _| {
 112            if let Event::Edited { .. } = event {
 113                events.write().push(event.clone())
 114            }
 115        })
 116        .detach();
 117    });
 118
 119    let subscription = multibuffer.update(cx, |multibuffer, cx| {
 120        let subscription = multibuffer.subscribe();
 121        multibuffer.push_excerpts(
 122            buffer_1.clone(),
 123            [ExcerptRange::new(Point::new(1, 2)..Point::new(2, 5))],
 124            cx,
 125        );
 126        assert_eq!(
 127            subscription.consume().into_inner(),
 128            [Edit {
 129                old: 0..0,
 130                new: 0..10
 131            }]
 132        );
 133
 134        multibuffer.push_excerpts(
 135            buffer_1.clone(),
 136            [ExcerptRange::new(Point::new(3, 3)..Point::new(4, 4))],
 137            cx,
 138        );
 139        multibuffer.push_excerpts(
 140            buffer_2.clone(),
 141            [ExcerptRange::new(Point::new(3, 1)..Point::new(3, 3))],
 142            cx,
 143        );
 144        assert_eq!(
 145            subscription.consume().into_inner(),
 146            [Edit {
 147                old: 10..10,
 148                new: 10..22
 149            }]
 150        );
 151
 152        subscription
 153    });
 154
 155    // Adding excerpts emits an edited event.
 156    assert_eq!(
 157        events.read().as_slice(),
 158        &[
 159            Event::Edited {
 160                singleton_buffer_edited: false,
 161                edited_buffer: None,
 162            },
 163            Event::Edited {
 164                singleton_buffer_edited: false,
 165                edited_buffer: None,
 166            },
 167            Event::Edited {
 168                singleton_buffer_edited: false,
 169                edited_buffer: None,
 170            }
 171        ]
 172    );
 173
 174    let snapshot = multibuffer.read(cx).snapshot(cx);
 175    assert_eq!(
 176        snapshot.text(),
 177        indoc!(
 178            "
 179            bbbb
 180            ccccc
 181            ddd
 182            eeee
 183            jj"
 184        ),
 185    );
 186    assert_eq!(
 187        snapshot
 188            .row_infos(MultiBufferRow(0))
 189            .map(|info| info.buffer_row)
 190            .collect::<Vec<_>>(),
 191        [Some(1), Some(2), Some(3), Some(4), Some(3)]
 192    );
 193    assert_eq!(
 194        snapshot
 195            .row_infos(MultiBufferRow(2))
 196            .map(|info| info.buffer_row)
 197            .collect::<Vec<_>>(),
 198        [Some(3), Some(4), Some(3)]
 199    );
 200    assert_eq!(
 201        snapshot
 202            .row_infos(MultiBufferRow(4))
 203            .map(|info| info.buffer_row)
 204            .collect::<Vec<_>>(),
 205        [Some(3)]
 206    );
 207    assert_eq!(
 208        snapshot
 209            .row_infos(MultiBufferRow(5))
 210            .map(|info| info.buffer_row)
 211            .collect::<Vec<_>>(),
 212        []
 213    );
 214
 215    assert_eq!(
 216        boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
 217        &[
 218            (MultiBufferRow(0), "bbbb\nccccc".to_string(), true),
 219            (MultiBufferRow(2), "ddd\neeee".to_string(), false),
 220            (MultiBufferRow(4), "jj".to_string(), true),
 221        ]
 222    );
 223    assert_eq!(
 224        boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
 225        &[(MultiBufferRow(0), "bbbb\nccccc".to_string(), true)]
 226    );
 227    assert_eq!(
 228        boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
 229        &[]
 230    );
 231    assert_eq!(
 232        boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
 233        &[]
 234    );
 235    assert_eq!(
 236        boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
 237        &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
 238    );
 239    assert_eq!(
 240        boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
 241        &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
 242    );
 243    assert_eq!(
 244        boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
 245        &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
 246    );
 247    assert_eq!(
 248        boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
 249        &[(MultiBufferRow(4), "jj".to_string(), true)]
 250    );
 251    assert_eq!(
 252        boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
 253        &[]
 254    );
 255
 256    buffer_1.update(cx, |buffer, cx| {
 257        let text = "\n";
 258        buffer.edit(
 259            [
 260                (Point::new(0, 0)..Point::new(0, 0), text),
 261                (Point::new(2, 1)..Point::new(2, 3), text),
 262            ],
 263            None,
 264            cx,
 265        );
 266    });
 267
 268    let snapshot = multibuffer.read(cx).snapshot(cx);
 269    assert_eq!(
 270        snapshot.text(),
 271        concat!(
 272            "bbbb\n", // Preserve newlines
 273            "c\n",    //
 274            "cc\n",   //
 275            "ddd\n",  //
 276            "eeee\n", //
 277            "jj"      //
 278        )
 279    );
 280
 281    assert_eq!(
 282        subscription.consume().into_inner(),
 283        [Edit {
 284            old: 6..8,
 285            new: 6..7
 286        }]
 287    );
 288
 289    let snapshot = multibuffer.read(cx).snapshot(cx);
 290    assert_eq!(
 291        snapshot.clip_point(Point::new(0, 5), Bias::Left),
 292        Point::new(0, 4)
 293    );
 294    assert_eq!(
 295        snapshot.clip_point(Point::new(0, 5), Bias::Right),
 296        Point::new(0, 4)
 297    );
 298    assert_eq!(
 299        snapshot.clip_point(Point::new(5, 1), Bias::Right),
 300        Point::new(5, 1)
 301    );
 302    assert_eq!(
 303        snapshot.clip_point(Point::new(5, 2), Bias::Right),
 304        Point::new(5, 2)
 305    );
 306    assert_eq!(
 307        snapshot.clip_point(Point::new(5, 3), Bias::Right),
 308        Point::new(5, 2)
 309    );
 310
 311    let snapshot = multibuffer.update(cx, |multibuffer, cx| {
 312        let (buffer_2_excerpt_id, _) =
 313            multibuffer.excerpts_for_buffer(buffer_2.read(cx).remote_id(), cx)[0].clone();
 314        multibuffer.remove_excerpts([buffer_2_excerpt_id], cx);
 315        multibuffer.snapshot(cx)
 316    });
 317
 318    assert_eq!(
 319        snapshot.text(),
 320        concat!(
 321            "bbbb\n", // Preserve newlines
 322            "c\n",    //
 323            "cc\n",   //
 324            "ddd\n",  //
 325            "eeee",   //
 326        )
 327    );
 328
 329    fn boundaries_in_range(
 330        range: Range<Point>,
 331        snapshot: &MultiBufferSnapshot,
 332    ) -> Vec<(MultiBufferRow, String, bool)> {
 333        snapshot
 334            .excerpt_boundaries_in_range(range)
 335            .map(|boundary| {
 336                let starts_new_buffer = boundary.starts_new_buffer();
 337                (
 338                    boundary.row,
 339                    boundary
 340                        .next
 341                        .buffer
 342                        .text_for_range(boundary.next.range.context)
 343                        .collect::<String>(),
 344                    starts_new_buffer,
 345                )
 346            })
 347            .collect::<Vec<_>>()
 348    }
 349}
 350
 351#[gpui::test]
 352fn test_diff_boundary_anchors(cx: &mut TestAppContext) {
 353    let base_text = "one\ntwo\nthree\n";
 354    let text = "one\nthree\n";
 355    let buffer = cx.new(|cx| Buffer::local(text, cx));
 356    let diff = cx.new(|cx| BufferDiff::new_with_base_text(base_text, &buffer, cx));
 357    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 358    multibuffer.update(cx, |multibuffer, cx| multibuffer.add_diff(diff, cx));
 359
 360    let (before, after) = multibuffer.update(cx, |multibuffer, cx| {
 361        let before = multibuffer.snapshot(cx).anchor_before(Point::new(1, 0));
 362        let after = multibuffer.snapshot(cx).anchor_after(Point::new(1, 0));
 363        multibuffer.set_all_diff_hunks_expanded(cx);
 364        (before, after)
 365    });
 366    cx.run_until_parked();
 367
 368    let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
 369    let actual_text = snapshot.text();
 370    let actual_row_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
 371    let actual_diff = format_diff(&actual_text, &actual_row_infos, &Default::default(), None);
 372    pretty_assertions::assert_eq!(
 373        actual_diff,
 374        indoc! {
 375            "  one
 376             - two
 377               three
 378             "
 379        },
 380    );
 381
 382    multibuffer.update(cx, |multibuffer, cx| {
 383        let snapshot = multibuffer.snapshot(cx);
 384        assert_eq!(before.to_point(&snapshot), Point::new(1, 0));
 385        assert_eq!(after.to_point(&snapshot), Point::new(2, 0));
 386        assert_eq!(
 387            vec![Point::new(1, 0), Point::new(2, 0),],
 388            snapshot.summaries_for_anchors::<Point, _>(&[before, after]),
 389        )
 390    })
 391}
 392
 393#[gpui::test]
 394fn test_diff_hunks_in_range(cx: &mut TestAppContext) {
 395    let base_text = "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\n";
 396    let text = "one\nfour\nseven\n";
 397    let buffer = cx.new(|cx| Buffer::local(text, cx));
 398    let diff = cx.new(|cx| BufferDiff::new_with_base_text(base_text, &buffer, cx));
 399    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 400    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
 401        (multibuffer.snapshot(cx), multibuffer.subscribe())
 402    });
 403
 404    multibuffer.update(cx, |multibuffer, cx| {
 405        multibuffer.add_diff(diff, cx);
 406        multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
 407    });
 408
 409    assert_new_snapshot(
 410        &multibuffer,
 411        &mut snapshot,
 412        &mut subscription,
 413        cx,
 414        indoc! {
 415            "  one
 416             - two
 417             - three
 418               four
 419             - five
 420             - six
 421               seven
 422             - eight
 423            "
 424        },
 425    );
 426
 427    assert_eq!(
 428        snapshot
 429            .diff_hunks_in_range(Point::new(1, 0)..Point::MAX)
 430            .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0)
 431            .collect::<Vec<_>>(),
 432        vec![1..3, 4..6, 7..8]
 433    );
 434
 435    assert_eq!(snapshot.diff_hunk_before(Point::new(1, 1)), None,);
 436    assert_eq!(
 437        snapshot.diff_hunk_before(Point::new(7, 0)),
 438        Some(MultiBufferRow(4))
 439    );
 440    assert_eq!(
 441        snapshot.diff_hunk_before(Point::new(4, 0)),
 442        Some(MultiBufferRow(1))
 443    );
 444
 445    multibuffer.update(cx, |multibuffer, cx| {
 446        multibuffer.collapse_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
 447    });
 448
 449    assert_new_snapshot(
 450        &multibuffer,
 451        &mut snapshot,
 452        &mut subscription,
 453        cx,
 454        indoc! {
 455            "
 456            one
 457            four
 458            seven
 459            "
 460        },
 461    );
 462
 463    assert_eq!(
 464        snapshot.diff_hunk_before(Point::new(2, 0)),
 465        Some(MultiBufferRow(1)),
 466    );
 467    assert_eq!(
 468        snapshot.diff_hunk_before(Point::new(4, 0)),
 469        Some(MultiBufferRow(2))
 470    );
 471}
 472
 473#[gpui::test]
 474fn test_editing_text_in_diff_hunks(cx: &mut TestAppContext) {
 475    let base_text = "one\ntwo\nfour\nfive\nsix\nseven\n";
 476    let text = "one\ntwo\nTHREE\nfour\nfive\nseven\n";
 477    let buffer = cx.new(|cx| Buffer::local(text, cx));
 478    let diff = cx.new(|cx| BufferDiff::new_with_base_text(&base_text, &buffer, cx));
 479    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
 480
 481    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
 482        multibuffer.add_diff(diff.clone(), cx);
 483        (multibuffer.snapshot(cx), multibuffer.subscribe())
 484    });
 485
 486    cx.executor().run_until_parked();
 487    multibuffer.update(cx, |multibuffer, cx| {
 488        multibuffer.set_all_diff_hunks_expanded(cx);
 489    });
 490
 491    assert_new_snapshot(
 492        &multibuffer,
 493        &mut snapshot,
 494        &mut subscription,
 495        cx,
 496        indoc! {
 497            "
 498              one
 499              two
 500            + THREE
 501              four
 502              five
 503            - six
 504              seven
 505            "
 506        },
 507    );
 508
 509    // Insert a newline within an insertion hunk
 510    multibuffer.update(cx, |multibuffer, cx| {
 511        multibuffer.edit([(Point::new(2, 0)..Point::new(2, 0), "__\n__")], None, cx);
 512    });
 513    assert_new_snapshot(
 514        &multibuffer,
 515        &mut snapshot,
 516        &mut subscription,
 517        cx,
 518        indoc! {
 519            "
 520              one
 521              two
 522            + __
 523            + __THREE
 524              four
 525              five
 526            - six
 527              seven
 528            "
 529        },
 530    );
 531
 532    // Delete the newline before a deleted hunk.
 533    multibuffer.update(cx, |multibuffer, cx| {
 534        multibuffer.edit([(Point::new(5, 4)..Point::new(6, 0), "")], None, cx);
 535    });
 536    assert_new_snapshot(
 537        &multibuffer,
 538        &mut snapshot,
 539        &mut subscription,
 540        cx,
 541        indoc! {
 542            "
 543              one
 544              two
 545            + __
 546            + __THREE
 547              four
 548              fiveseven
 549            "
 550        },
 551    );
 552
 553    multibuffer.update(cx, |multibuffer, cx| multibuffer.undo(cx));
 554    assert_new_snapshot(
 555        &multibuffer,
 556        &mut snapshot,
 557        &mut subscription,
 558        cx,
 559        indoc! {
 560            "
 561              one
 562              two
 563            + __
 564            + __THREE
 565              four
 566              five
 567            - six
 568              seven
 569            "
 570        },
 571    );
 572
 573    // Cannot (yet) insert at the beginning of a deleted hunk.
 574    // (because it would put the newline in the wrong place)
 575    multibuffer.update(cx, |multibuffer, cx| {
 576        multibuffer.edit([(Point::new(6, 0)..Point::new(6, 0), "\n")], None, cx);
 577    });
 578    assert_new_snapshot(
 579        &multibuffer,
 580        &mut snapshot,
 581        &mut subscription,
 582        cx,
 583        indoc! {
 584            "
 585              one
 586              two
 587            + __
 588            + __THREE
 589              four
 590              five
 591            - six
 592              seven
 593            "
 594        },
 595    );
 596
 597    // Replace a range that ends in a deleted hunk.
 598    multibuffer.update(cx, |multibuffer, cx| {
 599        multibuffer.edit([(Point::new(5, 2)..Point::new(6, 2), "fty-")], None, cx);
 600    });
 601    assert_new_snapshot(
 602        &multibuffer,
 603        &mut snapshot,
 604        &mut subscription,
 605        cx,
 606        indoc! {
 607            "
 608              one
 609              two
 610            + __
 611            + __THREE
 612              four
 613              fifty-seven
 614            "
 615        },
 616    );
 617}
 618
 619#[gpui::test]
 620fn test_excerpt_events(cx: &mut App) {
 621    let buffer_1 = cx.new(|cx| Buffer::local(sample_text(10, 3, 'a'), cx));
 622    let buffer_2 = cx.new(|cx| Buffer::local(sample_text(10, 3, 'm'), cx));
 623
 624    let leader_multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
 625    let follower_multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
 626    let follower_edit_event_count = Arc::new(RwLock::new(0));
 627
 628    follower_multibuffer.update(cx, |_, cx| {
 629        let follower_edit_event_count = follower_edit_event_count.clone();
 630        cx.subscribe(
 631            &leader_multibuffer,
 632            move |follower, _, event, cx| match event.clone() {
 633                Event::ExcerptsAdded {
 634                    buffer,
 635                    predecessor,
 636                    excerpts,
 637                } => follower.insert_excerpts_with_ids_after(predecessor, buffer, excerpts, cx),
 638                Event::ExcerptsRemoved { ids } => follower.remove_excerpts(ids, cx),
 639                Event::Edited { .. } => {
 640                    *follower_edit_event_count.write() += 1;
 641                }
 642                _ => {}
 643            },
 644        )
 645        .detach();
 646    });
 647
 648    leader_multibuffer.update(cx, |leader, cx| {
 649        leader.push_excerpts(
 650            buffer_1.clone(),
 651            [ExcerptRange::new(0..8), ExcerptRange::new(12..16)],
 652            cx,
 653        );
 654        leader.insert_excerpts_after(
 655            leader.excerpt_ids()[0],
 656            buffer_2.clone(),
 657            [ExcerptRange::new(0..5), ExcerptRange::new(10..15)],
 658            cx,
 659        )
 660    });
 661    assert_eq!(
 662        leader_multibuffer.read(cx).snapshot(cx).text(),
 663        follower_multibuffer.read(cx).snapshot(cx).text(),
 664    );
 665    assert_eq!(*follower_edit_event_count.read(), 2);
 666
 667    leader_multibuffer.update(cx, |leader, cx| {
 668        let excerpt_ids = leader.excerpt_ids();
 669        leader.remove_excerpts([excerpt_ids[1], excerpt_ids[3]], cx);
 670    });
 671    assert_eq!(
 672        leader_multibuffer.read(cx).snapshot(cx).text(),
 673        follower_multibuffer.read(cx).snapshot(cx).text(),
 674    );
 675    assert_eq!(*follower_edit_event_count.read(), 3);
 676
 677    // Removing an empty set of excerpts is a noop.
 678    leader_multibuffer.update(cx, |leader, cx| {
 679        leader.remove_excerpts([], cx);
 680    });
 681    assert_eq!(
 682        leader_multibuffer.read(cx).snapshot(cx).text(),
 683        follower_multibuffer.read(cx).snapshot(cx).text(),
 684    );
 685    assert_eq!(*follower_edit_event_count.read(), 3);
 686
 687    // Adding an empty set of excerpts is a noop.
 688    leader_multibuffer.update(cx, |leader, cx| {
 689        leader.push_excerpts::<usize>(buffer_2.clone(), [], cx);
 690    });
 691    assert_eq!(
 692        leader_multibuffer.read(cx).snapshot(cx).text(),
 693        follower_multibuffer.read(cx).snapshot(cx).text(),
 694    );
 695    assert_eq!(*follower_edit_event_count.read(), 3);
 696
 697    leader_multibuffer.update(cx, |leader, cx| {
 698        leader.clear(cx);
 699    });
 700    assert_eq!(
 701        leader_multibuffer.read(cx).snapshot(cx).text(),
 702        follower_multibuffer.read(cx).snapshot(cx).text(),
 703    );
 704    assert_eq!(*follower_edit_event_count.read(), 4);
 705}
 706
 707#[gpui::test]
 708fn test_expand_excerpts(cx: &mut App) {
 709    let buffer = cx.new(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
 710    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
 711
 712    multibuffer.update(cx, |multibuffer, cx| {
 713        multibuffer.set_excerpts_for_path(
 714            PathKey::for_buffer(&buffer, cx),
 715            buffer,
 716            vec![
 717                // Note that in this test, this first excerpt
 718                // does not contain a new line
 719                Point::new(3, 2)..Point::new(3, 3),
 720                Point::new(7, 1)..Point::new(7, 3),
 721                Point::new(15, 0)..Point::new(15, 0),
 722            ],
 723            1,
 724            cx,
 725        )
 726    });
 727
 728    let snapshot = multibuffer.read(cx).snapshot(cx);
 729
 730    assert_eq!(
 731        snapshot.text(),
 732        concat!(
 733            "ccc\n", //
 734            "ddd\n", //
 735            "eee",   //
 736            "\n",    // End of excerpt
 737            "ggg\n", //
 738            "hhh\n", //
 739            "iii",   //
 740            "\n",    // End of excerpt
 741            "ooo\n", //
 742            "ppp\n", //
 743            "qqq",   // End of excerpt
 744        )
 745    );
 746    drop(snapshot);
 747
 748    multibuffer.update(cx, |multibuffer, cx| {
 749        multibuffer.expand_excerpts(
 750            multibuffer.excerpt_ids(),
 751            1,
 752            ExpandExcerptDirection::UpAndDown,
 753            cx,
 754        )
 755    });
 756
 757    let snapshot = multibuffer.read(cx).snapshot(cx);
 758
 759    // Expanding context lines causes the line containing 'fff' to appear in two different excerpts.
 760    // We don't attempt to merge them, because removing the excerpt could create inconsistency with other layers
 761    // that are tracking excerpt ids.
 762    assert_eq!(
 763        snapshot.text(),
 764        concat!(
 765            "bbb\n", //
 766            "ccc\n", //
 767            "ddd\n", //
 768            "eee\n", //
 769            "fff\n", //
 770            "ggg\n", //
 771            "hhh\n", //
 772            "iii\n", //
 773            "jjj\n", // End of excerpt
 774            "nnn\n", //
 775            "ooo\n", //
 776            "ppp\n", //
 777            "qqq\n", //
 778            "rrr",   // End of excerpt
 779        )
 780    );
 781}
 782
 783#[gpui::test(iterations = 100)]
 784async fn test_push_multiple_excerpts_with_context_lines(cx: &mut TestAppContext) {
 785    let buffer_1 = cx.new(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
 786    let buffer_2 = cx.new(|cx| Buffer::local(sample_text(15, 4, 'a'), cx));
 787    let snapshot_1 = buffer_1.update(cx, |buffer, _| buffer.snapshot());
 788    let snapshot_2 = buffer_2.update(cx, |buffer, _| buffer.snapshot());
 789    let ranges_1 = vec![
 790        snapshot_1.anchor_before(Point::new(3, 2))..snapshot_1.anchor_before(Point::new(4, 2)),
 791        snapshot_1.anchor_before(Point::new(7, 1))..snapshot_1.anchor_before(Point::new(7, 3)),
 792        snapshot_1.anchor_before(Point::new(15, 0))..snapshot_1.anchor_before(Point::new(15, 0)),
 793    ];
 794    let ranges_2 = vec![
 795        snapshot_2.anchor_before(Point::new(2, 1))..snapshot_2.anchor_before(Point::new(3, 1)),
 796        snapshot_2.anchor_before(Point::new(10, 0))..snapshot_2.anchor_before(Point::new(10, 2)),
 797    ];
 798
 799    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
 800    let anchor_ranges = multibuffer
 801        .update(cx, |multibuffer, cx| {
 802            multibuffer.push_multiple_excerpts_with_context_lines(
 803                vec![(buffer_1.clone(), ranges_1), (buffer_2.clone(), ranges_2)],
 804                2,
 805                cx,
 806            )
 807        })
 808        .await;
 809
 810    let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
 811    assert_eq!(
 812        snapshot.text(),
 813        concat!(
 814            "bbb\n", // buffer_1
 815            "ccc\n", //
 816            "ddd\n", // <-- excerpt 1
 817            "eee\n", // <-- excerpt 1
 818            "fff\n", //
 819            "ggg\n", //
 820            "hhh\n", // <-- excerpt 2
 821            "iii\n", //
 822            "jjj\n", //
 823            //
 824            "nnn\n", //
 825            "ooo\n", //
 826            "ppp\n", // <-- excerpt 3
 827            "qqq\n", //
 828            "rrr\n", //
 829            //
 830            "aaaa\n", // buffer 2
 831            "bbbb\n", //
 832            "cccc\n", // <-- excerpt 4
 833            "dddd\n", // <-- excerpt 4
 834            "eeee\n", //
 835            "ffff\n", //
 836            //
 837            "iiii\n", //
 838            "jjjj\n", //
 839            "kkkk\n", // <-- excerpt 5
 840            "llll\n", //
 841            "mmmm",   //
 842        )
 843    );
 844
 845    assert_eq!(
 846        anchor_ranges
 847            .iter()
 848            .map(|range| range.to_point(&snapshot))
 849            .collect::<Vec<_>>(),
 850        vec![
 851            Point::new(2, 2)..Point::new(3, 2),
 852            Point::new(6, 1)..Point::new(6, 3),
 853            Point::new(11, 0)..Point::new(11, 0),
 854            Point::new(16, 1)..Point::new(17, 1),
 855            Point::new(22, 0)..Point::new(22, 2)
 856        ]
 857    );
 858}
 859
 860#[gpui::test]
 861fn test_empty_multibuffer(cx: &mut App) {
 862    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
 863
 864    let snapshot = multibuffer.read(cx).snapshot(cx);
 865    assert_eq!(snapshot.text(), "");
 866    assert_eq!(
 867        snapshot
 868            .row_infos(MultiBufferRow(0))
 869            .map(|info| info.buffer_row)
 870            .collect::<Vec<_>>(),
 871        &[Some(0)]
 872    );
 873    assert_eq!(
 874        snapshot
 875            .row_infos(MultiBufferRow(1))
 876            .map(|info| info.buffer_row)
 877            .collect::<Vec<_>>(),
 878        &[]
 879    );
 880}
 881
 882#[gpui::test]
 883fn test_empty_diff_excerpt(cx: &mut TestAppContext) {
 884    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
 885    let buffer = cx.new(|cx| Buffer::local("", cx));
 886    let base_text = "a\nb\nc";
 887
 888    let diff = cx.new(|cx| BufferDiff::new_with_base_text(base_text, &buffer, cx));
 889    multibuffer.update(cx, |multibuffer, cx| {
 890        multibuffer.push_excerpts(buffer.clone(), [ExcerptRange::new(0..0)], cx);
 891        multibuffer.set_all_diff_hunks_expanded(cx);
 892        multibuffer.add_diff(diff.clone(), cx);
 893    });
 894    cx.run_until_parked();
 895
 896    let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
 897    assert_eq!(snapshot.text(), "a\nb\nc\n");
 898
 899    let hunk = snapshot
 900        .diff_hunks_in_range(Point::new(1, 1)..Point::new(1, 1))
 901        .next()
 902        .unwrap();
 903
 904    assert_eq!(hunk.diff_base_byte_range.start, 0);
 905
 906    let buf2 = cx.new(|cx| Buffer::local("X", cx));
 907    multibuffer.update(cx, |multibuffer, cx| {
 908        multibuffer.push_excerpts(buf2, [ExcerptRange::new(0..1)], cx);
 909    });
 910
 911    buffer.update(cx, |buffer, cx| {
 912        buffer.edit([(0..0, "a\nb\nc")], None, cx);
 913        diff.update(cx, |diff, cx| {
 914            diff.recalculate_diff_sync(buffer.snapshot().text, cx);
 915        });
 916        assert_eq!(buffer.text(), "a\nb\nc")
 917    });
 918    cx.run_until_parked();
 919
 920    let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
 921    assert_eq!(snapshot.text(), "a\nb\nc\nX");
 922
 923    buffer.update(cx, |buffer, cx| {
 924        buffer.undo(cx);
 925        diff.update(cx, |diff, cx| {
 926            diff.recalculate_diff_sync(buffer.snapshot().text, cx);
 927        });
 928        assert_eq!(buffer.text(), "")
 929    });
 930    cx.run_until_parked();
 931
 932    let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
 933    assert_eq!(snapshot.text(), "a\nb\nc\n\nX");
 934}
 935
 936#[gpui::test]
 937fn test_singleton_multibuffer_anchors(cx: &mut App) {
 938    let buffer = cx.new(|cx| Buffer::local("abcd", cx));
 939    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
 940    let old_snapshot = multibuffer.read(cx).snapshot(cx);
 941    buffer.update(cx, |buffer, cx| {
 942        buffer.edit([(0..0, "X")], None, cx);
 943        buffer.edit([(5..5, "Y")], None, cx);
 944    });
 945    let new_snapshot = multibuffer.read(cx).snapshot(cx);
 946
 947    assert_eq!(old_snapshot.text(), "abcd");
 948    assert_eq!(new_snapshot.text(), "XabcdY");
 949
 950    assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
 951    assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
 952    assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
 953    assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
 954}
 955
 956#[gpui::test]
 957fn test_multibuffer_anchors(cx: &mut App) {
 958    let buffer_1 = cx.new(|cx| Buffer::local("abcd", cx));
 959    let buffer_2 = cx.new(|cx| Buffer::local("efghi", cx));
 960    let multibuffer = cx.new(|cx| {
 961        let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
 962        multibuffer.push_excerpts(buffer_1.clone(), [ExcerptRange::new(0..4)], cx);
 963        multibuffer.push_excerpts(buffer_2.clone(), [ExcerptRange::new(0..5)], cx);
 964        multibuffer
 965    });
 966    let old_snapshot = multibuffer.read(cx).snapshot(cx);
 967
 968    assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
 969    assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
 970    assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
 971    assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
 972    assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
 973    assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
 974
 975    buffer_1.update(cx, |buffer, cx| {
 976        buffer.edit([(0..0, "W")], None, cx);
 977        buffer.edit([(5..5, "X")], None, cx);
 978    });
 979    buffer_2.update(cx, |buffer, cx| {
 980        buffer.edit([(0..0, "Y")], None, cx);
 981        buffer.edit([(6..6, "Z")], None, cx);
 982    });
 983    let new_snapshot = multibuffer.read(cx).snapshot(cx);
 984
 985    assert_eq!(old_snapshot.text(), "abcd\nefghi");
 986    assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
 987
 988    assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
 989    assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
 990    assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
 991    assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
 992    assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
 993    assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
 994    assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
 995    assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
 996    assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
 997    assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
 998}
 999
1000#[gpui::test]
1001fn test_resolving_anchors_after_replacing_their_excerpts(cx: &mut App) {
1002    let buffer_1 = cx.new(|cx| Buffer::local("abcd", cx));
1003    let buffer_2 = cx.new(|cx| Buffer::local("ABCDEFGHIJKLMNOP", cx));
1004    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
1005
1006    // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
1007    // Add an excerpt from buffer 1 that spans this new insertion.
1008    buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], None, cx));
1009    let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
1010        multibuffer
1011            .push_excerpts(buffer_1.clone(), [ExcerptRange::new(0..7)], cx)
1012            .pop()
1013            .unwrap()
1014    });
1015
1016    let snapshot_1 = multibuffer.read(cx).snapshot(cx);
1017    assert_eq!(snapshot_1.text(), "abcd123");
1018
1019    // Replace the buffer 1 excerpt with new excerpts from buffer 2.
1020    let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
1021        multibuffer.remove_excerpts([excerpt_id_1], cx);
1022        let mut ids = multibuffer
1023            .push_excerpts(
1024                buffer_2.clone(),
1025                [
1026                    ExcerptRange::new(0..4),
1027                    ExcerptRange::new(6..10),
1028                    ExcerptRange::new(12..16),
1029                ],
1030                cx,
1031            )
1032            .into_iter();
1033        (ids.next().unwrap(), ids.next().unwrap())
1034    });
1035    let snapshot_2 = multibuffer.read(cx).snapshot(cx);
1036    assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
1037
1038    // The old excerpt id doesn't get reused.
1039    assert_ne!(excerpt_id_2, excerpt_id_1);
1040
1041    // Resolve some anchors from the previous snapshot in the new snapshot.
1042    // The current excerpts are from a different buffer, so we don't attempt to
1043    // resolve the old text anchor in the new buffer.
1044    assert_eq!(
1045        snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
1046        0
1047    );
1048    assert_eq!(
1049        snapshot_2.summaries_for_anchors::<usize, _>(&[
1050            snapshot_1.anchor_before(2),
1051            snapshot_1.anchor_after(3)
1052        ]),
1053        vec![0, 0]
1054    );
1055
1056    // Refresh anchors from the old snapshot. The return value indicates that both
1057    // anchors lost their original excerpt.
1058    let refresh =
1059        snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
1060    assert_eq!(
1061        refresh,
1062        &[
1063            (0, snapshot_2.anchor_before(0), false),
1064            (1, snapshot_2.anchor_after(0), false),
1065        ]
1066    );
1067
1068    // Replace the middle excerpt with a smaller excerpt in buffer 2,
1069    // that intersects the old excerpt.
1070    let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
1071        multibuffer.remove_excerpts([excerpt_id_3], cx);
1072        multibuffer
1073            .insert_excerpts_after(
1074                excerpt_id_2,
1075                buffer_2.clone(),
1076                [ExcerptRange::new(5..8)],
1077                cx,
1078            )
1079            .pop()
1080            .unwrap()
1081    });
1082
1083    let snapshot_3 = multibuffer.read(cx).snapshot(cx);
1084    assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
1085    assert_ne!(excerpt_id_5, excerpt_id_3);
1086
1087    // Resolve some anchors from the previous snapshot in the new snapshot.
1088    // The third anchor can't be resolved, since its excerpt has been removed,
1089    // so it resolves to the same position as its predecessor.
1090    let anchors = [
1091        snapshot_2.anchor_before(0),
1092        snapshot_2.anchor_after(2),
1093        snapshot_2.anchor_after(6),
1094        snapshot_2.anchor_after(14),
1095    ];
1096    assert_eq!(
1097        snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
1098        &[0, 2, 9, 13]
1099    );
1100
1101    let new_anchors = snapshot_3.refresh_anchors(&anchors);
1102    assert_eq!(
1103        new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
1104        &[(0, true), (1, true), (2, true), (3, true)]
1105    );
1106    assert_eq!(
1107        snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
1108        &[0, 2, 7, 13]
1109    );
1110}
1111
1112#[gpui::test]
1113fn test_basic_diff_hunks(cx: &mut TestAppContext) {
1114    let text = indoc!(
1115        "
1116        ZERO
1117        one
1118        TWO
1119        three
1120        six
1121        "
1122    );
1123    let base_text = indoc!(
1124        "
1125        one
1126        two
1127        three
1128        four
1129        five
1130        six
1131        "
1132    );
1133
1134    let buffer = cx.new(|cx| Buffer::local(text, cx));
1135    let diff = cx.new(|cx| BufferDiff::new_with_base_text(base_text, &buffer, cx));
1136    cx.run_until_parked();
1137
1138    let multibuffer = cx.new(|cx| {
1139        let mut multibuffer = MultiBuffer::singleton(buffer.clone(), cx);
1140        multibuffer.add_diff(diff.clone(), cx);
1141        multibuffer
1142    });
1143
1144    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
1145        (multibuffer.snapshot(cx), multibuffer.subscribe())
1146    });
1147    assert_eq!(
1148        snapshot.text(),
1149        indoc!(
1150            "
1151            ZERO
1152            one
1153            TWO
1154            three
1155            six
1156            "
1157        ),
1158    );
1159
1160    multibuffer.update(cx, |multibuffer, cx| {
1161        multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
1162    });
1163
1164    assert_new_snapshot(
1165        &multibuffer,
1166        &mut snapshot,
1167        &mut subscription,
1168        cx,
1169        indoc!(
1170            "
1171            + ZERO
1172              one
1173            - two
1174            + TWO
1175              three
1176            - four
1177            - five
1178              six
1179            "
1180        ),
1181    );
1182
1183    assert_eq!(
1184        snapshot
1185            .row_infos(MultiBufferRow(0))
1186            .map(|info| (info.buffer_row, info.diff_status))
1187            .collect::<Vec<_>>(),
1188        vec![
1189            (Some(0), Some(DiffHunkStatus::added_none())),
1190            (Some(1), None),
1191            (Some(1), Some(DiffHunkStatus::deleted_none())),
1192            (Some(2), Some(DiffHunkStatus::added_none())),
1193            (Some(3), None),
1194            (Some(3), Some(DiffHunkStatus::deleted_none())),
1195            (Some(4), Some(DiffHunkStatus::deleted_none())),
1196            (Some(4), None),
1197            (Some(5), None)
1198        ]
1199    );
1200
1201    assert_chunks_in_ranges(&snapshot);
1202    assert_consistent_line_numbers(&snapshot);
1203    assert_position_translation(&snapshot);
1204    assert_line_indents(&snapshot);
1205
1206    multibuffer.update(cx, |multibuffer, cx| {
1207        multibuffer.collapse_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
1208    });
1209    assert_new_snapshot(
1210        &multibuffer,
1211        &mut snapshot,
1212        &mut subscription,
1213        cx,
1214        indoc!(
1215            "
1216            ZERO
1217            one
1218            TWO
1219            three
1220            six
1221            "
1222        ),
1223    );
1224
1225    assert_chunks_in_ranges(&snapshot);
1226    assert_consistent_line_numbers(&snapshot);
1227    assert_position_translation(&snapshot);
1228    assert_line_indents(&snapshot);
1229
1230    // Expand the first diff hunk
1231    multibuffer.update(cx, |multibuffer, cx| {
1232        let position = multibuffer.read(cx).anchor_before(Point::new(2, 2));
1233        multibuffer.expand_diff_hunks(vec![position..position], cx)
1234    });
1235    assert_new_snapshot(
1236        &multibuffer,
1237        &mut snapshot,
1238        &mut subscription,
1239        cx,
1240        indoc!(
1241            "
1242              ZERO
1243              one
1244            - two
1245            + TWO
1246              three
1247              six
1248            "
1249        ),
1250    );
1251
1252    // Expand the second diff hunk
1253    multibuffer.update(cx, |multibuffer, cx| {
1254        let start = multibuffer.read(cx).anchor_before(Point::new(4, 0));
1255        let end = multibuffer.read(cx).anchor_before(Point::new(5, 0));
1256        multibuffer.expand_diff_hunks(vec![start..end], cx)
1257    });
1258    assert_new_snapshot(
1259        &multibuffer,
1260        &mut snapshot,
1261        &mut subscription,
1262        cx,
1263        indoc!(
1264            "
1265              ZERO
1266              one
1267            - two
1268            + TWO
1269              three
1270            - four
1271            - five
1272              six
1273            "
1274        ),
1275    );
1276
1277    assert_chunks_in_ranges(&snapshot);
1278    assert_consistent_line_numbers(&snapshot);
1279    assert_position_translation(&snapshot);
1280    assert_line_indents(&snapshot);
1281
1282    // Edit the buffer before the first hunk
1283    buffer.update(cx, |buffer, cx| {
1284        buffer.edit_via_marked_text(
1285            indoc!(
1286                "
1287                ZERO
1288                one« hundred
1289                  thousand»
1290                TWO
1291                three
1292                six
1293                "
1294            ),
1295            None,
1296            cx,
1297        );
1298    });
1299    assert_new_snapshot(
1300        &multibuffer,
1301        &mut snapshot,
1302        &mut subscription,
1303        cx,
1304        indoc!(
1305            "
1306              ZERO
1307              one hundred
1308                thousand
1309            - two
1310            + TWO
1311              three
1312            - four
1313            - five
1314              six
1315            "
1316        ),
1317    );
1318
1319    assert_chunks_in_ranges(&snapshot);
1320    assert_consistent_line_numbers(&snapshot);
1321    assert_position_translation(&snapshot);
1322    assert_line_indents(&snapshot);
1323
1324    // Recalculate the diff, changing the first diff hunk.
1325    diff.update(cx, |diff, cx| {
1326        diff.recalculate_diff_sync(buffer.read(cx).text_snapshot(), cx);
1327    });
1328    cx.run_until_parked();
1329    assert_new_snapshot(
1330        &multibuffer,
1331        &mut snapshot,
1332        &mut subscription,
1333        cx,
1334        indoc!(
1335            "
1336              ZERO
1337              one hundred
1338                thousand
1339              TWO
1340              three
1341            - four
1342            - five
1343              six
1344            "
1345        ),
1346    );
1347
1348    assert_eq!(
1349        snapshot
1350            .diff_hunks_in_range(0..snapshot.len())
1351            .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0)
1352            .collect::<Vec<_>>(),
1353        &[0..4, 5..7]
1354    );
1355}
1356
1357#[gpui::test]
1358fn test_repeatedly_expand_a_diff_hunk(cx: &mut TestAppContext) {
1359    let text = indoc!(
1360        "
1361        one
1362        TWO
1363        THREE
1364        four
1365        FIVE
1366        six
1367        "
1368    );
1369    let base_text = indoc!(
1370        "
1371        one
1372        four
1373        six
1374        "
1375    );
1376
1377    let buffer = cx.new(|cx| Buffer::local(text, cx));
1378    let diff = cx.new(|cx| BufferDiff::new_with_base_text(base_text, &buffer, cx));
1379    cx.run_until_parked();
1380
1381    let multibuffer = cx.new(|cx| {
1382        let mut multibuffer = MultiBuffer::singleton(buffer.clone(), cx);
1383        multibuffer.add_diff(diff.clone(), cx);
1384        multibuffer
1385    });
1386
1387    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
1388        (multibuffer.snapshot(cx), multibuffer.subscribe())
1389    });
1390
1391    multibuffer.update(cx, |multibuffer, cx| {
1392        multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
1393    });
1394
1395    assert_new_snapshot(
1396        &multibuffer,
1397        &mut snapshot,
1398        &mut subscription,
1399        cx,
1400        indoc!(
1401            "
1402              one
1403            + TWO
1404            + THREE
1405              four
1406            + FIVE
1407              six
1408            "
1409        ),
1410    );
1411
1412    // Regression test: expanding diff hunks that are already expanded should not change anything.
1413    multibuffer.update(cx, |multibuffer, cx| {
1414        multibuffer.expand_diff_hunks(
1415            vec![
1416                snapshot.anchor_before(Point::new(2, 0))..snapshot.anchor_before(Point::new(2, 0)),
1417            ],
1418            cx,
1419        );
1420    });
1421
1422    assert_new_snapshot(
1423        &multibuffer,
1424        &mut snapshot,
1425        &mut subscription,
1426        cx,
1427        indoc!(
1428            "
1429              one
1430            + TWO
1431            + THREE
1432              four
1433            + FIVE
1434              six
1435            "
1436        ),
1437    );
1438}
1439
1440#[gpui::test]
1441fn test_set_excerpts_for_buffer_ordering(cx: &mut TestAppContext) {
1442    let buf1 = cx.new(|cx| {
1443        Buffer::local(
1444            indoc! {
1445            "zero
1446            one
1447            two
1448            two.five
1449            three
1450            four
1451            five
1452            six
1453            seven
1454            eight
1455            nine
1456            ten
1457            eleven
1458            ",
1459            },
1460            cx,
1461        )
1462    });
1463    let path1: PathKey = PathKey::namespaced(0, Path::new("/").into());
1464
1465    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
1466    multibuffer.update(cx, |multibuffer, cx| {
1467        multibuffer.set_excerpts_for_path(
1468            path1.clone(),
1469            buf1.clone(),
1470            vec![
1471                Point::row_range(1..2),
1472                Point::row_range(6..7),
1473                Point::row_range(11..12),
1474            ],
1475            1,
1476            cx,
1477        );
1478    });
1479
1480    assert_excerpts_match(
1481        &multibuffer,
1482        cx,
1483        indoc! {
1484            "-----
1485            zero
1486            one
1487            two
1488            two.five
1489            -----
1490            four
1491            five
1492            six
1493            seven
1494            -----
1495            nine
1496            ten
1497            eleven
1498            "
1499        },
1500    );
1501
1502    buf1.update(cx, |buffer, cx| buffer.edit([(0..5, "")], None, cx));
1503
1504    multibuffer.update(cx, |multibuffer, cx| {
1505        multibuffer.set_excerpts_for_path(
1506            path1.clone(),
1507            buf1.clone(),
1508            vec![
1509                Point::row_range(0..3),
1510                Point::row_range(5..7),
1511                Point::row_range(10..11),
1512            ],
1513            1,
1514            cx,
1515        );
1516    });
1517
1518    assert_excerpts_match(
1519        &multibuffer,
1520        cx,
1521        indoc! {
1522            "-----
1523             one
1524             two
1525             two.five
1526             three
1527             four
1528             five
1529             six
1530             seven
1531             eight
1532             -----
1533             nine
1534             ten
1535             eleven
1536            "
1537        },
1538    );
1539}
1540
1541#[gpui::test]
1542fn test_set_excerpts_for_buffer(cx: &mut TestAppContext) {
1543    let buf1 = cx.new(|cx| {
1544        Buffer::local(
1545            indoc! {
1546            "zero
1547            one
1548            two
1549            three
1550            four
1551            five
1552            six
1553            seven
1554            ",
1555            },
1556            cx,
1557        )
1558    });
1559    let path1: PathKey = PathKey::namespaced(0, Path::new("/").into());
1560    let buf2 = cx.new(|cx| {
1561        Buffer::local(
1562            indoc! {
1563            "000
1564            111
1565            222
1566            333
1567            444
1568            555
1569            666
1570            777
1571            888
1572            999
1573            "
1574            },
1575            cx,
1576        )
1577    });
1578    let path2 = PathKey::namespaced(1, Path::new("/").into());
1579
1580    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
1581    multibuffer.update(cx, |multibuffer, cx| {
1582        multibuffer.set_excerpts_for_path(
1583            path1.clone(),
1584            buf1.clone(),
1585            vec![Point::row_range(0..1)],
1586            2,
1587            cx,
1588        );
1589    });
1590
1591    assert_excerpts_match(
1592        &multibuffer,
1593        cx,
1594        indoc! {
1595        "-----
1596        zero
1597        one
1598        two
1599        three
1600        "
1601        },
1602    );
1603
1604    multibuffer.update(cx, |multibuffer, cx| {
1605        multibuffer.set_excerpts_for_path(path1.clone(), buf1.clone(), vec![], 2, cx);
1606    });
1607
1608    assert_excerpts_match(&multibuffer, cx, "");
1609
1610    multibuffer.update(cx, |multibuffer, cx| {
1611        multibuffer.set_excerpts_for_path(
1612            path1.clone(),
1613            buf1.clone(),
1614            vec![Point::row_range(0..1), Point::row_range(7..8)],
1615            2,
1616            cx,
1617        );
1618    });
1619
1620    assert_excerpts_match(
1621        &multibuffer,
1622        cx,
1623        indoc! {"-----
1624                zero
1625                one
1626                two
1627                three
1628                -----
1629                five
1630                six
1631                seven
1632                "},
1633    );
1634
1635    multibuffer.update(cx, |multibuffer, cx| {
1636        multibuffer.set_excerpts_for_path(
1637            path1.clone(),
1638            buf1.clone(),
1639            vec![Point::row_range(0..1), Point::row_range(5..6)],
1640            2,
1641            cx,
1642        );
1643    });
1644
1645    assert_excerpts_match(
1646        &multibuffer,
1647        cx,
1648        indoc! {"-----
1649                    zero
1650                    one
1651                    two
1652                    three
1653                    four
1654                    five
1655                    six
1656                    seven
1657                    "},
1658    );
1659
1660    multibuffer.update(cx, |multibuffer, cx| {
1661        multibuffer.set_excerpts_for_path(
1662            path2.clone(),
1663            buf2.clone(),
1664            vec![Point::row_range(2..3)],
1665            2,
1666            cx,
1667        );
1668    });
1669
1670    assert_excerpts_match(
1671        &multibuffer,
1672        cx,
1673        indoc! {"-----
1674                zero
1675                one
1676                two
1677                three
1678                four
1679                five
1680                six
1681                seven
1682                -----
1683                000
1684                111
1685                222
1686                333
1687                444
1688                555
1689                "},
1690    );
1691
1692    multibuffer.update(cx, |multibuffer, cx| {
1693        multibuffer.set_excerpts_for_path(path1.clone(), buf1.clone(), vec![], 2, cx);
1694    });
1695
1696    multibuffer.update(cx, |multibuffer, cx| {
1697        multibuffer.set_excerpts_for_path(
1698            path1.clone(),
1699            buf1.clone(),
1700            vec![Point::row_range(3..4)],
1701            2,
1702            cx,
1703        );
1704    });
1705
1706    assert_excerpts_match(
1707        &multibuffer,
1708        cx,
1709        indoc! {"-----
1710                one
1711                two
1712                three
1713                four
1714                five
1715                six
1716                -----
1717                000
1718                111
1719                222
1720                333
1721                444
1722                555
1723                "},
1724    );
1725
1726    multibuffer.update(cx, |multibuffer, cx| {
1727        multibuffer.set_excerpts_for_path(
1728            path1.clone(),
1729            buf1.clone(),
1730            vec![Point::row_range(3..4)],
1731            2,
1732            cx,
1733        );
1734    });
1735}
1736
1737#[gpui::test]
1738fn test_diff_hunks_with_multiple_excerpts(cx: &mut TestAppContext) {
1739    let base_text_1 = indoc!(
1740        "
1741        one
1742        two
1743            three
1744        four
1745        five
1746        six
1747        "
1748    );
1749    let text_1 = indoc!(
1750        "
1751        ZERO
1752        one
1753        TWO
1754            three
1755        six
1756        "
1757    );
1758    let base_text_2 = indoc!(
1759        "
1760        seven
1761          eight
1762        nine
1763        ten
1764        eleven
1765        twelve
1766        "
1767    );
1768    let text_2 = indoc!(
1769        "
1770          eight
1771        nine
1772        eleven
1773        THIRTEEN
1774        FOURTEEN
1775        "
1776    );
1777
1778    let buffer_1 = cx.new(|cx| Buffer::local(text_1, cx));
1779    let buffer_2 = cx.new(|cx| Buffer::local(text_2, cx));
1780    let diff_1 = cx.new(|cx| BufferDiff::new_with_base_text(base_text_1, &buffer_1, cx));
1781    let diff_2 = cx.new(|cx| BufferDiff::new_with_base_text(base_text_2, &buffer_2, cx));
1782    cx.run_until_parked();
1783
1784    let multibuffer = cx.new(|cx| {
1785        let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
1786        multibuffer.push_excerpts(
1787            buffer_1.clone(),
1788            [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
1789            cx,
1790        );
1791        multibuffer.push_excerpts(
1792            buffer_2.clone(),
1793            [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
1794            cx,
1795        );
1796        multibuffer.add_diff(diff_1.clone(), cx);
1797        multibuffer.add_diff(diff_2.clone(), cx);
1798        multibuffer
1799    });
1800
1801    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
1802        (multibuffer.snapshot(cx), multibuffer.subscribe())
1803    });
1804    assert_eq!(
1805        snapshot.text(),
1806        indoc!(
1807            "
1808            ZERO
1809            one
1810            TWO
1811                three
1812            six
1813
1814              eight
1815            nine
1816            eleven
1817            THIRTEEN
1818            FOURTEEN
1819            "
1820        ),
1821    );
1822
1823    multibuffer.update(cx, |multibuffer, cx| {
1824        multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
1825    });
1826
1827    assert_new_snapshot(
1828        &multibuffer,
1829        &mut snapshot,
1830        &mut subscription,
1831        cx,
1832        indoc!(
1833            "
1834            + ZERO
1835              one
1836            - two
1837            + TWO
1838                  three
1839            - four
1840            - five
1841              six
1842
1843            - seven
1844                eight
1845              nine
1846            - ten
1847              eleven
1848            - twelve
1849            + THIRTEEN
1850            + FOURTEEN
1851            "
1852        ),
1853    );
1854
1855    let id_1 = buffer_1.read_with(cx, |buffer, _| buffer.remote_id());
1856    let id_2 = buffer_2.read_with(cx, |buffer, _| buffer.remote_id());
1857    let base_id_1 = diff_1.read_with(cx, |diff, _| diff.base_text().remote_id());
1858    let base_id_2 = diff_2.read_with(cx, |diff, _| diff.base_text().remote_id());
1859
1860    let buffer_lines = (0..=snapshot.max_row().0)
1861        .map(|row| {
1862            let (buffer, range) = snapshot.buffer_line_for_row(MultiBufferRow(row))?;
1863            Some((
1864                buffer.remote_id(),
1865                buffer.text_for_range(range).collect::<String>(),
1866            ))
1867        })
1868        .collect::<Vec<_>>();
1869    pretty_assertions::assert_eq!(
1870        buffer_lines,
1871        [
1872            Some((id_1, "ZERO".into())),
1873            Some((id_1, "one".into())),
1874            Some((base_id_1, "two".into())),
1875            Some((id_1, "TWO".into())),
1876            Some((id_1, "    three".into())),
1877            Some((base_id_1, "four".into())),
1878            Some((base_id_1, "five".into())),
1879            Some((id_1, "six".into())),
1880            Some((id_1, "".into())),
1881            Some((base_id_2, "seven".into())),
1882            Some((id_2, "  eight".into())),
1883            Some((id_2, "nine".into())),
1884            Some((base_id_2, "ten".into())),
1885            Some((id_2, "eleven".into())),
1886            Some((base_id_2, "twelve".into())),
1887            Some((id_2, "THIRTEEN".into())),
1888            Some((id_2, "FOURTEEN".into())),
1889            Some((id_2, "".into())),
1890        ]
1891    );
1892
1893    let buffer_ids_by_range = [
1894        (Point::new(0, 0)..Point::new(0, 0), &[id_1] as &[_]),
1895        (Point::new(0, 0)..Point::new(2, 0), &[id_1]),
1896        (Point::new(2, 0)..Point::new(2, 0), &[id_1]),
1897        (Point::new(3, 0)..Point::new(3, 0), &[id_1]),
1898        (Point::new(8, 0)..Point::new(9, 0), &[id_1]),
1899        (Point::new(8, 0)..Point::new(10, 0), &[id_1, id_2]),
1900        (Point::new(9, 0)..Point::new(9, 0), &[id_2]),
1901    ];
1902    for (range, buffer_ids) in buffer_ids_by_range {
1903        assert_eq!(
1904            snapshot
1905                .buffer_ids_for_range(range.clone())
1906                .collect::<Vec<_>>(),
1907            buffer_ids,
1908            "buffer_ids_for_range({range:?}"
1909        );
1910    }
1911
1912    assert_position_translation(&snapshot);
1913    assert_line_indents(&snapshot);
1914
1915    assert_eq!(
1916        snapshot
1917            .diff_hunks_in_range(0..snapshot.len())
1918            .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0)
1919            .collect::<Vec<_>>(),
1920        &[0..1, 2..4, 5..7, 9..10, 12..13, 14..17]
1921    );
1922
1923    buffer_2.update(cx, |buffer, cx| {
1924        buffer.edit_via_marked_text(
1925            indoc!(
1926                "
1927                  eight
1928                «»eleven
1929                THIRTEEN
1930                FOURTEEN
1931                "
1932            ),
1933            None,
1934            cx,
1935        );
1936    });
1937
1938    assert_new_snapshot(
1939        &multibuffer,
1940        &mut snapshot,
1941        &mut subscription,
1942        cx,
1943        indoc!(
1944            "
1945            + ZERO
1946              one
1947            - two
1948            + TWO
1949                  three
1950            - four
1951            - five
1952              six
1953
1954            - seven
1955                eight
1956              eleven
1957            - twelve
1958            + THIRTEEN
1959            + FOURTEEN
1960            "
1961        ),
1962    );
1963
1964    assert_line_indents(&snapshot);
1965}
1966
1967/// A naive implementation of a multi-buffer that does not maintain
1968/// any derived state, used for comparison in a randomized test.
1969#[derive(Default)]
1970struct ReferenceMultibuffer {
1971    excerpts: Vec<ReferenceExcerpt>,
1972    diffs: HashMap<BufferId, Entity<BufferDiff>>,
1973}
1974
1975#[derive(Debug)]
1976struct ReferenceExcerpt {
1977    id: ExcerptId,
1978    buffer: Entity<Buffer>,
1979    range: Range<text::Anchor>,
1980    expanded_diff_hunks: Vec<text::Anchor>,
1981}
1982
1983#[derive(Debug)]
1984struct ReferenceRegion {
1985    buffer_id: Option<BufferId>,
1986    range: Range<usize>,
1987    buffer_start: Option<Point>,
1988    status: Option<DiffHunkStatus>,
1989    excerpt_id: Option<ExcerptId>,
1990}
1991
1992impl ReferenceMultibuffer {
1993    fn expand_excerpts(&mut self, excerpts: &HashSet<ExcerptId>, line_count: u32, cx: &App) {
1994        if line_count == 0 {
1995            return;
1996        }
1997
1998        for id in excerpts {
1999            let excerpt = self.excerpts.iter_mut().find(|e| e.id == *id).unwrap();
2000            let snapshot = excerpt.buffer.read(cx).snapshot();
2001            let mut point_range = excerpt.range.to_point(&snapshot);
2002            point_range.start = Point::new(point_range.start.row.saturating_sub(line_count), 0);
2003            point_range.end =
2004                snapshot.clip_point(Point::new(point_range.end.row + line_count, 0), Bias::Left);
2005            point_range.end.column = snapshot.line_len(point_range.end.row);
2006            excerpt.range =
2007                snapshot.anchor_before(point_range.start)..snapshot.anchor_after(point_range.end);
2008        }
2009    }
2010
2011    fn remove_excerpt(&mut self, id: ExcerptId, cx: &App) {
2012        let ix = self
2013            .excerpts
2014            .iter()
2015            .position(|excerpt| excerpt.id == id)
2016            .unwrap();
2017        let excerpt = self.excerpts.remove(ix);
2018        let buffer = excerpt.buffer.read(cx);
2019        let id = buffer.remote_id();
2020        log::info!(
2021            "Removing excerpt {}: {:?}",
2022            ix,
2023            buffer
2024                .text_for_range(excerpt.range.to_offset(buffer))
2025                .collect::<String>(),
2026        );
2027        if !self
2028            .excerpts
2029            .iter()
2030            .any(|excerpt| excerpt.buffer.read(cx).remote_id() == id)
2031        {
2032            self.diffs.remove(&id);
2033        }
2034    }
2035
2036    fn insert_excerpt_after(
2037        &mut self,
2038        prev_id: ExcerptId,
2039        new_excerpt_id: ExcerptId,
2040        (buffer_handle, anchor_range): (Entity<Buffer>, Range<text::Anchor>),
2041    ) {
2042        let excerpt_ix = if prev_id == ExcerptId::max() {
2043            self.excerpts.len()
2044        } else {
2045            self.excerpts
2046                .iter()
2047                .position(|excerpt| excerpt.id == prev_id)
2048                .unwrap()
2049                + 1
2050        };
2051        self.excerpts.insert(
2052            excerpt_ix,
2053            ReferenceExcerpt {
2054                id: new_excerpt_id,
2055                buffer: buffer_handle,
2056                range: anchor_range,
2057                expanded_diff_hunks: Vec::new(),
2058            },
2059        );
2060    }
2061
2062    fn expand_diff_hunks(&mut self, excerpt_id: ExcerptId, range: Range<text::Anchor>, cx: &App) {
2063        let excerpt = self
2064            .excerpts
2065            .iter_mut()
2066            .find(|e| e.id == excerpt_id)
2067            .unwrap();
2068        let buffer = excerpt.buffer.read(cx).snapshot();
2069        let buffer_id = buffer.remote_id();
2070        let Some(diff) = self.diffs.get(&buffer_id) else {
2071            return;
2072        };
2073        let excerpt_range = excerpt.range.to_offset(&buffer);
2074        for hunk in diff.read(cx).hunks_intersecting_range(range, &buffer, cx) {
2075            let hunk_range = hunk.buffer_range.to_offset(&buffer);
2076            if hunk_range.start < excerpt_range.start || hunk_range.start > excerpt_range.end {
2077                continue;
2078            }
2079            if let Err(ix) = excerpt
2080                .expanded_diff_hunks
2081                .binary_search_by(|anchor| anchor.cmp(&hunk.buffer_range.start, &buffer))
2082            {
2083                log::info!(
2084                    "expanding diff hunk {:?}. excerpt:{:?}, excerpt range:{:?}",
2085                    hunk_range,
2086                    excerpt_id,
2087                    excerpt_range
2088                );
2089                excerpt
2090                    .expanded_diff_hunks
2091                    .insert(ix, hunk.buffer_range.start);
2092            } else {
2093                log::trace!("hunk {hunk_range:?} already expanded in excerpt {excerpt_id:?}");
2094            }
2095        }
2096    }
2097
2098    fn expected_content(&self, cx: &App) -> (String, Vec<RowInfo>, HashSet<MultiBufferRow>) {
2099        let mut text = String::new();
2100        let mut regions = Vec::<ReferenceRegion>::new();
2101        let mut excerpt_boundary_rows = HashSet::default();
2102        for excerpt in &self.excerpts {
2103            excerpt_boundary_rows.insert(MultiBufferRow(text.matches('\n').count() as u32));
2104            let buffer = excerpt.buffer.read(cx);
2105            let buffer_range = excerpt.range.to_offset(buffer);
2106            let diff = self.diffs.get(&buffer.remote_id()).unwrap().read(cx);
2107            let base_buffer = diff.base_text();
2108
2109            let mut offset = buffer_range.start;
2110            let mut hunks = diff
2111                .hunks_intersecting_range(excerpt.range.clone(), buffer, cx)
2112                .peekable();
2113
2114            while let Some(hunk) = hunks.next() {
2115                // Ignore hunks that are outside the excerpt range.
2116                let mut hunk_range = hunk.buffer_range.to_offset(buffer);
2117
2118                hunk_range.end = hunk_range.end.min(buffer_range.end);
2119                if hunk_range.start > buffer_range.end || hunk_range.start < buffer_range.start {
2120                    log::trace!("skipping hunk outside excerpt range");
2121                    continue;
2122                }
2123
2124                if !excerpt.expanded_diff_hunks.iter().any(|expanded_anchor| {
2125                    expanded_anchor.to_offset(&buffer).max(buffer_range.start)
2126                        == hunk_range.start.max(buffer_range.start)
2127                }) {
2128                    log::trace!("skipping a hunk that's not marked as expanded");
2129                    continue;
2130                }
2131
2132                if !hunk.buffer_range.start.is_valid(&buffer) {
2133                    log::trace!("skipping hunk with deleted start: {:?}", hunk.range);
2134                    continue;
2135                }
2136
2137                if hunk_range.start >= offset {
2138                    // Add the buffer text before the hunk
2139                    let len = text.len();
2140                    text.extend(buffer.text_for_range(offset..hunk_range.start));
2141                    regions.push(ReferenceRegion {
2142                        buffer_id: Some(buffer.remote_id()),
2143                        range: len..text.len(),
2144                        buffer_start: Some(buffer.offset_to_point(offset)),
2145                        status: None,
2146                        excerpt_id: Some(excerpt.id),
2147                    });
2148
2149                    // Add the deleted text for the hunk.
2150                    if !hunk.diff_base_byte_range.is_empty() {
2151                        let mut base_text = base_buffer
2152                            .text_for_range(hunk.diff_base_byte_range.clone())
2153                            .collect::<String>();
2154                        if !base_text.ends_with('\n') {
2155                            base_text.push('\n');
2156                        }
2157                        let len = text.len();
2158                        text.push_str(&base_text);
2159                        regions.push(ReferenceRegion {
2160                            buffer_id: Some(base_buffer.remote_id()),
2161                            range: len..text.len(),
2162                            buffer_start: Some(
2163                                base_buffer.offset_to_point(hunk.diff_base_byte_range.start),
2164                            ),
2165                            status: Some(DiffHunkStatus::deleted(hunk.secondary_status)),
2166                            excerpt_id: Some(excerpt.id),
2167                        });
2168                    }
2169
2170                    offset = hunk_range.start;
2171                }
2172
2173                // Add the inserted text for the hunk.
2174                if hunk_range.end > offset {
2175                    let len = text.len();
2176                    text.extend(buffer.text_for_range(offset..hunk_range.end));
2177                    regions.push(ReferenceRegion {
2178                        buffer_id: Some(buffer.remote_id()),
2179                        range: len..text.len(),
2180                        buffer_start: Some(buffer.offset_to_point(offset)),
2181                        status: Some(DiffHunkStatus::added(hunk.secondary_status)),
2182                        excerpt_id: Some(excerpt.id),
2183                    });
2184                    offset = hunk_range.end;
2185                }
2186            }
2187
2188            // Add the buffer text for the rest of the excerpt.
2189            let len = text.len();
2190            text.extend(buffer.text_for_range(offset..buffer_range.end));
2191            text.push('\n');
2192            regions.push(ReferenceRegion {
2193                buffer_id: Some(buffer.remote_id()),
2194                range: len..text.len(),
2195                buffer_start: Some(buffer.offset_to_point(offset)),
2196                status: None,
2197                excerpt_id: Some(excerpt.id),
2198            });
2199        }
2200
2201        // Remove final trailing newline.
2202        if self.excerpts.is_empty() {
2203            regions.push(ReferenceRegion {
2204                buffer_id: None,
2205                range: 0..1,
2206                buffer_start: Some(Point::new(0, 0)),
2207                status: None,
2208                excerpt_id: None,
2209            });
2210        } else {
2211            text.pop();
2212        }
2213
2214        // Retrieve the row info using the region that contains
2215        // the start of each multi-buffer line.
2216        let mut ix = 0;
2217        let row_infos = text
2218            .split('\n')
2219            .map(|line| {
2220                let row_info = regions
2221                    .iter()
2222                    .position(|region| region.range.contains(&ix))
2223                    .map_or(RowInfo::default(), |region_ix| {
2224                        let region = &regions[region_ix];
2225                        let buffer_row = region.buffer_start.map(|start_point| {
2226                            start_point.row
2227                                + text[region.range.start..ix].matches('\n').count() as u32
2228                        });
2229                        let is_excerpt_start = region_ix == 0
2230                            || &regions[region_ix - 1].excerpt_id != &region.excerpt_id
2231                            || regions[region_ix - 1].range.is_empty();
2232                        let mut is_excerpt_end = region_ix == regions.len() - 1
2233                            || &regions[region_ix + 1].excerpt_id != &region.excerpt_id;
2234                        let is_start = !text[region.range.start..ix].contains('\n');
2235                        let mut is_end = if region.range.end > text.len() {
2236                            !text[ix..].contains('\n')
2237                        } else {
2238                            text[ix..region.range.end.min(text.len())]
2239                                .matches('\n')
2240                                .count()
2241                                == 1
2242                        };
2243                        if region_ix < regions.len() - 1
2244                            && !text[ix..].contains("\n")
2245                            && region.status == Some(DiffHunkStatus::added_none())
2246                            && regions[region_ix + 1].excerpt_id == region.excerpt_id
2247                            && regions[region_ix + 1].range.start == text.len()
2248                        {
2249                            is_end = true;
2250                            is_excerpt_end = true;
2251                        }
2252                        let mut expand_direction = None;
2253                        if let Some(buffer) = &self
2254                            .excerpts
2255                            .iter()
2256                            .find(|e| e.id == region.excerpt_id.unwrap())
2257                            .map(|e| e.buffer.clone())
2258                        {
2259                            let needs_expand_up =
2260                                is_excerpt_start && is_start && buffer_row.unwrap() > 0;
2261                            let needs_expand_down = is_excerpt_end
2262                                && is_end
2263                                && buffer.read(cx).max_point().row > buffer_row.unwrap();
2264                            expand_direction = if needs_expand_up && needs_expand_down {
2265                                Some(ExpandExcerptDirection::UpAndDown)
2266                            } else if needs_expand_up {
2267                                Some(ExpandExcerptDirection::Up)
2268                            } else if needs_expand_down {
2269                                Some(ExpandExcerptDirection::Down)
2270                            } else {
2271                                None
2272                            };
2273                        }
2274                        RowInfo {
2275                            buffer_id: region.buffer_id,
2276                            diff_status: region.status,
2277                            buffer_row,
2278                            multibuffer_row: Some(MultiBufferRow(
2279                                text[..ix].matches('\n').count() as u32
2280                            )),
2281                            expand_info: expand_direction.zip(region.excerpt_id).map(
2282                                |(direction, excerpt_id)| ExpandInfo {
2283                                    direction,
2284                                    excerpt_id,
2285                                },
2286                            ),
2287                        }
2288                    });
2289                ix += line.len() + 1;
2290                row_info
2291            })
2292            .collect();
2293
2294        (text, row_infos, excerpt_boundary_rows)
2295    }
2296
2297    fn diffs_updated(&mut self, cx: &App) {
2298        for excerpt in &mut self.excerpts {
2299            let buffer = excerpt.buffer.read(cx).snapshot();
2300            let excerpt_range = excerpt.range.to_offset(&buffer);
2301            let buffer_id = buffer.remote_id();
2302            let diff = self.diffs.get(&buffer_id).unwrap().read(cx);
2303            let mut hunks = diff.hunks_in_row_range(0..u32::MAX, &buffer, cx).peekable();
2304            excerpt.expanded_diff_hunks.retain(|hunk_anchor| {
2305                if !hunk_anchor.is_valid(&buffer) {
2306                    return false;
2307                }
2308                while let Some(hunk) = hunks.peek() {
2309                    match hunk.buffer_range.start.cmp(&hunk_anchor, &buffer) {
2310                        cmp::Ordering::Less => {
2311                            hunks.next();
2312                        }
2313                        cmp::Ordering::Equal => {
2314                            let hunk_range = hunk.buffer_range.to_offset(&buffer);
2315                            return hunk_range.end >= excerpt_range.start
2316                                && hunk_range.start <= excerpt_range.end;
2317                        }
2318                        cmp::Ordering::Greater => break,
2319                    }
2320                }
2321                false
2322            });
2323        }
2324    }
2325
2326    fn add_diff(&mut self, diff: Entity<BufferDiff>, cx: &mut App) {
2327        let buffer_id = diff.read(cx).buffer_id;
2328        self.diffs.insert(buffer_id, diff);
2329    }
2330}
2331
2332#[gpui::test(iterations = 100)]
2333async fn test_random_multibuffer(cx: &mut TestAppContext, mut rng: StdRng) {
2334    let operations = env::var("OPERATIONS")
2335        .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2336        .unwrap_or(10);
2337
2338    let mut buffers: Vec<Entity<Buffer>> = Vec::new();
2339    let mut base_texts: HashMap<BufferId, String> = HashMap::default();
2340    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2341    let mut reference = ReferenceMultibuffer::default();
2342    let mut anchors = Vec::new();
2343    let mut old_versions = Vec::new();
2344    let mut needs_diff_calculation = false;
2345
2346    for _ in 0..operations {
2347        match rng.gen_range(0..100) {
2348            0..=14 if !buffers.is_empty() => {
2349                let buffer = buffers.choose(&mut rng).unwrap();
2350                buffer.update(cx, |buf, cx| {
2351                    let edit_count = rng.gen_range(1..5);
2352                    buf.randomly_edit(&mut rng, edit_count, cx);
2353                    log::info!("buffer text:\n{}", buf.text());
2354                    needs_diff_calculation = true;
2355                });
2356                cx.update(|cx| reference.diffs_updated(cx));
2357            }
2358            15..=19 if !reference.excerpts.is_empty() => {
2359                multibuffer.update(cx, |multibuffer, cx| {
2360                    let ids = multibuffer.excerpt_ids();
2361                    let mut excerpts = HashSet::default();
2362                    for _ in 0..rng.gen_range(0..ids.len()) {
2363                        excerpts.extend(ids.choose(&mut rng).copied());
2364                    }
2365
2366                    let line_count = rng.gen_range(0..5);
2367
2368                    let excerpt_ixs = excerpts
2369                        .iter()
2370                        .map(|id| reference.excerpts.iter().position(|e| e.id == *id).unwrap())
2371                        .collect::<Vec<_>>();
2372                    log::info!("Expanding excerpts {excerpt_ixs:?} by {line_count} lines");
2373                    multibuffer.expand_excerpts(
2374                        excerpts.iter().cloned(),
2375                        line_count,
2376                        ExpandExcerptDirection::UpAndDown,
2377                        cx,
2378                    );
2379
2380                    reference.expand_excerpts(&excerpts, line_count, cx);
2381                });
2382            }
2383            20..=29 if !reference.excerpts.is_empty() => {
2384                let mut ids_to_remove = vec![];
2385                for _ in 0..rng.gen_range(1..=3) {
2386                    let Some(excerpt) = reference.excerpts.choose(&mut rng) else {
2387                        break;
2388                    };
2389                    let id = excerpt.id;
2390                    cx.update(|cx| reference.remove_excerpt(id, cx));
2391                    ids_to_remove.push(id);
2392                }
2393                let snapshot =
2394                    multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2395                ids_to_remove.sort_unstable_by(|a, b| a.cmp(b, &snapshot));
2396                drop(snapshot);
2397                multibuffer.update(cx, |multibuffer, cx| {
2398                    multibuffer.remove_excerpts(ids_to_remove, cx)
2399                });
2400            }
2401            30..=39 if !reference.excerpts.is_empty() => {
2402                let multibuffer =
2403                    multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2404                let offset =
2405                    multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
2406                let bias = if rng.r#gen() { Bias::Left } else { Bias::Right };
2407                log::info!("Creating anchor at {} with bias {:?}", offset, bias);
2408                anchors.push(multibuffer.anchor_at(offset, bias));
2409                anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
2410            }
2411            40..=44 if !anchors.is_empty() => {
2412                let multibuffer =
2413                    multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2414                let prev_len = anchors.len();
2415                anchors = multibuffer
2416                    .refresh_anchors(&anchors)
2417                    .into_iter()
2418                    .map(|a| a.1)
2419                    .collect();
2420
2421                // Ensure the newly-refreshed anchors point to a valid excerpt and don't
2422                // overshoot its boundaries.
2423                assert_eq!(anchors.len(), prev_len);
2424                for anchor in &anchors {
2425                    if anchor.excerpt_id == ExcerptId::min()
2426                        || anchor.excerpt_id == ExcerptId::max()
2427                    {
2428                        continue;
2429                    }
2430
2431                    let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
2432                    assert_eq!(excerpt.id, anchor.excerpt_id);
2433                    assert!(excerpt.contains(anchor));
2434                }
2435            }
2436            45..=55 if !reference.excerpts.is_empty() => {
2437                multibuffer.update(cx, |multibuffer, cx| {
2438                    let snapshot = multibuffer.snapshot(cx);
2439                    let excerpt_ix = rng.gen_range(0..reference.excerpts.len());
2440                    let excerpt = &reference.excerpts[excerpt_ix];
2441                    let start = excerpt.range.start;
2442                    let end = excerpt.range.end;
2443                    let range = snapshot.anchor_in_excerpt(excerpt.id, start).unwrap()
2444                        ..snapshot.anchor_in_excerpt(excerpt.id, end).unwrap();
2445
2446                    log::info!(
2447                        "expanding diff hunks in range {:?} (excerpt id {:?}, index {excerpt_ix:?}, buffer id {:?})",
2448                        range.to_offset(&snapshot),
2449                        excerpt.id,
2450                        excerpt.buffer.read(cx).remote_id(),
2451                    );
2452                    reference.expand_diff_hunks(excerpt.id, start..end, cx);
2453                    multibuffer.expand_diff_hunks(vec![range], cx);
2454                });
2455            }
2456            56..=85 if needs_diff_calculation => {
2457                multibuffer.update(cx, |multibuffer, cx| {
2458                    for buffer in multibuffer.all_buffers() {
2459                        let snapshot = buffer.read(cx).snapshot();
2460                        multibuffer.diff_for(snapshot.remote_id()).unwrap().update(
2461                            cx,
2462                            |diff, cx| {
2463                                log::info!(
2464                                    "recalculating diff for buffer {:?}",
2465                                    snapshot.remote_id(),
2466                                );
2467                                diff.recalculate_diff_sync(snapshot.text, cx);
2468                            },
2469                        );
2470                    }
2471                    reference.diffs_updated(cx);
2472                    needs_diff_calculation = false;
2473                });
2474            }
2475            _ => {
2476                let buffer_handle = if buffers.is_empty() || rng.gen_bool(0.4) {
2477                    let mut base_text = util::RandomCharIter::new(&mut rng)
2478                        .take(256)
2479                        .collect::<String>();
2480
2481                    let buffer = cx.new(|cx| Buffer::local(base_text.clone(), cx));
2482                    text::LineEnding::normalize(&mut base_text);
2483                    base_texts.insert(
2484                        buffer.read_with(cx, |buffer, _| buffer.remote_id()),
2485                        base_text,
2486                    );
2487                    buffers.push(buffer);
2488                    buffers.last().unwrap()
2489                } else {
2490                    buffers.choose(&mut rng).unwrap()
2491                };
2492
2493                let prev_excerpt_ix = rng.gen_range(0..=reference.excerpts.len());
2494                let prev_excerpt_id = reference
2495                    .excerpts
2496                    .get(prev_excerpt_ix)
2497                    .map_or(ExcerptId::max(), |e| e.id);
2498                let excerpt_ix = (prev_excerpt_ix + 1).min(reference.excerpts.len());
2499
2500                let (range, anchor_range) = buffer_handle.read_with(cx, |buffer, _| {
2501                    let end_row = rng.gen_range(0..=buffer.max_point().row);
2502                    let start_row = rng.gen_range(0..=end_row);
2503                    let end_ix = buffer.point_to_offset(Point::new(end_row, 0));
2504                    let start_ix = buffer.point_to_offset(Point::new(start_row, 0));
2505                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
2506
2507                    log::info!(
2508                        "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
2509                        excerpt_ix,
2510                        reference.excerpts.len(),
2511                        buffer.remote_id(),
2512                        buffer.text(),
2513                        start_ix..end_ix,
2514                        &buffer.text()[start_ix..end_ix]
2515                    );
2516
2517                    (start_ix..end_ix, anchor_range)
2518                });
2519
2520                multibuffer.update(cx, |multibuffer, cx| {
2521                    let id = buffer_handle.read(cx).remote_id();
2522                    if multibuffer.diff_for(id).is_none() {
2523                        let base_text = base_texts.get(&id).unwrap();
2524                        let diff = cx.new(|cx| {
2525                            BufferDiff::new_with_base_text(base_text, &buffer_handle, cx)
2526                        });
2527                        reference.add_diff(diff.clone(), cx);
2528                        multibuffer.add_diff(diff, cx)
2529                    }
2530                });
2531
2532                let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
2533                    multibuffer
2534                        .insert_excerpts_after(
2535                            prev_excerpt_id,
2536                            buffer_handle.clone(),
2537                            [ExcerptRange::new(range.clone())],
2538                            cx,
2539                        )
2540                        .pop()
2541                        .unwrap()
2542                });
2543
2544                reference.insert_excerpt_after(
2545                    prev_excerpt_id,
2546                    excerpt_id,
2547                    (buffer_handle.clone(), anchor_range),
2548                );
2549            }
2550        }
2551
2552        if rng.gen_bool(0.3) {
2553            multibuffer.update(cx, |multibuffer, cx| {
2554                old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
2555            })
2556        }
2557
2558        let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2559        let actual_text = snapshot.text();
2560        let actual_boundary_rows = snapshot
2561            .excerpt_boundaries_in_range(0..)
2562            .map(|b| b.row)
2563            .collect::<HashSet<_>>();
2564        let actual_row_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
2565
2566        let (expected_text, expected_row_infos, expected_boundary_rows) =
2567            cx.update(|cx| reference.expected_content(cx));
2568
2569        let has_diff = actual_row_infos
2570            .iter()
2571            .any(|info| info.diff_status.is_some())
2572            || expected_row_infos
2573                .iter()
2574                .any(|info| info.diff_status.is_some());
2575        let actual_diff = format_diff(
2576            &actual_text,
2577            &actual_row_infos,
2578            &actual_boundary_rows,
2579            Some(has_diff),
2580        );
2581        let expected_diff = format_diff(
2582            &expected_text,
2583            &expected_row_infos,
2584            &expected_boundary_rows,
2585            Some(has_diff),
2586        );
2587
2588        log::info!("Multibuffer content:\n{}", actual_diff);
2589
2590        assert_eq!(
2591            actual_row_infos.len(),
2592            actual_text.split('\n').count(),
2593            "line count: {}",
2594            actual_text.split('\n').count()
2595        );
2596        pretty_assertions::assert_eq!(actual_diff, expected_diff);
2597        pretty_assertions::assert_eq!(actual_text, expected_text);
2598        pretty_assertions::assert_eq!(actual_row_infos, expected_row_infos);
2599
2600        for _ in 0..5 {
2601            let start_row = rng.gen_range(0..=expected_row_infos.len());
2602            assert_eq!(
2603                snapshot
2604                    .row_infos(MultiBufferRow(start_row as u32))
2605                    .collect::<Vec<_>>(),
2606                &expected_row_infos[start_row..],
2607                "buffer_rows({})",
2608                start_row
2609            );
2610        }
2611
2612        assert_eq!(
2613            snapshot.widest_line_number(),
2614            expected_row_infos
2615                .into_iter()
2616                .filter_map(|info| {
2617                    if info.diff_status.is_some_and(|status| status.is_deleted()) {
2618                        None
2619                    } else {
2620                        info.buffer_row
2621                    }
2622                })
2623                .max()
2624                .unwrap()
2625                + 1
2626        );
2627
2628        assert_consistent_line_numbers(&snapshot);
2629        assert_position_translation(&snapshot);
2630
2631        for (row, line) in expected_text.split('\n').enumerate() {
2632            assert_eq!(
2633                snapshot.line_len(MultiBufferRow(row as u32)),
2634                line.len() as u32,
2635                "line_len({}).",
2636                row
2637            );
2638        }
2639
2640        let text_rope = Rope::from(expected_text.as_str());
2641        for _ in 0..10 {
2642            let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
2643            let start_ix = text_rope.clip_offset(rng.gen_range(0..=end_ix), Bias::Left);
2644
2645            let text_for_range = snapshot
2646                .text_for_range(start_ix..end_ix)
2647                .collect::<String>();
2648            assert_eq!(
2649                text_for_range,
2650                &expected_text[start_ix..end_ix],
2651                "incorrect text for range {:?}",
2652                start_ix..end_ix
2653            );
2654
2655            let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
2656            assert_eq!(
2657                snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
2658                expected_summary,
2659                "incorrect summary for range {:?}",
2660                start_ix..end_ix
2661            );
2662        }
2663
2664        // Anchor resolution
2665        let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
2666        assert_eq!(anchors.len(), summaries.len());
2667        for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
2668            assert!(resolved_offset <= snapshot.len());
2669            assert_eq!(
2670                snapshot.summary_for_anchor::<usize>(anchor),
2671                resolved_offset,
2672                "anchor: {:?}",
2673                anchor
2674            );
2675        }
2676
2677        for _ in 0..10 {
2678            let end_ix = text_rope.clip_offset(rng.gen_range(0..=text_rope.len()), Bias::Right);
2679            assert_eq!(
2680                snapshot.reversed_chars_at(end_ix).collect::<String>(),
2681                expected_text[..end_ix].chars().rev().collect::<String>(),
2682            );
2683        }
2684
2685        for _ in 0..10 {
2686            let end_ix = rng.gen_range(0..=text_rope.len());
2687            let start_ix = rng.gen_range(0..=end_ix);
2688            assert_eq!(
2689                snapshot
2690                    .bytes_in_range(start_ix..end_ix)
2691                    .flatten()
2692                    .copied()
2693                    .collect::<Vec<_>>(),
2694                expected_text.as_bytes()[start_ix..end_ix].to_vec(),
2695                "bytes_in_range({:?})",
2696                start_ix..end_ix,
2697            );
2698        }
2699    }
2700
2701    let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2702    for (old_snapshot, subscription) in old_versions {
2703        let edits = subscription.consume().into_inner();
2704
2705        log::info!(
2706            "applying subscription edits to old text: {:?}: {:?}",
2707            old_snapshot.text(),
2708            edits,
2709        );
2710
2711        let mut text = old_snapshot.text();
2712        for edit in edits {
2713            let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
2714            text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
2715        }
2716        assert_eq!(text.to_string(), snapshot.text());
2717    }
2718}
2719
2720#[gpui::test]
2721fn test_history(cx: &mut App) {
2722    let test_settings = SettingsStore::test(cx);
2723    cx.set_global(test_settings);
2724    let group_interval: Duration = Duration::from_millis(1);
2725    let buffer_1 = cx.new(|cx| {
2726        let mut buf = Buffer::local("1234", cx);
2727        buf.set_group_interval(group_interval);
2728        buf
2729    });
2730    let buffer_2 = cx.new(|cx| {
2731        let mut buf = Buffer::local("5678", cx);
2732        buf.set_group_interval(group_interval);
2733        buf
2734    });
2735    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2736    multibuffer.update(cx, |this, _| {
2737        this.history.group_interval = group_interval;
2738    });
2739    multibuffer.update(cx, |multibuffer, cx| {
2740        multibuffer.push_excerpts(
2741            buffer_1.clone(),
2742            [ExcerptRange::new(0..buffer_1.read(cx).len())],
2743            cx,
2744        );
2745        multibuffer.push_excerpts(
2746            buffer_2.clone(),
2747            [ExcerptRange::new(0..buffer_2.read(cx).len())],
2748            cx,
2749        );
2750    });
2751
2752    let mut now = Instant::now();
2753
2754    multibuffer.update(cx, |multibuffer, cx| {
2755        let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
2756        multibuffer.edit(
2757            [
2758                (Point::new(0, 0)..Point::new(0, 0), "A"),
2759                (Point::new(1, 0)..Point::new(1, 0), "A"),
2760            ],
2761            None,
2762            cx,
2763        );
2764        multibuffer.edit(
2765            [
2766                (Point::new(0, 1)..Point::new(0, 1), "B"),
2767                (Point::new(1, 1)..Point::new(1, 1), "B"),
2768            ],
2769            None,
2770            cx,
2771        );
2772        multibuffer.end_transaction_at(now, cx);
2773        assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2774
2775        // Verify edited ranges for transaction 1
2776        assert_eq!(
2777            multibuffer.edited_ranges_for_transaction(transaction_1, cx),
2778            &[
2779                Point::new(0, 0)..Point::new(0, 2),
2780                Point::new(1, 0)..Point::new(1, 2)
2781            ]
2782        );
2783
2784        // Edit buffer 1 through the multibuffer
2785        now += 2 * group_interval;
2786        multibuffer.start_transaction_at(now, cx);
2787        multibuffer.edit([(2..2, "C")], None, cx);
2788        multibuffer.end_transaction_at(now, cx);
2789        assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
2790
2791        // Edit buffer 1 independently
2792        buffer_1.update(cx, |buffer_1, cx| {
2793            buffer_1.start_transaction_at(now);
2794            buffer_1.edit([(3..3, "D")], None, cx);
2795            buffer_1.end_transaction_at(now, cx);
2796
2797            now += 2 * group_interval;
2798            buffer_1.start_transaction_at(now);
2799            buffer_1.edit([(4..4, "E")], None, cx);
2800            buffer_1.end_transaction_at(now, cx);
2801        });
2802        assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
2803
2804        // An undo in the multibuffer undoes the multibuffer transaction
2805        // and also any individual buffer edits that have occurred since
2806        // that transaction.
2807        multibuffer.undo(cx);
2808        assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2809
2810        multibuffer.undo(cx);
2811        assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
2812
2813        multibuffer.redo(cx);
2814        assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2815
2816        multibuffer.redo(cx);
2817        assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
2818
2819        // Undo buffer 2 independently.
2820        buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
2821        assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
2822
2823        // An undo in the multibuffer undoes the components of the
2824        // the last multibuffer transaction that are not already undone.
2825        multibuffer.undo(cx);
2826        assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
2827
2828        multibuffer.undo(cx);
2829        assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
2830
2831        multibuffer.redo(cx);
2832        assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
2833
2834        buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
2835        assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
2836
2837        // Redo stack gets cleared after an edit.
2838        now += 2 * group_interval;
2839        multibuffer.start_transaction_at(now, cx);
2840        multibuffer.edit([(0..0, "X")], None, cx);
2841        multibuffer.end_transaction_at(now, cx);
2842        assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
2843        multibuffer.redo(cx);
2844        assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
2845        multibuffer.undo(cx);
2846        assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
2847        multibuffer.undo(cx);
2848        assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
2849
2850        // Transactions can be grouped manually.
2851        multibuffer.redo(cx);
2852        multibuffer.redo(cx);
2853        assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
2854        multibuffer.group_until_transaction(transaction_1, cx);
2855        multibuffer.undo(cx);
2856        assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
2857        multibuffer.redo(cx);
2858        assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
2859    });
2860}
2861
2862#[gpui::test]
2863async fn test_enclosing_indent(cx: &mut TestAppContext) {
2864    async fn enclosing_indent(
2865        text: &str,
2866        buffer_row: u32,
2867        cx: &mut TestAppContext,
2868    ) -> Option<(Range<u32>, LineIndent)> {
2869        let buffer = cx.update(|cx| MultiBuffer::build_simple(text, cx));
2870        let snapshot = cx.read(|cx| buffer.read(cx).snapshot(cx));
2871        let (range, indent) = snapshot
2872            .enclosing_indent(MultiBufferRow(buffer_row))
2873            .await?;
2874        Some((range.start.0..range.end.0, indent))
2875    }
2876
2877    assert_eq!(
2878        enclosing_indent(
2879            indoc!(
2880                "
2881                fn b() {
2882                    if c {
2883                        let d = 2;
2884                    }
2885                }
2886                "
2887            ),
2888            1,
2889            cx,
2890        )
2891        .await,
2892        Some((
2893            1..2,
2894            LineIndent {
2895                tabs: 0,
2896                spaces: 4,
2897                line_blank: false,
2898            }
2899        ))
2900    );
2901
2902    assert_eq!(
2903        enclosing_indent(
2904            indoc!(
2905                "
2906                fn b() {
2907                    if c {
2908                        let d = 2;
2909                    }
2910                }
2911                "
2912            ),
2913            2,
2914            cx,
2915        )
2916        .await,
2917        Some((
2918            1..2,
2919            LineIndent {
2920                tabs: 0,
2921                spaces: 4,
2922                line_blank: false,
2923            }
2924        ))
2925    );
2926
2927    assert_eq!(
2928        enclosing_indent(
2929            indoc!(
2930                "
2931                fn b() {
2932                    if c {
2933                        let d = 2;
2934
2935                        let e = 5;
2936                    }
2937                }
2938                "
2939            ),
2940            3,
2941            cx,
2942        )
2943        .await,
2944        Some((
2945            1..4,
2946            LineIndent {
2947                tabs: 0,
2948                spaces: 4,
2949                line_blank: false,
2950            }
2951        ))
2952    );
2953}
2954
2955#[gpui::test]
2956fn test_summaries_for_anchors(cx: &mut TestAppContext) {
2957    let base_text_1 = indoc!(
2958        "
2959        bar
2960        "
2961    );
2962    let text_1 = indoc!(
2963        "
2964        BAR
2965        "
2966    );
2967    let base_text_2 = indoc!(
2968        "
2969        foo
2970        "
2971    );
2972    let text_2 = indoc!(
2973        "
2974        FOO
2975        "
2976    );
2977
2978    let buffer_1 = cx.new(|cx| Buffer::local(text_1, cx));
2979    let buffer_2 = cx.new(|cx| Buffer::local(text_2, cx));
2980    let diff_1 = cx.new(|cx| BufferDiff::new_with_base_text(base_text_1, &buffer_1, cx));
2981    let diff_2 = cx.new(|cx| BufferDiff::new_with_base_text(base_text_2, &buffer_2, cx));
2982    cx.run_until_parked();
2983
2984    let mut ids = vec![];
2985    let multibuffer = cx.new(|cx| {
2986        let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
2987        multibuffer.set_all_diff_hunks_expanded(cx);
2988        ids.extend(multibuffer.push_excerpts(
2989            buffer_1.clone(),
2990            [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
2991            cx,
2992        ));
2993        ids.extend(multibuffer.push_excerpts(
2994            buffer_2.clone(),
2995            [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
2996            cx,
2997        ));
2998        multibuffer.add_diff(diff_1.clone(), cx);
2999        multibuffer.add_diff(diff_2.clone(), cx);
3000        multibuffer
3001    });
3002
3003    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3004        (multibuffer.snapshot(cx), multibuffer.subscribe())
3005    });
3006
3007    assert_new_snapshot(
3008        &multibuffer,
3009        &mut snapshot,
3010        &mut subscription,
3011        cx,
3012        indoc!(
3013            "
3014            - bar
3015            + BAR
3016
3017            - foo
3018            + FOO
3019            "
3020        ),
3021    );
3022
3023    let id_1 = buffer_1.read_with(cx, |buffer, _| buffer.remote_id());
3024    let id_2 = buffer_2.read_with(cx, |buffer, _| buffer.remote_id());
3025
3026    let anchor_1 = Anchor::in_buffer(ids[0], id_1, text::Anchor::MIN);
3027    let point_1 = snapshot.summaries_for_anchors::<Point, _>([&anchor_1])[0];
3028    assert_eq!(point_1, Point::new(0, 0));
3029
3030    let anchor_2 = Anchor::in_buffer(ids[1], id_2, text::Anchor::MIN);
3031    let point_2 = snapshot.summaries_for_anchors::<Point, _>([&anchor_2])[0];
3032    assert_eq!(point_2, Point::new(3, 0));
3033}
3034
3035#[gpui::test]
3036fn test_trailing_deletion_without_newline(cx: &mut TestAppContext) {
3037    let base_text_1 = "one\ntwo".to_owned();
3038    let text_1 = "one\n".to_owned();
3039
3040    let buffer_1 = cx.new(|cx| Buffer::local(text_1, cx));
3041    let diff_1 = cx.new(|cx| BufferDiff::new_with_base_text(&base_text_1, &buffer_1, cx));
3042    cx.run_until_parked();
3043
3044    let multibuffer = cx.new(|cx| {
3045        let mut multibuffer = MultiBuffer::singleton(buffer_1.clone(), cx);
3046        multibuffer.add_diff(diff_1.clone(), cx);
3047        multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
3048        multibuffer
3049    });
3050
3051    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3052        (multibuffer.snapshot(cx), multibuffer.subscribe())
3053    });
3054
3055    assert_new_snapshot(
3056        &multibuffer,
3057        &mut snapshot,
3058        &mut subscription,
3059        cx,
3060        indoc!(
3061            "
3062              one
3063            - two
3064            "
3065        ),
3066    );
3067
3068    assert_eq!(snapshot.max_point(), Point::new(2, 0));
3069    assert_eq!(snapshot.len(), 8);
3070
3071    assert_eq!(
3072        snapshot
3073            .dimensions_from_points::<Point>([Point::new(2, 0)])
3074            .collect::<Vec<_>>(),
3075        vec![Point::new(2, 0)]
3076    );
3077
3078    let (_, translated_offset) = snapshot.point_to_buffer_offset(Point::new(2, 0)).unwrap();
3079    assert_eq!(translated_offset, "one\n".len());
3080    let (_, translated_point, _) = snapshot.point_to_buffer_point(Point::new(2, 0)).unwrap();
3081    assert_eq!(translated_point, Point::new(1, 0));
3082
3083    // The same, for an excerpt that's not at the end of the multibuffer.
3084
3085    let text_2 = "foo\n".to_owned();
3086    let buffer_2 = cx.new(|cx| Buffer::local(&text_2, cx));
3087    multibuffer.update(cx, |multibuffer, cx| {
3088        multibuffer.push_excerpts(
3089            buffer_2.clone(),
3090            [ExcerptRange::new(Point::new(0, 0)..Point::new(1, 0))],
3091            cx,
3092        );
3093    });
3094
3095    assert_new_snapshot(
3096        &multibuffer,
3097        &mut snapshot,
3098        &mut subscription,
3099        cx,
3100        indoc!(
3101            "
3102              one
3103            - two
3104
3105              foo
3106            "
3107        ),
3108    );
3109
3110    assert_eq!(
3111        snapshot
3112            .dimensions_from_points::<Point>([Point::new(2, 0)])
3113            .collect::<Vec<_>>(),
3114        vec![Point::new(2, 0)]
3115    );
3116
3117    let buffer_1_id = buffer_1.read_with(cx, |buffer_1, _| buffer_1.remote_id());
3118    let (buffer, translated_offset) = snapshot.point_to_buffer_offset(Point::new(2, 0)).unwrap();
3119    assert_eq!(buffer.remote_id(), buffer_1_id);
3120    assert_eq!(translated_offset, "one\n".len());
3121    let (buffer, translated_point, _) = snapshot.point_to_buffer_point(Point::new(2, 0)).unwrap();
3122    assert_eq!(buffer.remote_id(), buffer_1_id);
3123    assert_eq!(translated_point, Point::new(1, 0));
3124}
3125
3126fn format_diff(
3127    text: &str,
3128    row_infos: &Vec<RowInfo>,
3129    boundary_rows: &HashSet<MultiBufferRow>,
3130    has_diff: Option<bool>,
3131) -> String {
3132    let has_diff =
3133        has_diff.unwrap_or_else(|| row_infos.iter().any(|info| info.diff_status.is_some()));
3134    text.split('\n')
3135        .enumerate()
3136        .zip(row_infos)
3137        .map(|((ix, line), info)| {
3138            let marker = match info.diff_status.map(|status| status.kind) {
3139                Some(DiffHunkStatusKind::Added) => "+ ",
3140                Some(DiffHunkStatusKind::Deleted) => "- ",
3141                Some(DiffHunkStatusKind::Modified) => unreachable!(),
3142                None => {
3143                    if has_diff && !line.is_empty() {
3144                        "  "
3145                    } else {
3146                        ""
3147                    }
3148                }
3149            };
3150            let boundary_row = if boundary_rows.contains(&MultiBufferRow(ix as u32)) {
3151                if has_diff {
3152                    "  ----------\n"
3153                } else {
3154                    "---------\n"
3155                }
3156            } else {
3157                ""
3158            };
3159            format!("{boundary_row}{marker}{line}")
3160        })
3161        .collect::<Vec<_>>()
3162        .join("\n")
3163}
3164
3165#[track_caller]
3166fn assert_excerpts_match(
3167    multibuffer: &Entity<MultiBuffer>,
3168    cx: &mut TestAppContext,
3169    expected: &str,
3170) {
3171    let mut output = String::new();
3172    multibuffer.read_with(cx, |multibuffer, cx| {
3173        for (_, buffer, range) in multibuffer.snapshot(cx).excerpts() {
3174            output.push_str("-----\n");
3175            output.extend(buffer.text_for_range(range.context));
3176            if !output.ends_with('\n') {
3177                output.push('\n');
3178            }
3179        }
3180    });
3181    assert_eq!(output, expected);
3182}
3183
3184#[track_caller]
3185fn assert_new_snapshot(
3186    multibuffer: &Entity<MultiBuffer>,
3187    snapshot: &mut MultiBufferSnapshot,
3188    subscription: &mut Subscription,
3189    cx: &mut TestAppContext,
3190    expected_diff: &str,
3191) {
3192    let new_snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
3193    let actual_text = new_snapshot.text();
3194    let line_infos = new_snapshot
3195        .row_infos(MultiBufferRow(0))
3196        .collect::<Vec<_>>();
3197    let actual_diff = format_diff(&actual_text, &line_infos, &Default::default(), None);
3198    pretty_assertions::assert_eq!(actual_diff, expected_diff);
3199    check_edits(
3200        snapshot,
3201        &new_snapshot,
3202        &subscription.consume().into_inner(),
3203    );
3204    *snapshot = new_snapshot;
3205}
3206
3207#[track_caller]
3208fn check_edits(
3209    old_snapshot: &MultiBufferSnapshot,
3210    new_snapshot: &MultiBufferSnapshot,
3211    edits: &[Edit<usize>],
3212) {
3213    let mut text = old_snapshot.text();
3214    let new_text = new_snapshot.text();
3215    for edit in edits.iter().rev() {
3216        if !text.is_char_boundary(edit.old.start)
3217            || !text.is_char_boundary(edit.old.end)
3218            || !new_text.is_char_boundary(edit.new.start)
3219            || !new_text.is_char_boundary(edit.new.end)
3220        {
3221            panic!(
3222                "invalid edits: {:?}\nold text: {:?}\nnew text: {:?}",
3223                edits, text, new_text
3224            );
3225        }
3226
3227        text.replace_range(
3228            edit.old.start..edit.old.end,
3229            &new_text[edit.new.start..edit.new.end],
3230        );
3231    }
3232
3233    pretty_assertions::assert_eq!(text, new_text, "invalid edits: {:?}", edits);
3234}
3235
3236#[track_caller]
3237fn assert_chunks_in_ranges(snapshot: &MultiBufferSnapshot) {
3238    let full_text = snapshot.text();
3239    for ix in 0..full_text.len() {
3240        let mut chunks = snapshot.chunks(0..snapshot.len(), false);
3241        chunks.seek(ix..snapshot.len());
3242        let tail = chunks.map(|chunk| chunk.text).collect::<String>();
3243        assert_eq!(tail, &full_text[ix..], "seek to range: {:?}", ix..);
3244    }
3245}
3246
3247#[track_caller]
3248fn assert_consistent_line_numbers(snapshot: &MultiBufferSnapshot) {
3249    let all_line_numbers = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
3250    for start_row in 1..all_line_numbers.len() {
3251        let line_numbers = snapshot
3252            .row_infos(MultiBufferRow(start_row as u32))
3253            .collect::<Vec<_>>();
3254        assert_eq!(
3255            line_numbers,
3256            all_line_numbers[start_row..],
3257            "start_row: {start_row}"
3258        );
3259    }
3260}
3261
3262#[track_caller]
3263fn assert_position_translation(snapshot: &MultiBufferSnapshot) {
3264    let text = Rope::from(snapshot.text());
3265
3266    let mut left_anchors = Vec::new();
3267    let mut right_anchors = Vec::new();
3268    let mut offsets = Vec::new();
3269    let mut points = Vec::new();
3270    for offset in 0..=text.len() + 1 {
3271        let clipped_left = snapshot.clip_offset(offset, Bias::Left);
3272        let clipped_right = snapshot.clip_offset(offset, Bias::Right);
3273        assert_eq!(
3274            clipped_left,
3275            text.clip_offset(offset, Bias::Left),
3276            "clip_offset({offset:?}, Left)"
3277        );
3278        assert_eq!(
3279            clipped_right,
3280            text.clip_offset(offset, Bias::Right),
3281            "clip_offset({offset:?}, Right)"
3282        );
3283        assert_eq!(
3284            snapshot.offset_to_point(clipped_left),
3285            text.offset_to_point(clipped_left),
3286            "offset_to_point({clipped_left})"
3287        );
3288        assert_eq!(
3289            snapshot.offset_to_point(clipped_right),
3290            text.offset_to_point(clipped_right),
3291            "offset_to_point({clipped_right})"
3292        );
3293        let anchor_after = snapshot.anchor_after(clipped_left);
3294        assert_eq!(
3295            anchor_after.to_offset(snapshot),
3296            clipped_left,
3297            "anchor_after({clipped_left}).to_offset {anchor_after:?}"
3298        );
3299        let anchor_before = snapshot.anchor_before(clipped_left);
3300        assert_eq!(
3301            anchor_before.to_offset(snapshot),
3302            clipped_left,
3303            "anchor_before({clipped_left}).to_offset"
3304        );
3305        left_anchors.push(anchor_before);
3306        right_anchors.push(anchor_after);
3307        offsets.push(clipped_left);
3308        points.push(text.offset_to_point(clipped_left));
3309    }
3310
3311    for row in 0..text.max_point().row {
3312        for column in 0..text.line_len(row) + 1 {
3313            let point = Point { row, column };
3314            let clipped_left = snapshot.clip_point(point, Bias::Left);
3315            let clipped_right = snapshot.clip_point(point, Bias::Right);
3316            assert_eq!(
3317                clipped_left,
3318                text.clip_point(point, Bias::Left),
3319                "clip_point({point:?}, Left)"
3320            );
3321            assert_eq!(
3322                clipped_right,
3323                text.clip_point(point, Bias::Right),
3324                "clip_point({point:?}, Right)"
3325            );
3326            assert_eq!(
3327                snapshot.point_to_offset(clipped_left),
3328                text.point_to_offset(clipped_left),
3329                "point_to_offset({clipped_left:?})"
3330            );
3331            assert_eq!(
3332                snapshot.point_to_offset(clipped_right),
3333                text.point_to_offset(clipped_right),
3334                "point_to_offset({clipped_right:?})"
3335            );
3336        }
3337    }
3338
3339    assert_eq!(
3340        snapshot.summaries_for_anchors::<usize, _>(&left_anchors),
3341        offsets,
3342        "left_anchors <-> offsets"
3343    );
3344    assert_eq!(
3345        snapshot.summaries_for_anchors::<Point, _>(&left_anchors),
3346        points,
3347        "left_anchors <-> points"
3348    );
3349    assert_eq!(
3350        snapshot.summaries_for_anchors::<usize, _>(&right_anchors),
3351        offsets,
3352        "right_anchors <-> offsets"
3353    );
3354    assert_eq!(
3355        snapshot.summaries_for_anchors::<Point, _>(&right_anchors),
3356        points,
3357        "right_anchors <-> points"
3358    );
3359
3360    for (anchors, bias) in [(&left_anchors, Bias::Left), (&right_anchors, Bias::Right)] {
3361        for (ix, (offset, anchor)) in offsets.iter().zip(anchors).enumerate() {
3362            if ix > 0 {
3363                if *offset == 252 {
3364                    if offset > &offsets[ix - 1] {
3365                        let prev_anchor = left_anchors[ix - 1];
3366                        assert!(
3367                            anchor.cmp(&prev_anchor, snapshot).is_gt(),
3368                            "anchor({}, {bias:?}).cmp(&anchor({}, {bias:?}).is_gt()",
3369                            offsets[ix],
3370                            offsets[ix - 1],
3371                        );
3372                        assert!(
3373                            prev_anchor.cmp(&anchor, snapshot).is_lt(),
3374                            "anchor({}, {bias:?}).cmp(&anchor({}, {bias:?}).is_lt()",
3375                            offsets[ix - 1],
3376                            offsets[ix],
3377                        );
3378                    }
3379                }
3380            }
3381        }
3382    }
3383
3384    if let Some((buffer, offset)) = snapshot.point_to_buffer_offset(snapshot.max_point()) {
3385        assert!(offset <= buffer.len());
3386    }
3387    if let Some((buffer, point, _)) = snapshot.point_to_buffer_point(snapshot.max_point()) {
3388        assert!(point <= buffer.max_point());
3389    }
3390}
3391
3392fn assert_line_indents(snapshot: &MultiBufferSnapshot) {
3393    let max_row = snapshot.max_point().row;
3394    let buffer_id = snapshot.excerpts().next().unwrap().1.remote_id();
3395    let text = text::Buffer::new(0, buffer_id, snapshot.text());
3396    let mut line_indents = text
3397        .line_indents_in_row_range(0..max_row + 1)
3398        .collect::<Vec<_>>();
3399    for start_row in 0..snapshot.max_point().row {
3400        pretty_assertions::assert_eq!(
3401            snapshot
3402                .line_indents(MultiBufferRow(start_row), |_| true)
3403                .map(|(row, indent, _)| (row.0, indent))
3404                .collect::<Vec<_>>(),
3405            &line_indents[(start_row as usize)..],
3406            "line_indents({start_row})"
3407        );
3408    }
3409
3410    line_indents.reverse();
3411    pretty_assertions::assert_eq!(
3412        snapshot
3413            .reversed_line_indents(MultiBufferRow(max_row), |_| true)
3414            .map(|(row, indent, _)| (row.0, indent))
3415            .collect::<Vec<_>>(),
3416        &line_indents[..],
3417        "reversed_line_indents({max_row})"
3418    );
3419}