jubarte-edit 0.20.0

The edit product of the jubarte engine: edit plans as tracked changes, text diff views, capabilities and staged publication
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
// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
//
// SPDX-License-Identifier: Apache-2.0

//! The changes between two documents as a git-style patch.
//!
//! ```text
//! --- a/agreement.md
//! +++ b/agreement.md<TAB>Arthur Rodrigues<TAB>2026-09-30T14:05:00Z
//! @@ [line:3] @@
//! Closing on [-04/20/26-]{+10/30/26+}{>>Arthur Rodrigues (2026-09-30T14:05:00Z): Financing.<<}.
//! ```
//!
//! Only the paragraphs that changed are shown, each whole, under the place it
//! has in the new version (`@@ [line:3] @@`), or in the old one when it was
//! removed (`@@ -[line:7] @@`). Deleted text is `[-...-]` and inserted text
//! `{+...+}`, as `git diff --word-diff` writes them; highlights and comments
//! stay CriticMarkup (`{==...==}`, `{>>...<<}`). The document owner and the
//! date of the patch are on the `+++` line, after tabs; a change by anyone else, or at
//! another time, is followed by its author and date (`{>>Name (date)<<}`),
//! and every comment names its author and date.
//!
//! The text is wrapped at [`DEFAULT_COLUMNS`], only at spaces, and never
//! where the break would change the Markdown: inside a code span or a link
//! target, after a backslash, before a list, heading, quote or table marker,
//! or in a heading, table row or code block.

use std::collections::{HashMap, HashSet};
use std::fmt;

use super::critic::{self, Piece, Token};
use super::diff::{continues, diff_markdown, marker_len, open_paragraph, table_row};
use super::redline::{RedlineOptions, Source, redline};
use super::write::named;
use super::{MarkdownError, MarkdownOptions, docx_to_markdown, docx_to_markdown_stories};
use crate::document_comparer::{accept_revisions, reject_revisions};
use crate::inspect;

/// The column width the [`Patch`] display formatter wraps to; passed to
/// [`Patch::render`] as `columns` to change it.
pub const DEFAULT_COLUMNS: usize = 72;

/// The author and date of a change or comment, in the form Word writes and
/// jubarte's Markdown edit path encodes (`YYYY-MM-DDTHH:MM:SSZ`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Attribution {
    /// The name Word shows.
    pub author: String,
    /// `YYYY-MM-DDTHH:MM:SSZ` (ISO 8601 down to the second, UTC offset
    /// `Z` by default).
    pub date: String,
}

/// The names written on the patch's `---` and `+++` header lines, and
/// the document owner (the author and date of every change and comment
/// that names none).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PatchOptions {
    /// The old document's name, after `--- a/`.
    pub old_name: String,
    /// The new document's name, after `+++ b/`.
    pub new_name: String,
    /// Author and date of every change and comment that names none.
    pub owner: Attribution,
}

/// Where a hunk's paragraph is.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Locator {
    /// The 1-based line of a Markdown document.
    Line(usize),
    /// A paragraph of a Word document by the id an edit plan names it by:
    /// `p3`, `footnotes.p1` ([`crate::ids::paragraph_id`]).
    Paragraph {
        /// `body`, or the part a header, footer or note is in
        /// (`header1`, `footnotes`).
        story: String,
        /// Its 0-based order in the story.
        index: usize,
    },
}

impl fmt::Display for Locator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Line(line) => write!(f, "line:{line}"),
            Self::Paragraph { story, index } => {
                f.write_str(&crate::ids::paragraph_id(story, *index))
            }
        }
    }
}

/// A comment, on a change, on highlighted text, or at a point.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Comment {
    /// The author name (Word's `w:author`).
    pub author: String,
    /// `YYYY-MM-DDTHH:MM:SSZ`, the date Word writes.
    pub date: String,
    /// The comment text: everything after `Name (date):`, or empty for an
    /// attribution alone (`{>>Name (date)<<}`).
    pub text: String,
    /// The highlighted text the comment is on (when the comment was on a
    /// `{==…==}` highlight), or `None` for a comment on a tracked change
    /// or a free-standing comment.
    pub on: Option<String>,
}

/// One tracked change (or self-contained substitution), with its author
/// and date. `old` and `new` are both nonempty for a substitution, only
/// `old` for a deletion, only `new` for an insertion.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Change {
    /// The text deleted (empty for an insertion).
    pub old: String,
    /// The text inserted (empty for a deletion).
    pub new: String,
    /// Who made the change (the change's own author, when it names one;
    /// otherwise the [`PatchOptions::owner`]).
    pub author: String,
    /// When the change was made.
    pub date: String,
    /// The comment written right after the change, if any.
    pub comment: Option<Comment>,
}

/// One changed paragraph: its [`Locator`] (where it is in the old or new
/// document), whether it is removed (a paragraph only in the old
/// version), its rendered text with markup intact, its changes in order,
/// and any comments that were not written right after a change.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Hunk {
    /// The paragraph in the new version, or in the old one when `removed`.
    pub at: Locator,
    /// The paragraph is not in the new version.
    pub removed: bool,
    /// The paragraph with its markup, unwrapped.
    pub text: String,
    /// The changes, in order.
    pub changes: Vec<Change>,
    /// Comments not written right after a change.
    pub comments: Vec<Comment>,
}

/// The changed paragraphs of a document, as a `git diff --word-diff`
/// patch. Displayed, it is [`render`](Self::render)ed at
/// [`DEFAULT_COLUMNS`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Patch {
    /// The old document's name.
    pub old_name: String,
    /// The new document's name.
    pub new_name: String,
    /// Author and date of the changes and comments that name none.
    pub owner: Attribution,
    /// The changed paragraphs, in document order.
    pub hunks: Vec<Hunk>,
}

impl Patch {
    /// Renders the patch as text, wrapped at `columns` (`0` does not
    /// wrap). Returns an empty string when nothing changed.
    pub fn render(&self, columns: usize) -> String {
        if self.hunks.is_empty() {
            return String::new();
        }
        let mut out = format!(
            "--- a/{}\n+++ b/{}\t{}\t{}\n",
            path_name(&self.old_name),
            path_name(&self.new_name),
            self.owner.author,
            self.owner.date
        );
        for (index, hunk) in self.hunks.iter().enumerate() {
            if index > 0 {
                out.push('\n');
            }
            let sign = if hunk.removed { "-" } else { "" };
            out.push_str(&format!("@@ {sign}[{}] @@\n", hunk.at));
            out.push_str(&wrap(&hunk.text, columns));
            out.push('\n');
        }
        out
    }
}

impl fmt::Display for Patch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.render(DEFAULT_COLUMNS))
    }
}

/// A file name as `git diff` shows it after `a/`: without `./` or `/`.
fn path_name(name: &str) -> &str {
    let name = name.strip_prefix("./").unwrap_or(name);
    name.trim_start_matches('/')
}

/// Diffs two Markdown documents (`old`, `new`) as a single [`Patch`]
/// whose changes are attributed to the [`PatchOptions::owner`]. Each
/// hunk lives at the line its paragraph starts on in the document
/// itself.
///
/// Backs `jubarte diff old.md new.md` (`--format critic`, or the unified
/// patch `--format`/`patch` when both inputs are Markdown).
///
/// ```
/// use jubarte_edit::markdown::{Attribution, PatchOptions, patch_markdown};
///
/// let options = PatchOptions {
///     old_name: "a.md".into(),
///     new_name: "b.md".into(),
///     owner: Attribution { author: "Ana".into(), date: "2026-09-30T14:05:00Z".into() },
/// };
/// let patch = patch_markdown("Due in 30 days.\n", "Due in 45 days.\n", &options);
/// assert_eq!(
///     patch.to_string(),
///     "--- a/a.md\n+++ b/b.md\tAna\t2026-09-30T14:05:00Z\n@@ [line:1] @@\nDue in [-30-]{+45+} days.\n"
/// );
/// ```
pub fn patch_markdown(old: &str, new: &str, options: &PatchOptions) -> Patch {
    let (mut patch, texts) = build(&diff_markdown(old, new), options);
    // Each hunk at the line its paragraph starts on in the document itself,
    // found in order; where it is not found (text the diff escaped), the
    // line counted from the markup stays.
    let lines = |text: &str| -> Vec<String> {
        text.replace("\r\n", "\n")
            .lines()
            .map(str::to_string)
            .collect()
    };
    let (old_lines, new_lines) = (lines(old), lines(new));
    let (mut old_from, mut new_from) = (0, 0);
    let texts = texts.into_iter().filter(|t| t.hunk.is_some());
    for (
        hunk,
        Paragraphs {
            old: old_text,
            new: new_text,
            ..
        },
    ) in patch.hunks.iter_mut().zip(texts)
    {
        let (text, lines, from) = if hunk.removed {
            (old_text, &old_lines, &mut old_from)
        } else {
            (new_text, &new_lines, &mut new_from)
        };
        let first = text.trim_start_matches('\n').lines().next().unwrap_or("");
        if first.is_empty() {
            continue;
        }
        if let Some(found) = lines[(*from).min(lines.len())..]
            .iter()
            .position(|l| l == first)
        {
            let line = *from + found;
            hunk.at = Locator::Line(line + 1);
            *from = line + 1;
        }
    }
    patch
}

/// Builds a [`Patch`] from a Markdown document whose CriticMarkup holds
/// the changes (as [`diff_markdown`] or [`docx_to_markdown`] write it).
///
/// # Attribution rules
///
/// - `{r1 Name (date)}` immediately after a change is its author and date.
///   A substitution tag names its deletion then insertion. `¶{r1 Name}`
///   attributes the following inserted paragraph separator.
/// - `{>>Name (date): text<<}` is a comment by `Name`, attached to the
///   preceding change (or to a highlight, depending on the context).
/// - Every other comment, and every change without an author, is the
///   [`PatchOptions::owner`]'s.
pub fn patch_critic(critic: &str, options: &PatchOptions) -> Patch {
    build(critic, options).0
}

