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 std::time::{Duration, Instant};
  11use util::RandomCharIter;
  12use util::rel_path::rel_path;
  13use util::test::sample_text;
  14
  15#[ctor::ctor]
  16fn init_logger() {
  17    zlog::init_test();
  18}
  19
  20#[gpui::test]
  21fn test_empty_singleton(cx: &mut App) {
  22    let buffer = cx.new(|cx| Buffer::local("", cx));
  23    let buffer_id = buffer.read(cx).remote_id();
  24    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
  25    let snapshot = multibuffer.read(cx).snapshot(cx);
  26    assert_eq!(snapshot.text(), "");
  27    assert_eq!(
  28        snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>(),
  29        [RowInfo {
  30            buffer_id: Some(buffer_id),
  31            buffer_row: Some(0),
  32            multibuffer_row: Some(MultiBufferRow(0)),
  33            diff_status: None,
  34            expand_info: None,
  35        }]
  36    );
  37}
  38
  39#[gpui::test]
  40fn test_singleton(cx: &mut App) {
  41    let buffer = cx.new(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
  42    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
  43
  44    let snapshot = multibuffer.read(cx).snapshot(cx);
  45    assert_eq!(snapshot.text(), buffer.read(cx).text());
  46
  47    assert_eq!(
  48        snapshot
  49            .row_infos(MultiBufferRow(0))
  50            .map(|info| info.buffer_row)
  51            .collect::<Vec<_>>(),
  52        (0..buffer.read(cx).row_count())
  53            .map(Some)
  54            .collect::<Vec<_>>()
  55    );
  56    assert_consistent_line_numbers(&snapshot);
  57
  58    buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
  59    let snapshot = multibuffer.read(cx).snapshot(cx);
  60
  61    assert_eq!(snapshot.text(), buffer.read(cx).text());
  62    assert_eq!(
  63        snapshot
  64            .row_infos(MultiBufferRow(0))
  65            .map(|info| info.buffer_row)
  66            .collect::<Vec<_>>(),
  67        (0..buffer.read(cx).row_count())
  68            .map(Some)
  69            .collect::<Vec<_>>()
  70    );
  71    assert_consistent_line_numbers(&snapshot);
  72}
  73
  74#[gpui::test]
  75fn test_remote(cx: &mut App) {
  76    let host_buffer = cx.new(|cx| Buffer::local("a", cx));
  77    let guest_buffer = cx.new(|cx| {
  78        let state = host_buffer.read(cx).to_proto(cx);
  79        let ops = cx
  80            .background_executor()
  81            .block(host_buffer.read(cx).serialize_ops(None, cx));
  82        let mut buffer =
  83            Buffer::from_proto(ReplicaId::REMOTE_SERVER, Capability::ReadWrite, state, None)
  84                .unwrap();
  85        buffer.apply_ops(
  86            ops.into_iter()
  87                .map(|op| language::proto::deserialize_operation(op).unwrap()),
  88            cx,
  89        );
  90        buffer
  91    });
  92    let multibuffer = cx.new(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
  93    let snapshot = multibuffer.read(cx).snapshot(cx);
  94    assert_eq!(snapshot.text(), "a");
  95
  96    guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
  97    let snapshot = multibuffer.read(cx).snapshot(cx);
  98    assert_eq!(snapshot.text(), "ab");
  99
 100    guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
 101    let snapshot = multibuffer.read(cx).snapshot(cx);
 102    assert_eq!(snapshot.text(), "abc");
 103}
 104
 105#[gpui::test]
 106fn test_excerpt_boundaries_and_clipping(cx: &mut App) {
 107    let buffer_1 = cx.new(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
 108    let buffer_2 = cx.new(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
 109    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
 110
 111    let events = Arc::new(RwLock::new(Vec::<Event>::new()));
 112    multibuffer.update(cx, |_, cx| {
 113        let events = events.clone();
 114        cx.subscribe(&multibuffer, move |_, _, event, _| {
 115            if let Event::Edited { .. } = event {
 116                events.write().push(event.clone())
 117            }
 118        })
 119        .detach();
 120    });
 121
 122    let subscription = multibuffer.update(cx, |multibuffer, cx| {
 123        let subscription = multibuffer.subscribe();
 124        multibuffer.push_excerpts(
 125            buffer_1.clone(),
 126            [ExcerptRange::new(Point::new(1, 2)..Point::new(2, 5))],
 127            cx,
 128        );
 129        assert_eq!(
 130            subscription.consume().into_inner(),
 131            [Edit {
 132                old: 0..0,
 133                new: 0..10
 134            }]
 135        );
 136
 137        multibuffer.push_excerpts(
 138            buffer_1.clone(),
 139            [ExcerptRange::new(Point::new(3, 3)..Point::new(4, 4))],
 140            cx,
 141        );
 142        multibuffer.push_excerpts(
 143            buffer_2.clone(),
 144            [ExcerptRange::new(Point::new(3, 1)..Point::new(3, 3))],
 145            cx,
 146        );
 147        assert_eq!(
 148            subscription.consume().into_inner(),
 149            [Edit {
 150                old: 10..10,
 151                new: 10..22
 152            }]
 153        );
 154
 155        subscription
 156    });
 157
 158    // Adding excerpts emits an edited event.
 159    assert_eq!(
 160        events.read().as_slice(),
 161        &[
 162            Event::Edited {
 163                edited_buffer: None,
 164            },
 165            Event::Edited {
 166                edited_buffer: None,
 167            },
 168            Event::Edited {
 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!(
 208        snapshot
 209            .row_infos(MultiBufferRow(5))
 210            .map(|info| info.buffer_row)
 211            .collect::<Vec<_>>()
 212            .is_empty()
 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        let line_zero = multibuffer.snapshot(cx).anchor_before(Point::new(0, 0));
 750        multibuffer.expand_excerpts(
 751            multibuffer.excerpt_ids(),
 752            1,
 753            ExpandExcerptDirection::UpAndDown,
 754            cx,
 755        );
 756        let snapshot = multibuffer.snapshot(cx);
 757        let line_two = snapshot.anchor_before(Point::new(2, 0));
 758        assert_eq!(line_two.cmp(&line_zero, &snapshot), cmp::Ordering::Greater);
 759    });
 760
 761    let snapshot = multibuffer.read(cx).snapshot(cx);
 762
 763    assert_eq!(
 764        snapshot.text(),
 765        concat!(
 766            "bbb\n", //
 767            "ccc\n", //
 768            "ddd\n", //
 769            "eee\n", //
 770            "fff\n", //
 771            "ggg\n", //
 772            "hhh\n", //
 773            "iii\n", //
 774            "jjj\n", // End of excerpt
 775            "nnn\n", //
 776            "ooo\n", //
 777            "ppp\n", //
 778            "qqq\n", //
 779            "rrr",   // End of excerpt
 780        )
 781    );
 782}
 783
 784#[gpui::test(iterations = 100)]
 785async fn test_set_anchored_excerpts_for_path(cx: &mut TestAppContext) {
 786    let buffer_1 = cx.new(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
 787    let buffer_2 = cx.new(|cx| Buffer::local(sample_text(15, 4, 'a'), cx));
 788    let snapshot_1 = buffer_1.update(cx, |buffer, _| buffer.snapshot());
 789    let snapshot_2 = buffer_2.update(cx, |buffer, _| buffer.snapshot());
 790    let ranges_1 = vec![
 791        snapshot_1.anchor_before(Point::new(3, 2))..snapshot_1.anchor_before(Point::new(4, 2)),
 792        snapshot_1.anchor_before(Point::new(7, 1))..snapshot_1.anchor_before(Point::new(7, 3)),
 793        snapshot_1.anchor_before(Point::new(15, 0))..snapshot_1.anchor_before(Point::new(15, 0)),
 794    ];
 795    let ranges_2 = vec![
 796        snapshot_2.anchor_before(Point::new(2, 1))..snapshot_2.anchor_before(Point::new(3, 1)),
 797        snapshot_2.anchor_before(Point::new(10, 0))..snapshot_2.anchor_before(Point::new(10, 2)),
 798    ];
 799
 800    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
 801    let anchor_ranges_1 = multibuffer
 802        .update(cx, |multibuffer, cx| {
 803            multibuffer.set_anchored_excerpts_for_path(
 804                PathKey::for_buffer(&buffer_1, cx),
 805                buffer_1.clone(),
 806                ranges_1,
 807                2,
 808                cx,
 809            )
 810        })
 811        .await;
 812    let snapshot_1 = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
 813    assert_eq!(
 814        anchor_ranges_1
 815            .iter()
 816            .map(|range| range.to_point(&snapshot_1))
 817            .collect::<Vec<_>>(),
 818        vec![
 819            Point::new(2, 2)..Point::new(3, 2),
 820            Point::new(6, 1)..Point::new(6, 3),
 821            Point::new(11, 0)..Point::new(11, 0),
 822        ]
 823    );
 824    let anchor_ranges_2 = multibuffer
 825        .update(cx, |multibuffer, cx| {
 826            multibuffer.set_anchored_excerpts_for_path(
 827                PathKey::for_buffer(&buffer_2, cx),
 828                buffer_2.clone(),
 829                ranges_2,
 830                2,
 831                cx,
 832            )
 833        })
 834        .await;
 835    let snapshot_2 = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
 836    assert_eq!(
 837        anchor_ranges_2
 838            .iter()
 839            .map(|range| range.to_point(&snapshot_2))
 840            .collect::<Vec<_>>(),
 841        vec![
 842            Point::new(16, 1)..Point::new(17, 1),
 843            Point::new(22, 0)..Point::new(22, 2)
 844        ]
 845    );
 846
 847    let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
 848    assert_eq!(
 849        snapshot.text(),
 850        concat!(
 851            "bbb\n", // buffer_1
 852            "ccc\n", //
 853            "ddd\n", // <-- excerpt 1
 854            "eee\n", // <-- excerpt 1
 855            "fff\n", //
 856            "ggg\n", //
 857            "hhh\n", // <-- excerpt 2
 858            "iii\n", //
 859            "jjj\n", //
 860            //
 861            "nnn\n", //
 862            "ooo\n", //
 863            "ppp\n", // <-- excerpt 3
 864            "qqq\n", //
 865            "rrr\n", //
 866            //
 867            "aaaa\n", // buffer 2
 868            "bbbb\n", //
 869            "cccc\n", // <-- excerpt 4
 870            "dddd\n", // <-- excerpt 4
 871            "eeee\n", //
 872            "ffff\n", //
 873            //
 874            "iiii\n", //
 875            "jjjj\n", //
 876            "kkkk\n", // <-- excerpt 5
 877            "llll\n", //
 878            "mmmm",   //
 879        )
 880    );
 881}
 882
 883#[gpui::test]
 884fn test_empty_multibuffer(cx: &mut App) {
 885    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
 886
 887    let snapshot = multibuffer.read(cx).snapshot(cx);
 888    assert_eq!(snapshot.text(), "");
 889    assert_eq!(
 890        snapshot
 891            .row_infos(MultiBufferRow(0))
 892            .map(|info| info.buffer_row)
 893            .collect::<Vec<_>>(),
 894        &[Some(0)]
 895    );
 896    assert!(
 897        snapshot
 898            .row_infos(MultiBufferRow(1))
 899            .map(|info| info.buffer_row)
 900            .collect::<Vec<_>>()
 901            .is_empty(),
 902    );
 903}
 904
 905#[gpui::test]
 906fn test_empty_diff_excerpt(cx: &mut TestAppContext) {
 907    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
 908    let buffer = cx.new(|cx| Buffer::local("", cx));
 909    let base_text = "a\nb\nc";
 910
 911    let diff = cx.new(|cx| BufferDiff::new_with_base_text(base_text, &buffer, cx));
 912    multibuffer.update(cx, |multibuffer, cx| {
 913        multibuffer.push_excerpts(buffer.clone(), [ExcerptRange::new(0..0)], cx);
 914        multibuffer.set_all_diff_hunks_expanded(cx);
 915        multibuffer.add_diff(diff.clone(), cx);
 916    });
 917    cx.run_until_parked();
 918
 919    let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
 920    assert_eq!(snapshot.text(), "a\nb\nc\n");
 921
 922    let hunk = snapshot
 923        .diff_hunks_in_range(Point::new(1, 1)..Point::new(1, 1))
 924        .next()
 925        .unwrap();
 926
 927    assert_eq!(hunk.diff_base_byte_range.start, 0);
 928
 929    let buf2 = cx.new(|cx| Buffer::local("X", cx));
 930    multibuffer.update(cx, |multibuffer, cx| {
 931        multibuffer.push_excerpts(buf2, [ExcerptRange::new(0..1)], cx);
 932    });
 933
 934    buffer.update(cx, |buffer, cx| {
 935        buffer.edit([(0..0, "a\nb\nc")], None, cx);
 936        diff.update(cx, |diff, cx| {
 937            diff.recalculate_diff_sync(buffer.snapshot().text, cx);
 938        });
 939        assert_eq!(buffer.text(), "a\nb\nc")
 940    });
 941    cx.run_until_parked();
 942
 943    let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
 944    assert_eq!(snapshot.text(), "a\nb\nc\nX");
 945
 946    buffer.update(cx, |buffer, cx| {
 947        buffer.undo(cx);
 948        diff.update(cx, |diff, cx| {
 949            diff.recalculate_diff_sync(buffer.snapshot().text, cx);
 950        });
 951        assert_eq!(buffer.text(), "")
 952    });
 953    cx.run_until_parked();
 954
 955    let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
 956    assert_eq!(snapshot.text(), "a\nb\nc\n\nX");
 957}
 958
 959#[gpui::test]
 960fn test_singleton_multibuffer_anchors(cx: &mut App) {
 961    let buffer = cx.new(|cx| Buffer::local("abcd", cx));
 962    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
 963    let old_snapshot = multibuffer.read(cx).snapshot(cx);
 964    buffer.update(cx, |buffer, cx| {
 965        buffer.edit([(0..0, "X")], None, cx);
 966        buffer.edit([(5..5, "Y")], None, cx);
 967    });
 968    let new_snapshot = multibuffer.read(cx).snapshot(cx);
 969
 970    assert_eq!(old_snapshot.text(), "abcd");
 971    assert_eq!(new_snapshot.text(), "XabcdY");
 972
 973    assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
 974    assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
 975    assert_eq!(old_snapshot.anchor_before(4).to_offset(&new_snapshot), 5);
 976    assert_eq!(old_snapshot.anchor_after(4).to_offset(&new_snapshot), 6);
 977}
 978
 979#[gpui::test]
 980fn test_multibuffer_anchors(cx: &mut App) {
 981    let buffer_1 = cx.new(|cx| Buffer::local("abcd", cx));
 982    let buffer_2 = cx.new(|cx| Buffer::local("efghi", cx));
 983    let multibuffer = cx.new(|cx| {
 984        let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
 985        multibuffer.push_excerpts(buffer_1.clone(), [ExcerptRange::new(0..4)], cx);
 986        multibuffer.push_excerpts(buffer_2.clone(), [ExcerptRange::new(0..5)], cx);
 987        multibuffer
 988    });
 989    let old_snapshot = multibuffer.read(cx).snapshot(cx);
 990
 991    assert_eq!(old_snapshot.anchor_before(0).to_offset(&old_snapshot), 0);
 992    assert_eq!(old_snapshot.anchor_after(0).to_offset(&old_snapshot), 0);
 993    assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
 994    assert_eq!(Anchor::min().to_offset(&old_snapshot), 0);
 995    assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
 996    assert_eq!(Anchor::max().to_offset(&old_snapshot), 10);
 997
 998    buffer_1.update(cx, |buffer, cx| {
 999        buffer.edit([(0..0, "W")], None, cx);
1000        buffer.edit([(5..5, "X")], None, cx);
1001    });
1002    buffer_2.update(cx, |buffer, cx| {
1003        buffer.edit([(0..0, "Y")], None, cx);
1004        buffer.edit([(6..6, "Z")], None, cx);
1005    });
1006    let new_snapshot = multibuffer.read(cx).snapshot(cx);
1007
1008    assert_eq!(old_snapshot.text(), "abcd\nefghi");
1009    assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
1010
1011    assert_eq!(old_snapshot.anchor_before(0).to_offset(&new_snapshot), 0);
1012    assert_eq!(old_snapshot.anchor_after(0).to_offset(&new_snapshot), 1);
1013    assert_eq!(old_snapshot.anchor_before(1).to_offset(&new_snapshot), 2);
1014    assert_eq!(old_snapshot.anchor_after(1).to_offset(&new_snapshot), 2);
1015    assert_eq!(old_snapshot.anchor_before(2).to_offset(&new_snapshot), 3);
1016    assert_eq!(old_snapshot.anchor_after(2).to_offset(&new_snapshot), 3);
1017    assert_eq!(old_snapshot.anchor_before(5).to_offset(&new_snapshot), 7);
1018    assert_eq!(old_snapshot.anchor_after(5).to_offset(&new_snapshot), 8);
1019    assert_eq!(old_snapshot.anchor_before(10).to_offset(&new_snapshot), 13);
1020    assert_eq!(old_snapshot.anchor_after(10).to_offset(&new_snapshot), 14);
1021}
1022
1023#[gpui::test]
1024fn test_resolving_anchors_after_replacing_their_excerpts(cx: &mut App) {
1025    let buffer_1 = cx.new(|cx| Buffer::local("abcd", cx));
1026    let buffer_2 = cx.new(|cx| Buffer::local("ABCDEFGHIJKLMNOP", cx));
1027    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
1028
1029    // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
1030    // Add an excerpt from buffer 1 that spans this new insertion.
1031    buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], None, cx));
1032    let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
1033        multibuffer
1034            .push_excerpts(buffer_1.clone(), [ExcerptRange::new(0..7)], cx)
1035            .pop()
1036            .unwrap()
1037    });
1038
1039    let snapshot_1 = multibuffer.read(cx).snapshot(cx);
1040    assert_eq!(snapshot_1.text(), "abcd123");
1041
1042    // Replace the buffer 1 excerpt with new excerpts from buffer 2.
1043    let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
1044        multibuffer.remove_excerpts([excerpt_id_1], cx);
1045        let mut ids = multibuffer
1046            .push_excerpts(
1047                buffer_2.clone(),
1048                [
1049                    ExcerptRange::new(0..4),
1050                    ExcerptRange::new(6..10),
1051                    ExcerptRange::new(12..16),
1052                ],
1053                cx,
1054            )
1055            .into_iter();
1056        (ids.next().unwrap(), ids.next().unwrap())
1057    });
1058    let snapshot_2 = multibuffer.read(cx).snapshot(cx);
1059    assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
1060
1061    // The old excerpt id doesn't get reused.
1062    assert_ne!(excerpt_id_2, excerpt_id_1);
1063
1064    // Resolve some anchors from the previous snapshot in the new snapshot.
1065    // The current excerpts are from a different buffer, so we don't attempt to
1066    // resolve the old text anchor in the new buffer.
1067    assert_eq!(
1068        snapshot_2.summary_for_anchor::<usize>(&snapshot_1.anchor_before(2)),
1069        0
1070    );
1071    assert_eq!(
1072        snapshot_2.summaries_for_anchors::<usize, _>(&[
1073            snapshot_1.anchor_before(2),
1074            snapshot_1.anchor_after(3)
1075        ]),
1076        vec![0, 0]
1077    );
1078
1079    // Refresh anchors from the old snapshot. The return value indicates that both
1080    // anchors lost their original excerpt.
1081    let refresh =
1082        snapshot_2.refresh_anchors(&[snapshot_1.anchor_before(2), snapshot_1.anchor_after(3)]);
1083    assert_eq!(
1084        refresh,
1085        &[
1086            (0, snapshot_2.anchor_before(0), false),
1087            (1, snapshot_2.anchor_after(0), false),
1088        ]
1089    );
1090
1091    // Replace the middle excerpt with a smaller excerpt in buffer 2,
1092    // that intersects the old excerpt.
1093    let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
1094        multibuffer.remove_excerpts([excerpt_id_3], cx);
1095        multibuffer
1096            .insert_excerpts_after(
1097                excerpt_id_2,
1098                buffer_2.clone(),
1099                [ExcerptRange::new(5..8)],
1100                cx,
1101            )
1102            .pop()
1103            .unwrap()
1104    });
1105
1106    let snapshot_3 = multibuffer.read(cx).snapshot(cx);
1107    assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
1108    assert_ne!(excerpt_id_5, excerpt_id_3);
1109
1110    // Resolve some anchors from the previous snapshot in the new snapshot.
1111    // The third anchor can't be resolved, since its excerpt has been removed,
1112    // so it resolves to the same position as its predecessor.
1113    let anchors = [
1114        snapshot_2.anchor_before(0),
1115        snapshot_2.anchor_after(2),
1116        snapshot_2.anchor_after(6),
1117        snapshot_2.anchor_after(14),
1118    ];
1119    assert_eq!(
1120        snapshot_3.summaries_for_anchors::<usize, _>(&anchors),
1121        &[0, 2, 9, 13]
1122    );
1123
1124    let new_anchors = snapshot_3.refresh_anchors(&anchors);
1125    assert_eq!(
1126        new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
1127        &[(0, true), (1, true), (2, true), (3, true)]
1128    );
1129    assert_eq!(
1130        snapshot_3.summaries_for_anchors::<usize, _>(new_anchors.iter().map(|a| &a.1)),
1131        &[0, 2, 7, 13]
1132    );
1133}
1134
1135#[gpui::test]
1136fn test_basic_diff_hunks(cx: &mut TestAppContext) {
1137    let text = indoc!(
1138        "
1139        ZERO
1140        one
1141        TWO
1142        three
1143        six
1144        "
1145    );
1146    let base_text = indoc!(
1147        "
1148        one
1149        two
1150        three
1151        four
1152        five
1153        six
1154        "
1155    );
1156
1157    let buffer = cx.new(|cx| Buffer::local(text, cx));
1158    let diff = cx.new(|cx| BufferDiff::new_with_base_text(base_text, &buffer, cx));
1159    cx.run_until_parked();
1160
1161    let multibuffer = cx.new(|cx| {
1162        let mut multibuffer = MultiBuffer::singleton(buffer.clone(), cx);
1163        multibuffer.add_diff(diff.clone(), cx);
1164        multibuffer
1165    });
1166
1167    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
1168        (multibuffer.snapshot(cx), multibuffer.subscribe())
1169    });
1170    assert_eq!(
1171        snapshot.text(),
1172        indoc!(
1173            "
1174            ZERO
1175            one
1176            TWO
1177            three
1178            six
1179            "
1180        ),
1181    );
1182
1183    multibuffer.update(cx, |multibuffer, cx| {
1184        multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
1185    });
1186
1187    assert_new_snapshot(
1188        &multibuffer,
1189        &mut snapshot,
1190        &mut subscription,
1191        cx,
1192        indoc!(
1193            "
1194            + ZERO
1195              one
1196            - two
1197            + TWO
1198              three
1199            - four
1200            - five
1201              six
1202            "
1203        ),
1204    );
1205
1206    assert_eq!(
1207        snapshot
1208            .row_infos(MultiBufferRow(0))
1209            .map(|info| (info.buffer_row, info.diff_status))
1210            .collect::<Vec<_>>(),
1211        vec![
1212            (Some(0), Some(DiffHunkStatus::added_none())),
1213            (Some(1), None),
1214            (Some(1), Some(DiffHunkStatus::deleted_none())),
1215            (Some(2), Some(DiffHunkStatus::added_none())),
1216            (Some(3), None),
1217            (Some(3), Some(DiffHunkStatus::deleted_none())),
1218            (Some(4), Some(DiffHunkStatus::deleted_none())),
1219            (Some(4), None),
1220            (Some(5), None)
1221        ]
1222    );
1223
1224    assert_chunks_in_ranges(&snapshot);
1225    assert_consistent_line_numbers(&snapshot);
1226    assert_position_translation(&snapshot);
1227    assert_line_indents(&snapshot);
1228
1229    multibuffer.update(cx, |multibuffer, cx| {
1230        multibuffer.collapse_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
1231    });
1232    assert_new_snapshot(
1233        &multibuffer,
1234        &mut snapshot,
1235        &mut subscription,
1236        cx,
1237        indoc!(
1238            "
1239            ZERO
1240            one
1241            TWO
1242            three
1243            six
1244            "
1245        ),
1246    );
1247
1248    assert_chunks_in_ranges(&snapshot);
1249    assert_consistent_line_numbers(&snapshot);
1250    assert_position_translation(&snapshot);
1251    assert_line_indents(&snapshot);
1252
1253    // Expand the first diff hunk
1254    multibuffer.update(cx, |multibuffer, cx| {
1255        let position = multibuffer.read(cx).anchor_before(Point::new(2, 2));
1256        multibuffer.expand_diff_hunks(vec![position..position], 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              six
1271            "
1272        ),
1273    );
1274
1275    // Expand the second diff hunk
1276    multibuffer.update(cx, |multibuffer, cx| {
1277        let start = multibuffer.read(cx).anchor_before(Point::new(4, 0));
1278        let end = multibuffer.read(cx).anchor_before(Point::new(5, 0));
1279        multibuffer.expand_diff_hunks(vec![start..end], cx)
1280    });
1281    assert_new_snapshot(
1282        &multibuffer,
1283        &mut snapshot,
1284        &mut subscription,
1285        cx,
1286        indoc!(
1287            "
1288              ZERO
1289              one
1290            - two
1291            + TWO
1292              three
1293            - four
1294            - five
1295              six
1296            "
1297        ),
1298    );
1299
1300    assert_chunks_in_ranges(&snapshot);
1301    assert_consistent_line_numbers(&snapshot);
1302    assert_position_translation(&snapshot);
1303    assert_line_indents(&snapshot);
1304
1305    // Edit the buffer before the first hunk
1306    buffer.update(cx, |buffer, cx| {
1307        buffer.edit_via_marked_text(
1308            indoc!(
1309                "
1310                ZERO
1311                one« hundred
1312                  thousand»
1313                TWO
1314                three
1315                six
1316                "
1317            ),
1318            None,
1319            cx,
1320        );
1321    });
1322    assert_new_snapshot(
1323        &multibuffer,
1324        &mut snapshot,
1325        &mut subscription,
1326        cx,
1327        indoc!(
1328            "
1329              ZERO
1330              one hundred
1331                thousand
1332            - two
1333            + TWO
1334              three
1335            - four
1336            - five
1337              six
1338            "
1339        ),
1340    );
1341
1342    assert_chunks_in_ranges(&snapshot);
1343    assert_consistent_line_numbers(&snapshot);
1344    assert_position_translation(&snapshot);
1345    assert_line_indents(&snapshot);
1346
1347    // Recalculate the diff, changing the first diff hunk.
1348    diff.update(cx, |diff, cx| {
1349        diff.recalculate_diff_sync(buffer.read(cx).text_snapshot(), cx);
1350    });
1351    cx.run_until_parked();
1352    assert_new_snapshot(
1353        &multibuffer,
1354        &mut snapshot,
1355        &mut subscription,
1356        cx,
1357        indoc!(
1358            "
1359              ZERO
1360              one hundred
1361                thousand
1362              TWO
1363              three
1364            - four
1365            - five
1366              six
1367            "
1368        ),
1369    );
1370
1371    assert_eq!(
1372        snapshot
1373            .diff_hunks_in_range(0..snapshot.len())
1374            .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0)
1375            .collect::<Vec<_>>(),
1376        &[0..4, 5..7]
1377    );
1378}
1379
1380#[gpui::test]
1381fn test_repeatedly_expand_a_diff_hunk(cx: &mut TestAppContext) {
1382    let text = indoc!(
1383        "
1384        one
1385        TWO
1386        THREE
1387        four
1388        FIVE
1389        six
1390        "
1391    );
1392    let base_text = indoc!(
1393        "
1394        one
1395        four
1396        five
1397        six
1398        "
1399    );
1400
1401    let buffer = cx.new(|cx| Buffer::local(text, cx));
1402    let diff = cx.new(|cx| BufferDiff::new_with_base_text(base_text, &buffer, cx));
1403    cx.run_until_parked();
1404
1405    let multibuffer = cx.new(|cx| {
1406        let mut multibuffer = MultiBuffer::singleton(buffer.clone(), cx);
1407        multibuffer.add_diff(diff.clone(), cx);
1408        multibuffer
1409    });
1410
1411    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
1412        (multibuffer.snapshot(cx), multibuffer.subscribe())
1413    });
1414
1415    multibuffer.update(cx, |multibuffer, cx| {
1416        multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
1417    });
1418
1419    assert_new_snapshot(
1420        &multibuffer,
1421        &mut snapshot,
1422        &mut subscription,
1423        cx,
1424        indoc!(
1425            "
1426              one
1427            + TWO
1428            + THREE
1429              four
1430            - five
1431            + FIVE
1432              six
1433            "
1434        ),
1435    );
1436
1437    // Regression test: expanding diff hunks that are already expanded should not change anything.
1438    multibuffer.update(cx, |multibuffer, cx| {
1439        multibuffer.expand_diff_hunks(
1440            vec![
1441                snapshot.anchor_before(Point::new(2, 0))..snapshot.anchor_before(Point::new(2, 0)),
1442            ],
1443            cx,
1444        );
1445    });
1446
1447    assert_new_snapshot(
1448        &multibuffer,
1449        &mut snapshot,
1450        &mut subscription,
1451        cx,
1452        indoc!(
1453            "
1454              one
1455            + TWO
1456            + THREE
1457              four
1458            - five
1459            + FIVE
1460              six
1461            "
1462        ),
1463    );
1464
1465    // Now collapse all diff hunks
1466    multibuffer.update(cx, |multibuffer, cx| {
1467        multibuffer.collapse_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
1468    });
1469
1470    assert_new_snapshot(
1471        &multibuffer,
1472        &mut snapshot,
1473        &mut subscription,
1474        cx,
1475        indoc!(
1476            "
1477            one
1478            TWO
1479            THREE
1480            four
1481            FIVE
1482            six
1483            "
1484        ),
1485    );
1486
1487    // Expand the hunks again, but this time provide two ranges that are both within the same hunk
1488    // Target the first hunk which is between "one" and "four"
1489    multibuffer.update(cx, |multibuffer, cx| {
1490        multibuffer.expand_diff_hunks(
1491            vec![
1492                snapshot.anchor_before(Point::new(4, 0))..snapshot.anchor_before(Point::new(4, 0)),
1493                snapshot.anchor_before(Point::new(4, 2))..snapshot.anchor_before(Point::new(4, 2)),
1494            ],
1495            cx,
1496        );
1497    });
1498    assert_new_snapshot(
1499        &multibuffer,
1500        &mut snapshot,
1501        &mut subscription,
1502        cx,
1503        indoc!(
1504            "
1505              one
1506              TWO
1507              THREE
1508              four
1509            - five
1510            + FIVE
1511              six
1512            "
1513        ),
1514    );
1515}
1516
1517#[gpui::test]
1518fn test_set_excerpts_for_buffer_ordering(cx: &mut TestAppContext) {
1519    let buf1 = cx.new(|cx| {
1520        Buffer::local(
1521            indoc! {
1522            "zero
1523            one
1524            two
1525            two.five
1526            three
1527            four
1528            five
1529            six
1530            seven
1531            eight
1532            nine
1533            ten
1534            eleven
1535            ",
1536            },
1537            cx,
1538        )
1539    });
1540    let path1: PathKey = PathKey::with_sort_prefix(0, rel_path("root").into_arc());
1541
1542    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
1543    multibuffer.update(cx, |multibuffer, cx| {
1544        multibuffer.set_excerpts_for_path(
1545            path1.clone(),
1546            buf1.clone(),
1547            vec![
1548                Point::row_range(1..2),
1549                Point::row_range(6..7),
1550                Point::row_range(11..12),
1551            ],
1552            1,
1553            cx,
1554        );
1555    });
1556
1557    assert_excerpts_match(
1558        &multibuffer,
1559        cx,
1560        indoc! {
1561            "-----
1562            zero
1563            one
1564            two
1565            two.five
1566            -----
1567            four
1568            five
1569            six
1570            seven
1571            -----
1572            nine
1573            ten
1574            eleven
1575            "
1576        },
1577    );
1578
1579    buf1.update(cx, |buffer, cx| buffer.edit([(0..5, "")], None, cx));
1580
1581    multibuffer.update(cx, |multibuffer, cx| {
1582        multibuffer.set_excerpts_for_path(
1583            path1.clone(),
1584            buf1.clone(),
1585            vec![
1586                Point::row_range(0..3),
1587                Point::row_range(5..7),
1588                Point::row_range(10..11),
1589            ],
1590            1,
1591            cx,
1592        );
1593    });
1594
1595    assert_excerpts_match(
1596        &multibuffer,
1597        cx,
1598        indoc! {
1599            "-----
1600             one
1601             two
1602             two.five
1603             three
1604             four
1605             five
1606             six
1607             seven
1608             eight
1609             nine
1610             ten
1611             eleven
1612            "
1613        },
1614    );
1615}
1616
1617#[gpui::test]
1618fn test_set_excerpts_for_buffer(cx: &mut TestAppContext) {
1619    let buf1 = cx.new(|cx| {
1620        Buffer::local(
1621            indoc! {
1622            "zero
1623            one
1624            two
1625            three
1626            four
1627            five
1628            six
1629            seven
1630            ",
1631            },
1632            cx,
1633        )
1634    });
1635    let path1: PathKey = PathKey::with_sort_prefix(0, rel_path("root").into_arc());
1636    let buf2 = cx.new(|cx| {
1637        Buffer::local(
1638            indoc! {
1639            "000
1640            111
1641            222
1642            333
1643            444
1644            555
1645            666
1646            777
1647            888
1648            999
1649            "
1650            },
1651            cx,
1652        )
1653    });
1654    let path2 = PathKey::with_sort_prefix(1, rel_path("root").into_arc());
1655
1656    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
1657    multibuffer.update(cx, |multibuffer, cx| {
1658        multibuffer.set_excerpts_for_path(
1659            path1.clone(),
1660            buf1.clone(),
1661            vec![Point::row_range(0..1)],
1662            2,
1663            cx,
1664        );
1665    });
1666
1667    assert_excerpts_match(
1668        &multibuffer,
1669        cx,
1670        indoc! {
1671        "-----
1672        zero
1673        one
1674        two
1675        three
1676        "
1677        },
1678    );
1679
1680    multibuffer.update(cx, |multibuffer, cx| {
1681        multibuffer.set_excerpts_for_path(path1.clone(), buf1.clone(), vec![], 2, cx);
1682    });
1683
1684    assert_excerpts_match(&multibuffer, cx, "");
1685
1686    multibuffer.update(cx, |multibuffer, cx| {
1687        multibuffer.set_excerpts_for_path(
1688            path1.clone(),
1689            buf1.clone(),
1690            vec![Point::row_range(0..1), Point::row_range(7..8)],
1691            2,
1692            cx,
1693        );
1694    });
1695
1696    assert_excerpts_match(
1697        &multibuffer,
1698        cx,
1699        indoc! {"-----
1700                zero
1701                one
1702                two
1703                three
1704                -----
1705                five
1706                six
1707                seven
1708                "},
1709    );
1710
1711    multibuffer.update(cx, |multibuffer, cx| {
1712        multibuffer.set_excerpts_for_path(
1713            path1.clone(),
1714            buf1.clone(),
1715            vec![Point::row_range(0..1), Point::row_range(5..6)],
1716            2,
1717            cx,
1718        );
1719    });
1720
1721    assert_excerpts_match(
1722        &multibuffer,
1723        cx,
1724        indoc! {"-----
1725                    zero
1726                    one
1727                    two
1728                    three
1729                    four
1730                    five
1731                    six
1732                    seven
1733                    "},
1734    );
1735
1736    multibuffer.update(cx, |multibuffer, cx| {
1737        multibuffer.set_excerpts_for_path(
1738            path2.clone(),
1739            buf2.clone(),
1740            vec![Point::row_range(2..3)],
1741            2,
1742            cx,
1743        );
1744    });
1745
1746    assert_excerpts_match(
1747        &multibuffer,
1748        cx,
1749        indoc! {"-----
1750                zero
1751                one
1752                two
1753                three
1754                four
1755                five
1756                six
1757                seven
1758                -----
1759                000
1760                111
1761                222
1762                333
1763                444
1764                555
1765                "},
1766    );
1767
1768    multibuffer.update(cx, |multibuffer, cx| {
1769        multibuffer.set_excerpts_for_path(path1.clone(), buf1.clone(), vec![], 2, cx);
1770    });
1771
1772    multibuffer.update(cx, |multibuffer, cx| {
1773        multibuffer.set_excerpts_for_path(
1774            path1.clone(),
1775            buf1.clone(),
1776            vec![Point::row_range(3..4)],
1777            2,
1778            cx,
1779        );
1780    });
1781
1782    assert_excerpts_match(
1783        &multibuffer,
1784        cx,
1785        indoc! {"-----
1786                one
1787                two
1788                three
1789                four
1790                five
1791                six
1792                -----
1793                000
1794                111
1795                222
1796                333
1797                444
1798                555
1799                "},
1800    );
1801
1802    multibuffer.update(cx, |multibuffer, cx| {
1803        multibuffer.set_excerpts_for_path(
1804            path1.clone(),
1805            buf1.clone(),
1806            vec![Point::row_range(3..4)],
1807            2,
1808            cx,
1809        );
1810    });
1811}
1812
1813#[gpui::test]
1814fn test_set_excerpts_for_buffer_rename(cx: &mut TestAppContext) {
1815    let buf1 = cx.new(|cx| {
1816        Buffer::local(
1817            indoc! {
1818            "zero
1819            one
1820            two
1821            three
1822            four
1823            five
1824            six
1825            seven
1826            ",
1827            },
1828            cx,
1829        )
1830    });
1831    let path: PathKey = PathKey::with_sort_prefix(0, rel_path("root").into_arc());
1832    let buf2 = cx.new(|cx| {
1833        Buffer::local(
1834            indoc! {
1835            "000
1836            111
1837            222
1838            333
1839            "
1840            },
1841            cx,
1842        )
1843    });
1844
1845    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
1846    multibuffer.update(cx, |multibuffer, cx| {
1847        multibuffer.set_excerpts_for_path(
1848            path.clone(),
1849            buf1.clone(),
1850            vec![Point::row_range(1..1), Point::row_range(4..5)],
1851            1,
1852            cx,
1853        );
1854    });
1855
1856    assert_excerpts_match(
1857        &multibuffer,
1858        cx,
1859        indoc! {
1860        "-----
1861        zero
1862        one
1863        two
1864        three
1865        four
1866        five
1867        six
1868        "
1869        },
1870    );
1871
1872    multibuffer.update(cx, |multibuffer, cx| {
1873        multibuffer.set_excerpts_for_path(
1874            path.clone(),
1875            buf2.clone(),
1876            vec![Point::row_range(0..1)],
1877            2,
1878            cx,
1879        );
1880    });
1881
1882    assert_excerpts_match(
1883        &multibuffer,
1884        cx,
1885        indoc! {"-----
1886                000
1887                111
1888                222
1889                333
1890                "},
1891    );
1892}
1893
1894#[gpui::test]
1895fn test_diff_hunks_with_multiple_excerpts(cx: &mut TestAppContext) {
1896    let base_text_1 = indoc!(
1897        "
1898        one
1899        two
1900            three
1901        four
1902        five
1903        six
1904        "
1905    );
1906    let text_1 = indoc!(
1907        "
1908        ZERO
1909        one
1910        TWO
1911            three
1912        six
1913        "
1914    );
1915    let base_text_2 = indoc!(
1916        "
1917        seven
1918          eight
1919        nine
1920        ten
1921        eleven
1922        twelve
1923        "
1924    );
1925    let text_2 = indoc!(
1926        "
1927          eight
1928        nine
1929        eleven
1930        THIRTEEN
1931        FOURTEEN
1932        "
1933    );
1934
1935    let buffer_1 = cx.new(|cx| Buffer::local(text_1, cx));
1936    let buffer_2 = cx.new(|cx| Buffer::local(text_2, cx));
1937    let diff_1 = cx.new(|cx| BufferDiff::new_with_base_text(base_text_1, &buffer_1, cx));
1938    let diff_2 = cx.new(|cx| BufferDiff::new_with_base_text(base_text_2, &buffer_2, cx));
1939    cx.run_until_parked();
1940
1941    let multibuffer = cx.new(|cx| {
1942        let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
1943        multibuffer.push_excerpts(
1944            buffer_1.clone(),
1945            [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
1946            cx,
1947        );
1948        multibuffer.push_excerpts(
1949            buffer_2.clone(),
1950            [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
1951            cx,
1952        );
1953        multibuffer.add_diff(diff_1.clone(), cx);
1954        multibuffer.add_diff(diff_2.clone(), cx);
1955        multibuffer
1956    });
1957
1958    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
1959        (multibuffer.snapshot(cx), multibuffer.subscribe())
1960    });
1961    assert_eq!(
1962        snapshot.text(),
1963        indoc!(
1964            "
1965            ZERO
1966            one
1967            TWO
1968                three
1969            six
1970
1971              eight
1972            nine
1973            eleven
1974            THIRTEEN
1975            FOURTEEN
1976            "
1977        ),
1978    );
1979
1980    multibuffer.update(cx, |multibuffer, cx| {
1981        multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
1982    });
1983
1984    assert_new_snapshot(
1985        &multibuffer,
1986        &mut snapshot,
1987        &mut subscription,
1988        cx,
1989        indoc!(
1990            "
1991            + ZERO
1992              one
1993            - two
1994            + TWO
1995                  three
1996            - four
1997            - five
1998              six
1999
2000            - seven
2001                eight
2002              nine
2003            - ten
2004              eleven
2005            - twelve
2006            + THIRTEEN
2007            + FOURTEEN
2008            "
2009        ),
2010    );
2011
2012    let id_1 = buffer_1.read_with(cx, |buffer, _| buffer.remote_id());
2013    let id_2 = buffer_2.read_with(cx, |buffer, _| buffer.remote_id());
2014    let base_id_1 = diff_1.read_with(cx, |diff, _| diff.base_text().remote_id());
2015    let base_id_2 = diff_2.read_with(cx, |diff, _| diff.base_text().remote_id());
2016
2017    let buffer_lines = (0..=snapshot.max_row().0)
2018        .map(|row| {
2019            let (buffer, range) = snapshot.buffer_line_for_row(MultiBufferRow(row))?;
2020            Some((
2021                buffer.remote_id(),
2022                buffer.text_for_range(range).collect::<String>(),
2023            ))
2024        })
2025        .collect::<Vec<_>>();
2026    pretty_assertions::assert_eq!(
2027        buffer_lines,
2028        [
2029            Some((id_1, "ZERO".into())),
2030            Some((id_1, "one".into())),
2031            Some((base_id_1, "two".into())),
2032            Some((id_1, "TWO".into())),
2033            Some((id_1, "    three".into())),
2034            Some((base_id_1, "four".into())),
2035            Some((base_id_1, "five".into())),
2036            Some((id_1, "six".into())),
2037            Some((id_1, "".into())),
2038            Some((base_id_2, "seven".into())),
2039            Some((id_2, "  eight".into())),
2040            Some((id_2, "nine".into())),
2041            Some((base_id_2, "ten".into())),
2042            Some((id_2, "eleven".into())),
2043            Some((base_id_2, "twelve".into())),
2044            Some((id_2, "THIRTEEN".into())),
2045            Some((id_2, "FOURTEEN".into())),
2046            Some((id_2, "".into())),
2047        ]
2048    );
2049
2050    let buffer_ids_by_range = [
2051        (Point::new(0, 0)..Point::new(0, 0), &[id_1] as &[_]),
2052        (Point::new(0, 0)..Point::new(2, 0), &[id_1]),
2053        (Point::new(2, 0)..Point::new(2, 0), &[id_1]),
2054        (Point::new(3, 0)..Point::new(3, 0), &[id_1]),
2055        (Point::new(8, 0)..Point::new(9, 0), &[id_1]),
2056        (Point::new(8, 0)..Point::new(10, 0), &[id_1, id_2]),
2057        (Point::new(9, 0)..Point::new(9, 0), &[id_2]),
2058    ];
2059    for (range, buffer_ids) in buffer_ids_by_range {
2060        assert_eq!(
2061            snapshot
2062                .buffer_ids_for_range(range.clone())
2063                .collect::<Vec<_>>(),
2064            buffer_ids,
2065            "buffer_ids_for_range({range:?}"
2066        );
2067    }
2068
2069    assert_position_translation(&snapshot);
2070    assert_line_indents(&snapshot);
2071
2072    assert_eq!(
2073        snapshot
2074            .diff_hunks_in_range(0..snapshot.len())
2075            .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0)
2076            .collect::<Vec<_>>(),
2077        &[0..1, 2..4, 5..7, 9..10, 12..13, 14..17]
2078    );
2079
2080    buffer_2.update(cx, |buffer, cx| {
2081        buffer.edit_via_marked_text(
2082            indoc!(
2083                "
2084                  eight
2085                «»eleven
2086                THIRTEEN
2087                FOURTEEN
2088                "
2089            ),
2090            None,
2091            cx,
2092        );
2093    });
2094
2095    assert_new_snapshot(
2096        &multibuffer,
2097        &mut snapshot,
2098        &mut subscription,
2099        cx,
2100        indoc!(
2101            "
2102            + ZERO
2103              one
2104            - two
2105            + TWO
2106                  three
2107            - four
2108            - five
2109              six
2110
2111            - seven
2112                eight
2113              eleven
2114            - twelve
2115            + THIRTEEN
2116            + FOURTEEN
2117            "
2118        ),
2119    );
2120
2121    assert_line_indents(&snapshot);
2122}
2123
2124/// A naive implementation of a multi-buffer that does not maintain
2125/// any derived state, used for comparison in a randomized test.
2126#[derive(Default)]
2127struct ReferenceMultibuffer {
2128    excerpts: Vec<ReferenceExcerpt>,
2129    diffs: HashMap<BufferId, Entity<BufferDiff>>,
2130}
2131
2132#[derive(Debug)]
2133struct ReferenceExcerpt {
2134    id: ExcerptId,
2135    buffer: Entity<Buffer>,
2136    range: Range<text::Anchor>,
2137    expanded_diff_hunks: Vec<text::Anchor>,
2138}
2139
2140#[derive(Debug)]
2141struct ReferenceRegion {
2142    buffer_id: Option<BufferId>,
2143    range: Range<usize>,
2144    buffer_start: Option<Point>,
2145    status: Option<DiffHunkStatus>,
2146    excerpt_id: Option<ExcerptId>,
2147}
2148
2149impl ReferenceMultibuffer {
2150    fn expand_excerpts(&mut self, excerpts: &HashSet<ExcerptId>, line_count: u32, cx: &App) {
2151        if line_count == 0 {
2152            return;
2153        }
2154
2155        for id in excerpts {
2156            let excerpt = self.excerpts.iter_mut().find(|e| e.id == *id).unwrap();
2157            let snapshot = excerpt.buffer.read(cx).snapshot();
2158            let mut point_range = excerpt.range.to_point(&snapshot);
2159            point_range.start = Point::new(point_range.start.row.saturating_sub(line_count), 0);
2160            point_range.end =
2161                snapshot.clip_point(Point::new(point_range.end.row + line_count, 0), Bias::Left);
2162            point_range.end.column = snapshot.line_len(point_range.end.row);
2163            excerpt.range =
2164                snapshot.anchor_before(point_range.start)..snapshot.anchor_after(point_range.end);
2165        }
2166    }
2167
2168    fn remove_excerpt(&mut self, id: ExcerptId, cx: &App) {
2169        let ix = self
2170            .excerpts
2171            .iter()
2172            .position(|excerpt| excerpt.id == id)
2173            .unwrap();
2174        let excerpt = self.excerpts.remove(ix);
2175        let buffer = excerpt.buffer.read(cx);
2176        let id = buffer.remote_id();
2177        log::info!(
2178            "Removing excerpt {}: {:?}",
2179            ix,
2180            buffer
2181                .text_for_range(excerpt.range.to_offset(buffer))
2182                .collect::<String>(),
2183        );
2184        if !self
2185            .excerpts
2186            .iter()
2187            .any(|excerpt| excerpt.buffer.read(cx).remote_id() == id)
2188        {
2189            self.diffs.remove(&id);
2190        }
2191    }
2192
2193    fn insert_excerpt_after(
2194        &mut self,
2195        prev_id: ExcerptId,
2196        new_excerpt_id: ExcerptId,
2197        (buffer_handle, anchor_range): (Entity<Buffer>, Range<text::Anchor>),
2198    ) {
2199        let excerpt_ix = if prev_id == ExcerptId::max() {
2200            self.excerpts.len()
2201        } else {
2202            self.excerpts
2203                .iter()
2204                .position(|excerpt| excerpt.id == prev_id)
2205                .unwrap()
2206                + 1
2207        };
2208        self.excerpts.insert(
2209            excerpt_ix,
2210            ReferenceExcerpt {
2211                id: new_excerpt_id,
2212                buffer: buffer_handle,
2213                range: anchor_range,
2214                expanded_diff_hunks: Vec::new(),
2215            },
2216        );
2217    }
2218
2219    fn expand_diff_hunks(&mut self, excerpt_id: ExcerptId, range: Range<text::Anchor>, cx: &App) {
2220        let excerpt = self
2221            .excerpts
2222            .iter_mut()
2223            .find(|e| e.id == excerpt_id)
2224            .unwrap();
2225        let buffer = excerpt.buffer.read(cx).snapshot();
2226        let buffer_id = buffer.remote_id();
2227        let Some(diff) = self.diffs.get(&buffer_id) else {
2228            return;
2229        };
2230        let excerpt_range = excerpt.range.to_offset(&buffer);
2231        for hunk in diff.read(cx).hunks_intersecting_range(range, &buffer, cx) {
2232            let hunk_range = hunk.buffer_range.to_offset(&buffer);
2233            if hunk_range.start < excerpt_range.start || hunk_range.start > excerpt_range.end {
2234                continue;
2235            }
2236            if let Err(ix) = excerpt
2237                .expanded_diff_hunks
2238                .binary_search_by(|anchor| anchor.cmp(&hunk.buffer_range.start, &buffer))
2239            {
2240                log::info!(
2241                    "expanding diff hunk {:?}. excerpt:{:?}, excerpt range:{:?}",
2242                    hunk_range,
2243                    excerpt_id,
2244                    excerpt_range
2245                );
2246                excerpt
2247                    .expanded_diff_hunks
2248                    .insert(ix, hunk.buffer_range.start);
2249            } else {
2250                log::trace!("hunk {hunk_range:?} already expanded in excerpt {excerpt_id:?}");
2251            }
2252        }
2253    }
2254
2255    fn expected_content(&self, cx: &App) -> (String, Vec<RowInfo>, HashSet<MultiBufferRow>) {
2256        let mut text = String::new();
2257        let mut regions = Vec::<ReferenceRegion>::new();
2258        let mut excerpt_boundary_rows = HashSet::default();
2259        for excerpt in &self.excerpts {
2260            excerpt_boundary_rows.insert(MultiBufferRow(text.matches('\n').count() as u32));
2261            let buffer = excerpt.buffer.read(cx);
2262            let buffer_range = excerpt.range.to_offset(buffer);
2263            let diff = self.diffs.get(&buffer.remote_id()).unwrap().read(cx);
2264            let base_buffer = diff.base_text();
2265
2266            let mut offset = buffer_range.start;
2267            let hunks = diff
2268                .hunks_intersecting_range(excerpt.range.clone(), buffer, cx)
2269                .peekable();
2270
2271            for hunk in hunks {
2272                // Ignore hunks that are outside the excerpt range.
2273                let mut hunk_range = hunk.buffer_range.to_offset(buffer);
2274
2275                hunk_range.end = hunk_range.end.min(buffer_range.end);
2276                if hunk_range.start > buffer_range.end || hunk_range.start < buffer_range.start {
2277                    log::trace!("skipping hunk outside excerpt range");
2278                    continue;
2279                }
2280
2281                if !excerpt.expanded_diff_hunks.iter().any(|expanded_anchor| {
2282                    expanded_anchor.to_offset(buffer).max(buffer_range.start)
2283                        == hunk_range.start.max(buffer_range.start)
2284                }) {
2285                    log::trace!("skipping a hunk that's not marked as expanded");
2286                    continue;
2287                }
2288
2289                if !hunk.buffer_range.start.is_valid(buffer) {
2290                    log::trace!("skipping hunk with deleted start: {:?}", hunk.range);
2291                    continue;
2292                }
2293
2294                if hunk_range.start >= offset {
2295                    // Add the buffer text before the hunk
2296                    let len = text.len();
2297                    text.extend(buffer.text_for_range(offset..hunk_range.start));
2298                    regions.push(ReferenceRegion {
2299                        buffer_id: Some(buffer.remote_id()),
2300                        range: len..text.len(),
2301                        buffer_start: Some(buffer.offset_to_point(offset)),
2302                        status: None,
2303                        excerpt_id: Some(excerpt.id),
2304                    });
2305
2306                    // Add the deleted text for the hunk.
2307                    if !hunk.diff_base_byte_range.is_empty() {
2308                        let mut base_text = base_buffer
2309                            .text_for_range(hunk.diff_base_byte_range.clone())
2310                            .collect::<String>();
2311                        if !base_text.ends_with('\n') {
2312                            base_text.push('\n');
2313                        }
2314                        let len = text.len();
2315                        text.push_str(&base_text);
2316                        regions.push(ReferenceRegion {
2317                            buffer_id: Some(base_buffer.remote_id()),
2318                            range: len..text.len(),
2319                            buffer_start: Some(
2320                                base_buffer.offset_to_point(hunk.diff_base_byte_range.start),
2321                            ),
2322                            status: Some(DiffHunkStatus::deleted(hunk.secondary_status)),
2323                            excerpt_id: Some(excerpt.id),
2324                        });
2325                    }
2326
2327                    offset = hunk_range.start;
2328                }
2329
2330                // Add the inserted text for the hunk.
2331                if hunk_range.end > offset {
2332                    let len = text.len();
2333                    text.extend(buffer.text_for_range(offset..hunk_range.end));
2334                    regions.push(ReferenceRegion {
2335                        buffer_id: Some(buffer.remote_id()),
2336                        range: len..text.len(),
2337                        buffer_start: Some(buffer.offset_to_point(offset)),
2338                        status: Some(DiffHunkStatus::added(hunk.secondary_status)),
2339                        excerpt_id: Some(excerpt.id),
2340                    });
2341                    offset = hunk_range.end;
2342                }
2343            }
2344
2345            // Add the buffer text for the rest of the excerpt.
2346            let len = text.len();
2347            text.extend(buffer.text_for_range(offset..buffer_range.end));
2348            text.push('\n');
2349            regions.push(ReferenceRegion {
2350                buffer_id: Some(buffer.remote_id()),
2351                range: len..text.len(),
2352                buffer_start: Some(buffer.offset_to_point(offset)),
2353                status: None,
2354                excerpt_id: Some(excerpt.id),
2355            });
2356        }
2357
2358        // Remove final trailing newline.
2359        if self.excerpts.is_empty() {
2360            regions.push(ReferenceRegion {
2361                buffer_id: None,
2362                range: 0..1,
2363                buffer_start: Some(Point::new(0, 0)),
2364                status: None,
2365                excerpt_id: None,
2366            });
2367        } else {
2368            text.pop();
2369        }
2370
2371        // Retrieve the row info using the region that contains
2372        // the start of each multi-buffer line.
2373        let mut ix = 0;
2374        let row_infos = text
2375            .split('\n')
2376            .map(|line| {
2377                let row_info = regions
2378                    .iter()
2379                    .position(|region| region.range.contains(&ix))
2380                    .map_or(RowInfo::default(), |region_ix| {
2381                        let region = &regions[region_ix];
2382                        let buffer_row = region.buffer_start.map(|start_point| {
2383                            start_point.row
2384                                + text[region.range.start..ix].matches('\n').count() as u32
2385                        });
2386                        let is_excerpt_start = region_ix == 0
2387                            || &regions[region_ix - 1].excerpt_id != &region.excerpt_id
2388                            || regions[region_ix - 1].range.is_empty();
2389                        let mut is_excerpt_end = region_ix == regions.len() - 1
2390                            || &regions[region_ix + 1].excerpt_id != &region.excerpt_id;
2391                        let is_start = !text[region.range.start..ix].contains('\n');
2392                        let mut is_end = if region.range.end > text.len() {
2393                            !text[ix..].contains('\n')
2394                        } else {
2395                            text[ix..region.range.end.min(text.len())]
2396                                .matches('\n')
2397                                .count()
2398                                == 1
2399                        };
2400                        if region_ix < regions.len() - 1
2401                            && !text[ix..].contains("\n")
2402                            && region.status == Some(DiffHunkStatus::added_none())
2403                            && regions[region_ix + 1].excerpt_id == region.excerpt_id
2404                            && regions[region_ix + 1].range.start == text.len()
2405                        {
2406                            is_end = true;
2407                            is_excerpt_end = true;
2408                        }
2409                        let mut expand_direction = None;
2410                        if let Some(buffer) = &self
2411                            .excerpts
2412                            .iter()
2413                            .find(|e| e.id == region.excerpt_id.unwrap())
2414                            .map(|e| e.buffer.clone())
2415                        {
2416                            let needs_expand_up =
2417                                is_excerpt_start && is_start && buffer_row.unwrap() > 0;
2418                            let needs_expand_down = is_excerpt_end
2419                                && is_end
2420                                && buffer.read(cx).max_point().row > buffer_row.unwrap();
2421                            expand_direction = if needs_expand_up && needs_expand_down {
2422                                Some(ExpandExcerptDirection::UpAndDown)
2423                            } else if needs_expand_up {
2424                                Some(ExpandExcerptDirection::Up)
2425                            } else if needs_expand_down {
2426                                Some(ExpandExcerptDirection::Down)
2427                            } else {
2428                                None
2429                            };
2430                        }
2431                        RowInfo {
2432                            buffer_id: region.buffer_id,
2433                            diff_status: region.status,
2434                            buffer_row,
2435                            multibuffer_row: Some(MultiBufferRow(
2436                                text[..ix].matches('\n').count() as u32
2437                            )),
2438                            expand_info: expand_direction.zip(region.excerpt_id).map(
2439                                |(direction, excerpt_id)| ExpandInfo {
2440                                    direction,
2441                                    excerpt_id,
2442                                },
2443                            ),
2444                        }
2445                    });
2446                ix += line.len() + 1;
2447                row_info
2448            })
2449            .collect();
2450
2451        (text, row_infos, excerpt_boundary_rows)
2452    }
2453
2454    fn diffs_updated(&mut self, cx: &App) {
2455        for excerpt in &mut self.excerpts {
2456            let buffer = excerpt.buffer.read(cx).snapshot();
2457            let excerpt_range = excerpt.range.to_offset(&buffer);
2458            let buffer_id = buffer.remote_id();
2459            let diff = self.diffs.get(&buffer_id).unwrap().read(cx);
2460            let mut hunks = diff.hunks_in_row_range(0..u32::MAX, &buffer, cx).peekable();
2461            excerpt.expanded_diff_hunks.retain(|hunk_anchor| {
2462                if !hunk_anchor.is_valid(&buffer) {
2463                    return false;
2464                }
2465                while let Some(hunk) = hunks.peek() {
2466                    match hunk.buffer_range.start.cmp(hunk_anchor, &buffer) {
2467                        cmp::Ordering::Less => {
2468                            hunks.next();
2469                        }
2470                        cmp::Ordering::Equal => {
2471                            let hunk_range = hunk.buffer_range.to_offset(&buffer);
2472                            return hunk_range.end >= excerpt_range.start
2473                                && hunk_range.start <= excerpt_range.end;
2474                        }
2475                        cmp::Ordering::Greater => break,
2476                    }
2477                }
2478                false
2479            });
2480        }
2481    }
2482
2483    fn add_diff(&mut self, diff: Entity<BufferDiff>, cx: &mut App) {
2484        let buffer_id = diff.read(cx).buffer_id;
2485        self.diffs.insert(buffer_id, diff);
2486    }
2487}
2488
2489#[gpui::test(iterations = 100)]
2490async fn test_random_set_ranges(cx: &mut TestAppContext, mut rng: StdRng) {
2491    let base_text = "a\n".repeat(100);
2492    let buf = cx.update(|cx| cx.new(|cx| Buffer::local(base_text, cx)));
2493    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2494
2495    let operations = env::var("OPERATIONS")
2496        .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2497        .unwrap_or(10);
2498
2499    fn row_ranges(ranges: &Vec<Range<Point>>) -> Vec<Range<u32>> {
2500        ranges
2501            .iter()
2502            .map(|range| range.start.row..range.end.row)
2503            .collect()
2504    }
2505
2506    for _ in 0..operations {
2507        let snapshot = buf.update(cx, |buf, _| buf.snapshot());
2508        let num_ranges = rng.random_range(0..=10);
2509        let max_row = snapshot.max_point().row;
2510        let mut ranges = (0..num_ranges)
2511            .map(|_| {
2512                let start = rng.random_range(0..max_row);
2513                let end = rng.random_range(start + 1..max_row + 1);
2514                Point::row_range(start..end)
2515            })
2516            .collect::<Vec<_>>();
2517        ranges.sort_by_key(|range| range.start);
2518        log::info!("Setting ranges: {:?}", row_ranges(&ranges));
2519        let (created, _) = multibuffer.update(cx, |multibuffer, cx| {
2520            multibuffer.set_excerpts_for_path(
2521                PathKey::for_buffer(&buf, cx),
2522                buf.clone(),
2523                ranges.clone(),
2524                2,
2525                cx,
2526            )
2527        });
2528
2529        assert_eq!(created.len(), ranges.len());
2530
2531        let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2532        let mut last_end = None;
2533        let mut seen_ranges = Vec::default();
2534
2535        for (_, buf, range) in snapshot.excerpts() {
2536            let start = range.context.start.to_point(buf);
2537            let end = range.context.end.to_point(buf);
2538            seen_ranges.push(start..end);
2539
2540            if let Some(last_end) = last_end.take() {
2541                assert!(
2542                    start > last_end,
2543                    "multibuffer has out-of-order ranges: {:?}; {:?} <= {:?}",
2544                    row_ranges(&seen_ranges),
2545                    start,
2546                    last_end
2547                )
2548            }
2549
2550            ranges.retain(|range| range.start < start || range.end > end);
2551
2552            last_end = Some(end)
2553        }
2554
2555        assert!(
2556            ranges.is_empty(),
2557            "multibuffer {:?} did not include all ranges: {:?}",
2558            row_ranges(&seen_ranges),
2559            row_ranges(&ranges)
2560        );
2561    }
2562}
2563
2564#[gpui::test(iterations = 100)]
2565async fn test_random_multibuffer(cx: &mut TestAppContext, mut rng: StdRng) {
2566    let operations = env::var("OPERATIONS")
2567        .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2568        .unwrap_or(10);
2569
2570    let mut buffers: Vec<Entity<Buffer>> = Vec::new();
2571    let mut base_texts: HashMap<BufferId, String> = HashMap::default();
2572    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2573    let mut reference = ReferenceMultibuffer::default();
2574    let mut anchors = Vec::new();
2575    let mut old_versions = Vec::new();
2576    let mut needs_diff_calculation = false;
2577
2578    for _ in 0..operations {
2579        match rng.random_range(0..100) {
2580            0..=14 if !buffers.is_empty() => {
2581                let buffer = buffers.choose(&mut rng).unwrap();
2582                buffer.update(cx, |buf, cx| {
2583                    let edit_count = rng.random_range(1..5);
2584                    buf.randomly_edit(&mut rng, edit_count, cx);
2585                    log::info!("buffer text:\n{}", buf.text());
2586                    needs_diff_calculation = true;
2587                });
2588                cx.update(|cx| reference.diffs_updated(cx));
2589            }
2590            15..=19 if !reference.excerpts.is_empty() => {
2591                multibuffer.update(cx, |multibuffer, cx| {
2592                    let ids = multibuffer.excerpt_ids();
2593                    let mut excerpts = HashSet::default();
2594                    for _ in 0..rng.random_range(0..ids.len()) {
2595                        excerpts.extend(ids.choose(&mut rng).copied());
2596                    }
2597
2598                    let line_count = rng.random_range(0..5);
2599
2600                    let excerpt_ixs = excerpts
2601                        .iter()
2602                        .map(|id| reference.excerpts.iter().position(|e| e.id == *id).unwrap())
2603                        .collect::<Vec<_>>();
2604                    log::info!("Expanding excerpts {excerpt_ixs:?} by {line_count} lines");
2605                    multibuffer.expand_excerpts(
2606                        excerpts.iter().cloned(),
2607                        line_count,
2608                        ExpandExcerptDirection::UpAndDown,
2609                        cx,
2610                    );
2611
2612                    reference.expand_excerpts(&excerpts, line_count, cx);
2613                });
2614            }
2615            20..=29 if !reference.excerpts.is_empty() => {
2616                let mut ids_to_remove = vec![];
2617                for _ in 0..rng.random_range(1..=3) {
2618                    let Some(excerpt) = reference.excerpts.choose(&mut rng) else {
2619                        break;
2620                    };
2621                    let id = excerpt.id;
2622                    cx.update(|cx| reference.remove_excerpt(id, cx));
2623                    ids_to_remove.push(id);
2624                }
2625                let snapshot =
2626                    multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2627                ids_to_remove.sort_unstable_by(|a, b| a.cmp(b, &snapshot));
2628                drop(snapshot);
2629                multibuffer.update(cx, |multibuffer, cx| {
2630                    multibuffer.remove_excerpts(ids_to_remove, cx)
2631                });
2632            }
2633            30..=39 if !reference.excerpts.is_empty() => {
2634                let multibuffer =
2635                    multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2636                let offset =
2637                    multibuffer.clip_offset(rng.random_range(0..=multibuffer.len()), Bias::Left);
2638                let bias = if rng.random() {
2639                    Bias::Left
2640                } else {
2641                    Bias::Right
2642                };
2643                log::info!("Creating anchor at {} with bias {:?}", offset, bias);
2644                anchors.push(multibuffer.anchor_at(offset, bias));
2645                anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
2646            }
2647            40..=44 if !anchors.is_empty() => {
2648                let multibuffer =
2649                    multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2650                let prev_len = anchors.len();
2651                anchors = multibuffer
2652                    .refresh_anchors(&anchors)
2653                    .into_iter()
2654                    .map(|a| a.1)
2655                    .collect();
2656
2657                // Ensure the newly-refreshed anchors point to a valid excerpt and don't
2658                // overshoot its boundaries.
2659                assert_eq!(anchors.len(), prev_len);
2660                for anchor in &anchors {
2661                    if anchor.excerpt_id == ExcerptId::min()
2662                        || anchor.excerpt_id == ExcerptId::max()
2663                    {
2664                        continue;
2665                    }
2666
2667                    let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
2668                    assert_eq!(excerpt.id, anchor.excerpt_id);
2669                    assert!(excerpt.contains(anchor));
2670                }
2671            }
2672            45..=55 if !reference.excerpts.is_empty() => {
2673                multibuffer.update(cx, |multibuffer, cx| {
2674                    let snapshot = multibuffer.snapshot(cx);
2675                    let excerpt_ix = rng.random_range(0..reference.excerpts.len());
2676                    let excerpt = &reference.excerpts[excerpt_ix];
2677                    let start = excerpt.range.start;
2678                    let end = excerpt.range.end;
2679                    let range = snapshot.anchor_in_excerpt(excerpt.id, start).unwrap()
2680                        ..snapshot.anchor_in_excerpt(excerpt.id, end).unwrap();
2681
2682                    log::info!(
2683                        "expanding diff hunks in range {:?} (excerpt id {:?}, index {excerpt_ix:?}, buffer id {:?})",
2684                        range.to_offset(&snapshot),
2685                        excerpt.id,
2686                        excerpt.buffer.read(cx).remote_id(),
2687                    );
2688                    reference.expand_diff_hunks(excerpt.id, start..end, cx);
2689                    multibuffer.expand_diff_hunks(vec![range], cx);
2690                });
2691            }
2692            56..=85 if needs_diff_calculation => {
2693                multibuffer.update(cx, |multibuffer, cx| {
2694                    for buffer in multibuffer.all_buffers() {
2695                        let snapshot = buffer.read(cx).snapshot();
2696                        multibuffer.diff_for(snapshot.remote_id()).unwrap().update(
2697                            cx,
2698                            |diff, cx| {
2699                                log::info!(
2700                                    "recalculating diff for buffer {:?}",
2701                                    snapshot.remote_id(),
2702                                );
2703                                diff.recalculate_diff_sync(snapshot.text, cx);
2704                            },
2705                        );
2706                    }
2707                    reference.diffs_updated(cx);
2708                    needs_diff_calculation = false;
2709                });
2710            }
2711            _ => {
2712                let buffer_handle = if buffers.is_empty() || rng.random_bool(0.4) {
2713                    let mut base_text = util::RandomCharIter::new(&mut rng)
2714                        .take(256)
2715                        .collect::<String>();
2716
2717                    let buffer = cx.new(|cx| Buffer::local(base_text.clone(), cx));
2718                    text::LineEnding::normalize(&mut base_text);
2719                    base_texts.insert(
2720                        buffer.read_with(cx, |buffer, _| buffer.remote_id()),
2721                        base_text,
2722                    );
2723                    buffers.push(buffer);
2724                    buffers.last().unwrap()
2725                } else {
2726                    buffers.choose(&mut rng).unwrap()
2727                };
2728
2729                let prev_excerpt_ix = rng.random_range(0..=reference.excerpts.len());
2730                let prev_excerpt_id = reference
2731                    .excerpts
2732                    .get(prev_excerpt_ix)
2733                    .map_or(ExcerptId::max(), |e| e.id);
2734                let excerpt_ix = (prev_excerpt_ix + 1).min(reference.excerpts.len());
2735
2736                let (range, anchor_range) = buffer_handle.read_with(cx, |buffer, _| {
2737                    let end_row = rng.random_range(0..=buffer.max_point().row);
2738                    let start_row = rng.random_range(0..=end_row);
2739                    let end_ix = buffer.point_to_offset(Point::new(end_row, 0));
2740                    let start_ix = buffer.point_to_offset(Point::new(start_row, 0));
2741                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
2742
2743                    log::info!(
2744                        "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
2745                        excerpt_ix,
2746                        reference.excerpts.len(),
2747                        buffer.remote_id(),
2748                        buffer.text(),
2749                        start_ix..end_ix,
2750                        &buffer.text()[start_ix..end_ix]
2751                    );
2752
2753                    (start_ix..end_ix, anchor_range)
2754                });
2755
2756                multibuffer.update(cx, |multibuffer, cx| {
2757                    let id = buffer_handle.read(cx).remote_id();
2758                    if multibuffer.diff_for(id).is_none() {
2759                        let base_text = base_texts.get(&id).unwrap();
2760                        let diff = cx
2761                            .new(|cx| BufferDiff::new_with_base_text(base_text, buffer_handle, cx));
2762                        reference.add_diff(diff.clone(), cx);
2763                        multibuffer.add_diff(diff, cx)
2764                    }
2765                });
2766
2767                let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
2768                    multibuffer
2769                        .insert_excerpts_after(
2770                            prev_excerpt_id,
2771                            buffer_handle.clone(),
2772                            [ExcerptRange::new(range.clone())],
2773                            cx,
2774                        )
2775                        .pop()
2776                        .unwrap()
2777                });
2778
2779                reference.insert_excerpt_after(
2780                    prev_excerpt_id,
2781                    excerpt_id,
2782                    (buffer_handle.clone(), anchor_range),
2783                );
2784            }
2785        }
2786
2787        if rng.random_bool(0.3) {
2788            multibuffer.update(cx, |multibuffer, cx| {
2789                old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
2790            })
2791        }
2792
2793        let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2794        let actual_text = snapshot.text();
2795        let actual_boundary_rows = snapshot
2796            .excerpt_boundaries_in_range(0..)
2797            .map(|b| b.row)
2798            .collect::<HashSet<_>>();
2799        let actual_row_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
2800
2801        let (expected_text, expected_row_infos, expected_boundary_rows) =
2802            cx.update(|cx| reference.expected_content(cx));
2803
2804        let has_diff = actual_row_infos
2805            .iter()
2806            .any(|info| info.diff_status.is_some())
2807            || expected_row_infos
2808                .iter()
2809                .any(|info| info.diff_status.is_some());
2810        let actual_diff = format_diff(
2811            &actual_text,
2812            &actual_row_infos,
2813            &actual_boundary_rows,
2814            Some(has_diff),
2815        );
2816        let expected_diff = format_diff(
2817            &expected_text,
2818            &expected_row_infos,
2819            &expected_boundary_rows,
2820            Some(has_diff),
2821        );
2822
2823        log::info!("Multibuffer content:\n{}", actual_diff);
2824
2825        assert_eq!(
2826            actual_row_infos.len(),
2827            actual_text.split('\n').count(),
2828            "line count: {}",
2829            actual_text.split('\n').count()
2830        );
2831        pretty_assertions::assert_eq!(actual_diff, expected_diff);
2832        pretty_assertions::assert_eq!(actual_text, expected_text);
2833        pretty_assertions::assert_eq!(actual_row_infos, expected_row_infos);
2834
2835        for _ in 0..5 {
2836            let start_row = rng.random_range(0..=expected_row_infos.len());
2837            assert_eq!(
2838                snapshot
2839                    .row_infos(MultiBufferRow(start_row as u32))
2840                    .collect::<Vec<_>>(),
2841                &expected_row_infos[start_row..],
2842                "buffer_rows({})",
2843                start_row
2844            );
2845        }
2846
2847        assert_eq!(
2848            snapshot.widest_line_number(),
2849            expected_row_infos
2850                .into_iter()
2851                .filter_map(|info| {
2852                    if info.diff_status.is_some_and(|status| status.is_deleted()) {
2853                        None
2854                    } else {
2855                        info.buffer_row
2856                    }
2857                })
2858                .max()
2859                .unwrap()
2860                + 1
2861        );
2862        let reference_ranges = cx.update(|cx| {
2863            reference
2864                .excerpts
2865                .iter()
2866                .map(|excerpt| {
2867                    (
2868                        excerpt.id,
2869                        excerpt.range.to_offset(&excerpt.buffer.read(cx).snapshot()),
2870                    )
2871                })
2872                .collect::<HashMap<_, _>>()
2873        });
2874        for i in 0..snapshot.len() {
2875            let excerpt = snapshot.excerpt_containing(i..i).unwrap();
2876            assert_eq!(excerpt.buffer_range(), reference_ranges[&excerpt.id()]);
2877        }
2878
2879        assert_consistent_line_numbers(&snapshot);
2880        assert_position_translation(&snapshot);
2881
2882        for (row, line) in expected_text.split('\n').enumerate() {
2883            assert_eq!(
2884                snapshot.line_len(MultiBufferRow(row as u32)),
2885                line.len() as u32,
2886                "line_len({}).",
2887                row
2888            );
2889        }
2890
2891        let text_rope = Rope::from(expected_text.as_str());
2892        for _ in 0..10 {
2893            let end_ix = text_rope.clip_offset(rng.random_range(0..=text_rope.len()), Bias::Right);
2894            let start_ix = text_rope.clip_offset(rng.random_range(0..=end_ix), Bias::Left);
2895
2896            let text_for_range = snapshot
2897                .text_for_range(start_ix..end_ix)
2898                .collect::<String>();
2899            assert_eq!(
2900                text_for_range,
2901                &expected_text[start_ix..end_ix],
2902                "incorrect text for range {:?}",
2903                start_ix..end_ix
2904            );
2905
2906            let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
2907            assert_eq!(
2908                snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
2909                expected_summary,
2910                "incorrect summary for range {:?}",
2911                start_ix..end_ix
2912            );
2913        }
2914
2915        // Anchor resolution
2916        let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
2917        assert_eq!(anchors.len(), summaries.len());
2918        for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
2919            assert!(resolved_offset <= snapshot.len());
2920            assert_eq!(
2921                snapshot.summary_for_anchor::<usize>(anchor),
2922                resolved_offset,
2923                "anchor: {:?}",
2924                anchor
2925            );
2926        }
2927
2928        for _ in 0..10 {
2929            let end_ix = text_rope.clip_offset(rng.random_range(0..=text_rope.len()), Bias::Right);
2930            assert_eq!(
2931                snapshot.reversed_chars_at(end_ix).collect::<String>(),
2932                expected_text[..end_ix].chars().rev().collect::<String>(),
2933            );
2934        }
2935
2936        for _ in 0..10 {
2937            let end_ix = rng.random_range(0..=text_rope.len());
2938            let start_ix = rng.random_range(0..=end_ix);
2939            assert_eq!(
2940                snapshot
2941                    .bytes_in_range(start_ix..end_ix)
2942                    .flatten()
2943                    .copied()
2944                    .collect::<Vec<_>>(),
2945                expected_text.as_bytes()[start_ix..end_ix].to_vec(),
2946                "bytes_in_range({:?})",
2947                start_ix..end_ix,
2948            );
2949        }
2950    }
2951
2952    let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2953    for (old_snapshot, subscription) in old_versions {
2954        let edits = subscription.consume().into_inner();
2955
2956        log::info!(
2957            "applying subscription edits to old text: {:?}: {:?}",
2958            old_snapshot.text(),
2959            edits,
2960        );
2961
2962        let mut text = old_snapshot.text();
2963        for edit in edits {
2964            let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
2965            text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
2966        }
2967        assert_eq!(text.to_string(), snapshot.text());
2968    }
2969}
2970
2971#[gpui::test]
2972fn test_history(cx: &mut App) {
2973    let test_settings = SettingsStore::test(cx);
2974    cx.set_global(test_settings);
2975    let group_interval: Duration = Duration::from_millis(1);
2976    let buffer_1 = cx.new(|cx| {
2977        let mut buf = Buffer::local("1234", cx);
2978        buf.set_group_interval(group_interval);
2979        buf
2980    });
2981    let buffer_2 = cx.new(|cx| {
2982        let mut buf = Buffer::local("5678", cx);
2983        buf.set_group_interval(group_interval);
2984        buf
2985    });
2986    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2987    multibuffer.update(cx, |this, _| {
2988        this.set_group_interval(group_interval);
2989    });
2990    multibuffer.update(cx, |multibuffer, cx| {
2991        multibuffer.push_excerpts(
2992            buffer_1.clone(),
2993            [ExcerptRange::new(0..buffer_1.read(cx).len())],
2994            cx,
2995        );
2996        multibuffer.push_excerpts(
2997            buffer_2.clone(),
2998            [ExcerptRange::new(0..buffer_2.read(cx).len())],
2999            cx,
3000        );
3001    });
3002
3003    let mut now = Instant::now();
3004
3005    multibuffer.update(cx, |multibuffer, cx| {
3006        let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
3007        multibuffer.edit(
3008            [
3009                (Point::new(0, 0)..Point::new(0, 0), "A"),
3010                (Point::new(1, 0)..Point::new(1, 0), "A"),
3011            ],
3012            None,
3013            cx,
3014        );
3015        multibuffer.edit(
3016            [
3017                (Point::new(0, 1)..Point::new(0, 1), "B"),
3018                (Point::new(1, 1)..Point::new(1, 1), "B"),
3019            ],
3020            None,
3021            cx,
3022        );
3023        multibuffer.end_transaction_at(now, cx);
3024        assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3025
3026        // Verify edited ranges for transaction 1
3027        assert_eq!(
3028            multibuffer.edited_ranges_for_transaction(transaction_1, cx),
3029            &[
3030                Point::new(0, 0)..Point::new(0, 2),
3031                Point::new(1, 0)..Point::new(1, 2)
3032            ]
3033        );
3034
3035        // Edit buffer 1 through the multibuffer
3036        now += 2 * group_interval;
3037        multibuffer.start_transaction_at(now, cx);
3038        multibuffer.edit([(2..2, "C")], None, cx);
3039        multibuffer.end_transaction_at(now, cx);
3040        assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3041
3042        // Edit buffer 1 independently
3043        buffer_1.update(cx, |buffer_1, cx| {
3044            buffer_1.start_transaction_at(now);
3045            buffer_1.edit([(3..3, "D")], None, cx);
3046            buffer_1.end_transaction_at(now, cx);
3047
3048            now += 2 * group_interval;
3049            buffer_1.start_transaction_at(now);
3050            buffer_1.edit([(4..4, "E")], None, cx);
3051            buffer_1.end_transaction_at(now, cx);
3052        });
3053        assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
3054
3055        // An undo in the multibuffer undoes the multibuffer transaction
3056        // and also any individual buffer edits that have occurred since
3057        // that transaction.
3058        multibuffer.undo(cx);
3059        assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3060
3061        multibuffer.undo(cx);
3062        assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3063
3064        multibuffer.redo(cx);
3065        assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3066
3067        multibuffer.redo(cx);
3068        assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
3069
3070        // Undo buffer 2 independently.
3071        buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
3072        assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
3073
3074        // An undo in the multibuffer undoes the components of the
3075        // the last multibuffer transaction that are not already undone.
3076        multibuffer.undo(cx);
3077        assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
3078
3079        multibuffer.undo(cx);
3080        assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3081
3082        multibuffer.redo(cx);
3083        assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3084
3085        buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
3086        assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
3087
3088        // Redo stack gets cleared after an edit.
3089        now += 2 * group_interval;
3090        multibuffer.start_transaction_at(now, cx);
3091        multibuffer.edit([(0..0, "X")], None, cx);
3092        multibuffer.end_transaction_at(now, cx);
3093        assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3094        multibuffer.redo(cx);
3095        assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3096        multibuffer.undo(cx);
3097        assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
3098        multibuffer.undo(cx);
3099        assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3100
3101        // Transactions can be grouped manually.
3102        multibuffer.redo(cx);
3103        multibuffer.redo(cx);
3104        assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3105        multibuffer.group_until_transaction(transaction_1, cx);
3106        multibuffer.undo(cx);
3107        assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3108        multibuffer.redo(cx);
3109        assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3110    });
3111}
3112
3113#[gpui::test]
3114async fn test_enclosing_indent(cx: &mut TestAppContext) {
3115    async fn enclosing_indent(
3116        text: &str,
3117        buffer_row: u32,
3118        cx: &mut TestAppContext,
3119    ) -> Option<(Range<u32>, LineIndent)> {
3120        let buffer = cx.update(|cx| MultiBuffer::build_simple(text, cx));
3121        let snapshot = cx.read(|cx| buffer.read(cx).snapshot(cx));
3122        let (range, indent) = snapshot
3123            .enclosing_indent(MultiBufferRow(buffer_row))
3124            .await?;
3125        Some((range.start.0..range.end.0, indent))
3126    }
3127
3128    assert_eq!(
3129        enclosing_indent(
3130            indoc!(
3131                "
3132                fn b() {
3133                    if c {
3134                        let d = 2;
3135                    }
3136                }
3137                "
3138            ),
3139            1,
3140            cx,
3141        )
3142        .await,
3143        Some((
3144            1..2,
3145            LineIndent {
3146                tabs: 0,
3147                spaces: 4,
3148                line_blank: false,
3149            }
3150        ))
3151    );
3152
3153    assert_eq!(
3154        enclosing_indent(
3155            indoc!(
3156                "
3157                fn b() {
3158                    if c {
3159                        let d = 2;
3160                    }
3161                }
3162                "
3163            ),
3164            2,
3165            cx,
3166        )
3167        .await,
3168        Some((
3169            1..2,
3170            LineIndent {
3171                tabs: 0,
3172                spaces: 4,
3173                line_blank: false,
3174            }
3175        ))
3176    );
3177
3178    assert_eq!(
3179        enclosing_indent(
3180            indoc!(
3181                "
3182                fn b() {
3183                    if c {
3184                        let d = 2;
3185
3186                        let e = 5;
3187                    }
3188                }
3189                "
3190            ),
3191            3,
3192            cx,
3193        )
3194        .await,
3195        Some((
3196            1..4,
3197            LineIndent {
3198                tabs: 0,
3199                spaces: 4,
3200                line_blank: false,
3201            }
3202        ))
3203    );
3204}
3205
3206#[gpui::test]
3207fn test_summaries_for_anchors(cx: &mut TestAppContext) {
3208    let base_text_1 = indoc!(
3209        "
3210        bar
3211        "
3212    );
3213    let text_1 = indoc!(
3214        "
3215        BAR
3216        "
3217    );
3218    let base_text_2 = indoc!(
3219        "
3220        foo
3221        "
3222    );
3223    let text_2 = indoc!(
3224        "
3225        FOO
3226        "
3227    );
3228
3229    let buffer_1 = cx.new(|cx| Buffer::local(text_1, cx));
3230    let buffer_2 = cx.new(|cx| Buffer::local(text_2, cx));
3231    let diff_1 = cx.new(|cx| BufferDiff::new_with_base_text(base_text_1, &buffer_1, cx));
3232    let diff_2 = cx.new(|cx| BufferDiff::new_with_base_text(base_text_2, &buffer_2, cx));
3233    cx.run_until_parked();
3234
3235    let mut ids = vec![];
3236    let multibuffer = cx.new(|cx| {
3237        let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
3238        multibuffer.set_all_diff_hunks_expanded(cx);
3239        ids.extend(multibuffer.push_excerpts(
3240            buffer_1.clone(),
3241            [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
3242            cx,
3243        ));
3244        ids.extend(multibuffer.push_excerpts(
3245            buffer_2.clone(),
3246            [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
3247            cx,
3248        ));
3249        multibuffer.add_diff(diff_1.clone(), cx);
3250        multibuffer.add_diff(diff_2.clone(), cx);
3251        multibuffer
3252    });
3253
3254    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3255        (multibuffer.snapshot(cx), multibuffer.subscribe())
3256    });
3257
3258    assert_new_snapshot(
3259        &multibuffer,
3260        &mut snapshot,
3261        &mut subscription,
3262        cx,
3263        indoc!(
3264            "
3265            - bar
3266            + BAR
3267
3268            - foo
3269            + FOO
3270            "
3271        ),
3272    );
3273
3274    let id_1 = buffer_1.read_with(cx, |buffer, _| buffer.remote_id());
3275    let id_2 = buffer_2.read_with(cx, |buffer, _| buffer.remote_id());
3276
3277    let anchor_1 = Anchor::in_buffer(ids[0], id_1, text::Anchor::MIN);
3278    let point_1 = snapshot.summaries_for_anchors::<Point, _>([&anchor_1])[0];
3279    assert_eq!(point_1, Point::new(0, 0));
3280
3281    let anchor_2 = Anchor::in_buffer(ids[1], id_2, text::Anchor::MIN);
3282    let point_2 = snapshot.summaries_for_anchors::<Point, _>([&anchor_2])[0];
3283    assert_eq!(point_2, Point::new(3, 0));
3284}
3285
3286#[gpui::test]
3287fn test_trailing_deletion_without_newline(cx: &mut TestAppContext) {
3288    let base_text_1 = "one\ntwo".to_owned();
3289    let text_1 = "one\n".to_owned();
3290
3291    let buffer_1 = cx.new(|cx| Buffer::local(text_1, cx));
3292    let diff_1 = cx.new(|cx| BufferDiff::new_with_base_text(&base_text_1, &buffer_1, cx));
3293    cx.run_until_parked();
3294
3295    let multibuffer = cx.new(|cx| {
3296        let mut multibuffer = MultiBuffer::singleton(buffer_1.clone(), cx);
3297        multibuffer.add_diff(diff_1.clone(), cx);
3298        multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
3299        multibuffer
3300    });
3301
3302    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3303        (multibuffer.snapshot(cx), multibuffer.subscribe())
3304    });
3305
3306    assert_new_snapshot(
3307        &multibuffer,
3308        &mut snapshot,
3309        &mut subscription,
3310        cx,
3311        indoc!(
3312            "
3313              one
3314            - two
3315            "
3316        ),
3317    );
3318
3319    assert_eq!(snapshot.max_point(), Point::new(2, 0));
3320    assert_eq!(snapshot.len(), 8);
3321
3322    assert_eq!(
3323        snapshot
3324            .dimensions_from_points::<Point>([Point::new(2, 0)])
3325            .collect::<Vec<_>>(),
3326        vec![Point::new(2, 0)]
3327    );
3328
3329    let (_, translated_offset) = snapshot.point_to_buffer_offset(Point::new(2, 0)).unwrap();
3330    assert_eq!(translated_offset, "one\n".len());
3331    let (_, translated_point, _) = snapshot.point_to_buffer_point(Point::new(2, 0)).unwrap();
3332    assert_eq!(translated_point, Point::new(1, 0));
3333
3334    // The same, for an excerpt that's not at the end of the multibuffer.
3335
3336    let text_2 = "foo\n".to_owned();
3337    let buffer_2 = cx.new(|cx| Buffer::local(&text_2, cx));
3338    multibuffer.update(cx, |multibuffer, cx| {
3339        multibuffer.push_excerpts(
3340            buffer_2.clone(),
3341            [ExcerptRange::new(Point::new(0, 0)..Point::new(1, 0))],
3342            cx,
3343        );
3344    });
3345
3346    assert_new_snapshot(
3347        &multibuffer,
3348        &mut snapshot,
3349        &mut subscription,
3350        cx,
3351        indoc!(
3352            "
3353              one
3354            - two
3355
3356              foo
3357            "
3358        ),
3359    );
3360
3361    assert_eq!(
3362        snapshot
3363            .dimensions_from_points::<Point>([Point::new(2, 0)])
3364            .collect::<Vec<_>>(),
3365        vec![Point::new(2, 0)]
3366    );
3367
3368    let buffer_1_id = buffer_1.read_with(cx, |buffer_1, _| buffer_1.remote_id());
3369    let (buffer, translated_offset) = snapshot.point_to_buffer_offset(Point::new(2, 0)).unwrap();
3370    assert_eq!(buffer.remote_id(), buffer_1_id);
3371    assert_eq!(translated_offset, "one\n".len());
3372    let (buffer, translated_point, _) = snapshot.point_to_buffer_point(Point::new(2, 0)).unwrap();
3373    assert_eq!(buffer.remote_id(), buffer_1_id);
3374    assert_eq!(translated_point, Point::new(1, 0));
3375}
3376
3377fn format_diff(
3378    text: &str,
3379    row_infos: &Vec<RowInfo>,
3380    boundary_rows: &HashSet<MultiBufferRow>,
3381    has_diff: Option<bool>,
3382) -> String {
3383    let has_diff =
3384        has_diff.unwrap_or_else(|| row_infos.iter().any(|info| info.diff_status.is_some()));
3385    text.split('\n')
3386        .enumerate()
3387        .zip(row_infos)
3388        .map(|((ix, line), info)| {
3389            let marker = match info.diff_status.map(|status| status.kind) {
3390                Some(DiffHunkStatusKind::Added) => "+ ",
3391                Some(DiffHunkStatusKind::Deleted) => "- ",
3392                Some(DiffHunkStatusKind::Modified) => unreachable!(),
3393                None => {
3394                    if has_diff && !line.is_empty() {
3395                        "  "
3396                    } else {
3397                        ""
3398                    }
3399                }
3400            };
3401            let boundary_row = if boundary_rows.contains(&MultiBufferRow(ix as u32)) {
3402                if has_diff {
3403                    "  ----------\n"
3404                } else {
3405                    "---------\n"
3406                }
3407            } else {
3408                ""
3409            };
3410            format!("{boundary_row}{marker}{line}")
3411        })
3412        .collect::<Vec<_>>()
3413        .join("\n")
3414}
3415
3416#[track_caller]
3417fn assert_excerpts_match(
3418    multibuffer: &Entity<MultiBuffer>,
3419    cx: &mut TestAppContext,
3420    expected: &str,
3421) {
3422    let mut output = String::new();
3423    multibuffer.read_with(cx, |multibuffer, cx| {
3424        for (_, buffer, range) in multibuffer.snapshot(cx).excerpts() {
3425            output.push_str("-----\n");
3426            output.extend(buffer.text_for_range(range.context));
3427            if !output.ends_with('\n') {
3428                output.push('\n');
3429            }
3430        }
3431    });
3432    assert_eq!(output, expected);
3433}
3434
3435#[track_caller]
3436fn assert_new_snapshot(
3437    multibuffer: &Entity<MultiBuffer>,
3438    snapshot: &mut MultiBufferSnapshot,
3439    subscription: &mut Subscription,
3440    cx: &mut TestAppContext,
3441    expected_diff: &str,
3442) {
3443    let new_snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
3444    let actual_text = new_snapshot.text();
3445    let line_infos = new_snapshot
3446        .row_infos(MultiBufferRow(0))
3447        .collect::<Vec<_>>();
3448    let actual_diff = format_diff(&actual_text, &line_infos, &Default::default(), None);
3449    pretty_assertions::assert_eq!(actual_diff, expected_diff);
3450    check_edits(
3451        snapshot,
3452        &new_snapshot,
3453        &subscription.consume().into_inner(),
3454    );
3455    *snapshot = new_snapshot;
3456}
3457
3458#[track_caller]
3459fn check_edits(
3460    old_snapshot: &MultiBufferSnapshot,
3461    new_snapshot: &MultiBufferSnapshot,
3462    edits: &[Edit<usize>],
3463) {
3464    let mut text = old_snapshot.text();
3465    let new_text = new_snapshot.text();
3466    for edit in edits.iter().rev() {
3467        if !text.is_char_boundary(edit.old.start)
3468            || !text.is_char_boundary(edit.old.end)
3469            || !new_text.is_char_boundary(edit.new.start)
3470            || !new_text.is_char_boundary(edit.new.end)
3471        {
3472            panic!(
3473                "invalid edits: {:?}\nold text: {:?}\nnew text: {:?}",
3474                edits, text, new_text
3475            );
3476        }
3477
3478        text.replace_range(
3479            edit.old.start..edit.old.end,
3480            &new_text[edit.new.start..edit.new.end],
3481        );
3482    }
3483
3484    pretty_assertions::assert_eq!(text, new_text, "invalid edits: {:?}", edits);
3485}
3486
3487#[track_caller]
3488fn assert_chunks_in_ranges(snapshot: &MultiBufferSnapshot) {
3489    let full_text = snapshot.text();
3490    for ix in 0..full_text.len() {
3491        let mut chunks = snapshot.chunks(0..snapshot.len(), false);
3492        chunks.seek(ix..snapshot.len());
3493        let tail = chunks.map(|chunk| chunk.text).collect::<String>();
3494        assert_eq!(tail, &full_text[ix..], "seek to range: {:?}", ix..);
3495    }
3496}
3497
3498#[track_caller]
3499fn assert_consistent_line_numbers(snapshot: &MultiBufferSnapshot) {
3500    let all_line_numbers = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
3501    for start_row in 1..all_line_numbers.len() {
3502        let line_numbers = snapshot
3503            .row_infos(MultiBufferRow(start_row as u32))
3504            .collect::<Vec<_>>();
3505        assert_eq!(
3506            line_numbers,
3507            all_line_numbers[start_row..],
3508            "start_row: {start_row}"
3509        );
3510    }
3511}
3512
3513#[track_caller]
3514fn assert_position_translation(snapshot: &MultiBufferSnapshot) {
3515    let text = Rope::from(snapshot.text());
3516
3517    let mut left_anchors = Vec::new();
3518    let mut right_anchors = Vec::new();
3519    let mut offsets = Vec::new();
3520    let mut points = Vec::new();
3521    for offset in 0..=text.len() + 1 {
3522        let clipped_left = snapshot.clip_offset(offset, Bias::Left);
3523        let clipped_right = snapshot.clip_offset(offset, Bias::Right);
3524        assert_eq!(
3525            clipped_left,
3526            text.clip_offset(offset, Bias::Left),
3527            "clip_offset({offset:?}, Left)"
3528        );
3529        assert_eq!(
3530            clipped_right,
3531            text.clip_offset(offset, Bias::Right),
3532            "clip_offset({offset:?}, Right)"
3533        );
3534        assert_eq!(
3535            snapshot.offset_to_point(clipped_left),
3536            text.offset_to_point(clipped_left),
3537            "offset_to_point({clipped_left})"
3538        );
3539        assert_eq!(
3540            snapshot.offset_to_point(clipped_right),
3541            text.offset_to_point(clipped_right),
3542            "offset_to_point({clipped_right})"
3543        );
3544        let anchor_after = snapshot.anchor_after(clipped_left);
3545        assert_eq!(
3546            anchor_after.to_offset(snapshot),
3547            clipped_left,
3548            "anchor_after({clipped_left}).to_offset {anchor_after:?}"
3549        );
3550        let anchor_before = snapshot.anchor_before(clipped_left);
3551        assert_eq!(
3552            anchor_before.to_offset(snapshot),
3553            clipped_left,
3554            "anchor_before({clipped_left}).to_offset"
3555        );
3556        left_anchors.push(anchor_before);
3557        right_anchors.push(anchor_after);
3558        offsets.push(clipped_left);
3559        points.push(text.offset_to_point(clipped_left));
3560    }
3561
3562    for row in 0..text.max_point().row {
3563        for column in 0..text.line_len(row) + 1 {
3564            let point = Point { row, column };
3565            let clipped_left = snapshot.clip_point(point, Bias::Left);
3566            let clipped_right = snapshot.clip_point(point, Bias::Right);
3567            assert_eq!(
3568                clipped_left,
3569                text.clip_point(point, Bias::Left),
3570                "clip_point({point:?}, Left)"
3571            );
3572            assert_eq!(
3573                clipped_right,
3574                text.clip_point(point, Bias::Right),
3575                "clip_point({point:?}, Right)"
3576            );
3577            assert_eq!(
3578                snapshot.point_to_offset(clipped_left),
3579                text.point_to_offset(clipped_left),
3580                "point_to_offset({clipped_left:?})"
3581            );
3582            assert_eq!(
3583                snapshot.point_to_offset(clipped_right),
3584                text.point_to_offset(clipped_right),
3585                "point_to_offset({clipped_right:?})"
3586            );
3587        }
3588    }
3589
3590    assert_eq!(
3591        snapshot.summaries_for_anchors::<usize, _>(&left_anchors),
3592        offsets,
3593        "left_anchors <-> offsets"
3594    );
3595    assert_eq!(
3596        snapshot.summaries_for_anchors::<Point, _>(&left_anchors),
3597        points,
3598        "left_anchors <-> points"
3599    );
3600    assert_eq!(
3601        snapshot.summaries_for_anchors::<usize, _>(&right_anchors),
3602        offsets,
3603        "right_anchors <-> offsets"
3604    );
3605    assert_eq!(
3606        snapshot.summaries_for_anchors::<Point, _>(&right_anchors),
3607        points,
3608        "right_anchors <-> points"
3609    );
3610
3611    for (anchors, bias) in [(&left_anchors, Bias::Left), (&right_anchors, Bias::Right)] {
3612        for (ix, (offset, anchor)) in offsets.iter().zip(anchors).enumerate() {
3613            if ix > 0 && *offset == 252 && offset > &offsets[ix - 1] {
3614                let prev_anchor = left_anchors[ix - 1];
3615                assert!(
3616                    anchor.cmp(&prev_anchor, snapshot).is_gt(),
3617                    "anchor({}, {bias:?}).cmp(&anchor({}, {bias:?}).is_gt()",
3618                    offsets[ix],
3619                    offsets[ix - 1],
3620                );
3621                assert!(
3622                    prev_anchor.cmp(anchor, snapshot).is_lt(),
3623                    "anchor({}, {bias:?}).cmp(&anchor({}, {bias:?}).is_lt()",
3624                    offsets[ix - 1],
3625                    offsets[ix],
3626                );
3627            }
3628        }
3629    }
3630
3631    if let Some((buffer, offset)) = snapshot.point_to_buffer_offset(snapshot.max_point()) {
3632        assert!(offset <= buffer.len());
3633    }
3634    if let Some((buffer, point, _)) = snapshot.point_to_buffer_point(snapshot.max_point()) {
3635        assert!(point <= buffer.max_point());
3636    }
3637}
3638
3639fn assert_line_indents(snapshot: &MultiBufferSnapshot) {
3640    let max_row = snapshot.max_point().row;
3641    let buffer_id = snapshot.excerpts().next().unwrap().1.remote_id();
3642    let text = text::Buffer::new(ReplicaId::LOCAL, buffer_id, snapshot.text());
3643    let mut line_indents = text
3644        .line_indents_in_row_range(0..max_row + 1)
3645        .collect::<Vec<_>>();
3646    for start_row in 0..snapshot.max_point().row {
3647        pretty_assertions::assert_eq!(
3648            snapshot
3649                .line_indents(MultiBufferRow(start_row), |_| true)
3650                .map(|(row, indent, _)| (row.0, indent))
3651                .collect::<Vec<_>>(),
3652            &line_indents[(start_row as usize)..],
3653            "line_indents({start_row})"
3654        );
3655    }
3656
3657    line_indents.reverse();
3658    pretty_assertions::assert_eq!(
3659        snapshot
3660            .reversed_line_indents(MultiBufferRow(max_row), |_| true)
3661            .map(|(row, indent, _)| (row.0, indent))
3662            .collect::<Vec<_>>(),
3663        &line_indents[..],
3664        "reversed_line_indents({max_row})"
3665    );
3666}
3667
3668#[gpui::test]
3669fn test_new_empty_buffer_uses_untitled_title(cx: &mut App) {
3670    let buffer = cx.new(|cx| Buffer::local("", cx));
3671    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3672
3673    assert_eq!(multibuffer.read(cx).title(cx), "untitled");
3674}
3675
3676#[gpui::test]
3677fn test_new_empty_buffer_uses_untitled_title_when_only_contains_whitespace(cx: &mut App) {
3678    let buffer = cx.new(|cx| Buffer::local("\n ", cx));
3679    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3680
3681    assert_eq!(multibuffer.read(cx).title(cx), "untitled");
3682}
3683
3684#[gpui::test]
3685fn test_new_empty_buffer_takes_first_line_for_title(cx: &mut App) {
3686    let buffer = cx.new(|cx| Buffer::local("Hello World\nSecond line", cx));
3687    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3688
3689    assert_eq!(multibuffer.read(cx).title(cx), "Hello World");
3690}
3691
3692#[gpui::test]
3693fn test_new_empty_buffer_takes_trimmed_first_line_for_title(cx: &mut App) {
3694    let buffer = cx.new(|cx| Buffer::local("\nHello, World ", cx));
3695    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3696
3697    assert_eq!(multibuffer.read(cx).title(cx), "Hello, World");
3698}
3699
3700#[gpui::test]
3701fn test_new_empty_buffer_uses_truncated_first_line_for_title(cx: &mut App) {
3702    let title = "aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeee";
3703    let title_after = "aaaaaaaaaabbbbbbbbbbccccccccccdddddddddd";
3704    let buffer = cx.new(|cx| Buffer::local(title, cx));
3705    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3706
3707    assert_eq!(multibuffer.read(cx).title(cx), title_after);
3708}
3709
3710#[gpui::test]
3711fn test_new_empty_buffer_uses_truncated_first_line_for_title_after_merging_adjacent_spaces(
3712    cx: &mut App,
3713) {
3714    let title = "aaaaaaaaaabbbbbbbbbb    ccccccccccddddddddddeeeeeeeeee";
3715    let title_after = "aaaaaaaaaabbbbbbbbbb ccccccccccddddddddd";
3716    let buffer = cx.new(|cx| Buffer::local(title, cx));
3717    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3718
3719    assert_eq!(multibuffer.read(cx).title(cx), title_after);
3720}
3721
3722#[gpui::test]
3723fn test_new_empty_buffers_title_can_be_set(cx: &mut App) {
3724    let buffer = cx.new(|cx| Buffer::local("Hello World", cx));
3725    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3726    assert_eq!(multibuffer.read(cx).title(cx), "Hello World");
3727
3728    multibuffer.update(cx, |multibuffer, cx| {
3729        multibuffer.set_title("Hey".into(), cx)
3730    });
3731    assert_eq!(multibuffer.read(cx).title(cx), "Hey");
3732}
3733
3734#[gpui::test(iterations = 100)]
3735fn test_random_chunk_bitmaps(cx: &mut App, mut rng: StdRng) {
3736    let multibuffer = if rng.random() {
3737        let len = rng.random_range(0..10000);
3738        let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
3739        let buffer = cx.new(|cx| Buffer::local(text, cx));
3740        cx.new(|cx| MultiBuffer::singleton(buffer, cx))
3741    } else {
3742        MultiBuffer::build_random(&mut rng, cx)
3743    };
3744
3745    let snapshot = multibuffer.read(cx).snapshot(cx);
3746
3747    let chunks = snapshot.chunks(0..snapshot.len(), false);
3748
3749    for chunk in chunks {
3750        let chunk_text = chunk.text;
3751        let chars_bitmap = chunk.chars;
3752        let tabs_bitmap = chunk.tabs;
3753
3754        if chunk_text.is_empty() {
3755            assert_eq!(
3756                chars_bitmap, 0,
3757                "Empty chunk should have empty chars bitmap"
3758            );
3759            assert_eq!(tabs_bitmap, 0, "Empty chunk should have empty tabs bitmap");
3760            continue;
3761        }
3762
3763        assert!(
3764            chunk_text.len() <= 128,
3765            "Chunk text length {} exceeds 128 bytes",
3766            chunk_text.len()
3767        );
3768
3769        // Verify chars bitmap
3770        let char_indices = chunk_text
3771            .char_indices()
3772            .map(|(i, _)| i)
3773            .collect::<Vec<_>>();
3774
3775        for byte_idx in 0..chunk_text.len() {
3776            let should_have_bit = char_indices.contains(&byte_idx);
3777            let has_bit = chars_bitmap & (1 << byte_idx) != 0;
3778
3779            if has_bit != should_have_bit {
3780                eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
3781                eprintln!("Char indices: {:?}", char_indices);
3782                eprintln!("Chars bitmap: {:#b}", chars_bitmap);
3783            }
3784
3785            assert_eq!(
3786                has_bit, should_have_bit,
3787                "Chars bitmap mismatch at byte index {} in chunk {:?}. Expected bit: {}, Got bit: {}",
3788                byte_idx, chunk_text, should_have_bit, has_bit
3789            );
3790        }
3791
3792        for (byte_idx, byte) in chunk_text.bytes().enumerate() {
3793            let is_tab = byte == b'\t';
3794            let has_bit = tabs_bitmap & (1 << byte_idx) != 0;
3795
3796            if has_bit != is_tab {
3797                eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
3798                eprintln!("Tabs bitmap: {:#b}", tabs_bitmap);
3799                assert_eq!(
3800                    has_bit, is_tab,
3801                    "Tabs bitmap mismatch at byte index {} in chunk {:?}. Byte: {:?}, Expected bit: {}, Got bit: {}",
3802                    byte_idx, chunk_text, byte as char, is_tab, has_bit
3803                );
3804            }
3805        }
3806    }
3807}
3808
3809#[gpui::test(iterations = 100)]
3810fn test_random_chunk_bitmaps_with_diffs(cx: &mut App, mut rng: StdRng) {
3811    use buffer_diff::BufferDiff;
3812    use util::RandomCharIter;
3813
3814    let multibuffer = if rng.random() {
3815        let len = rng.random_range(100..10000);
3816        let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
3817        let buffer = cx.new(|cx| Buffer::local(text, cx));
3818        cx.new(|cx| MultiBuffer::singleton(buffer, cx))
3819    } else {
3820        MultiBuffer::build_random(&mut rng, cx)
3821    };
3822
3823    let _diff_count = rng.random_range(1..5);
3824    let mut diffs = Vec::new();
3825
3826    multibuffer.update(cx, |multibuffer, cx| {
3827        for buffer_id in multibuffer.excerpt_buffer_ids() {
3828            if rng.random_bool(0.7) {
3829                if let Some(buffer_handle) = multibuffer.buffer(buffer_id) {
3830                    let buffer_text = buffer_handle.read(cx).text();
3831                    let mut base_text = String::new();
3832
3833                    for line in buffer_text.lines() {
3834                        if rng.random_bool(0.3) {
3835                            continue;
3836                        } else if rng.random_bool(0.3) {
3837                            let line_len = rng.random_range(0..50);
3838                            let modified_line = RandomCharIter::new(&mut rng)
3839                                .take(line_len)
3840                                .collect::<String>();
3841                            base_text.push_str(&modified_line);
3842                            base_text.push('\n');
3843                        } else {
3844                            base_text.push_str(line);
3845                            base_text.push('\n');
3846                        }
3847                    }
3848
3849                    if rng.random_bool(0.5) {
3850                        let extra_lines = rng.random_range(1..5);
3851                        for _ in 0..extra_lines {
3852                            let line_len = rng.random_range(0..50);
3853                            let extra_line = RandomCharIter::new(&mut rng)
3854                                .take(line_len)
3855                                .collect::<String>();
3856                            base_text.push_str(&extra_line);
3857                            base_text.push('\n');
3858                        }
3859                    }
3860
3861                    let diff =
3862                        cx.new(|cx| BufferDiff::new_with_base_text(&base_text, &buffer_handle, cx));
3863                    diffs.push(diff.clone());
3864                    multibuffer.add_diff(diff, cx);
3865                }
3866            }
3867        }
3868    });
3869
3870    multibuffer.update(cx, |multibuffer, cx| {
3871        if rng.random_bool(0.5) {
3872            multibuffer.set_all_diff_hunks_expanded(cx);
3873        } else {
3874            let snapshot = multibuffer.snapshot(cx);
3875            let text = snapshot.text();
3876
3877            let mut ranges = Vec::new();
3878            for _ in 0..rng.random_range(1..5) {
3879                if snapshot.len() == 0 {
3880                    break;
3881                }
3882
3883                let diff_size = rng.random_range(5..1000);
3884                let mut start = rng.random_range(0..snapshot.len());
3885
3886                while !text.is_char_boundary(start) {
3887                    start = start.saturating_sub(1);
3888                }
3889
3890                let mut end = rng.random_range(start..snapshot.len().min(start + diff_size));
3891
3892                while !text.is_char_boundary(end) {
3893                    end = end.saturating_add(1);
3894                }
3895                let start_anchor = snapshot.anchor_after(start);
3896                let end_anchor = snapshot.anchor_before(end);
3897                ranges.push(start_anchor..end_anchor);
3898            }
3899            multibuffer.expand_diff_hunks(ranges, cx);
3900        }
3901    });
3902
3903    let snapshot = multibuffer.read(cx).snapshot(cx);
3904
3905    let chunks = snapshot.chunks(0..snapshot.len(), false);
3906
3907    for chunk in chunks {
3908        let chunk_text = chunk.text;
3909        let chars_bitmap = chunk.chars;
3910        let tabs_bitmap = chunk.tabs;
3911
3912        if chunk_text.is_empty() {
3913            assert_eq!(
3914                chars_bitmap, 0,
3915                "Empty chunk should have empty chars bitmap"
3916            );
3917            assert_eq!(tabs_bitmap, 0, "Empty chunk should have empty tabs bitmap");
3918            continue;
3919        }
3920
3921        assert!(
3922            chunk_text.len() <= 128,
3923            "Chunk text length {} exceeds 128 bytes",
3924            chunk_text.len()
3925        );
3926
3927        let char_indices = chunk_text
3928            .char_indices()
3929            .map(|(i, _)| i)
3930            .collect::<Vec<_>>();
3931
3932        for byte_idx in 0..chunk_text.len() {
3933            let should_have_bit = char_indices.contains(&byte_idx);
3934            let has_bit = chars_bitmap & (1 << byte_idx) != 0;
3935
3936            if has_bit != should_have_bit {
3937                eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
3938                eprintln!("Char indices: {:?}", char_indices);
3939                eprintln!("Chars bitmap: {:#b}", chars_bitmap);
3940            }
3941
3942            assert_eq!(
3943                has_bit, should_have_bit,
3944                "Chars bitmap mismatch at byte index {} in chunk {:?}. Expected bit: {}, Got bit: {}",
3945                byte_idx, chunk_text, should_have_bit, has_bit
3946            );
3947        }
3948
3949        for (byte_idx, byte) in chunk_text.bytes().enumerate() {
3950            let is_tab = byte == b'\t';
3951            let has_bit = tabs_bitmap & (1 << byte_idx) != 0;
3952
3953            if has_bit != is_tab {
3954                eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
3955                eprintln!("Tabs bitmap: {:#b}", tabs_bitmap);
3956                assert_eq!(
3957                    has_bit, is_tab,
3958                    "Tabs bitmap mismatch at byte index {} in chunk {:?}. Byte: {:?}, Expected bit: {}, Got bit: {}",
3959                    byte_idx, chunk_text, byte as char, is_tab, has_bit
3960                );
3961            }
3962        }
3963    }
3964}
3965
3966// FIXME
3967#[gpui::test]
3968async fn test_diff_hunk_row_ranges(cx: &mut TestAppContext) {
3969    let text = indoc!(
3970        "
3971        ONE
3972        "
3973    );
3974    let base_text = indoc!(
3975        "
3976        one
3977        "
3978    );
3979
3980    let buffer = cx.new(|cx| Buffer::local(text, cx));
3981    let diff = cx.new(|cx| BufferDiff::new_with_base_text(base_text, &buffer, cx));
3982    cx.run_until_parked();
3983
3984    let multibuffer = cx.new(|cx| {
3985        let mut multibuffer = MultiBuffer::singleton(buffer.clone(), cx);
3986        multibuffer.set_all_diff_hunks_expanded(cx);
3987        multibuffer.add_diff(diff.clone(), cx);
3988        multibuffer
3989    });
3990
3991    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3992        (multibuffer.snapshot(cx), multibuffer.subscribe())
3993    });
3994    assert_new_snapshot(
3995        &multibuffer,
3996        &mut snapshot,
3997        &mut subscription,
3998        cx,
3999        indoc!(
4000            "
4001             - one
4002             + ONE
4003             "
4004        ),
4005    );
4006    let hunks = dbg!(
4007        snapshot
4008            .diff_hunks_in_range(Anchor::min()..Anchor::max())
4009            .collect::<Vec<_>>()
4010    );
4011    dbg!(
4012        hunks[0]
4013            .multi_buffer_range()
4014            .start
4015            .bias_right(&snapshot)
4016            .to_point(&snapshot)
4017    );
4018}