quillmark-content 0.114.0

Content model (splice-shaped USV text with line attributes, marks, and islands), canonical serialization, edit deltas, and richtext/plaintext codecs for Quillmark
Documentation
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
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
//! Island, line and mark op channels: structural edits separate from text
//! splices. All three apply after [`Content::apply_text_delta`] in one
//! [`ChangeBundle`], in that order; mark ranges are in final-text coordinates.

use crate::delta::{Assoc, Delta, Op};
use crate::model::{
    is_whole_line, Container, Island, Line, LineKind, Mark,
    MarkKind, Content, Usv, ISLAND_SLOT,
};
use crate::normalize::admit_char;
use crate::usv::char_to_byte;
use serde::Deserialize;
use std::borrow::Cow;

/// A mark edit in final-text coordinates (post-delta, post-line-op).
#[derive(Debug, Clone, PartialEq)]
pub enum MarkOp {
    /// Add a mark over `[start, end)`. An anchor `kind` must carry a non-empty
    /// `id` not already live in the field ([`ApplyError::AnchorIdCollision`] /
    /// [`ApplyError::EmptyAnchorId`]).
    Add {
        start: Usv,
        end: Usv,
        kind: MarkKind,
    },
    /// Un-format `kind` over `[start, end)`: subtract the range from each
    /// overlapping same-kind *formatting* mark, keeping the non-overlapping
    /// fragments. An identity handle cannot be range-fragmented, so an
    /// overlapping one is dropped whole; anchors normally go through
    /// [`MarkOp::RemoveAnchor`].
    Remove {
        start: Usv,
        end: Usv,
        kind: MarkKind,
    },
    /// Drop one identity anchor by id.
    RemoveAnchor { id: String },
}

/// A line/block edit. Split/join splice `\n` in `text`; set ops touch metadata
/// only.
#[derive(Debug, Clone, PartialEq)]
pub enum LineOp {
    /// Paragraph break at `at`: insert `\n` and split the line metadata.
    Split { at: Usv },
    /// Join line `line` with the next: remove the `\n` between them.
    Join { line: usize },
    /// Replace a line's block role.
    SetKind { line: usize, kind: LineKind },
    /// Replace a line's container path.
    SetContainers {
        line: usize,
        containers: Vec<Container>,
    },
    /// Set (or clear) a line's `continues` flag: whether it continues the
    /// previous line's block across a within-block hard break (a markdown hard
    /// break, a code fence's interior line) rather than starting a new block.
    /// Split, join and text-delta `\n` insertion all mint `continues: false`
    /// lines, so this is the only op that reaches the flag. The terminal
    /// normalize clears a flag no block above can take: line 0, which nothing
    /// precedes, a differing container path, or a heading, island or rule above,
    /// each rendering one line.
    SetContinues { line: usize, continues: bool },
}

/// An island edit: the channel that reaches [`Island`] payloads, which no other
/// channel carries. Both ops act on one island entry, leaving the slot in place,
/// so identity anchors elsewhere in the field survive an island edit.
///
/// Removal needs no op: a text delta that deletes a slot drops the backing
/// entry ([`Content::apply_text_delta`]'s cascade). That drop is whole, so
/// re-landing the island is an [`IslandOp::Insert`] carrying the [`Island`]
/// itself. A *block* island's line demotes to `Para` when its slot goes, so
/// re-landing one re-tags the line too.
#[derive(Debug, Clone, PartialEq)]
pub enum IslandOp {
    /// Replace the entry `island.id` names, in place. The id is the target *and*
    /// the stored value, so an island cannot be renamed through this op; an id no
    /// island carries is [`ApplyError::UnknownIslandId`], never a silent no-op.
    ///
    /// `props`, `island_type` and `loss` all come from the op, nothing deriving
    /// `loss` from the props — so retyping an inline island into a block-only one
    /// over a slot that shares its line is [`ApplyError::BlockIslandNotAlone`],
    /// as landing one there is.
    Set { island: Island },
    /// Insert an island: the [`ISLAND_SLOT`] at `at` and its backing entry in
    /// one op, so a slot never exists without the [`Island`] behind it.
    ///
    /// `at` is a USV position in the text the delta and this bundle's earlier
    /// island ops left: each insert splices its slot before the next op reads
    /// the text, so of two inserts at one position the later one lands first.
    /// The entry files at its slot-order index in that same frame. A stale frame
    /// misplaces slots and never errors.
    ///
    /// The id must be non-empty and unique in the field
    /// ([`ApplyError::EmptyIslandId`], [`ApplyError::IslandIdCollision`]); a
    /// delete earlier in the same bundle frees its id for reuse here.
    ///
    /// **Block islands.** The slot alone is an *inline* island. A block island
    /// is that slot alone on its own line under [`LineKind::Island`], which takes
    /// three channels in one bundle: the text delta inserts the `\n`, this op
    /// inserts the slot, [`LineOp::SetKind`] tags the line. That order is why
    /// island ops run *before* line ops — the mint settles the kind against the
    /// text the bundle left, and the slot has to be on the line by then — and
    /// why `LineOp::Split` cannot stand in for the delta's `\n`.
    ///
    /// A type markdown writes as a block
    /// ([`IslandType::block_only`](crate::island::IslandType::block_only)) has
    /// no inline placement: `at` must be an empty line, else
    /// [`ApplyError::BlockIslandNotAlone`].
    ///
    /// A slot inserted onto a line whose kind names its content (`Code`, `Rule`)
    /// contradicts that kind; `normalize` demotes the line to `Para` at the end
    /// of the bundle rather than failing it.
    Insert { at: Usv, island: Island },
}

/// One committed field edit: a text delta and the three op channels, applied in
/// field order (delta → islands → lines → marks) by
/// [`Content::apply_field_change`]. [`Default`] is the identity bundle, so a
/// caller names only the channels it uses:
/// `ChangeBundle { delta, ..Default::default() }`.
///
/// Within a channel ops apply in sequence: op *n*'s coordinates read the state
/// ops `0..n` left, not the frame the channel opens in. That is USV positions
/// for an island insert and line indices for [`LineOp::Split`] /
/// [`LineOp::Join`], which renumber every later line. A stale frame stays in
/// range, so the bundle applies cleanly and lands the wrong document.
///
/// # Mark rebase
///
/// `delta`, `island_ops` and `line_ops` each move text, and each rebases the
/// marks already in the field by one rule:
///
/// | mark edge | [`Assoc`] | an insertion at that exact position |
/// |---|---|---|
/// | a range's `start` | `After` | grows text *outside* the span |
/// | a range's `end` | `Before` | grows text *outside* the span |
/// | a zero-width mark | `Before` | leaves the mark put |
///
/// `mark_ops` name the result, so a caller emitting them predicts this rebase.
/// [`Content::map_marks`] runs it rather than reproducing it.
#[derive(Debug, Clone, PartialEq)]
pub struct ChangeBundle {
    /// The text splice; the identity delta (no ops) is no text change.
    pub delta: Delta,
    /// Island edits, in post-delta coordinates.
    pub island_ops: Vec<IslandOp>,
    /// Line edits, in post-delta, post-island-op coordinates.
    pub line_ops: Vec<LineOp>,
    /// Mark edits, in final-text coordinates.
    pub mark_ops: Vec<MarkOp>,
}

impl Default for ChangeBundle {
    fn default() -> Self {
        ChangeBundle {
            delta: Delta { ops: Vec::new() },
            island_ops: Vec::new(),
            line_ops: Vec::new(),
            mark_ops: Vec::new(),
        }
    }
}

impl ChangeBundle {
    fn is_delta_only(&self) -> bool {
        self.island_ops.is_empty() && self.line_ops.is_empty() && self.mark_ops.is_empty()
    }
}

// The op readers below reuse `serial`'s hand-written readers, so a bundle
// speaks the shapes the content read surface does rather than a second dialect.
// The wire is a reading direction: bundles are authored on the JS/Python side.

use crate::serial::{
    container_from_authored_value, island_from_authored_value, line_kind_from_authored_value,
    mark_from_authored_value, reject_unwritable_link_url, usv_from, ParseError,
};
use serde_json::Value;

/// Decode a [`MarkOp`] from its wire object (`{op, start, end, type, attrs}` for
/// `add`/`remove`, `{op, id}` for `removeAnchor`). `add`/`remove` read the mark
/// vocabulary on the authored lane, which refuses the `@0.93.0` payload
/// spelling rather than guessing which of the two a stale host meant. `add`
/// carries the url rule too, `remove` naming a mark the field already holds.
pub fn mark_op_from_value(v: &Value) -> Result<MarkOp, ParseError> {
    let o = v.as_object().ok_or(ParseError::Shape("mark op"))?;
    match o.get("op").and_then(Value::as_str) {
        Some("add") => {
            reject_unwritable_link_url(v)?;
            let mark = mark_from_authored_value(v)?;
            Ok(MarkOp::Add {
                start: mark.start,
                end: mark.end,
                kind: mark.kind,
            })
        }
        Some("remove") => {
            let mark = mark_from_authored_value(v)?;
            Ok(MarkOp::Remove {
                start: mark.start,
                end: mark.end,
                kind: mark.kind,
            })
        }
        Some("removeAnchor") => Ok(MarkOp::RemoveAnchor {
            id: o
                .get("id")
                .and_then(Value::as_str)
                .ok_or(ParseError::Shape("removeAnchor id"))?
                .to_string(),
        }),
        _ => Err(ParseError::Shape("mark op kind")),
    }
}

/// Decode a [`LineOp`] from its wire object. `setKind` carries the line-kind
/// discriminant (`kind` plus its `attrs`) flattened alongside `op`/`line`.
pub fn line_op_from_value(v: &Value) -> Result<LineOp, ParseError> {
    let o = v.as_object().ok_or(ParseError::Shape("line op"))?;
    let line = || usv_from(o.get("line"), "line op line");
    match o.get("op").and_then(Value::as_str) {
        Some("split") => Ok(LineOp::Split {
            at: usv_from(o.get("at"), "split at")?,
        }),
        Some("join") => Ok(LineOp::Join { line: line()? }),
        Some("setKind") => Ok(LineOp::SetKind {
            line: line()?,
            kind: line_kind_from_authored_value(v)?,
        }),
        Some("setContainers") => Ok(LineOp::SetContainers {
            line: line()?,
            containers: o
                .get("containers")
                .and_then(Value::as_array)
                .ok_or(ParseError::Shape("setContainers containers"))?
                .iter()
                .map(container_from_authored_value)
                .collect::<Result<_, _>>()?,
        }),
        Some("setContinues") => Ok(LineOp::SetContinues {
            line: line()?,
            continues: o
                .get("continues")
                .and_then(Value::as_bool)
                .ok_or(ParseError::Shape("setContinues continues"))?,
        }),
        _ => Err(ParseError::Shape("line op kind")),
    }
}

/// Decode an [`IslandOp`] from its wire object. Both arms carry the island
/// vocabulary (`{id, type, props, loss}`) flattened alongside `op`, read on the
/// authored lane, which refuses an image `url` the markdown projection cannot
/// write.
pub fn island_op_from_value(v: &Value) -> Result<IslandOp, ParseError> {
    let o = v.as_object().ok_or(ParseError::Shape("island op"))?;
    let island = || island_from_authored_value(v);
    match o.get("op").and_then(Value::as_str) {
        Some("set") => Ok(IslandOp::Set { island: island()? }),
        Some("insert") => Ok(IslandOp::Insert {
            at: usv_from(o.get("at"), "island insert at")?,
            island: island()?,
        }),
        _ => Err(ParseError::Shape("island op kind")),
    }
}

