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