1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
#!/usr/bin/env python3
"""Convert the Forge paper (OOPSLA 2024, CC-BY 4.0) into semantic HTML.

Strategy
--------
Two extractions of the same PDF are combined:

  spans.xml    pdftohtml -xml      font family/size/colour + geometry
                                   -> tells us what each line *is*
  pages/p*.txt pdftotext -layout   verbatim text with indentation
                                   -> tells us what code listings *say*

acmart uses fonts consistently enough that the role of every line can be
decided from its font (see lines.py).  Running heads and feet lie outside
the [100, 1005] vertical band and are dropped.  Paragraphs are joined
across line and page breaks; a hyphen at a line end is closed up only
when it is TeX hyphenation rather than a real compound.

Run from a directory holding those inputs, which ./extract produces:

    ./extract && (cd build && python3 ../convert.py)

./verify does both and checks the result against the committed page.
See forge-paper.7 (METHOD) for why each pass exists.
"""

import html
import re

import lines as L
import codeblocks as CB
import citations
import codespans as CS

OUT = "paper.html"
SRC_URL = ("https://cs.brown.edu/people/sk/Publications/Papers/"
           "Published/ngp----forge/paper.pdf")
DOI = "https://doi.org/10.1145/3649833"

# ---------------------------------------------------------------- utilities


def esc(s):
    return html.escape(s, quote=False)


# A hyphen at a line end is either TeX hyphenation ("pro-gramming") or a
# real compound ("Web-based").  Rather than guess from a prefix list, ask
# the paper itself: build a vocabulary from the whole text and see which
# of the two spellings it uses elsewhere.
_VOCAB = None
_HYPHENATED = None

# The few cases the vocabulary cannot settle, resolved by reading them.
HYPHEN_OVERRIDE = {
    "arbitraryarity": "arbitrary-arity",
    "datavisualization": "data-visualization",
    "carefullychosen": "carefully-chosen",
    "uncovering": "uncovering",
    "expectations": "expectations",
    "optimizations": "optimizations",
    "declarations": "declarations",
}


def _load_vocab():
    global _VOCAB, _HYPHENATED
    if _VOCAB is not None:
        return
    text = open("layout.txt", encoding="utf-8").read()
    text = CB._fix(text)
    # words that appear un-broken somewhere in the document
    joined = set()
    for w in re.findall(r"[A-Za-z]+", text):
        joined.add(w.lower())
    # compounds that appear hyphenated *within* a line
    hy = set()
    for line in text.split("\n"):
        for m in re.finditer(r"[A-Za-z]+-[A-Za-z]+", line):
            hy.add(m.group(0).lower())
    _VOCAB, _HYPHENATED = joined, hy


def _close_hyphen(head, tail):
    """True if `head-` + `tail` should close up into one word."""
    _load_vocab()
    stem = re.split(r"[\s(\[\u201c\u2018]", head[:-1])[-1]
    stem = re.sub(r"[^A-Za-z-]", "", stem)
    word = re.match(r"[A-Za-z]+", tail)
    if not stem or not word:
        return True
    a, b = stem.lower(), word.group(0).lower()
    # only the last element of an already-hyphenated stem matters
    a_last = a.split("-")[-1]
    closed, hyph = a_last + b, a_last + "-" + b
    if closed in HYPHEN_OVERRIDE:
        return "-" not in HYPHEN_OVERRIDE[closed]
    if hyph in _HYPHENATED:
        return False
    if closed in _VOCAB:
        return True
    return False


# A line may end, or the next begin, inside markup, so the hyphen that
# decides whether the two close up can be separated from the letter it
# joins to by any number of tags: "alloy-</a>" then "<a ...>tools.org".
# These find the text either side of that markup, and where to cut.
_TRAILING_TAGS = re.compile(r"(?:<[^>]+>)*$")
_LEADING_TAGS = re.compile(r"^(?:<[^>]+>)*")


def join_lines(chunks):
    out = ""
    for c in chunks:
        c = c.strip()
        if not c:
            continue
        if not out:
            out = c
            continue
        # look past any markup at the seam
        cut = _TRAILING_TAGS.search(out).start()
        head, head_tags = out[:cut], out[cut:]
        tail_at = _LEADING_TAGS.match(c).end()
        tail_tags, tail = c[:tail_at], c[tail_at:]
        if head.endswith("-") and not head.endswith("--") \
                and re.match(r"[a-z]", tail):
            # _close_hyphen reads the stem back to the preceding space, so
            # it must not see markup: an attribute value ("doc-biblioref")
            # would otherwise be taken for part of the word.
            if _close_hyphen(re.sub(r"<[^>]+>", " ", head), tail):
                out = head[:-1] + head_tags + tail_tags + tail
            else:
                out = head + head_tags + tail_tags + tail
        else:
            out += " " + c
    out = re.sub(r"[ \t]+", " ", out).strip()
    return fuse_adjacent_anchors(out)


# Two anchors to the same target, separated by nothing or by whitespace,
# are one citation that the typesetter broke across a line ("following
# Dolev / and Yao [1983]", "alloy- / tools.org 2023").  Emitting them
# as-is reads as two separate links, so they are fused once the line has
# been rejoined; a break inside a word leaves no space at all, which is
# why the separator is optional.
_ADJACENT_ANCHORS = re.compile(
    r'<a href="(#ref\d+)"([^>]*)>(.*?)</a>(\s*)<a href="\1"[^>]*>(.*?)</a>',
    re.S)


def fuse_adjacent_anchors(html_text):
    """Merge adjacent anchors to the same entry into one link.

    The absorbed anchor's id disappears from the document, so every
    back-reference pointing at it is redirected to the surviving anchor;
    otherwise the bibliography ends up with links to ids that no longer
    exist.
    """
    def merge(m):
        surviving, attrs = m.group(1), m.group(2)
        absorbed = re.search(r'id="(cite\d+)"', m.group(0)[m.end(3) - m.start():])
        keep = re.search(r'id="(cite\d+)"', attrs)
        if absorbed and keep:
            _retarget_backref(absorbed.group(1), keep.group(1))
        return (f'<a href="{surviving}"{attrs}>'
                f"{m.group(3)}{m.group(4)}{m.group(5)}</a>")

    prev = None
    while prev != html_text:
        prev = html_text
        html_text = _ADJACENT_ANCHORS.sub(merge, html_text)
    return html_text


def _retarget_backref(dead, alive):
    for rid, sites in BACKREFS.items():
        if dead in sites:
            sites[:] = [alive if s == dead else s for s in sites]
            # one citation site, listed once
            seen = set()
            sites[:] = [s for s in sites
                        if not (s in seen or seen.add(s))]
            return


# ------------------------------------------------------------- inline markup


BACKREFS = {}
UNRESOLVED = []

# The bibliography occupies these PDF pages.  An internal annotation
# outside them is a cross-reference to a section or figure, handled
# elsewhere, and must not be fed to the citation index.
REF_PAGES = (26, 29)
UNPLACED_NOTES = []


def final_href(piece):
    """Translate a poppler annotation target into a real href.

    An external annotation already names its target.  An internal one is
    resolved per piece by resolve_links(), which writes the answer into
    the piece's third slot: the same (target, text) pair is not unique
    (a bare "2012" appears under both Jackson and Montaghami and Rayside),
    so it cannot be keyed by text.
    """
    text, raw, resolved = piece
    if raw is None:
        return None
    if raw.startswith("http://") or raw.startswith("https://") \
            or raw.startswith("mailto:"):
        return raw
    return resolved


CITE_ID_SEQ = [0]

# number -> rendered html, filled by collect_footnotes()
FOOTNOTES = {}
SIDENOTES_DONE = set()
# off while the notes themselves are being rendered, so a note that cites
# another note cannot recurse
EMIT_SIDENOTES = False


def sidenote_html(n, body):
    """A footnote mark plus the note itself, to sit beside the text.

    The <aside> follows the mark in document order, so with CSS off (or on
    a narrow screen) it reads as an inline note right where it is
    referenced, rather than being stranded at the end of the document.
    """
    # NB: <aside> is flow content and may not appear inside <p>; a browser
    # closes the paragraph at it and splits the text in two (verified with
    # html-tidy).  A <span> carrying the note role renders identically,
    # nests legally, and keeps the semantics for assistive technology.
    return (
        f'<a class="fnref" id="fnref{n}" href="#fn{n}" '
        f'role="doc-noteref"><sup>{n}</sup></a>'
        f'<span class="sidenote" id="fn{n}" role="note">'
        f'<span class="fnnum">{n}</span> {body}</span>'
    )


def is_footnote_marker(span):
    """True for an in-text superscript footnote reference.

    acmart sets the reference mark at 11pt and the mark opening the note
    itself at 9pt.  The 9pt digits running down the left of page 11 are
    listing line numbers, not notes, so size alone is the discriminator
    and the footnote zone at the page foot is excluded.
    """
    return (round(span.size) == 11
            and span.family == "LinLibertineT"
            and span.top < 900
            and span.text.strip().isdigit()
            and len(span.text.strip()) == 1)


def collect_footnotes(all_lines):
    """Gather footnote bodies from the page feet, keyed by their number."""
    groups = {}
    cur = None
    for line in all_lines:
        page = line[0].page
        if not (2 <= page <= 25):
            continue
        if classify(line) != "footnote":
            cur = None
            continue
        text = L.line_text(line).strip()
        m = re.match(r"^(\d)(?=[A-Z\u201c])", text)
        if m:
            cur = int(m.group(1))
            groups.setdefault(cur, []).append(line)
        elif cur is not None:
            groups[cur].append(line)

    out = {}
    for n, lns in groups.items():
        html_txt = join_lines([render_inline(l) for l in lns])
        # drop the leading marker digit, which is part of the note's text
        html_txt = re.sub(r"^\s*(?:<[^>]+>)?\s*%d\s*" % n, "", html_txt, count=1)
        out[n] = html_txt.strip()
    return out