/// A Word redline's tracked changes and comments as a patch, each hunk at
/// the id ([`pN`](Locator::Paragraph)) [`jubarte::inspect`](crate::inspect) gives its
/// paragraph once every change is accepted (or rejected, for a removed
/// paragraph): the id an edit plan names it by. A change in a text box is
/// at the paragraph that holds the box. Every comment is shown.
pub fn patch_redline(docx: &[u8], options: &PatchOptions) -> Result<Patch, MarkdownError> {
    let package = |error: crate::opc::OpcError| MarkdownError::Package(error.to_string());
    let old = reject_revisions(docx).map_err(package)?;
    let new = accept_revisions(docx).map_err(package)?;
    patch_word(docx, &old, &new, None, options, &MarkdownOptions::default())
}

/// [`patch_redline`] for the owner's own changes: every change by
/// another author, or by the owner on another date, is accepted first,
/// so the patch reads as only the changes still attributed to the
/// owner. An edit plan with
/// [`existing_revisions: "keep"`](crate::edit::ExistingRevisions) writes
/// its patch this way, beside the other party's tracked changes.
///
/// # Errors
///
/// - [`MarkdownError::Docx`] when the package's tracked changes cannot
///   be listed (admission refusal, package read failure, or malformed
///   part).
/// - [`MarkdownError::Package`] when accepting the other-party
///   revisions or accepting / rejecting every revision afterward fails.
pub fn patch_own_changes(docx: &[u8], options: &PatchOptions) -> Result<Patch, MarkdownError> {
    let changes = crate::changes::list_changes(docx)
        .map_err(|error| MarkdownError::Docx(error.to_string()))?;
    let others: Vec<String> = changes
        .into_iter()
        .filter(|c| {
            c.author.as_deref() != Some(options.owner.author.as_str())
                || c.date.as_deref() != Some(options.owner.date.as_str())
        })
        .map(|c| c.id)
        .collect();
    if others.is_empty() {
        return patch_redline(docx, options);
    }
    let filter = crate::changes::ChangeFilter {
        ids: Some(others),
        ..crate::changes::ChangeFilter::default()
    };
    let own = crate::changes::accept_elements(docx, &filter)
        .map_err(|error| MarkdownError::Package(error.to_string()))?;
    patch_redline(&own, options)
}

/// The changes from `old` to `new` as a patch. Two Markdown documents give
/// [`patch_markdown`]'s patch, at lines; otherwise the documents are
/// compared as [`redline`] compares them and each hunk is at a `pN`
/// of the Word document on its side (of the redline, accepted or rejected,
/// where that side is Markdown). The comparer's changes are the owner's;
/// a comment the old document has too is not a change.
pub fn patch_documents(
    old: Source<'_>,
    new: Source<'_>,
    redline_options: &RedlineOptions<'_>,
    options: &PatchOptions,
) -> Result<Patch, MarkdownError> {
    if let (Source::Markdown(old), Source::Markdown(new)) = (old, new) {
        return Ok(patch_markdown(old, new, options));
    }
    let mut compared = redline_options.clone();
    compared.settings.author_for_revisions = options.owner.author.clone();
    compared.settings.date_time_for_revisions = options.owner.date.clone();
    let docx = redline(old, new, &compared)?;
    let package = |error: crate::opc::OpcError| MarkdownError::Package(error.to_string());
    let old = match old {
        Source::Docx(docx) => docx.to_vec(),
        Source::Markdown(_) => reject_revisions(&docx).map_err(package)?,
    };
    let new = match new {
        Source::Docx(docx) => docx.to_vec(),
        Source::Markdown(_) => accept_revisions(&docx).map_err(package)?,
    };
    let markdown_options = MarkdownOptions {
        input_limits: compared.settings.input_limits,
        ..MarkdownOptions::default()
    };
    let known = segments(&docx_to_markdown(&old, &markdown_options)?.markdown)
        .into_iter()
        .filter_map(|segment| match segment {
            Segment::Note(note, _) => Some(note),
            _ => None,
        })
        .collect();
    patch_word(&docx, &old, &new, Some(&known), options, &markdown_options)
}

/// The redline's patch with each hunk at the paragraph of `old` or `new`
/// its text is, found in order.
fn patch_word(
    docx: &[u8],
    old: &[u8],
    new: &[u8],
    known: Option<&HashSet<String>>,
    options: &PatchOptions,
    markdown_options: &MarkdownOptions,
) -> Result<Patch, MarkdownError> {
    let critic = docx_to_markdown_stories(docx, markdown_options)?.markdown;
    let (mut patch, texts) = build_with(&critic, options, known);
    let (old, new) = (
        word_paragraphs(old, markdown_options.input_limits)?,
        word_paragraphs(new, markdown_options.input_limits)?,
    );
    // Every paragraph is looked for, changed or not, so the search follows
    // the document; text found in no paragraph is in a text box, and goes
    // to the paragraph found last, the one that holds the box.
    let mut sides = [Search::new(&old), Search::new(&new)];
    for block in texts {
        let old_at = sides[0].next(&block.old);
        let new_at = sides[1].next(&block.new);
        if let Some(hunk) = block.hunk.and_then(|i| patch.hunks.get_mut(i)) {
            let at = if hunk.removed { old_at } else { new_at };
            if let Some(at) = at {
                hunk.at = at;
            }
        }
    }
    Ok(patch)
}

/// A Word paragraph as [`patch_word`] looks for it.
struct WordParagraph {
    at: Locator,
    letters: String,
}

/// The paragraphs of one version, looked for in order.
struct Search<'a> {
    letters: Vec<&'a str>,
    paragraphs: &'a [WordParagraph],
    /// Where the search goes on from.
    next: usize,
    /// The paragraph found last.
    last: usize,
}

impl<'a> Search<'a> {
    fn new(paragraphs: &'a [WordParagraph]) -> Self {
        Self {
            letters: paragraphs.iter().map(|p| p.letters.as_str()).collect(),
            paragraphs,
            next: 0,
            last: 0,
        }
    }

    /// Where a block with this Markdown is: the next paragraph with its
    /// text, else the one found last. `None` when the block has no text in
    /// this version, or the document no paragraphs.
    fn next(&mut self, markdown: &str) -> Option<Locator> {
        if !visible(markdown) {
            return None;
        }
        if let Some(found) = find(&letters(&plain(markdown)), &self.letters, self.next) {
            self.next = found + 1;
            self.last = found;
        }
        self.paragraphs.get(self.last).map(|p| p.at.clone())
    }
}

/// The body's paragraphs, then the headers', footers' and notes', as
/// `jubarte text` lists them.
fn word_paragraphs(
    docx: &[u8],
    limits: crate::admission::InputLimits,
) -> Result<Vec<WordParagraph>, MarkdownError> {
    let error = |error: inspect::InspectError| MarkdownError::Docx(error.to_string());
    let (body, stories) = inspect::paragraphs_and_stories_within(docx, limits).map_err(error)?;
    let all = body.into_iter().map(|p| ("body".to_string(), p)).chain(
        stories
            .into_iter()
            .flat_map(|s| s.paragraphs.into_iter().map(move |p| (s.id.clone(), p))),
    );
    Ok(all
        .map(|(story, p)| WordParagraph {
            at: Locator::Paragraph {
                story,
                index: p.index,
            },
            letters: letters(&p.text),
        })
        .collect())
}

/// The first paragraph from `from` on whose text is the block's, else one
/// the block holds (a table row's cell, a paragraph and the one joined to
/// it, a list item's text after its number).
fn find(block: &str, paragraphs: &[&str], from: usize) -> Option<usize> {
    let rest = paragraphs.get(from..)?;
    let at = |test: &dyn Fn(&str) -> bool| {
        rest.iter()
            .position(|p| !p.is_empty() && test(p))
            .map(|i| from + i)
    };
    at(&|p| p == block).or_else(|| at(&|p| block.contains(p)))
}

/// Letters and digits only.
fn letters(text: &str) -> String {
    text.chars().filter(|c| c.is_alphanumeric()).collect()
}

/// Markdown without what a paragraph's text does not have: the list or
/// heading marker, link and image targets, footnote references and HTML
/// tags.
fn plain(markdown: &str) -> String {
    let markdown = markdown.trim_start_matches('\n');
    let mut out = String::new();
    let mut rest = &markdown[marker_len(markdown)..];
    while let Some(c) = rest.chars().next() {
        let skip = if rest.starts_with("](") {
            out.push(']');
            rest.find(')').map(|end| end + 1)
        } else if rest.starts_with("[^") {
            rest.find(']').map(|end| end + 1)
        } else if c == '<' && rest[1..].starts_with(|c: char| c.is_ascii_alphabetic() || c == '/') {
            rest.find('>').map(|end| end + 1)
        } else {
            None
        };
        match skip {
            Some(length) => rest = &rest[length..],
            None => {
                out.push(c);
                rest = &rest[c.len_utf8()..];
            }
        }
    }
    out
}

/// A block's text in the old and new versions, and its hunk if it has one.
struct Paragraphs {
    hunk: Option<usize>,
    old: String,
    new: String,
}

/// The patch, with every block's text in the old and new versions.
fn build(critic: &str, options: &PatchOptions) -> (Patch, Vec<Paragraphs>) {
    build_with(critic, options, None)
}

