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