multi_buffer_tests.rs

   1use super::*;
   2use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind};
   3use gpui::{App, TestAppContext};
   4use indoc::indoc;
   5use language::{Buffer, Rope};
   6use parking_lot::RwLock;
   7use rand::prelude::*;
   8use settings::SettingsStore;
   9use std::env;
  10use util::RandomCharIter;
  11use util::rel_path::rel_path;
  12use util::test::sample_text;
  13
  14#[ctor::ctor]
  15fn init_logger() {
  16    zlog::init_test();
  17}
  18
  19#[gpui::test]
  20fn test_empty_singleton(cx: &mut App) {
  21    let buffer = cx.new(|cx| Buffer::local("", cx));
  22    let buffer_id = buffer.read(cx).remote_id();
  23    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
  24    let snapshot = multibuffer.read(cx).snapshot(cx);
  25    assert_eq!(snapshot.text(), "");
  26    assert_eq!(
  27        snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>(),
  28        [RowInfo {
  29            buffer_id: Some(buffer_id),
  30            buffer_row: Some(0),
  31            multibuffer_row: Some(MultiBufferRow(0)),
  32            diff_status: None,
  33            expand_info: None,
  34            wrapped: 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                            wrapped: None,
2436
2437                            multibuffer_row: Some(MultiBufferRow(
2438                                text[..ix].matches('\n').count() as u32
2439                            )),
2440                            expand_info: expand_direction.zip(region.excerpt_id).map(
2441                                |(direction, excerpt_id)| ExpandInfo {
2442                                    direction,
2443                                    excerpt_id,
2444                                },
2445                            ),
2446                        }
2447                    });
2448                ix += line.len() + 1;
2449                row_info
2450            })
2451            .collect();
2452
2453        (text, row_infos, excerpt_boundary_rows)
2454    }
2455
2456    fn diffs_updated(&mut self, cx: &App) {
2457        for excerpt in &mut self.excerpts {
2458            let buffer = excerpt.buffer.read(cx).snapshot();
2459            let excerpt_range = excerpt.range.to_offset(&buffer);
2460            let buffer_id = buffer.remote_id();
2461            let diff = self.diffs.get(&buffer_id).unwrap().read(cx);
2462            let mut hunks = diff.hunks_in_row_range(0..u32::MAX, &buffer, cx).peekable();
2463            excerpt.expanded_diff_hunks.retain(|hunk_anchor| {
2464                if !hunk_anchor.is_valid(&buffer) {
2465                    return false;
2466                }
2467                while let Some(hunk) = hunks.peek() {
2468                    match hunk.buffer_range.start.cmp(hunk_anchor, &buffer) {
2469                        cmp::Ordering::Less => {
2470                            hunks.next();
2471                        }
2472                        cmp::Ordering::Equal => {
2473                            let hunk_range = hunk.buffer_range.to_offset(&buffer);
2474                            return hunk_range.end >= excerpt_range.start
2475                                && hunk_range.start <= excerpt_range.end;
2476                        }
2477                        cmp::Ordering::Greater => break,
2478                    }
2479                }
2480                false
2481            });
2482        }
2483    }
2484
2485    fn add_diff(&mut self, diff: Entity<BufferDiff>, cx: &mut App) {
2486        let buffer_id = diff.read(cx).buffer_id;
2487        self.diffs.insert(buffer_id, diff);
2488    }
2489}
2490
2491#[gpui::test(iterations = 100)]
2492async fn test_random_set_ranges(cx: &mut TestAppContext, mut rng: StdRng) {
2493    let base_text = "a\n".repeat(100);
2494    let buf = cx.update(|cx| cx.new(|cx| Buffer::local(base_text, cx)));
2495    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2496
2497    let operations = env::var("OPERATIONS")
2498        .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2499        .unwrap_or(10);
2500
2501    fn row_ranges(ranges: &Vec<Range<Point>>) -> Vec<Range<u32>> {
2502        ranges
2503            .iter()
2504            .map(|range| range.start.row..range.end.row)
2505            .collect()
2506    }
2507
2508    for _ in 0..operations {
2509        let snapshot = buf.update(cx, |buf, _| buf.snapshot());
2510        let num_ranges = rng.random_range(0..=10);
2511        let max_row = snapshot.max_point().row;
2512        let mut ranges = (0..num_ranges)
2513            .map(|_| {
2514                let start = rng.random_range(0..max_row);
2515                let end = rng.random_range(start + 1..max_row + 1);
2516                Point::row_range(start..end)
2517            })
2518            .collect::<Vec<_>>();
2519        ranges.sort_by_key(|range| range.start);
2520        log::info!("Setting ranges: {:?}", row_ranges(&ranges));
2521        let (created, _) = multibuffer.update(cx, |multibuffer, cx| {
2522            multibuffer.set_excerpts_for_path(
2523                PathKey::for_buffer(&buf, cx),
2524                buf.clone(),
2525                ranges.clone(),
2526                2,
2527                cx,
2528            )
2529        });
2530
2531        assert_eq!(created.len(), ranges.len());
2532
2533        let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2534        let mut last_end = None;
2535        let mut seen_ranges = Vec::default();
2536
2537        for (_, buf, range) in snapshot.excerpts() {
2538            let start = range.context.start.to_point(buf);
2539            let end = range.context.end.to_point(buf);
2540            seen_ranges.push(start..end);
2541
2542            if let Some(last_end) = last_end.take() {
2543                assert!(
2544                    start > last_end,
2545                    "multibuffer has out-of-order ranges: {:?}; {:?} <= {:?}",
2546                    row_ranges(&seen_ranges),
2547                    start,
2548                    last_end
2549                )
2550            }
2551
2552            ranges.retain(|range| range.start < start || range.end > end);
2553
2554            last_end = Some(end)
2555        }
2556
2557        assert!(
2558            ranges.is_empty(),
2559            "multibuffer {:?} did not include all ranges: {:?}",
2560            row_ranges(&seen_ranges),
2561            row_ranges(&ranges)
2562        );
2563    }
2564}
2565
2566#[gpui::test(iterations = 100)]
2567async fn test_random_multibuffer(cx: &mut TestAppContext, mut rng: StdRng) {
2568    let operations = env::var("OPERATIONS")
2569        .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2570        .unwrap_or(10);
2571
2572    let mut buffers: Vec<Entity<Buffer>> = Vec::new();
2573    let mut base_texts: HashMap<BufferId, String> = HashMap::default();
2574    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2575    let mut reference = ReferenceMultibuffer::default();
2576    let mut anchors = Vec::new();
2577    let mut old_versions = Vec::new();
2578    let mut needs_diff_calculation = false;
2579
2580    for _ in 0..operations {
2581        match rng.random_range(0..100) {
2582            0..=14 if !buffers.is_empty() => {
2583                let buffer = buffers.choose(&mut rng).unwrap();
2584                buffer.update(cx, |buf, cx| {
2585                    let edit_count = rng.random_range(1..5);
2586                    buf.randomly_edit(&mut rng, edit_count, cx);
2587                    log::info!("buffer text:\n{}", buf.text());
2588                    needs_diff_calculation = true;
2589                });
2590                cx.update(|cx| reference.diffs_updated(cx));
2591            }
2592            15..=19 if !reference.excerpts.is_empty() => {
2593                multibuffer.update(cx, |multibuffer, cx| {
2594                    let ids = multibuffer.excerpt_ids();
2595                    let mut excerpts = HashSet::default();
2596                    for _ in 0..rng.random_range(0..ids.len()) {
2597                        excerpts.extend(ids.choose(&mut rng).copied());
2598                    }
2599
2600                    let line_count = rng.random_range(0..5);
2601
2602                    let excerpt_ixs = excerpts
2603                        .iter()
2604                        .map(|id| reference.excerpts.iter().position(|e| e.id == *id).unwrap())
2605                        .collect::<Vec<_>>();
2606                    log::info!("Expanding excerpts {excerpt_ixs:?} by {line_count} lines");
2607                    multibuffer.expand_excerpts(
2608                        excerpts.iter().cloned(),
2609                        line_count,
2610                        ExpandExcerptDirection::UpAndDown,
2611                        cx,
2612                    );
2613
2614                    reference.expand_excerpts(&excerpts, line_count, cx);
2615                });
2616            }
2617            20..=29 if !reference.excerpts.is_empty() => {
2618                let mut ids_to_remove = vec![];
2619                for _ in 0..rng.random_range(1..=3) {
2620                    let Some(excerpt) = reference.excerpts.choose(&mut rng) else {
2621                        break;
2622                    };
2623                    let id = excerpt.id;
2624                    cx.update(|cx| reference.remove_excerpt(id, cx));
2625                    ids_to_remove.push(id);
2626                }
2627                let snapshot =
2628                    multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2629                ids_to_remove.sort_unstable_by(|a, b| a.cmp(b, &snapshot));
2630                drop(snapshot);
2631                multibuffer.update(cx, |multibuffer, cx| {
2632                    multibuffer.remove_excerpts(ids_to_remove, cx)
2633                });
2634            }
2635            30..=39 if !reference.excerpts.is_empty() => {
2636                let multibuffer =
2637                    multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2638                let offset =
2639                    multibuffer.clip_offset(rng.random_range(0..=multibuffer.len()), Bias::Left);
2640                let bias = if rng.random() {
2641                    Bias::Left
2642                } else {
2643                    Bias::Right
2644                };
2645                log::info!("Creating anchor at {} with bias {:?}", offset, bias);
2646                anchors.push(multibuffer.anchor_at(offset, bias));
2647                anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
2648            }
2649            40..=44 if !anchors.is_empty() => {
2650                let multibuffer =
2651                    multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2652                let prev_len = anchors.len();
2653                anchors = multibuffer
2654                    .refresh_anchors(&anchors)
2655                    .into_iter()
2656                    .map(|a| a.1)
2657                    .collect();
2658
2659                // Ensure the newly-refreshed anchors point to a valid excerpt and don't
2660                // overshoot its boundaries.
2661                assert_eq!(anchors.len(), prev_len);
2662                for anchor in &anchors {
2663                    if anchor.excerpt_id == ExcerptId::min()
2664                        || anchor.excerpt_id == ExcerptId::max()
2665                    {
2666                        continue;
2667                    }
2668
2669                    let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
2670                    assert_eq!(excerpt.id, anchor.excerpt_id);
2671                    assert!(excerpt.contains(anchor));
2672                }
2673            }
2674            45..=55 if !reference.excerpts.is_empty() => {
2675                multibuffer.update(cx, |multibuffer, cx| {
2676                    let snapshot = multibuffer.snapshot(cx);
2677                    let excerpt_ix = rng.random_range(0..reference.excerpts.len());
2678                    let excerpt = &reference.excerpts[excerpt_ix];
2679                    let start = excerpt.range.start;
2680                    let end = excerpt.range.end;
2681                    let range = snapshot.anchor_in_excerpt(excerpt.id, start).unwrap()
2682                        ..snapshot.anchor_in_excerpt(excerpt.id, end).unwrap();
2683
2684                    log::info!(
2685                        "expanding diff hunks in range {:?} (excerpt id {:?}, index {excerpt_ix:?}, buffer id {:?})",
2686                        range.to_offset(&snapshot),
2687                        excerpt.id,
2688                        excerpt.buffer.read(cx).remote_id(),
2689                    );
2690                    reference.expand_diff_hunks(excerpt.id, start..end, cx);
2691                    multibuffer.expand_diff_hunks(vec![range], cx);
2692                });
2693            }
2694            56..=85 if needs_diff_calculation => {
2695                multibuffer.update(cx, |multibuffer, cx| {
2696                    for buffer in multibuffer.all_buffers() {
2697                        let snapshot = buffer.read(cx).snapshot();
2698                        multibuffer.diff_for(snapshot.remote_id()).unwrap().update(
2699                            cx,
2700                            |diff, cx| {
2701                                log::info!(
2702                                    "recalculating diff for buffer {:?}",
2703                                    snapshot.remote_id(),
2704                                );
2705                                diff.recalculate_diff_sync(snapshot.text, cx);
2706                            },
2707                        );
2708                    }
2709                    reference.diffs_updated(cx);
2710                    needs_diff_calculation = false;
2711                });
2712            }
2713            _ => {
2714                let buffer_handle = if buffers.is_empty() || rng.random_bool(0.4) {
2715                    let mut base_text = util::RandomCharIter::new(&mut rng)
2716                        .take(256)
2717                        .collect::<String>();
2718
2719                    let buffer = cx.new(|cx| Buffer::local(base_text.clone(), cx));
2720                    text::LineEnding::normalize(&mut base_text);
2721                    base_texts.insert(
2722                        buffer.read_with(cx, |buffer, _| buffer.remote_id()),
2723                        base_text,
2724                    );
2725                    buffers.push(buffer);
2726                    buffers.last().unwrap()
2727                } else {
2728                    buffers.choose(&mut rng).unwrap()
2729                };
2730
2731                let prev_excerpt_ix = rng.random_range(0..=reference.excerpts.len());
2732                let prev_excerpt_id = reference
2733                    .excerpts
2734                    .get(prev_excerpt_ix)
2735                    .map_or(ExcerptId::max(), |e| e.id);
2736                let excerpt_ix = (prev_excerpt_ix + 1).min(reference.excerpts.len());
2737
2738                let (range, anchor_range) = buffer_handle.read_with(cx, |buffer, _| {
2739                    let end_row = rng.random_range(0..=buffer.max_point().row);
2740                    let start_row = rng.random_range(0..=end_row);
2741                    let end_ix = buffer.point_to_offset(Point::new(end_row, 0));
2742                    let start_ix = buffer.point_to_offset(Point::new(start_row, 0));
2743                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
2744
2745                    log::info!(
2746                        "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
2747                        excerpt_ix,
2748                        reference.excerpts.len(),
2749                        buffer.remote_id(),
2750                        buffer.text(),
2751                        start_ix..end_ix,
2752                        &buffer.text()[start_ix..end_ix]
2753                    );
2754
2755                    (start_ix..end_ix, anchor_range)
2756                });
2757
2758                multibuffer.update(cx, |multibuffer, cx| {
2759                    let id = buffer_handle.read(cx).remote_id();
2760                    if multibuffer.diff_for(id).is_none() {
2761                        let base_text = base_texts.get(&id).unwrap();
2762                        let diff = cx
2763                            .new(|cx| BufferDiff::new_with_base_text(base_text, buffer_handle, cx));
2764                        reference.add_diff(diff.clone(), cx);
2765                        multibuffer.add_diff(diff, cx)
2766                    }
2767                });
2768
2769                let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
2770                    multibuffer
2771                        .insert_excerpts_after(
2772                            prev_excerpt_id,
2773                            buffer_handle.clone(),
2774                            [ExcerptRange::new(range.clone())],
2775                            cx,
2776                        )
2777                        .pop()
2778                        .unwrap()
2779                });
2780
2781                reference.insert_excerpt_after(
2782                    prev_excerpt_id,
2783                    excerpt_id,
2784                    (buffer_handle.clone(), anchor_range),
2785                );
2786            }
2787        }
2788
2789        if rng.random_bool(0.3) {
2790            multibuffer.update(cx, |multibuffer, cx| {
2791                old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
2792            })
2793        }
2794
2795        let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2796        let actual_text = snapshot.text();
2797        let actual_boundary_rows = snapshot
2798            .excerpt_boundaries_in_range(0..)
2799            .map(|b| b.row)
2800            .collect::<HashSet<_>>();
2801        let actual_row_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
2802
2803        let (expected_text, expected_row_infos, expected_boundary_rows) =
2804            cx.update(|cx| reference.expected_content(cx));
2805
2806        let has_diff = actual_row_infos
2807            .iter()
2808            .any(|info| info.diff_status.is_some())
2809            || expected_row_infos
2810                .iter()
2811                .any(|info| info.diff_status.is_some());
2812        let actual_diff = format_diff(
2813            &actual_text,
2814            &actual_row_infos,
2815            &actual_boundary_rows,
2816            Some(has_diff),
2817        );
2818        let expected_diff = format_diff(
2819            &expected_text,
2820            &expected_row_infos,
2821            &expected_boundary_rows,
2822            Some(has_diff),
2823        );
2824
2825        log::info!("Multibuffer content:\n{}", actual_diff);
2826
2827        assert_eq!(
2828            actual_row_infos.len(),
2829            actual_text.split('\n').count(),
2830            "line count: {}",
2831            actual_text.split('\n').count()
2832        );
2833        pretty_assertions::assert_eq!(actual_diff, expected_diff);
2834        pretty_assertions::assert_eq!(actual_text, expected_text);
2835        pretty_assertions::assert_eq!(actual_row_infos, expected_row_infos);
2836
2837        for _ in 0..5 {
2838            let start_row = rng.random_range(0..=expected_row_infos.len());
2839            assert_eq!(
2840                snapshot
2841                    .row_infos(MultiBufferRow(start_row as u32))
2842                    .collect::<Vec<_>>(),
2843                &expected_row_infos[start_row..],
2844                "buffer_rows({})",
2845                start_row
2846            );
2847        }
2848
2849        assert_eq!(
2850            snapshot.widest_line_number(),
2851            expected_row_infos
2852                .into_iter()
2853                .filter_map(|info| {
2854                    if info.diff_status.is_some_and(|status| status.is_deleted()) {
2855                        None
2856                    } else {
2857                        info.buffer_row
2858                    }
2859                })
2860                .max()
2861                .unwrap()
2862                + 1
2863        );
2864        let reference_ranges = cx.update(|cx| {
2865            reference
2866                .excerpts
2867                .iter()
2868                .map(|excerpt| {
2869                    (
2870                        excerpt.id,
2871                        excerpt.range.to_offset(&excerpt.buffer.read(cx).snapshot()),
2872                    )
2873                })
2874                .collect::<HashMap<_, _>>()
2875        });
2876        for i in 0..snapshot.len() {
2877            let excerpt = snapshot.excerpt_containing(i..i).unwrap();
2878            assert_eq!(excerpt.buffer_range(), reference_ranges[&excerpt.id()]);
2879        }
2880
2881        assert_consistent_line_numbers(&snapshot);
2882        assert_position_translation(&snapshot);
2883
2884        for (row, line) in expected_text.split('\n').enumerate() {
2885            assert_eq!(
2886                snapshot.line_len(MultiBufferRow(row as u32)),
2887                line.len() as u32,
2888                "line_len({}).",
2889                row
2890            );
2891        }
2892
2893        let text_rope = Rope::from(expected_text.as_str());
2894        for _ in 0..10 {
2895            let end_ix = text_rope.clip_offset(rng.random_range(0..=text_rope.len()), Bias::Right);
2896            let start_ix = text_rope.clip_offset(rng.random_range(0..=end_ix), Bias::Left);
2897
2898            let text_for_range = snapshot
2899                .text_for_range(start_ix..end_ix)
2900                .collect::<String>();
2901            assert_eq!(
2902                text_for_range,
2903                &expected_text[start_ix..end_ix],
2904                "incorrect text for range {:?}",
2905                start_ix..end_ix
2906            );
2907
2908            let expected_summary = TextSummary::from(&expected_text[start_ix..end_ix]);
2909            assert_eq!(
2910                snapshot.text_summary_for_range::<TextSummary, _>(start_ix..end_ix),
2911                expected_summary,
2912                "incorrect summary for range {:?}",
2913                start_ix..end_ix
2914            );
2915        }
2916
2917        // Anchor resolution
2918        let summaries = snapshot.summaries_for_anchors::<usize, _>(&anchors);
2919        assert_eq!(anchors.len(), summaries.len());
2920        for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
2921            assert!(resolved_offset <= snapshot.len());
2922            assert_eq!(
2923                snapshot.summary_for_anchor::<usize>(anchor),
2924                resolved_offset,
2925                "anchor: {:?}",
2926                anchor
2927            );
2928        }
2929
2930        for _ in 0..10 {
2931            let end_ix = text_rope.clip_offset(rng.random_range(0..=text_rope.len()), Bias::Right);
2932            assert_eq!(
2933                snapshot.reversed_chars_at(end_ix).collect::<String>(),
2934                expected_text[..end_ix].chars().rev().collect::<String>(),
2935            );
2936        }
2937
2938        for _ in 0..10 {
2939            let end_ix = rng.random_range(0..=text_rope.len());
2940            let start_ix = rng.random_range(0..=end_ix);
2941            assert_eq!(
2942                snapshot
2943                    .bytes_in_range(start_ix..end_ix)
2944                    .flatten()
2945                    .copied()
2946                    .collect::<Vec<_>>(),
2947                expected_text.as_bytes()[start_ix..end_ix].to_vec(),
2948                "bytes_in_range({:?})",
2949                start_ix..end_ix,
2950            );
2951        }
2952    }
2953
2954    let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2955    for (old_snapshot, subscription) in old_versions {
2956        let edits = subscription.consume().into_inner();
2957
2958        log::info!(
2959            "applying subscription edits to old text: {:?}: {:?}",
2960            old_snapshot.text(),
2961            edits,
2962        );
2963
2964        let mut text = old_snapshot.text();
2965        for edit in edits {
2966            let new_text: String = snapshot.text_for_range(edit.new.clone()).collect();
2967            text.replace_range(edit.new.start..edit.new.start + edit.old.len(), &new_text);
2968        }
2969        assert_eq!(text.to_string(), snapshot.text());
2970    }
2971}
2972
2973#[gpui::test]
2974fn test_history(cx: &mut App) {
2975    let test_settings = SettingsStore::test(cx);
2976    cx.set_global(test_settings);
2977    let group_interval: Duration = Duration::from_millis(1);
2978    let buffer_1 = cx.new(|cx| {
2979        let mut buf = Buffer::local("1234", cx);
2980        buf.set_group_interval(group_interval);
2981        buf
2982    });
2983    let buffer_2 = cx.new(|cx| {
2984        let mut buf = Buffer::local("5678", cx);
2985        buf.set_group_interval(group_interval);
2986        buf
2987    });
2988    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2989    multibuffer.update(cx, |this, _| {
2990        this.history.group_interval = group_interval;
2991    });
2992    multibuffer.update(cx, |multibuffer, cx| {
2993        multibuffer.push_excerpts(
2994            buffer_1.clone(),
2995            [ExcerptRange::new(0..buffer_1.read(cx).len())],
2996            cx,
2997        );
2998        multibuffer.push_excerpts(
2999            buffer_2.clone(),
3000            [ExcerptRange::new(0..buffer_2.read(cx).len())],
3001            cx,
3002        );
3003    });
3004
3005    let mut now = Instant::now();
3006
3007    multibuffer.update(cx, |multibuffer, cx| {
3008        let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
3009        multibuffer.edit(
3010            [
3011                (Point::new(0, 0)..Point::new(0, 0), "A"),
3012                (Point::new(1, 0)..Point::new(1, 0), "A"),
3013            ],
3014            None,
3015            cx,
3016        );
3017        multibuffer.edit(
3018            [
3019                (Point::new(0, 1)..Point::new(0, 1), "B"),
3020                (Point::new(1, 1)..Point::new(1, 1), "B"),
3021            ],
3022            None,
3023            cx,
3024        );
3025        multibuffer.end_transaction_at(now, cx);
3026        assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3027
3028        // Verify edited ranges for transaction 1
3029        assert_eq!(
3030            multibuffer.edited_ranges_for_transaction(transaction_1, cx),
3031            &[
3032                Point::new(0, 0)..Point::new(0, 2),
3033                Point::new(1, 0)..Point::new(1, 2)
3034            ]
3035        );
3036
3037        // Edit buffer 1 through the multibuffer
3038        now += 2 * group_interval;
3039        multibuffer.start_transaction_at(now, cx);
3040        multibuffer.edit([(2..2, "C")], None, cx);
3041        multibuffer.end_transaction_at(now, cx);
3042        assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3043
3044        // Edit buffer 1 independently
3045        buffer_1.update(cx, |buffer_1, cx| {
3046            buffer_1.start_transaction_at(now);
3047            buffer_1.edit([(3..3, "D")], None, cx);
3048            buffer_1.end_transaction_at(now, cx);
3049
3050            now += 2 * group_interval;
3051            buffer_1.start_transaction_at(now);
3052            buffer_1.edit([(4..4, "E")], None, cx);
3053            buffer_1.end_transaction_at(now, cx);
3054        });
3055        assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
3056
3057        // An undo in the multibuffer undoes the multibuffer transaction
3058        // and also any individual buffer edits that have occurred since
3059        // that transaction.
3060        multibuffer.undo(cx);
3061        assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3062
3063        multibuffer.undo(cx);
3064        assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3065
3066        multibuffer.redo(cx);
3067        assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3068
3069        multibuffer.redo(cx);
3070        assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
3071
3072        // Undo buffer 2 independently.
3073        buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
3074        assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
3075
3076        // An undo in the multibuffer undoes the components of the
3077        // the last multibuffer transaction that are not already undone.
3078        multibuffer.undo(cx);
3079        assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
3080
3081        multibuffer.undo(cx);
3082        assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3083
3084        multibuffer.redo(cx);
3085        assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3086
3087        buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
3088        assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
3089
3090        // Redo stack gets cleared after an edit.
3091        now += 2 * group_interval;
3092        multibuffer.start_transaction_at(now, cx);
3093        multibuffer.edit([(0..0, "X")], None, cx);
3094        multibuffer.end_transaction_at(now, cx);
3095        assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3096        multibuffer.redo(cx);
3097        assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3098        multibuffer.undo(cx);
3099        assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
3100        multibuffer.undo(cx);
3101        assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3102
3103        // Transactions can be grouped manually.
3104        multibuffer.redo(cx);
3105        multibuffer.redo(cx);
3106        assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3107        multibuffer.group_until_transaction(transaction_1, cx);
3108        multibuffer.undo(cx);
3109        assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3110        multibuffer.redo(cx);
3111        assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3112    });
3113}
3114
3115#[gpui::test]
3116async fn test_enclosing_indent(cx: &mut TestAppContext) {
3117    async fn enclosing_indent(
3118        text: &str,
3119        buffer_row: u32,
3120        cx: &mut TestAppContext,
3121    ) -> Option<(Range<u32>, LineIndent)> {
3122        let buffer = cx.update(|cx| MultiBuffer::build_simple(text, cx));
3123        let snapshot = cx.read(|cx| buffer.read(cx).snapshot(cx));
3124        let (range, indent) = snapshot
3125            .enclosing_indent(MultiBufferRow(buffer_row))
3126            .await?;
3127        Some((range.start.0..range.end.0, indent))
3128    }
3129
3130    assert_eq!(
3131        enclosing_indent(
3132            indoc!(
3133                "
3134                fn b() {
3135                    if c {
3136                        let d = 2;
3137                    }
3138                }
3139                "
3140            ),
3141            1,
3142            cx,
3143        )
3144        .await,
3145        Some((
3146            1..2,
3147            LineIndent {
3148                tabs: 0,
3149                spaces: 4,
3150                line_blank: false,
3151            }
3152        ))
3153    );
3154
3155    assert_eq!(
3156        enclosing_indent(
3157            indoc!(
3158                "
3159                fn b() {
3160                    if c {
3161                        let d = 2;
3162                    }
3163                }
3164                "
3165            ),
3166            2,
3167            cx,
3168        )
3169        .await,
3170        Some((
3171            1..2,
3172            LineIndent {
3173                tabs: 0,
3174                spaces: 4,
3175                line_blank: false,
3176            }
3177        ))
3178    );
3179
3180    assert_eq!(
3181        enclosing_indent(
3182            indoc!(
3183                "
3184                fn b() {
3185                    if c {
3186                        let d = 2;
3187
3188                        let e = 5;
3189                    }
3190                }
3191                "
3192            ),
3193            3,
3194            cx,
3195        )
3196        .await,
3197        Some((
3198            1..4,
3199            LineIndent {
3200                tabs: 0,
3201                spaces: 4,
3202                line_blank: false,
3203            }
3204        ))
3205    );
3206}
3207
3208#[gpui::test]
3209fn test_summaries_for_anchors(cx: &mut TestAppContext) {
3210    let base_text_1 = indoc!(
3211        "
3212        bar
3213        "
3214    );
3215    let text_1 = indoc!(
3216        "
3217        BAR
3218        "
3219    );
3220    let base_text_2 = indoc!(
3221        "
3222        foo
3223        "
3224    );
3225    let text_2 = indoc!(
3226        "
3227        FOO
3228        "
3229    );
3230
3231    let buffer_1 = cx.new(|cx| Buffer::local(text_1, cx));
3232    let buffer_2 = cx.new(|cx| Buffer::local(text_2, cx));
3233    let diff_1 = cx.new(|cx| BufferDiff::new_with_base_text(base_text_1, &buffer_1, cx));
3234    let diff_2 = cx.new(|cx| BufferDiff::new_with_base_text(base_text_2, &buffer_2, cx));
3235    cx.run_until_parked();
3236
3237    let mut ids = vec![];
3238    let multibuffer = cx.new(|cx| {
3239        let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
3240        multibuffer.set_all_diff_hunks_expanded(cx);
3241        ids.extend(multibuffer.push_excerpts(
3242            buffer_1.clone(),
3243            [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
3244            cx,
3245        ));
3246        ids.extend(multibuffer.push_excerpts(
3247            buffer_2.clone(),
3248            [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
3249            cx,
3250        ));
3251        multibuffer.add_diff(diff_1.clone(), cx);
3252        multibuffer.add_diff(diff_2.clone(), cx);
3253        multibuffer
3254    });
3255
3256    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3257        (multibuffer.snapshot(cx), multibuffer.subscribe())
3258    });
3259
3260    assert_new_snapshot(
3261        &multibuffer,
3262        &mut snapshot,
3263        &mut subscription,
3264        cx,
3265        indoc!(
3266            "
3267            - bar
3268            + BAR
3269
3270            - foo
3271            + FOO
3272            "
3273        ),
3274    );
3275
3276    let id_1 = buffer_1.read_with(cx, |buffer, _| buffer.remote_id());
3277    let id_2 = buffer_2.read_with(cx, |buffer, _| buffer.remote_id());
3278
3279    let anchor_1 = Anchor::in_buffer(ids[0], id_1, text::Anchor::MIN);
3280    let point_1 = snapshot.summaries_for_anchors::<Point, _>([&anchor_1])[0];
3281    assert_eq!(point_1, Point::new(0, 0));
3282
3283    let anchor_2 = Anchor::in_buffer(ids[1], id_2, text::Anchor::MIN);
3284    let point_2 = snapshot.summaries_for_anchors::<Point, _>([&anchor_2])[0];
3285    assert_eq!(point_2, Point::new(3, 0));
3286}
3287
3288#[gpui::test]
3289fn test_trailing_deletion_without_newline(cx: &mut TestAppContext) {
3290    let base_text_1 = "one\ntwo".to_owned();
3291    let text_1 = "one\n".to_owned();
3292
3293    let buffer_1 = cx.new(|cx| Buffer::local(text_1, cx));
3294    let diff_1 = cx.new(|cx| BufferDiff::new_with_base_text(&base_text_1, &buffer_1, cx));
3295    cx.run_until_parked();
3296
3297    let multibuffer = cx.new(|cx| {
3298        let mut multibuffer = MultiBuffer::singleton(buffer_1.clone(), cx);
3299        multibuffer.add_diff(diff_1.clone(), cx);
3300        multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
3301        multibuffer
3302    });
3303
3304    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3305        (multibuffer.snapshot(cx), multibuffer.subscribe())
3306    });
3307
3308    assert_new_snapshot(
3309        &multibuffer,
3310        &mut snapshot,
3311        &mut subscription,
3312        cx,
3313        indoc!(
3314            "
3315              one
3316            - two
3317            "
3318        ),
3319    );
3320
3321    assert_eq!(snapshot.max_point(), Point::new(2, 0));
3322    assert_eq!(snapshot.len(), 8);
3323
3324    assert_eq!(
3325        snapshot
3326            .dimensions_from_points::<Point>([Point::new(2, 0)])
3327            .collect::<Vec<_>>(),
3328        vec![Point::new(2, 0)]
3329    );
3330
3331    let (_, translated_offset) = snapshot.point_to_buffer_offset(Point::new(2, 0)).unwrap();
3332    assert_eq!(translated_offset, "one\n".len());
3333    let (_, translated_point, _) = snapshot.point_to_buffer_point(Point::new(2, 0)).unwrap();
3334    assert_eq!(translated_point, Point::new(1, 0));
3335
3336    // The same, for an excerpt that's not at the end of the multibuffer.
3337
3338    let text_2 = "foo\n".to_owned();
3339    let buffer_2 = cx.new(|cx| Buffer::local(&text_2, cx));
3340    multibuffer.update(cx, |multibuffer, cx| {
3341        multibuffer.push_excerpts(
3342            buffer_2.clone(),
3343            [ExcerptRange::new(Point::new(0, 0)..Point::new(1, 0))],
3344            cx,
3345        );
3346    });
3347
3348    assert_new_snapshot(
3349        &multibuffer,
3350        &mut snapshot,
3351        &mut subscription,
3352        cx,
3353        indoc!(
3354            "
3355              one
3356            - two
3357
3358              foo
3359            "
3360        ),
3361    );
3362
3363    assert_eq!(
3364        snapshot
3365            .dimensions_from_points::<Point>([Point::new(2, 0)])
3366            .collect::<Vec<_>>(),
3367        vec![Point::new(2, 0)]
3368    );
3369
3370    let buffer_1_id = buffer_1.read_with(cx, |buffer_1, _| buffer_1.remote_id());
3371    let (buffer, translated_offset) = snapshot.point_to_buffer_offset(Point::new(2, 0)).unwrap();
3372    assert_eq!(buffer.remote_id(), buffer_1_id);
3373    assert_eq!(translated_offset, "one\n".len());
3374    let (buffer, translated_point, _) = snapshot.point_to_buffer_point(Point::new(2, 0)).unwrap();
3375    assert_eq!(buffer.remote_id(), buffer_1_id);
3376    assert_eq!(translated_point, Point::new(1, 0));
3377}
3378
3379fn format_diff(
3380    text: &str,
3381    row_infos: &Vec<RowInfo>,
3382    boundary_rows: &HashSet<MultiBufferRow>,
3383    has_diff: Option<bool>,
3384) -> String {
3385    let has_diff =
3386        has_diff.unwrap_or_else(|| row_infos.iter().any(|info| info.diff_status.is_some()));
3387    text.split('\n')
3388        .enumerate()
3389        .zip(row_infos)
3390        .map(|((ix, line), info)| {
3391            let marker = match info.diff_status.map(|status| status.kind) {
3392                Some(DiffHunkStatusKind::Added) => "+ ",
3393                Some(DiffHunkStatusKind::Deleted) => "- ",
3394                Some(DiffHunkStatusKind::Modified) => unreachable!(),
3395                None => {
3396                    if has_diff && !line.is_empty() {
3397                        "  "
3398                    } else {
3399                        ""
3400                    }
3401                }
3402            };
3403            let boundary_row = if boundary_rows.contains(&MultiBufferRow(ix as u32)) {
3404                if has_diff {
3405                    "  ----------\n"
3406                } else {
3407                    "---------\n"
3408                }
3409            } else {
3410                ""
3411            };
3412            format!("{boundary_row}{marker}{line}")
3413        })
3414        .collect::<Vec<_>>()
3415        .join("\n")
3416}
3417
3418#[track_caller]
3419fn assert_excerpts_match(
3420    multibuffer: &Entity<MultiBuffer>,
3421    cx: &mut TestAppContext,
3422    expected: &str,
3423) {
3424    let mut output = String::new();
3425    multibuffer.read_with(cx, |multibuffer, cx| {
3426        for (_, buffer, range) in multibuffer.snapshot(cx).excerpts() {
3427            output.push_str("-----\n");
3428            output.extend(buffer.text_for_range(range.context));
3429            if !output.ends_with('\n') {
3430                output.push('\n');
3431            }
3432        }
3433    });
3434    assert_eq!(output, expected);
3435}
3436
3437#[track_caller]
3438fn assert_new_snapshot(
3439    multibuffer: &Entity<MultiBuffer>,
3440    snapshot: &mut MultiBufferSnapshot,
3441    subscription: &mut Subscription,
3442    cx: &mut TestAppContext,
3443    expected_diff: &str,
3444) {
3445    let new_snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
3446    let actual_text = new_snapshot.text();
3447    let line_infos = new_snapshot
3448        .row_infos(MultiBufferRow(0))
3449        .collect::<Vec<_>>();
3450    let actual_diff = format_diff(&actual_text, &line_infos, &Default::default(), None);
3451    pretty_assertions::assert_eq!(actual_diff, expected_diff);
3452    check_edits(
3453        snapshot,
3454        &new_snapshot,
3455        &subscription.consume().into_inner(),
3456    );
3457    *snapshot = new_snapshot;
3458}
3459
3460#[track_caller]
3461fn check_edits(
3462    old_snapshot: &MultiBufferSnapshot,
3463    new_snapshot: &MultiBufferSnapshot,
3464    edits: &[Edit<usize>],
3465) {
3466    let mut text = old_snapshot.text();
3467    let new_text = new_snapshot.text();
3468    for edit in edits.iter().rev() {
3469        if !text.is_char_boundary(edit.old.start)
3470            || !text.is_char_boundary(edit.old.end)
3471            || !new_text.is_char_boundary(edit.new.start)
3472            || !new_text.is_char_boundary(edit.new.end)
3473        {
3474            panic!(
3475                "invalid edits: {:?}\nold text: {:?}\nnew text: {:?}",
3476                edits, text, new_text
3477            );
3478        }
3479
3480        text.replace_range(
3481            edit.old.start..edit.old.end,
3482            &new_text[edit.new.start..edit.new.end],
3483        );
3484    }
3485
3486    pretty_assertions::assert_eq!(text, new_text, "invalid edits: {:?}", edits);
3487}
3488
3489#[track_caller]
3490fn assert_chunks_in_ranges(snapshot: &MultiBufferSnapshot) {
3491    let full_text = snapshot.text();
3492    for ix in 0..full_text.len() {
3493        let mut chunks = snapshot.chunks(0..snapshot.len(), false);
3494        chunks.seek(ix..snapshot.len());
3495        let tail = chunks.map(|chunk| chunk.text).collect::<String>();
3496        assert_eq!(tail, &full_text[ix..], "seek to range: {:?}", ix..);
3497    }
3498}
3499
3500#[track_caller]
3501fn assert_consistent_line_numbers(snapshot: &MultiBufferSnapshot) {
3502    let all_line_numbers = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
3503    for start_row in 1..all_line_numbers.len() {
3504        let line_numbers = snapshot
3505            .row_infos(MultiBufferRow(start_row as u32))
3506            .collect::<Vec<_>>();
3507        assert_eq!(
3508            line_numbers,
3509            all_line_numbers[start_row..],
3510            "start_row: {start_row}"
3511        );
3512    }
3513}
3514
3515#[track_caller]
3516fn assert_position_translation(snapshot: &MultiBufferSnapshot) {
3517    let text = Rope::from(snapshot.text());
3518
3519    let mut left_anchors = Vec::new();
3520    let mut right_anchors = Vec::new();
3521    let mut offsets = Vec::new();
3522    let mut points = Vec::new();
3523    for offset in 0..=text.len() + 1 {
3524        let clipped_left = snapshot.clip_offset(offset, Bias::Left);
3525        let clipped_right = snapshot.clip_offset(offset, Bias::Right);
3526        assert_eq!(
3527            clipped_left,
3528            text.clip_offset(offset, Bias::Left),
3529            "clip_offset({offset:?}, Left)"
3530        );
3531        assert_eq!(
3532            clipped_right,
3533            text.clip_offset(offset, Bias::Right),
3534            "clip_offset({offset:?}, Right)"
3535        );
3536        assert_eq!(
3537            snapshot.offset_to_point(clipped_left),
3538            text.offset_to_point(clipped_left),
3539            "offset_to_point({clipped_left})"
3540        );
3541        assert_eq!(
3542            snapshot.offset_to_point(clipped_right),
3543            text.offset_to_point(clipped_right),
3544            "offset_to_point({clipped_right})"
3545        );
3546        let anchor_after = snapshot.anchor_after(clipped_left);
3547        assert_eq!(
3548            anchor_after.to_offset(snapshot),
3549            clipped_left,
3550            "anchor_after({clipped_left}).to_offset {anchor_after:?}"
3551        );
3552        let anchor_before = snapshot.anchor_before(clipped_left);
3553        assert_eq!(
3554            anchor_before.to_offset(snapshot),
3555            clipped_left,
3556            "anchor_before({clipped_left}).to_offset"
3557        );
3558        left_anchors.push(anchor_before);
3559        right_anchors.push(anchor_after);
3560        offsets.push(clipped_left);
3561        points.push(text.offset_to_point(clipped_left));
3562    }
3563
3564    for row in 0..text.max_point().row {
3565        for column in 0..text.line_len(row) + 1 {
3566            let point = Point { row, column };
3567            let clipped_left = snapshot.clip_point(point, Bias::Left);
3568            let clipped_right = snapshot.clip_point(point, Bias::Right);
3569            assert_eq!(
3570                clipped_left,
3571                text.clip_point(point, Bias::Left),
3572                "clip_point({point:?}, Left)"
3573            );
3574            assert_eq!(
3575                clipped_right,
3576                text.clip_point(point, Bias::Right),
3577                "clip_point({point:?}, Right)"
3578            );
3579            assert_eq!(
3580                snapshot.point_to_offset(clipped_left),
3581                text.point_to_offset(clipped_left),
3582                "point_to_offset({clipped_left:?})"
3583            );
3584            assert_eq!(
3585                snapshot.point_to_offset(clipped_right),
3586                text.point_to_offset(clipped_right),
3587                "point_to_offset({clipped_right:?})"
3588            );
3589        }
3590    }
3591
3592    assert_eq!(
3593        snapshot.summaries_for_anchors::<usize, _>(&left_anchors),
3594        offsets,
3595        "left_anchors <-> offsets"
3596    );
3597    assert_eq!(
3598        snapshot.summaries_for_anchors::<Point, _>(&left_anchors),
3599        points,
3600        "left_anchors <-> points"
3601    );
3602    assert_eq!(
3603        snapshot.summaries_for_anchors::<usize, _>(&right_anchors),
3604        offsets,
3605        "right_anchors <-> offsets"
3606    );
3607    assert_eq!(
3608        snapshot.summaries_for_anchors::<Point, _>(&right_anchors),
3609        points,
3610        "right_anchors <-> points"
3611    );
3612
3613    for (anchors, bias) in [(&left_anchors, Bias::Left), (&right_anchors, Bias::Right)] {
3614        for (ix, (offset, anchor)) in offsets.iter().zip(anchors).enumerate() {
3615            if ix > 0 && *offset == 252 && offset > &offsets[ix - 1] {
3616                let prev_anchor = left_anchors[ix - 1];
3617                assert!(
3618                    anchor.cmp(&prev_anchor, snapshot).is_gt(),
3619                    "anchor({}, {bias:?}).cmp(&anchor({}, {bias:?}).is_gt()",
3620                    offsets[ix],
3621                    offsets[ix - 1],
3622                );
3623                assert!(
3624                    prev_anchor.cmp(anchor, snapshot).is_lt(),
3625                    "anchor({}, {bias:?}).cmp(&anchor({}, {bias:?}).is_lt()",
3626                    offsets[ix - 1],
3627                    offsets[ix],
3628                );
3629            }
3630        }
3631    }
3632
3633    if let Some((buffer, offset)) = snapshot.point_to_buffer_offset(snapshot.max_point()) {
3634        assert!(offset <= buffer.len());
3635    }
3636    if let Some((buffer, point, _)) = snapshot.point_to_buffer_point(snapshot.max_point()) {
3637        assert!(point <= buffer.max_point());
3638    }
3639}
3640
3641fn assert_line_indents(snapshot: &MultiBufferSnapshot) {
3642    let max_row = snapshot.max_point().row;
3643    let buffer_id = snapshot.excerpts().next().unwrap().1.remote_id();
3644    let text = text::Buffer::new(ReplicaId::LOCAL, buffer_id, snapshot.text());
3645    let mut line_indents = text
3646        .line_indents_in_row_range(0..max_row + 1)
3647        .collect::<Vec<_>>();
3648    for start_row in 0..snapshot.max_point().row {
3649        pretty_assertions::assert_eq!(
3650            snapshot
3651                .line_indents(MultiBufferRow(start_row), |_| true)
3652                .map(|(row, indent, _)| (row.0, indent))
3653                .collect::<Vec<_>>(),
3654            &line_indents[(start_row as usize)..],
3655            "line_indents({start_row})"
3656        );
3657    }
3658
3659    line_indents.reverse();
3660    pretty_assertions::assert_eq!(
3661        snapshot
3662            .reversed_line_indents(MultiBufferRow(max_row), |_| true)
3663            .map(|(row, indent, _)| (row.0, indent))
3664            .collect::<Vec<_>>(),
3665        &line_indents[..],
3666        "reversed_line_indents({max_row})"
3667    );
3668}
3669
3670#[gpui::test]
3671fn test_new_empty_buffer_uses_untitled_title(cx: &mut App) {
3672    let buffer = cx.new(|cx| Buffer::local("", cx));
3673    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3674
3675    assert_eq!(multibuffer.read(cx).title(cx), "untitled");
3676}
3677
3678#[gpui::test]
3679fn test_new_empty_buffer_uses_untitled_title_when_only_contains_whitespace(cx: &mut App) {
3680    let buffer = cx.new(|cx| Buffer::local("\n ", cx));
3681    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3682
3683    assert_eq!(multibuffer.read(cx).title(cx), "untitled");
3684}
3685
3686#[gpui::test]
3687fn test_new_empty_buffer_takes_first_line_for_title(cx: &mut App) {
3688    let buffer = cx.new(|cx| Buffer::local("Hello World\nSecond line", cx));
3689    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3690
3691    assert_eq!(multibuffer.read(cx).title(cx), "Hello World");
3692}
3693
3694#[gpui::test]
3695fn test_new_empty_buffer_takes_trimmed_first_line_for_title(cx: &mut App) {
3696    let buffer = cx.new(|cx| Buffer::local("\nHello, World ", cx));
3697    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3698
3699    assert_eq!(multibuffer.read(cx).title(cx), "Hello, World");
3700}
3701
3702#[gpui::test]
3703fn test_new_empty_buffer_uses_truncated_first_line_for_title(cx: &mut App) {
3704    let title = "aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeee";
3705    let title_after = "aaaaaaaaaabbbbbbbbbbccccccccccdddddddddd";
3706    let buffer = cx.new(|cx| Buffer::local(title, cx));
3707    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3708
3709    assert_eq!(multibuffer.read(cx).title(cx), title_after);
3710}
3711
3712#[gpui::test]
3713fn test_new_empty_buffer_uses_truncated_first_line_for_title_after_merging_adjacent_spaces(
3714    cx: &mut App,
3715) {
3716    let title = "aaaaaaaaaabbbbbbbbbb    ccccccccccddddddddddeeeeeeeeee";
3717    let title_after = "aaaaaaaaaabbbbbbbbbb ccccccccccddddddddd";
3718    let buffer = cx.new(|cx| Buffer::local(title, cx));
3719    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3720
3721    assert_eq!(multibuffer.read(cx).title(cx), title_after);
3722}
3723
3724#[gpui::test]
3725fn test_new_empty_buffers_title_can_be_set(cx: &mut App) {
3726    let buffer = cx.new(|cx| Buffer::local("Hello World", cx));
3727    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
3728    assert_eq!(multibuffer.read(cx).title(cx), "Hello World");
3729
3730    multibuffer.update(cx, |multibuffer, cx| {
3731        multibuffer.set_title("Hey".into(), cx)
3732    });
3733    assert_eq!(multibuffer.read(cx).title(cx), "Hey");
3734}
3735
3736#[gpui::test(iterations = 100)]
3737fn test_random_chunk_bitmaps(cx: &mut App, mut rng: StdRng) {
3738    let multibuffer = if rng.random() {
3739        let len = rng.random_range(0..10000);
3740        let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
3741        let buffer = cx.new(|cx| Buffer::local(text, cx));
3742        cx.new(|cx| MultiBuffer::singleton(buffer, cx))
3743    } else {
3744        MultiBuffer::build_random(&mut rng, cx)
3745    };
3746
3747    let snapshot = multibuffer.read(cx).snapshot(cx);
3748
3749    let chunks = snapshot.chunks(0..snapshot.len(), false);
3750
3751    for chunk in chunks {
3752        let chunk_text = chunk.text;
3753        let chars_bitmap = chunk.chars;
3754        let tabs_bitmap = chunk.tabs;
3755
3756        if chunk_text.is_empty() {
3757            assert_eq!(
3758                chars_bitmap, 0,
3759                "Empty chunk should have empty chars bitmap"
3760            );
3761            assert_eq!(tabs_bitmap, 0, "Empty chunk should have empty tabs bitmap");
3762            continue;
3763        }
3764
3765        assert!(
3766            chunk_text.len() <= 128,
3767            "Chunk text length {} exceeds 128 bytes",
3768            chunk_text.len()
3769        );
3770
3771        // Verify chars bitmap
3772        let char_indices = chunk_text
3773            .char_indices()
3774            .map(|(i, _)| i)
3775            .collect::<Vec<_>>();
3776
3777        for byte_idx in 0..chunk_text.len() {
3778            let should_have_bit = char_indices.contains(&byte_idx);
3779            let has_bit = chars_bitmap & (1 << byte_idx) != 0;
3780
3781            if has_bit != should_have_bit {
3782                eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
3783                eprintln!("Char indices: {:?}", char_indices);
3784                eprintln!("Chars bitmap: {:#b}", chars_bitmap);
3785            }
3786
3787            assert_eq!(
3788                has_bit, should_have_bit,
3789                "Chars bitmap mismatch at byte index {} in chunk {:?}. Expected bit: {}, Got bit: {}",
3790                byte_idx, chunk_text, should_have_bit, has_bit
3791            );
3792        }
3793
3794        for (byte_idx, byte) in chunk_text.bytes().enumerate() {
3795            let is_tab = byte == b'\t';
3796            let has_bit = tabs_bitmap & (1 << byte_idx) != 0;
3797
3798            if has_bit != is_tab {
3799                eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
3800                eprintln!("Tabs bitmap: {:#b}", tabs_bitmap);
3801                assert_eq!(
3802                    has_bit, is_tab,
3803                    "Tabs bitmap mismatch at byte index {} in chunk {:?}. Byte: {:?}, Expected bit: {}, Got bit: {}",
3804                    byte_idx, chunk_text, byte as char, is_tab, has_bit
3805                );
3806            }
3807        }
3808    }
3809}
3810
3811#[gpui::test(iterations = 100)]
3812fn test_random_chunk_bitmaps_with_diffs(cx: &mut App, mut rng: StdRng) {
3813    use buffer_diff::BufferDiff;
3814    use util::RandomCharIter;
3815
3816    let multibuffer = if rng.random() {
3817        let len = rng.random_range(100..10000);
3818        let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
3819        let buffer = cx.new(|cx| Buffer::local(text, cx));
3820        cx.new(|cx| MultiBuffer::singleton(buffer, cx))
3821    } else {
3822        MultiBuffer::build_random(&mut rng, cx)
3823    };
3824
3825    let _diff_count = rng.random_range(1..5);
3826    let mut diffs = Vec::new();
3827
3828    multibuffer.update(cx, |multibuffer, cx| {
3829        for buffer_id in multibuffer.excerpt_buffer_ids() {
3830            if rng.random_bool(0.7) {
3831                if let Some(buffer_handle) = multibuffer.buffer(buffer_id) {
3832                    let buffer_text = buffer_handle.read(cx).text();
3833                    let mut base_text = String::new();
3834
3835                    for line in buffer_text.lines() {
3836                        if rng.random_bool(0.3) {
3837                            continue;
3838                        } else if rng.random_bool(0.3) {
3839                            let line_len = rng.random_range(0..50);
3840                            let modified_line = RandomCharIter::new(&mut rng)
3841                                .take(line_len)
3842                                .collect::<String>();
3843                            base_text.push_str(&modified_line);
3844                            base_text.push('\n');
3845                        } else {
3846                            base_text.push_str(line);
3847                            base_text.push('\n');
3848                        }
3849                    }
3850
3851                    if rng.random_bool(0.5) {
3852                        let extra_lines = rng.random_range(1..5);
3853                        for _ in 0..extra_lines {
3854                            let line_len = rng.random_range(0..50);
3855                            let extra_line = RandomCharIter::new(&mut rng)
3856                                .take(line_len)
3857                                .collect::<String>();
3858                            base_text.push_str(&extra_line);
3859                            base_text.push('\n');
3860                        }
3861                    }
3862
3863                    let diff =
3864                        cx.new(|cx| BufferDiff::new_with_base_text(&base_text, &buffer_handle, cx));
3865                    diffs.push(diff.clone());
3866                    multibuffer.add_diff(diff, cx);
3867                }
3868            }
3869        }
3870    });
3871
3872    multibuffer.update(cx, |multibuffer, cx| {
3873        if rng.random_bool(0.5) {
3874            multibuffer.set_all_diff_hunks_expanded(cx);
3875        } else {
3876            let snapshot = multibuffer.snapshot(cx);
3877            let text = snapshot.text();
3878
3879            let mut ranges = Vec::new();
3880            for _ in 0..rng.random_range(1..5) {
3881                if snapshot.len() == 0 {
3882                    break;
3883                }
3884
3885                let diff_size = rng.random_range(5..1000);
3886                let mut start = rng.random_range(0..snapshot.len());
3887
3888                while !text.is_char_boundary(start) {
3889                    start = start.saturating_sub(1);
3890                }
3891
3892                let mut end = rng.random_range(start..snapshot.len().min(start + diff_size));
3893
3894                while !text.is_char_boundary(end) {
3895                    end = end.saturating_add(1);
3896                }
3897                let start_anchor = snapshot.anchor_after(start);
3898                let end_anchor = snapshot.anchor_before(end);
3899                ranges.push(start_anchor..end_anchor);
3900            }
3901            multibuffer.expand_diff_hunks(ranges, cx);
3902        }
3903    });
3904
3905    let snapshot = multibuffer.read(cx).snapshot(cx);
3906
3907    let chunks = snapshot.chunks(0..snapshot.len(), false);
3908
3909    for chunk in chunks {
3910        let chunk_text = chunk.text;
3911        let chars_bitmap = chunk.chars;
3912        let tabs_bitmap = chunk.tabs;
3913
3914        if chunk_text.is_empty() {
3915            assert_eq!(
3916                chars_bitmap, 0,
3917                "Empty chunk should have empty chars bitmap"
3918            );
3919            assert_eq!(tabs_bitmap, 0, "Empty chunk should have empty tabs bitmap");
3920            continue;
3921        }
3922
3923        assert!(
3924            chunk_text.len() <= 128,
3925            "Chunk text length {} exceeds 128 bytes",
3926            chunk_text.len()
3927        );
3928
3929        let char_indices = chunk_text
3930            .char_indices()
3931            .map(|(i, _)| i)
3932            .collect::<Vec<_>>();
3933
3934        for byte_idx in 0..chunk_text.len() {
3935            let should_have_bit = char_indices.contains(&byte_idx);
3936            let has_bit = chars_bitmap & (1 << byte_idx) != 0;
3937
3938            if has_bit != should_have_bit {
3939                eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
3940                eprintln!("Char indices: {:?}", char_indices);
3941                eprintln!("Chars bitmap: {:#b}", chars_bitmap);
3942            }
3943
3944            assert_eq!(
3945                has_bit, should_have_bit,
3946                "Chars bitmap mismatch at byte index {} in chunk {:?}. Expected bit: {}, Got bit: {}",
3947                byte_idx, chunk_text, should_have_bit, has_bit
3948            );
3949        }
3950
3951        for (byte_idx, byte) in chunk_text.bytes().enumerate() {
3952            let is_tab = byte == b'\t';
3953            let has_bit = tabs_bitmap & (1 << byte_idx) != 0;
3954
3955            if has_bit != is_tab {
3956                eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
3957                eprintln!("Tabs bitmap: {:#b}", tabs_bitmap);
3958                assert_eq!(
3959                    has_bit, is_tab,
3960                    "Tabs bitmap mismatch at byte index {} in chunk {:?}. Byte: {:?}, Expected bit: {}, Got bit: {}",
3961                    byte_idx, chunk_text, byte as char, is_tab, has_bit
3962                );
3963            }
3964        }
3965    }
3966}