/// [`build`], where a paragraph whose only marks are highlights and
/// comments in `known` (the old document's) is not a hunk.
fn build_with(
    critic: &str,
    options: &PatchOptions,
    known: Option<&HashSet<String>>,
) -> (Patch, Vec<Paragraphs>) {
    let critic = critic.replace("\r\n", "\n");
    let owner = &options.owner;
    // Only the front matter holds the table: a body paragraph that looks
    // like one names no one.
    let authors = super::write::split_front_matter(&critic)
        .map(|(yaml, _)| super::view_notes::authors(yaml))
        .unwrap_or_default();
    let blocks = blocks(detach_breaks(join_marks(attribute(
        segments(&critic),
        &authors,
        owner,
    ))));
    let mut hunks = Vec::new();
    let mut texts = Vec::new();
    let (mut old_line, mut new_line) = (1, 1);
    for block in &blocks {
        old_line += newlines(&block.separator, block.old_before_visible);
        new_line += newlines(&block.separator, block.new_before_visible);
        let (old_text, new_text) = (block.text(Side::Old), block.text(Side::New));
        if block.marked(known) {
            let (at, removed) = if visible(&new_text) || !visible(&old_text) {
                (Locator::Line(new_line), false)
            } else {
                (Locator::Line(old_line), true)
            };
            texts.push(Paragraphs {
                hunk: Some(hunks.len()),
                old: old_text.clone(),
                new: new_text.clone(),
            });
            hunks.push(hunk(block, at, removed, owner));
        } else {
            texts.push(Paragraphs {
                hunk: None,
                old: old_text.clone(),
                new: new_text.clone(),
            });
        }
        old_line += old_text.matches('\n').count();
        new_line += new_text.matches('\n').count();
    }
    let patch = Patch {
        old_name: options.old_name.clone(),
        new_name: options.new_name.clone(),
        owner: owner.clone(),
        hunks,
    };
    (patch, texts)
}