def resolve_links(all_lines, ref_items):
    """Resolve citation annotations to reference entries, in place.

    The PDF's internal links resolve only to a page ("spans.html#27"), and
    pages 26-29 are the bibliography.  The citation's own visible text says
    which entry is meant, so it is matched against an index built from the
    reference list, with the annotation's page as confirmation.  Anything
    that does not match confidently is left unlinked and reported.

    The answer is written into each piece's third slot rather than into a
    table keyed by text, because the text is not unique: a bare "2012"
    piece occurs under both Jackson and Montaghami and Rayside.
    """
    idx = citations.Index(ref_items)

    # A citation's author and year are separate annotated pieces, and the
    # typesetter may break the line between them ("following Dolev / and
    # Yao [1983]").  Scanning line by line would then see only "and Yao"
    # and mark the author's surname as ordinary text, so the pieces are
    # walked as one continuous sequence per page instead.
    by_page = {}
    for line in all_lines:
        for s in line:
            for p in s.pieces:
                if p[1]:
                    by_page.setdefault(s.page, []).append(p)

    for pieces in by_page.values():
        # Author of the last citation resolved on this page.  A citation
        # list may name an author once and then only years ("Beierle et
        # al. 2003, 2004b"; "alloytools.org 2023a,b,c"), and the run of
        # years may even change destination page mid-list, so the author
        # cannot be recovered by looking backwards through same-target
        # pieces alone.
        carried = None                    # (author, year) or None
        for i, p in enumerate(pieces):
            raw, text = p[1], p[0]
            if raw.startswith(("http", "mailto:")):
                continue
            m = re.match(r"spans\.html#(\d+)$", raw)
            if not m:
                continue
            page = int(m.group(1))
            if not REF_PAGES[0] <= page <= REF_PAGES[1]:
                continue              # a section/figure link, not a citation

            stripped = text.strip()
            own = ""                  # author words carried by this piece
            # Two shapes occur.  In the narrative form the year is a piece
            # of its own ("Brady" "[" "2013"), because acmart sets the
            # brackets around the year alone.  In the parenthetical form
            # the whole citation is one piece ("[" "Jackson 2012"), and
            # the author is simply the text before the year.
            ym = re.fullmatch(r"(\d{4}[a-z]?)", stripped)
            if ym:
                year = ym.group(1)
            else:
                # NB the author may end in a full stop ("Beierle et al.
                # 2003"), so the boundary is the space before the year and
                # not a letter class.
                ym = re.fullmatch(r"(.*[A-Za-z].*?)\s+(\d{4}[a-z]?)",
                                  stripped)
                if ym:
                    own, year = ym.group(1), ym.group(2)
                elif (carried and len(stripped) == 1 and stripped.isalpha()
                        and stripped.islower()):
                    # "2023a,b,c": a lone letter continues the previous
                    # year, and means that year with this suffix.
                    own, year = carried[0], carried[1][:4] + stripped
                else:
                    continue

            # The author may be split across pieces, but how far back to
            # reach depends on the shape, and reaching too far is a real
            # hazard: in a citation list every entry shares one
            # destination, so a blind backward scan swallows the previous
            # citation's author.
            prefix = []               # the pieces, not just their text
            if own:
                # Self-contained ("Jackson 2012"): only extend backwards
                # when this piece plainly cannot stand alone, i.e. it
                # starts mid-author ("Macedo" / "et al. 2022", "McCarthy"
                # / "and Krishnamurthi 2008") or continues a broken word
                # ("alloy-" / "tools.org 2023").
                for j in range(i - 1, max(-1, i - 4), -1):
                    cand = pieces[j]
                    head = prefix[-1][0].strip() if prefix else own
                    if cand[1] != raw or not cand[0].strip():
                        break
                    if not (re.match(r"^(et al\.|and\b)", head)
                            or cand[0].rstrip().endswith("-")):
                        break
                    prefix.append(cand)
            else:
                # Narrative form: the year is its own piece and the author
                # is whatever annotated text precedes it, possibly broken
                # across a line ("Dolev" / "and Yao" / "[" / "1983").
                for j in range(i - 1, max(-1, i - 6), -1):
                    cand = pieces[j]
                    if cand[1] != raw:
                        break
                    if re.search(r"[A-Za-z]{2}", cand[0]):
                        prefix.append(cand)
                    elif cand[0].strip() not in ("[", ";", ","):
                        break
            prefix.reverse()

            parts = [c[0].strip() for c in prefix] + ([own] if own else [])
            if not parts and carried:
                parts = [carried[0]]
            if not parts:
                continue
            # The pieces are joined the same way lines are, so that a
            # citation broken mid-word ("alloy-" / "tools.org 2023")
            # closes up into the name the bibliography actually lists.
            name = join_lines(parts)

            rid = idx.lookup(name, year, page)
            if rid is None:
                # fall back to the piece closest to the year
                rid = idx.lookup(parts[-1], year, page)
            if rid is None:
                UNRESOLVED.append((name, year, page))
                continue
            carried = (name, year)
            # The back-reference id is allocated when the anchor is
            # actually emitted (see render_inline): assigning it here
            # would hand two occurrences of one citation the same id.
            for cand in prefix + [p]:
                cand[2] = f"#{rid}"


def render_inline(line):
    """Render a visual line's spans, merging adjacent runs of equal style."""
    parts = []
    prev = None
    skip_until = -1.0
    for s in line:
        if s.mono and s.left < skip_until:
            continue
        if prev is not None:
            gap = s.left - prev.right
            # A style change mid-word ("assert" in code font + "ions" in
            # roman, for "assertions") leaves a hairline gap; only a wider
            # one is a real inter-word space.
            style_change = prev.mono != s.mono
            threshold = 2.5 if style_change else 1.0
            if gap > threshold and not s.text.startswith(" ") \
                    and not (parts and parts[-1][1].endswith(" ")):
                parts.append([None, " ", None])
        if s.mono:
            style = "code"
            fixed = code_at(s.page, s.top, s.left)
            if fixed:
                parts.append([style, fixed, None])
                skip_until = s.left + max(s.width, len(fixed) * 4.0)
                prev = s
                continue
        elif s.italic:
            style = "em"
        elif s.bold:
            style = "strong"
        elif s.smallcaps:
            style = "sc"
        else:
            style = None
        # An in-text footnote mark becomes the sidenote's anchor, with the
        # note itself emitted right here so it can sit beside this line.
        if EMIT_SIDENOTES and is_footnote_marker(s):
            n = int(s.text.strip())
            if n in FOOTNOTES and n not in SIDENOTES_DONE:
                SIDENOTES_DONE.add(n)
                parts.append(["raw", sidenote_html(n, FOOTNOTES[n]), None])
                prev = s
                continue
        # A span can be partly hyperlinked, so emit its pieces separately
        # and carry each piece's resolved href alongside the style.
        for piece in s.pieces:
            parts.append([style, piece[0], final_href(piece)])
        prev = s

    merged = []
    for style, txt, href in parts:
        if merged and merged[-1][0] == style and merged[-1][2] == href:
            merged[-1][1] += txt
        elif style is None and txt == " " and merged and merged[-1][2] is None:
            merged[-1][1] += txt
        else:
            merged.append([style, txt, href])

    # "assertions" is typeset with a code-font stem and a roman suffix, but
    # unlike "example"+"s" it is one ordinary word, not a Forge keyword.
    for i in range(len(merged) - 1):
        if merged[i][0] == "code" and merged[i + 1][0] is None \
                and merged[i][1].strip() + merged[i + 1][1].split()[0] \
                in ("assertions",):
            merged[i][0] = None

    # One citation may arrive as several annotated pieces ("Dolev" then
    # "and Yao", split by a line break).  They point at the same entry, so
    # fuse them into a single anchor rather than emitting adjacent links
    # that read as two separate citations.
    fused = []
    for part in merged:
        if (fused and part[2] and fused[-1][2] == part[2]
                and part[0] == fused[-1][0] and part[0] != "raw"):
            sep = "" if fused[-1][1].endswith(" ") \
                or part[1].startswith(" ") else " "
            fused[-1][1] += sep + part[1]
        else:
            fused.append(list(part))
    merged = fused

    out = []
    for style, txt, href in merged:
        if style == "raw":
            # already-built markup (a sidenote); must not be escaped
            out.append(txt)
            continue
        if not txt.strip():
            out.append(esc(txt))
            continue
        lead = " " if txt[:1] == " " else ""
        trail = " " if txt[-1:] == " " else ""
        core = esc(txt.strip())
        if style == "sc":
            # acmart small-caps: acronyms (fm, ide) and assignment names
            # (river, memory).  Not an abbreviation in general, so <abbr>
            # would be a lie; a styled span is the honest markup.
            core = f'<span class="sc">{core}</span>'
        elif style is not None:
            tag = {"code": "code", "em": "em", "strong": "strong"}[style]
            core = f"<{tag}>{core}</{tag}>"
        if href:
            attrs = ""
            if href.startswith("#ref"):
                # give this citation site an id so its entry can link back
                CITE_ID_SEQ[0] += 1
                cid = f"cite{CITE_ID_SEQ[0]}"
                BACKREFS.setdefault(href[1:], []).append(cid)
                attrs = f' id="{cid}" role="doc-biblioref"'
            core = f'<a href="{esc(href)}"{attrs}>{core}</a>'
        out.append(f"{lead}{core}{trail}")
    return re.sub(r"[ \t]+", " ", "".join(out))


# Inconsolata's wide advances make poppler split monospace runs into
# individual letters ("p . f a t h e r") at the default word-break
# threshold, while -wbt 40 resolves them correctly but destroys prose
# spacing.  So we extract twice and look inline code up by position in
# the -wbt 40 pass.
_CODE_INDEX = None