/// Lower a committed change bundle object (`{delta?, islandOps?, lineOps?,
/// markOps?}`) to core ops. A missing `delta` is the identity (no text change);
/// a missing/`null` op array is empty. The error is a message string the
/// binding wraps in its own error type.
pub fn change_bundle_from_value(v: &Value) -> Result<ChangeBundle, String> {
    let obj = v
        .as_object()
        .ok_or("bundle must be an object { delta?, islandOps?, lineOps?, markOps? }")?;
    let delta = match obj.get("delta") {
        Some(Value::Null) | None => Delta { ops: Vec::new() },
        Some(d) => Delta::deserialize(d).map_err(|e| format!("invalid delta: {e}"))?,
    };
    Ok(ChangeBundle {
        delta,
        island_ops: op_array(obj.get("islandOps"), island_op_from_value, "islandOps")?,
        line_ops: op_array(obj.get("lineOps"), line_op_from_value, "lineOps")?,
        mark_ops: op_array(obj.get("markOps"), mark_op_from_value, "markOps")?,
    })
}

fn op_array<T>(
    value: Option<&Value>,
    convert: impl Fn(&Value) -> Result<T, ParseError>,
    what: &str,
) -> Result<Vec<T>, String> {
    let Some(value) = value.filter(|v| !v.is_null()) else {
        return Ok(Vec::new());
    };
    let arr = value
        .as_array()
        .ok_or_else(|| format!("{what} must be an array"))?;
    arr.iter()
        .map(|v| convert(v).map_err(|e| format!("invalid {what}: {e}")))
        .collect()
}

/// Why an apply failed: range or line index out of bounds, or invariants
/// broken before normalization could repair them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ApplyError {
    MarkOutOfRange {
        start: Usv,
        end: Usv,
        len: Usv,
    },
    LineOutOfRange {
        line: usize,
        lines: usize,
    },
    SplitPositionOutOfRange {
        at: Usv,
        len: Usv,
    },
    SplitAtNewline {
        at: Usv,
    },
    LineCountMismatch {
        lines: usize,
        segments: usize,
    },
    /// The text delta's expected base length disagreed with the content:
    /// it was built against a different revision.
    DeltaBaseMismatch {
        expected: usize,
        actual: usize,
    },
    /// An `Op::Insert` carried a raw [`ISLAND_SLOT`], which would leave a slot
    /// with no backing [`Island`]. Islands are created through
    /// [`IslandOp::Insert`], never a text splice, so a whole-field splice
    /// carrying slots must be split into a slot-stripped delta plus one
    /// [`IslandOp::Insert`] per slot.
    IslandSlotInInsert,
    /// A [`MarkOp::Add`] of an anchor whose `id` is already live in the field.
    /// Rejected rather than replaced (which would retarget a live thread) or
    /// coexisting (which `RemoveAnchor` cannot disambiguate).
    AnchorIdCollision { id: String },
    /// A [`MarkOp::Add`] of an anchor with the empty `id`.
    EmptyAnchorId,
    /// An [`IslandOp::Set`] naming an `id` no island in the field carries.
    UnknownIslandId { id: String },
    /// An [`IslandOp::Insert`] whose `id` is already live in the field. `Set`
    /// addresses by id, so a duplicate is an island neither op can name.
    IslandIdCollision { id: String },
    /// An [`IslandOp::Insert`] carrying the empty `id`.
    EmptyIslandId,
    /// An [`IslandOp::Insert`] whose `at` is past the end of the text the delta
    /// and this bundle's earlier island ops left.
    IslandInsertOutOfRange { at: Usv, len: Usv },
    /// An island op would leave a **block-only** island's slot
    /// ([`IslandType::block_only`](crate::island::IslandType::block_only), a
    /// `table`) sharing its line with other content. Markdown writes such an
    /// island by breaking the line around it, so the op that lands one mid-line
    /// is refused rather than restructuring the author's blocks. `at` is the
    /// slot's position.
    BlockIslandNotAlone { at: Usv },
    /// A [`LineOp::SetContainers`] nested a line deeper than
    /// [`MAX_NESTING_DEPTH`](crate::MAX_NESTING_DEPTH).
    NestingTooDeep {
        line: usize,
        depth: usize,
        max: usize,
    },
    /// A [`LineOp::SetKind`] naming a heading level outside `1..=6`. Refused
    /// because `normalize` does not repair it: the level reaches export as that
    /// many `#`, which CommonMark reads back as a literal-hash paragraph.
    BadHeadingLevel {
        line: usize,
        level: u8,
    },
}

impl Content {
    /// Splice `text` via `delta`, rebase marks, sync `lines` to `\n` changes,
    /// cascade island removal for any deleted slot, then normalize.
    ///
    /// Islands stay in lockstep with their [`ISLAND_SLOT`] chars: a delta that
    /// *deletes* a slot drops the corresponding [`Island`]; a delta that
    /// *inserts* a raw slot is rejected ([`ApplyError::IslandSlotInInsert`]).
    ///
    /// Inserted text is sanitized first, mirroring what `import` applies at the
    /// string boundary: `\r` and Unicode bidi controls are stripped, and a line
    /// separator (VT, FF, NEL, U+2028, U+2029) becomes a space — the chars
    /// [`Content::validate`] forbids.
    pub fn apply_text_delta(&mut self, delta: &Delta) -> Result<(), ApplyError> {
        self.apply_text_delta_inner(delta)?;
        self.normalize();
        Ok(())
    }

    fn apply_text_delta_inner(&mut self, delta: &Delta) -> Result<(), ApplyError> {
        // Checked up front so the content is untouched on this error.
        for op in &delta.ops {
            if let Op::Insert(s) = op {
                if s.contains(ISLAND_SLOT) {
                    return Err(ApplyError::IslandSlotInInsert);
                }
            }
        }

        // Sanitizing the whole delta up front keeps `try_apply` / `map_pos` /
        // line+island sync in agreement on one cleaned op stream.
        let sanitized = sanitize_inserts(delta);
        let delta = sanitized.as_ref();

        let old_chars: Vec<char> = self.text.chars().collect();
        // `try_apply` retains the untouched remainder implicitly, so a splice
        // may name only the region it changes.
        let new_text = delta
            .try_apply(&self.text)
            .map_err(|e| ApplyError::DeltaBaseMismatch {
                expected: e.expected,
                actual: e.actual,
            })?;
        let old_lines = std::mem::take(&mut self.lines);

        self.rebase_marks(delta);
        let new_len = new_text.chars().count();
        self.marks.retain(|m| {
            m.start <= m.end
                && m.end <= new_len
                && (m.start < m.end || !m.kind.is_formatting())
        });

        self.text = new_text;
        let old_islands = std::mem::take(&mut self.islands);
        (self.lines, self.islands) = sync_for_delta(&old_chars, old_lines, old_islands, delta);
        if self.lines.len() != self.segment_count() {
            return Err(ApplyError::LineCountMismatch {
                lines: self.lines.len(),
                segments: self.segment_count(),
            });
        }
        Ok(())
    }

    pub(crate) fn rebase_marks(&mut self, delta: &Delta) {
        for m in &mut self.marks {
            if m.start == m.end {
                let p = delta.map_pos(m.start, Assoc::Before);
                m.start = p;
                m.end = p;
            } else {
                m.start = delta.map_pos(m.start, Assoc::After);
                m.end = delta.map_pos(m.end, Assoc::Before);
            }
        }
    }

    /// Apply mark ops in final-text coordinates, then normalize.
    pub fn apply_mark_ops(&mut self, ops: &[MarkOp]) -> Result<(), ApplyError> {
        self.apply_mark_ops_inner(ops)?;
        self.normalize();
        Ok(())
    }

    fn apply_mark_ops_inner(&mut self, ops: &[MarkOp]) -> Result<(), ApplyError> {
        let len = self.len_usv();
        for op in ops {
            match op {
                MarkOp::Add { start, end, kind } => {
                    if *start > *end || *end > len {
                        return Err(ApplyError::MarkOutOfRange {
                            start: *start,
                            end: *end,
                            len,
                        });
                    }
                    if kind.is_formatting() && start == end {
                        return Err(ApplyError::MarkOutOfRange {
                            start: *start,
                            end: *end,
                            len,
                        });
                    }
                    if let MarkKind::Anchor { id } = kind {
                        if id.is_empty() {
                            return Err(ApplyError::EmptyAnchorId);
                        }
                        if self
                            .marks
                            .iter()
                            .any(|m| matches!(&m.kind, MarkKind::Anchor { id: aid } if aid == id))
                        {
                            return Err(ApplyError::AnchorIdCollision { id: id.clone() });
                        }
                    }
                    self.marks.push(Mark {
                        start: *start,
                        end: *end,
                        kind: kind.clone(),
                    });
                }
                MarkOp::Remove { start, end, kind } => {
                    if *start > *end || *end > len {
                        return Err(ApplyError::MarkOutOfRange {
                            start: *start,
                            end: *end,
                            len,
                        });
                    }
                    let mut next = Vec::with_capacity(self.marks.len());
                    for m in self.marks.drain(..) {
                        if m.kind != *kind || !ranges_overlap(m.start, m.end, *start, *end) {
                            next.push(m);
                            continue;
                        }
                        // An identity handle has no range algebra to
                        // subtract: drop the overlapping one whole.
                        if !kind.is_formatting() {
                            continue;
                        }
                        // An edge-aligned removal yields a zero-width fragment
                        // here; `normalize` drops it.
                        if m.start < *start {
                            next.push(Mark {
                                start: m.start,
                                end: *start,
                                kind: m.kind.clone(),
                            });
                        }
                        if *end < m.end {
                            next.push(Mark {
                                start: *end,
                                end: m.end,
                                kind: m.kind.clone(),
                            });
                        }
                    }
                    self.marks = next;
                }
                MarkOp::RemoveAnchor { id } => {
                    self.marks
                        .retain(|m| !matches!(&m.kind, MarkKind::Anchor { id: aid } if aid == id));
                }
            }
        }
        Ok(())
    }

    /// Apply island ops: replace an entry by id, or insert a slot and its entry
    /// together.
    pub fn apply_island_ops(&mut self, ops: &[IslandOp]) -> Result<(), ApplyError> {
        self.apply_island_ops_inner(ops)?;
        self.normalize();
        Ok(())
    }

    fn apply_island_ops_inner(&mut self, ops: &[IslandOp]) -> Result<(), ApplyError> {
        for op in ops {
            match op {
                IslandOp::Set { island } => {
                    let idx = self
                        .islands
                        .iter()
                        .position(|i| i.id == island.id)
                        .ok_or_else(|| ApplyError::UnknownIslandId {
                            id: island.id.clone(),
                        })?;
                    // The type comes from the op, so a `Set` can turn an inline
                    // island into a block-only one over a slot that stays put.
                    if island.island_type.block_only() {
                        let chars: Vec<char> = self.text.chars().collect();
                        let at = nth_slot(&chars, idx);
                        if !is_whole_line(&chars, at, at + 1) {
                            return Err(ApplyError::BlockIslandNotAlone { at });
                        }
                    }
                    // In place: the slot does not move, so no anchor pays.
                    self.islands[idx] = island.clone();
                }
                IslandOp::Insert { at, island } => {
                    if island.id.is_empty() {
                        return Err(ApplyError::EmptyIslandId);
                    }
                    if self.islands.iter().any(|i| i.id == island.id) {
                        return Err(ApplyError::IslandIdCollision {
                            id: island.id.clone(),
                        });
                    }
                    let chars: Vec<char> = self.text.chars().collect();
                    if *at > chars.len() {
                        return Err(ApplyError::IslandInsertOutOfRange {
                            at: *at,
                            len: chars.len(),
                        });
                    }
                    // The slot lands alone on its line only where the line is
                    // empty now, which is the `\n` the bundle's delta opened.
                    if island.island_type.block_only()
                        && !is_whole_line(&chars, *at, *at)
                    {
                        return Err(ApplyError::BlockIslandNotAlone { at: *at });
                    }
                    // Islands are stored in slot order.
                    let slot_idx = chars[..*at].iter().filter(|&&c| c == ISLAND_SLOT).count();
                    let byte = char_to_byte(&self.text, *at);
                    self.text.insert(byte, ISLAND_SLOT);
                    self.rebase_marks(&Delta {
                        ops: vec![Op::Retain(*at), Op::Insert(ISLAND_SLOT.to_string())],
                    });
                    self.islands.insert(slot_idx, island.clone());
                }
            }
        }
        Ok(())
    }

