multi_buffer_tests.rs

   1use super::*;
   2use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind};
   3use gpui::{App, TestAppContext};
   4use indoc::indoc;
   5use language::{Buffer, Rope};
   6use parking_lot::RwLock;
   7use rand::prelude::*;
   8use settings::SettingsStore;
   9use std::env;
  10use std::time::{Duration, Instant};
  11use util::RandomCharIter;
  12use util::rel_path::rel_path;
  13use util::test::sample_text;
  14
  15#[ctor::ctor]
  16fn init_logger() {
  17    zlog::init_test();
  18}
  19
  20#[gpui::test]
  21fn test_empty_singleton(cx: &mut App) {
  22    let buffer = cx.new(|cx| Buffer::local("", cx));
  23    let buffer_id = buffer.read(cx).remote_id();
  24    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
  25    let snapshot = multibuffer.read(cx).snapshot(cx);
  26    assert_eq!(snapshot.text(), "");
  27    assert_eq!(
  28        snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>(),
  29        [RowInfo {
  30            buffer_id: Some(buffer_id),
  31            buffer_row: Some(0),
  32            multibuffer_row: Some(MultiBufferRow(0)),
  33            diff_status: None,
  34            expand_info: None,
  35            wrapped_buffer_row: None,
  36        }]
  37    );
  38}
  39
  40#[gpui::test]
  41fn test_singleton(cx: &mut App) {
  42    let buffer = cx.new(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
  43    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
  44
  45    let snapshot = multibuffer.read(cx).snapshot(cx);
  46    assert_eq!(snapshot.text(), buffer.read(cx).text());
  47
  48    assert_eq!(
  49        snapshot
  50            .row_infos(MultiBufferRow(0))
  51            .map(|info| info.buffer_row)
  52            .collect::<Vec<_>>(),
  53        (0..buffer.read(cx).row_count())
  54            .map(Some)
  55            .collect::<Vec<_>>()
  56    );
  57    assert_consistent_line_numbers(&snapshot);
  58
  59    buffer.update(cx, |buffer, cx| buffer.edit([(1..3, "XXX\n")], None, cx));
  60    let snapshot = multibuffer.read(cx).snapshot(cx);
  61
  62    assert_eq!(snapshot.text(), buffer.read(cx).text());
  63    assert_eq!(
  64        snapshot
  65            .row_infos(MultiBufferRow(0))
  66            .map(|info| info.buffer_row)
  67            .collect::<Vec<_>>(),
  68        (0..buffer.read(cx).row_count())
  69            .map(Some)
  70            .collect::<Vec<_>>()
  71    );
  72    assert_consistent_line_numbers(&snapshot);
  73}
  74
  75#[gpui::test]
  76fn test_remote(cx: &mut App) {
  77    let host_buffer = cx.new(|cx| Buffer::local("a", cx));
  78    let guest_buffer = cx.new(|cx| {
  79        let state = host_buffer.read(cx).to_proto(cx);
  80        let ops = cx
  81            .foreground_executor()
  82            .block_on(host_buffer.read(cx).serialize_ops(None, cx));
  83        let mut buffer =
  84            Buffer::from_proto(ReplicaId::REMOTE_SERVER, Capability::ReadWrite, state, None)
  85                .unwrap();
  86        buffer.apply_ops(
  87            ops.into_iter()
  88                .map(|op| language::proto::deserialize_operation(op).unwrap()),
  89            cx,
  90        );
  91        buffer
  92    });
  93    let multibuffer = cx.new(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
  94    let snapshot = multibuffer.read(cx).snapshot(cx);
  95    assert_eq!(snapshot.text(), "a");
  96
  97    guest_buffer.update(cx, |buffer, cx| buffer.edit([(1..1, "b")], None, cx));
  98    let snapshot = multibuffer.read(cx).snapshot(cx);
  99    assert_eq!(snapshot.text(), "ab");
 100
 101    guest_buffer.update(cx, |buffer, cx| buffer.edit([(2..2, "c")], None, cx));
 102    let snapshot = multibuffer.read(cx).snapshot(cx);
 103    assert_eq!(snapshot.text(), "abc");
 104}
 105
 106#[gpui::test]
 107fn test_excerpt_boundaries_and_clipping(cx: &mut App) {
 108    let buffer_1 = cx.new(|cx| Buffer::local(sample_text(6, 6, 'a'), cx));
 109    let buffer_2 = cx.new(|cx| Buffer::local(sample_text(6, 6, 'g'), cx));
 110    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
 111
 112    let events = Arc::new(RwLock::new(Vec::<Event>::new()));
 113    multibuffer.update(cx, |_, cx| {
 114        let events = events.clone();
 115        cx.subscribe(&multibuffer, move |_, _, event, _| {
 116            if let Event::Edited { .. } = event {
 117                events.write().push(event.clone())
 118            }
 119        })
 120        .detach();
 121    });
 122
 123    let subscription = multibuffer.update(cx, |multibuffer, cx| {
 124        let subscription = multibuffer.subscribe();
 125        multibuffer.push_excerpts(
 126            buffer_1.clone(),
 127            [ExcerptRange::new(Point::new(1, 2)..Point::new(2, 5))],
 128            cx,
 129        );
 130        assert_eq!(
 131            subscription.consume().into_inner(),
 132            [Edit {
 133                old: MultiBufferOffset(0)..MultiBufferOffset(0),
 134                new: MultiBufferOffset(0)..MultiBufferOffset(10)
 135            }]
 136        );
 137
 138        multibuffer.push_excerpts(
 139            buffer_1.clone(),
 140            [ExcerptRange::new(Point::new(3, 3)..Point::new(4, 4))],
 141            cx,
 142        );
 143        multibuffer.push_excerpts(
 144            buffer_2.clone(),
 145            [ExcerptRange::new(Point::new(3, 1)..Point::new(3, 3))],
 146            cx,
 147        );
 148        assert_eq!(
 149            subscription.consume().into_inner(),
 150            [Edit {
 151                old: MultiBufferOffset(10)..MultiBufferOffset(10),
 152                new: MultiBufferOffset(10)..MultiBufferOffset(22)
 153            }]
 154        );
 155
 156        subscription
 157    });
 158
 159    // Adding excerpts emits an edited event.
 160    assert_eq!(
 161        events.read().as_slice(),
 162        &[
 163            Event::Edited {
 164                edited_buffer: None,
 165            },
 166            Event::Edited {
 167                edited_buffer: None,
 168            },
 169            Event::Edited {
 170                edited_buffer: None,
 171            }
 172        ]
 173    );
 174
 175    let snapshot = multibuffer.read(cx).snapshot(cx);
 176    assert_eq!(
 177        snapshot.text(),
 178        indoc!(
 179            "
 180            bbbb
 181            ccccc
 182            ddd
 183            eeee
 184            jj"
 185        ),
 186    );
 187    assert_eq!(
 188        snapshot
 189            .row_infos(MultiBufferRow(0))
 190            .map(|info| info.buffer_row)
 191            .collect::<Vec<_>>(),
 192        [Some(1), Some(2), Some(3), Some(4), Some(3)]
 193    );
 194    assert_eq!(
 195        snapshot
 196            .row_infos(MultiBufferRow(2))
 197            .map(|info| info.buffer_row)
 198            .collect::<Vec<_>>(),
 199        [Some(3), Some(4), Some(3)]
 200    );
 201    assert_eq!(
 202        snapshot
 203            .row_infos(MultiBufferRow(4))
 204            .map(|info| info.buffer_row)
 205            .collect::<Vec<_>>(),
 206        [Some(3)]
 207    );
 208    assert!(
 209        snapshot
 210            .row_infos(MultiBufferRow(5))
 211            .map(|info| info.buffer_row)
 212            .collect::<Vec<_>>()
 213            .is_empty()
 214    );
 215
 216    assert_eq!(
 217        boundaries_in_range(Point::new(0, 0)..Point::new(4, 2), &snapshot),
 218        &[
 219            (MultiBufferRow(0), "bbbb\nccccc".to_string(), true),
 220            (MultiBufferRow(2), "ddd\neeee".to_string(), false),
 221            (MultiBufferRow(4), "jj".to_string(), true),
 222        ]
 223    );
 224    assert_eq!(
 225        boundaries_in_range(Point::new(0, 0)..Point::new(2, 0), &snapshot),
 226        &[(MultiBufferRow(0), "bbbb\nccccc".to_string(), true)]
 227    );
 228    assert_eq!(
 229        boundaries_in_range(Point::new(1, 0)..Point::new(1, 5), &snapshot),
 230        &[]
 231    );
 232    assert_eq!(
 233        boundaries_in_range(Point::new(1, 0)..Point::new(2, 0), &snapshot),
 234        &[]
 235    );
 236    assert_eq!(
 237        boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
 238        &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
 239    );
 240    assert_eq!(
 241        boundaries_in_range(Point::new(1, 0)..Point::new(4, 0), &snapshot),
 242        &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
 243    );
 244    assert_eq!(
 245        boundaries_in_range(Point::new(2, 0)..Point::new(3, 0), &snapshot),
 246        &[(MultiBufferRow(2), "ddd\neeee".to_string(), false)]
 247    );
 248    assert_eq!(
 249        boundaries_in_range(Point::new(4, 0)..Point::new(4, 2), &snapshot),
 250        &[(MultiBufferRow(4), "jj".to_string(), true)]
 251    );
 252    assert_eq!(
 253        boundaries_in_range(Point::new(4, 2)..Point::new(4, 2), &snapshot),
 254        &[]
 255    );
 256
 257    buffer_1.update(cx, |buffer, cx| {
 258        let text = "\n";
 259        buffer.edit(
 260            [
 261                (Point::new(0, 0)..Point::new(0, 0), text),
 262                (Point::new(2, 1)..Point::new(2, 3), text),
 263            ],
 264            None,
 265            cx,
 266        );
 267    });
 268
 269    let snapshot = multibuffer.read(cx).snapshot(cx);
 270    assert_eq!(
 271        snapshot.text(),
 272        concat!(
 273            "bbbb\n", // Preserve newlines
 274            "c\n",    //
 275            "cc\n",   //
 276            "ddd\n",  //
 277            "eeee\n", //
 278            "jj"      //
 279        )
 280    );
 281
 282    assert_eq!(
 283        subscription.consume().into_inner(),
 284        [Edit {
 285            old: MultiBufferOffset(6)..MultiBufferOffset(8),
 286            new: MultiBufferOffset(6)..MultiBufferOffset(7)
 287        }]
 288    );
 289
 290    let snapshot = multibuffer.read(cx).snapshot(cx);
 291    assert_eq!(
 292        snapshot.clip_point(Point::new(0, 5), Bias::Left),
 293        Point::new(0, 4)
 294    );
 295    assert_eq!(
 296        snapshot.clip_point(Point::new(0, 5), Bias::Right),
 297        Point::new(0, 4)
 298    );
 299    assert_eq!(
 300        snapshot.clip_point(Point::new(5, 1), Bias::Right),
 301        Point::new(5, 1)
 302    );
 303    assert_eq!(
 304        snapshot.clip_point(Point::new(5, 2), Bias::Right),
 305        Point::new(5, 2)
 306    );
 307    assert_eq!(
 308        snapshot.clip_point(Point::new(5, 3), Bias::Right),
 309        Point::new(5, 2)
 310    );
 311
 312    let snapshot = multibuffer.update(cx, |multibuffer, cx| {
 313        let (buffer_2_excerpt_id, _) =
 314            multibuffer.excerpts_for_buffer(buffer_2.read(cx).remote_id(), cx)[0].clone();
 315        multibuffer.remove_excerpts([buffer_2_excerpt_id], cx);
 316        multibuffer.snapshot(cx)
 317    });
 318
 319    assert_eq!(
 320        snapshot.text(),
 321        concat!(
 322            "bbbb\n", // Preserve newlines
 323            "c\n",    //
 324            "cc\n",   //
 325            "ddd\n",  //
 326            "eeee",   //
 327        )
 328    );
 329
 330    fn boundaries_in_range(
 331        range: Range<Point>,
 332        snapshot: &MultiBufferSnapshot,
 333    ) -> Vec<(MultiBufferRow, String, bool)> {
 334        snapshot
 335            .excerpt_boundaries_in_range(range)
 336            .map(|boundary| {
 337                let starts_new_buffer = boundary.starts_new_buffer();
 338                (
 339                    boundary.row,
 340                    boundary
 341                        .next
 342                        .buffer
 343                        .text_for_range(boundary.next.range.context)
 344                        .collect::<String>(),
 345                    starts_new_buffer,
 346                )
 347            })
 348            .collect::<Vec<_>>()
 349    }
 350}
 351
 352#[gpui::test]
 353async fn test_diff_boundary_anchors(cx: &mut TestAppContext) {
 354    let base_text = "one\ntwo\nthree\n";
 355    let text = "one\nthree\n";
 356    let buffer = cx.new(|cx| Buffer::local(text, cx));
 357    let diff = cx
 358        .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
 359    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 360    multibuffer.update(cx, |multibuffer, cx| multibuffer.add_diff(diff, cx));
 361
 362    let (before, after) = multibuffer.update(cx, |multibuffer, cx| {
 363        let before = multibuffer.snapshot(cx).anchor_before(Point::new(1, 0));
 364        let after = multibuffer.snapshot(cx).anchor_after(Point::new(1, 0));
 365        multibuffer.set_all_diff_hunks_expanded(cx);
 366        (before, after)
 367    });
 368    cx.run_until_parked();
 369
 370    let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
 371    let actual_text = snapshot.text();
 372    let actual_row_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
 373    let actual_diff = format_diff(&actual_text, &actual_row_infos, &Default::default(), None);
 374    pretty_assertions::assert_eq!(
 375        actual_diff,
 376        indoc! {
 377            "  one
 378             - two
 379               three
 380             "
 381        },
 382    );
 383
 384    multibuffer.update(cx, |multibuffer, cx| {
 385        let snapshot = multibuffer.snapshot(cx);
 386        assert_eq!(before.to_point(&snapshot), Point::new(1, 0));
 387        assert_eq!(after.to_point(&snapshot), Point::new(2, 0));
 388        assert_eq!(
 389            vec![Point::new(1, 0), Point::new(2, 0),],
 390            snapshot.summaries_for_anchors::<Point, _>(&[before, after]),
 391        )
 392    })
 393}
 394
 395#[gpui::test]
 396async fn test_diff_hunks_in_range(cx: &mut TestAppContext) {
 397    let base_text = "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\n";
 398    let text = "one\nfour\nseven\n";
 399    let buffer = cx.new(|cx| Buffer::local(text, cx));
 400    let diff = cx
 401        .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
 402    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 403    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
 404        (multibuffer.snapshot(cx), multibuffer.subscribe())
 405    });
 406
 407    multibuffer.update(cx, |multibuffer, cx| {
 408        multibuffer.add_diff(diff, cx);
 409        multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
 410    });
 411
 412    assert_new_snapshot(
 413        &multibuffer,
 414        &mut snapshot,
 415        &mut subscription,
 416        cx,
 417        indoc! {
 418            "  one
 419             - two
 420             - three
 421               four
 422             - five
 423             - six
 424               seven
 425             - eight
 426            "
 427        },
 428    );
 429
 430    assert_eq!(
 431        snapshot
 432            .diff_hunks_in_range(Point::new(1, 0)..Point::MAX)
 433            .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0)
 434            .collect::<Vec<_>>(),
 435        vec![1..3, 4..6, 7..8]
 436    );
 437
 438    assert_eq!(snapshot.diff_hunk_before(Point::new(1, 1)), None,);
 439    assert_eq!(
 440        snapshot.diff_hunk_before(Point::new(7, 0)),
 441        Some(MultiBufferRow(4))
 442    );
 443    assert_eq!(
 444        snapshot.diff_hunk_before(Point::new(4, 0)),
 445        Some(MultiBufferRow(1))
 446    );
 447
 448    multibuffer.update(cx, |multibuffer, cx| {
 449        multibuffer.collapse_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
 450    });
 451
 452    assert_new_snapshot(
 453        &multibuffer,
 454        &mut snapshot,
 455        &mut subscription,
 456        cx,
 457        indoc! {
 458            "
 459            one
 460            four
 461            seven
 462            "
 463        },
 464    );
 465
 466    assert_eq!(
 467        snapshot.diff_hunk_before(Point::new(2, 0)),
 468        Some(MultiBufferRow(1)),
 469    );
 470    assert_eq!(
 471        snapshot.diff_hunk_before(Point::new(4, 0)),
 472        Some(MultiBufferRow(2))
 473    );
 474}
 475
 476#[gpui::test]
 477async fn test_diff_hunks_in_range_query_starting_at_added_row(cx: &mut TestAppContext) {
 478    let base_text = "one\ntwo\nthree\n";
 479    let text = "one\nTWO\nthree\n";
 480    let buffer = cx.new(|cx| Buffer::local(text, cx));
 481    let diff = cx
 482        .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
 483    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 484    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
 485        (multibuffer.snapshot(cx), multibuffer.subscribe())
 486    });
 487
 488    multibuffer.update(cx, |multibuffer, cx| {
 489        multibuffer.add_diff(diff, cx);
 490        multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
 491    });
 492
 493    assert_new_snapshot(
 494        &multibuffer,
 495        &mut snapshot,
 496        &mut subscription,
 497        cx,
 498        indoc! {
 499            "  one
 500             - two
 501             + TWO
 502               three
 503            "
 504        },
 505    );
 506
 507    assert_eq!(
 508        snapshot
 509            .diff_hunks_in_range(Point::new(2, 0)..Point::MAX)
 510            .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0)
 511            .collect::<Vec<_>>(),
 512        vec![1..3],
 513        "querying starting at the added row should still return the full hunk including deleted lines"
 514    );
 515}
 516
 517#[gpui::test]
 518async fn test_inverted_diff_hunks_in_range(cx: &mut TestAppContext) {
 519    let base_text = "one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\n";
 520    let text = "ZERO\none\nTHREE\nfour\nseven\nEIGHT\nNINE\n";
 521    let buffer = cx.new(|cx| Buffer::local(text, cx));
 522    let diff = cx
 523        .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
 524    let base_text_buffer = diff.read_with(cx, |diff, _| diff.base_text_buffer());
 525    let multibuffer = cx.new(|cx| MultiBuffer::singleton(base_text_buffer.clone(), cx));
 526    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
 527        (multibuffer.snapshot(cx), multibuffer.subscribe())
 528    });
 529
 530    multibuffer.update(cx, |multibuffer, cx| {
 531        multibuffer.add_inverted_diff(diff, cx);
 532    });
 533
 534    assert_new_snapshot(
 535        &multibuffer,
 536        &mut snapshot,
 537        &mut subscription,
 538        cx,
 539        indoc! {
 540            "  one
 541             - two
 542             - three
 543               four
 544             - five
 545             - six
 546               seven
 547             - eight
 548            "
 549        },
 550    );
 551
 552    assert_eq!(
 553        snapshot
 554            .diff_hunks_in_range(Point::new(0, 0)..Point::MAX)
 555            .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0)
 556            .collect::<Vec<_>>(),
 557        vec![0..0, 1..3, 4..6, 7..8]
 558    );
 559
 560    assert_eq!(
 561        snapshot.diff_hunk_before(Point::new(1, 1)),
 562        Some(MultiBufferRow(0))
 563    );
 564    assert_eq!(
 565        snapshot.diff_hunk_before(Point::new(7, 0)),
 566        Some(MultiBufferRow(4))
 567    );
 568    assert_eq!(
 569        snapshot.diff_hunk_before(Point::new(4, 0)),
 570        Some(MultiBufferRow(1))
 571    );
 572}
 573
 574#[gpui::test]
 575async fn test_editing_text_in_diff_hunks(cx: &mut TestAppContext) {
 576    let base_text = "one\ntwo\nfour\nfive\nsix\nseven\n";
 577    let text = "one\ntwo\nTHREE\nfour\nfive\nseven\n";
 578    let buffer = cx.new(|cx| Buffer::local(text, cx));
 579    let diff = cx
 580        .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
 581    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
 582
 583    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
 584        multibuffer.add_diff(diff.clone(), cx);
 585        (multibuffer.snapshot(cx), multibuffer.subscribe())
 586    });
 587
 588    cx.executor().run_until_parked();
 589    multibuffer.update(cx, |multibuffer, cx| {
 590        multibuffer.set_all_diff_hunks_expanded(cx);
 591    });
 592
 593    assert_new_snapshot(
 594        &multibuffer,
 595        &mut snapshot,
 596        &mut subscription,
 597        cx,
 598        indoc! {
 599            "
 600              one
 601              two
 602            + THREE
 603              four
 604              five
 605            - six
 606              seven
 607            "
 608        },
 609    );
 610
 611    // Insert a newline within an insertion hunk
 612    multibuffer.update(cx, |multibuffer, cx| {
 613        multibuffer.edit([(Point::new(2, 0)..Point::new(2, 0), "__\n__")], None, cx);
 614    });
 615    assert_new_snapshot(
 616        &multibuffer,
 617        &mut snapshot,
 618        &mut subscription,
 619        cx,
 620        indoc! {
 621            "
 622              one
 623              two
 624            + __
 625            + __THREE
 626              four
 627              five
 628            - six
 629              seven
 630            "
 631        },
 632    );
 633
 634    // Delete the newline before a deleted hunk.
 635    multibuffer.update(cx, |multibuffer, cx| {
 636        multibuffer.edit([(Point::new(5, 4)..Point::new(6, 0), "")], None, cx);
 637    });
 638    assert_new_snapshot(
 639        &multibuffer,
 640        &mut snapshot,
 641        &mut subscription,
 642        cx,
 643        indoc! {
 644            "
 645              one
 646              two
 647            + __
 648            + __THREE
 649              four
 650              fiveseven
 651            "
 652        },
 653    );
 654
 655    multibuffer.update(cx, |multibuffer, cx| multibuffer.undo(cx));
 656    assert_new_snapshot(
 657        &multibuffer,
 658        &mut snapshot,
 659        &mut subscription,
 660        cx,
 661        indoc! {
 662            "
 663              one
 664              two
 665            + __
 666            + __THREE
 667              four
 668              five
 669            - six
 670              seven
 671            "
 672        },
 673    );
 674
 675    // Cannot (yet) insert at the beginning of a deleted hunk.
 676    // (because it would put the newline in the wrong place)
 677    multibuffer.update(cx, |multibuffer, cx| {
 678        multibuffer.edit([(Point::new(6, 0)..Point::new(6, 0), "\n")], None, cx);
 679    });
 680    assert_new_snapshot(
 681        &multibuffer,
 682        &mut snapshot,
 683        &mut subscription,
 684        cx,
 685        indoc! {
 686            "
 687              one
 688              two
 689            + __
 690            + __THREE
 691              four
 692              five
 693            - six
 694              seven
 695            "
 696        },
 697    );
 698
 699    // Replace a range that ends in a deleted hunk.
 700    multibuffer.update(cx, |multibuffer, cx| {
 701        multibuffer.edit([(Point::new(5, 2)..Point::new(6, 2), "fty-")], None, cx);
 702    });
 703    assert_new_snapshot(
 704        &multibuffer,
 705        &mut snapshot,
 706        &mut subscription,
 707        cx,
 708        indoc! {
 709            "
 710              one
 711              two
 712            + __
 713            + __THREE
 714              four
 715              fifty-seven
 716            "
 717        },
 718    );
 719}
 720
 721#[gpui::test]
 722fn test_excerpt_events(cx: &mut App) {
 723    let buffer_1 = cx.new(|cx| Buffer::local(sample_text(10, 3, 'a'), cx));
 724    let buffer_2 = cx.new(|cx| Buffer::local(sample_text(10, 3, 'm'), cx));
 725
 726    let leader_multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
 727    let follower_multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
 728    let follower_edit_event_count = Arc::new(RwLock::new(0));
 729
 730    follower_multibuffer.update(cx, |_, cx| {
 731        let follower_edit_event_count = follower_edit_event_count.clone();
 732        cx.subscribe(
 733            &leader_multibuffer,
 734            move |follower, _, event, cx| match event.clone() {
 735                Event::ExcerptsAdded {
 736                    buffer,
 737                    predecessor,
 738                    excerpts,
 739                } => follower.insert_excerpts_with_ids_after(predecessor, buffer, excerpts, cx),
 740                Event::ExcerptsRemoved { ids, .. } => follower.remove_excerpts(ids, cx),
 741                Event::Edited { .. } => {
 742                    *follower_edit_event_count.write() += 1;
 743                }
 744                _ => {}
 745            },
 746        )
 747        .detach();
 748    });
 749
 750    leader_multibuffer.update(cx, |leader, cx| {
 751        leader.push_excerpts(
 752            buffer_1.clone(),
 753            [ExcerptRange::new(0..8), ExcerptRange::new(12..16)],
 754            cx,
 755        );
 756        leader.insert_excerpts_after(
 757            leader.excerpt_ids()[0],
 758            buffer_2.clone(),
 759            [ExcerptRange::new(0..5), ExcerptRange::new(10..15)],
 760            cx,
 761        )
 762    });
 763    assert_eq!(
 764        leader_multibuffer.read(cx).snapshot(cx).text(),
 765        follower_multibuffer.read(cx).snapshot(cx).text(),
 766    );
 767    assert_eq!(*follower_edit_event_count.read(), 2);
 768
 769    leader_multibuffer.update(cx, |leader, cx| {
 770        let excerpt_ids = leader.excerpt_ids();
 771        leader.remove_excerpts([excerpt_ids[1], excerpt_ids[3]], cx);
 772    });
 773    assert_eq!(
 774        leader_multibuffer.read(cx).snapshot(cx).text(),
 775        follower_multibuffer.read(cx).snapshot(cx).text(),
 776    );
 777    assert_eq!(*follower_edit_event_count.read(), 3);
 778
 779    // Removing an empty set of excerpts is a noop.
 780    leader_multibuffer.update(cx, |leader, cx| {
 781        leader.remove_excerpts([], cx);
 782    });
 783    assert_eq!(
 784        leader_multibuffer.read(cx).snapshot(cx).text(),
 785        follower_multibuffer.read(cx).snapshot(cx).text(),
 786    );
 787    assert_eq!(*follower_edit_event_count.read(), 3);
 788
 789    // Adding an empty set of excerpts is a noop.
 790    leader_multibuffer.update(cx, |leader, cx| {
 791        leader.push_excerpts::<usize>(buffer_2.clone(), [], cx);
 792    });
 793    assert_eq!(
 794        leader_multibuffer.read(cx).snapshot(cx).text(),
 795        follower_multibuffer.read(cx).snapshot(cx).text(),
 796    );
 797    assert_eq!(*follower_edit_event_count.read(), 3);
 798
 799    leader_multibuffer.update(cx, |leader, cx| {
 800        leader.clear(cx);
 801    });
 802    assert_eq!(
 803        leader_multibuffer.read(cx).snapshot(cx).text(),
 804        follower_multibuffer.read(cx).snapshot(cx).text(),
 805    );
 806    assert_eq!(*follower_edit_event_count.read(), 4);
 807}
 808
 809#[gpui::test]
 810fn test_expand_excerpts(cx: &mut App) {
 811    let buffer = cx.new(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
 812    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
 813
 814    multibuffer.update(cx, |multibuffer, cx| {
 815        multibuffer.set_excerpts_for_path(
 816            PathKey::for_buffer(&buffer, cx),
 817            buffer,
 818            vec![
 819                // Note that in this test, this first excerpt
 820                // does not contain a new line
 821                Point::new(3, 2)..Point::new(3, 3),
 822                Point::new(7, 1)..Point::new(7, 3),
 823                Point::new(15, 0)..Point::new(15, 0),
 824            ],
 825            1,
 826            cx,
 827        )
 828    });
 829
 830    let snapshot = multibuffer.read(cx).snapshot(cx);
 831
 832    assert_eq!(
 833        snapshot.text(),
 834        concat!(
 835            "ccc\n", //
 836            "ddd\n", //
 837            "eee",   //
 838            "\n",    // End of excerpt
 839            "ggg\n", //
 840            "hhh\n", //
 841            "iii",   //
 842            "\n",    // End of excerpt
 843            "ooo\n", //
 844            "ppp\n", //
 845            "qqq",   // End of excerpt
 846        )
 847    );
 848    drop(snapshot);
 849
 850    multibuffer.update(cx, |multibuffer, cx| {
 851        let line_zero = multibuffer.snapshot(cx).anchor_before(Point::new(0, 0));
 852        multibuffer.expand_excerpts(
 853            multibuffer.excerpt_ids(),
 854            1,
 855            ExpandExcerptDirection::UpAndDown,
 856            cx,
 857        );
 858        let snapshot = multibuffer.snapshot(cx);
 859        let line_two = snapshot.anchor_before(Point::new(2, 0));
 860        assert_eq!(line_two.cmp(&line_zero, &snapshot), cmp::Ordering::Greater);
 861    });
 862
 863    let snapshot = multibuffer.read(cx).snapshot(cx);
 864
 865    assert_eq!(
 866        snapshot.text(),
 867        concat!(
 868            "bbb\n", //
 869            "ccc\n", //
 870            "ddd\n", //
 871            "eee\n", //
 872            "fff\n", //
 873            "ggg\n", //
 874            "hhh\n", //
 875            "iii\n", //
 876            "jjj\n", // End of excerpt
 877            "nnn\n", //
 878            "ooo\n", //
 879            "ppp\n", //
 880            "qqq\n", //
 881            "rrr",   // End of excerpt
 882        )
 883    );
 884}
 885
 886#[gpui::test(iterations = 100)]
 887async fn test_set_anchored_excerpts_for_path(cx: &mut TestAppContext) {
 888    let buffer_1 = cx.new(|cx| Buffer::local(sample_text(20, 3, 'a'), cx));
 889    let buffer_2 = cx.new(|cx| Buffer::local(sample_text(15, 4, 'a'), cx));
 890    let snapshot_1 = buffer_1.update(cx, |buffer, _| buffer.snapshot());
 891    let snapshot_2 = buffer_2.update(cx, |buffer, _| buffer.snapshot());
 892    let ranges_1 = vec![
 893        snapshot_1.anchor_before(Point::new(3, 2))..snapshot_1.anchor_before(Point::new(4, 2)),
 894        snapshot_1.anchor_before(Point::new(7, 1))..snapshot_1.anchor_before(Point::new(7, 3)),
 895        snapshot_1.anchor_before(Point::new(15, 0))..snapshot_1.anchor_before(Point::new(15, 0)),
 896    ];
 897    let ranges_2 = vec![
 898        snapshot_2.anchor_before(Point::new(2, 1))..snapshot_2.anchor_before(Point::new(3, 1)),
 899        snapshot_2.anchor_before(Point::new(10, 0))..snapshot_2.anchor_before(Point::new(10, 2)),
 900    ];
 901
 902    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
 903    let anchor_ranges_1 = multibuffer
 904        .update(cx, |multibuffer, cx| {
 905            multibuffer.set_anchored_excerpts_for_path(
 906                PathKey::for_buffer(&buffer_1, cx),
 907                buffer_1.clone(),
 908                ranges_1,
 909                2,
 910                cx,
 911            )
 912        })
 913        .await;
 914    let snapshot_1 = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
 915    assert_eq!(
 916        anchor_ranges_1
 917            .iter()
 918            .map(|range| range.to_point(&snapshot_1))
 919            .collect::<Vec<_>>(),
 920        vec![
 921            Point::new(2, 2)..Point::new(3, 2),
 922            Point::new(6, 1)..Point::new(6, 3),
 923            Point::new(11, 0)..Point::new(11, 0),
 924        ]
 925    );
 926    let anchor_ranges_2 = multibuffer
 927        .update(cx, |multibuffer, cx| {
 928            multibuffer.set_anchored_excerpts_for_path(
 929                PathKey::for_buffer(&buffer_2, cx),
 930                buffer_2.clone(),
 931                ranges_2,
 932                2,
 933                cx,
 934            )
 935        })
 936        .await;
 937    let snapshot_2 = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
 938    assert_eq!(
 939        anchor_ranges_2
 940            .iter()
 941            .map(|range| range.to_point(&snapshot_2))
 942            .collect::<Vec<_>>(),
 943        vec![
 944            Point::new(16, 1)..Point::new(17, 1),
 945            Point::new(22, 0)..Point::new(22, 2)
 946        ]
 947    );
 948
 949    let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
 950    assert_eq!(
 951        snapshot.text(),
 952        concat!(
 953            "bbb\n", // buffer_1
 954            "ccc\n", //
 955            "ddd\n", // <-- excerpt 1
 956            "eee\n", // <-- excerpt 1
 957            "fff\n", //
 958            "ggg\n", //
 959            "hhh\n", // <-- excerpt 2
 960            "iii\n", //
 961            "jjj\n", //
 962            //
 963            "nnn\n", //
 964            "ooo\n", //
 965            "ppp\n", // <-- excerpt 3
 966            "qqq\n", //
 967            "rrr\n", //
 968            //
 969            "aaaa\n", // buffer 2
 970            "bbbb\n", //
 971            "cccc\n", // <-- excerpt 4
 972            "dddd\n", // <-- excerpt 4
 973            "eeee\n", //
 974            "ffff\n", //
 975            //
 976            "iiii\n", //
 977            "jjjj\n", //
 978            "kkkk\n", // <-- excerpt 5
 979            "llll\n", //
 980            "mmmm",   //
 981        )
 982    );
 983}
 984
 985#[gpui::test]
 986fn test_empty_multibuffer(cx: &mut App) {
 987    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
 988
 989    let snapshot = multibuffer.read(cx).snapshot(cx);
 990    assert_eq!(snapshot.text(), "");
 991    assert_eq!(
 992        snapshot
 993            .row_infos(MultiBufferRow(0))
 994            .map(|info| info.buffer_row)
 995            .collect::<Vec<_>>(),
 996        &[Some(0)]
 997    );
 998    assert!(
 999        snapshot
1000            .row_infos(MultiBufferRow(1))
1001            .map(|info| info.buffer_row)
1002            .collect::<Vec<_>>()
1003            .is_empty(),
1004    );
1005}
1006
1007#[gpui::test]
1008async fn test_empty_diff_excerpt(cx: &mut TestAppContext) {
1009    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
1010    let buffer = cx.new(|cx| Buffer::local("", cx));
1011    let base_text = "a\nb\nc";
1012
1013    let diff = cx
1014        .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
1015    multibuffer.update(cx, |multibuffer, cx| {
1016        multibuffer.push_excerpts(buffer.clone(), [ExcerptRange::new(0..0)], cx);
1017        multibuffer.set_all_diff_hunks_expanded(cx);
1018        multibuffer.add_diff(diff.clone(), cx);
1019    });
1020    cx.run_until_parked();
1021
1022    let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
1023    assert_eq!(snapshot.text(), "a\nb\nc\n");
1024
1025    let hunk = snapshot
1026        .diff_hunks_in_range(Point::new(1, 1)..Point::new(1, 1))
1027        .next()
1028        .unwrap();
1029
1030    assert_eq!(hunk.diff_base_byte_range.start, BufferOffset(0));
1031
1032    let buf2 = cx.new(|cx| Buffer::local("X", cx));
1033    multibuffer.update(cx, |multibuffer, cx| {
1034        multibuffer.push_excerpts(buf2, [ExcerptRange::new(0..1)], cx);
1035    });
1036
1037    buffer.update(cx, |buffer, cx| {
1038        buffer.edit([(0..0, "a\nb\nc")], None, cx);
1039        diff.update(cx, |diff, cx| {
1040            diff.recalculate_diff_sync(&buffer.text_snapshot(), cx);
1041        });
1042        assert_eq!(buffer.text(), "a\nb\nc")
1043    });
1044    cx.run_until_parked();
1045
1046    let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
1047    assert_eq!(snapshot.text(), "a\nb\nc\nX");
1048
1049    buffer.update(cx, |buffer, cx| {
1050        buffer.undo(cx);
1051        diff.update(cx, |diff, cx| {
1052            diff.recalculate_diff_sync(&buffer.text_snapshot(), cx);
1053        });
1054        assert_eq!(buffer.text(), "")
1055    });
1056    cx.run_until_parked();
1057
1058    let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
1059    assert_eq!(snapshot.text(), "a\nb\nc\n\nX");
1060}
1061
1062#[gpui::test]
1063fn test_singleton_multibuffer_anchors(cx: &mut App) {
1064    let buffer = cx.new(|cx| Buffer::local("abcd", cx));
1065    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
1066    let old_snapshot = multibuffer.read(cx).snapshot(cx);
1067    buffer.update(cx, |buffer, cx| {
1068        buffer.edit([(0..0, "X")], None, cx);
1069        buffer.edit([(5..5, "Y")], None, cx);
1070    });
1071    let new_snapshot = multibuffer.read(cx).snapshot(cx);
1072
1073    assert_eq!(old_snapshot.text(), "abcd");
1074    assert_eq!(new_snapshot.text(), "XabcdY");
1075
1076    assert_eq!(
1077        old_snapshot
1078            .anchor_before(MultiBufferOffset(0))
1079            .to_offset(&new_snapshot),
1080        MultiBufferOffset(0)
1081    );
1082    assert_eq!(
1083        old_snapshot
1084            .anchor_after(MultiBufferOffset(0))
1085            .to_offset(&new_snapshot),
1086        MultiBufferOffset(1)
1087    );
1088    assert_eq!(
1089        old_snapshot
1090            .anchor_before(MultiBufferOffset(4))
1091            .to_offset(&new_snapshot),
1092        MultiBufferOffset(5)
1093    );
1094    assert_eq!(
1095        old_snapshot
1096            .anchor_after(MultiBufferOffset(4))
1097            .to_offset(&new_snapshot),
1098        MultiBufferOffset(6)
1099    );
1100}
1101
1102#[gpui::test]
1103fn test_multibuffer_anchors(cx: &mut App) {
1104    let buffer_1 = cx.new(|cx| Buffer::local("abcd", cx));
1105    let buffer_2 = cx.new(|cx| Buffer::local("efghi", cx));
1106    let multibuffer = cx.new(|cx| {
1107        let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
1108        multibuffer.push_excerpts(buffer_1.clone(), [ExcerptRange::new(0..4)], cx);
1109        multibuffer.push_excerpts(buffer_2.clone(), [ExcerptRange::new(0..5)], cx);
1110        multibuffer
1111    });
1112    let old_snapshot = multibuffer.read(cx).snapshot(cx);
1113
1114    assert_eq!(
1115        old_snapshot
1116            .anchor_before(MultiBufferOffset(0))
1117            .to_offset(&old_snapshot),
1118        MultiBufferOffset(0)
1119    );
1120    assert_eq!(
1121        old_snapshot
1122            .anchor_after(MultiBufferOffset(0))
1123            .to_offset(&old_snapshot),
1124        MultiBufferOffset(0)
1125    );
1126    assert_eq!(Anchor::min().to_offset(&old_snapshot), MultiBufferOffset(0));
1127    assert_eq!(Anchor::min().to_offset(&old_snapshot), MultiBufferOffset(0));
1128    assert_eq!(
1129        Anchor::max().to_offset(&old_snapshot),
1130        MultiBufferOffset(10)
1131    );
1132    assert_eq!(
1133        Anchor::max().to_offset(&old_snapshot),
1134        MultiBufferOffset(10)
1135    );
1136
1137    buffer_1.update(cx, |buffer, cx| {
1138        buffer.edit([(0..0, "W")], None, cx);
1139        buffer.edit([(5..5, "X")], None, cx);
1140    });
1141    buffer_2.update(cx, |buffer, cx| {
1142        buffer.edit([(0..0, "Y")], None, cx);
1143        buffer.edit([(6..6, "Z")], None, cx);
1144    });
1145    let new_snapshot = multibuffer.read(cx).snapshot(cx);
1146
1147    assert_eq!(old_snapshot.text(), "abcd\nefghi");
1148    assert_eq!(new_snapshot.text(), "WabcdX\nYefghiZ");
1149
1150    assert_eq!(
1151        old_snapshot
1152            .anchor_before(MultiBufferOffset(0))
1153            .to_offset(&new_snapshot),
1154        MultiBufferOffset(0)
1155    );
1156    assert_eq!(
1157        old_snapshot
1158            .anchor_after(MultiBufferOffset(0))
1159            .to_offset(&new_snapshot),
1160        MultiBufferOffset(1)
1161    );
1162    assert_eq!(
1163        old_snapshot
1164            .anchor_before(MultiBufferOffset(1))
1165            .to_offset(&new_snapshot),
1166        MultiBufferOffset(2)
1167    );
1168    assert_eq!(
1169        old_snapshot
1170            .anchor_after(MultiBufferOffset(1))
1171            .to_offset(&new_snapshot),
1172        MultiBufferOffset(2)
1173    );
1174    assert_eq!(
1175        old_snapshot
1176            .anchor_before(MultiBufferOffset(2))
1177            .to_offset(&new_snapshot),
1178        MultiBufferOffset(3)
1179    );
1180    assert_eq!(
1181        old_snapshot
1182            .anchor_after(MultiBufferOffset(2))
1183            .to_offset(&new_snapshot),
1184        MultiBufferOffset(3)
1185    );
1186    assert_eq!(
1187        old_snapshot
1188            .anchor_before(MultiBufferOffset(5))
1189            .to_offset(&new_snapshot),
1190        MultiBufferOffset(7)
1191    );
1192    assert_eq!(
1193        old_snapshot
1194            .anchor_after(MultiBufferOffset(5))
1195            .to_offset(&new_snapshot),
1196        MultiBufferOffset(8)
1197    );
1198    assert_eq!(
1199        old_snapshot
1200            .anchor_before(MultiBufferOffset(10))
1201            .to_offset(&new_snapshot),
1202        MultiBufferOffset(13)
1203    );
1204    assert_eq!(
1205        old_snapshot
1206            .anchor_after(MultiBufferOffset(10))
1207            .to_offset(&new_snapshot),
1208        MultiBufferOffset(14)
1209    );
1210}
1211
1212#[gpui::test]
1213fn test_resolving_anchors_after_replacing_their_excerpts(cx: &mut App) {
1214    let buffer_1 = cx.new(|cx| Buffer::local("abcd", cx));
1215    let buffer_2 = cx.new(|cx| Buffer::local("ABCDEFGHIJKLMNOP", cx));
1216    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
1217
1218    // Create an insertion id in buffer 1 that doesn't exist in buffer 2.
1219    // Add an excerpt from buffer 1 that spans this new insertion.
1220    buffer_1.update(cx, |buffer, cx| buffer.edit([(4..4, "123")], None, cx));
1221    let excerpt_id_1 = multibuffer.update(cx, |multibuffer, cx| {
1222        multibuffer
1223            .push_excerpts(buffer_1.clone(), [ExcerptRange::new(0..7)], cx)
1224            .pop()
1225            .unwrap()
1226    });
1227
1228    let snapshot_1 = multibuffer.read(cx).snapshot(cx);
1229    assert_eq!(snapshot_1.text(), "abcd123");
1230
1231    // Replace the buffer 1 excerpt with new excerpts from buffer 2.
1232    let (excerpt_id_2, excerpt_id_3) = multibuffer.update(cx, |multibuffer, cx| {
1233        multibuffer.remove_excerpts([excerpt_id_1], cx);
1234        let mut ids = multibuffer
1235            .push_excerpts(
1236                buffer_2.clone(),
1237                [
1238                    ExcerptRange::new(0..4),
1239                    ExcerptRange::new(6..10),
1240                    ExcerptRange::new(12..16),
1241                ],
1242                cx,
1243            )
1244            .into_iter();
1245        (ids.next().unwrap(), ids.next().unwrap())
1246    });
1247    let snapshot_2 = multibuffer.read(cx).snapshot(cx);
1248    assert_eq!(snapshot_2.text(), "ABCD\nGHIJ\nMNOP");
1249
1250    // The old excerpt id doesn't get reused.
1251    assert_ne!(excerpt_id_2, excerpt_id_1);
1252
1253    // Resolve some anchors from the previous snapshot in the new snapshot.
1254    // The current excerpts are from a different buffer, so we don't attempt to
1255    // resolve the old text anchor in the new buffer.
1256    assert_eq!(
1257        snapshot_2.summary_for_anchor::<MultiBufferOffset>(
1258            &snapshot_1.anchor_before(MultiBufferOffset(2))
1259        ),
1260        MultiBufferOffset(0)
1261    );
1262    assert_eq!(
1263        snapshot_2.summaries_for_anchors::<MultiBufferOffset, _>(&[
1264            snapshot_1.anchor_before(MultiBufferOffset(2)),
1265            snapshot_1.anchor_after(MultiBufferOffset(3))
1266        ]),
1267        vec![MultiBufferOffset(0), MultiBufferOffset(0)]
1268    );
1269
1270    // Refresh anchors from the old snapshot. The return value indicates that both
1271    // anchors lost their original excerpt.
1272    let refresh = snapshot_2.refresh_anchors(&[
1273        snapshot_1.anchor_before(MultiBufferOffset(2)),
1274        snapshot_1.anchor_after(MultiBufferOffset(3)),
1275    ]);
1276    assert_eq!(
1277        refresh,
1278        &[
1279            (0, snapshot_2.anchor_before(MultiBufferOffset(0)), false),
1280            (1, snapshot_2.anchor_after(MultiBufferOffset(0)), false),
1281        ]
1282    );
1283
1284    // Replace the middle excerpt with a smaller excerpt in buffer 2,
1285    // that intersects the old excerpt.
1286    let excerpt_id_5 = multibuffer.update(cx, |multibuffer, cx| {
1287        multibuffer.remove_excerpts([excerpt_id_3], cx);
1288        multibuffer
1289            .insert_excerpts_after(
1290                excerpt_id_2,
1291                buffer_2.clone(),
1292                [ExcerptRange::new(5..8)],
1293                cx,
1294            )
1295            .pop()
1296            .unwrap()
1297    });
1298
1299    let snapshot_3 = multibuffer.read(cx).snapshot(cx);
1300    assert_eq!(snapshot_3.text(), "ABCD\nFGH\nMNOP");
1301    assert_ne!(excerpt_id_5, excerpt_id_3);
1302
1303    // Resolve some anchors from the previous snapshot in the new snapshot.
1304    // The third anchor can't be resolved, since its excerpt has been removed,
1305    // so it resolves to the same position as its predecessor.
1306    let anchors = [
1307        snapshot_2.anchor_before(MultiBufferOffset(0)),
1308        snapshot_2.anchor_after(MultiBufferOffset(2)),
1309        snapshot_2.anchor_after(MultiBufferOffset(6)),
1310        snapshot_2.anchor_after(MultiBufferOffset(14)),
1311    ];
1312    assert_eq!(
1313        snapshot_3.summaries_for_anchors::<MultiBufferOffset, _>(&anchors),
1314        &[
1315            MultiBufferOffset(0),
1316            MultiBufferOffset(2),
1317            MultiBufferOffset(9),
1318            MultiBufferOffset(13)
1319        ]
1320    );
1321
1322    let new_anchors = snapshot_3.refresh_anchors(&anchors);
1323    assert_eq!(
1324        new_anchors.iter().map(|a| (a.0, a.2)).collect::<Vec<_>>(),
1325        &[(0, true), (1, true), (2, true), (3, true)]
1326    );
1327    assert_eq!(
1328        snapshot_3.summaries_for_anchors::<MultiBufferOffset, _>(new_anchors.iter().map(|a| &a.1)),
1329        &[
1330            MultiBufferOffset(0),
1331            MultiBufferOffset(2),
1332            MultiBufferOffset(7),
1333            MultiBufferOffset(13)
1334        ]
1335    );
1336}
1337
1338#[gpui::test]
1339async fn test_basic_diff_hunks(cx: &mut TestAppContext) {
1340    let text = indoc!(
1341        "
1342        ZERO
1343        one
1344        TWO
1345        three
1346        six
1347        "
1348    );
1349    let base_text = indoc!(
1350        "
1351        one
1352        two
1353        three
1354        four
1355        five
1356        six
1357        "
1358    );
1359
1360    let buffer = cx.new(|cx| Buffer::local(text, cx));
1361    let diff = cx
1362        .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
1363    cx.run_until_parked();
1364
1365    let multibuffer = cx.new(|cx| {
1366        let mut multibuffer = MultiBuffer::singleton(buffer.clone(), cx);
1367        multibuffer.add_diff(diff.clone(), cx);
1368        multibuffer
1369    });
1370
1371    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
1372        (multibuffer.snapshot(cx), multibuffer.subscribe())
1373    });
1374    assert_eq!(
1375        snapshot.text(),
1376        indoc!(
1377            "
1378            ZERO
1379            one
1380            TWO
1381            three
1382            six
1383            "
1384        ),
1385    );
1386
1387    multibuffer.update(cx, |multibuffer, cx| {
1388        multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
1389    });
1390
1391    assert_new_snapshot(
1392        &multibuffer,
1393        &mut snapshot,
1394        &mut subscription,
1395        cx,
1396        indoc!(
1397            "
1398            + ZERO
1399              one
1400            - two
1401            + TWO
1402              three
1403            - four
1404            - five
1405              six
1406            "
1407        ),
1408    );
1409
1410    assert_eq!(
1411        snapshot
1412            .row_infos(MultiBufferRow(0))
1413            .map(|info| (info.buffer_row, info.diff_status))
1414            .collect::<Vec<_>>(),
1415        vec![
1416            (Some(0), Some(DiffHunkStatus::added_none())),
1417            (Some(1), None),
1418            (Some(1), Some(DiffHunkStatus::deleted_none())),
1419            (Some(2), Some(DiffHunkStatus::added_none())),
1420            (Some(3), None),
1421            (Some(3), Some(DiffHunkStatus::deleted_none())),
1422            (Some(4), Some(DiffHunkStatus::deleted_none())),
1423            (Some(4), None),
1424            (Some(5), None)
1425        ]
1426    );
1427
1428    assert_chunks_in_ranges(&snapshot);
1429    assert_consistent_line_numbers(&snapshot);
1430    assert_position_translation(&snapshot);
1431    assert_line_indents(&snapshot);
1432
1433    multibuffer.update(cx, |multibuffer, cx| {
1434        multibuffer.collapse_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
1435    });
1436    assert_new_snapshot(
1437        &multibuffer,
1438        &mut snapshot,
1439        &mut subscription,
1440        cx,
1441        indoc!(
1442            "
1443            ZERO
1444            one
1445            TWO
1446            three
1447            six
1448            "
1449        ),
1450    );
1451
1452    assert_chunks_in_ranges(&snapshot);
1453    assert_consistent_line_numbers(&snapshot);
1454    assert_position_translation(&snapshot);
1455    assert_line_indents(&snapshot);
1456
1457    // Expand the first diff hunk
1458    multibuffer.update(cx, |multibuffer, cx| {
1459        let position = multibuffer.read(cx).anchor_before(Point::new(2, 2));
1460        multibuffer.expand_diff_hunks(vec![position..position], cx)
1461    });
1462    assert_new_snapshot(
1463        &multibuffer,
1464        &mut snapshot,
1465        &mut subscription,
1466        cx,
1467        indoc!(
1468            "
1469              ZERO
1470              one
1471            - two
1472            + TWO
1473              three
1474              six
1475            "
1476        ),
1477    );
1478
1479    // Expand the second diff hunk
1480    multibuffer.update(cx, |multibuffer, cx| {
1481        let start = multibuffer.read(cx).anchor_before(Point::new(4, 0));
1482        let end = multibuffer.read(cx).anchor_before(Point::new(5, 0));
1483        multibuffer.expand_diff_hunks(vec![start..end], cx)
1484    });
1485    assert_new_snapshot(
1486        &multibuffer,
1487        &mut snapshot,
1488        &mut subscription,
1489        cx,
1490        indoc!(
1491            "
1492              ZERO
1493              one
1494            - two
1495            + TWO
1496              three
1497            - four
1498            - five
1499              six
1500            "
1501        ),
1502    );
1503
1504    assert_chunks_in_ranges(&snapshot);
1505    assert_consistent_line_numbers(&snapshot);
1506    assert_position_translation(&snapshot);
1507    assert_line_indents(&snapshot);
1508
1509    // Edit the buffer before the first hunk
1510    buffer.update(cx, |buffer, cx| {
1511        buffer.edit_via_marked_text(
1512            indoc!(
1513                "
1514                ZERO
1515                one« hundred
1516                  thousand»
1517                TWO
1518                three
1519                six
1520                "
1521            ),
1522            None,
1523            cx,
1524        );
1525    });
1526    assert_new_snapshot(
1527        &multibuffer,
1528        &mut snapshot,
1529        &mut subscription,
1530        cx,
1531        indoc!(
1532            "
1533              ZERO
1534              one hundred
1535                thousand
1536            - two
1537            + TWO
1538              three
1539            - four
1540            - five
1541              six
1542            "
1543        ),
1544    );
1545
1546    assert_chunks_in_ranges(&snapshot);
1547    assert_consistent_line_numbers(&snapshot);
1548    assert_position_translation(&snapshot);
1549    assert_line_indents(&snapshot);
1550
1551    // Recalculate the diff, changing the first diff hunk.
1552    diff.update(cx, |diff, cx| {
1553        diff.recalculate_diff_sync(&buffer.read(cx).text_snapshot(), cx);
1554    });
1555    cx.run_until_parked();
1556    assert_new_snapshot(
1557        &multibuffer,
1558        &mut snapshot,
1559        &mut subscription,
1560        cx,
1561        indoc!(
1562            "
1563              ZERO
1564              one hundred
1565                thousand
1566              TWO
1567              three
1568            - four
1569            - five
1570              six
1571            "
1572        ),
1573    );
1574
1575    assert_eq!(
1576        snapshot
1577            .diff_hunks_in_range(MultiBufferOffset(0)..snapshot.len())
1578            .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0)
1579            .collect::<Vec<_>>(),
1580        &[0..4, 5..7]
1581    );
1582}
1583
1584#[gpui::test]
1585async fn test_repeatedly_expand_a_diff_hunk(cx: &mut TestAppContext) {
1586    let text = indoc!(
1587        "
1588        one
1589        TWO
1590        THREE
1591        four
1592        FIVE
1593        six
1594        "
1595    );
1596    let base_text = indoc!(
1597        "
1598        one
1599        four
1600        five
1601        six
1602        "
1603    );
1604
1605    let buffer = cx.new(|cx| Buffer::local(text, cx));
1606    let diff = cx
1607        .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
1608    cx.run_until_parked();
1609
1610    let multibuffer = cx.new(|cx| {
1611        let mut multibuffer = MultiBuffer::singleton(buffer.clone(), cx);
1612        multibuffer.add_diff(diff.clone(), cx);
1613        multibuffer
1614    });
1615
1616    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
1617        (multibuffer.snapshot(cx), multibuffer.subscribe())
1618    });
1619
1620    multibuffer.update(cx, |multibuffer, cx| {
1621        multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
1622    });
1623
1624    assert_new_snapshot(
1625        &multibuffer,
1626        &mut snapshot,
1627        &mut subscription,
1628        cx,
1629        indoc!(
1630            "
1631              one
1632            + TWO
1633            + THREE
1634              four
1635            - five
1636            + FIVE
1637              six
1638            "
1639        ),
1640    );
1641
1642    // Regression test: expanding diff hunks that are already expanded should not change anything.
1643    multibuffer.update(cx, |multibuffer, cx| {
1644        multibuffer.expand_diff_hunks(
1645            vec![
1646                snapshot.anchor_before(Point::new(2, 0))..snapshot.anchor_before(Point::new(2, 0)),
1647            ],
1648            cx,
1649        );
1650    });
1651
1652    assert_new_snapshot(
1653        &multibuffer,
1654        &mut snapshot,
1655        &mut subscription,
1656        cx,
1657        indoc!(
1658            "
1659              one
1660            + TWO
1661            + THREE
1662              four
1663            - five
1664            + FIVE
1665              six
1666            "
1667        ),
1668    );
1669
1670    // Now collapse all diff hunks
1671    multibuffer.update(cx, |multibuffer, cx| {
1672        multibuffer.collapse_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
1673    });
1674
1675    assert_new_snapshot(
1676        &multibuffer,
1677        &mut snapshot,
1678        &mut subscription,
1679        cx,
1680        indoc!(
1681            "
1682            one
1683            TWO
1684            THREE
1685            four
1686            FIVE
1687            six
1688            "
1689        ),
1690    );
1691
1692    // Expand the hunks again, but this time provide two ranges that are both within the same hunk
1693    // Target the first hunk which is between "one" and "four"
1694    multibuffer.update(cx, |multibuffer, cx| {
1695        multibuffer.expand_diff_hunks(
1696            vec![
1697                snapshot.anchor_before(Point::new(4, 0))..snapshot.anchor_before(Point::new(4, 0)),
1698                snapshot.anchor_before(Point::new(4, 2))..snapshot.anchor_before(Point::new(4, 2)),
1699            ],
1700            cx,
1701        );
1702    });
1703    assert_new_snapshot(
1704        &multibuffer,
1705        &mut snapshot,
1706        &mut subscription,
1707        cx,
1708        indoc!(
1709            "
1710              one
1711              TWO
1712              THREE
1713              four
1714            - five
1715            + FIVE
1716              six
1717            "
1718        ),
1719    );
1720}
1721
1722#[gpui::test]
1723fn test_set_excerpts_for_buffer_ordering(cx: &mut TestAppContext) {
1724    let buf1 = cx.new(|cx| {
1725        Buffer::local(
1726            indoc! {
1727            "zero
1728            one
1729            two
1730            two.five
1731            three
1732            four
1733            five
1734            six
1735            seven
1736            eight
1737            nine
1738            ten
1739            eleven
1740            ",
1741            },
1742            cx,
1743        )
1744    });
1745    let path1: PathKey = PathKey::with_sort_prefix(0, rel_path("root").into_arc());
1746
1747    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
1748    multibuffer.update(cx, |multibuffer, cx| {
1749        multibuffer.set_excerpts_for_path(
1750            path1.clone(),
1751            buf1.clone(),
1752            vec![
1753                Point::row_range(1..2),
1754                Point::row_range(6..7),
1755                Point::row_range(11..12),
1756            ],
1757            1,
1758            cx,
1759        );
1760    });
1761
1762    assert_excerpts_match(
1763        &multibuffer,
1764        cx,
1765        indoc! {
1766            "-----
1767            zero
1768            one
1769            two
1770            two.five
1771            -----
1772            four
1773            five
1774            six
1775            seven
1776            -----
1777            nine
1778            ten
1779            eleven
1780            "
1781        },
1782    );
1783
1784    buf1.update(cx, |buffer, cx| buffer.edit([(0..5, "")], None, cx));
1785
1786    multibuffer.update(cx, |multibuffer, cx| {
1787        multibuffer.set_excerpts_for_path(
1788            path1.clone(),
1789            buf1.clone(),
1790            vec![
1791                Point::row_range(0..3),
1792                Point::row_range(5..7),
1793                Point::row_range(10..11),
1794            ],
1795            1,
1796            cx,
1797        );
1798    });
1799
1800    assert_excerpts_match(
1801        &multibuffer,
1802        cx,
1803        indoc! {
1804            "-----
1805             one
1806             two
1807             two.five
1808             three
1809             four
1810             five
1811             six
1812             seven
1813             eight
1814             nine
1815             ten
1816             eleven
1817            "
1818        },
1819    );
1820}
1821
1822#[gpui::test]
1823fn test_set_excerpts_for_buffer(cx: &mut TestAppContext) {
1824    let buf1 = cx.new(|cx| {
1825        Buffer::local(
1826            indoc! {
1827            "zero
1828            one
1829            two
1830            three
1831            four
1832            five
1833            six
1834            seven
1835            ",
1836            },
1837            cx,
1838        )
1839    });
1840    let path1: PathKey = PathKey::with_sort_prefix(0, rel_path("root").into_arc());
1841    let buf2 = cx.new(|cx| {
1842        Buffer::local(
1843            indoc! {
1844            "000
1845            111
1846            222
1847            333
1848            444
1849            555
1850            666
1851            777
1852            888
1853            999
1854            "
1855            },
1856            cx,
1857        )
1858    });
1859    let path2 = PathKey::with_sort_prefix(1, rel_path("root").into_arc());
1860
1861    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
1862    multibuffer.update(cx, |multibuffer, cx| {
1863        multibuffer.set_excerpts_for_path(
1864            path1.clone(),
1865            buf1.clone(),
1866            vec![Point::row_range(0..1)],
1867            2,
1868            cx,
1869        );
1870    });
1871
1872    assert_excerpts_match(
1873        &multibuffer,
1874        cx,
1875        indoc! {
1876        "-----
1877        zero
1878        one
1879        two
1880        three
1881        "
1882        },
1883    );
1884
1885    multibuffer.update(cx, |multibuffer, cx| {
1886        multibuffer.set_excerpts_for_path(path1.clone(), buf1.clone(), vec![], 2, cx);
1887    });
1888
1889    assert_excerpts_match(&multibuffer, cx, "");
1890
1891    multibuffer.update(cx, |multibuffer, cx| {
1892        multibuffer.set_excerpts_for_path(
1893            path1.clone(),
1894            buf1.clone(),
1895            vec![Point::row_range(0..1), Point::row_range(7..8)],
1896            2,
1897            cx,
1898        );
1899    });
1900
1901    assert_excerpts_match(
1902        &multibuffer,
1903        cx,
1904        indoc! {"-----
1905                zero
1906                one
1907                two
1908                three
1909                -----
1910                five
1911                six
1912                seven
1913                "},
1914    );
1915
1916    multibuffer.update(cx, |multibuffer, cx| {
1917        multibuffer.set_excerpts_for_path(
1918            path1.clone(),
1919            buf1.clone(),
1920            vec![Point::row_range(0..1), Point::row_range(5..6)],
1921            2,
1922            cx,
1923        );
1924    });
1925
1926    assert_excerpts_match(
1927        &multibuffer,
1928        cx,
1929        indoc! {"-----
1930                    zero
1931                    one
1932                    two
1933                    three
1934                    four
1935                    five
1936                    six
1937                    seven
1938                    "},
1939    );
1940
1941    multibuffer.update(cx, |multibuffer, cx| {
1942        multibuffer.set_excerpts_for_path(
1943            path2.clone(),
1944            buf2.clone(),
1945            vec![Point::row_range(2..3)],
1946            2,
1947            cx,
1948        );
1949    });
1950
1951    assert_excerpts_match(
1952        &multibuffer,
1953        cx,
1954        indoc! {"-----
1955                zero
1956                one
1957                two
1958                three
1959                four
1960                five
1961                six
1962                seven
1963                -----
1964                000
1965                111
1966                222
1967                333
1968                444
1969                555
1970                "},
1971    );
1972
1973    multibuffer.update(cx, |multibuffer, cx| {
1974        multibuffer.set_excerpts_for_path(path1.clone(), buf1.clone(), vec![], 2, cx);
1975    });
1976
1977    multibuffer.update(cx, |multibuffer, cx| {
1978        multibuffer.set_excerpts_for_path(
1979            path1.clone(),
1980            buf1.clone(),
1981            vec![Point::row_range(3..4)],
1982            2,
1983            cx,
1984        );
1985    });
1986
1987    assert_excerpts_match(
1988        &multibuffer,
1989        cx,
1990        indoc! {"-----
1991                one
1992                two
1993                three
1994                four
1995                five
1996                six
1997                -----
1998                000
1999                111
2000                222
2001                333
2002                444
2003                555
2004                "},
2005    );
2006
2007    multibuffer.update(cx, |multibuffer, cx| {
2008        multibuffer.set_excerpts_for_path(
2009            path1.clone(),
2010            buf1.clone(),
2011            vec![Point::row_range(3..4)],
2012            2,
2013            cx,
2014        );
2015    });
2016}
2017
2018#[gpui::test]
2019fn test_set_excerpts_for_buffer_rename(cx: &mut TestAppContext) {
2020    let buf1 = cx.new(|cx| {
2021        Buffer::local(
2022            indoc! {
2023            "zero
2024            one
2025            two
2026            three
2027            four
2028            five
2029            six
2030            seven
2031            ",
2032            },
2033            cx,
2034        )
2035    });
2036    let path: PathKey = PathKey::with_sort_prefix(0, rel_path("root").into_arc());
2037    let buf2 = cx.new(|cx| {
2038        Buffer::local(
2039            indoc! {
2040            "000
2041            111
2042            222
2043            333
2044            "
2045            },
2046            cx,
2047        )
2048    });
2049
2050    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2051    multibuffer.update(cx, |multibuffer, cx| {
2052        multibuffer.set_excerpts_for_path(
2053            path.clone(),
2054            buf1.clone(),
2055            vec![Point::row_range(1..1), Point::row_range(4..5)],
2056            1,
2057            cx,
2058        );
2059    });
2060
2061    assert_excerpts_match(
2062        &multibuffer,
2063        cx,
2064        indoc! {
2065        "-----
2066        zero
2067        one
2068        two
2069        three
2070        four
2071        five
2072        six
2073        "
2074        },
2075    );
2076
2077    multibuffer.update(cx, |multibuffer, cx| {
2078        multibuffer.set_excerpts_for_path(
2079            path.clone(),
2080            buf2.clone(),
2081            vec![Point::row_range(0..1)],
2082            2,
2083            cx,
2084        );
2085    });
2086
2087    assert_excerpts_match(
2088        &multibuffer,
2089        cx,
2090        indoc! {"-----
2091                000
2092                111
2093                222
2094                333
2095                "},
2096    );
2097}
2098
2099#[gpui::test]
2100async fn test_diff_hunks_with_multiple_excerpts(cx: &mut TestAppContext) {
2101    let base_text_1 = indoc!(
2102        "
2103        one
2104        two
2105            three
2106        four
2107        five
2108        six
2109        "
2110    );
2111    let text_1 = indoc!(
2112        "
2113        ZERO
2114        one
2115        TWO
2116            three
2117        six
2118        "
2119    );
2120    let base_text_2 = indoc!(
2121        "
2122        seven
2123          eight
2124        nine
2125        ten
2126        eleven
2127        twelve
2128        "
2129    );
2130    let text_2 = indoc!(
2131        "
2132          eight
2133        nine
2134        eleven
2135        THIRTEEN
2136        FOURTEEN
2137        "
2138    );
2139
2140    let buffer_1 = cx.new(|cx| Buffer::local(text_1, cx));
2141    let buffer_2 = cx.new(|cx| Buffer::local(text_2, cx));
2142    let diff_1 = cx.new(|cx| {
2143        BufferDiff::new_with_base_text(base_text_1, &buffer_1.read(cx).text_snapshot(), cx)
2144    });
2145    let diff_2 = cx.new(|cx| {
2146        BufferDiff::new_with_base_text(base_text_2, &buffer_2.read(cx).text_snapshot(), cx)
2147    });
2148    cx.run_until_parked();
2149
2150    let multibuffer = cx.new(|cx| {
2151        let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
2152        multibuffer.push_excerpts(
2153            buffer_1.clone(),
2154            [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
2155            cx,
2156        );
2157        multibuffer.push_excerpts(
2158            buffer_2.clone(),
2159            [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
2160            cx,
2161        );
2162        multibuffer.add_diff(diff_1.clone(), cx);
2163        multibuffer.add_diff(diff_2.clone(), cx);
2164        multibuffer
2165    });
2166
2167    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
2168        (multibuffer.snapshot(cx), multibuffer.subscribe())
2169    });
2170    assert_eq!(
2171        snapshot.text(),
2172        indoc!(
2173            "
2174            ZERO
2175            one
2176            TWO
2177                three
2178            six
2179
2180              eight
2181            nine
2182            eleven
2183            THIRTEEN
2184            FOURTEEN
2185            "
2186        ),
2187    );
2188
2189    multibuffer.update(cx, |multibuffer, cx| {
2190        multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
2191    });
2192
2193    assert_new_snapshot(
2194        &multibuffer,
2195        &mut snapshot,
2196        &mut subscription,
2197        cx,
2198        indoc!(
2199            "
2200            + ZERO
2201              one
2202            - two
2203            + TWO
2204                  three
2205            - four
2206            - five
2207              six
2208
2209            - seven
2210                eight
2211              nine
2212            - ten
2213              eleven
2214            - twelve
2215            + THIRTEEN
2216            + FOURTEEN
2217            "
2218        ),
2219    );
2220
2221    let id_1 = buffer_1.read_with(cx, |buffer, _| buffer.remote_id());
2222    let id_2 = buffer_2.read_with(cx, |buffer, _| buffer.remote_id());
2223    let base_id_1 = diff_1.read_with(cx, |diff, cx| diff.base_text(cx).remote_id());
2224    let base_id_2 = diff_2.read_with(cx, |diff, cx| diff.base_text(cx).remote_id());
2225
2226    let buffer_lines = (0..=snapshot.max_row().0)
2227        .map(|row| {
2228            let (buffer, range) = snapshot.buffer_line_for_row(MultiBufferRow(row))?;
2229            Some((
2230                buffer.remote_id(),
2231                buffer.text_for_range(range).collect::<String>(),
2232            ))
2233        })
2234        .collect::<Vec<_>>();
2235    pretty_assertions::assert_eq!(
2236        buffer_lines,
2237        [
2238            Some((id_1, "ZERO".into())),
2239            Some((id_1, "one".into())),
2240            Some((base_id_1, "two".into())),
2241            Some((id_1, "TWO".into())),
2242            Some((id_1, "    three".into())),
2243            Some((base_id_1, "four".into())),
2244            Some((base_id_1, "five".into())),
2245            Some((id_1, "six".into())),
2246            Some((id_1, "".into())),
2247            Some((base_id_2, "seven".into())),
2248            Some((id_2, "  eight".into())),
2249            Some((id_2, "nine".into())),
2250            Some((base_id_2, "ten".into())),
2251            Some((id_2, "eleven".into())),
2252            Some((base_id_2, "twelve".into())),
2253            Some((id_2, "THIRTEEN".into())),
2254            Some((id_2, "FOURTEEN".into())),
2255            Some((id_2, "".into())),
2256        ]
2257    );
2258
2259    let buffer_ids_by_range = [
2260        (Point::new(0, 0)..Point::new(0, 0), &[id_1] as &[_]),
2261        (Point::new(0, 0)..Point::new(2, 0), &[id_1]),
2262        (Point::new(2, 0)..Point::new(2, 0), &[id_1]),
2263        (Point::new(3, 0)..Point::new(3, 0), &[id_1]),
2264        (Point::new(8, 0)..Point::new(9, 0), &[id_1]),
2265        (Point::new(8, 0)..Point::new(10, 0), &[id_1, id_2]),
2266        (Point::new(9, 0)..Point::new(9, 0), &[id_2]),
2267    ];
2268    for (range, buffer_ids) in buffer_ids_by_range {
2269        assert_eq!(
2270            snapshot
2271                .buffer_ids_for_range(range.clone())
2272                .collect::<Vec<_>>(),
2273            buffer_ids,
2274            "buffer_ids_for_range({range:?}"
2275        );
2276    }
2277
2278    assert_position_translation(&snapshot);
2279    assert_line_indents(&snapshot);
2280
2281    assert_eq!(
2282        snapshot
2283            .diff_hunks_in_range(MultiBufferOffset(0)..snapshot.len())
2284            .map(|hunk| hunk.row_range.start.0..hunk.row_range.end.0)
2285            .collect::<Vec<_>>(),
2286        &[0..1, 2..4, 5..7, 9..10, 12..13, 14..17]
2287    );
2288
2289    buffer_2.update(cx, |buffer, cx| {
2290        buffer.edit_via_marked_text(
2291            indoc!(
2292                "
2293                  eight
2294                «»eleven
2295                THIRTEEN
2296                FOURTEEN
2297                "
2298            ),
2299            None,
2300            cx,
2301        );
2302    });
2303
2304    assert_new_snapshot(
2305        &multibuffer,
2306        &mut snapshot,
2307        &mut subscription,
2308        cx,
2309        indoc!(
2310            "
2311            + ZERO
2312              one
2313            - two
2314            + TWO
2315                  three
2316            - four
2317            - five
2318              six
2319
2320            - seven
2321                eight
2322              eleven
2323            - twelve
2324            + THIRTEEN
2325            + FOURTEEN
2326            "
2327        ),
2328    );
2329
2330    assert_line_indents(&snapshot);
2331}
2332
2333/// A naive implementation of a multi-buffer that does not maintain
2334/// any derived state, used for comparison in a randomized test.
2335#[derive(Default)]
2336struct ReferenceMultibuffer {
2337    excerpts: Vec<ReferenceExcerpt>,
2338    diffs: HashMap<BufferId, Entity<BufferDiff>>,
2339    inverted_diffs: HashMap<BufferId, Entity<BufferDiff>>,
2340}
2341
2342#[derive(Debug)]
2343struct ReferenceExcerpt {
2344    id: ExcerptId,
2345    buffer: Entity<Buffer>,
2346    range: Range<text::Anchor>,
2347    expanded_diff_hunks: Vec<text::Anchor>,
2348}
2349
2350#[derive(Debug)]
2351struct ReferenceRegion {
2352    buffer_id: Option<BufferId>,
2353    range: Range<usize>,
2354    buffer_range: Option<Range<Point>>,
2355    status: Option<DiffHunkStatus>,
2356    excerpt_id: Option<ExcerptId>,
2357}
2358
2359impl ReferenceMultibuffer {
2360    fn expand_excerpts(&mut self, excerpts: &HashSet<ExcerptId>, line_count: u32, cx: &App) {
2361        if line_count == 0 {
2362            return;
2363        }
2364
2365        for id in excerpts {
2366            let excerpt = self.excerpts.iter_mut().find(|e| e.id == *id).unwrap();
2367            let snapshot = excerpt.buffer.read(cx).snapshot();
2368            let mut point_range = excerpt.range.to_point(&snapshot);
2369            point_range.start = Point::new(point_range.start.row.saturating_sub(line_count), 0);
2370            point_range.end =
2371                snapshot.clip_point(Point::new(point_range.end.row + line_count, 0), Bias::Left);
2372            point_range.end.column = snapshot.line_len(point_range.end.row);
2373            excerpt.range =
2374                snapshot.anchor_before(point_range.start)..snapshot.anchor_after(point_range.end);
2375        }
2376    }
2377
2378    fn remove_excerpt(&mut self, id: ExcerptId, cx: &App) {
2379        let ix = self
2380            .excerpts
2381            .iter()
2382            .position(|excerpt| excerpt.id == id)
2383            .unwrap();
2384        let excerpt = self.excerpts.remove(ix);
2385        let buffer = excerpt.buffer.read(cx);
2386        let buffer_id = buffer.remote_id();
2387        log::info!(
2388            "Removing excerpt {}: {:?}",
2389            ix,
2390            buffer
2391                .text_for_range(excerpt.range.to_offset(buffer))
2392                .collect::<String>(),
2393        );
2394        if !self
2395            .excerpts
2396            .iter()
2397            .any(|excerpt| excerpt.buffer.read(cx).remote_id() == buffer_id)
2398        {
2399            self.diffs.remove(&buffer_id);
2400            self.inverted_diffs.remove(&buffer_id);
2401        }
2402    }
2403
2404    fn insert_excerpt_after(
2405        &mut self,
2406        prev_id: ExcerptId,
2407        new_excerpt_id: ExcerptId,
2408        (buffer_handle, anchor_range): (Entity<Buffer>, Range<text::Anchor>),
2409    ) {
2410        let excerpt_ix = if prev_id == ExcerptId::max() {
2411            self.excerpts.len()
2412        } else {
2413            self.excerpts
2414                .iter()
2415                .position(|excerpt| excerpt.id == prev_id)
2416                .unwrap()
2417                + 1
2418        };
2419        self.excerpts.insert(
2420            excerpt_ix,
2421            ReferenceExcerpt {
2422                id: new_excerpt_id,
2423                buffer: buffer_handle,
2424                range: anchor_range,
2425                expanded_diff_hunks: Vec::new(),
2426            },
2427        );
2428    }
2429
2430    fn expand_diff_hunks(&mut self, excerpt_id: ExcerptId, range: Range<text::Anchor>, cx: &App) {
2431        let excerpt = self
2432            .excerpts
2433            .iter_mut()
2434            .find(|e| e.id == excerpt_id)
2435            .unwrap();
2436        let buffer = excerpt.buffer.read(cx).snapshot();
2437        let buffer_id = buffer.remote_id();
2438
2439        // Skip inverted excerpts - hunks are always expanded
2440        if self.inverted_diffs.contains_key(&buffer_id) {
2441            return;
2442        }
2443
2444        let Some(diff) = self.diffs.get(&buffer_id) else {
2445            return;
2446        };
2447        let excerpt_range = excerpt.range.to_offset(&buffer);
2448        for hunk in diff
2449            .read(cx)
2450            .snapshot(cx)
2451            .hunks_intersecting_range(range, &buffer)
2452        {
2453            let hunk_range = hunk.buffer_range.to_offset(&buffer);
2454            if hunk_range.start < excerpt_range.start || hunk_range.start > excerpt_range.end {
2455                continue;
2456            }
2457            if let Err(ix) = excerpt
2458                .expanded_diff_hunks
2459                .binary_search_by(|anchor| anchor.cmp(&hunk.buffer_range.start, &buffer))
2460            {
2461                log::info!(
2462                    "expanding diff hunk {:?}. excerpt:{:?}, excerpt range:{:?}",
2463                    hunk_range,
2464                    excerpt_id,
2465                    excerpt_range
2466                );
2467                excerpt
2468                    .expanded_diff_hunks
2469                    .insert(ix, hunk.buffer_range.start);
2470            } else {
2471                log::trace!("hunk {hunk_range:?} already expanded in excerpt {excerpt_id:?}");
2472            }
2473        }
2474    }
2475
2476    fn expected_content(&self, cx: &App) -> (String, Vec<RowInfo>, HashSet<MultiBufferRow>) {
2477        let mut text = String::new();
2478        let mut regions = Vec::<ReferenceRegion>::new();
2479        let mut excerpt_boundary_rows = HashSet::default();
2480        for excerpt in &self.excerpts {
2481            excerpt_boundary_rows.insert(MultiBufferRow(text.matches('\n').count() as u32));
2482            let buffer = excerpt.buffer.read(cx);
2483            let buffer_id = buffer.remote_id();
2484            let buffer_range = excerpt.range.to_offset(buffer);
2485
2486            if let Some(diff) = self.inverted_diffs.get(&buffer_id) {
2487                let diff_snapshot = diff.read(cx).snapshot(cx);
2488
2489                let mut offset = buffer_range.start;
2490                for hunk in diff_snapshot.hunks_intersecting_base_text_range(
2491                    buffer_range.clone(),
2492                    diff_snapshot.original_buffer_snapshot(),
2493                ) {
2494                    let mut hunk_base_range = hunk.diff_base_byte_range.clone();
2495
2496                    hunk_base_range.end = hunk_base_range.end.min(buffer_range.end);
2497                    if hunk_base_range.start > buffer_range.end
2498                        || hunk_base_range.start < buffer_range.start
2499                    {
2500                        continue;
2501                    }
2502
2503                    // Add the text before the hunk
2504                    if hunk_base_range.start >= offset {
2505                        let len = text.len();
2506                        text.extend(buffer.text_for_range(offset..hunk_base_range.start));
2507                        if text.len() > len {
2508                            regions.push(ReferenceRegion {
2509                                buffer_id: Some(buffer_id),
2510                                range: len..text.len(),
2511                                buffer_range: Some(
2512                                    (offset..hunk_base_range.start).to_point(&buffer),
2513                                ),
2514                                status: None,
2515                                excerpt_id: Some(excerpt.id),
2516                            });
2517                        }
2518                    }
2519
2520                    // Add the "deleted" region (base text that's not in main)
2521                    if !hunk_base_range.is_empty() {
2522                        let len = text.len();
2523                        text.extend(buffer.text_for_range(hunk_base_range.clone()));
2524                        regions.push(ReferenceRegion {
2525                            buffer_id: Some(buffer_id),
2526                            range: len..text.len(),
2527                            buffer_range: Some(hunk_base_range.to_point(&buffer)),
2528                            status: Some(DiffHunkStatus::deleted(hunk.secondary_status)),
2529                            excerpt_id: Some(excerpt.id),
2530                        });
2531                    }
2532
2533                    offset = hunk_base_range.end;
2534                }
2535
2536                // Add remaining buffer text
2537                let len = text.len();
2538                text.extend(buffer.text_for_range(offset..buffer_range.end));
2539                text.push('\n');
2540                regions.push(ReferenceRegion {
2541                    buffer_id: Some(buffer_id),
2542                    range: len..text.len(),
2543                    buffer_range: Some((offset..buffer_range.end).to_point(&buffer)),
2544                    status: None,
2545                    excerpt_id: Some(excerpt.id),
2546                });
2547            } else {
2548                let diff = self.diffs.get(&buffer_id).unwrap().read(cx).snapshot(cx);
2549                let base_buffer = diff.base_text();
2550
2551                let mut offset = buffer_range.start;
2552                let hunks = diff
2553                    .hunks_intersecting_range(excerpt.range.clone(), buffer)
2554                    .peekable();
2555
2556                for hunk in hunks {
2557                    // Ignore hunks that are outside the excerpt range.
2558                    let mut hunk_range = hunk.buffer_range.to_offset(buffer);
2559
2560                    hunk_range.end = hunk_range.end.min(buffer_range.end);
2561                    if hunk_range.start > buffer_range.end || hunk_range.start < buffer_range.start
2562                    {
2563                        log::trace!("skipping hunk outside excerpt range");
2564                        continue;
2565                    }
2566
2567                    if !excerpt.expanded_diff_hunks.iter().any(|expanded_anchor| {
2568                        expanded_anchor.to_offset(buffer).max(buffer_range.start)
2569                            == hunk_range.start.max(buffer_range.start)
2570                    }) {
2571                        log::trace!("skipping a hunk that's not marked as expanded");
2572                        continue;
2573                    }
2574
2575                    if !hunk.buffer_range.start.is_valid(buffer) {
2576                        log::trace!("skipping hunk with deleted start: {:?}", hunk.range);
2577                        continue;
2578                    }
2579
2580                    if hunk_range.start >= offset {
2581                        // Add the buffer text before the hunk
2582                        let len = text.len();
2583                        text.extend(buffer.text_for_range(offset..hunk_range.start));
2584                        if text.len() > len {
2585                            regions.push(ReferenceRegion {
2586                                buffer_id: Some(buffer_id),
2587                                range: len..text.len(),
2588                                buffer_range: Some((offset..hunk_range.start).to_point(&buffer)),
2589                                status: None,
2590                                excerpt_id: Some(excerpt.id),
2591                            });
2592                        }
2593
2594                        // Add the deleted text for the hunk.
2595                        if !hunk.diff_base_byte_range.is_empty() {
2596                            let mut base_text = base_buffer
2597                                .text_for_range(hunk.diff_base_byte_range.clone())
2598                                .collect::<String>();
2599                            if !base_text.ends_with('\n') {
2600                                base_text.push('\n');
2601                            }
2602                            let len = text.len();
2603                            text.push_str(&base_text);
2604                            regions.push(ReferenceRegion {
2605                                buffer_id: Some(base_buffer.remote_id()),
2606                                range: len..text.len(),
2607                                buffer_range: Some(
2608                                    hunk.diff_base_byte_range.to_point(&base_buffer),
2609                                ),
2610                                status: Some(DiffHunkStatus::deleted(hunk.secondary_status)),
2611                                excerpt_id: Some(excerpt.id),
2612                            });
2613                        }
2614
2615                        offset = hunk_range.start;
2616                    }
2617
2618                    // Add the inserted text for the hunk.
2619                    if hunk_range.end > offset {
2620                        let len = text.len();
2621                        text.extend(buffer.text_for_range(offset..hunk_range.end));
2622                        let range = len..text.len();
2623                        let region = ReferenceRegion {
2624                            buffer_id: Some(buffer_id),
2625                            range,
2626                            buffer_range: Some((offset..hunk_range.end).to_point(&buffer)),
2627                            status: Some(DiffHunkStatus::added(hunk.secondary_status)),
2628                            excerpt_id: Some(excerpt.id),
2629                        };
2630                        offset = hunk_range.end;
2631                        regions.push(region);
2632                    }
2633                }
2634
2635                // Add the buffer text for the rest of the excerpt.
2636                let len = text.len();
2637                text.extend(buffer.text_for_range(offset..buffer_range.end));
2638                text.push('\n');
2639                regions.push(ReferenceRegion {
2640                    buffer_id: Some(buffer_id),
2641                    range: len..text.len(),
2642                    buffer_range: Some((offset..buffer_range.end).to_point(&buffer)),
2643                    status: None,
2644                    excerpt_id: Some(excerpt.id),
2645                });
2646            }
2647        }
2648
2649        // Remove final trailing newline.
2650        if self.excerpts.is_empty() {
2651            regions.push(ReferenceRegion {
2652                buffer_id: None,
2653                range: 0..1,
2654                buffer_range: Some(Point::new(0, 0)..Point::new(0, 1)),
2655                status: None,
2656                excerpt_id: None,
2657            });
2658        } else {
2659            text.pop();
2660        }
2661
2662        // Retrieve the row info using the region that contains
2663        // the start of each multi-buffer line.
2664        let mut ix = 0;
2665        let row_infos = text
2666            .split('\n')
2667            .map(|line| {
2668                let row_info = regions
2669                    .iter()
2670                    .position(|region| region.range.contains(&ix))
2671                    .map_or(RowInfo::default(), |region_ix| {
2672                        let region = &regions[region_ix];
2673                        let buffer_row = region.buffer_range.as_ref().map(|buffer_range| {
2674                            buffer_range.start.row
2675                                + text[region.range.start..ix].matches('\n').count() as u32
2676                        });
2677                        let main_buffer = self
2678                            .excerpts
2679                            .iter()
2680                            .find(|e| e.id == region.excerpt_id.unwrap())
2681                            .map(|e| e.buffer.clone());
2682                        let is_excerpt_start = region_ix == 0
2683                            || &regions[region_ix - 1].excerpt_id != &region.excerpt_id
2684                            || regions[region_ix - 1].range.is_empty();
2685                        let mut is_excerpt_end = region_ix == regions.len() - 1
2686                            || &regions[region_ix + 1].excerpt_id != &region.excerpt_id;
2687                        let is_start = !text[region.range.start..ix].contains('\n');
2688                        let mut is_end = if region.range.end > text.len() {
2689                            !text[ix..].contains('\n')
2690                        } else {
2691                            text[ix..region.range.end.min(text.len())]
2692                                .matches('\n')
2693                                .count()
2694                                == 1
2695                        };
2696                        if region_ix < regions.len() - 1
2697                            && !text[ix..].contains("\n")
2698                            && (region.status == Some(DiffHunkStatus::added_none())
2699                                || region.status.is_some_and(|s| s.is_deleted()))
2700                            && regions[region_ix + 1].excerpt_id == region.excerpt_id
2701                            && regions[region_ix + 1].range.start == text.len()
2702                        {
2703                            is_end = true;
2704                            is_excerpt_end = true;
2705                        }
2706                        let multibuffer_row =
2707                            MultiBufferRow(text[..ix].matches('\n').count() as u32);
2708                        let mut expand_direction = None;
2709                        if let Some(buffer) = &main_buffer {
2710                            let buffer_row = buffer_row.unwrap();
2711                            let needs_expand_up = is_excerpt_start && is_start && buffer_row > 0;
2712                            let needs_expand_down = is_excerpt_end
2713                                && is_end
2714                                && buffer.read(cx).max_point().row > buffer_row;
2715                            expand_direction = if needs_expand_up && needs_expand_down {
2716                                Some(ExpandExcerptDirection::UpAndDown)
2717                            } else if needs_expand_up {
2718                                Some(ExpandExcerptDirection::Up)
2719                            } else if needs_expand_down {
2720                                Some(ExpandExcerptDirection::Down)
2721                            } else {
2722                                None
2723                            };
2724                        }
2725                        RowInfo {
2726                            buffer_id: region.buffer_id,
2727                            diff_status: region.status,
2728                            buffer_row,
2729                            wrapped_buffer_row: None,
2730
2731                            multibuffer_row: Some(multibuffer_row),
2732                            expand_info: expand_direction.zip(region.excerpt_id).map(
2733                                |(direction, excerpt_id)| ExpandInfo {
2734                                    direction,
2735                                    excerpt_id,
2736                                },
2737                            ),
2738                        }
2739                    });
2740                ix += line.len() + 1;
2741                row_info
2742            })
2743            .collect();
2744
2745        (text, row_infos, excerpt_boundary_rows)
2746    }
2747
2748    fn diffs_updated(&mut self, cx: &App) {
2749        for excerpt in &mut self.excerpts {
2750            let buffer = excerpt.buffer.read(cx).snapshot();
2751            let buffer_id = buffer.remote_id();
2752
2753            // Skip inverted diff excerpts - hunks are always expanded
2754            if self.inverted_diffs.contains_key(&buffer_id) {
2755                continue;
2756            }
2757
2758            let excerpt_range = excerpt.range.to_offset(&buffer);
2759            let Some(diff) = self.diffs.get(&buffer_id) else {
2760                continue;
2761            };
2762            let diff = diff.read(cx).snapshot(cx);
2763            let mut hunks = diff.hunks_in_row_range(0..u32::MAX, &buffer).peekable();
2764            excerpt.expanded_diff_hunks.retain(|hunk_anchor| {
2765                if !hunk_anchor.is_valid(&buffer) {
2766                    return false;
2767                }
2768                while let Some(hunk) = hunks.peek() {
2769                    match hunk.buffer_range.start.cmp(hunk_anchor, &buffer) {
2770                        cmp::Ordering::Less => {
2771                            hunks.next();
2772                        }
2773                        cmp::Ordering::Equal => {
2774                            let hunk_range = hunk.buffer_range.to_offset(&buffer);
2775                            return hunk_range.end >= excerpt_range.start
2776                                && hunk_range.start <= excerpt_range.end;
2777                        }
2778                        cmp::Ordering::Greater => break,
2779                    }
2780                }
2781                false
2782            });
2783        }
2784    }
2785
2786    fn add_diff(&mut self, diff: Entity<BufferDiff>, cx: &mut App) {
2787        let buffer_id = diff.read(cx).buffer_id;
2788        self.diffs.insert(buffer_id, diff);
2789    }
2790
2791    fn add_inverted_diff(&mut self, diff: Entity<BufferDiff>, cx: &App) {
2792        let base_text_buffer_id = diff.read(cx).base_text(cx).remote_id();
2793        self.inverted_diffs.insert(base_text_buffer_id, diff);
2794    }
2795}
2796
2797#[gpui::test(iterations = 100)]
2798async fn test_random_set_ranges(cx: &mut TestAppContext, mut rng: StdRng) {
2799    let base_text = "a\n".repeat(100);
2800    let buf = cx.update(|cx| cx.new(|cx| Buffer::local(base_text, cx)));
2801    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2802
2803    let operations = env::var("OPERATIONS")
2804        .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2805        .unwrap_or(10);
2806
2807    fn row_ranges(ranges: &Vec<Range<Point>>) -> Vec<Range<u32>> {
2808        ranges
2809            .iter()
2810            .map(|range| range.start.row..range.end.row)
2811            .collect()
2812    }
2813
2814    for _ in 0..operations {
2815        let snapshot = buf.update(cx, |buf, _| buf.snapshot());
2816        let num_ranges = rng.random_range(0..=10);
2817        let max_row = snapshot.max_point().row;
2818        let mut ranges = (0..num_ranges)
2819            .map(|_| {
2820                let start = rng.random_range(0..max_row);
2821                let end = rng.random_range(start + 1..max_row + 1);
2822                Point::row_range(start..end)
2823            })
2824            .collect::<Vec<_>>();
2825        ranges.sort_by_key(|range| range.start);
2826        log::info!("Setting ranges: {:?}", row_ranges(&ranges));
2827        let (created, _) = multibuffer.update(cx, |multibuffer, cx| {
2828            multibuffer.set_excerpts_for_path(
2829                PathKey::for_buffer(&buf, cx),
2830                buf.clone(),
2831                ranges.clone(),
2832                2,
2833                cx,
2834            )
2835        });
2836
2837        assert_eq!(created.len(), ranges.len());
2838
2839        let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2840        let mut last_end = None;
2841        let mut seen_ranges = Vec::default();
2842
2843        for (_, buf, range) in snapshot.excerpts() {
2844            let start = range.context.start.to_point(buf);
2845            let end = range.context.end.to_point(buf);
2846            seen_ranges.push(start..end);
2847
2848            if let Some(last_end) = last_end.take() {
2849                assert!(
2850                    start > last_end,
2851                    "multibuffer has out-of-order ranges: {:?}; {:?} <= {:?}",
2852                    row_ranges(&seen_ranges),
2853                    start,
2854                    last_end
2855                )
2856            }
2857
2858            ranges.retain(|range| range.start < start || range.end > end);
2859
2860            last_end = Some(end)
2861        }
2862
2863        assert!(
2864            ranges.is_empty(),
2865            "multibuffer {:?} did not include all ranges: {:?}",
2866            row_ranges(&seen_ranges),
2867            row_ranges(&ranges)
2868        );
2869    }
2870}
2871
2872#[gpui::test(iterations = 100)]
2873async fn test_random_multibuffer(cx: &mut TestAppContext, mut rng: StdRng) {
2874    let operations = env::var("OPERATIONS")
2875        .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2876        .unwrap_or(10);
2877    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2878    let mut buffers: Vec<Entity<Buffer>> = Vec::new();
2879    let mut base_texts: HashMap<BufferId, String> = HashMap::default();
2880    let mut reference = ReferenceMultibuffer::default();
2881    let mut anchors = Vec::new();
2882    let mut old_versions = Vec::new();
2883    let mut needs_diff_calculation = false;
2884    let mut inverted_diff_main_buffers: HashMap<BufferId, Entity<BufferDiff>> = HashMap::default();
2885    for _ in 0..operations {
2886        match rng.random_range(0..100) {
2887            0..=14 if !buffers.is_empty() => {
2888                let buffer = buffers.choose(&mut rng).unwrap();
2889                buffer.update(cx, |buf, cx| {
2890                    let edit_count = rng.random_range(1..5);
2891                    buf.randomly_edit(&mut rng, edit_count, cx);
2892                    log::info!("buffer text:\n{}", buf.text());
2893                    needs_diff_calculation = true;
2894                });
2895                cx.update(|cx| reference.diffs_updated(cx));
2896            }
2897            15..=19 if !reference.excerpts.is_empty() => {
2898                multibuffer.update(cx, |multibuffer, cx| {
2899                    let ids = multibuffer.excerpt_ids();
2900                    let mut excerpts = HashSet::default();
2901                    for _ in 0..rng.random_range(0..ids.len()) {
2902                        excerpts.extend(ids.choose(&mut rng).copied());
2903                    }
2904
2905                    let line_count = rng.random_range(0..5);
2906
2907                    let excerpt_ixs = excerpts
2908                        .iter()
2909                        .map(|id| reference.excerpts.iter().position(|e| e.id == *id).unwrap())
2910                        .collect::<Vec<_>>();
2911                    log::info!("Expanding excerpts {excerpt_ixs:?} by {line_count} lines");
2912                    multibuffer.expand_excerpts(
2913                        excerpts.iter().cloned(),
2914                        line_count,
2915                        ExpandExcerptDirection::UpAndDown,
2916                        cx,
2917                    );
2918
2919                    reference.expand_excerpts(&excerpts, line_count, cx);
2920                });
2921            }
2922            20..=29 if !reference.excerpts.is_empty() => {
2923                let mut ids_to_remove = vec![];
2924                for _ in 0..rng.random_range(1..=3) {
2925                    let Some(excerpt) = reference.excerpts.choose(&mut rng) else {
2926                        break;
2927                    };
2928                    let id = excerpt.id;
2929                    cx.update(|cx| reference.remove_excerpt(id, cx));
2930                    ids_to_remove.push(id);
2931                }
2932                let snapshot =
2933                    multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2934                ids_to_remove.sort_unstable_by(|a, b| a.cmp(b, &snapshot));
2935                drop(snapshot);
2936                multibuffer.update(cx, |multibuffer, cx| {
2937                    multibuffer.remove_excerpts(ids_to_remove, cx)
2938                });
2939            }
2940            30..=39 if !reference.excerpts.is_empty() => {
2941                let multibuffer =
2942                    multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2943                let offset = multibuffer.clip_offset(
2944                    MultiBufferOffset(rng.random_range(0..=multibuffer.len().0)),
2945                    Bias::Left,
2946                );
2947                let bias = if rng.random() {
2948                    Bias::Left
2949                } else {
2950                    Bias::Right
2951                };
2952                log::info!("Creating anchor at {} with bias {:?}", offset.0, bias);
2953                anchors.push(multibuffer.anchor_at(offset, bias));
2954                anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
2955            }
2956            40..=44 if !anchors.is_empty() => {
2957                let multibuffer =
2958                    multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2959                let prev_len = anchors.len();
2960                anchors = multibuffer
2961                    .refresh_anchors(&anchors)
2962                    .into_iter()
2963                    .map(|a| a.1)
2964                    .collect();
2965
2966                // Ensure the newly-refreshed anchors point to a valid excerpt and don't
2967                // overshoot its boundaries.
2968                assert_eq!(anchors.len(), prev_len);
2969                for anchor in &anchors {
2970                    if anchor.excerpt_id == ExcerptId::min()
2971                        || anchor.excerpt_id == ExcerptId::max()
2972                    {
2973                        continue;
2974                    }
2975
2976                    let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
2977                    assert_eq!(excerpt.id, anchor.excerpt_id);
2978                    assert!(excerpt.contains(anchor));
2979                }
2980            }
2981            45..=55 if !reference.excerpts.is_empty() => {
2982                multibuffer.update(cx, |multibuffer, cx| {
2983                    let snapshot = multibuffer.snapshot(cx);
2984                    let excerpt_ix = rng.random_range(0..reference.excerpts.len());
2985                    let excerpt = &reference.excerpts[excerpt_ix];
2986
2987                    // Skip inverted excerpts - hunks can't be collapsed
2988                    let buffer_id = excerpt.buffer.read(cx).remote_id();
2989                    if reference.inverted_diffs.contains_key(&buffer_id) {
2990                        return;
2991                    }
2992
2993                    let start = excerpt.range.start;
2994                    let end = excerpt.range.end;
2995                    let range = snapshot.anchor_in_excerpt(excerpt.id, start).unwrap()
2996                        ..snapshot.anchor_in_excerpt(excerpt.id, end).unwrap();
2997
2998                    log::info!(
2999                        "expanding diff hunks in range {:?} (excerpt id {:?}, index {excerpt_ix:?}, buffer id {:?})",
3000                        range.to_offset(&snapshot),
3001                        excerpt.id,
3002                        buffer_id,
3003                    );
3004                    reference.expand_diff_hunks(excerpt.id, start..end, cx);
3005                    multibuffer.expand_diff_hunks(vec![range], cx);
3006                });
3007            }
3008            56..=85 if needs_diff_calculation => {
3009                multibuffer.update(cx, |multibuffer, cx| {
3010                    for buffer in multibuffer.all_buffers() {
3011                        let snapshot = buffer.read(cx).snapshot();
3012                        let buffer_id = snapshot.remote_id();
3013
3014                        if let Some(diff) = multibuffer.diff_for(buffer_id) {
3015                            diff.update(cx, |diff, cx| {
3016                                log::info!("recalculating diff for buffer {:?}", buffer_id,);
3017                                diff.recalculate_diff_sync(&snapshot.text, cx);
3018                            });
3019                        }
3020
3021                        if let Some(inverted_diff) = inverted_diff_main_buffers.get(&buffer_id) {
3022                            inverted_diff.update(cx, |diff, cx| {
3023                                log::info!(
3024                                    "recalculating inverted diff for main buffer {:?}",
3025                                    buffer_id,
3026                                );
3027                                diff.recalculate_diff_sync(&snapshot.text, cx);
3028                            });
3029                        }
3030                    }
3031                    reference.diffs_updated(cx);
3032                    needs_diff_calculation = false;
3033                });
3034            }
3035            _ => {
3036                // Decide if we're creating a new buffer or reusing an existing one
3037                let create_new_buffer = buffers.is_empty() || rng.random_bool(0.4);
3038
3039                let prev_excerpt_ix = rng.random_range(0..=reference.excerpts.len());
3040                let prev_excerpt_id = reference
3041                    .excerpts
3042                    .get(prev_excerpt_ix)
3043                    .map_or(ExcerptId::max(), |e| e.id);
3044                let excerpt_ix = (prev_excerpt_ix + 1).min(reference.excerpts.len());
3045
3046                let (excerpt_buffer, diff, inverted_main_buffer) = if create_new_buffer {
3047                    let create_inverted = rng.random_bool(0.3);
3048
3049                    if create_inverted {
3050                        let mut main_buffer_text = util::RandomCharIter::new(&mut rng)
3051                            .take(256)
3052                            .collect::<String>();
3053                        let main_buffer = cx.new(|cx| Buffer::local(main_buffer_text.clone(), cx));
3054                        text::LineEnding::normalize(&mut main_buffer_text);
3055                        let main_buffer_id =
3056                            main_buffer.read_with(cx, |buffer, _| buffer.remote_id());
3057                        base_texts.insert(main_buffer_id, main_buffer_text.clone());
3058                        buffers.push(main_buffer.clone());
3059
3060                        let diff = cx.new(|cx| {
3061                            BufferDiff::new_with_base_text(
3062                                &main_buffer_text,
3063                                &main_buffer.read(cx).text_snapshot(),
3064                                cx,
3065                            )
3066                        });
3067
3068                        let base_text_buffer =
3069                            diff.read_with(cx, |diff, _| diff.base_text_buffer());
3070
3071                        // Track for recalculation when main buffer is edited
3072                        inverted_diff_main_buffers.insert(main_buffer_id, diff.clone());
3073
3074                        (base_text_buffer, diff, Some(main_buffer))
3075                    } else {
3076                        let mut base_text = util::RandomCharIter::new(&mut rng)
3077                            .take(256)
3078                            .collect::<String>();
3079
3080                        let buffer_handle = cx.new(|cx| Buffer::local(base_text.clone(), cx));
3081                        text::LineEnding::normalize(&mut base_text);
3082                        let buffer_id = buffer_handle.read_with(cx, |buffer, _| buffer.remote_id());
3083                        base_texts.insert(buffer_id, base_text.clone());
3084                        buffers.push(buffer_handle.clone());
3085
3086                        let diff = cx.new(|cx| {
3087                            BufferDiff::new_with_base_text(
3088                                &base_text,
3089                                &buffer_handle.read(cx).text_snapshot(),
3090                                cx,
3091                            )
3092                        });
3093
3094                        (buffer_handle, diff, None)
3095                    }
3096                } else {
3097                    // Reuse an existing buffer
3098                    let buffer_handle = buffers.choose(&mut rng).unwrap().clone();
3099                    let buffer_id = buffer_handle.read_with(cx, |buffer, _| buffer.remote_id());
3100
3101                    if let Some(diff) = inverted_diff_main_buffers.get(&buffer_id) {
3102                        let base_text_buffer =
3103                            diff.read_with(cx, |diff, _| diff.base_text_buffer());
3104                        (base_text_buffer, diff.clone(), Some(buffer_handle))
3105                    } else {
3106                        // Get existing diff or create new one for regular buffer
3107                        let diff = multibuffer
3108                            .read_with(cx, |mb, _| mb.diff_for(buffer_id))
3109                            .unwrap_or_else(|| {
3110                                let base_text = base_texts.get(&buffer_id).unwrap();
3111                                cx.new(|cx| {
3112                                    BufferDiff::new_with_base_text(
3113                                        base_text,
3114                                        &buffer_handle.read(cx).text_snapshot(),
3115                                        cx,
3116                                    )
3117                                })
3118                            });
3119                        (buffer_handle, diff, None)
3120                    }
3121                };
3122
3123                let (range, anchor_range) = excerpt_buffer.read_with(cx, |buffer, _| {
3124                    let end_row = rng.random_range(0..=buffer.max_point().row);
3125                    let start_row = rng.random_range(0..=end_row);
3126                    let end_ix = buffer.point_to_offset(Point::new(end_row, 0));
3127                    let start_ix = buffer.point_to_offset(Point::new(start_row, 0));
3128                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
3129
3130                    log::info!(
3131                        "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
3132                        excerpt_ix,
3133                        reference.excerpts.len(),
3134                        buffer.remote_id(),
3135                        buffer.text(),
3136                        start_ix..end_ix,
3137                        &buffer.text()[start_ix..end_ix]
3138                    );
3139
3140                    (start_ix..end_ix, anchor_range)
3141                });
3142
3143                let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
3144                    multibuffer
3145                        .insert_excerpts_after(
3146                            prev_excerpt_id,
3147                            excerpt_buffer.clone(),
3148                            [ExcerptRange::new(range.clone())],
3149                            cx,
3150                        )
3151                        .pop()
3152                        .unwrap()
3153                });
3154
3155                reference.insert_excerpt_after(
3156                    prev_excerpt_id,
3157                    excerpt_id,
3158                    (excerpt_buffer.clone(), anchor_range),
3159                );
3160
3161                let excerpt_buffer_id =
3162                    excerpt_buffer.read_with(cx, |buffer, _| buffer.remote_id());
3163                multibuffer.update(cx, |multibuffer, cx| {
3164                    if multibuffer.diff_for(excerpt_buffer_id).is_none() {
3165                        if inverted_main_buffer.is_some() {
3166                            reference.add_inverted_diff(diff.clone(), cx);
3167                            multibuffer.add_inverted_diff(diff, cx);
3168                        } else {
3169                            reference.add_diff(diff.clone(), cx);
3170                            multibuffer.add_diff(diff, cx);
3171                        }
3172                    }
3173                });
3174            }
3175        }
3176
3177        if rng.random_bool(0.3) {
3178            multibuffer.update(cx, |multibuffer, cx| {
3179                old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
3180            })
3181        }
3182
3183        multibuffer.read_with(cx, |multibuffer, cx| {
3184            check_multibuffer(multibuffer, &reference, &anchors, cx, &mut rng);
3185        });
3186    }
3187    let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
3188    for (old_snapshot, subscription) in old_versions {
3189        check_multibuffer_edits(&snapshot, &old_snapshot, subscription);
3190    }
3191}
3192
3193fn check_multibuffer(
3194    multibuffer: &MultiBuffer,
3195    reference: &ReferenceMultibuffer,
3196    anchors: &[Anchor],
3197    cx: &App,
3198    rng: &mut StdRng,
3199) {
3200    let snapshot = multibuffer.snapshot(cx);
3201    let actual_text = snapshot.text();
3202    let actual_boundary_rows = snapshot
3203        .excerpt_boundaries_in_range(MultiBufferOffset(0)..)
3204        .map(|b| b.row)
3205        .collect::<HashSet<_>>();
3206    let actual_row_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
3207
3208    let (expected_text, expected_row_infos, expected_boundary_rows) =
3209        reference.expected_content(cx);
3210
3211    let has_diff = actual_row_infos
3212        .iter()
3213        .any(|info| info.diff_status.is_some())
3214        || expected_row_infos
3215            .iter()
3216            .any(|info| info.diff_status.is_some());
3217    let actual_diff = format_diff(
3218        &actual_text,
3219        &actual_row_infos,
3220        &actual_boundary_rows,
3221        Some(has_diff),
3222    );
3223    let expected_diff = format_diff(
3224        &expected_text,
3225        &expected_row_infos,
3226        &expected_boundary_rows,
3227        Some(has_diff),
3228    );
3229
3230    log::info!("Multibuffer content:\n{}", actual_diff);
3231
3232    assert_eq!(
3233        actual_row_infos.len(),
3234        actual_text.split('\n').count(),
3235        "line count: {}",
3236        actual_text.split('\n').count()
3237    );
3238    pretty_assertions::assert_eq!(actual_diff, expected_diff);
3239    pretty_assertions::assert_eq!(actual_text, expected_text);
3240    pretty_assertions::assert_eq!(actual_row_infos, expected_row_infos);
3241
3242    for _ in 0..5 {
3243        let start_row = rng.random_range(0..=expected_row_infos.len());
3244        assert_eq!(
3245            snapshot
3246                .row_infos(MultiBufferRow(start_row as u32))
3247                .collect::<Vec<_>>(),
3248            &expected_row_infos[start_row..],
3249            "buffer_rows({})",
3250            start_row
3251        );
3252    }
3253
3254    assert_eq!(
3255        snapshot.widest_line_number(),
3256        expected_row_infos
3257            .into_iter()
3258            .filter_map(|info| {
3259                // For inverted diffs, deleted rows are visible and should be counted.
3260                // Only filter out deleted rows that are NOT from inverted diffs.
3261                let is_inverted_diff = info
3262                    .buffer_id
3263                    .is_some_and(|id| reference.inverted_diffs.contains_key(&id));
3264                if info.diff_status.is_some_and(|status| status.is_deleted()) && !is_inverted_diff {
3265                    None
3266                } else {
3267                    info.buffer_row
3268                }
3269            })
3270            .max()
3271            .unwrap()
3272            + 1
3273    );
3274    let reference_ranges = reference
3275        .excerpts
3276        .iter()
3277        .map(|excerpt| {
3278            (
3279                excerpt.id,
3280                excerpt.range.to_offset(&excerpt.buffer.read(cx).snapshot()),
3281            )
3282        })
3283        .collect::<HashMap<_, _>>();
3284    for i in 0..snapshot.len().0 {
3285        let excerpt = snapshot
3286            .excerpt_containing(MultiBufferOffset(i)..MultiBufferOffset(i))
3287            .unwrap();
3288        assert_eq!(
3289            excerpt.buffer_range().start.0..excerpt.buffer_range().end.0,
3290            reference_ranges[&excerpt.id()]
3291        );
3292    }
3293
3294    assert_consistent_line_numbers(&snapshot);
3295    assert_position_translation(&snapshot);
3296
3297    for (row, line) in expected_text.split('\n').enumerate() {
3298        assert_eq!(
3299            snapshot.line_len(MultiBufferRow(row as u32)),
3300            line.len() as u32,
3301            "line_len({}).",
3302            row
3303        );
3304    }
3305
3306    let text_rope = Rope::from(expected_text.as_str());
3307    for _ in 0..10 {
3308        let end_ix = text_rope.clip_offset(rng.random_range(0..=text_rope.len()), Bias::Right);
3309        let start_ix = text_rope.clip_offset(rng.random_range(0..=end_ix), Bias::Left);
3310
3311        let text_for_range = snapshot
3312            .text_for_range(MultiBufferOffset(start_ix)..MultiBufferOffset(end_ix))
3313            .collect::<String>();
3314        assert_eq!(
3315            text_for_range,
3316            &expected_text[start_ix..end_ix],
3317            "incorrect text for range {:?}",
3318            start_ix..end_ix
3319        );
3320
3321        let expected_summary =
3322            MBTextSummary::from(TextSummary::from(&expected_text[start_ix..end_ix]));
3323        assert_eq!(
3324            snapshot.text_summary_for_range::<MBTextSummary, _>(
3325                MultiBufferOffset(start_ix)..MultiBufferOffset(end_ix)
3326            ),
3327            expected_summary,
3328            "incorrect summary for range {:?}",
3329            start_ix..end_ix
3330        );
3331    }
3332
3333    // Anchor resolution
3334    let summaries = snapshot.summaries_for_anchors::<MultiBufferOffset, _>(anchors);
3335    assert_eq!(anchors.len(), summaries.len());
3336    for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
3337        assert!(resolved_offset <= snapshot.len());
3338        assert_eq!(
3339            snapshot.summary_for_anchor::<MultiBufferOffset>(anchor),
3340            resolved_offset,
3341            "anchor: {:?}",
3342            anchor
3343        );
3344    }
3345
3346    for _ in 0..10 {
3347        let end_ix = text_rope.clip_offset(rng.random_range(0..=text_rope.len()), Bias::Right);
3348        assert_eq!(
3349            snapshot
3350                .reversed_chars_at(MultiBufferOffset(end_ix))
3351                .collect::<String>(),
3352            expected_text[..end_ix].chars().rev().collect::<String>(),
3353        );
3354    }
3355
3356    for _ in 0..10 {
3357        let end_ix = rng.random_range(0..=text_rope.len());
3358        let end_ix = text_rope.floor_char_boundary(end_ix);
3359        let start_ix = rng.random_range(0..=end_ix);
3360        let start_ix = text_rope.floor_char_boundary(start_ix);
3361        assert_eq!(
3362            snapshot
3363                .bytes_in_range(MultiBufferOffset(start_ix)..MultiBufferOffset(end_ix))
3364                .flatten()
3365                .copied()
3366                .collect::<Vec<_>>(),
3367            expected_text.as_bytes()[start_ix..end_ix].to_vec(),
3368            "bytes_in_range({:?})",
3369            start_ix..end_ix,
3370        );
3371    }
3372}
3373
3374fn check_multibuffer_edits(
3375    snapshot: &MultiBufferSnapshot,
3376    old_snapshot: &MultiBufferSnapshot,
3377    subscription: Subscription<MultiBufferOffset>,
3378) {
3379    let edits = subscription.consume().into_inner();
3380
3381    log::info!(
3382        "applying subscription edits to old text: {:?}: {:#?}",
3383        old_snapshot.text(),
3384        edits,
3385    );
3386
3387    let mut text = old_snapshot.text();
3388    for edit in edits {
3389        let new_text: String = snapshot
3390            .text_for_range(edit.new.start..edit.new.end)
3391            .collect();
3392        text.replace_range(
3393            (edit.new.start.0..edit.new.start.0 + (edit.old.end.0 - edit.old.start.0)).clone(),
3394            &new_text,
3395        );
3396        pretty_assertions::assert_eq!(
3397            &text[0..edit.new.end.0],
3398            snapshot
3399                .text_for_range(MultiBufferOffset(0)..edit.new.end)
3400                .collect::<String>()
3401        );
3402    }
3403    pretty_assertions::assert_eq!(text, snapshot.text());
3404}
3405
3406#[gpui::test]
3407fn test_history(cx: &mut App) {
3408    let test_settings = SettingsStore::test(cx);
3409    cx.set_global(test_settings);
3410
3411    let group_interval: Duration = Duration::from_millis(1);
3412    let buffer_1 = cx.new(|cx| {
3413        let mut buf = Buffer::local("1234", cx);
3414        buf.set_group_interval(group_interval);
3415        buf
3416    });
3417    let buffer_2 = cx.new(|cx| {
3418        let mut buf = Buffer::local("5678", cx);
3419        buf.set_group_interval(group_interval);
3420        buf
3421    });
3422    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
3423    multibuffer.update(cx, |this, _| {
3424        this.set_group_interval(group_interval);
3425    });
3426    multibuffer.update(cx, |multibuffer, cx| {
3427        multibuffer.push_excerpts(
3428            buffer_1.clone(),
3429            [ExcerptRange::new(0..buffer_1.read(cx).len())],
3430            cx,
3431        );
3432        multibuffer.push_excerpts(
3433            buffer_2.clone(),
3434            [ExcerptRange::new(0..buffer_2.read(cx).len())],
3435            cx,
3436        );
3437    });
3438
3439    let mut now = Instant::now();
3440
3441    multibuffer.update(cx, |multibuffer, cx| {
3442        let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
3443        multibuffer.edit(
3444            [
3445                (Point::new(0, 0)..Point::new(0, 0), "A"),
3446                (Point::new(1, 0)..Point::new(1, 0), "A"),
3447            ],
3448            None,
3449            cx,
3450        );
3451        multibuffer.edit(
3452            [
3453                (Point::new(0, 1)..Point::new(0, 1), "B"),
3454                (Point::new(1, 1)..Point::new(1, 1), "B"),
3455            ],
3456            None,
3457            cx,
3458        );
3459        multibuffer.end_transaction_at(now, cx);
3460        assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3461
3462        // Verify edited ranges for transaction 1
3463        assert_eq!(
3464            multibuffer.edited_ranges_for_transaction(transaction_1, cx),
3465            &[
3466                Point::new(0, 0)..Point::new(0, 2),
3467                Point::new(1, 0)..Point::new(1, 2)
3468            ]
3469        );
3470
3471        // Edit buffer 1 through the multibuffer
3472        now += 2 * group_interval;
3473        multibuffer.start_transaction_at(now, cx);
3474        multibuffer.edit(
3475            [(MultiBufferOffset(2)..MultiBufferOffset(2), "C")],
3476            None,
3477            cx,
3478        );
3479        multibuffer.end_transaction_at(now, cx);
3480        assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3481
3482        // Edit buffer 1 independently
3483        buffer_1.update(cx, |buffer_1, cx| {
3484            buffer_1.start_transaction_at(now);
3485            buffer_1.edit([(3..3, "D")], None, cx);
3486            buffer_1.end_transaction_at(now, cx);
3487
3488            now += 2 * group_interval;
3489            buffer_1.start_transaction_at(now);
3490            buffer_1.edit([(4..4, "E")], None, cx);
3491            buffer_1.end_transaction_at(now, cx);
3492        });
3493        assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
3494
3495        // An undo in the multibuffer undoes the multibuffer transaction
3496        // and also any individual buffer edits that have occurred since
3497        // that transaction.
3498        multibuffer.undo(cx);
3499        assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3500
3501        multibuffer.undo(cx);
3502        assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3503
3504        multibuffer.redo(cx);
3505        assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3506
3507        multibuffer.redo(cx);
3508        assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
3509
3510        // Undo buffer 2 independently.
3511        buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
3512        assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
3513
3514        // An undo in the multibuffer undoes the components of the
3515        // the last multibuffer transaction that are not already undone.
3516        multibuffer.undo(cx);
3517        assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
3518
3519        multibuffer.undo(cx);
3520        assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3521
3522        multibuffer.redo(cx);
3523        assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3524
3525        buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
3526        assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
3527
3528        // Redo stack gets cleared after an edit.
3529        now += 2 * group_interval;
3530        multibuffer.start_transaction_at(now, cx);
3531        multibuffer.edit(
3532            [(MultiBufferOffset(0)..MultiBufferOffset(0), "X")],
3533            None,
3534            cx,
3535        );
3536        multibuffer.end_transaction_at(now, cx);
3537        assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3538        multibuffer.redo(cx);
3539        assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3540        multibuffer.undo(cx);
3541        assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
3542        multibuffer.undo(cx);
3543        assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3544
3545        // Transactions can be grouped manually.
3546        multibuffer.redo(cx);
3547        multibuffer.redo(cx);
3548        assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3549        multibuffer.group_until_transaction(transaction_1, cx);
3550        multibuffer.undo(cx);
3551        assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3552        multibuffer.redo(cx);
3553        assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3554    });
3555}
3556
3557#[gpui::test]
3558async fn test_enclosing_indent(cx: &mut TestAppContext) {
3559    async fn enclosing_indent(
3560        text: &str,
3561        buffer_row: u32,
3562        cx: &mut TestAppContext,
3563    ) -> Option<(Range<u32>, LineIndent)> {
3564        let buffer = cx.update(|cx| MultiBuffer::build_simple(text, cx));
3565        let snapshot = cx.read(|cx| buffer.read(cx).snapshot(cx));
3566        let (range, indent) = snapshot
3567            .enclosing_indent(MultiBufferRow(buffer_row))
3568            .await?;
3569        Some((range.start.0..range.end.0, indent))
3570    }
3571
3572    assert_eq!(
3573        enclosing_indent(
3574            indoc!(
3575                "
3576                fn b() {
3577                    if c {
3578                        let d = 2;
3579                    }
3580                }
3581                "
3582            ),
3583            1,
3584            cx,
3585        )
3586        .await,
3587        Some((
3588            1..2,
3589            LineIndent {
3590                tabs: 0,
3591                spaces: 4,
3592                line_blank: false,
3593            }
3594        ))
3595    );
3596
3597    assert_eq!(
3598        enclosing_indent(
3599            indoc!(
3600                "
3601                fn b() {
3602                    if c {
3603                        let d = 2;
3604                    }
3605                }
3606                "
3607            ),
3608            2,
3609            cx,
3610        )
3611        .await,
3612        Some((
3613            1..2,
3614            LineIndent {
3615                tabs: 0,
3616                spaces: 4,
3617                line_blank: false,
3618            }
3619        ))
3620    );
3621
3622    assert_eq!(
3623        enclosing_indent(
3624            indoc!(
3625                "
3626                fn b() {
3627                    if c {
3628                        let d = 2;
3629
3630                        let e = 5;
3631                    }
3632                }
3633                "
3634            ),
3635            3,
3636            cx,
3637        )
3638        .await,
3639        Some((
3640            1..4,
3641            LineIndent {
3642                tabs: 0,
3643                spaces: 4,
3644                line_blank: false,
3645            }
3646        ))
3647    );
3648}
3649
3650#[gpui::test]
3651async fn test_summaries_for_anchors(cx: &mut TestAppContext) {
3652    let base_text_1 = indoc!(
3653        "
3654        bar
3655        "
3656    );
3657    let text_1 = indoc!(
3658        "
3659        BAR
3660        "
3661    );
3662    let base_text_2 = indoc!(
3663        "
3664        foo
3665        "
3666    );
3667    let text_2 = indoc!(
3668        "
3669        FOO
3670        "
3671    );
3672
3673    let buffer_1 = cx.new(|cx| Buffer::local(text_1, cx));
3674    let buffer_2 = cx.new(|cx| Buffer::local(text_2, cx));
3675    let diff_1 = cx.new(|cx| {
3676        BufferDiff::new_with_base_text(base_text_1, &buffer_1.read(cx).text_snapshot(), cx)
3677    });
3678    let diff_2 = cx.new(|cx| {
3679        BufferDiff::new_with_base_text(base_text_2, &buffer_2.read(cx).text_snapshot(), cx)
3680    });
3681    cx.run_until_parked();
3682
3683    let mut ids = vec![];
3684    let multibuffer = cx.new(|cx| {
3685        let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
3686        multibuffer.set_all_diff_hunks_expanded(cx);
3687        ids.extend(multibuffer.push_excerpts(
3688            buffer_1.clone(),
3689            [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
3690            cx,
3691        ));
3692        ids.extend(multibuffer.push_excerpts(
3693            buffer_2.clone(),
3694            [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
3695            cx,
3696        ));
3697        multibuffer.add_diff(diff_1.clone(), cx);
3698        multibuffer.add_diff(diff_2.clone(), cx);
3699        multibuffer
3700    });
3701
3702    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3703        (multibuffer.snapshot(cx), multibuffer.subscribe())
3704    });
3705
3706    assert_new_snapshot(
3707        &multibuffer,
3708        &mut snapshot,
3709        &mut subscription,
3710        cx,
3711        indoc!(
3712            "
3713            - bar
3714            + BAR
3715
3716            - foo
3717            + FOO
3718            "
3719        ),
3720    );
3721
3722    let anchor_1 = Anchor::in_buffer(ids[0], text::Anchor::MIN);
3723    let point_1 = snapshot.summaries_for_anchors::<Point, _>([&anchor_1])[0];
3724    assert_eq!(point_1, Point::new(0, 0));
3725
3726    let anchor_2 = Anchor::in_buffer(ids[1], text::Anchor::MIN);
3727    let point_2 = snapshot.summaries_for_anchors::<Point, _>([&anchor_2])[0];
3728    assert_eq!(point_2, Point::new(3, 0));
3729}
3730
3731#[gpui::test]
3732async fn test_trailing_deletion_without_newline(cx: &mut TestAppContext) {
3733    let base_text_1 = "one\ntwo".to_owned();
3734    let text_1 = "one\n".to_owned();
3735
3736    let buffer_1 = cx.new(|cx| Buffer::local(text_1, cx));
3737    let diff_1 = cx.new(|cx| {
3738        BufferDiff::new_with_base_text(&base_text_1, &buffer_1.read(cx).text_snapshot(), cx)
3739    });
3740    cx.run_until_parked();
3741
3742    let multibuffer = cx.new(|cx| {
3743        let mut multibuffer = MultiBuffer::singleton(buffer_1.clone(), cx);
3744        multibuffer.add_diff(diff_1.clone(), cx);
3745        multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
3746        multibuffer
3747    });
3748
3749    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3750        (multibuffer.snapshot(cx), multibuffer.subscribe())
3751    });
3752
3753    assert_new_snapshot(
3754        &multibuffer,
3755        &mut snapshot,
3756        &mut subscription,
3757        cx,
3758        indoc!(
3759            "
3760              one
3761            - two
3762            "
3763        ),
3764    );
3765
3766    assert_eq!(snapshot.max_point(), Point::new(2, 0));
3767    assert_eq!(snapshot.len().0, 8);
3768
3769    assert_eq!(
3770        snapshot
3771            .dimensions_from_points::<Point>([Point::new(2, 0)])
3772            .collect::<Vec<_>>(),
3773        vec![Point::new(2, 0)]
3774    );
3775
3776    let (_, translated_offset) = snapshot.point_to_buffer_offset(Point::new(2, 0)).unwrap();
3777    assert_eq!(translated_offset.0, "one\n".len());
3778    let (_, translated_point, _) = snapshot.point_to_buffer_point(Point::new(2, 0)).unwrap();
3779    assert_eq!(translated_point, Point::new(1, 0));
3780
3781    // The same, for an excerpt that's not at the end of the multibuffer.
3782
3783    let text_2 = "foo\n".to_owned();
3784    let buffer_2 = cx.new(|cx| Buffer::local(&text_2, cx));
3785    multibuffer.update(cx, |multibuffer, cx| {
3786        multibuffer.push_excerpts(
3787            buffer_2.clone(),
3788            [ExcerptRange::new(Point::new(0, 0)..Point::new(1, 0))],
3789            cx,
3790        );
3791    });
3792
3793    assert_new_snapshot(
3794        &multibuffer,
3795        &mut snapshot,
3796        &mut subscription,
3797        cx,
3798        indoc!(
3799            "
3800              one
3801            - two
3802
3803              foo
3804            "
3805        ),
3806    );
3807
3808    assert_eq!(
3809        snapshot
3810            .dimensions_from_points::<Point>([Point::new(2, 0)])
3811            .collect::<Vec<_>>(),
3812        vec![Point::new(2, 0)]
3813    );
3814
3815    let buffer_1_id = buffer_1.read_with(cx, |buffer_1, _| buffer_1.remote_id());
3816    let (buffer, translated_offset) = snapshot.point_to_buffer_offset(Point::new(2, 0)).unwrap();
3817    assert_eq!(buffer.remote_id(), buffer_1_id);
3818    assert_eq!(translated_offset.0, "one\n".len());
3819    let (buffer, translated_point, _) = snapshot.point_to_buffer_point(Point::new(2, 0)).unwrap();
3820    assert_eq!(buffer.remote_id(), buffer_1_id);
3821    assert_eq!(translated_point, Point::new(1, 0));
3822}
3823
3824fn format_diff(
3825    text: &str,
3826    row_infos: &Vec<RowInfo>,
3827    boundary_rows: &HashSet<MultiBufferRow>,
3828    has_diff: Option<bool>,
3829) -> String {
3830    let has_diff =
3831        has_diff.unwrap_or_else(|| row_infos.iter().any(|info| info.diff_status.is_some()));
3832    text.split('\n')
3833        .enumerate()
3834        .zip(row_infos)
3835        .map(|((ix, line), info)| {
3836            let marker = match info.diff_status.map(|status| status.kind) {
3837                Some(DiffHunkStatusKind::Added) => "+ ",
3838                Some(DiffHunkStatusKind::Deleted) => "- ",
3839                Some(DiffHunkStatusKind::Modified) => unreachable!(),
3840                None => {
3841                    if has_diff && !line.is_empty() {
3842                        "  "
3843                    } else {
3844                        ""
3845                    }
3846                }
3847            };
3848            let boundary_row = if boundary_rows.contains(&MultiBufferRow(ix as u32)) {
3849                if has_diff {
3850                    "  ----------\n"
3851                } else {
3852                    "---------\n"
3853                }
3854            } else {
3855                ""
3856            };
3857            let expand = info
3858                .expand_info
3859                .map(|expand_info| match expand_info.direction {
3860                    ExpandExcerptDirection::Up => " [↑]",
3861                    ExpandExcerptDirection::Down => " [↓]",
3862                    ExpandExcerptDirection::UpAndDown => " [↕]",
3863                })
3864                .unwrap_or_default();
3865
3866            format!("{boundary_row}{marker}{line}{expand}")
3867            // let mbr = info
3868            //     .multibuffer_row
3869            //     .map(|row| format!("{:0>3}", row.0))
3870            //     .unwrap_or_else(|| "???".to_string());
3871            // let byte_range = format!("{byte_range_start:0>3}..{byte_range_end:0>3}");
3872            // format!("{boundary_row}Row: {mbr}, Bytes: {byte_range} | {marker}{line}{expand}")
3873        })
3874        .collect::<Vec<_>>()
3875        .join("\n")
3876}
3877
3878// fn format_transforms(snapshot: &MultiBufferSnapshot) -> String {
3879//     snapshot
3880//         .diff_transforms
3881//         .iter()
3882//         .map(|transform| {
3883//             let (kind, summary) = match transform {
3884//                 DiffTransform::DeletedHunk { summary, .. } => ("   Deleted", (*summary).into()),
3885//                 DiffTransform::FilteredInsertedHunk { summary, .. } => ("  Filtered", *summary),
3886//                 DiffTransform::InsertedHunk { summary, .. } => ("  Inserted", *summary),
3887//                 DiffTransform::Unmodified { summary, .. } => ("Unmodified", *summary),
3888//             };
3889//             format!("{kind}(len: {}, lines: {:?})", summary.len, summary.lines)
3890//         })
3891//         .join("\n")
3892// }
3893
3894// fn format_excerpts(snapshot: &MultiBufferSnapshot) -> String {
3895//     snapshot
3896//         .excerpts
3897//         .iter()
3898//         .map(|excerpt| {
3899//             format!(
3900//                 "Excerpt(buffer_range = {:?}, lines = {:?}, has_trailing_newline = {:?})",
3901//                 excerpt.range.context.to_point(&excerpt.buffer),
3902//                 excerpt.text_summary.lines,
3903//                 excerpt.has_trailing_newline
3904//             )
3905//         })
3906//         .join("\n")
3907// }
3908
3909#[gpui::test]
3910async fn test_singleton_with_inverted_diff(cx: &mut TestAppContext) {
3911    let text = indoc!(
3912        "
3913        ZERO
3914        one
3915        TWO
3916        three
3917        six
3918        "
3919    );
3920    let base_text = indoc!(
3921        "
3922        one
3923        two
3924        three
3925        four
3926        five
3927        six
3928        "
3929    );
3930
3931    let buffer = cx.new(|cx| Buffer::local(text, cx));
3932    let diff = cx
3933        .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
3934    cx.run_until_parked();
3935
3936    let base_text_buffer = diff.read_with(cx, |diff, _| diff.base_text_buffer());
3937
3938    let multibuffer = cx.new(|cx| {
3939        let mut multibuffer = MultiBuffer::singleton(base_text_buffer.clone(), cx);
3940        multibuffer.set_all_diff_hunks_expanded(cx);
3941        multibuffer.add_inverted_diff(diff.clone(), cx);
3942        multibuffer
3943    });
3944
3945    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3946        (multibuffer.snapshot(cx), multibuffer.subscribe())
3947    });
3948
3949    assert_eq!(snapshot.text(), base_text);
3950    assert_new_snapshot(
3951        &multibuffer,
3952        &mut snapshot,
3953        &mut subscription,
3954        cx,
3955        indoc!(
3956            "
3957              one
3958            - two
3959              three
3960            - four
3961            - five
3962              six
3963            "
3964        ),
3965    );
3966
3967    buffer.update(cx, |buffer, cx| {
3968        buffer.edit_via_marked_text(
3969            indoc!(
3970                "
3971                ZERO
3972                one
3973                «<inserted>»W«O
3974                T»hree
3975                six
3976                "
3977            ),
3978            None,
3979            cx,
3980        );
3981    });
3982    cx.run_until_parked();
3983    let update = diff
3984        .update(cx, |diff, cx| {
3985            diff.update_diff(
3986                buffer.read(cx).text_snapshot(),
3987                Some(base_text.into()),
3988                None,
3989                None,
3990                cx,
3991            )
3992        })
3993        .await;
3994    diff.update(cx, |diff, cx| {
3995        diff.set_snapshot(update, &buffer.read(cx).text_snapshot(), cx)
3996    })
3997    .await;
3998    cx.run_until_parked();
3999
4000    assert_new_snapshot(
4001        &multibuffer,
4002        &mut snapshot,
4003        &mut subscription,
4004        cx,
4005        indoc! {
4006            "
4007              one
4008            - two
4009            - three
4010            - four
4011            - five
4012              six
4013            "
4014        },
4015    );
4016
4017    buffer.update(cx, |buffer, cx| {
4018        buffer.set_text("ZERO\nONE\nTWO\n", cx);
4019    });
4020    cx.run_until_parked();
4021    let update = diff
4022        .update(cx, |diff, cx| {
4023            diff.update_diff(
4024                buffer.read(cx).text_snapshot(),
4025                Some(base_text.into()),
4026                None,
4027                None,
4028                cx,
4029            )
4030        })
4031        .await;
4032    diff.update(cx, |diff, cx| {
4033        diff.set_snapshot(update, &buffer.read(cx).text_snapshot(), cx)
4034    })
4035    .await;
4036    cx.run_until_parked();
4037
4038    assert_new_snapshot(
4039        &multibuffer,
4040        &mut snapshot,
4041        &mut subscription,
4042        cx,
4043        indoc! {
4044            "
4045            - one
4046            - two
4047            - three
4048            - four
4049            - five
4050            - six
4051            "
4052        },
4053    );
4054
4055    diff.update(cx, |diff, cx| {
4056        diff.set_base_text(
4057            Some("new base\n".into()),
4058            None,
4059            buffer.read(cx).text_snapshot(),
4060            cx,
4061        )
4062    })
4063    .await
4064    .unwrap();
4065    cx.run_until_parked();
4066
4067    assert_new_snapshot(
4068        &multibuffer,
4069        &mut snapshot,
4070        &mut subscription,
4071        cx,
4072        indoc! {"
4073            - new base
4074        "},
4075    );
4076}
4077
4078#[gpui::test]
4079async fn test_inverted_diff_base_text_change(cx: &mut TestAppContext) {
4080    let base_text = "aaa\nbbb\nccc\n";
4081    let text = "ddd\n";
4082    let buffer = cx.new(|cx| Buffer::local(text, cx));
4083    let diff = cx
4084        .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
4085    cx.run_until_parked();
4086
4087    let base_text_buffer = diff.read_with(cx, |diff, _| diff.base_text_buffer());
4088
4089    let multibuffer = cx.new(|cx| {
4090        let mut multibuffer = MultiBuffer::singleton(base_text_buffer.clone(), cx);
4091        multibuffer.set_all_diff_hunks_expanded(cx);
4092        multibuffer.add_inverted_diff(diff.clone(), cx);
4093        multibuffer
4094    });
4095
4096    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
4097        (multibuffer.snapshot(cx), multibuffer.subscribe())
4098    });
4099
4100    assert_eq!(snapshot.text(), base_text);
4101    assert_new_snapshot(
4102        &multibuffer,
4103        &mut snapshot,
4104        &mut subscription,
4105        cx,
4106        indoc!(
4107            "
4108            - aaa
4109            - bbb
4110            - ccc
4111            "
4112        ),
4113    );
4114
4115    let update = diff
4116        .update(cx, |diff, cx| {
4117            diff.update_diff(
4118                buffer.read(cx).text_snapshot(),
4119                Some("ddd\n".into()),
4120                Some(true),
4121                None,
4122                cx,
4123            )
4124        })
4125        .await;
4126    diff.update(cx, |diff, cx| {
4127        diff.set_snapshot(update, &buffer.read(cx).text_snapshot(), cx)
4128    })
4129    .detach();
4130
4131    let _hunks: Vec<_> = multibuffer
4132        .read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx))
4133        .diff_hunks()
4134        .collect();
4135}
4136
4137#[track_caller]
4138fn assert_excerpts_match(
4139    multibuffer: &Entity<MultiBuffer>,
4140    cx: &mut TestAppContext,
4141    expected: &str,
4142) {
4143    let mut output = String::new();
4144    multibuffer.read_with(cx, |multibuffer, cx| {
4145        for (_, buffer, range) in multibuffer.snapshot(cx).excerpts() {
4146            output.push_str("-----\n");
4147            output.extend(buffer.text_for_range(range.context));
4148            if !output.ends_with('\n') {
4149                output.push('\n');
4150            }
4151        }
4152    });
4153    assert_eq!(output, expected);
4154}
4155
4156#[track_caller]
4157fn assert_new_snapshot(
4158    multibuffer: &Entity<MultiBuffer>,
4159    snapshot: &mut MultiBufferSnapshot,
4160    subscription: &mut Subscription<MultiBufferOffset>,
4161    cx: &mut TestAppContext,
4162    expected_diff: &str,
4163) {
4164    let new_snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
4165    let actual_text = new_snapshot.text();
4166    let line_infos = new_snapshot
4167        .row_infos(MultiBufferRow(0))
4168        .collect::<Vec<_>>();
4169    let actual_diff = format_diff(&actual_text, &line_infos, &Default::default(), None);
4170    pretty_assertions::assert_eq!(actual_diff, expected_diff);
4171    check_edits(
4172        snapshot,
4173        &new_snapshot,
4174        &subscription.consume().into_inner(),
4175    );
4176    *snapshot = new_snapshot;
4177}
4178
4179#[track_caller]
4180fn check_edits(
4181    old_snapshot: &MultiBufferSnapshot,
4182    new_snapshot: &MultiBufferSnapshot,
4183    edits: &[Edit<MultiBufferOffset>],
4184) {
4185    let mut text = old_snapshot.text();
4186    let new_text = new_snapshot.text();
4187    for edit in edits.iter().rev() {
4188        if !text.is_char_boundary(edit.old.start.0)
4189            || !text.is_char_boundary(edit.old.end.0)
4190            || !new_text.is_char_boundary(edit.new.start.0)
4191            || !new_text.is_char_boundary(edit.new.end.0)
4192        {
4193            panic!(
4194                "invalid edits: {:?}\nold text: {:?}\nnew text: {:?}",
4195                edits, text, new_text
4196            );
4197        }
4198
4199        text.replace_range(
4200            edit.old.start.0..edit.old.end.0,
4201            &new_text[edit.new.start.0..edit.new.end.0],
4202        );
4203    }
4204
4205    pretty_assertions::assert_eq!(text, new_text, "invalid edits: {:?}", edits);
4206}
4207
4208#[track_caller]
4209fn assert_chunks_in_ranges(snapshot: &MultiBufferSnapshot) {
4210    let full_text = snapshot.text();
4211    for ix in 0..full_text.len() {
4212        let mut chunks = snapshot.chunks(MultiBufferOffset(0)..snapshot.len(), false);
4213        chunks.seek(MultiBufferOffset(ix)..snapshot.len());
4214        let tail = chunks.map(|chunk| chunk.text).collect::<String>();
4215        assert_eq!(tail, &full_text[ix..], "seek to range: {:?}", ix..);
4216    }
4217}
4218
4219#[track_caller]
4220fn assert_consistent_line_numbers(snapshot: &MultiBufferSnapshot) {
4221    let all_line_numbers = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
4222    for start_row in 1..all_line_numbers.len() {
4223        let line_numbers = snapshot
4224            .row_infos(MultiBufferRow(start_row as u32))
4225            .collect::<Vec<_>>();
4226        assert_eq!(
4227            line_numbers,
4228            all_line_numbers[start_row..],
4229            "start_row: {start_row}"
4230        );
4231    }
4232}
4233
4234#[track_caller]
4235fn assert_position_translation(snapshot: &MultiBufferSnapshot) {
4236    let text = Rope::from(snapshot.text());
4237
4238    let mut left_anchors = Vec::new();
4239    let mut right_anchors = Vec::new();
4240    let mut offsets = Vec::new();
4241    let mut points = Vec::new();
4242    for offset in 0..=text.len() + 1 {
4243        let offset = MultiBufferOffset(offset);
4244        let clipped_left = snapshot.clip_offset(offset, Bias::Left);
4245        let clipped_right = snapshot.clip_offset(offset, Bias::Right);
4246        assert_eq!(
4247            clipped_left.0,
4248            text.clip_offset(offset.0, Bias::Left),
4249            "clip_offset({offset:?}, Left)"
4250        );
4251        assert_eq!(
4252            clipped_right.0,
4253            text.clip_offset(offset.0, Bias::Right),
4254            "clip_offset({offset:?}, Right)"
4255        );
4256        assert_eq!(
4257            snapshot.offset_to_point(clipped_left),
4258            text.offset_to_point(clipped_left.0),
4259            "offset_to_point({})",
4260            clipped_left.0
4261        );
4262        assert_eq!(
4263            snapshot.offset_to_point(clipped_right),
4264            text.offset_to_point(clipped_right.0),
4265            "offset_to_point({})",
4266            clipped_right.0
4267        );
4268        let anchor_after = snapshot.anchor_after(clipped_left);
4269        assert_eq!(
4270            anchor_after.to_offset(snapshot),
4271            clipped_left,
4272            "anchor_after({}).to_offset {anchor_after:?}",
4273            clipped_left.0
4274        );
4275        let anchor_before = snapshot.anchor_before(clipped_left);
4276        assert_eq!(
4277            anchor_before.to_offset(snapshot),
4278            clipped_left,
4279            "anchor_before({}).to_offset",
4280            clipped_left.0
4281        );
4282        left_anchors.push(anchor_before);
4283        right_anchors.push(anchor_after);
4284        offsets.push(clipped_left);
4285        points.push(text.offset_to_point(clipped_left.0));
4286    }
4287
4288    for row in 0..text.max_point().row {
4289        for column in 0..text.line_len(row) + 1 {
4290            let point = Point { row, column };
4291            let clipped_left = snapshot.clip_point(point, Bias::Left);
4292            let clipped_right = snapshot.clip_point(point, Bias::Right);
4293            assert_eq!(
4294                clipped_left,
4295                text.clip_point(point, Bias::Left),
4296                "clip_point({point:?}, Left)"
4297            );
4298            assert_eq!(
4299                clipped_right,
4300                text.clip_point(point, Bias::Right),
4301                "clip_point({point:?}, Right)"
4302            );
4303            assert_eq!(
4304                snapshot.point_to_offset(clipped_left).0,
4305                text.point_to_offset(clipped_left),
4306                "point_to_offset({clipped_left:?})"
4307            );
4308            assert_eq!(
4309                snapshot.point_to_offset(clipped_right).0,
4310                text.point_to_offset(clipped_right),
4311                "point_to_offset({clipped_right:?})"
4312            );
4313        }
4314    }
4315
4316    assert_eq!(
4317        snapshot.summaries_for_anchors::<MultiBufferOffset, _>(&left_anchors),
4318        offsets,
4319        "left_anchors <-> offsets"
4320    );
4321    assert_eq!(
4322        snapshot.summaries_for_anchors::<Point, _>(&left_anchors),
4323        points,
4324        "left_anchors <-> points"
4325    );
4326    assert_eq!(
4327        snapshot.summaries_for_anchors::<MultiBufferOffset, _>(&right_anchors),
4328        offsets,
4329        "right_anchors <-> offsets"
4330    );
4331    assert_eq!(
4332        snapshot.summaries_for_anchors::<Point, _>(&right_anchors),
4333        points,
4334        "right_anchors <-> points"
4335    );
4336
4337    for (anchors, bias) in [(&left_anchors, Bias::Left), (&right_anchors, Bias::Right)] {
4338        for (ix, (offset, anchor)) in offsets.iter().zip(anchors).enumerate() {
4339            if ix > 0 && *offset == MultiBufferOffset(252) && offset > &offsets[ix - 1] {
4340                let prev_anchor = left_anchors[ix - 1];
4341                assert!(
4342                    anchor.cmp(&prev_anchor, snapshot).is_gt(),
4343                    "anchor({}, {bias:?}).cmp(&anchor({}, {bias:?}).is_gt()",
4344                    offsets[ix],
4345                    offsets[ix - 1],
4346                );
4347                assert!(
4348                    prev_anchor.cmp(anchor, snapshot).is_lt(),
4349                    "anchor({}, {bias:?}).cmp(&anchor({}, {bias:?}).is_lt()",
4350                    offsets[ix - 1],
4351                    offsets[ix],
4352                );
4353            }
4354        }
4355    }
4356
4357    if let Some((buffer, offset)) = snapshot.point_to_buffer_offset(snapshot.max_point()) {
4358        assert!(offset.0 <= buffer.len());
4359    }
4360    if let Some((buffer, point, _)) = snapshot.point_to_buffer_point(snapshot.max_point()) {
4361        assert!(point <= buffer.max_point());
4362    }
4363}
4364
4365fn assert_line_indents(snapshot: &MultiBufferSnapshot) {
4366    let max_row = snapshot.max_point().row;
4367    let buffer_id = snapshot.excerpts().next().unwrap().1.remote_id();
4368    let text = text::Buffer::new(ReplicaId::LOCAL, buffer_id, snapshot.text());
4369    let mut line_indents = text
4370        .line_indents_in_row_range(0..max_row + 1)
4371        .collect::<Vec<_>>();
4372    for start_row in 0..snapshot.max_point().row {
4373        pretty_assertions::assert_eq!(
4374            snapshot
4375                .line_indents(MultiBufferRow(start_row), |_| true)
4376                .map(|(row, indent, _)| (row.0, indent))
4377                .collect::<Vec<_>>(),
4378            &line_indents[(start_row as usize)..],
4379            "line_indents({start_row})"
4380        );
4381    }
4382
4383    line_indents.reverse();
4384    pretty_assertions::assert_eq!(
4385        snapshot
4386            .reversed_line_indents(MultiBufferRow(max_row), |_| true)
4387            .map(|(row, indent, _)| (row.0, indent))
4388            .collect::<Vec<_>>(),
4389        &line_indents[..],
4390        "reversed_line_indents({max_row})"
4391    );
4392}
4393
4394#[gpui::test]
4395fn test_new_empty_buffer_uses_untitled_title(cx: &mut App) {
4396    let buffer = cx.new(|cx| Buffer::local("", cx));
4397    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4398
4399    assert_eq!(multibuffer.read(cx).title(cx), "untitled");
4400}
4401
4402#[gpui::test]
4403fn test_new_empty_buffer_uses_untitled_title_when_only_contains_whitespace(cx: &mut App) {
4404    let buffer = cx.new(|cx| Buffer::local("\n ", cx));
4405    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4406
4407    assert_eq!(multibuffer.read(cx).title(cx), "untitled");
4408}
4409
4410#[gpui::test]
4411fn test_new_empty_buffer_takes_first_line_for_title(cx: &mut App) {
4412    let buffer = cx.new(|cx| Buffer::local("Hello World\nSecond line", cx));
4413    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4414
4415    assert_eq!(multibuffer.read(cx).title(cx), "Hello World");
4416}
4417
4418#[gpui::test]
4419fn test_new_empty_buffer_takes_trimmed_first_line_for_title(cx: &mut App) {
4420    let buffer = cx.new(|cx| Buffer::local("\nHello, World ", cx));
4421    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4422
4423    assert_eq!(multibuffer.read(cx).title(cx), "Hello, World");
4424}
4425
4426#[gpui::test]
4427fn test_new_empty_buffer_uses_truncated_first_line_for_title(cx: &mut App) {
4428    let title = "aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeee";
4429    let title_after = "aaaaaaaaaabbbbbbbbbbccccccccccdddddddddd";
4430    let buffer = cx.new(|cx| Buffer::local(title, cx));
4431    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4432
4433    assert_eq!(multibuffer.read(cx).title(cx), title_after);
4434}
4435
4436#[gpui::test]
4437fn test_new_empty_buffer_uses_truncated_first_line_for_title_after_merging_adjacent_spaces(
4438    cx: &mut App,
4439) {
4440    let title = "aaaaaaaaaabbbbbbbbbb    ccccccccccddddddddddeeeeeeeeee";
4441    let title_after = "aaaaaaaaaabbbbbbbbbb ccccccccccddddddddd";
4442    let buffer = cx.new(|cx| Buffer::local(title, cx));
4443    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4444
4445    assert_eq!(multibuffer.read(cx).title(cx), title_after);
4446}
4447
4448#[gpui::test]
4449fn test_new_empty_buffers_title_can_be_set(cx: &mut App) {
4450    let buffer = cx.new(|cx| Buffer::local("Hello World", cx));
4451    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4452    assert_eq!(multibuffer.read(cx).title(cx), "Hello World");
4453
4454    multibuffer.update(cx, |multibuffer, cx| {
4455        multibuffer.set_title("Hey".into(), cx)
4456    });
4457    assert_eq!(multibuffer.read(cx).title(cx), "Hey");
4458}
4459
4460#[gpui::test(iterations = 100)]
4461fn test_random_chunk_bitmaps(cx: &mut App, mut rng: StdRng) {
4462    let multibuffer = if rng.random() {
4463        let len = rng.random_range(0..10000);
4464        let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
4465        let buffer = cx.new(|cx| Buffer::local(text, cx));
4466        cx.new(|cx| MultiBuffer::singleton(buffer, cx))
4467    } else {
4468        MultiBuffer::build_random(&mut rng, cx)
4469    };
4470
4471    let snapshot = multibuffer.read(cx).snapshot(cx);
4472
4473    let chunks = snapshot.chunks(MultiBufferOffset(0)..snapshot.len(), false);
4474
4475    for chunk in chunks {
4476        let chunk_text = chunk.text;
4477        let chars_bitmap = chunk.chars;
4478        let tabs_bitmap = chunk.tabs;
4479
4480        if chunk_text.is_empty() {
4481            assert_eq!(
4482                chars_bitmap, 0,
4483                "Empty chunk should have empty chars bitmap"
4484            );
4485            assert_eq!(tabs_bitmap, 0, "Empty chunk should have empty tabs bitmap");
4486            continue;
4487        }
4488
4489        assert!(
4490            chunk_text.len() <= 128,
4491            "Chunk text length {} exceeds 128 bytes",
4492            chunk_text.len()
4493        );
4494
4495        // Verify chars bitmap
4496        let char_indices = chunk_text
4497            .char_indices()
4498            .map(|(i, _)| i)
4499            .collect::<Vec<_>>();
4500
4501        for byte_idx in 0..chunk_text.len() {
4502            let should_have_bit = char_indices.contains(&byte_idx);
4503            let has_bit = chars_bitmap & (1 << byte_idx) != 0;
4504
4505            if has_bit != should_have_bit {
4506                eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
4507                eprintln!("Char indices: {:?}", char_indices);
4508                eprintln!("Chars bitmap: {:#b}", chars_bitmap);
4509            }
4510
4511            assert_eq!(
4512                has_bit, should_have_bit,
4513                "Chars bitmap mismatch at byte index {} in chunk {:?}. Expected bit: {}, Got bit: {}",
4514                byte_idx, chunk_text, should_have_bit, has_bit
4515            );
4516        }
4517
4518        for (byte_idx, byte) in chunk_text.bytes().enumerate() {
4519            let is_tab = byte == b'\t';
4520            let has_bit = tabs_bitmap & (1 << byte_idx) != 0;
4521
4522            if has_bit != is_tab {
4523                eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
4524                eprintln!("Tabs bitmap: {:#b}", tabs_bitmap);
4525                assert_eq!(
4526                    has_bit, is_tab,
4527                    "Tabs bitmap mismatch at byte index {} in chunk {:?}. Byte: {:?}, Expected bit: {}, Got bit: {}",
4528                    byte_idx, chunk_text, byte as char, is_tab, has_bit
4529                );
4530            }
4531        }
4532    }
4533}
4534
4535#[gpui::test(iterations = 10)]
4536fn test_random_chunk_bitmaps_with_diffs(cx: &mut App, mut rng: StdRng) {
4537    let settings_store = SettingsStore::test(cx);
4538    cx.set_global(settings_store);
4539    use buffer_diff::BufferDiff;
4540    use util::RandomCharIter;
4541
4542    let multibuffer = if rng.random() {
4543        let len = rng.random_range(100..10000);
4544        let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
4545        let buffer = cx.new(|cx| Buffer::local(text, cx));
4546        cx.new(|cx| MultiBuffer::singleton(buffer, cx))
4547    } else {
4548        MultiBuffer::build_random(&mut rng, cx)
4549    };
4550
4551    let _diff_count = rng.random_range(1..5);
4552    let mut diffs = Vec::new();
4553
4554    multibuffer.update(cx, |multibuffer, cx| {
4555        for buffer_id in multibuffer.excerpt_buffer_ids() {
4556            if rng.random_bool(0.7) {
4557                if let Some(buffer_handle) = multibuffer.buffer(buffer_id) {
4558                    let buffer_text = buffer_handle.read(cx).text();
4559                    let mut base_text = String::new();
4560
4561                    for line in buffer_text.lines() {
4562                        if rng.random_bool(0.3) {
4563                            continue;
4564                        } else if rng.random_bool(0.3) {
4565                            let line_len = rng.random_range(0..50);
4566                            let modified_line = RandomCharIter::new(&mut rng)
4567                                .take(line_len)
4568                                .collect::<String>();
4569                            base_text.push_str(&modified_line);
4570                            base_text.push('\n');
4571                        } else {
4572                            base_text.push_str(line);
4573                            base_text.push('\n');
4574                        }
4575                    }
4576
4577                    if rng.random_bool(0.5) {
4578                        let extra_lines = rng.random_range(1..5);
4579                        for _ in 0..extra_lines {
4580                            let line_len = rng.random_range(0..50);
4581                            let extra_line = RandomCharIter::new(&mut rng)
4582                                .take(line_len)
4583                                .collect::<String>();
4584                            base_text.push_str(&extra_line);
4585                            base_text.push('\n');
4586                        }
4587                    }
4588
4589                    let diff = cx.new(|cx| {
4590                        BufferDiff::new_with_base_text(
4591                            &base_text,
4592                            &buffer_handle.read(cx).text_snapshot(),
4593                            cx,
4594                        )
4595                    });
4596                    diffs.push(diff.clone());
4597                    multibuffer.add_diff(diff, cx);
4598                }
4599            }
4600        }
4601    });
4602
4603    multibuffer.update(cx, |multibuffer, cx| {
4604        if rng.random_bool(0.5) {
4605            multibuffer.set_all_diff_hunks_expanded(cx);
4606        } else {
4607            let snapshot = multibuffer.snapshot(cx);
4608            let text = snapshot.text();
4609
4610            let mut ranges = Vec::new();
4611            for _ in 0..rng.random_range(1..5) {
4612                if snapshot.len().0 == 0 {
4613                    break;
4614                }
4615
4616                let diff_size = rng.random_range(5..1000);
4617                let mut start = rng.random_range(0..snapshot.len().0);
4618
4619                while !text.is_char_boundary(start) {
4620                    start = start.saturating_sub(1);
4621                }
4622
4623                let mut end = rng.random_range(start..snapshot.len().0.min(start + diff_size));
4624
4625                while !text.is_char_boundary(end) {
4626                    end = end.saturating_add(1);
4627                }
4628                let start_anchor = snapshot.anchor_after(MultiBufferOffset(start));
4629                let end_anchor = snapshot.anchor_before(MultiBufferOffset(end));
4630                ranges.push(start_anchor..end_anchor);
4631            }
4632            multibuffer.expand_diff_hunks(ranges, cx);
4633        }
4634    });
4635
4636    let snapshot = multibuffer.read(cx).snapshot(cx);
4637
4638    let chunks = snapshot.chunks(MultiBufferOffset(0)..snapshot.len(), false);
4639
4640    for chunk in chunks {
4641        let chunk_text = chunk.text;
4642        let chars_bitmap = chunk.chars;
4643        let tabs_bitmap = chunk.tabs;
4644
4645        if chunk_text.is_empty() {
4646            assert_eq!(
4647                chars_bitmap, 0,
4648                "Empty chunk should have empty chars bitmap"
4649            );
4650            assert_eq!(tabs_bitmap, 0, "Empty chunk should have empty tabs bitmap");
4651            continue;
4652        }
4653
4654        assert!(
4655            chunk_text.len() <= 128,
4656            "Chunk text length {} exceeds 128 bytes",
4657            chunk_text.len()
4658        );
4659
4660        let char_indices = chunk_text
4661            .char_indices()
4662            .map(|(i, _)| i)
4663            .collect::<Vec<_>>();
4664
4665        for byte_idx in 0..chunk_text.len() {
4666            let should_have_bit = char_indices.contains(&byte_idx);
4667            let has_bit = chars_bitmap & (1 << byte_idx) != 0;
4668
4669            if has_bit != should_have_bit {
4670                eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
4671                eprintln!("Char indices: {:?}", char_indices);
4672                eprintln!("Chars bitmap: {:#b}", chars_bitmap);
4673            }
4674
4675            assert_eq!(
4676                has_bit, should_have_bit,
4677                "Chars bitmap mismatch at byte index {} in chunk {:?}. Expected bit: {}, Got bit: {}",
4678                byte_idx, chunk_text, should_have_bit, has_bit
4679            );
4680        }
4681
4682        for (byte_idx, byte) in chunk_text.bytes().enumerate() {
4683            let is_tab = byte == b'\t';
4684            let has_bit = tabs_bitmap & (1 << byte_idx) != 0;
4685
4686            if has_bit != is_tab {
4687                eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
4688                eprintln!("Tabs bitmap: {:#b}", tabs_bitmap);
4689                assert_eq!(
4690                    has_bit, is_tab,
4691                    "Tabs bitmap mismatch at byte index {} in chunk {:?}. Byte: {:?}, Expected bit: {}, Got bit: {}",
4692                    byte_idx, chunk_text, byte as char, is_tab, has_bit
4693                );
4694            }
4695        }
4696    }
4697}
4698
4699fn collect_word_diffs(
4700    base_text: &str,
4701    modified_text: &str,
4702    cx: &mut TestAppContext,
4703) -> Vec<String> {
4704    let buffer = cx.new(|cx| Buffer::local(modified_text, cx));
4705    let diff = cx
4706        .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
4707    cx.run_until_parked();
4708
4709    let multibuffer = cx.new(|cx| {
4710        let mut multibuffer = MultiBuffer::singleton(buffer.clone(), cx);
4711        multibuffer.add_diff(diff.clone(), cx);
4712        multibuffer
4713    });
4714
4715    multibuffer.update(cx, |multibuffer, cx| {
4716        multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
4717    });
4718
4719    let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
4720    let text = snapshot.text();
4721
4722    snapshot
4723        .diff_hunks()
4724        .flat_map(|hunk| hunk.word_diffs)
4725        .map(|range| text[range.start.0..range.end.0].to_string())
4726        .collect()
4727}
4728
4729#[gpui::test]
4730async fn test_word_diff_simple_replacement(cx: &mut TestAppContext) {
4731    let settings_store = cx.update(|cx| SettingsStore::test(cx));
4732    cx.set_global(settings_store);
4733
4734    let base_text = "hello world foo bar\n";
4735    let modified_text = "hello WORLD foo BAR\n";
4736
4737    let word_diffs = collect_word_diffs(base_text, modified_text, cx);
4738
4739    assert_eq!(word_diffs, vec!["world", "bar", "WORLD", "BAR"]);
4740}
4741
4742#[gpui::test]
4743async fn test_word_diff_white_space(cx: &mut TestAppContext) {
4744    let settings_store = cx.update(|cx| SettingsStore::test(cx));
4745    cx.set_global(settings_store);
4746
4747    let base_text = "hello world foo bar\n";
4748    let modified_text = "    hello world foo bar\n";
4749
4750    let word_diffs = collect_word_diffs(base_text, modified_text, cx);
4751
4752    assert_eq!(word_diffs, vec!["    "]);
4753}
4754
4755#[gpui::test]
4756async fn test_word_diff_consecutive_modified_lines(cx: &mut TestAppContext) {
4757    let settings_store = cx.update(|cx| SettingsStore::test(cx));
4758    cx.set_global(settings_store);
4759
4760    let base_text = "aaa bbb\nccc ddd\n";
4761    let modified_text = "aaa BBB\nccc DDD\n";
4762
4763    let word_diffs = collect_word_diffs(base_text, modified_text, cx);
4764
4765    assert_eq!(
4766        word_diffs,
4767        vec!["bbb", "ddd", "BBB", "DDD"],
4768        "consecutive modified lines should produce word diffs when line counts match"
4769    );
4770}
4771
4772#[gpui::test]
4773async fn test_word_diff_modified_lines_with_deletion_between(cx: &mut TestAppContext) {
4774    let settings_store = cx.update(|cx| SettingsStore::test(cx));
4775    cx.set_global(settings_store);
4776
4777    let base_text = "aaa bbb\ndeleted line\nccc ddd\n";
4778    let modified_text = "aaa BBB\nccc DDD\n";
4779
4780    let word_diffs = collect_word_diffs(base_text, modified_text, cx);
4781
4782    assert_eq!(
4783        word_diffs,
4784        Vec::<String>::new(),
4785        "modified lines with a deleted line between should not produce word diffs"
4786    );
4787}
4788
4789#[gpui::test]
4790async fn test_word_diff_disabled(cx: &mut TestAppContext) {
4791    let settings_store = cx.update(|cx| {
4792        let mut settings_store = SettingsStore::test(cx);
4793        settings_store.update_user_settings(cx, |settings| {
4794            settings.project.all_languages.defaults.word_diff_enabled = Some(false);
4795        });
4796        settings_store
4797    });
4798    cx.set_global(settings_store);
4799
4800    let base_text = "hello world\n";
4801    let modified_text = "hello WORLD\n";
4802
4803    let word_diffs = collect_word_diffs(base_text, modified_text, cx);
4804
4805    assert_eq!(
4806        word_diffs,
4807        Vec::<String>::new(),
4808        "word diffs should be empty when disabled"
4809    );
4810}
4811
4812/// Tests `excerpt_containing` and `excerpts_for_range` (functions mapping multi-buffer text-coordinates to excerpts)
4813#[gpui::test]
4814fn test_excerpts_containment_functions(cx: &mut App) {
4815    // Multibuffer content for these tests:
4816    //    0123
4817    // 0: aa0
4818    // 1: aa1
4819    //    -----
4820    // 2: bb0
4821    // 3: bb1
4822    //    -----MultiBufferOffset(0)..
4823    // 4: cc0
4824
4825    let buffer_1 = cx.new(|cx| Buffer::local("aa0\naa1", cx));
4826    let buffer_2 = cx.new(|cx| Buffer::local("bb0\nbb1", cx));
4827    let buffer_3 = cx.new(|cx| Buffer::local("cc0", cx));
4828
4829    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
4830
4831    let (excerpt_1_id, excerpt_2_id, excerpt_3_id) = multibuffer.update(cx, |multibuffer, cx| {
4832        let excerpt_1_id = multibuffer.push_excerpts(
4833            buffer_1.clone(),
4834            [ExcerptRange::new(Point::new(0, 0)..Point::new(1, 3))],
4835            cx,
4836        )[0];
4837
4838        let excerpt_2_id = multibuffer.push_excerpts(
4839            buffer_2.clone(),
4840            [ExcerptRange::new(Point::new(0, 0)..Point::new(1, 3))],
4841            cx,
4842        )[0];
4843
4844        let excerpt_3_id = multibuffer.push_excerpts(
4845            buffer_3.clone(),
4846            [ExcerptRange::new(Point::new(0, 0)..Point::new(0, 3))],
4847            cx,
4848        )[0];
4849
4850        (excerpt_1_id, excerpt_2_id, excerpt_3_id)
4851    });
4852
4853    let snapshot = multibuffer.read(cx).snapshot(cx);
4854
4855    assert_eq!(snapshot.text(), "aa0\naa1\nbb0\nbb1\ncc0");
4856
4857    //// Test `excerpts_for_range`
4858
4859    let p00 = snapshot.point_to_offset(Point::new(0, 0));
4860    let p10 = snapshot.point_to_offset(Point::new(1, 0));
4861    let p20 = snapshot.point_to_offset(Point::new(2, 0));
4862    let p23 = snapshot.point_to_offset(Point::new(2, 3));
4863    let p13 = snapshot.point_to_offset(Point::new(1, 3));
4864    let p40 = snapshot.point_to_offset(Point::new(4, 0));
4865    let p43 = snapshot.point_to_offset(Point::new(4, 3));
4866
4867    let excerpts: Vec<_> = snapshot.excerpts_for_range(p00..p00).collect();
4868    assert_eq!(excerpts.len(), 1);
4869    assert_eq!(excerpts[0].id, excerpt_1_id);
4870
4871    // Cursor at very end of excerpt 3
4872    let excerpts: Vec<_> = snapshot.excerpts_for_range(p43..p43).collect();
4873    assert_eq!(excerpts.len(), 1);
4874    assert_eq!(excerpts[0].id, excerpt_3_id);
4875
4876    let excerpts: Vec<_> = snapshot.excerpts_for_range(p00..p23).collect();
4877    assert_eq!(excerpts.len(), 2);
4878    assert_eq!(excerpts[0].id, excerpt_1_id);
4879    assert_eq!(excerpts[1].id, excerpt_2_id);
4880
4881    // This range represent an selection with end-point just inside excerpt_2
4882    // Today we only expand the first excerpt, but another interpretation that
4883    // we could consider is expanding both here
4884    let excerpts: Vec<_> = snapshot.excerpts_for_range(p10..p20).collect();
4885    assert_eq!(excerpts.len(), 1);
4886    assert_eq!(excerpts[0].id, excerpt_1_id);
4887
4888    //// Test that `excerpts_for_range` and `excerpt_containing` agree for all single offsets (cursor positions)
4889    for offset in 0..=snapshot.len().0 {
4890        let offset = MultiBufferOffset(offset);
4891        let excerpts_for_range: Vec<_> = snapshot.excerpts_for_range(offset..offset).collect();
4892        assert_eq!(
4893            excerpts_for_range.len(),
4894            1,
4895            "Expected exactly one excerpt for offset {offset}",
4896        );
4897
4898        let excerpt_containing = snapshot.excerpt_containing(offset..offset);
4899        assert!(
4900            excerpt_containing.is_some(),
4901            "Expected excerpt_containing to find excerpt for offset {offset}",
4902        );
4903
4904        assert_eq!(
4905            excerpts_for_range[0].id,
4906            excerpt_containing.unwrap().id(),
4907            "excerpts_for_range and excerpt_containing should agree for offset {offset}",
4908        );
4909    }
4910
4911    //// Test `excerpt_containing` behavior with ranges:
4912
4913    // Ranges intersecting a single-excerpt
4914    let containing = snapshot.excerpt_containing(p00..p13);
4915    assert!(containing.is_some());
4916    assert_eq!(containing.unwrap().id(), excerpt_1_id);
4917
4918    // Ranges intersecting multiple excerpts (should return None)
4919    let containing = snapshot.excerpt_containing(p20..p40);
4920    assert!(
4921        containing.is_none(),
4922        "excerpt_containing should return None for ranges spanning multiple excerpts"
4923    );
4924}
4925
4926#[gpui::test]
4927fn test_range_to_buffer_ranges_with_range_bounds(cx: &mut App) {
4928    use std::ops::Bound;
4929
4930    let buffer_1 = cx.new(|cx| Buffer::local("aaa\nbbb", cx));
4931    let buffer_2 = cx.new(|cx| Buffer::local("ccc", cx));
4932
4933    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
4934    let (excerpt_1_id, excerpt_2_id) = multibuffer.update(cx, |multibuffer, cx| {
4935        let excerpt_1_id = multibuffer.push_excerpts(
4936            buffer_1.clone(),
4937            [ExcerptRange::new(Point::new(0, 0)..Point::new(1, 3))],
4938            cx,
4939        )[0];
4940
4941        let excerpt_2_id = multibuffer.push_excerpts(
4942            buffer_2.clone(),
4943            [ExcerptRange::new(Point::new(0, 0)..Point::new(0, 3))],
4944            cx,
4945        )[0];
4946
4947        (excerpt_1_id, excerpt_2_id)
4948    });
4949
4950    let snapshot = multibuffer.read(cx).snapshot(cx);
4951    assert_eq!(snapshot.text(), "aaa\nbbb\nccc");
4952
4953    let excerpt_2_start = Point::new(2, 0);
4954
4955    let ranges_half_open = snapshot.range_to_buffer_ranges(Point::zero()..excerpt_2_start);
4956    assert_eq!(
4957        ranges_half_open.len(),
4958        1,
4959        "Half-open range ending at excerpt start should EXCLUDE that excerpt"
4960    );
4961    assert_eq!(ranges_half_open[0].2, excerpt_1_id);
4962
4963    let ranges_inclusive = snapshot.range_to_buffer_ranges(Point::zero()..=excerpt_2_start);
4964    assert_eq!(
4965        ranges_inclusive.len(),
4966        2,
4967        "Inclusive range ending at excerpt start should INCLUDE that excerpt"
4968    );
4969    assert_eq!(ranges_inclusive[0].2, excerpt_1_id);
4970    assert_eq!(ranges_inclusive[1].2, excerpt_2_id);
4971
4972    let ranges_unbounded =
4973        snapshot.range_to_buffer_ranges((Bound::Included(Point::zero()), Bound::Unbounded));
4974    assert_eq!(
4975        ranges_unbounded.len(),
4976        2,
4977        "Unbounded end should include all excerpts"
4978    );
4979    assert_eq!(ranges_unbounded[0].2, excerpt_1_id);
4980    assert_eq!(ranges_unbounded[1].2, excerpt_2_id);
4981
4982    let ranges_excluded_end = snapshot.range_to_buffer_ranges((
4983        Bound::Included(Point::zero()),
4984        Bound::Excluded(excerpt_2_start),
4985    ));
4986    assert_eq!(
4987        ranges_excluded_end.len(),
4988        1,
4989        "Excluded end bound should exclude excerpt starting at that point"
4990    );
4991    assert_eq!(ranges_excluded_end[0].2, excerpt_1_id);
4992
4993    let buffer_empty = cx.new(|cx| Buffer::local("", cx));
4994    let multibuffer_trailing_empty = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
4995    let (te_excerpt_1_id, te_excerpt_2_id) =
4996        multibuffer_trailing_empty.update(cx, |multibuffer, cx| {
4997            let excerpt_1_id = multibuffer.push_excerpts(
4998                buffer_1.clone(),
4999                [ExcerptRange::new(Point::new(0, 0)..Point::new(1, 3))],
5000                cx,
5001            )[0];
5002
5003            let excerpt_2_id = multibuffer.push_excerpts(
5004                buffer_empty.clone(),
5005                [ExcerptRange::new(Point::new(0, 0)..Point::new(0, 0))],
5006                cx,
5007            )[0];
5008
5009            (excerpt_1_id, excerpt_2_id)
5010        });
5011
5012    let snapshot_trailing = multibuffer_trailing_empty.read(cx).snapshot(cx);
5013    assert_eq!(snapshot_trailing.text(), "aaa\nbbb\n");
5014
5015    let max_point = snapshot_trailing.max_point();
5016
5017    let ranges_half_open_max = snapshot_trailing.range_to_buffer_ranges(Point::zero()..max_point);
5018    assert_eq!(
5019        ranges_half_open_max.len(),
5020        1,
5021        "Half-open range to max_point should EXCLUDE trailing empty excerpt at max_point"
5022    );
5023    assert_eq!(ranges_half_open_max[0].2, te_excerpt_1_id);
5024
5025    let ranges_inclusive_max = snapshot_trailing.range_to_buffer_ranges(Point::zero()..=max_point);
5026    assert_eq!(
5027        ranges_inclusive_max.len(),
5028        2,
5029        "Inclusive range to max_point should INCLUDE trailing empty excerpt"
5030    );
5031    assert_eq!(ranges_inclusive_max[0].2, te_excerpt_1_id);
5032    assert_eq!(ranges_inclusive_max[1].2, te_excerpt_2_id);
5033
5034    let ranges_unbounded_trailing = snapshot_trailing
5035        .range_to_buffer_ranges((Bound::Included(Point::zero()), Bound::Unbounded));
5036    assert_eq!(
5037        ranges_unbounded_trailing.len(),
5038        2,
5039        "Unbounded end should include trailing empty excerpt"
5040    );
5041    assert_eq!(ranges_unbounded_trailing[0].2, te_excerpt_1_id);
5042    assert_eq!(ranges_unbounded_trailing[1].2, te_excerpt_2_id);
5043}
5044
5045#[gpui::test]
5046fn test_cannot_seek_backward_after_excerpt_replacement(cx: &mut TestAppContext) {
5047    let buffer_b_text: String = (0..50).map(|i| format!("line_b {i}\n")).collect();
5048    let buffer_b = cx.new(|cx| Buffer::local(buffer_b_text, cx));
5049
5050    let buffer_c_text: String = (0..10).map(|i| format!("line_c {i}\n")).collect();
5051    let buffer_c = cx.new(|cx| Buffer::local(buffer_c_text, cx));
5052
5053    let buffer_d_text: String = (0..10).map(|i| format!("line_d {i}\n")).collect();
5054    let buffer_d = cx.new(|cx| Buffer::local(buffer_d_text, cx));
5055
5056    let path_b = PathKey::with_sort_prefix(0, rel_path("bbb.rs").into_arc());
5057    let path_c = PathKey::with_sort_prefix(0, rel_path("ddd.rs").into_arc());
5058    let path_d = PathKey::with_sort_prefix(0, rel_path("ccc.rs").into_arc());
5059
5060    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
5061
5062    multibuffer.update(cx, |multibuffer, cx| {
5063        multibuffer.set_excerpts_for_path(
5064            path_b.clone(),
5065            buffer_b.clone(),
5066            vec![
5067                Point::row_range(0..3),
5068                Point::row_range(15..18),
5069                Point::row_range(30..33),
5070            ],
5071            0,
5072            cx,
5073        );
5074    });
5075
5076    multibuffer.update(cx, |multibuffer, cx| {
5077        multibuffer.set_excerpts_for_path(
5078            path_c.clone(),
5079            buffer_c.clone(),
5080            vec![Point::row_range(0..3)],
5081            0,
5082            cx,
5083        );
5084    });
5085
5086    let (anchor_in_e_b2, anchor_in_e_b3) = multibuffer.read_with(cx, |multibuffer, cx| {
5087        let snapshot = multibuffer.snapshot(cx);
5088        let excerpt_ids: Vec<ExcerptId> = snapshot.excerpts().map(|(id, _, _)| id).collect();
5089        assert_eq!(excerpt_ids.len(), 4, "expected 4 excerpts (3×B + 1×C)");
5090
5091        let e_b2_id = excerpt_ids[1];
5092        let e_b3_id = excerpt_ids[2];
5093
5094        let e_b2 = snapshot.excerpt(e_b2_id).expect("E_B2 should exist");
5095        let e_b3 = snapshot.excerpt(e_b3_id).expect("E_B3 should exist");
5096
5097        let anchor_b2 = Anchor::in_buffer(e_b2_id, e_b2.range.context.start);
5098        let anchor_b3 = Anchor::in_buffer(e_b3_id, e_b3.range.context.start);
5099        (anchor_b2, anchor_b3)
5100    });
5101
5102    multibuffer.update(cx, |multibuffer, cx| {
5103        multibuffer.set_excerpts_for_path(
5104            path_b.clone(),
5105            buffer_b.clone(),
5106            vec![Point::row_range(0..3), Point::row_range(28..36)],
5107            0,
5108            cx,
5109        );
5110    });
5111
5112    multibuffer.update(cx, |multibuffer, cx| {
5113        multibuffer.set_excerpts_for_path(
5114            path_d.clone(),
5115            buffer_d.clone(),
5116            vec![Point::row_range(0..3)],
5117            0,
5118            cx,
5119        );
5120    });
5121
5122    multibuffer.read_with(cx, |multibuffer, cx| {
5123        let snapshot = multibuffer.snapshot(cx);
5124        snapshot.summaries_for_anchors::<Point, _>(&[anchor_in_e_b2, anchor_in_e_b3]);
5125    });
5126}