fn newlines(separator: &str, counted: bool) -> usize {
    if counted {
        separator.matches('\n').count()
    } else {
        0
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum Side {
    Old,
    New,
}

/// Deleted and inserted text: `plain` without the markup nested in it,
/// `marked` with it.
#[derive(Clone, Debug, Default)]
struct Edit {
    old: String,
    new: String,
    old_marked: String,
    new_marked: String,
    by: Option<(String, String)>,
    /// The insertion's own author and date, when a substitution's sides
    /// were made by two authors (the view names them old then new).
    new_by: Option<(String, String)>,
}

impl Edit {
    fn push(&mut self, side: Side, text: &str, plain: bool) {
        let (plain_text, marked) = match side {
            Side::Old => (&mut self.old, &mut self.old_marked),
            Side::New => (&mut self.new, &mut self.new_marked),
        };
        if plain {
            plain_text.push_str(text);
        }
        marked.push_str(text);
    }
}

#[derive(Clone, Debug)]
enum Segment {
    Same(String),
    Edit(Edit),
    HighlightStart,
    HighlightEnd,
    /// A comment's text, as written.
    Note(String, bool),
}

/// The document as text, changes, highlight delimiters and comments.
fn segments(critic: &str) -> Vec<Segment> {
    let mut out: Vec<Segment> = Vec::new();
    let mut edit: Option<Edit> = None;
    let mut side = Side::New;
    let mut note: Option<String> = None;
    let mut attribution = false;
    let mut paragraph_note = false;
    // A ¶ tag attributes the next paragraph separator, not the preceding text.
    let mut paragraph_break: Option<(String, String)> = None;
    // Comments that end inside a change, written after it.
    let mut held: Vec<String> = Vec::new();
    critic::Pieces::default().feed(&critic::encode_spans_only(critic), |piece| match piece {
        Piece::Text(mut text) => {
            if let Some((tag, mut separator)) = paragraph_break.take() {
                while separator.bytes().filter(|&b| b == b'\n').count() < 2 {
                    let width = if text.starts_with("\r\n") {
                        2
                    } else if text.starts_with('\n') {
                        1
                    } else {
                        break;
                    };
                    separator.push_str(&text[..width]);
                    text = &text[width..];
                }
                if separator.bytes().filter(|&b| b == b'\n').count() == 2 {
                    let mut boundary = Edit::default();
                    boundary.push(Side::New, &separator, true);
                    out.push(Segment::Edit(boundary));
                    out.push(Segment::Note(tag, true));
                } else if text.is_empty() {
                    paragraph_break = Some((tag, separator));
                } else {
                    push_same(&mut out, &separator);
                }
                if text.is_empty() {
                    return;
                }
            }
            if let Some(note) = &mut note {
                note.push_str(text);
            } else if let Some(edit) = &mut edit {
                edit.push(side, text, true);
            } else if let Some(Segment::Same(same)) = out.last_mut() {
                same.push_str(text);
            } else {
                out.push(Segment::Same(text.to_string()));
            }
        }
        Piece::Token(token) => match token {
            // A highlight run or a field is Markdown text, not a change.
            Token::MarkStart
            | Token::MarkEnd
            | Token::FieldStart
            | Token::FieldSeparator
            | Token::FieldEnd => {
                let text = critic::delimiter(token);
                if let Some(note) = &mut note {
                    note.push_str(text);
                } else if let Some(edit) = &mut edit {
                    edit.push(side, text, false);
                } else {
                    push_same(&mut out, text);
                }
            }
            Token::InsertStart | Token::DeleteStart | Token::SubstituteStart => {
                edit = Some(Edit::default());
                side = if token == Token::InsertStart {
                    Side::New
                } else {
                    Side::Old
                };
            }
            Token::SubstituteSeparator => side = Side::New,
            Token::InsertEnd | Token::DeleteEnd | Token::SubstituteEnd => {
                if let Some(edit) = edit.take() {
                    out.push(Segment::Edit(edit));
                }
                out.extend(held.drain(..).map(|text| Segment::Note(text, false)));
            }
            Token::HighlightStart | Token::HighlightEnd => {
                let start = token == Token::HighlightStart;
                match &mut edit {
                    Some(edit) => edit.push(side, if start { "{==" } else { "==}" }, false),
                    None if start => out.push(Segment::HighlightStart),
                    None => out.push(Segment::HighlightEnd),
                }
            }
            Token::CommentStart | Token::AttributionStart | Token::ParagraphInsertion => {
                attribution = token != Token::CommentStart;
                paragraph_note = token == Token::ParagraphInsertion;
                note = Some(String::new());
            }
            // A comment paragraph break, inside a note or in dropped
            // text.
            Token::CommentBreak => {
                if let Some(note) = &mut note {
                    note.push_str("\n\n");
                }
            }
            Token::CommentEnd | Token::AttributionEnd => {
                let text = note.take().unwrap_or_default();
                if std::mem::take(&mut paragraph_note) {
                    paragraph_break = Some((text, String::new()));
                    return;
                }
                if edit.is_some() {
                    held.push(text);
                } else {
                    out.push(Segment::Note(text, attribution));
                }
            }
        },
    });
    if let Some((_, separator)) = paragraph_break {
        push_same(&mut out, &separator);
    }
    out
}

/// `Name (date)` in the comment right after a change, or after the
/// comments that follow it, becomes the change's author and date; so does
/// the plain view's numbered note (`r3 Name (date)`), whose number says it
/// names the change. A number alone names no one: the owner made it.
/// An agent tag (`r1 @A`) names the person in the document's `authors:`
/// table, or the patch owner when that handle is absent, and is not a
/// comment; a nested one (`r3 @BO re r1 @AL`) names the change by its
/// first tag. A substitution whose sides two authors made is followed by
/// two such notes, the deletion's then the insertion's.
fn attribute(
    segments: Vec<Segment>,
    authors: &HashMap<String, super::view_notes::Author>,
    owner: &Attribution,
) -> Vec<Segment> {
    let mut out: Vec<Segment> = Vec::with_capacity(segments.len());
    // Whether the last edit has taken its (first) note.
    let mut named_edit = false;
    // The side of the last edit an undated tag of an author dated
    // `first..last` named, by handle: it takes the last day at the end.
    let mut ranged: HashMap<String, (usize, Side)> = HashMap::new();
    for segment in segments {
        // Where the edit a note names sits: the last segment before it that
        // is no note.
        let at = out
            .iter()
            .rposition(|s| !matches!(s, Segment::Note(..)))
            .unwrap_or_default();
        if let Segment::Note(text, true) = &segment
            && let Some(Segment::Edit(edit)) = out
                .iter_mut()
                .rev()
                .find(|s| !matches!(s, Segment::Note(..)))
        {
            if let Some(parts) = super::view_notes::plain_revisions(text.trim())
                && parts.len() == 2
                && !edit.old_marked.is_empty()
                && !edit.new_marked.is_empty()
            {
                let by = |part: &super::view_notes::PlainRevision| {
                    (!part.author.is_empty() || !part.date.is_empty())
                        .then(|| (part.author.clone(), part.date.clone()))
                };
                edit.by = by(&parts[0]);
                edit.new_by = by(&parts[1]);
                named_edit = true;
                continue;
            }
            if let Some(tags) = super::view_notes::revision_tags(text.trim()).or_else(|| {
                super::view_notes::nested_revision_tags(text.trim())
                    .map(|nest| nest.into_iter().take(1).collect())
            }) && let Some(first) = tags.first()
            {
                let mut range = |tag: &super::view_notes::Tag, side: Side| {
                    if tag.date.is_none() && authors.get(&tag.handle).is_some_and(ranged_only) {
                        ranged.insert(tag.handle.clone(), (at, side));
                    }
                };
                let both_sides = !edit.old_marked.is_empty() && !edit.new_marked.is_empty();
                if tags.len() == 2 && both_sides {
                    edit.by = Some(tag_attribution(&tags[0], authors, owner));
                    edit.new_by = Some(tag_attribution(&tags[1], authors, owner));
                    range(&tags[0], Side::Old);
                    range(&tags[1], Side::New);
                    named_edit = true;
                    continue;
                }
                let resolved = Some(tag_attribution(first, authors, owner));
                if !named_edit || (!both_sides && edit.by.is_none()) {
                    edit.by = resolved;
                    // One tag on a substitution: the deletion is the mark
                    // written last, as the reader writes the insertion
                    // first.
                    range(
                        first,
                        if edit.old_marked.is_empty() {
                            Side::New
                        } else {
                            Side::Old
                        },
                    );
                    named_edit = true;
                    continue;
                }
                if both_sides && edit.new_by.is_none() {
                    edit.new_by = resolved;
                    range(first, Side::New);
                    continue;
                }
            }
            let by = if let Some(plain) = super::view_notes::plain_revision(text.trim()) {
                Some(
                    (!plain.author.is_empty() || !plain.date.is_empty())
                        .then_some((plain.author, plain.date)),
                )
            } else if let Some((Some(author), date, "")) = named(text.trim()) {
                Some(Some((author, date.to_string())))
            } else {
                None
            };
            if let Some(by) = by {
                let both_sides = !edit.old_marked.is_empty() && !edit.new_marked.is_empty();
                // A note that names no one (`r3`) leaves a one-sided change
                // to the next note that does.
                if !named_edit || (!both_sides && edit.by.is_none()) {
                    edit.by = by;
                    named_edit = true;
                    continue;
                }
                if both_sides && edit.new_by.is_none() && by.is_some() {
                    edit.new_by = by;
                    continue;
                }
            }
        }
        if matches!(segment, Segment::Edit(_)) {
            named_edit = false;
        }
        out.push(segment);
    }
    for (handle, (at, side)) in ranged {
        let Some((_, last)) = authors.get(&handle).and_then(|known| known.range.as_ref()) else {
            continue;
        };
        let Some(Segment::Edit(edit)) = out.get_mut(at) else {
            continue;
        };
        let last = format!("{last}T23:59:59Z");
        let both_sides = !edit.old_marked.is_empty() && !edit.new_marked.is_empty();
        match side {
            Side::New if both_sides => {
                if let Some((_, date)) = &mut edit.new_by {
                    *date = last;
                }
            }
            Side::Old if both_sides && edit.new_by.is_none() => {
                // The insertion keeps the first day; the deletion takes
                // the last.
                edit.new_by = edit.by.clone();
                if let Some((_, date)) = &mut edit.by {
                    *date = last;
                }
            }
            _ => {
                if let Some((_, date)) = &mut edit.by {
                    *date = last;
                }
            }
        }
    }
    out
}

/// Whether an author row dates its marks only by a range of days
/// (`2026-03-02..2026-03-04`), with no single date or latest one.
fn ranged_only(known: &super::view_notes::Author) -> bool {
    known.range.is_some() && known.date.is_none() && known.latest.is_none()
}

/// Who an agent tag names, as the view reader reads it: the `authors:` row
/// for its handle, `??` no one, and the patch owner a handle the table
/// lacks. A date on the tag wins; otherwise the row's date, latest date or
/// first day of its range. A known row with none of them leaves the change
/// undated; only an unknown handle takes the owner's date.
fn tag_attribution(
    tag: &super::view_notes::Tag,
    authors: &HashMap<String, super::view_notes::Author>,
    owner: &Attribution,
) -> (String, String) {
    let known = authors.get(&tag.handle);
    let author = match known {
        _ if tag.handle == super::view_notes::UNNAMED => String::new(),
        Some(person) => person.name.clone(),
        None => owner.author.clone(),
    };
    if let Some(date) = &tag.date {
        return (author, date.clone());
    }
    let date = match known {
        Some(person) => person
            .date
            .clone()
            .or_else(|| person.latest.clone())
            .or_else(|| {
                person
                    .range
                    .as_ref()
                    .map(|(first, _)| format!("{first}T00:00:00Z"))
            })
            .unwrap_or_default(),
        None if tag.handle == super::view_notes::UNNAMED => String::new(),
        None => owner.date.clone(),
    };
    (author, date)
}

/// The side a one-sided change is on, and whether it is only paragraph
/// marks.
fn one_side(edit: &Edit) -> Option<(Side, bool)> {
    match (edit.old.is_empty(), edit.new.is_empty()) {
        (false, true) => Some((Side::Old, edit.old.trim().is_empty())),
        (true, false) => Some((Side::New, edit.new.trim().is_empty())),
        _ => None,
    }
}

/// The view writes a paragraph mark's change apart from the text beside
/// it, each with its own id (#1135). Word made them as one, so the patch
/// reads them as one: a change on the same side by the same author, with
/// only comments between, joins the change before it when either is the
/// mark. A paragraph deleted whole is then one change ending in its mark,
/// and a deletion across paragraphs one change through the mark.
fn join_marks(segments: Vec<Segment>) -> Vec<Segment> {
    let mut out: Vec<Segment> = Vec::with_capacity(segments.len());
    for segment in segments {
        if let Segment::Edit(edit) = &segment
            && let Some((side, mark)) = one_side(edit)
            && let Some(Segment::Edit(before)) = out
                .iter_mut()
                .rev()
                .find(|s| !matches!(s, Segment::Note(..)))
            && let Some((before_side, _)) = one_side(before)
            && before_side == side
            && before.by == edit.by
            && (mark
                || match side {
                    Side::Old => before.old.ends_with('\n'),
                    Side::New => before.new.ends_with('\n'),
                })
        {
            match side {
                Side::Old => {
                    before.old.push_str(&edit.old);
                    before.old_marked.push_str(&edit.old_marked);
                }
                Side::New => {
                    before.new.push_str(&edit.new);
                    before.new_marked.push_str(&edit.new_marked);
                }
            }
            continue;
        }
        out.push(segment);
    }
    out
}

/// Word deletes or inserts a paragraph with its mark, so the change ends
/// with the paragraph break (or, for the last paragraph, starts with the
/// one before it). That break moves out of the change, after its comments,
/// so the paragraph is a block of its own. A change that is only a break
/// joins or splits paragraphs and stays as it is, unless it leads a
/// paragraph the same side changes whole: the view writes a story's last
/// paragraph and the mark before it as two changes (`{--\n\n--}{r1
/// @C}{--Last.--}{r2 @C}`), and the paragraph is still a hunk of its own.
/// A change that starts inside a paragraph stays as it is too: its break
/// joins that paragraph to the next.
fn detach_breaks(segments: Vec<Segment>) -> Vec<Segment> {
    fn same(out: &mut Vec<Segment>, text: &str) {
        match out.last_mut() {
            Some(Segment::Same(same)) => same.push_str(text),
            _ => out.push(Segment::Same(text.to_string())),
        }
    }
    // Whether the next change starts its paragraph: nothing but a list,
    // quote or heading marker before it on its line.
    fn starts_paragraph(out: &[Segment]) -> bool {
        for segment in out.iter().rev() {
            match segment {
                Segment::Same(text) => match text.rsplit_once('\n') {
                    Some((_, line)) => return !visible(line),
                    None if visible(text) => return false,
                    None => {}
                },
                Segment::Edit(_) => return false,
                _ => {}
            }
        }
        true
    }
    let leads = leading_breaks(&segments);
    let mut out: Vec<Segment> = Vec::with_capacity(segments.len());
    let mut after: Option<String> = None;
    for (at, segment) in segments.into_iter().enumerate() {
        if !matches!(segment, Segment::Note(..))
            && let Some(text) = after.take()
        {
            same(&mut out, &text);
        }
        let Segment::Edit(mut edit) = segment else {
            match segment {
                Segment::Same(text) => same(&mut out, &text),
                other => out.push(other),
            }
            continue;
        };
        let side = match (edit.old.is_empty(), edit.new.is_empty()) {
            (false, true) => Side::Old,
            (true, false) => Side::New,
            _ => {
                out.push(Segment::Edit(edit));
                continue;
            }
        };
        let (plain, marked) = match side {
            Side::Old => (&mut edit.old, &mut edit.old_marked),
            Side::New => (&mut edit.new, &mut edit.new_marked),
        };
        let trailing = plain.len() - plain.trim_end_matches('\n').len();
        let leading = plain.len() - plain.trim_start_matches('\n').len();
        if leads.contains(&at) {
            same(&mut out, plain);
        } else if plain.trim().is_empty() {
            out.push(Segment::Edit(edit));
        } else if trailing >= 2
            && marked.ends_with(&plain[plain.len() - trailing..])
            && starts_paragraph(&out)
        {
            let text = plain.split_off(plain.len() - trailing);
            marked.truncate(marked.len() - trailing);
            out.push(Segment::Edit(edit));
            after = Some(text);
        } else if leading >= 2 && marked.starts_with(&plain[..leading]) {
            let text: String = plain.drain(..leading).collect();
            marked.drain(..leading);
            same(&mut out, &text);
            out.push(Segment::Edit(edit));
        } else {
            out.push(Segment::Edit(edit));
        }
    }
    if let Some(text) = after {
        same(&mut out, &text);
    }
    out
}

/// The changes [`detach_breaks`] moves out as a paragraph's leading
/// break, by position: a change that is only a break, followed (comments
/// between) by the same side's changes of a paragraph's whole text, which
/// ends the story or a break follows. Word often splits that text into
/// several changes, and a line break in it is the view's hard break (`\`
/// before the newline). Text after the paragraph's changes, a paragraph
/// break in them, or another author's mark means the break joins
/// paragraphs (accepting it alone joins them), and it stays a change.
fn leading_breaks(segments: &[Segment]) -> HashSet<usize> {
    // The side a one-sided change makes, its text, and who made it.
    fn one_side(segment: &Segment) -> Option<(Side, &str, Option<&str>)> {
        let Segment::Edit(edit) = segment else {
            return None;
        };
        let author = edit.by.as_ref().map(|(author, _)| author.as_str());
        match (edit.old.is_empty(), edit.new.is_empty()) {
            (false, true) => Some((Side::Old, edit.old.as_str(), author)),
            (true, false) => Some((Side::New, edit.new.as_str(), author)),
            _ => None,
        }
    }
    // Text within one paragraph: every newline is a hard break.
    fn in_paragraph(text: &str) -> bool {
        text.match_indices('\n')
            .all(|(at, _)| text[..at].ends_with('\\'))
    }
    // The first segment from `from` on that is no comment.
    let next =
        |from: usize| (from..segments.len()).find(|&i| !matches!(segments[i], Segment::Note(..)));
    let mut out = HashSet::new();
    for (at, segment) in segments.iter().enumerate() {
        let Some((side, plain, author)) = one_side(segment) else {
            continue;
        };
        if !plain.trim().is_empty() || !plain.contains("\n\n") {
            continue;
        }
        let mut cursor = next(at + 1);
        let mut text = false;
        while let Some(piece) = cursor
            && let Some((piece_side, piece_text, piece_author)) = one_side(&segments[piece])
            && piece_side == side
            && piece_author == author
            && in_paragraph(piece_text)
        {
            text |= !piece_text.trim().is_empty();
            cursor = next(piece + 1);
        }
        if !text {
            continue;
        }
        let ends = match cursor.map(|i| &segments[i]) {
            None => true,
            Some(Segment::Same(after)) => after.starts_with('\n'),
            Some(after) => {
                one_side(after).is_some_and(|(s, t, _)| s == side && t.starts_with("\n\n"))
            }
        };
        if ends {
            out.insert(at);
        }
    }
    out
}

/// A paragraph (or table row) of segments, with the line breaks before it.
struct Block {
    separator: String,
    /// The block before this one is in that version, so the separator is
    /// too.
    old_before_visible: bool,
    new_before_visible: bool,
    segments: Vec<Segment>,
}

impl Block {
    fn text(&self, side: Side) -> String {
        let mut out = String::new();
        for segment in &self.segments {
            match segment {
                Segment::Same(text) => out.push_str(text),
                Segment::Edit(edit) => out.push_str(match side {
                    Side::Old => &edit.old,
                    Side::New => &edit.new,
                }),
                _ => {}
            }
        }
        out
    }

    fn marked(&self, known: Option<&HashSet<String>>) -> bool {
        self.segments.iter().any(|s| match (s, known) {
            (Segment::Same(_), _) => false,
            (Segment::Edit(_), _) | (_, None) => true,
            (Segment::Note(note, _), Some(known)) => !known.contains(note),
            (_, Some(_)) => false,
        })
    }
}

/// The segments split into blocks at the line breaks between paragraphs,
/// outside changes: a change across a paragraph break keeps both
/// paragraphs in one block.
fn blocks(segments: Vec<Segment>) -> Vec<Block> {
    let mut out: Vec<Block> = Vec::new();
    let mut current: Vec<Segment> = Vec::new();
    let mut separator = String::new();
    // The new version's text of the line being read.
    let mut line = String::new();
    let mut visible = (true, true);
    let mut close = |current: &mut Vec<Segment>, separator: &mut String, out: &mut Vec<Block>| {
        let block = Block {
            separator: std::mem::take(separator),
            old_before_visible: visible.0,
            new_before_visible: visible.1,
            segments: std::mem::take(current),
        };
        visible = (
            self::visible(&block.text(Side::Old)),
            self::visible(&block.text(Side::New)),
        );
        out.push(block);
    };
    for segment in segments {
        let Segment::Same(text) = segment else {
            if let Segment::Edit(edit) = &segment {
                match edit.new.rfind('\n') {
                    Some(at) => line = edit.new[at + 1..].to_string(),
                    None => line.push_str(&edit.new),
                }
            }
            current.push(segment);
            continue;
        };
        let mut rest = text.as_str();
        while let Some(at) = rest.find('\n') {
            let before = &rest[..at];
            if !before.is_empty() {
                push_same(&mut current, before);
            }
            line.push_str(before);
            let after = &rest[at + 1..];
            let next = after.split('\n').next().unwrap_or("");
            let boundary = next.trim().is_empty() || !open_paragraph(&line) || !continues(next);
            if boundary {
                if current.is_empty() {
                    separator.push('\n');
                } else {
                    close(&mut current, &mut separator, &mut out);
                    separator.push('\n');
                }
            } else if current.is_empty() {
                separator.push('\n');
            } else {
                push_same(&mut current, "\n");
            }
            line.clear();
            rest = after;
        }
        if !rest.is_empty() {
            push_same(&mut current, rest);
            line.push_str(rest);
        }
    }
    if !current.is_empty() {
        close(&mut current, &mut separator, &mut out);
    }
    out
}

/// Whether a block has text in a version: more than its list, quote or
/// heading marker.
fn visible(text: &str) -> bool {
    let text = text.trim_start();
    if table_row(text) {
        return text
            .chars()
            .any(|c| !matches!(c, '|' | '-' | ':') && !c.is_whitespace());
    }
    !text[marker_len(text)..].trim().is_empty()
}

fn push_same(segments: &mut Vec<Segment>, text: &str) {
    if let Some(Segment::Same(same)) = segments.last_mut() {
        same.push_str(text);
    } else {
        segments.push(Segment::Same(text.to_string()));
    }
}

/// A comment's author, date and text: `Name (date): text`, or the owner's.
fn comment(text: &str, owner: &Attribution, on: Option<String>) -> Comment {
    let trimmed = text.trim();
    if let Some((Some(author), date, rest)) = named(trimmed)
        && let Some(body) = rest.strip_prefix(':').or(rest.is_empty().then_some(""))
    {
        return Comment {
            author,
            date: date.to_string(),
            text: body.trim().to_string(),
            on,
        };
    }
    Comment {
        author: owner.author.clone(),
        date: owner.date.clone(),
        text: trimmed.to_string(),
        on,
    }
}

fn hunk(block: &Block, at: Locator, removed: bool, owner: &Attribution) -> Hunk {
    let mut text = String::new();
    let mut changes: Vec<Change> = Vec::new();
    let mut comments = Vec::new();
    // The highlighted text being read, and the last highlight's.
    let mut highlight: Option<String> = None;
    let mut highlighted: Option<String> = None;
    let mut previous: Option<&Segment> = None;
    for segment in &block.segments {
        match segment {
            Segment::Same(same) => {
                text.push_str(&escape(same));
                if let Some(h) = &mut highlight {
                    h.push_str(same);
                }
            }
            Segment::Edit(edit) => {
                // The note after a change names its author unless the
                // owner made it then.
                let named = |text: &mut String, by: &Option<(String, String)>| match by {
                    Some((author, date)) => {
                        if author != &owner.author || date != &owner.date {
                            text.push_str(&format!("{{>>{author} ({date})<<}}"));
                        }
                        (author.clone(), date.clone())
                    }
                    None => (owner.author.clone(), owner.date.clone()),
                };
                let mut sides = Vec::with_capacity(2);
                match &edit.new_by {
                    // Two authors: the deletion and the insertion are
                    // changes of their own, each named after itself.
                    Some(_) => {
                        text.push_str(&format!("[-{}-]", escape(&edit.old_marked)));
                        sides.push((edit.old.clone(), String::new(), named(&mut text, &edit.by)));
                        text.push_str(&format!("{{+{}+}}", escape(&edit.new_marked)));
                        sides.push((
                            String::new(),
                            edit.new.clone(),
                            named(&mut text, &edit.new_by),
                        ));
                    }
                    None => {
                        if !edit.old_marked.is_empty() {
                            text.push_str(&format!("[-{}-]", escape(&edit.old_marked)));
                        }
                        if !edit.new_marked.is_empty() {
                            text.push_str(&format!("{{+{}+}}", escape(&edit.new_marked)));
                        }
                        sides.push((
                            edit.old.clone(),
                            edit.new.clone(),
                            named(&mut text, &edit.by),
                        ));
                    }
                }
                if let Some(h) = &mut highlight {
                    h.push_str(&edit.new);
                }
                changes.extend(sides.into_iter().map(|(old, new, (author, date))| Change {
                    old,
                    new,
                    author,
                    date,
                    comment: None,
                }));
            }
            Segment::HighlightStart => {
                text.push_str("{==");
                highlight = Some(String::new());
            }
            Segment::HighlightEnd => {
                text.push_str("==}");
                highlighted = highlight.take();
            }
            Segment::Note(note, _) => {
                let on = match previous {
                    Some(Segment::HighlightEnd) => highlighted.take(),
                    _ => None,
                };
                let comment = comment(note, owner, on);
                text.push_str(&format!(
                    "{{>>{} ({}): {}<<}}",
                    comment.author, comment.date, comment.text
                ));
                match (previous, changes.last_mut()) {
                    (Some(Segment::Edit(edit)), Some(change))
                        if change.comment.is_none()
                            && edit
                                .new_by
                                .as_ref()
                                .or(edit.by.as_ref())
                                .is_none_or(|(a, d)| a == &owner.author && d == &owner.date) =>
                    {
                        change.comment = Some(comment);
                    }
                    _ => comments.push(comment),
                }
            }
        }
        previous = Some(segment);
    }
    Hunk {
        at,
        removed,
        text,
        changes,
        comments,
    }
}

/// The patch's own delimiters in text, escaped so they stay text.
fn escape(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut backslashes = 0;
    let mut chars = text.chars().peekable();
    while let Some(c) = chars.next() {
        let next = chars.peek().copied();
        match (c, next) {
            ('[', Some('-')) | ('{', Some('+')) if backslashes % 2 == 0 => out.push('\\'),
            _ => {}
        }
        out.push(c);
        match (c, next) {
            ('-', Some(']')) | ('+', Some('}')) => out.push('\\'),
            _ => {}
        }
        backslashes = if c == '\\' { backslashes + 1 } else { 0 };
    }
    out
}

/// `text` with each line broken at spaces to fit `columns`, where Markdown
/// reads the break as a space.
fn wrap(text: &str, columns: usize) -> String {
    let mut out: Vec<String> = Vec::new();
    let mut fenced = false;
    for line in text.split('\n') {
        let trimmed = line.trim_start();
        let fence = trimmed.starts_with("```") || trimmed.starts_with("~~~");
        let keep = columns == 0
            || fenced
            || fence
            || trimmed.starts_with('#')
            || table_row(line)
            || line.chars().count() <= columns;
        if fence {
            fenced = !fenced;
        }
        if keep {
            out.push(line.to_string());
        } else {
            out.extend(break_line(line, columns).into_iter().map(str::to_string));
        }
    }
    out.join("\n")
}

fn break_line(line: &str, columns: usize) -> Vec<&str> {
    let protected = protected(line);
    let breaks: Vec<usize> = line
        .char_indices()
        .filter(|&(at, c)| c == ' ' && can_break(line, at, &protected))
        .map(|(at, _)| at)
        .collect();
    let mut out = Vec::new();
    let mut start = 0;
    loop {
        let width = |end: usize| line[start..end].chars().count();
        if width(line.len()) <= columns {
            break;
        }
        let candidates = breaks.iter().copied().filter(|&b| b > start);
        let fitting = candidates
            .clone()
            .take_while(|&b| width(b) <= columns)
            .last();
        let Some(at) = fitting.or_else(|| candidates.clone().next()) else {
            break;
        };
        out.push(&line[start..at]);
        start = at + 1;
    }
    out.push(&line[start..]);
    out
}

/// Byte ranges no break may fall in: code spans, link targets, autolinks.
fn protected(line: &str) -> Vec<(usize, usize)> {
    let bytes = line.as_bytes();
    let mut out = Vec::new();
    let mut at = 0;
    while at < bytes.len() {
        match bytes[at] {
            b'\\' => at += 2,
            b'`' => {
                let run = bytes[at..].iter().take_while(|b| **b == b'`').count();
                let fence = &line[at..at + run];
                let mut end = at + run;
                let mut closed = None;
                while let Some(found) = line[end..].find(fence) {
                    let start = end + found;
                    let length = bytes[start..].iter().take_while(|b| **b == b'`').count();
                    if length == run {
                        closed = Some(start + run);
                        break;
                    }
                    end = start + length;
                }
                match closed {
                    Some(close) => {
                        out.push((at, close));
                        at = close;
                    }
                    None => at += run,
                }
            }
            b']' if bytes.get(at + 1) == Some(&b'(') => {
                let mut depth = 0;
                let mut end = at + 1;
                while end < bytes.len() {
                    match bytes[end] {
                        b'(' => depth += 1,
                        b')' => {
                            depth -= 1;
                            if depth == 0 {
                                break;
                            }
                        }
                        b'\\' => end += 1,
                        _ => {}
                    }
                    end += 1;
                }
                out.push((at, end.min(bytes.len())));
                at = end + 1;
            }
            b'<' if line[at + 1..].starts_with("http") || line[at + 1..].starts_with("mailto:") => {
                let end = line[at..].find('>').map_or(bytes.len(), |e| at + e + 1);
                out.push((at, end));
                at = end;
            }
            _ => at += 1,
        }
    }
    out
}

/// The markers that open and close a deletion, insertion, highlight and
/// comment.
const OPENERS: [&str; 4] = ["[-", "{+", "{==", "{>>"];
const CLOSERS: [&str; 4] = ["-]", "+}", "==}", "<<}"];

/// Whether the space at byte `at` may become a line break.
fn can_break(line: &str, at: usize, protected: &[(usize, usize)]) -> bool {
    if protected.iter().any(|&(start, end)| start < at && at < end) {
        return false;
    }
    let before = &line[..at];
    let after = &line[at + 1..];
    if before.is_empty()
        || before.ends_with([' ', '\\'])
        || after.is_empty()
        || after.starts_with(' ')
    {
        return false;
    }
    // A change marker stays on the line of the text it marks: no line ends
    // with an opening marker or starts with a closing one (`{+paragraph` /
    // `+}style` read as two changes).
    if OPENERS.iter().any(|m| before.ends_with(m)) || CLOSERS.iter().any(|m| after.starts_with(m)) {
        return false;
    }
    !starts_block(after)
}

/// Whether a line starting with `text` would start a block of its own.
fn starts_block(text: &str) -> bool {
    let word = text.split(' ').next().unwrap_or("");
    marker_len(text) > 0
        || text.starts_with(['|', '>', '#', '<'])
        || text.starts_with("```")
        || text.starts_with("~~~")
        || (!word.is_empty() && word.chars().all(|c| c == '=' || c == '-'))
        || (word.len() > 1 && word.chars().all(|c| c == '*' || c == '_'))
        || (word.ends_with(['.', ')'])
            && word[..word.len() - 1].bytes().all(|b| b.is_ascii_digit())
            && word.len() > 1)
}

#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod tests {
    use super::*;

    #[test]
    fn a_wrap_never_strands_a_change_marker() {
        // The heading pair wrapped as `{+paragraph` / `+}style`: the break
        // was the inserted space itself.
        let line = "**This document [-shows-]{+demonstrates+} Heading 1 {+paragraph +}style[- with extra bold emphasis-].** {==see==}{>>note <<} end";
        for columns in [20, 40, 56, 60, 72] {
            let wrapped = wrap(line, columns);
            assert_eq!(wrapped.replace('\n', " "), line, "{columns}");
            for row in wrapped.lines() {
                for close in ["+}", "-]", "==}", "<<}"] {
                    assert!(
                        !row.starts_with(close),
                        "{columns}: {row:?} starts with {close}"
                    );
                }
                for open in ["{+", "[-", "{==", "{>>"] {
                    assert!(!row.ends_with(open), "{columns}: {row:?} ends with {open}");
                }
            }
        }
    }

    #[test]
    fn escapes_only_unescaped_delimiters() {
        assert_eq!(escape("a [-b-] {+c+}"), "a \\[-b-\\] \\{+c+\\}");
        assert_eq!(escape("\\[-b"), "\\[-b");
        assert_eq!(escape("x-y [z]"), "x-y [z]");
    }

    #[test]
    fn protects_code_links_and_autolinks() {
        let line = "a `b c` [d](e f) <http://g h>";
        let ranges = protected(line);
        assert_eq!(ranges.len(), 3, "{ranges:?}");
        assert!(!can_break(line, line.find(" c`").unwrap(), &ranges));
        assert!(!can_break(line, line.find(" f)").unwrap(), &ranges));
        assert!(can_break(line, 1, &ranges));
    }

    #[test]
    fn a_numbered_note_after_a_change_names_its_author_never_a_comment() {
        let owner = Attribution {
            author: "Owner".to_string(),
            date: "2026-01-01T00:00:00Z".to_string(),
        };
        let by = |critic: &str| {
            attribute(segments(critic), &HashMap::new(), &owner)
                .into_iter()
                .map(|segment| match segment {
                    Segment::Edit(edit) => format!("edit {:?}", edit.by),
                    Segment::Note(note, _) => format!("note {note}"),
                    _ => String::new(),
                })
                .filter(|s| !s.is_empty())
                .collect::<Vec<_>>()
        };
        let ana = Some(("Ana Lima".to_string(), "2026-09-30T14:05:00Z".to_string()));
        assert_eq!(
            by("a {++b++}{r3 Ana Lima (2026-09-30T14:05:00Z)} c"),
            [format!("edit {ana:?}")]
        );
        assert_eq!(
            by("a {++b++}{footnotes.r3+4 Ana Lima (2026-09-30T14:05:00Z)}"),
            [format!("edit {ana:?}")]
        );
        // The old note without a number still names the author.
        assert_eq!(
            by("a {++b++}{noid Ana Lima (2026-09-30T14:05:00Z)}"),
            [format!("edit {ana:?}")]
        );
        // A number alone names the change and no one: the owner made it.
        assert_eq!(by("a {++b++}{r3}"), ["edit None"]);
        // A comment is still a comment.
        assert_eq!(
            by("a {++b++}{>>Ana Lima (2026-09-30T14:05:00Z): why<<}"),
            ["edit None", "note Ana Lima (2026-09-30T14:05:00Z): why"]
        );
    }

    #[test]
    fn plain_text_drops_markers_targets_note_references_and_tags() {
        assert_eq!(plain("- a<u>b</u>c [d](e)[^1] x < y"), "abc [d] x < y");
    }

    #[test]
    fn no_line_starts_a_block() {
        for text in [
            "- x", "* x", "+ x", "1. x", "12) x", "# x", "> x", "| x", "=== x", "--- x", "```",
            "<div>",
        ] {
            assert!(starts_block(text), "{text}");
        }
        for text in ["x", "1.5 x", "-5 x", "word"] {
            assert!(!starts_block(text), "{text}");
        }
    }
}

#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod literal_wrapping_boundary_tests {
    use super::*;

    #[test]
    fn protected_source_ranges_keep_exact_code_target_and_autolink_owners() {
        for (source, owned) in [
            ("before ``one ` two`` after", "``one ` two``"),
            ("before `one `` two` after", "`one `` two`"),
            (
                "before [label](outer(inner) tail) after",
                "](outer(inner) tail",
            ),
            (r"before [label](escaped\) tail) after", r"](escaped\) tail"),
            ("before [label](unterminated tail", "](unterminated tail"),
            ("before <mailto:one two> after", "<mailto:one two>"),
            ("before <https://one two", "<https://one two"),
        ] {
            let ranges = protected(source);
            assert_eq!(ranges.len(), 1, "{source}");
            assert_eq!(&source[ranges[0].0..ranges[0].1], owned, "{source}");
            for (at, c) in source
                .char_indices()
                .filter(|(at, c)| *c == ' ' && ranges[0].0 < *at && *at < ranges[0].1)
            {
                assert_eq!(c, ' ');
                assert!(!can_break(source, at, &ranges));
            }
            let wrapped = wrap(source, 8);
            assert_eq!(wrapped.replace('\n', " "), source);
            assert!(wrapped.contains(owned));
        }
        for source in [
            "before `unclosed tail",
            r"before \`literal tail",
            "before <ordinary tail>",
            r"before [label]\(literal tail)",
        ] {
            assert!(protected(source).is_empty(), "{source}");
            assert_eq!(wrap(source, 8).replace('\n', " "), source);
        }
    }

    #[test]
    fn exact_markdown_break_guards_preserve_literal_whitespace_and_block_markers() {
        for source in [" leading", "trailing ", "double  space", r"escaped\ space"] {
            for (at, _) in source.char_indices().filter(|(_, c)| *c == ' ') {
                assert!(!can_break(source, at, &[]), "{source:?} at {at}");
            }
        }
        for marker in ["[-", "{+", "{==", "{>>"] {
            let source = format!("{marker} text");
            assert!(!can_break(&source, marker.len(), &[]));
        }
        for marker in ["-]", "+}", "==}", "<<}"] {
            let source = format!("text {marker}");
            assert!(!can_break(&source, 4, &[]));
        }
        for (suffix, starts) in [
            ("*** text", true),
            ("__ text", true),
            ("~~~", true),
            ("12) text", true),
            ("1x. text", false),
            (". text", false),
            ("a*b text", false),
            ("=x text", false),
            ("", false),
        ] {
            assert_eq!(starts_block(suffix), starts, "{suffix}");
            let source = format!("owned {suffix}");
            assert_eq!(
                can_break(&source, 5, &[]),
                !starts && !suffix.is_empty(),
                "{suffix}"
            );
        }
        assert_eq!(wrap("αβ γδ εζ", 5), "αβ γδ\nεζ");
        assert_eq!(wrap("unbreakable", 1), "unbreakable");
        assert_eq!(wrap("a b c", 0), "a b c");
        let fenced = "~~~rust\nowned very long source\n~~~\na b c";
        assert_eq!(
            wrap(fenced, 3),
            "~~~rust\nowned very long source\n~~~\na b\nc"
        );
    }
}