_ROMAN_INDEX = None


def roman_at(page, top, left, tol=6.0):
    """Correctly-spaced roman text at this position, from the default pass.

    The -wbt 40 extraction that keeps listings intact runs prose words
    together ("equivalentto"), so displayed lines mixing code and prose
    must take their roman runs from the default extraction instead.
    """
    global _ROMAN_INDEX
    if _ROMAN_INDEX is None:
        _ROMAN_INDEX = {}
        for s in L.parse_spans():
            if not s.mono:
                _ROMAN_INDEX.setdefault(s.page, []).append(s)
    best = None
    for s in _ROMAN_INDEX.get(page, []):
        if abs(s.top - top) <= tol and abs(s.left - left) <= tol:
            if best is None or abs(s.left - left) < abs(best.left - left):
                best = s
    return best.text.strip() if best else None


def code_at(page, top, left, tol=6.0):
    """Return the correctly-spaced monospace text at this position, if any."""
    global _CODE_INDEX
    if _CODE_INDEX is None:
        _CODE_INDEX = {}
        for s in L.parse_spans("spans_code.xml"):
            if s.mono:
                _CODE_INDEX.setdefault(s.page, []).append(s)
    best = None
    for s in _CODE_INDEX.get(page, []):
        if abs(s.top - top) <= tol and abs(s.left - left) <= tol:
            if best is None or abs(s.left - left) < abs(best.left - left):
                best = s
    return best.text.strip() if best else None


def mono_ratio(line):
    tot = sum(s.width for s in line)
    return (sum(s.width for s in line if s.mono) / tot) if tot else 0.0


# ------------------------------------------------------------------ analysis


def classify(line):
    txt = L.line_text(line).strip()
    if mono_ratio(line) > 0.6:
        return "code"
    if any(s.family == "LinBiolinumTB" and round(s.size) == 15 for s in line):
        return "heading"
    if any(s.family == "LinBiolinumTI" and round(s.size) == 15 for s in line) \
            and re.match(r"^\d+\.\d+\.\d+", txt):
        return "subsub"
    if any(s.family.startswith("LinBiolinum") and round(s.size) == 13
           for s in line):
        return "caption"
    if max(round(s.size) for s in line) <= 12 and line[0].top > 900:
        return "footnote"
    if txt.startswith("\u2022"):
        return "bullet"
    if re.match(r"^\(\d+\)\s", txt):
        return "enum"
    return "body"


def load_images():
    """Map each extracted PNG to its position on the page.

    `pdfimages -png -p` names files in PDF object order, and `pdftohtml
    -xml` lists <image> elements in the same order per page, so the two
    can be zipped page by page.  Positions let a figure claim exactly the
    images that sit above its caption (figs. 5 and 6 share page 9).
    """
    import glob
    import os

    # Only the files pdfimages extracted, named img-<page>-<object>.png.
    # The images/ directory also holds crops rendered by vectorfigs.py,
    # which have no page/object fields and are placed by name, not by
    # position.
    by_page = {}
    for f in sorted(glob.glob("images/img-*-*.png")):
        page = int(os.path.basename(f).split("-")[1])
        by_page.setdefault(page, []).append(os.path.basename(f))

    xml = open("with_images.xml", encoding="utf-8").read()
    out = {}
    for pm in re.finditer(r'<page number="(\d+)".*?(?=<page number=|</pdf2xml>)',
                          xml, re.S):
        page = int(pm.group(1))
        boxes = re.findall(
            r'<image top="([\-\d]+)" left="([\-\d]+)" '
            r'width="(\d+)" height="(\d+)"', pm.group(0))
        files = by_page.get(page, [])
        if len(boxes) != len(files):
            continue
        out[page] = [
            {"file": f, "top": int(t), "left": int(l),
             "width": int(w), "height": int(h)}
            for (t, l, w, h), f in zip(boxes, files)
        ]
    return out


IMAGES = load_images()


# The two tables are transcribed by hand: their cells are typeset with
# tabular rules and Dingbat check marks, which no text extraction turns
# into rows and columns.  Content checked against pages 7 and 14.
YES = '<td class="yes" aria-label="yes">\u2713</td>'
NO = '<td class="no" aria-label="no">\u2717</td>'

TABLE1_ROWS = [
    ("Partial-function fields, <code>some</code>, <code>all</code> quantifiers",
     "YYYY"),
    ('Dedicated testing constructs (<a href="#sec5">section 5</a>)', "YYYN"),
    ("Unrestricted relation fields", "NYYY"),
    ("Unrestricted relational operators", "NYYY"),
    ("<code>one</code>, <code>lone</code>, <code>no</code> quantifiers",
     "NYYY"),
    ('Scriptability (<a href="#sec6">section 6</a>)', "NYYN"),
    ("LTL operators, infinite-trace semantics", "NNYY"),
    ("Non-compositional shorthand", "NNNY"),
    ("Global constraints, <code>sig</code>-specific constraints", "NNNY"),
]

TABLE2 = [
    ("2022", [("total", "45", "33"), ("Froglet", "36", "0"),
              ("Relational", "8", "18"), ("Temporal", "N/A", "13"),
              ("SMT", "1", "2")]),
    ("2023", [("total", "32", "26"), ("Froglet", "23", "2"),
              ("Relational", "9", "8"), ("Temporal", "N/A", "13"),
              ("SMT", "0", "3")]),
]


_CODE_SPANS = None


def render_code_block(code_lines):
    """Render a listing from spans, preserving keyword weight and spacing.

    `code_lines` are the visual lines classified as code in the default
    extraction; their vertical extent selects the matching spans in the
    -wbt 40 extraction, which is the one that keeps <b> runs and does not
    pad tokens apart.
    """
    global _CODE_SPANS
    if _CODE_SPANS is None:
        _CODE_SPANS = CS.load()

    page = code_lines[0][0].page
    spans = _CODE_SPANS.get(page)
    if not spans:
        return None

    tops = [l[0].top for l in code_lines]
    lo, hi = min(tops) - 4.0, max(tops) + 4.0
    sel = [s for s in spans if lo <= s.top <= hi]
    # Where the page has two columns side by side, selecting on `top` alone
    # drags in the neighbouring column (figure 8's diagram labels), which
    # then merge back into the rows this was meant to separate.
    for top, bottom, x in COLUMN_SPLITS.get(page, []):
        if top <= min(tops) and max(tops) <= bottom:
            right = code_lines[0][0].left >= x
            sel = [s for s in sel if (s.left >= x) == right]
            break
    if not sel:
        return None

    rows = CS.group_rows(sel)
    if len(rows) != len(code_lines):
        return None      # geometry disagrees; let the caller fall back

    unit = CS.width_unit(sel)
    base = min(r[0].left for r in rows if any(s.mono for s in r))

    def roman(txt, span):
        # Prose interleaved with a displayed listing (page 5's "is not
        # equivalent to").  The -wbt 40 pass runs its words together, so
        # take the text from the default pass and keep the emphasis.
        fixed = roman_at(page, span.top, span.left)
        out = esc(fixed) if fixed else txt
        return f"<i>{out}</i>" if span.italic else out

    return "\n".join(
        CS.render_row(r, unit, base, esc,
                      lambda t: f"<b>{t}</b>", roman)
        for r in rows
    )


def figure_images_html(images, label):
    """Emit a figure's images as click-to-enlarge buttons.

    The extracted PNGs are roughly 3x the size the PDF displays them at
    (a 109x111 box holding a 301x307 image), so there is real detail to
    reveal.  The small rendering is kept inline and the full-resolution
    file is shown in a dialog on click.
    """
    n = len(images)
    row = ' figrow' if n > 1 else ''
    out = [f'  <div class="figbody{row}">']
    for i, im in enumerate(images):
        alt = esc(label if n == 1 else f"{label}, image {i + 1} of {n}")
        out.append(
            f'    <button type="button" class="zoom" '
            f'data-full="images/{im["file"]}" '
            f'aria-label="Enlarge {alt}">'
            f'<img src="images/{im["file"]}" alt="{alt}" loading="lazy">'
            f"</button>"
        )
    out.append("  </div>")
    return "\n".join(out)


def table1_html():
    head = ("<thead><tr><th scope=\"col\">Language feature</th>"
            "<th scope=\"col\">Froglet</th><th scope=\"col\">Rel. Forge</th>"
            "<th scope=\"col\">Temporal Forge</th>"
            "<th scope=\"col\">Alloy 6</th></tr></thead>")
    rows = []
    for label, flags in TABLE1_ROWS:
        cells = "".join(YES if f == "Y" else NO for f in flags)
        rows.append(f'<tr><th scope="row">{label}</th>{cells}</tr>')
    return ("<table>\n" + head + "\n<tbody>\n" + "\n".join(rows)
            + "\n</tbody>\n</table>")


# Figure 12 is a table drawn with vector rules, so nothing is extractable
# as an image and its cells flow into nonsense as prose.  Transcribed from
# page 23; "N/A" marks the combinations the caption says are unmeasurable.
FIG12_ROWS = [
    ("total # submissions", ["32", "26", "62", "59"], ["", "", "", ""]),
    ("w/ <code>test suite</code>", ["19", "20", "N/A", "N/A"],
     ["N/A", "N/A", "N/A", "N/A"]),
    ("w/ <code>test expect</code>", ["19", "20", "1", "84"],
     ["5 (6)", "14 (8)", "0 (0)", "4 (4)"]),
    ("w/ <code>example</code>", ["30", "7", "62", "55"],
     ["21 (18)", "21 (15)", "19 (13)", "8 (6)"]),
    ("w/ <code>necessary</code>", ["2", "2", "6", "14"],
     ["2 (1)", "1 (1)", "8 (7)", "5 (5)"]),
    ("w/ <code>sufficient</code>", ["0", "0", "4", "15"],
     ["1 (1)", "0 (0)", "8 (7)", "5 (5)"]),
]

