multi_buffer_tests.rs

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