    /// Apply line ops: split/join splice `\n`; set ops touch metadata only.
    pub fn apply_line_ops(&mut self, ops: &[LineOp]) -> Result<(), ApplyError> {
        self.apply_line_ops_inner(ops)?;
        self.normalize();
        Ok(())
    }

    fn apply_line_ops_inner(&mut self, ops: &[LineOp]) -> Result<(), ApplyError> {
        for op in ops {
            match op {
                LineOp::Split { at } => self.split_line(*at)?,
                LineOp::Join { line } => self.join_line(*line)?,
                LineOp::SetKind { line, kind } => {
                    if let LineKind::Heading { level } = kind
                        && !(1..=6).contains(level)
                    {
                        return Err(ApplyError::BadHeadingLevel {
                            line: *line,
                            level: *level,
                        });
                    }
                    let line = self.line_mut(*line)?;
                    line.kind = kind.clone();
                }
                LineOp::SetContainers { line, containers } => {
                    // The Typst emitter recurses one frame per container, so a
                    // path past this cap is a render refusal rather than markup.
                    // Same cap as import.
                    if containers.len() > crate::MAX_NESTING_DEPTH {
                        return Err(ApplyError::NestingTooDeep {
                            line: *line,
                            depth: containers.len(),
                            max: crate::MAX_NESTING_DEPTH,
                        });
                    }
                    let line = self.line_mut(*line)?;
                    line.containers = containers.clone();
                }
                LineOp::SetContinues { line, continues } => {
                    let l = self.line_mut(*line)?;
                    l.continues = *continues;
                }
            }
        }
        Ok(())
    }

    /// One committed field edit bundle: text delta, then island ops, then line
    /// ops, then marks, canonicalized by a single terminal
    /// [`normalize`](Self::normalize).
    ///
    /// All-or-nothing: on any op's error `self` is left exactly as it was. A
    /// bundle carrying ops stages on a scratch copy and swaps in only once every
    /// stage succeeds; the pure-text-delta path skips that clone, since
    /// `apply_text_delta` validates before mutating.
    ///
    /// **Stage order is a coordinate contract**: each stage reads the text the
    /// earlier ones left. An island insert splices a slot, so a
    /// `LineOp::SetKind { kind: Island }` in the same bundle settles against a
    /// line that already carries it, and `Split`/`Join` and every mark range are
    /// then measured in a frame that includes the new slots.
    ///
    /// One terminal normalize suffices because split/join rebase marks through
    /// their `\n` splice, so the formatting-edge `\n`-trim commutes with the
    /// line ops, and `MarkOp::Remove` is coverage-set subtraction, which
    /// commutes with `normalize`'s same-kind union (`(A ∪ B) \ R = (A\R) ∪
    /// (B\R)`).
    pub fn apply_field_change(&mut self, bundle: &ChangeBundle) -> Result<(), ApplyError> {
        if bundle.is_delta_only() {
            return self.apply_text_delta(&bundle.delta);
        }
        let mut scratch = self.clone();
        scratch.apply_text_channels(bundle)?;
        scratch.apply_mark_ops_inner(&bundle.mark_ops)?;
        scratch.normalize();
        *self = scratch;
        Ok(())
    }

    /// Every channel of `bundle` that moves text, in bundle order. Sole caller
    /// of the three, so an editor reading [`map_marks`](Self::map_marks) and the
    /// store reading [`apply_field_change`](Self::apply_field_change) cannot
    /// answer a position differently.
    fn apply_text_channels(&mut self, bundle: &ChangeBundle) -> Result<(), ApplyError> {
        self.apply_text_delta_inner(&bundle.delta)?;
        self.apply_island_ops_inner(&bundle.island_ops)?;
        self.apply_line_ops_inner(&bundle.line_ops)
    }

    /// Where `bundle`'s text-moving channels leave the marks this content
    /// already holds: the final-text coordinates [`ChangeBundle::mark_ops`] are
    /// written in, under the rebase rule stated on [`ChangeBundle`].
    ///
    /// `bundle.mark_ops` are ignored, so an editor building them diffs its
    /// intended marks against this instead of predicting the rebase. The answer
    /// is [`normalize`](Self::normalize)d, as the store's is: marks a text move
    /// drops (out of range, zero-width formatting) are absent, and same-kind
    /// runs a move left adjacent arrive already unioned. A bundle whose
    /// `mark_ops` are empty therefore names the marks the field will hold.
    ///
    /// Errors are [`apply_field_change`](Self::apply_field_change)'s on the same
    /// ops, minus those only a mark op raises.
    pub fn map_marks(&self, bundle: &ChangeBundle) -> Result<Vec<Mark>, ApplyError> {
        let mut scratch = self.clone();
        scratch.apply_text_channels(bundle)?;
        scratch.normalize();
        Ok(scratch.marks)
    }

    fn line_mut(&mut self, line: usize) -> Result<&mut Line, ApplyError> {
        let lines = self.lines.len();
        self.lines
            .get_mut(line)
            .ok_or(ApplyError::LineOutOfRange { line, lines })
    }

    fn split_line(&mut self, at: Usv) -> Result<(), ApplyError> {
        let char_indices: Vec<(usize, char)> = self.text.char_indices().collect();
        let len = char_indices.len();
        if at > len {
            return Err(ApplyError::SplitPositionOutOfRange { at, len });
        }
        if at > 0 && char_indices[at - 1].1 == '\n' {
            return Err(ApplyError::SplitAtNewline { at });
        }
        if at < len && char_indices[at].1 == '\n' {
            return Err(ApplyError::SplitAtNewline { at });
        }

        // The newline count before `at` is the post-insert line index, since the
        // insertion lands at index `at`, not before it.
        let byte = char_indices.get(at).map_or(self.text.len(), |&(b, _)| b);
        let line_idx = char_indices[..at].iter().filter(|&(_, c)| *c == '\n').count();
        self.text.insert(byte, '\n');

        self.rebase_marks(&Delta {
            ops: vec![Op::Retain(at), Op::Insert("\n".to_string())],
        });

        let template = self
            .lines
            .get(line_idx)
            .cloned()
            .unwrap_or_else(|| Line::new(LineKind::Para));
        let mut new_line = template;
        new_line.continues = false;
        self.lines.insert(line_idx + 1, new_line);

        if self.lines.len() != self.segment_count() {
            return Err(ApplyError::LineCountMismatch {
                lines: self.lines.len(),
                segments: self.segment_count(),
            });
        }
        Ok(())
    }

    fn join_line(&mut self, line: usize) -> Result<(), ApplyError> {
        if line + 1 >= self.lines.len() {
            return Err(ApplyError::LineOutOfRange {
                line,
                lines: self.lines.len(),
            });
        }
        let nl = newline_at_line_boundary(&self.text, line)?;
        let byte = char_to_byte(&self.text, nl);
        self.text.remove(byte);

        self.rebase_marks(&Delta {
            ops: vec![Op::Retain(nl), Op::Delete(1)],
        });

        self.lines.remove(line + 1);

        if self.lines.len() != self.segment_count() {
            return Err(ApplyError::LineCountMismatch {
                lines: self.lines.len(),
                segments: self.segment_count(),
            });
        }
        Ok(())
    }
}

fn ranges_overlap(a0: Usv, a1: Usv, b0: Usv, b1: Usv) -> bool {
    a0 < b1 && b0 < a1
}

/// Put every `Op::Insert` under the [`admit_char`] contract — the chars
/// `validate()` rejects, dropped or spaced — borrowing the delta through
/// untouched when none carries one. A raw [`ISLAND_SLOT`] is refused separately.
fn sanitize_inserts(delta: &Delta) -> Cow<'_, Delta> {
    let needs_cleaning = delta
        .ops
        .iter()
        .any(|op| matches!(op, Op::Insert(s) if s.chars().any(|c| admit_char(c) != Some(c))));
    if !needs_cleaning {
        return Cow::Borrowed(delta);
    }
    let ops = delta
        .ops
        .iter()
        .map(|op| match op {
            Op::Insert(s) => Op::Insert(s.chars().filter_map(admit_char).collect()),
            other => other.clone(),
        })
        .collect();
    Cow::Owned(Delta { ops })
}

/// Walk `delta` over `old_chars` once, mirroring both structures the base chars
/// index: `\n` insert/delete in `lines`, and a deleted [`ISLAND_SLOT`] dropping
/// its island. A `Retain`/`Delete` reaching past the end of the base names no
/// char.
///
/// The line cursor sits *in* a line, `cur`; downstream of it is always the
/// untouched original suffix (`rest`), so lines are emitted in order rather than
/// by per-`\n` mid-`Vec` `remove`/`insert`. `cur == None` is the past-the-end
/// state on a malformed content (more `\n` than lines), where a split clones a
/// default line.
///
/// Islands are stored in slot order, so the Nth slot the walk passes backs the
/// Nth island.
fn sync_for_delta(
    old_chars: &[char],
    old_lines: Vec<Line>,
    old_islands: Vec<Island>,
    delta: &Delta,
) -> (Vec<Line>, Vec<Island>) {
    let mut rest = old_lines.into_iter();
    let mut lines: Vec<Line> = Vec::with_capacity(rest.len());
    let mut cur: Option<Line> = rest.next();
    let mut keep = vec![true; old_islands.len()];
    let mut slot = 0usize;
    let mut old = 0usize;

    for op in &delta.ops {
        match op {
            Op::Retain(n) | Op::Delete(n) => {
                let deleted = matches!(op, Op::Delete(_));
                let end = old.saturating_add(*n).min(old_chars.len());
                for &c in &old_chars[old..end] {
                    match c {
                        // A deleted '\n' merges the next original into `cur`.
                        '\n' if deleted => {
                            rest.next();
                        }
                        '\n' => {
                            lines.extend(cur.take());
                            cur = rest.next();
                        }
                        ISLAND_SLOT => {
                            if deleted && let Some(k) = keep.get_mut(slot) {
                                *k = false;
                            }
                            slot += 1;
                        }
                        _ => {}
                    }
                }
                old = end;
            }
            // A raw ISLAND_SLOT insert is rejected before this walk.
            Op::Insert(s) => {
                for c in s.chars() {
                    if c == '\n' {
                        let mut new_line = match cur.take() {
                            Some(line) => {
                                let clone = line.clone();
                                lines.push(line);
                                clone
                            }
                            None => Line::new(LineKind::Para),
                        };
                        new_line.continues = false;
                        cur = Some(new_line);
                    }
                }
            }
        }
    }

    lines.extend(cur);
    lines.extend(rest);
    let islands = old_islands
        .into_iter()
        .zip(keep)
        .filter_map(|(island, keep)| keep.then_some(island))
        .collect();
    (lines, islands)
}