FIG12_COLS = ["mid", "fin", "river", "memory"]

# Figure 11's left-hand panel: the 2023 final projects and how each one was
# visualised.  Transcribed from page 21; the prose says "26 projects in
# total", which the row count checks against.  Markup mirrors the page:
# "Default" is bold (it names the built-in view) and "div" is code.
FIG11_ROWS = [
    ("2048", "D3FX"),
    ("Air Traffic Control", "D3FX"),
    ("Among Us", "<strong>Default</strong> Table"),
    ("Chopsticks Game", "<strong>Default</strong> Table"),
    ("Chopsticks Game (1)", "D3FX"),
    ("Chromatic Sudoku", "Raw D3"),
    ("Connect4", "Raw D3"),
    ("Gomoku", "<code>div</code>-based"),
    ("Grammar Modeling", "Raw D3 &amp; <strong>Default</strong> Graph"),
    ("<em>k</em>-Means Clustering", "Z3 Library"),
    ("Minesweeper", "<code>div</code>-based"),
    ("Minesweeper (1)", "Z3 Library"),
    ("Minesweeper (2)", "D3FX"),
    ("OS Memory Mgmt.", "<strong>Default</strong> Graph"),
    ("Online Payment Sys.", "<strong>Default</strong> Table"),
    ("Polyomino Packing", "Z3 Library"),
    ("RPG Randomizer", "<strong>Default</strong> Graph"),
    ("Runway Traffic", "<code>div</code>-based"),
    ("Rust Lifetimes", "Raw D3"),
    ("Skyscrapers", "Raw D3"),
    ("Spikeball", "D3FX"),
    ("Sudoku", "Raw D3"),
    ("TA Queue", "<code>div</code>-based"),
    ("Texas Hold\u2019em", "<code>div</code>-based"),
    ("Triple Triad", "<code>div</code>-based"),
    ("Uno", "D3FX"),
]


def fig11_table_html():
    rows = "\n".join(
        f'<tr><th scope="row">{title}</th><td>{mode}</td></tr>'
        for title, mode in FIG11_ROWS
    )
    return (
        "<table>\n"
        '<thead><tr><th scope="col">Title</th>'
        '<th scope="col">Visualization</th></tr></thead>\n'
        f"<tbody>\n{rows}\n</tbody>\n</table>"
    )


def fig12_html():
    head = (
        '<thead>\n<tr><td></td>'
        '<th scope="colgroup" colspan="4"># projects using constructs</th>'
        '<th scope="colgroup" colspan="4">avg(median) uses of constructs</th>'
        "</tr>\n<tr><td></td>"
        + "".join(f'<th scope="col"><span class="sc">{c}</span></th>'
                  for c in FIG12_COLS * 2)
        + "</tr>\n</thead>"
    )
    body = []
    for label, a, b in FIG12_ROWS:
        cells = "".join(f"<td>{v}</td>" for v in a)
        cells += "".join(f"<td>{v}</td>" if v else "<td></td>" for v in b)
        body.append(f'<tr><th scope="row">{label}</th>{cells}</tr>')
    return ("<table>\n" + head + "\n<tbody>\n" + "\n".join(body)
            + "\n</tbody>\n</table>")


def table2_html():
    out = []
    for year, rows in TABLE2:
        body = "\n".join(
            f'<tr><th scope="row">{lvl}</th><td>{mid}</td><td>{fin}</td></tr>'
            for lvl, mid, fin in rows
        )
        out.append(
            f'<table>\n<caption>{year}</caption>\n'
            f'<thead><tr><th scope="col">Language level</th>'
            f'<th scope="col">Midterm</th><th scope="col">Final</th></tr>'
            f"</thead>\n<tbody>\n{body}\n</tbody>\n</table>"
        )
    return '<div class="table-pair">\n' + "\n".join(out) + "\n</div>"


def link_crossrefs(body_html, ref_ids):
    """Turn the paper's own cross-references into links.

    Only rewrites text outside tags, so attribute values and existing
    anchors are never touched.
    """
    # A trailing (?![\w.]) keeps "fig. 8a" and "section 7.2.4" intact:
    # without it the number is cut short and a stray "a" is left behind.
    sec = re.compile(r"\b([Ss]ections?|§)\s*(\d+(?:\.\d+)*)(?![\w.])")
    fig = re.compile(
        r"\b([Ff]ig(?:ure)?s?\.?)\s*(\d+)(?![\w.])(?:\s+and\s+(\d+)(?![\w.]))?")
    tab = re.compile(r"\b([Tt]ables?)\s*(\d+)(?![\w.])")

    def sub_text(t):
        t = sec.sub(lambda m: f'{m.group(1)} <a href="#sec{m.group(2)}">'
                              f"{m.group(2)}</a>", t)
        def figrep(m):
            a = f'{m.group(1)} <a href="#fig{m.group(2)}">{m.group(2)}</a>'
            if m.group(3):
                a += f' and <a href="#fig{m.group(3)}">{m.group(3)}</a>'
            return a
        t = fig.sub(figrep, t)
        t = tab.sub(lambda m: f'{m.group(1)} <a href="#tab{m.group(2)}">'
                              f"{m.group(2)}</a>", t)
        return t

    out = []
    in_anchor = False
    for i, chunk in enumerate(re.split(r"(<[^>]+>)", body_html)):
        if i % 2 == 1:
            # never rewrite inside an existing <a>: the hand-built tables
            # already carry links, and nesting anchors is invalid HTML
            if re.match(r"<a\b", chunk):
                in_anchor = True
            elif re.match(r"</a\b", chunk):
                in_anchor = False
            out.append(chunk)
        elif in_anchor or not chunk.strip():
            out.append(chunk)
        else:
            out.append(sub_text(chunk))
    return "".join(out)


def build_toc(body_html):
    items = re.findall(
        r'<(h2|h3) id="(sec[\d.]+)"[^>]*>(.*?)</\1>', body_html, re.S)
    # A nested list must sit *inside* the <li> it belongs to, so the parent
    # item is held open until its children are emitted.
    lines = ['<h2>Contents</h2>', "<ol>"]
    depth = 2
    open_li = False
    for tag, hid, inner in items:
        text = re.sub(r"<[^>]+>", "", inner).strip()
        lvl = 2 if tag == "h2" else 3
        if lvl > depth:
            lines.append("<ol>")           # inside the still-open parent <li>
            depth = lvl
        while lvl < depth:
            lines.append("</ol>")
            lines.append("</li>")
            depth -= 1
            open_li = False
        if lvl == depth and open_li and lvl == 2:
            lines.append("</li>")
            open_li = False
        if lvl == 2:
            lines.append(f'<li><a href="#{hid}">{esc(text)}</a>')
            open_li = True
        else:
            lines.append(f'<li><a href="#{hid}">{esc(text)}</a></li>')
    while depth > 2:
        lines.append("</ol>")
        lines.append("</li>")
        depth -= 1
        open_li = False
    if open_li:
        lines.append("</li>")
    lines.append("</ol>")
    return "\n".join(lines)


# Section titles are set in all caps by acmart; restore normal case.
# Words that must not be lower-cased, and acronyms that must stay upper.
TITLE_MINOR = {"a", "an", "and", "as", "at", "but", "by", "for", "from",
               "in", "into", "of", "on", "or", "the", "to", "vs", "with"}
TITLE_UPPER = {"FM", "LTL", "SMT", "RQ1", "RQ2", "RQ3", "OS", "ACM"}


def title_case(s):
    words = s.split()
    out = []
    after_colon = True
    for i, w in enumerate(words):
        core = w.strip(":,.")
        punct = w[len(core):]
        if core.upper() in TITLE_UPPER:
            new = core.upper()
        elif not after_colon and i != len(words) - 1 \
                and core.lower() in TITLE_MINOR:
            new = core.lower()
        else:
            # capitalise each part of a hyphenated compound
            new = "-".join(p.capitalize() for p in core.split("-"))
        out.append(new + punct)
        after_colon = w.endswith(":")
    return " ".join(out)


# Vertical bands holding the two tabular figures.  Their cells flow into
# meaningless prose if treated as body text, and they are re-created by
# hand as real <table>s, so the raw lines are skipped.
TABLE_REGIONS = {
    7: (190.0, 350.0),
    14: (170.0, 280.0),
    # Figure 11's project table occupies the left column down to the main
    # caption; the screenshots beside it are a separate column (see
    # COLUMN_SPLITS) and must not be swept up with it.
    21: (125.0, 600.0, 0.0, 380.0),
    23: (125.0, 275.0),
}

# Regions where the page is laid out in two columns side by side, and the
# boundary between them.  Lines are grouped by their vertical position, so
# without this a diagram label at x=184 and a line of code at x=351 that
# happen to share a baseline are merged into one "line" -- which is what
# shredded figure 8.
COLUMN_SPLITS = {
    12: [(128.0, 285.0, 340.0)],   # fig 8: diagram (a) | code listing (b)
    21: [(125.0, 600.0, 380.0)],   # fig 11: project table | screenshots
}


def split_columns(spans):
    """Group spans into lines, honouring side-by-side column boundaries."""
    plain, split = [], {}
    for s in spans:
        for top, bottom, x in COLUMN_SPLITS.get(s.page, []):
            if top <= s.top <= bottom:
                key = (s.page, top, bottom, s.left >= x)
                split.setdefault(key, []).append(s)
                break
        else:
            plain.append(s)
    lines_out = L.group_lines(plain)
    for key in sorted(split):
        lines_out.extend(L.group_lines(split[key]))
    return sorted(lines_out, key=lambda ln: (ln[0].page, ln[0].top,
                                             ln[0].left))