#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod review_tests {
    use super::*;

    #[test]
    fn review_paragraph_tag_keeps_an_incomplete_trailing_separator() {
        let text = segments("A¶{r1 Alice}\n")
            .into_iter()
            .filter_map(|segment| match segment {
                Segment::Same(text) => Some(text),
                _ => None,
            })
            .collect::<String>();
        assert_eq!(text, "A\n");
    }
}

#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod attribution_branch_tests {
    use super::super::view_notes::Author;
    use super::*;

    const D1: &str = "2026-01-02T03:04:05Z";
    const D2: &str = "2026-02-03T04:05:06Z";

    fn owner() -> Attribution {
        Attribution {
            author: "Owner".to_string(),
            date: "2026-01-01T00:00:00Z".to_string(),
        }
    }

    fn change(old: &str, new: &str) -> Segment {
        let mut edit = Edit::default();
        if !old.is_empty() {
            edit.push(Side::Old, old, true);
        }
        if !new.is_empty() {
            edit.push(Side::New, new, true);
        }
        Segment::Edit(edit)
    }

    fn tag(text: &str) -> Segment {
        Segment::Note(text.to_string(), true)
    }

    fn who(author: &str, date: &str) -> Option<(String, String)> {
        Some((author.to_string(), date.to_string()))
    }

    type By = (Option<(String, String)>, Option<(String, String)>);

    /// Each edit's (deletion-or-only, insertion) attribution, and every
    /// note that stayed a note.
    fn run(segments: Vec<Segment>, authors: &HashMap<String, Author>) -> (Vec<By>, Vec<String>) {
        let mut edits = Vec::new();
        let mut notes = Vec::new();
        for segment in attribute(segments, authors, &owner()) {
            match segment {
                Segment::Edit(edit) => edits.push((edit.by, edit.new_by)),
                Segment::Note(text, _) => notes.push(text),
                _ => {}
            }
        }
        (edits, notes)
    }

    fn authors() -> HashMap<String, Author> {
        HashMap::from([
            (
                "AL".to_string(),
                Author {
                    name: "Ana Lima".to_string(),
                    date: None,
                    latest: None,
                    range: Some(("2026-03-02".to_string(), "2026-03-04".to_string())),
                },
            ),
            (
                "BO".to_string(),
                Author {
                    name: "Ben Ode".to_string(),
                    date: Some(D1.to_string()),
                    latest: None,
                    range: None,
                },
            ),
            (
                "LT".to_string(),
                Author {
                    name: "Lia Tam".to_string(),
                    date: None,
                    latest: Some(D2.to_string()),
                    range: Some(("2026-03-02".to_string(), "2026-03-04".to_string())),
                },
            ),
            (
                "ND".to_string(),
                Author {
                    name: "No Date".to_string(),
                    date: None,
                    latest: None,
                    range: None,
                },
            ),
        ])
    }

    #[test]
    fn two_plain_parts_name_each_side_of_a_substitution_only() {
        let none = HashMap::new();
        let (edits, notes) = run(
            vec![
                change("a", "b"),
                tag(&format!("r1 Ana Lima ({D1}); r2 ({D2})")),
            ],
            &none,
        );
        assert_eq!(edits, [(who("Ana Lima", D1), who("", D2))]);
        assert!(notes.is_empty());
        // Parts that name no one and carry no date leave both sides open.
        let (edits, _) = run(vec![change("a", "b"), tag("r1; r2")], &none);
        assert_eq!(edits, [(None, None)]);
        // Two parts on a one-sided change are no substitution: the first
        // plain revision path does not apply, and the note names no one.
        for one_sided in [change("", "b"), change("a", "")] {
            let (edits, notes) = run(
                vec![
                    one_sided,
                    tag(&format!("r1 Ana Lima ({D1}); r2 Ben ({D2})")),
                ],
                &none,
            );
            assert_eq!(edits, [(None, None)]);
            assert_eq!(notes, [format!("r1 Ana Lima ({D1}); r2 Ben ({D2})")]);
        }
    }

    #[test]
    fn agent_tags_resolve_through_the_authors_table() {
        let table = authors();
        // Two tags on a substitution: deletion, then insertion; the ranged
        // author's insertion takes the last day of the range.
        let (edits, _) = run(vec![change("a", "b"), tag("r1 @BO; r2 @AL")], &table);
        assert_eq!(
            edits,
            [(who("Ben Ode", D1), who("Ana Lima", "2026-03-04T23:59:59Z"))]
        );
        // One ranged tag on a substitution: the insertion keeps the first
        // day and the deletion takes the last.
        let (edits, _) = run(vec![change("a", "b"), tag("r1 @AL")], &table);
        assert_eq!(
            edits,
            [(
                who("Ana Lima", "2026-03-04T23:59:59Z"),
                who("Ana Lima", "2026-03-02T00:00:00Z")
            )]
        );
        // One ranged tag on an insertion takes the last day.
        let (edits, _) = run(vec![change("", "b"), tag("r1 @AL")], &table);
        assert_eq!(edits, [(who("Ana Lima", "2026-03-04T23:59:59Z"), None)]);
        // A dated tag wins over the table, and is no range.
        let (edits, _) = run(vec![change("", "b"), tag(&format!("r1 @AL {D2}"))], &table);
        assert_eq!(edits, [(who("Ana Lima", D2), None)]);
        // The latest date of a row with a range wins over the range.
        let (edits, _) = run(vec![change("", "b"), tag("r1 @LT")], &table);
        assert_eq!(edits, [(who("Lia Tam", D2), None)]);
        // A row with no date leaves the change undated; an unknown handle
        // takes the owner; the unnamed handle names no one.
        let (edits, _) = run(
            vec![
                change("", "b"),
                tag("r1 @ND"),
                change("", "c"),
                tag("r2 @ZZ"),
                change("", "d"),
                tag("r3 @??"),
            ],
            &table,
        );
        assert_eq!(
            edits,
            [
                (who("No Date", ""), None),
                (who("Owner", "2026-01-01T00:00:00Z"), None),
                (who("", ""), None),
            ]
        );
        // Two tags on a one-sided change: the first names it.
        let (edits, _) = run(vec![change("", "b"), tag("r1 @BO; r2 @ND")], &table);
        assert_eq!(edits, [(who("Ben Ode", D1), None)]);
        // A nested tag names the change by its own (first) tag.
        let (edits, _) = run(vec![change("a", ""), tag("r3 @BO re r1 @ND")], &table);
        assert_eq!(edits, [(who("Ben Ode", D1), None)]);
    }

    #[test]
    fn later_tags_fill_the_open_side_or_stay_notes() {
        let table = authors();
        // A second single tag on a substitution names the insertion; a third
        // has no side left and stays a note.
        let (edits, notes) = run(
            vec![
                change("a", "b"),
                tag("r1 @BO"),
                tag("r2 @AL"),
                tag("r3 @ND"),
            ],
            &table,
        );
        assert_eq!(
            edits,
            [(who("Ben Ode", D1), who("Ana Lima", "2026-03-04T23:59:59Z"))]
        );
        assert_eq!(notes, ["r3 @ND"]);
        // A number alone names no one; the next tag on the one-sided
        // change then names it.
        let (edits, _) = run(vec![change("", "b"), tag("r3"), tag("r4 @BO")], &table);
        assert_eq!(edits, [(who("Ben Ode", D1), None)]);
        // A named one-sided change keeps its author against a later tag.
        let (edits, notes) = run(vec![change("", "b"), tag("r1 @BO"), tag("r2 @ND")], &table);
        assert_eq!(edits, [(who("Ben Ode", D1), None)]);
        assert_eq!(notes, ["r2 @ND"]);
    }

    #[test]
    fn plain_and_named_notes_fill_sides_in_order() {
        let none = HashMap::new();
        // Plain revisions: the first names the deletion, the second the
        // insertion; a nameless third stays a note.
        let (edits, notes) = run(
            vec![
                change("a", "b"),
                tag(&format!("r1 Ana Lima ({D1})")),
                tag(&format!("r2 Ben Ode ({D2})")),
                tag("r3"),
            ],
            &none,
        );
        assert_eq!(edits, [(who("Ana Lima", D1), who("Ben Ode", D2))]);
        assert_eq!(notes, ["r3"]);
        // A bare `Name (date)` note names a change too.
        let (edits, _) = run(
            vec![change("", "b"), tag(&format!("Ana Lima ({D1})"))],
            &none,
        );
        assert_eq!(edits, [(who("Ana Lima", D1), None)]);
        // A dated note with no name, or a comment after a name, names no
        // one and stays.
        let (edits, notes) = run(
            vec![
                change("", "b"),
                tag(&format!("({D1})")),
                tag(&format!("Ana Lima ({D1}): why")),
            ],
            &none,
        );
        assert_eq!(edits, [(None, None)]);
        assert_eq!(notes.len(), 2);
        // A nameless number leaves the substitution's insertion open to the
        // next named note, never to another nameless one.
        let (edits, notes) = run(
            vec![
                change("a", "b"),
                tag(&format!("r1 Ana Lima ({D1})")),
                tag("r2"),
            ],
            &none,
        );
        assert_eq!(edits, [(who("Ana Lima", D1), None)]);
        assert_eq!(notes, ["r2"]);
        // On a one-sided change named by nobody, a later plain note names it.
        let (edits, _) = run(
            vec![
                change("a", ""),
                tag("r2"),
                tag(&format!("r3 Ben Ode ({D2})")),
            ],
            &none,
        );
        assert_eq!(edits, [(who("Ben Ode", D2), None)]);
    }
}