/// The USV position of the `n`th [`ISLAND_SLOT`] in `chars`, or the end of the
/// text where the slots run out — a slot-synced island list has no such index.
fn nth_slot(chars: &[char], n: usize) -> Usv {
    chars
        .iter()
        .enumerate()
        .filter(|&(_, &c)| c == ISLAND_SLOT)
        .map(|(i, _)| i)
        .nth(n)
        .unwrap_or(chars.len())
}

fn newline_at_line_boundary(text: &str, line: usize) -> Result<Usv, ApplyError> {
    let mut current = 0usize;
    for (i, c) in text.chars().enumerate() {
        if c == '\n' {
            if current == line {
                return Ok(i);
            }
            current += 1;
        }
    }
    Err(ApplyError::LineOutOfRange {
        line,
        lines: text.chars().filter(|&c| c == '\n').count() + 1,
    })
}

/// The mutations that re-establish the invariant, forwarded.
///
/// Each normalizes before it returns, on an error too: an op list that fails
/// partway leaves its earlier ops applied. So the token states that the value
/// is canonical, not that the edit landed.
///
/// Any other edit takes [`into_content`](crate::model::Normalized::into_content).
impl crate::model::Normalized {
    fn seal(&mut self, applied: Result<(), ApplyError>) -> Result<(), ApplyError> {
        if applied.is_err() {
            self.as_content_mut().normalize();
        }
        applied
    }

    pub fn apply_text_delta(&mut self, delta: &Delta) -> Result<(), ApplyError> {
        let applied = self.as_content_mut().apply_text_delta(delta);
        self.seal(applied)
    }

    pub fn apply_mark_ops(&mut self, ops: &[MarkOp]) -> Result<(), ApplyError> {
        let applied = self.as_content_mut().apply_mark_ops(ops);
        self.seal(applied)
    }

    pub fn apply_island_ops(&mut self, ops: &[IslandOp]) -> Result<(), ApplyError> {
        let applied = self.as_content_mut().apply_island_ops(ops);
        self.seal(applied)
    }

    pub fn apply_line_ops(&mut self, ops: &[LineOp]) -> Result<(), ApplyError> {
        let applied = self.as_content_mut().apply_line_ops(ops);
        self.seal(applied)
    }

