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    invert_diffs: bool,
2299}
2300
2301#[derive(Debug)]
2302struct ReferenceExcerpt {
2303    id: ExcerptId,
2304    buffer: Entity<Buffer>,
2305    range: Range<text::Anchor>,
2306    expanded_diff_hunks: Vec<text::Anchor>,
2307}
2308
2309#[derive(Debug)]
2310struct ReferenceRegion {
2311    buffer_id: Option<BufferId>,
2312    range: Range<usize>,
2313    buffer_range: Option<Range<Point>>,
2314    status: Option<DiffHunkStatus>,
2315    excerpt_id: Option<ExcerptId>,
2316}
2317
2318impl ReferenceMultibuffer {
2319    fn expand_excerpts(&mut self, excerpts: &HashSet<ExcerptId>, line_count: u32, cx: &App) {
2320        if line_count == 0 {
2321            return;
2322        }
2323
2324        for id in excerpts {
2325            let excerpt = self.excerpts.iter_mut().find(|e| e.id == *id).unwrap();
2326            let snapshot = excerpt.buffer.read(cx).snapshot();
2327            let mut point_range = excerpt.range.to_point(&snapshot);
2328            point_range.start = Point::new(point_range.start.row.saturating_sub(line_count), 0);
2329            point_range.end =
2330                snapshot.clip_point(Point::new(point_range.end.row + line_count, 0), Bias::Left);
2331            point_range.end.column = snapshot.line_len(point_range.end.row);
2332            excerpt.range =
2333                snapshot.anchor_before(point_range.start)..snapshot.anchor_after(point_range.end);
2334        }
2335    }
2336
2337    fn remove_excerpt(&mut self, id: ExcerptId, cx: &App) {
2338        let ix = self
2339            .excerpts
2340            .iter()
2341            .position(|excerpt| excerpt.id == id)
2342            .unwrap();
2343        let excerpt = self.excerpts.remove(ix);
2344        let buffer = excerpt.buffer.read(cx);
2345        let id = buffer.remote_id();
2346        log::info!(
2347            "Removing excerpt {}: {:?}",
2348            ix,
2349            buffer
2350                .text_for_range(excerpt.range.to_offset(buffer))
2351                .collect::<String>(),
2352        );
2353        if !self
2354            .excerpts
2355            .iter()
2356            .any(|excerpt| excerpt.buffer.read(cx).remote_id() == id)
2357        {
2358            self.diffs.remove(&id);
2359        }
2360    }
2361
2362    fn insert_excerpt_after(
2363        &mut self,
2364        prev_id: ExcerptId,
2365        new_excerpt_id: ExcerptId,
2366        (buffer_handle, anchor_range): (Entity<Buffer>, Range<text::Anchor>),
2367    ) {
2368        let excerpt_ix = if prev_id == ExcerptId::max() {
2369            self.excerpts.len()
2370        } else {
2371            self.excerpts
2372                .iter()
2373                .position(|excerpt| excerpt.id == prev_id)
2374                .unwrap()
2375                + 1
2376        };
2377        self.excerpts.insert(
2378            excerpt_ix,
2379            ReferenceExcerpt {
2380                id: new_excerpt_id,
2381                buffer: buffer_handle,
2382                range: anchor_range,
2383                expanded_diff_hunks: Vec::new(),
2384            },
2385        );
2386    }
2387
2388    fn expand_diff_hunks(&mut self, excerpt_id: ExcerptId, range: Range<text::Anchor>, cx: &App) {
2389        let excerpt = self
2390            .excerpts
2391            .iter_mut()
2392            .find(|e| e.id == excerpt_id)
2393            .unwrap();
2394        let buffer = excerpt.buffer.read(cx).snapshot();
2395        let buffer_id = buffer.remote_id();
2396        let Some(diff) = self.diffs.get(&buffer_id) else {
2397            return;
2398        };
2399        let excerpt_range = excerpt.range.to_offset(&buffer);
2400        for hunk in diff
2401            .read(cx)
2402            .snapshot(cx)
2403            .hunks_intersecting_range(range, &buffer)
2404        {
2405            let hunk_range = hunk.buffer_range.to_offset(&buffer);
2406            if hunk_range.start < excerpt_range.start || hunk_range.start > excerpt_range.end {
2407                continue;
2408            }
2409            if let Err(ix) = excerpt
2410                .expanded_diff_hunks
2411                .binary_search_by(|anchor| anchor.cmp(&hunk.buffer_range.start, &buffer))
2412            {
2413                log::info!(
2414                    "expanding diff hunk {:?}. excerpt:{:?}, excerpt range:{:?}",
2415                    hunk_range,
2416                    excerpt_id,
2417                    excerpt_range
2418                );
2419                excerpt
2420                    .expanded_diff_hunks
2421                    .insert(ix, hunk.buffer_range.start);
2422            } else {
2423                log::trace!("hunk {hunk_range:?} already expanded in excerpt {excerpt_id:?}");
2424            }
2425        }
2426    }
2427
2428    fn expected_content(&self, cx: &App) -> (String, Vec<RowInfo>, HashSet<MultiBufferRow>) {
2429        let mut text = String::new();
2430        let mut regions = Vec::<ReferenceRegion>::new();
2431        let mut excerpt_boundary_rows = HashSet::default();
2432        for excerpt in &self.excerpts {
2433            excerpt_boundary_rows.insert(MultiBufferRow(text.matches('\n').count() as u32));
2434            let buffer = excerpt.buffer.read(cx);
2435            let buffer_range = excerpt.range.to_offset(buffer);
2436            let diff = self
2437                .diffs
2438                .get(&buffer.remote_id())
2439                .unwrap()
2440                .read(cx)
2441                .snapshot(cx);
2442            let base_buffer = diff.base_text();
2443
2444            let mut offset = buffer_range.start;
2445            let hunks = diff
2446                .hunks_intersecting_range(excerpt.range.clone(), buffer)
2447                .peekable();
2448
2449            for hunk in hunks {
2450                // Ignore hunks that are outside the excerpt range.
2451                let mut hunk_range = hunk.buffer_range.to_offset(buffer);
2452
2453                hunk_range.end = hunk_range.end.min(buffer_range.end);
2454                if hunk_range.start > buffer_range.end || hunk_range.start < buffer_range.start {
2455                    log::trace!("skipping hunk outside excerpt range");
2456                    continue;
2457                }
2458
2459                if !excerpt.expanded_diff_hunks.iter().any(|expanded_anchor| {
2460                    expanded_anchor.to_offset(buffer).max(buffer_range.start)
2461                        == hunk_range.start.max(buffer_range.start)
2462                }) {
2463                    log::trace!("skipping a hunk that's not marked as expanded");
2464                    continue;
2465                }
2466
2467                if !hunk.buffer_range.start.is_valid(buffer) {
2468                    log::trace!("skipping hunk with deleted start: {:?}", hunk.range);
2469                    continue;
2470                }
2471
2472                if hunk_range.start >= offset {
2473                    // Add the buffer text before the hunk
2474                    let len = text.len();
2475                    text.extend(buffer.text_for_range(offset..hunk_range.start));
2476                    if text.len() > len {
2477                        regions.push(ReferenceRegion {
2478                            buffer_id: Some(buffer.remote_id()),
2479                            range: len..text.len(),
2480                            buffer_range: Some((offset..hunk_range.start).to_point(&buffer)),
2481                            status: None,
2482                            excerpt_id: Some(excerpt.id),
2483                        });
2484                    }
2485
2486                    // Add the deleted text for the hunk.
2487                    if !hunk.diff_base_byte_range.is_empty() {
2488                        let mut base_text = base_buffer
2489                            .text_for_range(hunk.diff_base_byte_range.clone())
2490                            .collect::<String>();
2491                        if !base_text.ends_with('\n') {
2492                            base_text.push('\n');
2493                        }
2494                        let len = text.len();
2495                        text.push_str(&base_text);
2496                        regions.push(ReferenceRegion {
2497                            buffer_id: Some(base_buffer.remote_id()),
2498                            range: len..text.len(),
2499                            buffer_range: Some(hunk.diff_base_byte_range.to_point(&base_buffer)),
2500                            status: Some(DiffHunkStatus::deleted(hunk.secondary_status)),
2501                            excerpt_id: Some(excerpt.id),
2502                        });
2503                    }
2504
2505                    offset = hunk_range.start;
2506                }
2507
2508                // Add the inserted text for the hunk.
2509                if hunk_range.end > offset {
2510                    let len = text.len();
2511                    text.extend(buffer.text_for_range(offset..hunk_range.end));
2512                    let range = len..text.len();
2513                    let region = ReferenceRegion {
2514                        buffer_id: Some(buffer.remote_id()),
2515                        range,
2516                        buffer_range: Some((offset..hunk_range.end).to_point(&buffer)),
2517                        status: Some(DiffHunkStatus::added(hunk.secondary_status)),
2518                        excerpt_id: Some(excerpt.id),
2519                    };
2520                    offset = hunk_range.end;
2521                    regions.push(region);
2522                }
2523            }
2524
2525            // Add the buffer text for the rest of the excerpt.
2526            let len = text.len();
2527            text.extend(buffer.text_for_range(offset..buffer_range.end));
2528            text.push('\n');
2529            regions.push(ReferenceRegion {
2530                buffer_id: Some(buffer.remote_id()),
2531                range: len..text.len(),
2532                buffer_range: Some((offset..buffer_range.end).to_point(&buffer)),
2533                status: None,
2534                excerpt_id: Some(excerpt.id),
2535            });
2536        }
2537
2538        // Remove final trailing newline.
2539        if self.excerpts.is_empty() {
2540            regions.push(ReferenceRegion {
2541                buffer_id: None,
2542                range: 0..1,
2543                buffer_range: Some(Point::new(0, 0)..Point::new(0, 1)),
2544                status: None,
2545                excerpt_id: None,
2546            });
2547        } else {
2548            text.pop();
2549        }
2550
2551        // Retrieve the row info using the region that contains
2552        // the start of each multi-buffer line.
2553        let mut ix = 0;
2554        let row_infos = text
2555            .split('\n')
2556            .map(|line| {
2557                let row_info = regions
2558                    .iter()
2559                    .position(|region| region.range.contains(&ix))
2560                    .map_or(RowInfo::default(), |region_ix| {
2561                        let region = &regions[region_ix];
2562                        let buffer_row = region.buffer_range.as_ref().map(|buffer_range| {
2563                            buffer_range.start.row
2564                                + text[region.range.start..ix].matches('\n').count() as u32
2565                        });
2566                        let main_buffer = self
2567                            .excerpts
2568                            .iter()
2569                            .find(|e| e.id == region.excerpt_id.unwrap())
2570                            .map(|e| e.buffer.clone());
2571                        let is_excerpt_start = region_ix == 0
2572                            || &regions[region_ix - 1].excerpt_id != &region.excerpt_id
2573                            || regions[region_ix - 1].range.is_empty();
2574                        let mut is_excerpt_end = region_ix == regions.len() - 1
2575                            || &regions[region_ix + 1].excerpt_id != &region.excerpt_id;
2576                        let is_start = !text[region.range.start..ix].contains('\n');
2577                        let mut is_end = if region.range.end > text.len() {
2578                            !text[ix..].contains('\n')
2579                        } else {
2580                            text[ix..region.range.end.min(text.len())]
2581                                .matches('\n')
2582                                .count()
2583                                == 1
2584                        };
2585                        if region_ix < regions.len() - 1
2586                            && !text[ix..].contains("\n")
2587                            && region.status == Some(DiffHunkStatus::added_none())
2588                            && regions[region_ix + 1].excerpt_id == region.excerpt_id
2589                            && regions[region_ix + 1].range.start == text.len()
2590                        {
2591                            is_end = true;
2592                            is_excerpt_end = true;
2593                        }
2594                        let multibuffer_row =
2595                            MultiBufferRow(text[..ix].matches('\n').count() as u32);
2596                        let mut expand_direction = None;
2597                        if let Some(buffer) = &main_buffer {
2598                            let buffer_row = buffer_row.unwrap();
2599                            let needs_expand_up = is_excerpt_start && is_start && buffer_row > 0;
2600                            let needs_expand_down = is_excerpt_end
2601                                && is_end
2602                                && buffer.read(cx).max_point().row > buffer_row;
2603                            expand_direction = if needs_expand_up && needs_expand_down {
2604                                Some(ExpandExcerptDirection::UpAndDown)
2605                            } else if needs_expand_up {
2606                                Some(ExpandExcerptDirection::Up)
2607                            } else if needs_expand_down {
2608                                Some(ExpandExcerptDirection::Down)
2609                            } else {
2610                                None
2611                            };
2612                        }
2613                        RowInfo {
2614                            buffer_id: region.buffer_id,
2615                            diff_status: region.status,
2616                            buffer_row,
2617                            wrapped_buffer_row: None,
2618
2619                            multibuffer_row: Some(multibuffer_row),
2620                            expand_info: expand_direction.zip(region.excerpt_id).map(
2621                                |(direction, excerpt_id)| ExpandInfo {
2622                                    direction,
2623                                    excerpt_id,
2624                                },
2625                            ),
2626                        }
2627                    });
2628                ix += line.len() + 1;
2629                row_info
2630            })
2631            .collect();
2632
2633        (text, row_infos, excerpt_boundary_rows)
2634    }
2635
2636    fn diffs_updated(&mut self, cx: &App) {
2637        for excerpt in &mut self.excerpts {
2638            let buffer = excerpt.buffer.read(cx).snapshot();
2639            let excerpt_range = excerpt.range.to_offset(&buffer);
2640            let buffer_id = buffer.remote_id();
2641            let diff = self.diffs.get(&buffer_id).unwrap().read(cx).snapshot(cx);
2642            let mut hunks = diff.hunks_in_row_range(0..u32::MAX, &buffer).peekable();
2643            excerpt.expanded_diff_hunks.retain(|hunk_anchor| {
2644                if !hunk_anchor.is_valid(&buffer) {
2645                    return false;
2646                }
2647                while let Some(hunk) = hunks.peek() {
2648                    match hunk.buffer_range.start.cmp(hunk_anchor, &buffer) {
2649                        cmp::Ordering::Less => {
2650                            hunks.next();
2651                        }
2652                        cmp::Ordering::Equal => {
2653                            let hunk_range = hunk.buffer_range.to_offset(&buffer);
2654                            return hunk_range.end >= excerpt_range.start
2655                                && hunk_range.start <= excerpt_range.end;
2656                        }
2657                        cmp::Ordering::Greater => break,
2658                    }
2659                }
2660                false
2661            });
2662        }
2663    }
2664
2665    fn add_diff(&mut self, diff: Entity<BufferDiff>, cx: &mut App) {
2666        let buffer_id = diff.read(cx).buffer_id;
2667        self.diffs.insert(buffer_id, diff);
2668    }
2669}
2670
2671#[gpui::test(iterations = 100)]
2672async fn test_random_set_ranges(cx: &mut TestAppContext, mut rng: StdRng) {
2673    let base_text = "a\n".repeat(100);
2674    let buf = cx.update(|cx| cx.new(|cx| Buffer::local(base_text, cx)));
2675    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2676
2677    let operations = env::var("OPERATIONS")
2678        .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2679        .unwrap_or(10);
2680
2681    fn row_ranges(ranges: &Vec<Range<Point>>) -> Vec<Range<u32>> {
2682        ranges
2683            .iter()
2684            .map(|range| range.start.row..range.end.row)
2685            .collect()
2686    }
2687
2688    for _ in 0..operations {
2689        let snapshot = buf.update(cx, |buf, _| buf.snapshot());
2690        let num_ranges = rng.random_range(0..=10);
2691        let max_row = snapshot.max_point().row;
2692        let mut ranges = (0..num_ranges)
2693            .map(|_| {
2694                let start = rng.random_range(0..max_row);
2695                let end = rng.random_range(start + 1..max_row + 1);
2696                Point::row_range(start..end)
2697            })
2698            .collect::<Vec<_>>();
2699        ranges.sort_by_key(|range| range.start);
2700        log::info!("Setting ranges: {:?}", row_ranges(&ranges));
2701        let (created, _) = multibuffer.update(cx, |multibuffer, cx| {
2702            multibuffer.set_excerpts_for_path(
2703                PathKey::for_buffer(&buf, cx),
2704                buf.clone(),
2705                ranges.clone(),
2706                2,
2707                cx,
2708            )
2709        });
2710
2711        assert_eq!(created.len(), ranges.len());
2712
2713        let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2714        let mut last_end = None;
2715        let mut seen_ranges = Vec::default();
2716
2717        for (_, buf, range) in snapshot.excerpts() {
2718            let start = range.context.start.to_point(buf);
2719            let end = range.context.end.to_point(buf);
2720            seen_ranges.push(start..end);
2721
2722            if let Some(last_end) = last_end.take() {
2723                assert!(
2724                    start > last_end,
2725                    "multibuffer has out-of-order ranges: {:?}; {:?} <= {:?}",
2726                    row_ranges(&seen_ranges),
2727                    start,
2728                    last_end
2729                )
2730            }
2731
2732            ranges.retain(|range| range.start < start || range.end > end);
2733
2734            last_end = Some(end)
2735        }
2736
2737        assert!(
2738            ranges.is_empty(),
2739            "multibuffer {:?} did not include all ranges: {:?}",
2740            row_ranges(&seen_ranges),
2741            row_ranges(&ranges)
2742        );
2743    }
2744}
2745
2746#[gpui::test(iterations = 100)]
2747async fn test_random_multibuffer(cx: &mut TestAppContext, rng: StdRng) {
2748    test_random_multibuffer_impl(cx, rng).await;
2749}
2750
2751async fn test_random_multibuffer_impl(cx: &mut TestAppContext, mut rng: StdRng) {
2752    let operations = env::var("OPERATIONS")
2753        .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
2754        .unwrap_or(10);
2755
2756    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
2757    let mut buffers: Vec<Entity<Buffer>> = Vec::new();
2758    let mut base_texts: HashMap<BufferId, String> = HashMap::default();
2759    let mut reference = ReferenceMultibuffer::default();
2760    let mut anchors = Vec::new();
2761    let mut old_versions = Vec::new();
2762    let mut needs_diff_calculation = false;
2763
2764    for _ in 0..operations {
2765        match rng.random_range(0..100) {
2766            0..=14 if !buffers.is_empty() => {
2767                let buffer = buffers.choose(&mut rng).unwrap();
2768                buffer.update(cx, |buf, cx| {
2769                    let edit_count = rng.random_range(1..5);
2770                    buf.randomly_edit(&mut rng, edit_count, cx);
2771                    log::info!("buffer text:\n{}", buf.text());
2772                    needs_diff_calculation = true;
2773                });
2774                cx.update(|cx| reference.diffs_updated(cx));
2775            }
2776            15..=19 if !reference.excerpts.is_empty() => {
2777                multibuffer.update(cx, |multibuffer, cx| {
2778                    let ids = multibuffer.excerpt_ids();
2779                    let mut excerpts = HashSet::default();
2780                    for _ in 0..rng.random_range(0..ids.len()) {
2781                        excerpts.extend(ids.choose(&mut rng).copied());
2782                    }
2783
2784                    let line_count = rng.random_range(0..5);
2785
2786                    let excerpt_ixs = excerpts
2787                        .iter()
2788                        .map(|id| reference.excerpts.iter().position(|e| e.id == *id).unwrap())
2789                        .collect::<Vec<_>>();
2790                    log::info!("Expanding excerpts {excerpt_ixs:?} by {line_count} lines");
2791                    multibuffer.expand_excerpts(
2792                        excerpts.iter().cloned(),
2793                        line_count,
2794                        ExpandExcerptDirection::UpAndDown,
2795                        cx,
2796                    );
2797
2798                    reference.expand_excerpts(&excerpts, line_count, cx);
2799                });
2800            }
2801            20..=29 if !reference.excerpts.is_empty() => {
2802                let mut ids_to_remove = vec![];
2803                for _ in 0..rng.random_range(1..=3) {
2804                    let Some(excerpt) = reference.excerpts.choose(&mut rng) else {
2805                        break;
2806                    };
2807                    let id = excerpt.id;
2808                    cx.update(|cx| reference.remove_excerpt(id, cx));
2809                    ids_to_remove.push(id);
2810                }
2811                let snapshot =
2812                    multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2813                ids_to_remove.sort_unstable_by(|a, b| a.cmp(b, &snapshot));
2814                drop(snapshot);
2815                multibuffer.update(cx, |multibuffer, cx| {
2816                    multibuffer.remove_excerpts(ids_to_remove, cx)
2817                });
2818            }
2819            30..=39 if !reference.excerpts.is_empty() => {
2820                let multibuffer =
2821                    multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2822                let offset = multibuffer.clip_offset(
2823                    MultiBufferOffset(rng.random_range(0..=multibuffer.len().0)),
2824                    Bias::Left,
2825                );
2826                let bias = if rng.random() {
2827                    Bias::Left
2828                } else {
2829                    Bias::Right
2830                };
2831                log::info!("Creating anchor at {} with bias {:?}", offset.0, bias);
2832                anchors.push(multibuffer.anchor_at(offset, bias));
2833                anchors.sort_by(|a, b| a.cmp(b, &multibuffer));
2834            }
2835            40..=44 if !anchors.is_empty() => {
2836                let multibuffer =
2837                    multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2838                let prev_len = anchors.len();
2839                anchors = multibuffer
2840                    .refresh_anchors(&anchors)
2841                    .into_iter()
2842                    .map(|a| a.1)
2843                    .collect();
2844
2845                // Ensure the newly-refreshed anchors point to a valid excerpt and don't
2846                // overshoot its boundaries.
2847                assert_eq!(anchors.len(), prev_len);
2848                for anchor in &anchors {
2849                    if anchor.excerpt_id == ExcerptId::min()
2850                        || anchor.excerpt_id == ExcerptId::max()
2851                    {
2852                        continue;
2853                    }
2854
2855                    let excerpt = multibuffer.excerpt(anchor.excerpt_id).unwrap();
2856                    assert_eq!(excerpt.id, anchor.excerpt_id);
2857                    assert!(excerpt.contains(anchor));
2858                }
2859            }
2860            45..=55 if !reference.excerpts.is_empty() => {
2861                multibuffer.update(cx, |multibuffer, cx| {
2862                    let snapshot = multibuffer.snapshot(cx);
2863                    let excerpt_ix = rng.random_range(0..reference.excerpts.len());
2864                    let excerpt = &reference.excerpts[excerpt_ix];
2865                    let start = excerpt.range.start;
2866                    let end = excerpt.range.end;
2867                    let range = snapshot.anchor_in_excerpt(excerpt.id, start).unwrap()
2868                        ..snapshot.anchor_in_excerpt(excerpt.id, end).unwrap();
2869
2870                    log::info!(
2871                        "expanding diff hunks in range {:?} (excerpt id {:?}, index {excerpt_ix:?}, buffer id {:?})",
2872                        range.to_offset(&snapshot),
2873                        excerpt.id,
2874                        excerpt.buffer.read(cx).remote_id(),
2875                    );
2876                    reference.expand_diff_hunks(excerpt.id, start..end, cx);
2877                    multibuffer.expand_diff_hunks(vec![range], cx);
2878                });
2879            }
2880            56..=85 if needs_diff_calculation => {
2881                multibuffer.update(cx, |multibuffer, cx| {
2882                    for buffer in multibuffer.all_buffers() {
2883                        let snapshot = buffer.read(cx).snapshot();
2884                        multibuffer.diff_for(snapshot.remote_id()).unwrap().update(
2885                            cx,
2886                            |diff, cx| {
2887                                log::info!(
2888                                    "recalculating diff for buffer {:?}",
2889                                    snapshot.remote_id(),
2890                                );
2891                                diff.recalculate_diff_sync(&snapshot.text, cx);
2892                            },
2893                        );
2894                    }
2895                    reference.diffs_updated(cx);
2896                    needs_diff_calculation = false;
2897                });
2898            }
2899            _ => {
2900                let buffer_handle = if buffers.is_empty() || rng.random_bool(0.4) {
2901                    let mut base_text = util::RandomCharIter::new(&mut rng)
2902                        .take(256)
2903                        .collect::<String>();
2904
2905                    let buffer = cx.new(|cx| Buffer::local(base_text.clone(), cx));
2906                    text::LineEnding::normalize(&mut base_text);
2907                    base_texts.insert(
2908                        buffer.read_with(cx, |buffer, _| buffer.remote_id()),
2909                        base_text,
2910                    );
2911                    buffers.push(buffer);
2912                    buffers.last().unwrap()
2913                } else {
2914                    buffers.choose(&mut rng).unwrap()
2915                };
2916
2917                let prev_excerpt_ix = rng.random_range(0..=reference.excerpts.len());
2918                let prev_excerpt_id = reference
2919                    .excerpts
2920                    .get(prev_excerpt_ix)
2921                    .map_or(ExcerptId::max(), |e| e.id);
2922                let excerpt_ix = (prev_excerpt_ix + 1).min(reference.excerpts.len());
2923
2924                let (range, anchor_range) = buffer_handle.read_with(cx, |buffer, _| {
2925                    let end_row = rng.random_range(0..=buffer.max_point().row);
2926                    let start_row = rng.random_range(0..=end_row);
2927                    let end_ix = buffer.point_to_offset(Point::new(end_row, 0));
2928                    let start_ix = buffer.point_to_offset(Point::new(start_row, 0));
2929                    let anchor_range = buffer.anchor_before(start_ix)..buffer.anchor_after(end_ix);
2930
2931                    log::info!(
2932                        "Inserting excerpt at {} of {} for buffer {}: {:?}[{:?}] = {:?}",
2933                        excerpt_ix,
2934                        reference.excerpts.len(),
2935                        buffer.remote_id(),
2936                        buffer.text(),
2937                        start_ix..end_ix,
2938                        &buffer.text()[start_ix..end_ix]
2939                    );
2940
2941                    (start_ix..end_ix, anchor_range)
2942                });
2943
2944                let excerpt_id = multibuffer.update(cx, |multibuffer, cx| {
2945                    multibuffer
2946                        .insert_excerpts_after(
2947                            prev_excerpt_id,
2948                            buffer_handle.clone(),
2949                            [ExcerptRange::new(range.clone())],
2950                            cx,
2951                        )
2952                        .pop()
2953                        .unwrap()
2954                });
2955
2956                reference.insert_excerpt_after(
2957                    prev_excerpt_id,
2958                    excerpt_id,
2959                    (buffer_handle.clone(), anchor_range),
2960                );
2961
2962                multibuffer.update(cx, |multibuffer, cx| {
2963                    let id = buffer_handle.read(cx).remote_id();
2964                    if multibuffer.diff_for(id).is_none() {
2965                        let base_text = base_texts.get(&id).unwrap();
2966                        let diff = cx.new(|cx| {
2967                            BufferDiff::new_with_base_text(
2968                                base_text,
2969                                &buffer_handle.read(cx).text_snapshot(),
2970                                cx,
2971                            )
2972                        });
2973                        reference.add_diff(diff.clone(), cx);
2974                        multibuffer.add_diff(diff, cx)
2975                    }
2976                });
2977            }
2978        }
2979
2980        if rng.random_bool(0.3) {
2981            multibuffer.update(cx, |multibuffer, cx| {
2982                old_versions.push((multibuffer.snapshot(cx), multibuffer.subscribe()));
2983            })
2984        }
2985
2986        multibuffer.read_with(cx, |multibuffer, cx| {
2987            check_multibuffer(multibuffer, &reference, &anchors, cx, &mut rng);
2988        });
2989    }
2990
2991    let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
2992    for (old_snapshot, subscription) in old_versions {
2993        check_multibuffer_edits(&snapshot, &old_snapshot, subscription);
2994    }
2995}
2996
2997fn check_multibuffer(
2998    multibuffer: &MultiBuffer,
2999    reference: &ReferenceMultibuffer,
3000    anchors: &[Anchor],
3001    cx: &App,
3002    rng: &mut StdRng,
3003) {
3004    let snapshot = multibuffer.snapshot(cx);
3005    let actual_text = snapshot.text();
3006    let actual_boundary_rows = snapshot
3007        .excerpt_boundaries_in_range(MultiBufferOffset(0)..)
3008        .map(|b| b.row)
3009        .collect::<HashSet<_>>();
3010    let actual_row_infos = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
3011
3012    let (expected_text, expected_row_infos, expected_boundary_rows) =
3013        reference.expected_content(cx);
3014
3015    let has_diff = actual_row_infos
3016        .iter()
3017        .any(|info| info.diff_status.is_some())
3018        || expected_row_infos
3019            .iter()
3020            .any(|info| info.diff_status.is_some());
3021    let actual_diff = format_diff(
3022        &actual_text,
3023        &actual_row_infos,
3024        &actual_boundary_rows,
3025        Some(has_diff),
3026    );
3027    let expected_diff = format_diff(
3028        &expected_text,
3029        &expected_row_infos,
3030        &expected_boundary_rows,
3031        Some(has_diff),
3032    );
3033
3034    log::info!("Multibuffer content:\n{}", actual_diff);
3035
3036    assert_eq!(
3037        actual_row_infos.len(),
3038        actual_text.split('\n').count(),
3039        "line count: {}",
3040        actual_text.split('\n').count()
3041    );
3042    pretty_assertions::assert_eq!(actual_diff, expected_diff);
3043    pretty_assertions::assert_eq!(actual_text, expected_text);
3044    pretty_assertions::assert_eq!(actual_row_infos, expected_row_infos);
3045
3046    for _ in 0..5 {
3047        let start_row = rng.random_range(0..=expected_row_infos.len());
3048        assert_eq!(
3049            snapshot
3050                .row_infos(MultiBufferRow(start_row as u32))
3051                .collect::<Vec<_>>(),
3052            &expected_row_infos[start_row..],
3053            "buffer_rows({})",
3054            start_row
3055        );
3056    }
3057
3058    assert_eq!(
3059        snapshot.widest_line_number(),
3060        expected_row_infos
3061            .into_iter()
3062            .filter_map(|info| {
3063                if info.diff_status.is_some_and(|status| status.is_deleted()) {
3064                    None
3065                } else {
3066                    info.buffer_row
3067                }
3068            })
3069            .max()
3070            .unwrap()
3071            + 1
3072    );
3073    let reference_ranges = reference
3074        .excerpts
3075        .iter()
3076        .map(|excerpt| {
3077            (
3078                excerpt.id,
3079                excerpt.range.to_offset(&excerpt.buffer.read(cx).snapshot()),
3080            )
3081        })
3082        .collect::<HashMap<_, _>>();
3083    for i in 0..snapshot.len().0 {
3084        let excerpt = snapshot
3085            .excerpt_containing(MultiBufferOffset(i)..MultiBufferOffset(i))
3086            .unwrap();
3087        assert_eq!(
3088            excerpt.buffer_range().start.0..excerpt.buffer_range().end.0,
3089            reference_ranges[&excerpt.id()]
3090        );
3091    }
3092
3093    assert_consistent_line_numbers(&snapshot);
3094    assert_position_translation(&snapshot);
3095
3096    for (row, line) in expected_text.split('\n').enumerate() {
3097        assert_eq!(
3098            snapshot.line_len(MultiBufferRow(row as u32)),
3099            line.len() as u32,
3100            "line_len({}).",
3101            row
3102        );
3103    }
3104
3105    let text_rope = Rope::from(expected_text.as_str());
3106    for _ in 0..10 {
3107        let end_ix = text_rope.clip_offset(rng.random_range(0..=text_rope.len()), Bias::Right);
3108        let start_ix = text_rope.clip_offset(rng.random_range(0..=end_ix), Bias::Left);
3109
3110        let text_for_range = snapshot
3111            .text_for_range(MultiBufferOffset(start_ix)..MultiBufferOffset(end_ix))
3112            .collect::<String>();
3113        assert_eq!(
3114            text_for_range,
3115            &expected_text[start_ix..end_ix],
3116            "incorrect text for range {:?}",
3117            start_ix..end_ix
3118        );
3119
3120        let expected_summary =
3121            MBTextSummary::from(TextSummary::from(&expected_text[start_ix..end_ix]));
3122        assert_eq!(
3123            snapshot.text_summary_for_range::<MBTextSummary, _>(
3124                MultiBufferOffset(start_ix)..MultiBufferOffset(end_ix)
3125            ),
3126            expected_summary,
3127            "incorrect summary for range {:?}",
3128            start_ix..end_ix
3129        );
3130    }
3131
3132    // Anchor resolution
3133    let summaries = snapshot.summaries_for_anchors::<MultiBufferOffset, _>(anchors);
3134    assert_eq!(anchors.len(), summaries.len());
3135    for (anchor, resolved_offset) in anchors.iter().zip(summaries) {
3136        assert!(resolved_offset <= snapshot.len());
3137        assert_eq!(
3138            snapshot.summary_for_anchor::<MultiBufferOffset>(anchor),
3139            resolved_offset,
3140            "anchor: {:?}",
3141            anchor
3142        );
3143    }
3144
3145    for _ in 0..10 {
3146        let end_ix = text_rope.clip_offset(rng.random_range(0..=text_rope.len()), Bias::Right);
3147        assert_eq!(
3148            snapshot
3149                .reversed_chars_at(MultiBufferOffset(end_ix))
3150                .collect::<String>(),
3151            expected_text[..end_ix].chars().rev().collect::<String>(),
3152        );
3153    }
3154
3155    for _ in 0..10 {
3156        let end_ix = rng.random_range(0..=text_rope.len());
3157        let end_ix = text_rope.floor_char_boundary(end_ix);
3158        let start_ix = rng.random_range(0..=end_ix);
3159        let start_ix = text_rope.floor_char_boundary(start_ix);
3160        assert_eq!(
3161            snapshot
3162                .bytes_in_range(MultiBufferOffset(start_ix)..MultiBufferOffset(end_ix))
3163                .flatten()
3164                .copied()
3165                .collect::<Vec<_>>(),
3166            expected_text.as_bytes()[start_ix..end_ix].to_vec(),
3167            "bytes_in_range({:?})",
3168            start_ix..end_ix,
3169        );
3170    }
3171}
3172
3173fn check_multibuffer_edits(
3174    snapshot: &MultiBufferSnapshot,
3175    old_snapshot: &MultiBufferSnapshot,
3176    subscription: Subscription<MultiBufferOffset>,
3177) {
3178    let edits = subscription.consume().into_inner();
3179
3180    log::info!(
3181        "applying subscription edits to old text: {:?}: {:#?}",
3182        old_snapshot.text(),
3183        edits,
3184    );
3185
3186    let mut text = old_snapshot.text();
3187    for edit in edits {
3188        let new_text: String = snapshot
3189            .text_for_range(edit.new.start..edit.new.end)
3190            .collect();
3191        text.replace_range(
3192            (edit.new.start.0..edit.new.start.0 + (edit.old.end.0 - edit.old.start.0)).clone(),
3193            &new_text,
3194        );
3195        pretty_assertions::assert_eq!(
3196            &text[0..edit.new.end.0],
3197            snapshot
3198                .text_for_range(MultiBufferOffset(0)..edit.new.end)
3199                .collect::<String>()
3200        );
3201    }
3202    pretty_assertions::assert_eq!(text, snapshot.text());
3203}
3204
3205#[gpui::test]
3206fn test_history(cx: &mut App) {
3207    let test_settings = SettingsStore::test(cx);
3208    cx.set_global(test_settings);
3209
3210    let group_interval: Duration = Duration::from_millis(1);
3211    let buffer_1 = cx.new(|cx| {
3212        let mut buf = Buffer::local("1234", cx);
3213        buf.set_group_interval(group_interval);
3214        buf
3215    });
3216    let buffer_2 = cx.new(|cx| {
3217        let mut buf = Buffer::local("5678", cx);
3218        buf.set_group_interval(group_interval);
3219        buf
3220    });
3221    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
3222    multibuffer.update(cx, |this, _| {
3223        this.set_group_interval(group_interval);
3224    });
3225    multibuffer.update(cx, |multibuffer, cx| {
3226        multibuffer.push_excerpts(
3227            buffer_1.clone(),
3228            [ExcerptRange::new(0..buffer_1.read(cx).len())],
3229            cx,
3230        );
3231        multibuffer.push_excerpts(
3232            buffer_2.clone(),
3233            [ExcerptRange::new(0..buffer_2.read(cx).len())],
3234            cx,
3235        );
3236    });
3237
3238    let mut now = Instant::now();
3239
3240    multibuffer.update(cx, |multibuffer, cx| {
3241        let transaction_1 = multibuffer.start_transaction_at(now, cx).unwrap();
3242        multibuffer.edit(
3243            [
3244                (Point::new(0, 0)..Point::new(0, 0), "A"),
3245                (Point::new(1, 0)..Point::new(1, 0), "A"),
3246            ],
3247            None,
3248            cx,
3249        );
3250        multibuffer.edit(
3251            [
3252                (Point::new(0, 1)..Point::new(0, 1), "B"),
3253                (Point::new(1, 1)..Point::new(1, 1), "B"),
3254            ],
3255            None,
3256            cx,
3257        );
3258        multibuffer.end_transaction_at(now, cx);
3259        assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3260
3261        // Verify edited ranges for transaction 1
3262        assert_eq!(
3263            multibuffer.edited_ranges_for_transaction(transaction_1, cx),
3264            &[
3265                Point::new(0, 0)..Point::new(0, 2),
3266                Point::new(1, 0)..Point::new(1, 2)
3267            ]
3268        );
3269
3270        // Edit buffer 1 through the multibuffer
3271        now += 2 * group_interval;
3272        multibuffer.start_transaction_at(now, cx);
3273        multibuffer.edit(
3274            [(MultiBufferOffset(2)..MultiBufferOffset(2), "C")],
3275            None,
3276            cx,
3277        );
3278        multibuffer.end_transaction_at(now, cx);
3279        assert_eq!(multibuffer.read(cx).text(), "ABC1234\nAB5678");
3280
3281        // Edit buffer 1 independently
3282        buffer_1.update(cx, |buffer_1, cx| {
3283            buffer_1.start_transaction_at(now);
3284            buffer_1.edit([(3..3, "D")], None, cx);
3285            buffer_1.end_transaction_at(now, cx);
3286
3287            now += 2 * group_interval;
3288            buffer_1.start_transaction_at(now);
3289            buffer_1.edit([(4..4, "E")], None, cx);
3290            buffer_1.end_transaction_at(now, cx);
3291        });
3292        assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
3293
3294        // An undo in the multibuffer undoes the multibuffer transaction
3295        // and also any individual buffer edits that have occurred since
3296        // that transaction.
3297        multibuffer.undo(cx);
3298        assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3299
3300        multibuffer.undo(cx);
3301        assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3302
3303        multibuffer.redo(cx);
3304        assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3305
3306        multibuffer.redo(cx);
3307        assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\nAB5678");
3308
3309        // Undo buffer 2 independently.
3310        buffer_2.update(cx, |buffer_2, cx| buffer_2.undo(cx));
3311        assert_eq!(multibuffer.read(cx).text(), "ABCDE1234\n5678");
3312
3313        // An undo in the multibuffer undoes the components of the
3314        // the last multibuffer transaction that are not already undone.
3315        multibuffer.undo(cx);
3316        assert_eq!(multibuffer.read(cx).text(), "AB1234\n5678");
3317
3318        multibuffer.undo(cx);
3319        assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3320
3321        multibuffer.redo(cx);
3322        assert_eq!(multibuffer.read(cx).text(), "AB1234\nAB5678");
3323
3324        buffer_1.update(cx, |buffer_1, cx| buffer_1.redo(cx));
3325        assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
3326
3327        // Redo stack gets cleared after an edit.
3328        now += 2 * group_interval;
3329        multibuffer.start_transaction_at(now, cx);
3330        multibuffer.edit(
3331            [(MultiBufferOffset(0)..MultiBufferOffset(0), "X")],
3332            None,
3333            cx,
3334        );
3335        multibuffer.end_transaction_at(now, cx);
3336        assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3337        multibuffer.redo(cx);
3338        assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3339        multibuffer.undo(cx);
3340        assert_eq!(multibuffer.read(cx).text(), "ABCD1234\nAB5678");
3341        multibuffer.undo(cx);
3342        assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3343
3344        // Transactions can be grouped manually.
3345        multibuffer.redo(cx);
3346        multibuffer.redo(cx);
3347        assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3348        multibuffer.group_until_transaction(transaction_1, cx);
3349        multibuffer.undo(cx);
3350        assert_eq!(multibuffer.read(cx).text(), "1234\n5678");
3351        multibuffer.redo(cx);
3352        assert_eq!(multibuffer.read(cx).text(), "XABCD1234\nAB5678");
3353    });
3354}
3355
3356#[gpui::test]
3357async fn test_enclosing_indent(cx: &mut TestAppContext) {
3358    async fn enclosing_indent(
3359        text: &str,
3360        buffer_row: u32,
3361        cx: &mut TestAppContext,
3362    ) -> Option<(Range<u32>, LineIndent)> {
3363        let buffer = cx.update(|cx| MultiBuffer::build_simple(text, cx));
3364        let snapshot = cx.read(|cx| buffer.read(cx).snapshot(cx));
3365        let (range, indent) = snapshot
3366            .enclosing_indent(MultiBufferRow(buffer_row))
3367            .await?;
3368        Some((range.start.0..range.end.0, indent))
3369    }
3370
3371    assert_eq!(
3372        enclosing_indent(
3373            indoc!(
3374                "
3375                fn b() {
3376                    if c {
3377                        let d = 2;
3378                    }
3379                }
3380                "
3381            ),
3382            1,
3383            cx,
3384        )
3385        .await,
3386        Some((
3387            1..2,
3388            LineIndent {
3389                tabs: 0,
3390                spaces: 4,
3391                line_blank: false,
3392            }
3393        ))
3394    );
3395
3396    assert_eq!(
3397        enclosing_indent(
3398            indoc!(
3399                "
3400                fn b() {
3401                    if c {
3402                        let d = 2;
3403                    }
3404                }
3405                "
3406            ),
3407            2,
3408            cx,
3409        )
3410        .await,
3411        Some((
3412            1..2,
3413            LineIndent {
3414                tabs: 0,
3415                spaces: 4,
3416                line_blank: false,
3417            }
3418        ))
3419    );
3420
3421    assert_eq!(
3422        enclosing_indent(
3423            indoc!(
3424                "
3425                fn b() {
3426                    if c {
3427                        let d = 2;
3428
3429                        let e = 5;
3430                    }
3431                }
3432                "
3433            ),
3434            3,
3435            cx,
3436        )
3437        .await,
3438        Some((
3439            1..4,
3440            LineIndent {
3441                tabs: 0,
3442                spaces: 4,
3443                line_blank: false,
3444            }
3445        ))
3446    );
3447}
3448
3449#[gpui::test]
3450async fn test_summaries_for_anchors(cx: &mut TestAppContext) {
3451    let base_text_1 = indoc!(
3452        "
3453        bar
3454        "
3455    );
3456    let text_1 = indoc!(
3457        "
3458        BAR
3459        "
3460    );
3461    let base_text_2 = indoc!(
3462        "
3463        foo
3464        "
3465    );
3466    let text_2 = indoc!(
3467        "
3468        FOO
3469        "
3470    );
3471
3472    let buffer_1 = cx.new(|cx| Buffer::local(text_1, cx));
3473    let buffer_2 = cx.new(|cx| Buffer::local(text_2, cx));
3474    let diff_1 = cx.new(|cx| {
3475        BufferDiff::new_with_base_text(base_text_1, &buffer_1.read(cx).text_snapshot(), cx)
3476    });
3477    let diff_2 = cx.new(|cx| {
3478        BufferDiff::new_with_base_text(base_text_2, &buffer_2.read(cx).text_snapshot(), cx)
3479    });
3480    cx.run_until_parked();
3481
3482    let mut ids = vec![];
3483    let multibuffer = cx.new(|cx| {
3484        let mut multibuffer = MultiBuffer::new(Capability::ReadWrite);
3485        multibuffer.set_all_diff_hunks_expanded(cx);
3486        ids.extend(multibuffer.push_excerpts(
3487            buffer_1.clone(),
3488            [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
3489            cx,
3490        ));
3491        ids.extend(multibuffer.push_excerpts(
3492            buffer_2.clone(),
3493            [ExcerptRange::new(text::Anchor::MIN..text::Anchor::MAX)],
3494            cx,
3495        ));
3496        multibuffer.add_diff(diff_1.clone(), cx);
3497        multibuffer.add_diff(diff_2.clone(), cx);
3498        multibuffer
3499    });
3500
3501    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3502        (multibuffer.snapshot(cx), multibuffer.subscribe())
3503    });
3504
3505    assert_new_snapshot(
3506        &multibuffer,
3507        &mut snapshot,
3508        &mut subscription,
3509        cx,
3510        indoc!(
3511            "
3512            - bar
3513            + BAR
3514
3515            - foo
3516            + FOO
3517            "
3518        ),
3519    );
3520
3521    let anchor_1 = Anchor::in_buffer(ids[0], text::Anchor::MIN);
3522    let point_1 = snapshot.summaries_for_anchors::<Point, _>([&anchor_1])[0];
3523    assert_eq!(point_1, Point::new(0, 0));
3524
3525    let anchor_2 = Anchor::in_buffer(ids[1], text::Anchor::MIN);
3526    let point_2 = snapshot.summaries_for_anchors::<Point, _>([&anchor_2])[0];
3527    assert_eq!(point_2, Point::new(3, 0));
3528}
3529
3530#[gpui::test]
3531async fn test_trailing_deletion_without_newline(cx: &mut TestAppContext) {
3532    let base_text_1 = "one\ntwo".to_owned();
3533    let text_1 = "one\n".to_owned();
3534
3535    let buffer_1 = cx.new(|cx| Buffer::local(text_1, cx));
3536    let diff_1 = cx.new(|cx| {
3537        BufferDiff::new_with_base_text(&base_text_1, &buffer_1.read(cx).text_snapshot(), cx)
3538    });
3539    cx.run_until_parked();
3540
3541    let multibuffer = cx.new(|cx| {
3542        let mut multibuffer = MultiBuffer::singleton(buffer_1.clone(), cx);
3543        multibuffer.add_diff(diff_1.clone(), cx);
3544        multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
3545        multibuffer
3546    });
3547
3548    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3549        (multibuffer.snapshot(cx), multibuffer.subscribe())
3550    });
3551
3552    assert_new_snapshot(
3553        &multibuffer,
3554        &mut snapshot,
3555        &mut subscription,
3556        cx,
3557        indoc!(
3558            "
3559              one
3560            - two
3561            "
3562        ),
3563    );
3564
3565    assert_eq!(snapshot.max_point(), Point::new(2, 0));
3566    assert_eq!(snapshot.len().0, 8);
3567
3568    assert_eq!(
3569        snapshot
3570            .dimensions_from_points::<Point>([Point::new(2, 0)])
3571            .collect::<Vec<_>>(),
3572        vec![Point::new(2, 0)]
3573    );
3574
3575    let (_, translated_offset) = snapshot.point_to_buffer_offset(Point::new(2, 0)).unwrap();
3576    assert_eq!(translated_offset.0, "one\n".len());
3577    let (_, translated_point, _) = snapshot.point_to_buffer_point(Point::new(2, 0)).unwrap();
3578    assert_eq!(translated_point, Point::new(1, 0));
3579
3580    // The same, for an excerpt that's not at the end of the multibuffer.
3581
3582    let text_2 = "foo\n".to_owned();
3583    let buffer_2 = cx.new(|cx| Buffer::local(&text_2, cx));
3584    multibuffer.update(cx, |multibuffer, cx| {
3585        multibuffer.push_excerpts(
3586            buffer_2.clone(),
3587            [ExcerptRange::new(Point::new(0, 0)..Point::new(1, 0))],
3588            cx,
3589        );
3590    });
3591
3592    assert_new_snapshot(
3593        &multibuffer,
3594        &mut snapshot,
3595        &mut subscription,
3596        cx,
3597        indoc!(
3598            "
3599              one
3600            - two
3601
3602              foo
3603            "
3604        ),
3605    );
3606
3607    assert_eq!(
3608        snapshot
3609            .dimensions_from_points::<Point>([Point::new(2, 0)])
3610            .collect::<Vec<_>>(),
3611        vec![Point::new(2, 0)]
3612    );
3613
3614    let buffer_1_id = buffer_1.read_with(cx, |buffer_1, _| buffer_1.remote_id());
3615    let (buffer, translated_offset) = snapshot.point_to_buffer_offset(Point::new(2, 0)).unwrap();
3616    assert_eq!(buffer.remote_id(), buffer_1_id);
3617    assert_eq!(translated_offset.0, "one\n".len());
3618    let (buffer, translated_point, _) = snapshot.point_to_buffer_point(Point::new(2, 0)).unwrap();
3619    assert_eq!(buffer.remote_id(), buffer_1_id);
3620    assert_eq!(translated_point, Point::new(1, 0));
3621}
3622
3623fn format_diff(
3624    text: &str,
3625    row_infos: &Vec<RowInfo>,
3626    boundary_rows: &HashSet<MultiBufferRow>,
3627    has_diff: Option<bool>,
3628) -> String {
3629    let has_diff =
3630        has_diff.unwrap_or_else(|| row_infos.iter().any(|info| info.diff_status.is_some()));
3631    text.split('\n')
3632        .enumerate()
3633        .zip(row_infos)
3634        .map(|((ix, line), info)| {
3635            let marker = match info.diff_status.map(|status| status.kind) {
3636                Some(DiffHunkStatusKind::Added) => "+ ",
3637                Some(DiffHunkStatusKind::Deleted) => "- ",
3638                Some(DiffHunkStatusKind::Modified) => unreachable!(),
3639                None => {
3640                    if has_diff && !line.is_empty() {
3641                        "  "
3642                    } else {
3643                        ""
3644                    }
3645                }
3646            };
3647            let boundary_row = if boundary_rows.contains(&MultiBufferRow(ix as u32)) {
3648                if has_diff {
3649                    "  ----------\n"
3650                } else {
3651                    "---------\n"
3652                }
3653            } else {
3654                ""
3655            };
3656            let expand = info
3657                .expand_info
3658                .map(|expand_info| match expand_info.direction {
3659                    ExpandExcerptDirection::Up => " [↑]",
3660                    ExpandExcerptDirection::Down => " [↓]",
3661                    ExpandExcerptDirection::UpAndDown => " [↕]",
3662                })
3663                .unwrap_or_default();
3664
3665            format!("{boundary_row}{marker}{line}{expand}")
3666            // let mbr = info
3667            //     .multibuffer_row
3668            //     .map(|row| format!("{:0>3}", row.0))
3669            //     .unwrap_or_else(|| "???".to_string());
3670            // let byte_range = format!("{byte_range_start:0>3}..{byte_range_end:0>3}");
3671            // format!("{boundary_row}Row: {mbr}, Bytes: {byte_range} | {marker}{line}{expand}")
3672        })
3673        .collect::<Vec<_>>()
3674        .join("\n")
3675}
3676
3677// fn format_transforms(snapshot: &MultiBufferSnapshot) -> String {
3678//     snapshot
3679//         .diff_transforms
3680//         .iter()
3681//         .map(|transform| {
3682//             let (kind, summary) = match transform {
3683//                 DiffTransform::DeletedHunk { summary, .. } => ("   Deleted", (*summary).into()),
3684//                 DiffTransform::FilteredInsertedHunk { summary, .. } => ("  Filtered", *summary),
3685//                 DiffTransform::InsertedHunk { summary, .. } => ("  Inserted", *summary),
3686//                 DiffTransform::Unmodified { summary, .. } => ("Unmodified", *summary),
3687//             };
3688//             format!("{kind}(len: {}, lines: {:?})", summary.len, summary.lines)
3689//         })
3690//         .join("\n")
3691// }
3692
3693// fn format_excerpts(snapshot: &MultiBufferSnapshot) -> String {
3694//     snapshot
3695//         .excerpts
3696//         .iter()
3697//         .map(|excerpt| {
3698//             format!(
3699//                 "Excerpt(buffer_range = {:?}, lines = {:?}, has_trailing_newline = {:?})",
3700//                 excerpt.range.context.to_point(&excerpt.buffer),
3701//                 excerpt.text_summary.lines,
3702//                 excerpt.has_trailing_newline
3703//             )
3704//         })
3705//         .join("\n")
3706// }
3707
3708#[gpui::test]
3709async fn test_singleton_with_inverted_diff(cx: &mut TestAppContext) {
3710    let text = indoc!(
3711        "
3712        ZERO
3713        one
3714        TWO
3715        three
3716        six
3717        "
3718    );
3719    let base_text = indoc!(
3720        "
3721        one
3722        two
3723        three
3724        four
3725        five
3726        six
3727        "
3728    );
3729
3730    let buffer = cx.new(|cx| Buffer::local(text, cx));
3731    let diff = cx
3732        .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
3733    cx.run_until_parked();
3734
3735    let base_text_buffer = diff.read_with(cx, |diff, _| diff.base_text_buffer());
3736
3737    let multibuffer = cx.new(|cx| {
3738        let mut multibuffer = MultiBuffer::singleton(base_text_buffer.clone(), cx);
3739        multibuffer.set_all_diff_hunks_expanded(cx);
3740        multibuffer.add_inverted_diff(diff.clone(), buffer.clone(), cx);
3741        multibuffer
3742    });
3743
3744    let (mut snapshot, mut subscription) = multibuffer.update(cx, |multibuffer, cx| {
3745        (multibuffer.snapshot(cx), multibuffer.subscribe())
3746    });
3747
3748    assert_eq!(snapshot.text(), base_text);
3749    assert_new_snapshot(
3750        &multibuffer,
3751        &mut snapshot,
3752        &mut subscription,
3753        cx,
3754        indoc!(
3755            "
3756              one
3757            - two
3758              three
3759            - four
3760            - five
3761              six
3762            "
3763        ),
3764    );
3765
3766    buffer.update(cx, |buffer, cx| {
3767        buffer.edit_via_marked_text(
3768            indoc!(
3769                "
3770                ZERO
3771                one
3772                «<inserted>»W«O
3773                T»hree
3774                six
3775                "
3776            ),
3777            None,
3778            cx,
3779        );
3780    });
3781    cx.run_until_parked();
3782    let update = diff
3783        .update(cx, |diff, cx| {
3784            diff.update_diff(
3785                buffer.read(cx).text_snapshot(),
3786                Some(base_text.into()),
3787                false,
3788                None,
3789                cx,
3790            )
3791        })
3792        .await;
3793    diff.update(cx, |diff, cx| {
3794        diff.set_snapshot(update, &buffer.read(cx).text_snapshot(), false, cx);
3795    });
3796    cx.run_until_parked();
3797
3798    assert_new_snapshot(
3799        &multibuffer,
3800        &mut snapshot,
3801        &mut subscription,
3802        cx,
3803        indoc! {
3804            "
3805              one
3806            - two
3807            - three
3808            - four
3809            - five
3810              six
3811            "
3812        },
3813    );
3814
3815    buffer.update(cx, |buffer, cx| {
3816        buffer.set_text("ZERO\nONE\nTWO\n", cx);
3817    });
3818    cx.run_until_parked();
3819    let update = diff
3820        .update(cx, |diff, cx| {
3821            diff.update_diff(
3822                buffer.read(cx).text_snapshot(),
3823                Some(base_text.into()),
3824                false,
3825                None,
3826                cx,
3827            )
3828        })
3829        .await;
3830    diff.update(cx, |diff, cx| {
3831        diff.set_snapshot(update, &buffer.read(cx).text_snapshot(), false, cx);
3832    });
3833    cx.run_until_parked();
3834
3835    assert_new_snapshot(
3836        &multibuffer,
3837        &mut snapshot,
3838        &mut subscription,
3839        cx,
3840        indoc! {
3841            "
3842            - one
3843            - two
3844            - three
3845            - four
3846            - five
3847            - six
3848            "
3849        },
3850    );
3851
3852    diff.update(cx, |diff, cx| {
3853        diff.set_base_text(
3854            Some("new base\n".into()),
3855            None,
3856            buffer.read(cx).text_snapshot(),
3857            cx,
3858        )
3859    })
3860    .await
3861    .unwrap();
3862    cx.run_until_parked();
3863
3864    assert_new_snapshot(
3865        &multibuffer,
3866        &mut snapshot,
3867        &mut subscription,
3868        cx,
3869        indoc! {"
3870            - new base
3871        "},
3872    );
3873}
3874
3875#[track_caller]
3876fn assert_excerpts_match(
3877    multibuffer: &Entity<MultiBuffer>,
3878    cx: &mut TestAppContext,
3879    expected: &str,
3880) {
3881    let mut output = String::new();
3882    multibuffer.read_with(cx, |multibuffer, cx| {
3883        for (_, buffer, range) in multibuffer.snapshot(cx).excerpts() {
3884            output.push_str("-----\n");
3885            output.extend(buffer.text_for_range(range.context));
3886            if !output.ends_with('\n') {
3887                output.push('\n');
3888            }
3889        }
3890    });
3891    assert_eq!(output, expected);
3892}
3893
3894#[track_caller]
3895fn assert_new_snapshot(
3896    multibuffer: &Entity<MultiBuffer>,
3897    snapshot: &mut MultiBufferSnapshot,
3898    subscription: &mut Subscription<MultiBufferOffset>,
3899    cx: &mut TestAppContext,
3900    expected_diff: &str,
3901) {
3902    let new_snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
3903    let actual_text = new_snapshot.text();
3904    let line_infos = new_snapshot
3905        .row_infos(MultiBufferRow(0))
3906        .collect::<Vec<_>>();
3907    let actual_diff = format_diff(&actual_text, &line_infos, &Default::default(), None);
3908    pretty_assertions::assert_eq!(actual_diff, expected_diff);
3909    check_edits(
3910        snapshot,
3911        &new_snapshot,
3912        &subscription.consume().into_inner(),
3913    );
3914    *snapshot = new_snapshot;
3915}
3916
3917#[track_caller]
3918fn check_edits(
3919    old_snapshot: &MultiBufferSnapshot,
3920    new_snapshot: &MultiBufferSnapshot,
3921    edits: &[Edit<MultiBufferOffset>],
3922) {
3923    let mut text = old_snapshot.text();
3924    let new_text = new_snapshot.text();
3925    for edit in edits.iter().rev() {
3926        if !text.is_char_boundary(edit.old.start.0)
3927            || !text.is_char_boundary(edit.old.end.0)
3928            || !new_text.is_char_boundary(edit.new.start.0)
3929            || !new_text.is_char_boundary(edit.new.end.0)
3930        {
3931            panic!(
3932                "invalid edits: {:?}\nold text: {:?}\nnew text: {:?}",
3933                edits, text, new_text
3934            );
3935        }
3936
3937        text.replace_range(
3938            edit.old.start.0..edit.old.end.0,
3939            &new_text[edit.new.start.0..edit.new.end.0],
3940        );
3941    }
3942
3943    pretty_assertions::assert_eq!(text, new_text, "invalid edits: {:?}", edits);
3944}
3945
3946#[track_caller]
3947fn assert_chunks_in_ranges(snapshot: &MultiBufferSnapshot) {
3948    let full_text = snapshot.text();
3949    for ix in 0..full_text.len() {
3950        let mut chunks = snapshot.chunks(MultiBufferOffset(0)..snapshot.len(), false);
3951        chunks.seek(MultiBufferOffset(ix)..snapshot.len());
3952        let tail = chunks.map(|chunk| chunk.text).collect::<String>();
3953        assert_eq!(tail, &full_text[ix..], "seek to range: {:?}", ix..);
3954    }
3955}
3956
3957#[track_caller]
3958fn assert_consistent_line_numbers(snapshot: &MultiBufferSnapshot) {
3959    let all_line_numbers = snapshot.row_infos(MultiBufferRow(0)).collect::<Vec<_>>();
3960    for start_row in 1..all_line_numbers.len() {
3961        let line_numbers = snapshot
3962            .row_infos(MultiBufferRow(start_row as u32))
3963            .collect::<Vec<_>>();
3964        assert_eq!(
3965            line_numbers,
3966            all_line_numbers[start_row..],
3967            "start_row: {start_row}"
3968        );
3969    }
3970}
3971
3972#[track_caller]
3973fn assert_position_translation(snapshot: &MultiBufferSnapshot) {
3974    let text = Rope::from(snapshot.text());
3975
3976    let mut left_anchors = Vec::new();
3977    let mut right_anchors = Vec::new();
3978    let mut offsets = Vec::new();
3979    let mut points = Vec::new();
3980    for offset in 0..=text.len() + 1 {
3981        let offset = MultiBufferOffset(offset);
3982        let clipped_left = snapshot.clip_offset(offset, Bias::Left);
3983        let clipped_right = snapshot.clip_offset(offset, Bias::Right);
3984        assert_eq!(
3985            clipped_left.0,
3986            text.clip_offset(offset.0, Bias::Left),
3987            "clip_offset({offset:?}, Left)"
3988        );
3989        assert_eq!(
3990            clipped_right.0,
3991            text.clip_offset(offset.0, Bias::Right),
3992            "clip_offset({offset:?}, Right)"
3993        );
3994        assert_eq!(
3995            snapshot.offset_to_point(clipped_left),
3996            text.offset_to_point(clipped_left.0),
3997            "offset_to_point({})",
3998            clipped_left.0
3999        );
4000        assert_eq!(
4001            snapshot.offset_to_point(clipped_right),
4002            text.offset_to_point(clipped_right.0),
4003            "offset_to_point({})",
4004            clipped_right.0
4005        );
4006        let anchor_after = snapshot.anchor_after(clipped_left);
4007        assert_eq!(
4008            anchor_after.to_offset(snapshot),
4009            clipped_left,
4010            "anchor_after({}).to_offset {anchor_after:?}",
4011            clipped_left.0
4012        );
4013        let anchor_before = snapshot.anchor_before(clipped_left);
4014        assert_eq!(
4015            anchor_before.to_offset(snapshot),
4016            clipped_left,
4017            "anchor_before({}).to_offset",
4018            clipped_left.0
4019        );
4020        left_anchors.push(anchor_before);
4021        right_anchors.push(anchor_after);
4022        offsets.push(clipped_left);
4023        points.push(text.offset_to_point(clipped_left.0));
4024    }
4025
4026    for row in 0..text.max_point().row {
4027        for column in 0..text.line_len(row) + 1 {
4028            let point = Point { row, column };
4029            let clipped_left = snapshot.clip_point(point, Bias::Left);
4030            let clipped_right = snapshot.clip_point(point, Bias::Right);
4031            assert_eq!(
4032                clipped_left,
4033                text.clip_point(point, Bias::Left),
4034                "clip_point({point:?}, Left)"
4035            );
4036            assert_eq!(
4037                clipped_right,
4038                text.clip_point(point, Bias::Right),
4039                "clip_point({point:?}, Right)"
4040            );
4041            assert_eq!(
4042                snapshot.point_to_offset(clipped_left).0,
4043                text.point_to_offset(clipped_left),
4044                "point_to_offset({clipped_left:?})"
4045            );
4046            assert_eq!(
4047                snapshot.point_to_offset(clipped_right).0,
4048                text.point_to_offset(clipped_right),
4049                "point_to_offset({clipped_right:?})"
4050            );
4051        }
4052    }
4053
4054    assert_eq!(
4055        snapshot.summaries_for_anchors::<MultiBufferOffset, _>(&left_anchors),
4056        offsets,
4057        "left_anchors <-> offsets"
4058    );
4059    assert_eq!(
4060        snapshot.summaries_for_anchors::<Point, _>(&left_anchors),
4061        points,
4062        "left_anchors <-> points"
4063    );
4064    assert_eq!(
4065        snapshot.summaries_for_anchors::<MultiBufferOffset, _>(&right_anchors),
4066        offsets,
4067        "right_anchors <-> offsets"
4068    );
4069    assert_eq!(
4070        snapshot.summaries_for_anchors::<Point, _>(&right_anchors),
4071        points,
4072        "right_anchors <-> points"
4073    );
4074
4075    for (anchors, bias) in [(&left_anchors, Bias::Left), (&right_anchors, Bias::Right)] {
4076        for (ix, (offset, anchor)) in offsets.iter().zip(anchors).enumerate() {
4077            if ix > 0 && *offset == MultiBufferOffset(252) && offset > &offsets[ix - 1] {
4078                let prev_anchor = left_anchors[ix - 1];
4079                assert!(
4080                    anchor.cmp(&prev_anchor, snapshot).is_gt(),
4081                    "anchor({}, {bias:?}).cmp(&anchor({}, {bias:?}).is_gt()",
4082                    offsets[ix],
4083                    offsets[ix - 1],
4084                );
4085                assert!(
4086                    prev_anchor.cmp(anchor, snapshot).is_lt(),
4087                    "anchor({}, {bias:?}).cmp(&anchor({}, {bias:?}).is_lt()",
4088                    offsets[ix - 1],
4089                    offsets[ix],
4090                );
4091            }
4092        }
4093    }
4094
4095    if let Some((buffer, offset)) = snapshot.point_to_buffer_offset(snapshot.max_point()) {
4096        assert!(offset.0 <= buffer.len());
4097    }
4098    if let Some((buffer, point, _)) = snapshot.point_to_buffer_point(snapshot.max_point()) {
4099        assert!(point <= buffer.max_point());
4100    }
4101}
4102
4103fn assert_line_indents(snapshot: &MultiBufferSnapshot) {
4104    let max_row = snapshot.max_point().row;
4105    let buffer_id = snapshot.excerpts().next().unwrap().1.remote_id();
4106    let text = text::Buffer::new(ReplicaId::LOCAL, buffer_id, snapshot.text());
4107    let mut line_indents = text
4108        .line_indents_in_row_range(0..max_row + 1)
4109        .collect::<Vec<_>>();
4110    for start_row in 0..snapshot.max_point().row {
4111        pretty_assertions::assert_eq!(
4112            snapshot
4113                .line_indents(MultiBufferRow(start_row), |_| true)
4114                .map(|(row, indent, _)| (row.0, indent))
4115                .collect::<Vec<_>>(),
4116            &line_indents[(start_row as usize)..],
4117            "line_indents({start_row})"
4118        );
4119    }
4120
4121    line_indents.reverse();
4122    pretty_assertions::assert_eq!(
4123        snapshot
4124            .reversed_line_indents(MultiBufferRow(max_row), |_| true)
4125            .map(|(row, indent, _)| (row.0, indent))
4126            .collect::<Vec<_>>(),
4127        &line_indents[..],
4128        "reversed_line_indents({max_row})"
4129    );
4130}
4131
4132#[gpui::test]
4133fn test_new_empty_buffer_uses_untitled_title(cx: &mut App) {
4134    let buffer = cx.new(|cx| Buffer::local("", cx));
4135    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4136
4137    assert_eq!(multibuffer.read(cx).title(cx), "untitled");
4138}
4139
4140#[gpui::test]
4141fn test_new_empty_buffer_uses_untitled_title_when_only_contains_whitespace(cx: &mut App) {
4142    let buffer = cx.new(|cx| Buffer::local("\n ", cx));
4143    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4144
4145    assert_eq!(multibuffer.read(cx).title(cx), "untitled");
4146}
4147
4148#[gpui::test]
4149fn test_new_empty_buffer_takes_first_line_for_title(cx: &mut App) {
4150    let buffer = cx.new(|cx| Buffer::local("Hello World\nSecond line", cx));
4151    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4152
4153    assert_eq!(multibuffer.read(cx).title(cx), "Hello World");
4154}
4155
4156#[gpui::test]
4157fn test_new_empty_buffer_takes_trimmed_first_line_for_title(cx: &mut App) {
4158    let buffer = cx.new(|cx| Buffer::local("\nHello, World ", cx));
4159    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4160
4161    assert_eq!(multibuffer.read(cx).title(cx), "Hello, World");
4162}
4163
4164#[gpui::test]
4165fn test_new_empty_buffer_uses_truncated_first_line_for_title(cx: &mut App) {
4166    let title = "aaaaaaaaaabbbbbbbbbbccccccccccddddddddddeeeeeeeeee";
4167    let title_after = "aaaaaaaaaabbbbbbbbbbccccccccccdddddddddd";
4168    let buffer = cx.new(|cx| Buffer::local(title, cx));
4169    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4170
4171    assert_eq!(multibuffer.read(cx).title(cx), title_after);
4172}
4173
4174#[gpui::test]
4175fn test_new_empty_buffer_uses_truncated_first_line_for_title_after_merging_adjacent_spaces(
4176    cx: &mut App,
4177) {
4178    let title = "aaaaaaaaaabbbbbbbbbb    ccccccccccddddddddddeeeeeeeeee";
4179    let title_after = "aaaaaaaaaabbbbbbbbbb ccccccccccddddddddd";
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_buffers_title_can_be_set(cx: &mut App) {
4188    let buffer = cx.new(|cx| Buffer::local("Hello World", cx));
4189    let multibuffer = cx.new(|cx| MultiBuffer::singleton(buffer.clone(), cx));
4190    assert_eq!(multibuffer.read(cx).title(cx), "Hello World");
4191
4192    multibuffer.update(cx, |multibuffer, cx| {
4193        multibuffer.set_title("Hey".into(), cx)
4194    });
4195    assert_eq!(multibuffer.read(cx).title(cx), "Hey");
4196}
4197
4198#[gpui::test(iterations = 100)]
4199fn test_random_chunk_bitmaps(cx: &mut App, mut rng: StdRng) {
4200    let multibuffer = if rng.random() {
4201        let len = rng.random_range(0..10000);
4202        let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
4203        let buffer = cx.new(|cx| Buffer::local(text, cx));
4204        cx.new(|cx| MultiBuffer::singleton(buffer, cx))
4205    } else {
4206        MultiBuffer::build_random(&mut rng, cx)
4207    };
4208
4209    let snapshot = multibuffer.read(cx).snapshot(cx);
4210
4211    let chunks = snapshot.chunks(MultiBufferOffset(0)..snapshot.len(), false);
4212
4213    for chunk in chunks {
4214        let chunk_text = chunk.text;
4215        let chars_bitmap = chunk.chars;
4216        let tabs_bitmap = chunk.tabs;
4217
4218        if chunk_text.is_empty() {
4219            assert_eq!(
4220                chars_bitmap, 0,
4221                "Empty chunk should have empty chars bitmap"
4222            );
4223            assert_eq!(tabs_bitmap, 0, "Empty chunk should have empty tabs bitmap");
4224            continue;
4225        }
4226
4227        assert!(
4228            chunk_text.len() <= 128,
4229            "Chunk text length {} exceeds 128 bytes",
4230            chunk_text.len()
4231        );
4232
4233        // Verify chars bitmap
4234        let char_indices = chunk_text
4235            .char_indices()
4236            .map(|(i, _)| i)
4237            .collect::<Vec<_>>();
4238
4239        for byte_idx in 0..chunk_text.len() {
4240            let should_have_bit = char_indices.contains(&byte_idx);
4241            let has_bit = chars_bitmap & (1 << byte_idx) != 0;
4242
4243            if has_bit != should_have_bit {
4244                eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
4245                eprintln!("Char indices: {:?}", char_indices);
4246                eprintln!("Chars bitmap: {:#b}", chars_bitmap);
4247            }
4248
4249            assert_eq!(
4250                has_bit, should_have_bit,
4251                "Chars bitmap mismatch at byte index {} in chunk {:?}. Expected bit: {}, Got bit: {}",
4252                byte_idx, chunk_text, should_have_bit, has_bit
4253            );
4254        }
4255
4256        for (byte_idx, byte) in chunk_text.bytes().enumerate() {
4257            let is_tab = byte == b'\t';
4258            let has_bit = tabs_bitmap & (1 << byte_idx) != 0;
4259
4260            if has_bit != is_tab {
4261                eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
4262                eprintln!("Tabs bitmap: {:#b}", tabs_bitmap);
4263                assert_eq!(
4264                    has_bit, is_tab,
4265                    "Tabs bitmap mismatch at byte index {} in chunk {:?}. Byte: {:?}, Expected bit: {}, Got bit: {}",
4266                    byte_idx, chunk_text, byte as char, is_tab, has_bit
4267                );
4268            }
4269        }
4270    }
4271}
4272
4273#[gpui::test(iterations = 10)]
4274fn test_random_chunk_bitmaps_with_diffs(cx: &mut App, mut rng: StdRng) {
4275    let settings_store = SettingsStore::test(cx);
4276    cx.set_global(settings_store);
4277    use buffer_diff::BufferDiff;
4278    use util::RandomCharIter;
4279
4280    let multibuffer = if rng.random() {
4281        let len = rng.random_range(100..10000);
4282        let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
4283        let buffer = cx.new(|cx| Buffer::local(text, cx));
4284        cx.new(|cx| MultiBuffer::singleton(buffer, cx))
4285    } else {
4286        MultiBuffer::build_random(&mut rng, cx)
4287    };
4288
4289    let _diff_count = rng.random_range(1..5);
4290    let mut diffs = Vec::new();
4291
4292    multibuffer.update(cx, |multibuffer, cx| {
4293        for buffer_id in multibuffer.excerpt_buffer_ids() {
4294            if rng.random_bool(0.7) {
4295                if let Some(buffer_handle) = multibuffer.buffer(buffer_id) {
4296                    let buffer_text = buffer_handle.read(cx).text();
4297                    let mut base_text = String::new();
4298
4299                    for line in buffer_text.lines() {
4300                        if rng.random_bool(0.3) {
4301                            continue;
4302                        } else if rng.random_bool(0.3) {
4303                            let line_len = rng.random_range(0..50);
4304                            let modified_line = RandomCharIter::new(&mut rng)
4305                                .take(line_len)
4306                                .collect::<String>();
4307                            base_text.push_str(&modified_line);
4308                            base_text.push('\n');
4309                        } else {
4310                            base_text.push_str(line);
4311                            base_text.push('\n');
4312                        }
4313                    }
4314
4315                    if rng.random_bool(0.5) {
4316                        let extra_lines = rng.random_range(1..5);
4317                        for _ in 0..extra_lines {
4318                            let line_len = rng.random_range(0..50);
4319                            let extra_line = RandomCharIter::new(&mut rng)
4320                                .take(line_len)
4321                                .collect::<String>();
4322                            base_text.push_str(&extra_line);
4323                            base_text.push('\n');
4324                        }
4325                    }
4326
4327                    let diff = cx.new(|cx| {
4328                        BufferDiff::new_with_base_text(
4329                            &base_text,
4330                            &buffer_handle.read(cx).text_snapshot(),
4331                            cx,
4332                        )
4333                    });
4334                    diffs.push(diff.clone());
4335                    multibuffer.add_diff(diff, cx);
4336                }
4337            }
4338        }
4339    });
4340
4341    multibuffer.update(cx, |multibuffer, cx| {
4342        if rng.random_bool(0.5) {
4343            multibuffer.set_all_diff_hunks_expanded(cx);
4344        } else {
4345            let snapshot = multibuffer.snapshot(cx);
4346            let text = snapshot.text();
4347
4348            let mut ranges = Vec::new();
4349            for _ in 0..rng.random_range(1..5) {
4350                if snapshot.len().0 == 0 {
4351                    break;
4352                }
4353
4354                let diff_size = rng.random_range(5..1000);
4355                let mut start = rng.random_range(0..snapshot.len().0);
4356
4357                while !text.is_char_boundary(start) {
4358                    start = start.saturating_sub(1);
4359                }
4360
4361                let mut end = rng.random_range(start..snapshot.len().0.min(start + diff_size));
4362
4363                while !text.is_char_boundary(end) {
4364                    end = end.saturating_add(1);
4365                }
4366                let start_anchor = snapshot.anchor_after(MultiBufferOffset(start));
4367                let end_anchor = snapshot.anchor_before(MultiBufferOffset(end));
4368                ranges.push(start_anchor..end_anchor);
4369            }
4370            multibuffer.expand_diff_hunks(ranges, cx);
4371        }
4372    });
4373
4374    let snapshot = multibuffer.read(cx).snapshot(cx);
4375
4376    let chunks = snapshot.chunks(MultiBufferOffset(0)..snapshot.len(), false);
4377
4378    for chunk in chunks {
4379        let chunk_text = chunk.text;
4380        let chars_bitmap = chunk.chars;
4381        let tabs_bitmap = chunk.tabs;
4382
4383        if chunk_text.is_empty() {
4384            assert_eq!(
4385                chars_bitmap, 0,
4386                "Empty chunk should have empty chars bitmap"
4387            );
4388            assert_eq!(tabs_bitmap, 0, "Empty chunk should have empty tabs bitmap");
4389            continue;
4390        }
4391
4392        assert!(
4393            chunk_text.len() <= 128,
4394            "Chunk text length {} exceeds 128 bytes",
4395            chunk_text.len()
4396        );
4397
4398        let char_indices = chunk_text
4399            .char_indices()
4400            .map(|(i, _)| i)
4401            .collect::<Vec<_>>();
4402
4403        for byte_idx in 0..chunk_text.len() {
4404            let should_have_bit = char_indices.contains(&byte_idx);
4405            let has_bit = chars_bitmap & (1 << byte_idx) != 0;
4406
4407            if has_bit != should_have_bit {
4408                eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
4409                eprintln!("Char indices: {:?}", char_indices);
4410                eprintln!("Chars bitmap: {:#b}", chars_bitmap);
4411            }
4412
4413            assert_eq!(
4414                has_bit, should_have_bit,
4415                "Chars bitmap mismatch at byte index {} in chunk {:?}. Expected bit: {}, Got bit: {}",
4416                byte_idx, chunk_text, should_have_bit, has_bit
4417            );
4418        }
4419
4420        for (byte_idx, byte) in chunk_text.bytes().enumerate() {
4421            let is_tab = byte == b'\t';
4422            let has_bit = tabs_bitmap & (1 << byte_idx) != 0;
4423
4424            if has_bit != is_tab {
4425                eprintln!("Chunk text bytes: {:?}", chunk_text.as_bytes());
4426                eprintln!("Tabs bitmap: {:#b}", tabs_bitmap);
4427                assert_eq!(
4428                    has_bit, is_tab,
4429                    "Tabs bitmap mismatch at byte index {} in chunk {:?}. Byte: {:?}, Expected bit: {}, Got bit: {}",
4430                    byte_idx, chunk_text, byte as char, is_tab, has_bit
4431                );
4432            }
4433        }
4434    }
4435}
4436
4437fn collect_word_diffs(
4438    base_text: &str,
4439    modified_text: &str,
4440    cx: &mut TestAppContext,
4441) -> Vec<String> {
4442    let buffer = cx.new(|cx| Buffer::local(modified_text, cx));
4443    let diff = cx
4444        .new(|cx| BufferDiff::new_with_base_text(base_text, &buffer.read(cx).text_snapshot(), cx));
4445    cx.run_until_parked();
4446
4447    let multibuffer = cx.new(|cx| {
4448        let mut multibuffer = MultiBuffer::singleton(buffer.clone(), cx);
4449        multibuffer.add_diff(diff.clone(), cx);
4450        multibuffer
4451    });
4452
4453    multibuffer.update(cx, |multibuffer, cx| {
4454        multibuffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx);
4455    });
4456
4457    let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
4458    let text = snapshot.text();
4459
4460    snapshot
4461        .diff_hunks()
4462        .flat_map(|hunk| hunk.word_diffs)
4463        .map(|range| text[range.start.0..range.end.0].to_string())
4464        .collect()
4465}
4466
4467#[gpui::test]
4468async fn test_word_diff_simple_replacement(cx: &mut TestAppContext) {
4469    let settings_store = cx.update(|cx| SettingsStore::test(cx));
4470    cx.set_global(settings_store);
4471
4472    let base_text = "hello world foo bar\n";
4473    let modified_text = "hello WORLD foo BAR\n";
4474
4475    let word_diffs = collect_word_diffs(base_text, modified_text, cx);
4476
4477    assert_eq!(word_diffs, vec!["world", "bar", "WORLD", "BAR"]);
4478}
4479
4480#[gpui::test]
4481async fn test_word_diff_consecutive_modified_lines(cx: &mut TestAppContext) {
4482    let settings_store = cx.update(|cx| SettingsStore::test(cx));
4483    cx.set_global(settings_store);
4484
4485    let base_text = "aaa bbb\nccc ddd\n";
4486    let modified_text = "aaa BBB\nccc DDD\n";
4487
4488    let word_diffs = collect_word_diffs(base_text, modified_text, cx);
4489
4490    assert_eq!(
4491        word_diffs,
4492        vec!["bbb", "ddd", "BBB", "DDD"],
4493        "consecutive modified lines should produce word diffs when line counts match"
4494    );
4495}
4496
4497#[gpui::test]
4498async fn test_word_diff_modified_lines_with_deletion_between(cx: &mut TestAppContext) {
4499    let settings_store = cx.update(|cx| SettingsStore::test(cx));
4500    cx.set_global(settings_store);
4501
4502    let base_text = "aaa bbb\ndeleted line\nccc ddd\n";
4503    let modified_text = "aaa BBB\nccc DDD\n";
4504
4505    let word_diffs = collect_word_diffs(base_text, modified_text, cx);
4506
4507    assert_eq!(
4508        word_diffs,
4509        Vec::<String>::new(),
4510        "modified lines with a deleted line between should not produce word diffs"
4511    );
4512}
4513
4514#[gpui::test]
4515async fn test_word_diff_disabled(cx: &mut TestAppContext) {
4516    let settings_store = cx.update(|cx| {
4517        let mut settings_store = SettingsStore::test(cx);
4518        settings_store.update_user_settings(cx, |settings| {
4519            settings.project.all_languages.defaults.word_diff_enabled = Some(false);
4520        });
4521        settings_store
4522    });
4523    cx.set_global(settings_store);
4524
4525    let base_text = "hello world\n";
4526    let modified_text = "hello WORLD\n";
4527
4528    let word_diffs = collect_word_diffs(base_text, modified_text, cx);
4529
4530    assert_eq!(
4531        word_diffs,
4532        Vec::<String>::new(),
4533        "word diffs should be empty when disabled"
4534    );
4535}
4536
4537/// Tests `excerpt_containing` and `excerpts_for_range` (functions mapping multi-buffer text-coordinates to excerpts)
4538#[gpui::test]
4539fn test_excerpts_containment_functions(cx: &mut App) {
4540    // Multibuffer content for these tests:
4541    //    0123
4542    // 0: aa0
4543    // 1: aa1
4544    //    -----
4545    // 2: bb0
4546    // 3: bb1
4547    //    -----MultiBufferOffset(0)..
4548    // 4: cc0
4549
4550    let buffer_1 = cx.new(|cx| Buffer::local("aa0\naa1", cx));
4551    let buffer_2 = cx.new(|cx| Buffer::local("bb0\nbb1", cx));
4552    let buffer_3 = cx.new(|cx| Buffer::local("cc0", cx));
4553
4554    let multibuffer = cx.new(|_| MultiBuffer::new(Capability::ReadWrite));
4555
4556    let (excerpt_1_id, excerpt_2_id, excerpt_3_id) = multibuffer.update(cx, |multibuffer, cx| {
4557        let excerpt_1_id = multibuffer.push_excerpts(
4558            buffer_1.clone(),
4559            [ExcerptRange::new(Point::new(0, 0)..Point::new(1, 3))],
4560            cx,
4561        )[0];
4562
4563        let excerpt_2_id = multibuffer.push_excerpts(
4564            buffer_2.clone(),
4565            [ExcerptRange::new(Point::new(0, 0)..Point::new(1, 3))],
4566            cx,
4567        )[0];
4568
4569        let excerpt_3_id = multibuffer.push_excerpts(
4570            buffer_3.clone(),
4571            [ExcerptRange::new(Point::new(0, 0)..Point::new(0, 3))],
4572            cx,
4573        )[0];
4574
4575        (excerpt_1_id, excerpt_2_id, excerpt_3_id)
4576    });
4577
4578    let snapshot = multibuffer.read(cx).snapshot(cx);
4579
4580    assert_eq!(snapshot.text(), "aa0\naa1\nbb0\nbb1\ncc0");
4581
4582    //// Test `excerpts_for_range`
4583
4584    let p00 = snapshot.point_to_offset(Point::new(0, 0));
4585    let p10 = snapshot.point_to_offset(Point::new(1, 0));
4586    let p20 = snapshot.point_to_offset(Point::new(2, 0));
4587    let p23 = snapshot.point_to_offset(Point::new(2, 3));
4588    let p13 = snapshot.point_to_offset(Point::new(1, 3));
4589    let p40 = snapshot.point_to_offset(Point::new(4, 0));
4590    let p43 = snapshot.point_to_offset(Point::new(4, 3));
4591
4592    let excerpts: Vec<_> = snapshot.excerpts_for_range(p00..p00).collect();
4593    assert_eq!(excerpts.len(), 1);
4594    assert_eq!(excerpts[0].id, excerpt_1_id);
4595
4596    // Cursor at very end of excerpt 3
4597    let excerpts: Vec<_> = snapshot.excerpts_for_range(p43..p43).collect();
4598    assert_eq!(excerpts.len(), 1);
4599    assert_eq!(excerpts[0].id, excerpt_3_id);
4600
4601    let excerpts: Vec<_> = snapshot.excerpts_for_range(p00..p23).collect();
4602    assert_eq!(excerpts.len(), 2);
4603    assert_eq!(excerpts[0].id, excerpt_1_id);
4604    assert_eq!(excerpts[1].id, excerpt_2_id);
4605
4606    // This range represent an selection with end-point just inside excerpt_2
4607    // Today we only expand the first excerpt, but another interpretation that
4608    // we could consider is expanding both here
4609    let excerpts: Vec<_> = snapshot.excerpts_for_range(p10..p20).collect();
4610    assert_eq!(excerpts.len(), 1);
4611    assert_eq!(excerpts[0].id, excerpt_1_id);
4612
4613    //// Test that `excerpts_for_range` and `excerpt_containing` agree for all single offsets (cursor positions)
4614    for offset in 0..=snapshot.len().0 {
4615        let offset = MultiBufferOffset(offset);
4616        let excerpts_for_range: Vec<_> = snapshot.excerpts_for_range(offset..offset).collect();
4617        assert_eq!(
4618            excerpts_for_range.len(),
4619            1,
4620            "Expected exactly one excerpt for offset {offset}",
4621        );
4622
4623        let excerpt_containing = snapshot.excerpt_containing(offset..offset);
4624        assert!(
4625            excerpt_containing.is_some(),
4626            "Expected excerpt_containing to find excerpt for offset {offset}",
4627        );
4628
4629        assert_eq!(
4630            excerpts_for_range[0].id,
4631            excerpt_containing.unwrap().id(),
4632            "excerpts_for_range and excerpt_containing should agree for offset {offset}",
4633        );
4634    }
4635
4636    //// Test `excerpt_containing` behavior with ranges:
4637
4638    // Ranges intersecting a single-excerpt
4639    let containing = snapshot.excerpt_containing(p00..p13);
4640    assert!(containing.is_some());
4641    assert_eq!(containing.unwrap().id(), excerpt_1_id);
4642
4643    // Ranges intersecting multiple excerpts (should return None)
4644    let containing = snapshot.excerpt_containing(p20..p40);
4645    assert!(
4646        containing.is_none(),
4647        "excerpt_containing should return None for ranges spanning multiple excerpts"
4648    );
4649}