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