    pub fn apply_field_change(&mut self, bundle: &ChangeBundle) -> Result<(), ApplyError> {
        let applied = self.as_content_mut().apply_field_change(bundle);
        self.seal(applied)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::island::IslandType;
    use crate::delta::diff;
    use crate::import::from_markdown;

    #[test]
    fn mark_op_wire_decodes_each_variant() {
        let cases = vec![
            (
                serde_json::json!({"op": "add", "start": 0, "end": 3, "type": "strong"}),
                MarkOp::Add {
                    start: 0,
                    end: 3,
                    kind: MarkKind::Strong,
                },
            ),
            (
                serde_json::json!({
                    "op": "add", "start": 1, "end": 2, "type": "link", "attrs": {"url": "https://x"},
                }),
                MarkOp::Add {
                    start: 1,
                    end: 2,
                    kind: MarkKind::Link {
                        url: "https://x".into(),
                    },
                },
            ),
            (
                serde_json::json!({
                    "op": "remove", "start": 4, "end": 6, "type": "anchor", "attrs": {"id": "c1"},
                }),
                MarkOp::Remove {
                    start: 4,
                    end: 6,
                    kind: MarkKind::Anchor { id: "c1".into() },
                },
            ),
            (
                serde_json::json!({"op": "removeAnchor", "id": "c2"}),
                MarkOp::RemoveAnchor { id: "c2".into() },
            ),
        ];
        for (v, op) in cases {
            assert_eq!(mark_op_from_value(&v).unwrap(), op, "decode: {v}");
        }
    }

    #[test]
    fn line_op_wire_decodes_each_variant() {
        let cases = vec![
            (
                serde_json::json!({"op": "split", "at": 5}),
                LineOp::Split { at: 5 },
            ),
            (
                serde_json::json!({"op": "join", "line": 1}),
                LineOp::Join { line: 1 },
            ),
            (
                serde_json::json!({"op": "setKind", "line": 0, "kind": "heading", "attrs": {"level": 2}}),
                LineOp::SetKind {
                    line: 0,
                    kind: LineKind::Heading { level: 2 },
                },
            ),
            (
                serde_json::json!({
                    "op": "setContainers", "line": 2, "containers": [{"container": "quote"}],
                }),
                LineOp::SetContainers {
                    line: 2,
                    containers: vec![Container::Quote { instance: 0 }],
                },
            ),
            (
                serde_json::json!({"op": "setContinues", "line": 1, "continues": true}),
                LineOp::SetContinues {
                    line: 1,
                    continues: true,
                },
            ),
            (
                serde_json::json!({"op": "setContinues", "line": 3, "continues": false}),
                LineOp::SetContinues {
                    line: 3,
                    continues: false,
                },
            ),
        ];
        for (v, op) in cases {
            assert_eq!(line_op_from_value(&v).unwrap(), op, "decode: {v}");
        }
    }

    /// The op wire is authored-now, so it refuses the `@0.93.0` payload spelling
    /// the storage lane still reads: the write would land where it did not aim.
    #[test]
    fn op_wire_rejects_the_legacy_payload_spelling() {
        let bad = serde_json::json!({
            "op": "setKind", "line": 0, "kind": "heading", "level": 2,
        });
        assert!(matches!(line_op_from_value(&bad), Err(ParseError::Shape(_))));
        let bad = serde_json::json!({
            "op": "setContainers", "line": 0,
            "containers": [{"container": "list_item", "ordered": true}],
        });
        assert!(matches!(line_op_from_value(&bad), Err(ParseError::Shape(_))));
        let bad = serde_json::json!({
            "op": "add", "start": 0, "end": 1, "type": "link", "url": "u",
        });
        assert!(matches!(mark_op_from_value(&bad), Err(ParseError::Shape(_))));

        // One spelling per name: a built-in's payload rides the bag, and a
        // foreign bag on a built-in drops unread.
        for ok in [
            serde_json::json!({"op": "setKind", "line": 0, "kind": "heading", "attrs": {"level": 2}}),
            serde_json::json!({"op": "setKind", "line": 0, "kind": "para", "attrs": {"tone": "warn"}}),
        ] {
            assert!(line_op_from_value(&ok).is_ok(), "rejected: {ok}");
        }
    }

    /// The op wire funnels through the same decoders as storage, so every axis
    /// refuses an unknown name there too.
    #[test]
    fn op_wire_refuses_an_unknown_name() {
        let cases: [(Value, &str, &str); 5] = [
            (
                serde_json::json!({"op": "setKind", "line": 0, "kind": "callout"}),
                "line kind",
                "callout",
            ),
            (
                serde_json::json!({"op": "setContainers", "line": 0,
                  "containers": [{"container": "indent", "instance": 0}]}),
                "container",
                "indent",
            ),
            (
                serde_json::json!({"op": "add", "start": 0, "end": 1, "type": "highlight"}),
                "mark type",
                "highlight",
            ),
            (
                serde_json::json!({"op": "insert", "at": 0, "id": "i1",
                  "type": "widget", "loss": "lossless", "props": {}}),
                "island type",
                "widget",
            ),
            (
                serde_json::json!({"op": "insert", "at": 0, "id": "i1",
                  "type": "table", "loss": "partial", "props": {}}),
                "island loss",
                "partial",
            ),
        ];
        for (op, axis, name) in cases {
            let decode = match axis {
                "line kind" | "container" => line_op_from_value(&op),
                "mark type" => mark_op_from_value(&op).map(|_| unreachable!()),
                _ => island_op_from_value(&op).map(|_| unreachable!()),
            };
            assert_eq!(
                decode.unwrap_err(),
                ParseError::UnknownName {
                    axis,
                    name: name.to_string()
                },
                "op wire accepted {axis} {name:?}"
            );
        }
    }

    /// A markdown destination admits no line ending, bare or angle-wrapped, so
    /// a `url` carrying one exports as markup that re-imports without its link
    /// or image. An op that stores a url refuses it rather than landing a mark
    /// the projection dissolves; `remove` names a mark the field already holds,
    /// so a legacy link stays removable.
    #[test]
    fn a_url_the_projection_cannot_write_is_refused_where_an_op_stores_it() {
        let link = |op: &str, url: &str| {
            serde_json::json!({"op": op, "start": 0, "end": 1, "type": "link", "attrs": {"url": url}})
        };
        for url in ["a\nb", "a\rb"] {
            assert!(
                matches!(
                    mark_op_from_value(&link("add", url)),
                    Err(ParseError::Shape(_))
                ),
                "accepted: {url:?}"
            );
            assert!(
                mark_op_from_value(&link("remove", url)).is_ok(),
                "unremovable: {url:?}"
            );
        }
        let image = |url: &str| {
            serde_json::json!({
                "op": "insert", "at": 0, "id": "i1", "type": "image",
                "props": {"alt": "a", "url": url},
            })
        };
        assert!(matches!(
            island_op_from_value(&image("u\nv")),
            Err(ParseError::Shape(_))
        ));
        assert!(
            island_op_from_value(&image("u v")).is_ok(),
            "a space angle-wraps and round-trips"
        );
    }

    #[test]
    fn delta_serde_shape() {
        let d = Delta {
            ops: vec![Op::Retain(2), Op::Insert("hi".into()), Op::Delete(1)],
        };
        let v = serde_json::to_value(&d).unwrap();
        assert_eq!(
            v,
            serde_json::json!({"ops": [{"retain": 2}, {"insert": "hi"}, {"delete": 1}]})
        );
        assert_eq!(serde_json::from_value::<Delta>(v).unwrap(), d);
    }

    #[test]
    fn apply_text_delta_rebases_marks() {
        let mut rt = from_markdown("hello").unwrap().into_content();
        rt.marks.push(Mark {
            start: 1,
            end: 4,
            kind: MarkKind::Strong,
        });
        let mut rt = rt.into_normalized();
        let d = diff("hello", "hXello");
        rt.apply_text_delta(&d).unwrap();
        let strong = rt
            .marks
            .iter()
            .find(|m| matches!(m.kind, MarkKind::Strong))
            .unwrap();
        assert_eq!((strong.start, strong.end), (2, 5));
        assert_eq!(rt.text, "hXello");
    }

    fn anchored(text: &str, at: Usv) -> crate::model::Normalized {
        let mut rt = from_markdown(text).unwrap();
        rt.apply_mark_ops(&[MarkOp::Add {
            start: at,
            end: at,
            kind: MarkKind::Anchor { id: "a1".into() },
        }])
        .unwrap();
        rt
    }

    fn anchor_at(rt: &Content) -> (Usv, Usv) {
        let m = rt
            .marks
            .iter()
            .find(|m| matches!(&m.kind, MarkKind::Anchor { id } if id == "a1"))
            .expect("the anchor survives");
        (m.start, m.end)
    }

    fn strong_at(rt: &Content) -> (Usv, Usv) {
        let m = rt
            .marks
            .iter()
            .find(|m| matches!(m.kind, MarkKind::Strong))
            .expect("the mark survives");
        (m.start, m.end)
    }

    /// A zero-width mark's own position is where the two assocs part, and where
    /// an anchor most often sits. Every text-moving channel answers it `Before`.
    #[test]
    fn an_insert_at_a_zero_width_marks_position_leaves_it_put() {
        let d = diff("hello world", "hello Xworld");
        assert_eq!(d.map_pos(6, Assoc::After), 7, "the answer not taken");

        let mut via_delta = anchored("hello world", 6);
        via_delta.apply_text_delta(&d).unwrap();
        assert_eq!(anchor_at(&via_delta), (6, 6));

        let mut via_island = anchored("hello world", 6);
        via_island
            .apply_island_ops(&[IslandOp::Insert {
                at: 6,
                island: image("i1"),
            }])
            .unwrap();
        assert_eq!(anchor_at(&via_island), (6, 6));

        let mut via_line = anchored("hello world", 6);
        via_line.apply_line_ops(&[LineOp::Split { at: 6 }]).unwrap();
        assert_eq!(anchor_at(&via_line), (6, 6));
    }

    #[test]
    fn an_insert_at_a_range_marks_edge_stays_outside_the_span() {
        let mut at_start = from_markdown("hello world").unwrap();
        at_start
            .apply_mark_ops(&[MarkOp::Add {
                start: 6,
                end: 11,
                kind: MarkKind::Strong,
            }])
            .unwrap();
        at_start
            .apply_text_delta(&diff("hello world", "hello Xworld"))
            .unwrap();
        assert_eq!(strong_at(&at_start), (7, 12));

        let mut at_end = from_markdown("hello world").unwrap();
        at_end
            .apply_mark_ops(&[MarkOp::Add {
                start: 0,
                end: 5,
                kind: MarkKind::Strong,
            }])
            .unwrap();
        at_end
            .apply_text_delta(&diff("hello world", "helloX world"))
            .unwrap();
        assert_eq!(strong_at(&at_end), (0, 5));

        let mut at_end_island = from_markdown("hello world").unwrap();
        at_end_island
            .apply_mark_ops(&[MarkOp::Add {
                start: 0,
                end: 5,
                kind: MarkKind::Strong,
            }])
            .unwrap();
        at_end_island
            .apply_island_ops(&[IslandOp::Insert {
                at: 5,
                island: image("i1"),
            }])
            .unwrap();
        assert_eq!(strong_at(&at_end_island), (0, 5));
    }

    /// The reason an editor can diff against `map_marks` rather than reproduce
    /// the rebase: both readings walk one channel list, over every channel at
    /// once and at the position the assocs disagree on.
    #[test]
    fn map_marks_reports_where_apply_field_change_puts_them() {
        let mut rt = anchored("hello world", 6);
        rt.apply_mark_ops(&[MarkOp::Add {
            start: 0,
            end: 5,
            kind: MarkKind::Strong,
        }])
        .unwrap();
        let bundle = ChangeBundle {
            delta: diff("hello world", "hello Xworld"),
            island_ops: vec![IslandOp::Insert {
                at: 6,
                island: image("i1"),
            }],
            line_ops: vec![LineOp::Split { at: 6 }],
            mark_ops: Vec::new(),
        };

        let predicted = rt.map_marks(&bundle).unwrap();
        rt.apply_field_change(&bundle).unwrap();
        assert_eq!(predicted, rt.marks);
        assert_eq!(anchor_at(&rt), (6, 6), "the anchor never left its position");
    }

    /// A move can leave two same-kind runs touching, and the store unions them.
    /// An editor holding the returned marks as its own model of the field would
    /// otherwise disagree with the next read.
    #[test]
    fn map_marks_reports_the_union_a_move_makes_adjacent() {
        // Both bundle shapes: `apply_field_change` splits on `is_delta_only`,
        // and the answer must match the store on either side of that split.
        for line_ops in [
            Vec::new(),
            vec![LineOp::SetKind {
                line: 0,
                kind: LineKind::Para,
            }],
        ] {
            let mut rt = from_markdown("ab cd").unwrap();
            rt.apply_mark_ops(&[
                MarkOp::Add {
                    start: 0,
                    end: 2,
                    kind: MarkKind::Strong,
                },
                MarkOp::Add {
                    start: 3,
                    end: 5,
                    kind: MarkKind::Strong,
                },
            ])
            .unwrap();
            let bundle = ChangeBundle {
                delta: diff("ab cd", "abcd"),
                line_ops,
                ..Default::default()
            };

            let predicted = rt.map_marks(&bundle).unwrap();
            rt.apply_field_change(&bundle).unwrap();
            assert_eq!(predicted, rt.marks);
            assert_eq!(strong_at(&rt), (0, 4), "the two runs are one");
        }
    }

    #[test]
    fn map_marks_reports_an_out_of_bounds_bundle_without_touching_the_content() {
        let rt = anchored("hello world", 6);
        let before = rt.clone();
        let err = rt
            .map_marks(&ChangeBundle {
                island_ops: vec![IslandOp::Insert {
                    at: 99,
                    island: image("i1"),
                }],
                ..Default::default()
            })
            .unwrap_err();
        assert!(matches!(err, ApplyError::IslandInsertOutOfRange { .. }));
        assert_eq!(rt.marks, before.marks);
        assert_eq!(rt.text, before.text);
    }

    #[test]
    fn apply_text_delta_pads_short_prepend() {
        // A prepend naming only its inserted text (no trailing retain) still
        // splices against the whole content.
        let mut rt = from_markdown("hello").unwrap();
        rt.apply_text_delta(&Delta {
            ops: vec![Op::Insert("NEW ".into())],
        })
        .unwrap();
        assert_eq!(rt.text, "NEW hello");
    }

    #[test]
    fn apply_text_delta_rejects_over_long_delta() {
        // Consuming more base than exists is a wrong-revision delta, not an
        // abbreviated one.
        let mut rt = from_markdown("hi").unwrap();
        assert!(matches!(
            rt.apply_text_delta(&Delta {
                ops: vec![Op::Retain(99)],
            }),
            Err(ApplyError::DeltaBaseMismatch { .. })
        ));
        assert_eq!(rt.text, "hi");
    }

    #[test]
    fn apply_field_change_rejects_a_bundle_whose_retains_overflow() {
        // The whole host lane: JSON bundle through the store, not a Delta
        // built in Rust.
        let bundle = change_bundle_from_value(&serde_json::json!({
            "delta": { "ops": [{ "retain": usize::MAX }, { "retain": 2 }] }
        }))
        .unwrap();
        let mut rt = from_markdown("hi").unwrap();
        assert!(matches!(
            rt.apply_field_change(&bundle),
            Err(ApplyError::DeltaBaseMismatch { .. })
        ));
        assert_eq!(rt.text, "hi");
    }

    #[test]
    fn apply_mark_ops_remove_punches_hole() {
        let mut rt = from_markdown("abcdef").unwrap();
        rt.apply_mark_ops(&[MarkOp::Add {
            start: 0,
            end: 6,
            kind: MarkKind::Strong,
        }])
        .unwrap();
        rt.apply_mark_ops(&[MarkOp::Remove {
            start: 2,
            end: 4,
            kind: MarkKind::Strong,
        }])
        .unwrap();
        let strong: Vec<_> = rt
            .marks
            .iter()
            .filter(|m| matches!(m.kind, MarkKind::Strong))
            .map(|m| (m.start, m.end))
            .collect();
        assert_eq!(strong, vec![(0, 2), (4, 6)]);
    }

    #[test]
    fn apply_mark_ops_remove_at_edge_leaves_no_zero_width() {
        let mut rt = from_markdown("abcdef").unwrap();
        rt.apply_mark_ops(&[MarkOp::Add {
            start: 0,
            end: 6,
            kind: MarkKind::Strong,
        }])
        .unwrap();
        rt.apply_mark_ops(&[MarkOp::Remove {
            start: 0,
            end: 2,
            kind: MarkKind::Strong,
        }])
        .unwrap();
        let strong: Vec<_> = rt
            .marks
            .iter()
            .filter(|m| matches!(m.kind, MarkKind::Strong))
            .map(|m| (m.start, m.end))
            .collect();
        assert_eq!(strong, vec![(2, 6)]);
    }

    #[test]
    fn apply_mark_ops_remove_covering_range_drops_mark() {
        let mut rt = from_markdown("abcdef").unwrap();
        rt.apply_mark_ops(&[MarkOp::Add {
            start: 2,
            end: 4,
            kind: MarkKind::Emph,
        }])
        .unwrap();
        rt.apply_mark_ops(&[MarkOp::Remove {
            start: 0,
            end: 6,
            kind: MarkKind::Emph,
        }])
        .unwrap();
        assert!(!rt.marks.iter().any(|m| matches!(m.kind, MarkKind::Emph)));
    }

    #[test]
    fn apply_mark_ops_remove_non_formatting_drops_whole() {
        let anchor = || MarkKind::Anchor { id: "a".into() };
        let mut rt = from_markdown("abcdef").unwrap().into_content();
        rt.marks.push(Mark {
            start: 0,
            end: 6,
            kind: anchor(),
        });
        let mut rt = rt.into_normalized();
        rt.apply_mark_ops(&[MarkOp::Remove {
            start: 2,
            end: 4,
            kind: anchor(),
        }])
        .unwrap();
        assert!(!rt
            .marks
            .iter()
            .any(|m| matches!(m.kind, MarkKind::Anchor { .. })));
    }

    /// [`Normalized::seal`]: an op list that fails partway leaves its earlier
    /// ops applied, so the token has to re-establish the invariant on the error
    /// path too.
    #[test]
    fn a_failed_op_list_leaves_the_token_canonical() {
        let mut rt = from_markdown("**a**b").unwrap();
        let ops = [
            MarkOp::Add {
                start: 0,
                end: 2,
                kind: MarkKind::Strong,
            },
            MarkOp::Add {
                start: 0,
                end: 99,
                kind: MarkKind::Strong,
            },
        ];
        assert!(rt.apply_mark_ops(&ops).is_err());
        assert_eq!((*rt).clone().into_normalized(), rt);
    }

    #[test]
    fn line_op_split_and_join() {
        let mut rt = from_markdown("onetwo").unwrap();
        rt.apply_line_ops(&[LineOp::Split { at: 3 }]).unwrap();
        assert_eq!(rt.text, "one\ntwo");
        assert_eq!(rt.lines.len(), 2);

        rt.apply_line_ops(&[LineOp::Join { line: 0 }]).unwrap();
        assert_eq!(rt.text, "onetwo");
        assert_eq!(rt.lines.len(), 1);
        assert_eq!(rt.validate(), Ok(()));
    }

    #[test]
    fn line_op_set_kind() {
        let mut rt = from_markdown("title").unwrap();
        rt.apply_line_ops(&[LineOp::SetKind {
            line: 0,
            kind: LineKind::Heading { level: 2 },
        }])
        .unwrap();
        assert!(matches!(rt.lines[0].kind, LineKind::Heading { level: 2 }));
    }

    /// A kind the line's text contradicts lands and the terminal normalize
    /// settles it to what the text spells, leaving the text itself alone.
    #[test]
    fn line_op_set_kind_over_contradicting_text_settles_to_what_the_text_spells() {
        for kind in [LineKind::Island, LineKind::Rule] {
            let mut rt = from_markdown("hello world").unwrap();
            assert_eq!(rt.apply_line_ops(&[LineOp::SetKind { line: 0, kind }]), Ok(()));
            assert_eq!(rt.text, "hello world");
            assert_eq!(rt.lines[0].kind, LineKind::Para);
            assert_eq!(rt.validate(), Ok(()));
        }

        // Tagging a table island's line `Code` would fence the slot, which
        // re-imports as nothing. The demotion runs first and `island_line_kind`
        // reads the slot back: the line settles where it started.
        let mut tbl = from_markdown("| a | b |\n|---|---|\n| 1 | 2 |").unwrap();
        assert_eq!(
            tbl.apply_line_ops(&[LineOp::SetKind {
                line: 0,
                kind: LineKind::Code { lang: None },
            }]),
            Ok(())
        );
        assert_eq!(tbl.lines[0].kind, LineKind::Island);

        // The one case that costs text: a heading retagged `Island` is a
        // paragraph afterward, its `#` gone from the projection.
        let mut heading = from_markdown("# a").unwrap();
        assert_eq!(
            heading.apply_line_ops(&[LineOp::SetKind {
                line: 0,
                kind: LineKind::Island,
            }]),
            Ok(())
        );
        assert_eq!(heading.lines[0].kind, LineKind::Para);
        assert_eq!(crate::export::to_markdown(&heading), "a");
    }

    /// A within-block break lives inside one container, and a heading, an
    /// island and a rule are one line in both projections. `continues` lands
    /// wherever it is asked for and the mint clears it where no block above can
    /// take it, leaving the projection untouched.
    #[test]
    fn set_continues_lands_only_where_a_block_can_continue() {
        let mut rt = from_markdown("- a\n\npara").unwrap();
        assert_ne!(rt.lines[0].containers, rt.lines[1].containers);
        assert_eq!(
            rt.apply_line_ops(&[LineOp::SetContinues {
                line: 1,
                continues: true
            }]),
            Ok(())
        );
        assert!(!rt.lines[1].continues, "the crossing is cleared");

        // Inside one container it is an ordinary hard break.
        let mut rt = from_markdown("- a\n\n  b").unwrap();
        assert_eq!(rt.lines[0].containers, rt.lines[1].containers);
        assert_eq!(
            rt.apply_line_ops(&[LineOp::SetContinues {
                line: 1,
                continues: true
            }]),
            Ok(())
        );
        assert!(rt.lines[1].continues);

        for markdown in ["# a\n\nb", "| h |\n| --- |\n| c |\n\nb", "***\n\nb"] {
            let mut rt = from_markdown(markdown).unwrap();
            let line = rt.lines.len() - 1;
            assert_eq!(
                rt.apply_line_ops(&[LineOp::SetContinues {
                    line,
                    continues: true
                }]),
                Ok(()),
                "{markdown}"
            );
            assert!(!rt.lines[line].continues, "{markdown}");
            assert_eq!(crate::export::to_markdown(&rt), markdown, "{markdown}");
        }

        // `SetKind` reaches the shape from the other side, by retagging the
        // block a continuation already follows. That retag is accepted and the
        // terminal `normalize` clears the flag, so the continuation lands as
        // the paragraph it is rather than vanishing.
        let mut rt = from_markdown("a\\\nb").unwrap();
        assert!(rt.lines[1].continues, "a hard break is a continuation");
        assert_eq!(
            rt.apply_line_ops(&[LineOp::SetKind {
                line: 0,
                kind: LineKind::Heading { level: 1 },
            }]),
            Ok(())
        );
        assert!(!rt.lines[1].continues);
        assert_eq!(rt.validate(), Ok(()));
        assert_eq!(crate::export::to_markdown(&rt), "# a\n\nb");
    }

    /// A `Join` merging two lines of differing paths leaves the line after the
    /// seam continuing across it. The op is accepted and the content is still
    /// storable, which is what putting the repair in `normalize` rather than
    /// `validate` buys.
    #[test]
    fn join_across_two_paths_leaves_a_valid_content() {
        let mut rt = from_markdown("- a\n\npara\\\nbroken").unwrap();
        let seam = rt
            .lines
            .iter()
            .position(|l| l.continues)
            .expect("the hard break is there");
        assert!(rt.apply_line_ops(&[LineOp::Join { line: seam - 2 }]).is_ok());
        assert_eq!(rt.validate(), Ok(()), "the join left a storable content");
        let mut again = rt.clone().into_content();
        again.normalize();
        assert_eq!(&again, &*rt, "the join left a repairable shape");
    }

    #[test]
    fn line_op_set_containers_is_depth_capped() {
        let mut rt = from_markdown("hi").unwrap();
        let deep = vec![Container::Quote { instance: 0 }; crate::MAX_NESTING_DEPTH + 1];
        assert_eq!(
            rt.apply_line_ops(&[LineOp::SetContainers {
                line: 0,
                containers: deep,
            }]),
            Err(ApplyError::NestingTooDeep {
                line: 0,
                depth: crate::MAX_NESTING_DEPTH + 1,
                max: crate::MAX_NESTING_DEPTH,
            })
        );
        assert!(rt.lines[0].containers.is_empty());
    }

    #[test]
    fn line_op_set_kind_range_checks_the_heading_level() {
        let mut rt = from_markdown("t").unwrap();
        assert_eq!(
            rt.apply_line_ops(&[LineOp::SetKind {
                line: 0,
                kind: LineKind::Heading { level: 9 },
            }]),
            Err(ApplyError::BadHeadingLevel { line: 0, level: 9 })
        );
        assert_eq!(rt.validate(), Ok(()));
        assert!(rt
            .apply_line_ops(&[LineOp::SetKind {
                line: 0,
                kind: LineKind::Heading { level: 6 },
            }])
            .is_ok());
    }

    #[test]
    fn line_op_set_continues_sets_and_clears() {
        let mut rt = from_markdown("one two").unwrap();
        rt.apply_text_delta(&diff("one two", "one\ntwo")).unwrap();
        assert!(!rt.lines[1].continues, "delta-split newline is a new block");

        rt.apply_line_ops(&[LineOp::SetContinues {
            line: 1,
            continues: true,
        }])
        .unwrap();
        assert!(rt.lines[1].continues);
        assert_eq!(rt.validate(), Ok(()));
        assert_eq!(
            crate::export::to_markdown(&rt).matches("\n\n").count(),
            0,
            "a within-block hard break is not a paragraph boundary"
        );

        rt.apply_line_ops(&[LineOp::SetContinues {
            line: 1,
            continues: false,
        }])
        .unwrap();
        assert!(!rt.lines[1].continues);
        assert_eq!(rt.validate(), Ok(()));
    }

    /// Nothing precedes the first line, so the flag there is dead to every
    /// reader: the mint clears it and the content is what it was.
    #[test]
    fn line_op_set_continues_on_the_first_line_clears() {
        let mut rt = from_markdown("one two").unwrap();
        rt.apply_text_delta(&diff("one two", "one\ntwo")).unwrap();
        let before = rt.clone();
        for continues in [true, false] {
            assert_eq!(
                rt.apply_line_ops(&[LineOp::SetContinues { line: 0, continues }]),
                Ok(())
            );
            assert!(!rt.lines[0].continues);
            assert_eq!(rt, before, "the first line's flag reaches no projection");
            assert_eq!(rt.validate(), Ok(()));
        }
    }

    fn island(id: &str) -> Island {
        Island {
            id: id.into(),
            island_type: IslandType::Image,
            props: serde_json::json!({}),
            loss: crate::model::Loss::Lossless,
        }
    }

    #[test]
    fn delete_one_of_two_slots_removes_the_matching_island() {
        let mut rt = Content::empty();
        rt.text = format!("{ISLAND_SLOT}x{ISLAND_SLOT}");
        rt.lines = vec![Line {
            kind: LineKind::Para,
            containers: vec![],
            continues: false,
        }];
        rt.islands = vec![island("first"), island("second")];
        assert_eq!(rt.validate(), Ok(()));

        // Delete the FIRST slot (index 0): `x` -> `x`.
        let d = Delta {
            ops: vec![Op::Delete(1), Op::Retain(2)],
        };
        rt.apply_text_delta(&d).unwrap();
        assert_eq!(rt.text, format!("x{ISLAND_SLOT}"));
        assert_eq!(rt.islands.len(), 1);
        assert_eq!(rt.islands[0].id, "second");
        assert_eq!(rt.validate(), Ok(()));
    }

    #[test]
    fn insert_bidi_control_is_stripped() {
        // Import's Trojan-source defense is not bypassed by the delta channel.
        let mut rt = from_markdown("ab").unwrap();
        let d = Delta {
            ops: vec![
                Op::Retain(1),
                Op::Insert("\u{202E}".into()),
                Op::Retain(1),
            ],
        };
        rt.apply_text_delta(&d).unwrap();
        assert_eq!(rt.text, "ab");
        assert_eq!(rt.validate(), Ok(()));
    }

    #[test]
    fn insert_line_separator_is_spaced() {
        // A space keeps the words apart without minting the line break Typst
        // would read, and which would make `- item` a bullet.
        for sep in ['\u{000B}', '\u{000C}', '\u{0085}', '\u{2028}', '\u{2029}'] {
            let mut rt = from_markdown("ab").unwrap();
            let d = Delta {
                ops: vec![Op::Retain(2), Op::Insert(format!("{sep}- item"))],
            };
            rt.apply_text_delta(&d).unwrap();
            assert_eq!(rt.text, "ab - item", "for {sep:?}");
            assert_eq!(rt.lines.len(), 1);
            assert_eq!(rt.validate(), Ok(()));
        }
    }

    #[test]
    fn insert_crlf_keeps_the_newline_and_splits() {
        let mut rt = from_markdown("ab").unwrap();
        let d = Delta {
            ops: vec![Op::Retain(1), Op::Insert("\r\n".into()), Op::Retain(1)],
        };
        rt.apply_text_delta(&d).unwrap();
        assert_eq!(rt.text, "a\nb");
        assert_eq!(rt.lines.len(), 2);
        assert_eq!(rt.validate(), Ok(()));
    }

    #[test]
    fn insert_of_clean_text_is_not_reallocated() {
        let d = Delta {
            ops: vec![Op::Retain(1), Op::Insert("clean\n".into()), Op::Retain(1)],
        };
        assert!(matches!(sanitize_inserts(&d), Cow::Borrowed(_)));
    }

    fn mark_bundle(delta: Delta, mark_ops: Vec<MarkOp>) -> ChangeBundle {
        ChangeBundle {
            delta,
            mark_ops,
            ..Default::default()
        }
    }

    fn island_bundle(island_ops: Vec<IslandOp>) -> ChangeBundle {
        ChangeBundle {
            island_ops,
            ..Default::default()
        }
    }

    /// A one-cell table island's props, the shape `normalize` leaves alone.
    fn table_props(header: &str, cell: &str) -> serde_json::Value {
        serde_json::json!({
            "header": [{ "text": header, "marks": [] }],
            "rows": [[{ "text": cell, "marks": [] }]],
            "aligns": ["none"],
        })
    }

    fn image(id: &str) -> Island {
        Island::new(id.into(), IslandType::Image)
            .with_props(serde_json::json!({ "url": "u", "alt": "a" }))
    }

    #[test]
    fn island_op_wire_decodes_each_variant() {
        let island = Island::new("isl-0".into(), IslandType::Table)
            .with_props(table_props("H", "a"))
            .with_loss(crate::model::Loss::Degraded);
        let cases = vec![
            (
                serde_json::json!({
                    "op": "set", "id": "isl-0", "type": "table",
                    "props": table_props("H", "a"), "loss": "degraded",
                }),
                IslandOp::Set {
                    island: island.clone(),
                },
            ),
            (
                serde_json::json!({
                    "op": "insert", "at": 7, "id": "isl-0", "type": "table",
                    "props": table_props("H", "a"), "loss": "degraded",
                }),
                IslandOp::Insert { at: 7, island },
            ),
        ];
        for (v, op) in cases {
            assert_eq!(island_op_from_value(&v).unwrap(), op, "decode: {v}");
        }
    }

    /// An island payload edit moves the entry alone, so an anchor elsewhere in
    /// the field survives an edit a whole-value `overwrite` would have cleared.
    #[test]
    fn island_set_edits_props_and_keeps_the_field_anchors() {
        let mut rt = from_markdown("intro\n\n| H |\n| --- |\n| a |").unwrap();
        assert_eq!(rt.islands.len(), 1, "one table island");
        let id = rt.islands[0].id.clone();
        rt.apply_mark_ops(&[MarkOp::Add {
            start: 0,
            end: 5,
            kind: MarkKind::Anchor { id: "c1".into() },
        }])
        .unwrap();

        rt.apply_field_change(&island_bundle(vec![IslandOp::Set {
            island: Island::new(id.clone(), IslandType::Table).with_props(table_props("H", "b")),
        }]))
        .unwrap();

        assert_eq!(rt.islands.len(), 1);
        assert_eq!(rt.islands[0].id, id, "the id is target and stored value");
        assert_eq!(rt.islands[0].props, table_props("H", "b"));
        let anchor = rt
            .marks
            .iter()
            .find(|m| matches!(&m.kind, MarkKind::Anchor { id } if id == "c1"))
            .expect("the anchor above the table survives the island edit");
        assert_eq!((anchor.start, anchor.end), (0, 5));
        assert_eq!(rt.validate(), Ok(()));
    }

    #[test]
    fn island_set_rejects_an_unknown_id() {
        let mut rt = from_markdown("| H |\n| --- |\n| a |").unwrap();
        let before = rt.clone();
        assert_eq!(
            rt.apply_field_change(&island_bundle(vec![IslandOp::Set {
                island: Island::new("isl-nope".into(), IslandType::Table)
                    .with_props(table_props("H", "b")),
            }])),
            Err(ApplyError::UnknownIslandId {
                id: "isl-nope".into()
            })
        );
        assert_eq!(rt, before);
    }

    #[test]
    fn island_insert_adds_the_slot_and_its_entry() {
        let mut rt = from_markdown("ab").unwrap();
        rt.apply_mark_ops(&[MarkOp::Add {
            start: 0,
            end: 1,
            kind: MarkKind::Anchor { id: "c1".into() },
        }])
        .unwrap();

        rt.apply_field_change(&island_bundle(vec![IslandOp::Insert {
            at: 1,
            island: Island::new("isl-new".into(), IslandType::Image)
                .with_props(serde_json::json!({ "url": "u", "alt": "a" })),
        }]))
        .unwrap();

        assert_eq!(rt.text, format!("a{ISLAND_SLOT}b"));
        assert_eq!(rt.islands.len(), 1);
        assert_eq!(rt.islands[0].id, "isl-new");
        assert_eq!(rt.validate(), Ok(()), "slot count matches the island list");
        let anchor = rt
            .marks
            .iter()
            .find(|m| matches!(&m.kind, MarkKind::Anchor { id } if id == "c1"))
            .expect("anchor survives");
        assert_eq!((anchor.start, anchor.end), (0, 1));
    }

    /// Op *n*'s `at` counts the slots ops `0..n` already spliced, not the shared
    /// post-delta frame; both assertions land differently under the
    /// post-delta-only reading, which errors neither way.
    #[test]
    fn island_inserts_apply_in_sequence() {
        let mut rt = from_markdown("xabc").unwrap();
        rt.apply_field_change(&ChangeBundle {
            // Post-delta: the deleted `x` is out of the frame the ops read.
            delta: diff("xabc", "abc"),
            island_ops: vec![
                IslandOp::Insert {
                    at: 1,
                    island: image("isl-b"),
                },
                // 3, not 2: op 0's slot is in the frame this op reads.
                IslandOp::Insert {
                    at: 3,
                    island: image("isl-c"),
                },
                // An earlier position emitted last, so its slot lands first.
                IslandOp::Insert {
                    at: 1,
                    island: image("isl-a"),
                },
            ],
            ..Default::default()
        })
        .unwrap();

        assert_eq!(
            rt.text,
            format!("a{ISLAND_SLOT}{ISLAND_SLOT}b{ISLAND_SLOT}c")
        );
        let ids: Vec<&str> = rt.islands.iter().map(|i| i.id.as_str()).collect();
        assert_eq!(ids, ["isl-a", "isl-b", "isl-c"], "slot order, not emission");
        assert_eq!(rt.validate(), Ok(()));
    }

    #[test]
    fn slot_bearing_splice_splits_into_delta_and_insert() {
        let mut rt = from_markdown("ab").unwrap();
        let before = rt.clone();

        let paste = format!("x{ISLAND_SLOT}y");
        assert_eq!(
            rt.apply_field_change(&ChangeBundle {
                delta: Delta {
                    ops: vec![Op::Retain(1), Op::Insert(paste)],
                },
                ..Default::default()
            }),
            Err(ApplyError::IslandSlotInInsert)
        );
        assert_eq!(rt, before, "the refusal commits nothing");

        rt.apply_field_change(&ChangeBundle {
            delta: Delta {
                ops: vec![Op::Retain(1), Op::Insert("xy".into())],
            },
            // The delta leaves `axyb`; the slot goes between `x` and `y`.
            island_ops: vec![IslandOp::Insert {
                at: 2,
                island: image("isl-p"),
            }],
            ..Default::default()
        })
        .unwrap();
        assert_eq!(rt.text, format!("ax{ISLAND_SLOT}yb"));
        assert_eq!(rt.islands[0].id, "isl-p");
        assert_eq!(rt.validate(), Ok(()));
    }

    /// A block island's line demotes to `Para` when its slot goes: the kind
    /// stops matching the text and `normalize` repairs rather than fails.
    #[test]
    fn block_island_restore_retags_its_line() {
        let mut rt = from_markdown("intro").unwrap();
        rt.apply_field_change(&ChangeBundle {
            delta: diff("intro", "intro\n"),
            island_ops: vec![IslandOp::Insert {
                at: 6,
                island: Island::new("isl-a".into(), IslandType::Table)
                    .with_props(table_props("H", "a")),
            }],
            line_ops: vec![LineOp::SetKind {
                line: 1,
                kind: LineKind::Island,
            }],
            ..Default::default()
        })
        .unwrap();
        let before = rt.clone();
        let held = rt.islands[0].clone();
        assert_eq!(before.lines[1].kind, LineKind::Island);

        rt.apply_field_change(&ChangeBundle {
            delta: diff(&before.text, "intro\n"),
            ..Default::default()
        })
        .unwrap();
        assert!(rt.islands.is_empty());
        assert_eq!(rt.lines[1].kind, LineKind::Para, "demoted, not failed");

        // The line stayed open, so the restore needs no delta.
        rt.apply_field_change(&ChangeBundle {
            island_ops: vec![IslandOp::Insert { at: 6, island: held }],
            line_ops: vec![LineOp::SetKind {
                line: 1,
                kind: LineKind::Island,
            }],
            ..Default::default()
        })
        .unwrap();
        assert_eq!(rt, before, "same content, original id and kind included");
    }

    /// An op landing a table's slot inside a paragraph would write pipes that
    /// re-import as prose. `Set` carries the type, so retyping is the same
    /// refusal.
    #[test]
    fn a_block_only_island_lands_only_on_a_line_of_its_own() {
        let table = |id: &str| {
            Island::new(id.into(), IslandType::Table).with_props(table_props("H", "a"))
        };
        let mut rt = from_markdown("ab").unwrap();
        let before = rt.clone();
        assert_eq!(
            rt.apply_field_change(&island_bundle(vec![IslandOp::Insert {
                at: 1,
                island: table("isl-t"),
            }])),
            Err(ApplyError::BlockIslandNotAlone { at: 1 })
        );
        assert_eq!(rt, before, "the refusal commits nothing");

        // The three-channel bundle a block island takes: the delta opens the
        // line, this op fills it, `SetKind` tags it.
        rt.apply_field_change(&ChangeBundle {
            delta: diff("ab", "ab\n"),
            island_ops: vec![IslandOp::Insert {
                at: 3,
                island: table("isl-t"),
            }],
            line_ops: vec![LineOp::SetKind {
                line: 1,
                kind: LineKind::Island,
            }],
            ..Default::default()
        })
        .unwrap();
        assert_eq!(rt.validate(), Ok(()));

        rt.apply_field_change(&island_bundle(vec![IslandOp::Insert {
            at: 1,
            island: image("isl-i"),
        }]))
        .unwrap();
        assert_eq!(rt.text, format!("a{ISLAND_SLOT}b\n{ISLAND_SLOT}"));
        assert_eq!(
            rt.apply_field_change(&island_bundle(vec![IslandOp::Set {
                island: table("isl-i"),
            }])),
            Err(ApplyError::BlockIslandNotAlone { at: 1 })
        );
        rt.apply_field_change(&island_bundle(vec![IslandOp::Set {
            island: table("isl-t"),
        }]))
        .expect("the block island's own slot is a whole line");
    }

    /// `Join` names two lines rather than an island, so it is the accepted op
    /// that can run a block island's slot back into prose. The mint takes the
    /// line apart again, so the placement holds however the content was reached.
    #[test]
    fn a_join_onto_a_block_island_line_is_undone_by_the_mint() {
        let mut rt = from_markdown("ab\n\n| H |\n| --- |\n| a |").unwrap();
        let before = rt.clone();
        rt.apply_line_ops(&[LineOp::Join { line: 0 }]).unwrap();
        assert_eq!(rt.validate(), Ok(()));
        assert_eq!(rt, before, "the slot stayed in the paragraph");
    }

    /// An inserted island's id is caller-supplied on an anchor id's terms:
    /// non-empty and unused, since `Set` addresses by it.
    #[test]
    fn island_insert_id_and_position_rules() {
        let mut rt = from_markdown("ab").unwrap();
        assert_eq!(
            rt.apply_field_change(&island_bundle(vec![IslandOp::Insert {
                at: 1,
                island: image(""),
            }])),
            Err(ApplyError::EmptyIslandId)
        );
        assert_eq!(
            rt.apply_field_change(&island_bundle(vec![IslandOp::Insert {
                at: 9,
                island: image("isl-a"),
            }])),
            Err(ApplyError::IslandInsertOutOfRange { at: 9, len: 2 })
        );

        rt.apply_field_change(&island_bundle(vec![IslandOp::Insert {
            at: 1,
            island: image("isl-a"),
        }]))
        .unwrap();
        assert_eq!(
            rt.apply_field_change(&island_bundle(vec![IslandOp::Insert {
                at: 0,
                island: image("isl-a"),
            }])),
            Err(ApplyError::IslandIdCollision { id: "isl-a".into() })
        );
    }

    /// What the stage order buys: the delta opens the line, the island op fills
    /// it, `SetKind` tags it, and the field's anchors stay.
    #[test]
    fn block_island_lands_in_one_bundle() {
        let mut rt = from_markdown("intro").unwrap();
        rt.apply_mark_ops(&[MarkOp::Add {
            start: 0,
            end: 5,
            kind: MarkKind::Anchor { id: "c1".into() },
        }])
        .unwrap();

        rt.apply_field_change(&ChangeBundle {
            delta: diff("intro", "intro\n"),
            island_ops: vec![IslandOp::Insert {
                at: 6,
                island: Island::new("isl-t".into(), IslandType::Table)
                    .with_props(table_props("H", "a")),
            }],
            line_ops: vec![LineOp::SetKind {
                line: 1,
                kind: LineKind::Island,
            }],
            ..Default::default()
        })
        .unwrap();

        assert_eq!(rt.text, format!("intro\n{ISLAND_SLOT}"));
        assert_eq!(rt.lines[1].kind, LineKind::Island);
        assert_eq!(rt.validate(), Ok(()));
        assert!(rt
            .marks
            .iter()
            .any(|m| matches!(&m.kind, MarkKind::Anchor { id } if id == "c1")));
        assert!(
            crate::export::to_markdown(&rt).contains("| H |"),
            "the block island projects as a pipe table"
        );
    }

    #[test]
    fn apply_field_change_bundle_order() {
        let mut rt = from_markdown("abc").unwrap();
        let d = diff("abc", "abXc");
        rt.apply_field_change(&mark_bundle(
            d,
            vec![MarkOp::Add {
                start: 3,
                end: 4,
                kind: MarkKind::Strong,
            }],
        ))
        .unwrap();
        let strong = rt
            .marks
            .iter()
            .find(|m| matches!(m.kind, MarkKind::Strong))
            .unwrap();
        assert_eq!((strong.start, strong.end), (3, 4));
        assert_eq!(rt.text, "abXc");
    }

    #[test]
    fn apply_field_change_is_all_or_nothing() {
        let mut rt = from_markdown("abc").unwrap();
        let before = rt.clone();
        let d = diff("abc", "abXc");
        let err = rt.apply_field_change(&mark_bundle(
            d,
            vec![
                MarkOp::Add {
                    start: 0,
                    end: 2,
                    kind: MarkKind::Strong,
                },
                MarkOp::Add {
                    start: 99,
                    end: 100,
                    kind: MarkKind::Emph,
                },
            ],
        ));
        assert!(matches!(err, Err(ApplyError::MarkOutOfRange { .. })));
        assert_eq!(rt, before, "failed bundle must not mutate the content");
    }

    #[test]
    fn add_anchor_id_uniqueness() {
        let anchor = |id: &str| MarkKind::Anchor { id: id.into() };
        let add = |start, end, id: &str| MarkOp::Add {
            start,
            end,
            kind: anchor(id),
        };

        let noop = || diff("abcd", "abcd");

        let mut rt = from_markdown("abcd").unwrap();
        rt.apply_field_change(&mark_bundle(noop(), vec![add(0, 2, "x")]))
            .unwrap();
        assert_eq!(
            rt.apply_field_change(&mark_bundle(noop(), vec![add(2, 4, "x")])),
            Err(ApplyError::AnchorIdCollision { id: "x".into() })
        );

        let mut rt = from_markdown("abcd").unwrap();
        assert_eq!(
            rt.apply_field_change(&mark_bundle(noop(), vec![add(0, 2, "")])),
            Err(ApplyError::EmptyAnchorId)
        );

        // Remove-then-add of the same id in one bundle: ops apply in sequence,
        // so the id is free by the time the `add` runs.
        let mut rt = from_markdown("abcd").unwrap();
        rt.apply_field_change(&mark_bundle(noop(), vec![add(0, 2, "x")]))
            .unwrap();
        rt.apply_field_change(&mark_bundle(
            noop(),
            vec![MarkOp::RemoveAnchor { id: "x".into() }, add(2, 4, "x")],
        ))
        .unwrap();
        let anchors: Vec<_> = rt
            .marks
            .iter()
            .filter(|m| matches!(m.kind, MarkKind::Anchor { .. }))
            .collect();
        assert_eq!(anchors.len(), 1);
        assert_eq!((anchors[0].start, anchors[0].end), (2, 4));
    }

    /// A `Heading{level}` line, its level a visible tag so a test can trace
    /// which original line landed where.
    fn tag_line(level: u8, continues: bool) -> Line {
        Line {
            kind: LineKind::Heading { level },
            containers: Vec::new(),
            continues,
        }
    }

    /// [`sync_for_delta`] on island-free content.
    fn sync_lines(old_chars: &[char], old_lines: Vec<Line>, delta: &Delta) -> Vec<Line> {
        sync_for_delta(old_chars, old_lines, Vec::new(), delta).0
    }

    /// `(tag, continues)` per line: a heading's level, 0 for `Para` (the default
    /// line), 255 for anything else.
    fn tags(lines: &[Line]) -> Vec<(u8, bool)> {
        lines
            .iter()
            .map(|l| match l.kind {
                LineKind::Heading { level } => (level, l.continues),
                LineKind::Para => (0, l.continues),
                _ => (255, l.continues),
            })
            .collect()
    }

    #[test]
    fn sync_lines_insert_newline_clones_split_line_and_clears_continues() {
        let old_chars: Vec<char> = "a\nbc".chars().collect();
        let l1 = Line {
            kind: LineKind::Heading { level: 5 },
            containers: vec![Container::Quote { instance: 0 }],
            continues: true,
        };
        let lines = vec![tag_line(1, false), l1.clone()];
        // Retain(3)[a\nb] moves to line 1; Insert("\n") splits it; Retain(1)[c].
        let d = Delta {
            ops: vec![Op::Retain(3), Op::Insert("\n".into()), Op::Retain(1)],
        };
        let out = sync_lines(&old_chars, lines, &d);
        assert_eq!(out.len(), 3);
        assert_eq!(out[1], l1, "first half is the untouched original line");
        assert_eq!(out[2].kind, LineKind::Heading { level: 5 });
        assert_eq!(out[2].containers, vec![Container::Quote { instance: 0 }]);
        assert!(!out[2].continues, "the split clone starts a new block");
    }

    #[test]
    fn sync_lines_delete_newline_drops_following_line() {
        let old_chars: Vec<char> = "a\nb\nc".chars().collect();
        let lines = vec![tag_line(1, false), tag_line(2, false), tag_line(3, false)];
        let d = Delta {
            ops: vec![Op::Retain(1), Op::Delete(1), Op::Retain(3)],
        };
        let out = sync_lines(&old_chars, lines, &d);
        assert_eq!(tags(&out), vec![(1, false), (3, false)]);
    }

    #[test]
    fn sync_walks_lines_and_islands_off_one_cursor() {
        // One delete run crosses a slot and then a '\n'; the retain behind it
        // has to land on slot 1, and the merged line has to be line 1's.
        let old_chars: Vec<char> = format!("{ISLAND_SLOT}\n{ISLAND_SLOT}").chars().collect();
        let d = Delta {
            ops: vec![Op::Delete(2), Op::Retain(1)],
        };
        let (lines, islands) = sync_for_delta(
            &old_chars,
            vec![tag_line(1, false), tag_line(2, false)],
            vec![island("first"), island("second")],
            &d,
        );
        assert_eq!(tags(&lines), vec![(1, false)]);
        assert_eq!(islands.iter().map(|i| &i.id).collect::<Vec<_>>(), ["second"]);
    }

    #[test]
    fn sync_lines_delete_trailing_newline_without_following_line_is_guarded() {
        // Malformed content: "a\n" is two segments but `lines` has one entry.
        let old_chars: Vec<char> = "a\n".chars().collect();
        let lines = vec![tag_line(1, false)];
        let d = Delta {
            ops: vec![Op::Retain(1), Op::Delete(1)],
        };
        let out = sync_lines(&old_chars, lines, &d);
        assert_eq!(tags(&out), vec![(1, false)]);
    }

    #[test]
    fn sync_lines_stops_at_end_of_old_chars() {
        let old_chars: Vec<char> = "a\nb".chars().collect();
        let lines = vec![tag_line(1, false), tag_line(2, false)];
        let d = Delta {
            ops: vec![Op::Retain(99)],
        };
        assert_eq!(sync_lines(&old_chars, lines.clone(), &d), lines);
    }

    #[test]
    fn split_line_rebases_mark_across_the_split_point() {
        let mut rt = from_markdown("abcd").unwrap();
        rt.apply_mark_ops(&[MarkOp::Add {
            start: 1,
            end: 3,
            kind: MarkKind::Strong,
        }])
        .unwrap();
        rt.apply_line_ops(&[LineOp::Split { at: 2 }]).unwrap();
        assert_eq!(rt.text, "ab\ncd");
        let strong: Vec<_> = rt
            .marks
            .iter()
            .filter(|m| matches!(m.kind, MarkKind::Strong))
            .map(|m| (m.start, m.end))
            .collect();
        // [1..4) spans "b\nc": normalize keeps an interior `\n`, trimming only
        // leading/trailing boundaries.
        assert_eq!(strong, vec![(1, 4)]);
        assert_eq!(rt.validate(), Ok(()));
    }

    #[test]
    fn join_line_rebases_marks_to_final_text_coordinates() {
        let mut rt = from_markdown("ab").unwrap().into_content();
        rt.apply_text_delta(&diff("ab", "ab\ncd")).unwrap();
        rt.marks.push(Mark {
            start: 2,
            end: 4,
            kind: MarkKind::Strong,
        });
        let mut rt = rt.into_normalized();
        rt.apply_line_ops(&[LineOp::Join { line: 0 }]).unwrap();
        assert_eq!(rt.text, "abcd");
        let strong: Vec<_> = rt
            .marks
            .iter()
            .filter(|m| matches!(m.kind, MarkKind::Strong))
            .map(|m| (m.start, m.end))
            .collect();
        assert_eq!(strong, vec![(2, 3)], "strong lands on 'c', not 'd' or 'cd'");
        assert_eq!(rt.validate(), Ok(()));
    }

    #[test]
    fn field_change_terminal_normalize_matches_per_stage_normalize() {
        let start = from_markdown("hello world").unwrap();
        let text_delta = diff("hello world", "hello brave world");
        let line_ops = vec![LineOp::Split { at: 5 }]; // after "hello"
        let mark_ops = vec![MarkOp::Add {
            start: 0,
            end: 5,
            kind: MarkKind::Strong,
        }];

        let mut bundled = start.clone();
        bundled
            .apply_field_change(&ChangeBundle {
                delta: text_delta.clone(),
                line_ops: line_ops.clone(),
                mark_ops: mark_ops.clone(),
                ..Default::default()
            })
            .unwrap();

        let mut staged = start;
        staged.apply_text_delta(&text_delta).unwrap();
        staged.apply_line_ops(&line_ops).unwrap();
        staged.apply_mark_ops(&mark_ops).unwrap();

        assert_eq!(bundled, staged, "terminal normalize diverged from per-stage");
        assert_eq!(bundled.validate(), Ok(()));
    }

    #[test]
    fn sync_lines_select_all_delete_collapses_to_first_line() {
        let text: String = (0..50).map(|i| format!("line{i}\n")).collect();
        let old_chars: Vec<char> = text.chars().collect();
        let lines: Vec<Line> = (0..=50).map(|i| tag_line((i % 200) as u8, false)).collect();
        assert_eq!(lines.len(), old_chars.iter().filter(|&&c| c == '\n').count() + 1);
        let d = Delta {
            ops: vec![Op::Delete(old_chars.len())],
        };
        let out = sync_lines(&old_chars, lines, &d);
        assert_eq!(tags(&out), vec![(0, false)], "only the first line survives");
    }

    #[test]
    fn sync_lines_insert_newline_past_end_appends_default() {
        // Malformed content: after the retain walks past the sole line, an
        // inserted '\n' has no line to clone and appends a default Para.
        let old_chars: Vec<char> = "a\n".chars().collect();
        let lines = vec![tag_line(1, false)];
        let d = Delta {
            ops: vec![Op::Retain(2), Op::Insert("\n".into())],
        };
        let out = sync_lines(&old_chars, lines, &d);
        assert_eq!(out.len(), 2);
        assert_eq!(tags(&out)[0], (1, false));
        assert_eq!(out[1].kind, LineKind::Para);
        assert!(out[1].containers.is_empty());
        assert!(!out[1].continues);
    }
}