# Vector figures: their labels are page text, not an image, so left as body
# they interleave with whatever sits beside them.  The regions are rendered
# to PNG by vectorfigs.py and the underlying text is dropped here.
#
# Figure 8 is two panels side by side; only panel (a), the diagram, is
# rasterised.  Panel (b) is a code listing and stays real text, so the
# region stops at the column boundary (x=340) rather than spanning the page.
VECTOR_REGIONS = {
    12: [(128.0, 285.0, 0.0, 340.0)],     # fig 8(a) architecture diagram
    15: [(126.0, 268.0, 0.0, 1000.0)],    # fig 9 survey rating matrix
}


# LaTeX `description` lists: a bold run-in term at one indent, its body
# indented further under it.  Flattened into <p><strong>term</strong> text
# the relationship is only typographic; as a <dl> it is in the markup.
DESC_TERM_LEFT = (88.0, 93.0)
DESC_BODY_LEFT = (100.0, 110.0)


def is_desc_term(line):
    lo, hi = DESC_TERM_LEFT
    return (lo <= line[0].left <= hi
            and line[0].family in ("LinLibertineTB", "LinLibertineTI"))


def is_desc_body(line):
    lo, hi = DESC_BODY_LEFT
    return lo <= line[0].left <= hi


def in_vector_region(line):
    for top, bottom, left, right in VECTOR_REGIONS.get(line[0].page, []):
        if top <= line[0].top <= bottom and left <= line[0].left <= right:
            return True
    return False


def in_table_region(line):
    region = TABLE_REGIONS.get(line[0].page)
    if not region:
        return False
    top, bottom = region[0], region[1]
    if not (top <= line[0].top <= bottom):
        return False
    if len(region) == 4:      # also bounded horizontally
        return region[2] <= line[0].left <= region[3]
    return True


def slug(text):
    s = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
    return s[:60]


def main():
    spans = L.parse_spans()
    body = L.body_spans(spans)
    all_lines = split_columns(body)

    # ---- split off front matter (page 1) and references (after REFERENCES)
    ref_idx = None
    for i, ln in enumerate(all_lines):
        if L.line_text(ln).strip() == "REFERENCES":
            ref_idx = i
            break

    front = [ln for ln in all_lines if ln[0].page == 1]
    main_lines = [ln for ln in all_lines[:ref_idx] if ln[0].page > 1]

    # The bibliography must be parsed *before* the body is rendered, so
    # citation annotations can be resolved to entry anchors as they are
    # emitted.
    ref_items = build_refs()
    resolve_links(all_lines, ref_items)

    # Notes are rendered first (with sidenote emission off, so a note
    # cannot nest inside itself), then placed at their reference marks.
    global EMIT_SIDENOTES
    FOOTNOTES.update(collect_footnotes(all_lines))
    EMIT_SIDENOTES = True

    body_html = build_body(main_lines)
    body_html = link_crossrefs(body_html, {})
    refs_html = render_refs(ref_items, BACKREFS)

    front_html = build_front(front)
    front_html = front_html.replace("<!--TOC-->", build_toc(body_html))

    doc = PAGE_TEMPLATE.format(
        body="\n".join([front_html, body_html, refs_html]))
    with open(OUT, "w", encoding="utf-8") as fh:
        fh.write(doc)

    cited = len(BACKREFS)
    print(f"wrote {OUT} ({len(doc)} bytes)")
    print(f"citations resolved: {CITE_ID_SEQ[0]} to {cited} entries; "
          f"unresolved: {len(UNRESOLVED)}")
    for name, year, page in UNRESOLVED[:20]:
        print(f"   ? {name} {year} (pdf points at p{page})")



# ---------------------------------------------------------------- front page


def build_front(front):
    texts = [L.line_text(ln).strip() for ln in front]
    title = texts[0]

    # The author list is set in all caps, which loses the intercaps in
    # names like "LeVine".  The addresses block further down the page
    # spells every name in normal case, so use it as the authority.
    canon = {}
    addr = " ".join(texts)
    m = re.search(r"Authors\u2019 addresses:(.*)", addr, re.S)
    if m:
        for chunk in m.group(1).split(";"):
            nm = chunk.strip().split(",")[0].strip()
            nm = re.sub(r"\s+", " ", nm)
            if re.match(r"^[A-Z][A-Za-z\u2019.\-]*(?: [A-Z][A-Za-z\u2019.\-]*)+$",
                        nm):
                canon[nm.upper()] = nm

    authors = []
    i = 1
    while i < len(texts) and re.match(r"^[A-Z][A-Z\u2019.\- ]+,", texts[i]):
        name, _, aff = texts[i].partition(",")
        key = re.sub(r"\s+", " ", name.strip()).upper()
        authors.append((canon.get(key, name.strip().title()), aff.strip()))
        i += 1

    # abstract runs until the CCS Concepts line
    abs_lines = []
    while i < len(texts) and not texts[i].startswith("CCS Concepts"):
        abs_lines.append(texts[i])
        i += 1
    # the abstract has two paragraphs; the second starts at "Forge offers"
    abstract = join_lines(abs_lines)
    parts = abstract.split("Forge offers a progression")
    abs_html = f"<p>{esc(parts[0].strip())}</p>"
    if len(parts) > 1:
        abs_html += ("\n<p>Forge offers a progression"
                     f"{esc(parts[1])}</p>")

    ccs = keywords = ""
    if i < len(texts):
        ccs = texts[i][len("CCS Concepts:"):].strip()
        i += 1
    for t in texts[i:]:
        if t.startswith("Additional Key Words"):
            keywords = t.split(":", 1)[1].strip()

    ol = "\n".join(
        f'    <li>{esc(n)}<span class="aff">{esc(a)}</span></li>'
        for n, a in authors
    )
    return f"""<p class="provenance">
  This is an <b>unofficial HTML rendering</b> of a paper published at OOPSLA
  2024, reproduced under its
  <a href="https://creativecommons.org/licenses/by/4.0/">CC&nbsp;BY&nbsp;4.0</a>
  licence. It is not published by, or endorsed by, the authors or the ACM.
  The authoritative version is the
  <a href="{SRC_URL}">original PDF</a> (<a href="{DOI}">{DOI}</a>);
  quote from that, not from this page.
  <!-- data-web-only marks content that ./make-epub strips: inside the EPUB
       this would link to a missing file and describe the file being read. -->
  <span data-web-only>This rendering is also available as an
  <a href="forge-paper.epub" type="application/epub+zip">EPUB</a> for
  e&#8209;readers.</span>
</p>

<header class="paper-head">
  <p class="venue">Proc. ACM Program. Lang. <b>8</b>, OOPSLA1, Article 116
     (April 2024) &middot; 29 pages</p>
  <h1>{esc(title)}</h1>
  <ol class="authors">
{ol}
  </ol>
</header>

<section class="abstract" aria-label="Abstract">
  <h2>Abstract</h2>
  {abs_html}
  <p class="ccs"><b>CCS Concepts:</b> {esc(ccs)}</p>
  <p class="kw"><b>Keywords:</b> {esc(keywords)}</p>
</section>

<nav class="toc" aria-label="Table of contents"><!--TOC--></nav>
"""


# --------------------------------------------------------------------- body