#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod segment_branch_tests {
    use super::*;

    fn show(segments: &[Segment]) -> Vec<String> {
        segments
            .iter()
            .map(|s| match s {
                Segment::Same(t) => format!("S:{t}"),
                Segment::Edit(e) => {
                    format!("E:{}|{}|{}|{}", e.old, e.new, e.old_marked, e.new_marked)
                }
                Segment::Note(t, a) => format!("N:{t}:{a}"),
                Segment::HighlightStart => "H<".to_string(),
                Segment::HighlightEnd => "H>".to_string(),
            })
            .collect()
    }

    fn insert(text: &str) -> Segment {
        let mut edit = Edit::default();
        edit.push(Side::New, text, true);
        Segment::Edit(edit)
    }

    fn delete(text: &str) -> Segment {
        let mut edit = Edit::default();
        edit.push(Side::Old, text, true);
        Segment::Edit(edit)
    }

    fn marked_insert(plain: &str, marked: &str) -> Segment {
        Segment::Edit(Edit {
            new: plain.to_string(),
            new_marked: marked.to_string(),
            ..Edit::default()
        })
    }

    fn by(segment: Segment, author: &str) -> Segment {
        match segment {
            Segment::Edit(mut edit) => {
                edit.by = Some((author.to_string(), String::new()));
                Segment::Edit(edit)
            }
            other => other,
        }
    }

    #[test]
    fn highlight_marks_are_text_in_plain_runs_changes_and_comments() {
        assert_eq!(show(&segments("a ==b== c")), ["S:a ==b== c"]);
        assert_eq!(
            show(&segments("x {++y ==z== w++} {>>see ==q==<<}")),
            ["S:x ", "E:|y z w||y ==z== w", "S: ", "N:see ==q==:false"]
        );
    }

    #[test]
    fn a_paragraph_tag_owns_the_separator_after_it() {
        // Two newlines after the tag: a boundary change named by the tag.
        assert_eq!(
            show(&segments("a¶{r1 @AL}\n\nb")),
            ["S:a", "E:|\n\n||\n\n", "N:r1 @AL:true", "S:b"]
        );
        // CRLF separators count as one break each.
        assert_eq!(
            show(&segments("a¶{r1 @AL}\r\n\r\nb")),
            ["S:a", "E:|\r\n\r\n||\r\n\r\n", "N:r1 @AL:true", "S:b"]
        );
        // Text right after the tag: no separator to own.
        assert_eq!(show(&segments("a¶{r1 @AL}b")), ["S:ab"]);
        // A single break at the end stays text.
        assert_eq!(show(&segments("a¶{r1 @AL}\n")), ["S:a\n"]);
    }

    #[test]
    fn detach_breaks_moves_paragraph_marks_out_of_whole_paragraph_changes() {
        // A whole inserted paragraph that ends the story: its break follows.
        assert_eq!(
            show(&detach_breaks(vec![insert("Para.\n\n")])),
            ["E:|Para.||Para.", "S:\n\n"]
        );
        // After visible text on the same line the change starts inside a
        // paragraph and keeps its break.
        assert_eq!(
            show(&detach_breaks(vec![
                Segment::Same("x".into()),
                insert("Para.\n\n")
            ])),
            ["S:x", "E:|Para.\n\n||Para.\n\n"]
        );
        // Markup after the break keeps the break inside.
        assert_eq!(
            show(&detach_breaks(vec![marked_insert(
                "Para.\n\n",
                "Para.\n\n=="
            )])),
            ["E:|Para.\n\n||Para.\n\n=="]
        );
        // A leading break moves out before the change.
        assert_eq!(
            show(&detach_breaks(vec![
                Segment::Same("a".into()),
                delete("\n\nGone")
            ])),
            ["S:a\n\n", "E:Gone||Gone|"]
        );
        // Unless markup leads the change.
        assert_eq!(
            show(&detach_breaks(vec![marked_insert("\n\nNew", "==\n\nNew")])),
            ["E:|\n\nNew||==\n\nNew"]
        );
    }

    #[test]
    fn leading_breaks_need_a_whole_same_side_paragraph_after_them() {
        let note = || Segment::Note("r1 @AL".into(), true);
        // Break, then the paragraph's text ending the story.
        assert_eq!(
            leading_breaks(&[insert("\n\n"), note(), insert("Para.")]),
            HashSet::from([0])
        );
        // The other side's change after the break: no paragraph.
        assert!(leading_breaks(&[insert("\n\n"), delete("x")]).is_empty());
        // Another author's text: no paragraph.
        assert!(leading_breaks(&[insert("\n\n"), by(insert("Para."), "Bo")]).is_empty());
        // A soft line break inside the paragraph is fine; a plain newline
        // is a second paragraph.
        assert_eq!(
            leading_breaks(&[insert("\n\n"), insert("one\\\ntwo")]),
            HashSet::from([0])
        );
        assert!(leading_breaks(&[insert("\n\n"), insert("one\ntwo")]).is_empty());
        // A same-side change starting a new paragraph ends it; another
        // side's change does not.
        assert_eq!(
            leading_breaks(&[insert("\n\n"), insert("P"), insert("\n\nQ")]),
            HashSet::from([0])
        );
        assert!(leading_breaks(&[insert("\n\n"), insert("P"), delete("\n\nQ")]).is_empty());
        // Text after the paragraph on the same line joins paragraphs.
        assert!(
            leading_breaks(&[insert("\n\n"), insert("P"), Segment::Same(" tail".into())])
                .is_empty()
        );
        assert_eq!(
            leading_breaks(&[insert("\n\n"), insert("P"), Segment::Same("\nnext".into())]),
            HashSet::from([0])
        );
    }

    #[test]
    fn soft_breaks_inside_a_paragraph_keep_one_block() {
        // A continuation line after an empty block start goes to the
        // separator, not the block.
        let out = blocks(vec![Segment::Same("\ncontinued\n\nnext".into())]);
        assert_eq!(out.len(), 2);
        assert_eq!(out[0].separator, "\n");
        assert_eq!(out[0].text(Side::New), "continued");
        assert_eq!(out[1].separator, "\n\n");
        assert_eq!(out[1].text(Side::Old), "next");
    }

    #[test]
    fn comments_need_a_colon_after_the_attribution() {
        let owner = Attribution {
            author: "Owner".into(),
            date: "2026-01-01T00:00:00Z".into(),
        };
        let named = comment("Ana Lima (2026-02-02T00:00:00Z): why", &owner, None);
        assert_eq!(
            (named.author.as_str(), named.text.as_str()),
            ("Ana Lima", "why")
        );
        let bare = comment("Ana Lima (2026-02-02T00:00:00Z)", &owner, None);
        assert_eq!((bare.author.as_str(), bare.text.as_str()), ("Ana Lima", ""));
        let text_after = comment("Ana Lima (2026-02-02T00:00:00Z) why", &owner, None);
        assert_eq!(text_after.author, "Owner");
        assert_eq!(text_after.text, "Ana Lima (2026-02-02T00:00:00Z) why");
    }

    #[test]
    fn tilde_fences_keep_long_code_lines_whole() {
        let long = "word ".repeat(20);
        let text = format!("~~~\n{long}\n~~~\n{long}");
        let wrapped = wrap(&text, 20);
        let lines: Vec<&str> = wrapped.lines().collect();
        assert_eq!(lines[0], "~~~");
        assert_eq!(lines[1], long);
        assert_eq!(lines[2], "~~~");
        assert!(lines[3..].iter().all(|l| l.chars().count() <= 20));
    }
}

#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod fence_branch_tests {
    use super::super::view_notes::Author;
    use super::*;

    #[test]
    fn backtick_fences_keep_their_lines_whole() {
        let text = "```\na code line far longer than ten columns\n```\nprose words that wrap";
        let wrapped = wrap(text, 10);
        assert_eq!(
            wrapped,
            "```\na code line far longer than ten columns\n```\nprose\nwords that\nwrap"
        );
    }

    #[test]
    fn only_a_bare_range_dates_marks_by_range() {
        let range = Some(("2026-03-02".to_string(), "2026-03-04".to_string()));
        let author = |date: Option<&str>, latest: Option<&str>, range| Author {
            name: "A".to_string(),
            date: date.map(str::to_string),
            latest: latest.map(str::to_string),
            range,
        };
        assert!(ranged_only(&author(None, None, range.clone())));
        assert!(!ranged_only(&author(
            Some("2026-03-02"),
            None,
            range.clone()
        )));
        assert!(!ranged_only(&author(None, Some("2026-03-04"), range)));
        assert!(!ranged_only(&author(None, None, None)));
    }
}