def build_body(main_lines):
    out = []
    para = []          # accumulating body lines
    cap = []           # accumulating caption lines
    code = []          # accumulating code lines
    footnotes = []
    fn_buf = []
    list_items = []
    list_kind = None
    desc_item = []     # lines of the description item being accumulated
    desc_pairs = []    # (term, definition) pairs of the open <dl>
    used_layout = {}   # page -> consumed layout line indices
    fig_counter = {"fig": 0, "tab": 0}
    img_queue = {p: list(v) for p, v in IMAGES.items()}
    claimed = {}   # page -> top of the last caption that took images

    def flush_para():
        nonlocal para
        if para:
            txt = join_lines([render_inline(l) for l in para])
            if txt.strip():
                out.append(f"<p>{txt}</p>")
            para = []

    def flush_list():
        nonlocal list_items, list_kind
        if list_items:
            tag = "ul" if list_kind == "bullet" else "ol"
            out.append(f"<{tag}>")
            for it in list_items:
                out.append(f"  <li>{it}</li>")
            out.append(f"</{tag}>")
            list_items = []
            list_kind = None

    def flush_desc(close=True):
        """Close the current description item, and the <dl> around it.

        The term is the bold run-in text at the start of the item; the rest
        of the item is its definition.  Rendering both into <dt>/<dd> keeps
        the relationship in the markup instead of only in the typography.
        """
        nonlocal desc_item, desc_pairs
        if desc_item:
            first = desc_item[0]
            # The term is the *leading* run of label-font spans only.
            # Collecting every matching span on the line would also pick up
            # emphasis from mid-sentence ("a progression of sub-languages").
            label_font = first[0].family
            parts = []
            for s in first:
                if s.family != label_font:
                    break
                parts.append(s.text)
            term = "".join(parts).strip().rstrip(":")
            html_txt = join_lines([render_inline(l) for l in desc_item])
            body = re.sub(
                r"^\s*(?:<(?:strong|em)>\s*)?" + re.escape(esc(term))
                + r"\s*:?\s*(?:</(?:strong|em)>)?\s*:?\s*",
                "", html_txt, count=1)
            body = body.strip()
            if body:
                desc_pairs.append((esc(term), body))
            else:
                # A label on a line of its own ("Frustrations:") introduces
                # the bullet list beneath it rather than a definition; an
                # empty <dd> would be a lie.  Emit it as a lead-in instead.
                flush_desc_pairs()
                out.append(f'<p class="runin">{esc(term)}:</p>')
            desc_item = []
        if close:
            flush_desc_pairs()

    def flush_desc_pairs():
        nonlocal desc_pairs
        if desc_pairs:
            out.append("<dl>")
            for term, body in desc_pairs:
                out.append(f"  <dt>{term}</dt>")
                out.append(f"  <dd>{body}</dd>")
            out.append("</dl>")
            desc_pairs = []

    def flush_code():
        nonlocal code
        if not code:
            return
        block = render_code_block(code)
        if block is None:
            # fall back to the layout extraction, which has the right shape
            # but no keyword weight
            page = code[0][0].page
            want = "".join(CB.sig(L.line_text(l)) for l in code)
            used = used_layout.setdefault(page, set())
            lay = CB.find_block(page, want, used)
            lay = lay if lay is not None else [L.line_text(l) for l in code]
            block = esc("\n".join(lay))
        out.append("<pre><code>" + block + "</code></pre>")
        code = []

    def flush_caption():
        nonlocal cap
        if not cap:
            return
        txt = join_lines([render_inline(l) for l in cap])
        plain = re.sub("<[^>]+>", "", txt)
        m = re.match(r"^(Fig\.|Table)\s*(\d+)\.\s*(.*)$", plain, re.S)
        page = cap[0][0].page
        if m:
            kind, num = m.group(1), m.group(2)
            anchor = ("fig" if kind.startswith("Fig") else "tab") + num
            label = f"{'Figure' if kind.startswith('Fig') else 'Table'} {num}"
            # Strip the label from the *marked-up* text.  Splitting on the
            # first "." would cut inside "Fig." and duplicate the number.
            body_html = re.sub(
                r"^\s*(?:<[^>]+>\s*)*(Fig\.|Table)\s*\d+\.\s*", "", txt
            ).strip()
            # Claim the images sitting above this caption but below the
            # previous one on the same page.
            # An image belongs to this caption only if it lies *entirely*
            # above it.  Comparing the image's top would mis-assign a tall
            # right-column image that starts above the caption of the
            # figure before it (page 9, figs. 5 and 6).
            cap_top = cap[0][0].top
            avail = img_queue.get(page) or []
            take = [im for im in avail
                    if im["top"] + im["height"] <= cap_top]
            inner = ""
            if take:
                claimed[page] = cap_top
                img_queue[page] = [im for im in avail if im not in take]
                # Order by column first, then by row.  A caption that says
                # "Left: ... Right: ..." describes the page's left-to-right
                # order, and bucketing by row put a narrow right-column
                # image before the wide left-column one it contrasts with
                # (page 9, fig. 6).
                take.sort(key=lambda im: (im["left"] // 200, im["top"]))
                inner = figure_images_html(take, label)
            # the two tabular figures get their hand-transcribed markup
            if not inner and anchor == "tab1":
                inner = "  " + table1_html()
            elif not inner and anchor == "fig12":
                inner = "  " + fig12_html()
            elif not inner and anchor == "tab2":
                inner = "  " + table2_html()
            elif anchor == "fig8":
                # Two panels: (a) is vector art, rasterised by vectorfigs.py;
                # (b) is a code listing and stays selectable text.
                #
                # The panel subcaptions ("(a) ... (b) ...") arrive as their
                # own caption line between the listing and this caption;
                # drop it, since each panel gets its own <figcaption> below.
                listing = ""
                for i in range(len(out) - 1, max(-1, len(out) - 4), -1):
                    if out[i].startswith("<pre>"):
                        listing = out.pop(i)
                        break
                    if out[i].startswith('<p class="caption">'):
                        out.pop(i)
                inner = (
                    '  <div class="figbody figrow">\n'
                    '    <figure class="subfig">\n'
                    '      <button type="button" class="zoom" '
                    'data-full="images/fig8a.png" '
                    'aria-label="Enlarge the Forge architecture diagram">'
                    '<img src="images/fig8a.png" '
                    'alt="Forge architecture: a visualizer over a surface '
                    'language over a core language over the Pardinus solver, '
                    'with custom visualization and navigation feeding the '
                    'visualizer, and a domain model compiling through '
                    'helper predicates and #lang to the solver." '
                    'loading="lazy"></button>\n'
                    "      <figcaption>(a) Forge architecture</figcaption>\n"
                    "    </figure>\n"
                    '    <figure class="subfig">\n'
                    f"      {listing}\n"
                    "      <figcaption>(b) Core Forge version of a temporal "
                    'program (<a href="#fig3">fig. 3</a>)</figcaption>\n'
                    "    </figure>\n"
                    "  </div>"
                )
            elif anchor == "fig9":
                # The survey question is a matrix of vector-drawn radio
                # buttons; the response chart below it is a real image.
                matrix = (
                    '    <button type="button" class="zoom" '
                    'data-full="images/fig9matrix.png" '
                    'aria-label="Enlarge the survey question">'
                    '<img src="images/fig9matrix.png" '
                    'alt="Survey question. Prompt: run { some c: Course | c '
                    'in c.prereqs }. Respondents rate four outcomes (SAT, '
                    "UNSAT, an unknown-field error, and a course-cannot-be-"
                    "its-own-prereq error) on a four-point scale from "
                    'expected and liked to unexpected and disliked." '
                    'loading="lazy"></button>'
                )
                if inner:
                    inner = inner.replace(
                        '<div class="figbody">',
                        f'<div class="figbody">\n{matrix}', 1)
                    # describe the response chart, rather than leaving it
                    # labelled with the figure number
                    chart_alt = (
                        "Bar chart of the 2023 responses to the question "
                        "above, grouped by outcome and coloured by the four "
                        "expected/liked combinations."
                    )
                    inner = re.sub(
                        r'(data-full="images/img-015-021\.png"[^>]*>'
                        r'<img src="images/img-015-021\.png" )alt="[^"]*"',
                        lambda m: m.group(1) + f'alt="{chart_alt}"',
                        inner)
                    inner = inner.replace(
                        'aria-label="Enlarge Figure 9"',
                        'aria-label="Enlarge the response chart"')
                else:
                    inner = f'  <div class="figbody">\n{matrix}\n  </div>'
            elif anchor == "fig11":
                # Two panels: a table of projects on the left, three
                # screenshots with their own subcaptions on the right.
                shots = [
                    ("img-021-027.png", "(a) Spikeball (D3FX)",
                     "A Spikeball game state: a grid of coloured player "
                     "tokens beside a panel of per-team scores and touches."),
                    ("img-021-029.png",
                     "(b) Uno (D3FX) and Triple Triad "
                     "(<code>div</code>-based)",
                     "Two visualisations side by side: an Uno hand of "
                     "coloured number cards, and a Triple Triad board of "
                     "numbered tiles."),
                    ("img-021-033.png",
                     "(c) Texas Hold\u2019em (<code>div</code>-based)",
                     "A Texas Hold\u2019em table showing two players' hands "
                     "and the community cards."),
                ]
                panels = "\n".join(
                    '    <figure class="subfig">\n'
                    f'      <button type="button" class="zoom" '
                    f'data-full="images/{f}" '
                    f'aria-label="Enlarge {re.sub("<[^>]+>", "", cap)}">'
                    f'<img src="images/{f}" alt="{alt}" loading="lazy">'
                    "</button>\n"
                    f"      <figcaption>{cap}</figcaption>\n"
                    "    </figure>"
                    for f, cap, alt in shots
                )
                inner = (
                    '  <div class="figbody figsplit">\n'
                    '    <div class="figtable">\n'
                    f"      {fig11_table_html()}\n"
                    "    </div>\n"
                    '    <div class="figshots">\n'
                    f"{panels}\n"
                    "    </div>\n"
                    "  </div>"
                )
                img_queue[page] = []
            # a code listing immediately preceding becomes the figure content
            if not inner and out and out[-1].startswith("<pre>"):
                inner = "  " + out.pop()
            out.append(
                f'<figure id="{anchor}">\n{inner}\n'
                f'  <figcaption><b>{label}.</b> {body_html}</figcaption>\n'
                f"</figure>"
            )
        else:
            out.append(f'<p class="caption">{txt}</p>')
        cap = []

    def flush_all():
        flush_code()
        flush_caption()
        flush_para()
        flush_list()
        flush_desc()

    prev_role = None
    for i, ln in enumerate(main_lines):
        if in_table_region(ln) or in_vector_region(ln):
            continue
        role = classify(ln)
        txt = L.line_text(ln).strip()

        if role == "code":
            flush_caption()
            flush_para()
            flush_list()
            code.append(ln)
            prev_role = role
            continue
        if role != "code" and code:
            flush_code()

        if role == "caption":
            flush_para()
            flush_list()
            # A new "Fig. n."/"Table n." label starts a new caption even if
            # the previous one is still open (figures 5 and 6 are adjacent).
            if cap and re.match(r"^(Fig\.|Table)\s*\d+\.", txt):
                flush_caption()
            cap.append(ln)
            prev_role = role
            continue
        if role != "caption" and cap:
            flush_caption()

        if role == "heading":
            flush_all()
            num = txt.split()[0]
            rest = txt[len(num):].strip()
            if re.match(r"^\d+$", num):
                out.append(f'<h2 id="sec{num}">'
                           f'<span class="num">{num}</span> {esc(title_case(rest))}</h2>')
            elif re.match(r"^\d+\.\d+$", num):
                out.append(f'<h3 id="sec{num}">'
                           f'<span class="num">{num}</span> {esc(rest)}</h3>')
            else:
                out.append(f'<h2 id="{slug(txt)}">{esc(title_case(txt))}</h2>')
            prev_role = role
            continue

        if role == "subsub":
            flush_all()
            # The heading title is exactly the italic run; the roman text
            # after it already belongs to the first paragraph.  Splitting on
            # "." instead would break at "vs." and miss titles ending in "?".
            # Only LinBiolinumTI (sans italic) is the heading; body emphasis
            # on the same line is LinLibertineTI (serif italic).
            head = "".join(s.text for s in ln
                           if s.family == "LinBiolinumTI"
                           and round(s.size) == 15).strip()
            head = re.sub(r"^\d+(\.\d+)*\s*", "", head).strip()
            num_m = re.match(r"^(\d+\.\d+\.\d+)", txt)
            if head and num_m:
                num = num_m.group(1)
                rest = txt[len(num):].strip()
                if rest.startswith(head):
                    rest = rest[len(head):].strip()
                out.append(f'<h4 id="sec{num}">'
                           f'<span class="num">{num}</span> {esc(head)}</h4>')
                if rest:
                    para.append([_TextSpan(rest)])
                prev_role = role
                continue
            m = re.match(r"^(\d+\.\d+\.\d+)\s+(.*?\.)\s*(.*)$", txt, re.S)
            if m:
                num, head, rest = m.groups()
                out.append(f'<h4 id="sec{num}">'
                           f'<span class="num">{num}</span> {esc(head)}</h4>')
                if rest.strip():
                    para.append([_TextSpan(rest)])
            else:
                out.append(f"<h4>{esc(txt)}</h4>")
            prev_role = role
            continue

        if role == "footnote":
            fn_buf.append(ln)
            prev_role = role
            continue
        if role != "footnote" and fn_buf:
            footnotes.append(fn_buf)
            fn_buf = []

        if role in ("bullet", "enum"):
            flush_para()
            flush_desc()
            if list_kind and list_kind != role:
                flush_list()
            list_kind = role
            inner = render_inline(ln)
            inner = re.sub(r"^\s*(\u2022|\(\d+\))\s*", "", inner)
            list_items.append(inner)
            prev_role = role
            continue

        # A description list: bold run-in term, body indented beneath it.
        if role == "body" and is_desc_term(ln):
            flush_para()
            flush_list()
            # Close the previous item but keep the <dl> open, so that
            # consecutive terms become siblings in one list.
            flush_desc(close=False)
            desc_item.append(ln)
            prev_role = role
            continue

        if role == "body" and desc_item and is_desc_body(ln):
            desc_item.append(ln)
            prev_role = role
            continue

        if desc_item and role == "body" and not is_desc_body(ln):
            flush_desc()

        if role == "body":
            if list_items and ln[0].left > 95:
                # continuation of the current list item
                list_items[-1] = join_lines([list_items[-1],
                                             render_inline(ln)])
                prev_role = role
                continue
            flush_list()
            # a new paragraph starts on an indented line
            if para and ln[0].left > 75 and ln[0].left < 95:
                flush_para()
            para.append(ln)
            prev_role = role
            continue

    flush_all()
    if fn_buf:
        footnotes.append(fn_buf)

    # Footnotes are emitted as sidenotes at their reference mark (see
    # sidenote_html), so no trailing notes section is produced.  Any note
    # whose mark was never found would be lost, so report that instead of
    # dropping it silently.
    missed = sorted(set(FOOTNOTES) - SIDENOTES_DONE)
    if missed:
        out.append('<section class="footnotes" aria-label="Notes">')
        out.append("<h2>Notes</h2>\n<ol>")
        for n in missed:
            out.append(f'  <li id="fn{n}">{FOOTNOTES[n]}</li>')
        out.append("</ol>\n</section>")
        UNPLACED_NOTES.extend(missed)

    return "\n".join(out)


class _TextSpan:
    """Minimal span stand-in for text recovered from a run-in heading line."""
    def __init__(self, text):
        self.text = text
        self.left = 0.0
        self.width = 0.0
        self.right = 0.0
        self.mono = self.italic = self.bold = self.smallcaps = False
        self.pieces = [[text, None, None]]
        self.size = 15.0
        self.family = "LinLibertineT"
        self.top = 0.0
        self.page = 0


# -------------------------------------------------------------- bibliography


_ANNOT_URLS = None


def annotation_urls():
    """Every URL the PDF's own link annotations declare on the reference pages.

    These are authoritative: they say where a link *goes*, independently of
    where the visible text happens to end.
    """
    global _ANNOT_URLS
    if _ANNOT_URLS is None:
        raw = open("spans.xml", encoding="utf-8").read()
        urls = set()
        for pm in re.finditer(
                r'<page number="(\d+)".*?(?=<page number=|</pdf2xml>)',
                raw, re.S):
            if int(pm.group(1)) < 26:
                continue
            for m in re.finditer(r'<a href="(https?://[^"]+)"', pm.group(0)):
                urls.add(html.unescape(m.group(1)))
        _ANNOT_URLS = urls
    return _ANNOT_URLS


def linkify_urls(text):
    """Wrap URLs in anchors, ending each one where the PDF says it ends.

    A reference often continues after its URL ("...ecp04012.pdf . Accessed
    2024-01-25"), and a greedy match swallows that into the href, producing
    a dead link.  Where the annotations know the URL, use their length as
    the boundary; otherwise fall back to trimming trailing punctuation.
    """
    known = sorted(annotation_urls(), key=len, reverse=True)

    def repl(m):
        cand = m.group(0)
        for url in known:
            if cand.startswith(esc(url)):
                rest = cand[len(esc(url)):]
                return f'<a href="{esc(url)}">{esc(url)}</a>{rest}'
        trimmed = cand.rstrip(".,;)")
        rest = cand[len(trimmed):]
        return f'<a href="{trimmed}">{trimmed}</a>{rest}'

    return re.sub(r"https?://\S+", repl, text)


def build_refs():
    entries = []
    cur = []
    cur_page = None
    for p in range(26, 30):
        txt = open(f"pages/p{p}.txt", encoding="utf-8").read().split("\n")
        if p == 26:
            k = [n for n, l in enumerate(txt) if l.strip() == "REFERENCES"]
            txt = txt[k[0] + 1:] if k else []
        for raw in txt:
            if not raw.strip():
                continue
            s = raw.strip()
            # The running head is one text line holding two fields, e.g.
            # "116:28            Nelson, et al." — matching either field
            # anywhere on the line is what catches it.
            if s.startswith("Proc. ACM Program. Lang.") or \
               re.match(r"^116:\d+\b", s) or \
               s.endswith("Nelson, et al.") or \
               s.startswith("Forge: A Tool and Language"):
                continue
            indent = len(raw) - len(raw.lstrip())
            if indent == 0:
                if cur:
                    entries.append((cur, cur_page))
                cur = [s]
                cur_page = p     # page the entry *starts* on
            else:
                cur.append(s)
    if cur:
        entries.append((cur, cur_page))

    items = []
    for n, (e, page) in enumerate(entries, 1):
        t = join_lines(e)
        t = CB._fix(t)
        t = esc(t)
        # DOIs and URLs are broken across lines by the typesetter; close
        # those breaks up first.
        t = re.sub(r"(https?://\S*?)\s+(\S)", r"\1\2", t)
        t = linkify_urls(t)
        items.append((f"ref{n}", page, t))
    return items


def render_refs(items, backrefs):
    out = ['<section class="references" id="references">',
           "<h2>References</h2>", "<ol>"]
    for rid, _page, t in items:
        back = ""
        sites = backrefs.get(rid, [])
        if sites:
            links = " ".join(
                f'<a href="#{cid}" aria-label="back to citation">\u21a9</a>'
                for cid in sites
            )
            back = f' <span class="backrefs">{links}</span>'
        out.append(f'  <li id="{rid}">{t}{back}</li>')
    out.append("</ol>\n</section>")
    return "\n".join(out)


PAGE_TEMPLATE = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Forge: A Tool and Language for Teaching Formal Methods</title>
<meta name="author" content="Tim Nelson, Ben Greenman, Siddhartha Prasad, Tristan Dyer, Ethan Bove, Qianfan Chen, Charles Cutting, Thomas Del Vecchio, Sidney LeVine, Julianne Rudner, Ben Ryjikov, Alexander Varga, Andrew Wagner, Luke West, Shriram Krishnamurthi">
<meta name="description" content="Forge is a tool for teaching formal methods gradually, based on Alloy. OOPSLA 2024.">
<link rel="canonical" href="https://doi.org/10.1145/3649833">
<style>
:root {{
  --ink: #16161a;
  --muted: #5a5a66;
  --rule: #d8d8e0;
  --link: #7c1773;
  --accent: #004f91;
  --bg: #fdfdfb;
  --code-bg: #f4f4f0;
}}
@media (prefers-color-scheme: dark) {{
  :root {{
    --ink: #e6e6e6; --muted: #a0a0ac; --rule: #33333c;
    --link: #d79ad2; --accent: #8ab8e6; --bg: #16161a; --code-bg: #22222a;
  }}
}}
* {{ box-sizing: border-box; }}
html {{ font-size: 17px; }}
body {{
  margin: 0 auto; padding: 2.5rem 1.25rem 6rem; max-width: 42rem;
  background: var(--bg); color: var(--ink);
  font-family: "Linux Libertine", Libertinus Serif, Palatino, Georgia, serif;
  line-height: 1.6; text-rendering: optimizeLegibility;
}}
a {{ color: var(--link); }}
a:hover {{ text-decoration-thickness: 2px; }}
h1 {{ font-size: 1.9rem; line-height: 1.25; margin: 0 0 1rem; font-weight: 600; }}
h2, h3, h4 {{
  font-family: "Linux Biolinum", Optima, "Segoe UI", system-ui, sans-serif;
  line-height: 1.3; margin: 2.4rem 0 .6rem; font-weight: 600;
}}
h2 {{ font-size: 1.35rem; border-bottom: 1px solid var(--rule); padding-bottom: .3rem; }}
h3 {{ font-size: 1.12rem; }}
h4 {{ font-size: 1rem; display: inline; margin-right: .4rem; }}
h4 + p {{ display: inline; }}
.num {{ color: var(--muted); font-variant-numeric: tabular-nums; margin-right: .35em; }}
p {{ margin: 0 0 .85rem; hyphens: auto; }}
.venue {{ color: var(--muted); font-size: .82rem; margin-bottom: .6rem; }}
.paper-head {{ border-bottom: 2px solid var(--rule); padding-bottom: 1.2rem; }}
ol.authors {{ list-style: none; margin: 0; padding: 0;
  display: flex; flex-wrap: wrap; gap: .15rem 1.1rem; font-size: .92rem; }}
ol.authors li {{ white-space: nowrap; }}
.aff {{ color: var(--muted); font-size: .8rem; margin-left: .35em; }}
.abstract {{ margin: 1.8rem 0; font-size: .97rem; }}
.abstract h2 {{ font-size: .82rem; text-transform: uppercase;
  letter-spacing: .09em; border: 0; color: var(--muted); margin: 0 0 .5rem; }}
.ccs, .kw {{ font-size: .85rem; color: var(--muted); }}
code {{
  font-family: Inconsolata, "SF Mono", ui-monospace, Menlo, monospace;
  font-size: .88em; background: var(--code-bg); padding: .08em .3em;
  border-radius: 3px; word-break: break-word;
}}
pre {{
  background: var(--code-bg); border: 1px solid var(--rule); border-radius: 5px;
  padding: .85rem 1rem; overflow-x: auto; margin: 0; line-height: 1.45;
}}
pre code {{ background: none; padding: 0; font-size: .84rem; white-space: pre; }}
/* Only images are centred.  Setting text-align on the figure itself would
   be inherited by <pre>, centring every line of a code listing. */
figure {{ margin: 1.8rem 0; }}
figure .figbody {{ text-align: center; }}
figure pre {{ text-align: left; }}
figure img {{ max-width: 100%; height: auto; border: 1px solid var(--rule);
  border-radius: 4px; background: #fff; display: block; margin: 0 auto; }}
/* Figures that hold several images sit side by side until the screen is
   too narrow, then stack. */
.figrow {{ display: flex; flex-wrap: wrap; gap: .75rem;
  justify-content: center; align-items: flex-end; }}
.figrow .zoom {{ flex: 0 1 auto; max-width: 100%; }}
/* A figure whose two halves are different kinds of thing: a table beside a
   stack of screenshots (fig. 11).  They sit side by side while there is
   room and stack when there is not. */
.figsplit {{ display: flex; flex-wrap: wrap; gap: 1.2rem;
  align-items: flex-start; justify-content: center; }}
.figsplit .figtable {{ flex: 1 1 20rem; min-width: 16rem; }}
.figsplit .figtable table {{ margin: 0; font-size: .82rem; }}
.figsplit .figtable td, .figsplit .figtable th {{ padding: .18rem .4rem; }}
.figsplit .figshots {{ flex: 1 1 16rem; display: flex;
  flex-direction: column; gap: .7rem; align-items: center; }}
.figsplit .subfig {{ margin: 0; }}
.subfig figcaption {{ text-align: center; font-size: .8rem;
  margin-top: .35rem; }}
button.zoom {{ padding: 0; border: 0; background: none; cursor: zoom-in;
  display: inline-block; max-width: 100%; }}
button.zoom:focus-visible img {{ outline: 3px solid var(--accent);
  outline-offset: 2px; }}
button.zoom:hover img {{ border-color: var(--accent); }}
dialog.lightbox {{ border: 0; padding: 0; background: none; max-width: 100vw;
  max-height: 100vh; width: 100%; height: 100%; overflow: auto; }}
dialog.lightbox::backdrop {{ background: rgba(0, 0, 0, .82); }}
dialog.lightbox img {{ display: block; margin: auto; background: #fff;
  border-radius: 4px; max-width: 96vw; }}
/* The images are ~3x the size the PDF showed them at, so enlarging is
   worthwhile; allow panning when the natural size exceeds the viewport. */
dialog.lightbox .wrap {{ min-height: 100%; display: grid; place-items: center;
  padding: 1rem; }}
dialog.lightbox .close {{ position: fixed; top: .75rem; right: 1rem;
  font: inherit; font-size: 1.1rem; line-height: 1; color: #fff;
  background: rgba(0, 0, 0, .55); border: 1px solid rgba(255, 255, 255, .4);
  border-radius: 4px; padding: .4rem .6rem; cursor: pointer; }}
figcaption {{ font-family: "Linux Biolinum", Optima, system-ui, sans-serif;
  font-size: .85rem; color: var(--muted); text-align: left;
  margin-top: .6rem; line-height: 1.45; }}
table {{ border-collapse: collapse; width: 100%; font-size: .88rem;
  margin: 1rem 0; }}
th, td {{ border-bottom: 1px solid var(--rule); padding: .4rem .5rem;
  text-align: left; }}
thead th {{ border-bottom: 2px solid var(--ink); }}
td.yes {{ color: #2e7d32; font-weight: 700; }}
td.no {{ color: #b03030; }}
ul, ol {{ padding-left: 1.4rem; margin: 0 0 .9rem; }}
/* Description lists: the term stays a run-in label, as in the paper, but
   the term/definition relationship is now in the markup. */
dl {{ margin: 0 0 .9rem; }}
dl dt {{ font-weight: 600; float: left; clear: left; margin-right: .4em; }}
dl dt::after {{ content: "."; }}
dl dd {{ margin: 0 0 .55rem 1.4rem; }}
@media (max-width: 34rem) {{
  dl dt {{ float: none; margin-bottom: .15rem; }}
  dl dd {{ margin-left: 1rem; }}
}}
p.runin {{ font-weight: 600; margin-bottom: .3rem; }}
li {{ margin-bottom: .35rem; }}
abbr {{ font-variant: small-caps; text-transform: lowercase;
  letter-spacing: .02em; text-decoration: none; }}
/* Sidenotes: the note sits in the right margin, level with the mark that
   references it.  The <aside> follows the mark in document order, so with
   CSS off it still reads as a note in the right place. */
.fnref {{ text-decoration: none; }}
.fnref sup {{ font-size: .72em; padding: 0 .1em; }}
.sidenote {{
  display: block;
  float: right; clear: right;
  width: 15rem; margin: .2rem -17rem .8rem 1rem;
  font-size: .78rem; line-height: 1.45; color: var(--muted);
  text-align: left; text-indent: 0;
}}
.sidenote .fnnum {{ font-weight: 700; color: var(--ink); margin-right: .25em; }}
.sidenote code {{ font-size: .95em; }}
/* Not enough room beside the text: fall back to an indented inline note. */
@media (max-width: 78rem) {{
  .sidenote {{
    float: none; width: auto; margin: .7rem 0;
    padding: .55rem .8rem; border-left: 3px solid var(--rule);
    background: var(--code-bg); display: block;
  }}
}}
.backrefs {{ margin-left: .35em; white-space: nowrap; }}
.backrefs a {{ text-decoration: none; font-size: .9em; opacity: .65; }}
.backrefs a:hover {{ opacity: 1; }}
.footnotes, .references {{ margin-top: 3rem; font-size: .87rem; }}
.footnotes li, .references li {{ margin-bottom: .55rem; }}
.references a {{ word-break: break-all; }}
.toc {{ margin: 2rem 0; font-size: .9rem; }}
.toc ol {{ list-style: none; padding-left: 0; }}
.toc ol ol {{ padding-left: 1.2rem; }}
.toc a {{ text-decoration: none; color: var(--accent); }}
.toc a:hover {{ text-decoration: underline; }}
.srconly {{ position: absolute; width: 1px; height: 1px; overflow: hidden;
  clip: rect(0 0 0 0); }}
.provenance {{
  font-size: .82rem; line-height: 1.5; color: var(--muted);
  border: 1px solid var(--rule); border-left: 4px solid var(--accent);
  border-radius: 4px; padding: .7rem .9rem; margin: 0 0 2rem;
  background: var(--code-bg);
}}
.provenance a {{ color: var(--accent); }}
.license {{ margin-top: 3rem; padding-top: 1rem; border-top: 1px solid var(--rule);
  font-size: .8rem; color: var(--muted); }}
</style>
</head>
<body>
{body}

<footer class="license">
<p>This is an HTML rendering of &ldquo;Forge: A Tool and Language for Teaching
Formal Methods&rdquo;, <i>Proc. ACM Program. Lang.</i> 8, OOPSLA1, Article 116
(April 2024), by Tim Nelson et al.
&copy; 2024 Copyright held by the owner/author(s).</p>
<p>The article is licensed under a
<a href="https://creativecommons.org/licenses/by/4.0/">Creative Commons
Attribution 4.0 International License</a>, which permits this reproduction.
Authoritative version: <a href="__DOI__">__DOI__</a> &middot;
<a href="__SRC__">original PDF</a>.</p>
</footer>

<dialog class="lightbox" aria-label="Enlarged figure">
  <button type="button" class="close" aria-label="Close">Close &times;</button>
  <div class="wrap"><img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" alt=""></div>
</dialog>
<script>
// Click-to-enlarge.  The extracted images are about three times the size
// the PDF displayed them at, so there is genuine detail to reveal.
// Progressive enhancement: without JS every figure is still a plain <img>.
(function () {{
  var dlg = document.querySelector('dialog.lightbox');
  if (!dlg || typeof dlg.showModal !== 'function') return;
  var img = dlg.querySelector('img');
  var opener = null;

  document.addEventListener('click', function (ev) {{
    var btn = ev.target.closest('button.zoom');
    if (btn) {{
      opener = btn;
      img.src = btn.dataset.full;
      img.alt = btn.querySelector('img').alt;
      dlg.showModal();
      return;
    }}
    // clicking the backdrop or the close button dismisses
    if (ev.target === dlg || ev.target.closest('.close')) dlg.close();
  }});

  dlg.addEventListener('close', function () {{
    img.removeAttribute('src');
    if (opener) {{ opener.focus(); opener = null; }}
  }});
}})();
</script>
</body>
</html>
"""

PAGE_TEMPLATE = PAGE_TEMPLATE.replace("__DOI__", DOI).replace("__SRC__", SRC_URL)


if __name__ == "__main__":
    main()