deduxit 0.5.0

A collection of logic suites: decides, checks, proves step by step and exports sequents of linear logic and of classical, intuitionistic and minimal propositional logic, with checked proofs, Kripke countermodels and Rocq certificates.
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
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

//! Draws proofs, sequents and proof nets as SVG documents.
//!
//! Every call returns a whole SVG document, drawn under a [`Style`]:
//!
//! | to draw | call |
//! |---|---|
//! | a proof, as a proof tree | [`to_string`] of its [`Proof::derivation`](crate::linear::Proof::derivation) |
//! | the same, written into your own buffer, with a stop | [`write()`] |
//! | a sequent alone, as one line of text | [`sequent`] |
//! | a proof net, or any proof structure | [`net()`] |
//! | a step of cut elimination on a proof net | [`net_step`] |
//! | a proof structure with `!`-boxes, or a step on one | [`mell_net`], [`mell_net_step`] |
//! | a Kripke countermodel of an ordinary sequent | [`countermodel`] |
//!
//! `Style::default()` draws black on a transparent background in the
//! Euler Math font, and [`Style::dark()`] light on dark. `export::png` and
//! `export::pdf` render a drawing to an image or a PDF.
//!
//! Needs the cargo feature `svg` (on by default).
//!
//! # Examples
//!
//! A proof as a proof tree:
//!
#![cfg_attr(feature = "parse", doc = "```")]
#![cfg_attr(not(feature = "parse"), doc = "```ignore")]
//! use deduxit::export::svg::{self, Style};
//! use deduxit::linear::{Mode, Options, Sequent, prove};
//!
//! let sequent: Sequent = "A, A -o B |- B".parse()?;
//! let outcome = prove(&sequent, Mode::INTUITIONISTIC, &Options::default())?;
//! let proof = outcome.verdict.proof().expect("provable");
//! let svg = svg::to_string(&proof.derivation()?, &Style::default())?;
//! assert!(svg.starts_with("<svg xmlns=\"http://www.w3.org/2000/svg\""));
//! assert!(svg.contains("<title>A, A ⊸ B ⊢ B</title>"));
//! # Ok::<(), deduxit::Error>(())
//! ```
//!
//! The proof net of a proof:
//!
#![cfg_attr(feature = "parse", doc = "```")]
#![cfg_attr(not(feature = "parse"), doc = "```ignore")]
//! use deduxit::Limits;
//! use deduxit::export::svg::{self, Style};
//! use deduxit::linear::{Criterion, Mode, Options, ProofStructure, Sequent, prove};
//!
//! let sequent: Sequent = "A * B |- B * A".parse()?;
//! let outcome = prove(&sequent, Mode::CLASSICAL, &Options::default())?;
//! let proof = outcome.verdict.proof().expect("provable");
//! let net = ProofStructure::from_proof(proof, Criterion::MLL, &Limits::default(), |_| false)?;
//! let svg = svg::net(&net, &Style::default(), &Limits::default(), |_| false)?;
//! assert!(svg.contains("<title>⊢ A⊥ ⅋ B⊥, B ⊗ A</title>"));
//! # Ok::<(), deduxit::Error>(())
//! ```
//!
//! A sequent alone:
//!
#![cfg_attr(feature = "parse", doc = "```")]
#![cfg_attr(not(feature = "parse"), doc = "```ignore")]
//! use deduxit::export::svg::{self, Style};
//! use deduxit::{Limits, linear::{Mode, Sequent}};
//!
//! let sequent: Sequent = "A |- A".parse()?;
//! let svg = svg::sequent(&sequent, Mode::CLASSICAL, &Style::default(), &Limits::default())?;
//! assert!(svg.starts_with("<svg xmlns=\"http://www.w3.org/2000/svg\""));
//! assert!(svg.contains("<title>⊢ A⊥, A</title>"));
//! # Ok::<(), deduxit::Error>(())
//! ```
//!
//! # How a drawing is laid out
//!
//! deduxit computes the layout, not the viewer. So the output is the same
//! bytes on every machine, and needs no font file at run time.
//! - Every width is the sum of the advances of the style's [`Font`]: by
//!   default Euler Math's, or another [`MathFont`]'s, from tables committed
//!   with the code.
//! - The document names the font's families (`'Euler Math', 'Neo Euler',
//!   serif` by default) and does not embed the font. Every `<text>` carries
//!   its computed width as `textLength`, so a viewer that sets it in
//!   another font still fits the layout.
//! - The letters of atom names are mathematical italic characters, which a
//!   math font sets as math italic. Rule names stay upright. The `⊥` of a
//!   negated atom is a superscript, and the `₁` and `₂` of a rule name are
//!   subscripts.
//! - All coordinates are integers in thousandths of an em of formula text,
//!   which is [`Style::font_size`] pixels. Text stays text, which a reader
//!   can select, and the drawing scales without loss.
//!
//! A drawing is an accessible image: the root has `role="img"`, the
//! `<title>` names the drawing by its sequent in plain text, and with
//! [`Style::description`] a `<desc>` reads it out in order.

/// Fitch proofs as numbered lines.
#[cfg(feature = "serialize")]
mod fitch;
/// The fonts a drawing can ask for, and their metrics.
mod font;
/// Kripke models, as rows of worlds with arrows up.
mod kripke;
/// Proof structures with `!`-boxes, drawn as the multiplicative ones are.
mod mell;
/// Proof structures as formula trees under their axiom links.
mod net;
/// Derivations as proof trees.
mod tree;

use super::Drawable;
use crate::Error;
use crate::linear::nets::{MellStructure, ProofStructure};
use crate::linear::occurrences::Reading;
use crate::linear::proofs::style::{Part, parts};
use crate::linear::proofs::{Labels, OpenGoal};
use crate::linear::sequents::Sequent;
use crate::linear::sequents::notation::{Atoms, Notation};
use crate::ordinary::Symbols;
pub use font::{Advances, Font, MONOSPACE, MathFont};
use font::{DEPTH, HEIGHT, LOWER, RAISE, SCRIPT};
use std::fmt::Write;

/// How a drawing looks: its font, rule labels, sizes, distances and
/// colours. Every drawing of this module takes one.
///
/// Start from `Style::default()`, [`Style::dark()`] or
/// [`Style::monospace()`], and change the fields you need, by assignment
/// or with the `with_*` methods. A struct literal is refused outside the
/// crate, so that a field added later breaks no caller. Each field below
/// gives its default.
///
/// - Lengths are in thousandths of an em of formula text: 1000 is the size
///   of formula text, which is [`font_size`](Self::font_size) pixels.
/// - Colours are CSS colours, such as `"black"` or `"#0072b2"`.
/// - Every number has a maximum. A drawing checks its style first
///   ([`check`](Self::check)) and refuses one past it.
///
/// In JSON (feature `serialize`) each field is under its own name. A
/// field left out keeps its default, and an unknown field is an error.
///
/// # Examples
///
/// ```
/// use deduxit::export::svg::{MathFont, Style};
///
/// let style = Style::dark()
///     .with_font(MathFont::StixTwo.font())
///     .with_font_size(20);
/// assert_eq!(style.font.family, "'STIX Two Math', serif");
/// assert!(style.check().is_ok());
/// ```
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(default, deny_unknown_fields))]
pub struct Style {
    /// The font the document asks for, and the advances its layout gives
    /// the characters. Default: Euler Math ([`Font::euler`]).
    /// [`MathFont::font`] gives the other math fonts.
    pub font: Font,
    /// How the rules are labelled. Default: [`Labels::Upright`].
    pub labels: Labels,
    /// How an open goal of a proof in progress is drawn. Default: its
    /// sequent under vertical dots ([`OpenGoal::Dots`]).
    pub open: OpenGoal,
    /// Whether each formula of an inference's conclusion in a derivation
    /// is a group of its own, with the id `i<n>-<p>`: `p` is the
    /// formula's position in the sequent of inference `n`, hypotheses
    /// first. Default: `false`.
    pub ids: bool,
    /// Whether a drawing of a derivation or a net has a `<desc>`, which a
    /// screen reader reads out: the derivation's numbered inferences,
    /// premises first, or short sentences of the net's conclusion, links,
    /// boxes and verdict. A sequent drawn alone has none. Default: `true`.
    pub description: bool,
    /// The size of formula text in pixels. It scales the whole drawing:
    /// the document is this many pixels wide per 1000 units of its view
    /// box. Default: 16.
    pub font_size: u32,
    /// The size of rule names, and of the connectives in a proof net's
    /// nodes, in thousandths of the size of formula text. Default: 800.
    pub label_size: u32,
    /// The vertical distance between rows. Default: 1500.
    ///
    /// - In a derivation, from the baseline of a conclusion to the
    ///   baseline of its premises.
    /// - In a compact proof net, from one layer of nodes to the next.
    /// - In a proof net drawn with its formulas, the space between the
    ///   text of one layer and the text of the next, besides the
    ///   [`node_radius`](Self::node_radius) the joints take.
    ///
    /// A net with boxes may set its rows further apart, so that the wires
    /// that share a row stay apart.
    pub line_height: u32,
    /// The horizontal space between two premises side by side in a
    /// derivation. Default: 1500.
    pub premise_gap: u32,
    /// The horizontal space between the formula trees of two conclusions
    /// side by side in a proof net. In a compact net it is also the space
    /// between the two premises' subtrees of a `⊗` or `⅋`, so between two
    /// neighbouring literals. Default: 1000.
    pub literal_gap: u32,
    /// The horizontal space between the right end of an inference line
    /// and its rule name. Default: 200.
    pub label_gap: u32,
    /// The empty border around the drawing. Default: 300.
    pub margin: u32,
    /// The thickness of every line. Default: 40.
    pub stroke_width: u32,
    /// The height of an axiom link's arc, in thousandths of half its
    /// width: at 600, an arc 2000 wide is 600 high. Arcs of one shape
    /// nest, so the arc over two literals between two others stays below
    /// theirs. Default: 600.
    pub link_height: u32,
    /// The half-width past which an axiom link's arc grows only with the
    /// square root of its half-width, so that a wide link stays low. The
    /// arcs of nested links still never cross. `None` lets every arc grow
    /// in proportion to its width. Default: `Some(8000)`.
    pub link_cap: Option<u32>,
    /// The radius of a `⊗` or `⅋` node's circle in a compact proof net,
    /// and, in a net drawn with its formulas, how far the edges stop from
    /// the connective at a link's joint. Other parts of a net are sized by
    /// it: a cut link's bar stands twice the radius under its formulas, an
    /// arrowhead is half the radius long, and a box's outline is the
    /// radius away from its contents. Default: 380.
    pub node_radius: u32,
    /// The colour of text. Default: `"black"`.
    pub text: String,
    /// The colour of inference lines, and of a proof net's edges, nodes,
    /// boxes and cut links where no other colour of the style applies.
    /// Default: `"black"`.
    pub line: String,
    /// The colour of the edges into a `⅋` or `?` node and of a `?` node's
    /// wires, which are also dashed: a switching keeps one premise of a
    /// `⅋`. This holds under [`Premises::Dashed`], the default of
    /// [`net_look`](Self::net_look). Under [`Premises::Plain`], and in an
    /// essential net, they are drawn as the other edges. Default:
    /// `"#0072b2"`, a blue.
    pub par: String,
    /// The colour of axiom links. Default: `"black"`.
    pub link: String,
    /// The colour of what a drawing of a net points out. Default:
    /// `"#d55e00"`, an orange.
    ///
    /// - The edges of a switching cycle, or in an essential net those of a
    ///   directed cycle or of a path around an implication.
    /// - In a net without boxes that falls into several parts, the edges,
    ///   conclusions and links of every part but the first.
    /// - What a step of cut elimination acts on ([`net_step`],
    ///   [`mell_net_step`]).
    pub highlight: String,
    /// The colour the drawing is filled with, or `None` for a transparent
    /// background. Default: `None`.
    pub background: Option<String>,
    /// Whether a proof structure is drawn as its essential net, when its
    /// sequent has an intuitionistic reading (which formulas are
    /// hypotheses and which is the goal). Default: `false`.
    ///
    /// An essential net is the proof net with the reading drawn in:
    /// - every edge is an arrow, from the hypotheses toward the goal;
    /// - the input occurrences are in the [`input`](Self::input) colour;
    /// - every formula is written as the reading reads it, a literal as its
    ///   atom;
    /// - the links are the reading's connectives, `⊸` and `⊗`;
    /// - each implication in output position is joined to its antecedent
    ///   by a dotted line in the [`dominator`](Self::dominator) colour;
    /// - a directed cycle, or a path around an implication, is in the
    ///   [`highlight`](Self::highlight) colour.
    ///
    /// A structure without an intuitionistic reading is drawn as if this
    /// were `false`, so one style serves classical and intuitionistic
    /// nets. A net with boxes highlights its switching cycle, which
    /// decides it.
    pub essential: bool,
    /// How a proof net is drawn: every subformula written
    /// ([`NetDrawing::Formulas`], the default), or only the literals and
    /// the conclusions ([`NetDrawing::Compact`]).
    pub net: NetDrawing,
    /// How a proof net's switched edges, conclusions and `?` nodes look.
    /// Default: [`NetLook::DEDUXIT`].
    pub net_look: NetLook,
    /// The colour of the input occurrences of an essential net, of their
    /// edges and of the edges below the hypotheses. Default: `"#0072b2"`,
    /// the blue of [`par`](Self::par); green is the colour of a checked
    /// proof.
    pub input: String,
    /// The colour of the dotted line in an essential net from an
    /// implication to its antecedent, which no edge joins: the implication
    /// must dominate it. Default: `"#cc79a7"`, a pink.
    pub dominator: String,
    /// The options of the derivation's lambda-term, written under its
    /// conclusion as its typing judgement ([`lambda`](crate::lambda)) in
    /// the drawing's own notation. Default: `None`, which writes no term.
    ///
    /// A derivation without a term is refused ([`Error::NoTerm`]). So is a
    /// term whose text would pass the default output bound
    /// ([`Limits::DEFAULT_DERIVATION_BYTES`](crate::Limits::DEFAULT_DERIVATION_BYTES)),
    /// before anything is written.
    pub lambda: Option<crate::lambda::Options>,
}

impl Default for Style {
    /// Returns the default style: Euler Math, upright labels, an open
    /// goal under vertical dots, no ids per formula, and a description.
    /// Lines and text are black at 16 pixels to the em on a transparent
    /// background, `⅋` edges blue and a switching cycle orange. Each field
    /// of [`Style`] gives its own default.
    fn default() -> Self {
        Self {
            font: Font::euler(),
            labels: Labels::Upright,
            open: OpenGoal::Dots,
            ids: false,
            description: true,
            font_size: 16,
            label_size: 800,
            line_height: 1500,
            premise_gap: 1500,
            literal_gap: 1000,
            label_gap: 200,
            margin: 300,
            stroke_width: 40,
            link_height: 600,
            link_cap: Some(8000),
            node_radius: 380,
            text: "black".into(),
            line: "black".into(),
            par: "#0072b2".into(),
            link: "black".into(),
            highlight: "#d55e00".into(),
            background: None,
            essential: false,
            input: "#0072b2".into(),
            dominator: "#cc79a7".into(),
            net: NetDrawing::Formulas,
            net_look: NetLook::DEDUXIT,
            lambda: None,
        }
    }
}

/// How a proof net is drawn. In JSON (feature `serialize`) `"formulas"`
/// or `"compact"`.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(rename_all = "lowercase"))]
pub enum NetDrawing {
    /// Every subformula of the conclusions written as its formula, where
    /// it stands in its conclusion's text. The literals stand along the
    /// top under the axiom links' arcs. Each link of a `⊗` or `⅋` joins
    /// its two premises to its conclusion written below them, with the
    /// connective small at the joint. The conclusions stand at the bottom
    /// in the sequent's order.
    #[default]
    Formulas,
    /// Only the literals and the conclusions written, for nets too wide to
    /// write every subformula. The literals stand along the top, every
    /// inner `⊗` and `⅋` is a small circle, and the conclusions stand at
    /// the bottom in the sequent's order.
    Compact,
}

/// How the nodes and edges of a proof net look, in either
/// [`NetDrawing`]: deduxit's own look ([`NetLook::DEDUXIT`], the default),
/// or the look the textbooks share ([`NetLook::TEXTBOOK`]). Each field can
/// be set apart from the others.
///
/// In JSON (feature `serialize`) the three fields, or the name of a
/// [`NetPreset`] alone, such as `"textbook"`, which reads as that preset's
/// [`NetPreset::look`].
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize))]
pub struct NetLook {
    /// How the premise edges of a `⅋` or `?` node and the wires of a `?`
    /// node are drawn.
    pub premises: Premises,
    /// Where the conclusions of a net with boxes stand.
    pub conclusions: Conclusions,
    /// How a `?` node of a net with boxes is drawn.
    pub why_not: WhyNot,
}

impl NetLook {
    /// deduxit's own look, the default: switched edges dashed, a `!`
    /// conclusion with auxiliary doors a row above its `?` nodes, and one
    /// `?` node with any number of premises. An auxiliary door is where a
    /// wire leaves a box for a `?` node outside it.
    pub const DEDUXIT: Self = Self {
        premises: Premises::Dashed,
        conclusions: Conclusions::Raised,
        why_not: WhyNot::Node,
    };

    /// The look the textbooks share: every edge plain, every conclusion
    /// on the bottom row, and a `?` node drawn as the dereliction,
    /// contraction and weakening nodes of the sequent calculus's rules.
    pub const TEXTBOOK: Self = Self {
        premises: Premises::Plain,
        conclusions: Conclusions::Bottom,
        why_not: WhyNot::Rules,
    };

    /// Returns the look with other [`premises`](Self::premises).
    #[must_use]
    pub const fn with_premises(self, premises: Premises) -> Self {
        Self { premises, ..self }
    }

    /// Returns the look with other [`conclusions`](Self::conclusions).
    #[must_use]
    pub const fn with_conclusions(self, conclusions: Conclusions) -> Self {
        Self {
            conclusions,
            ..self
        }
    }

    /// Returns the look with another [`why_not`](Self::why_not).
    #[must_use]
    pub const fn with_why_not(self, why_not: WhyNot) -> Self {
        Self { why_not, ..self }
    }
}

#[cfg(feature = "serialize")]
impl<'de> serde::Deserialize<'de> for NetLook {
    /// Reads a look's fields, or a [`NetPreset`]'s name.
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        /// A look's fields as JSON writes them, each left out the default
        /// look's.
        #[derive(serde::Deserialize)]
        #[serde(default, deny_unknown_fields)]
        struct Fields {
            /// [`NetLook::premises`].
            premises: Premises,
            /// [`NetLook::conclusions`].
            conclusions: Conclusions,
            /// [`NetLook::why_not`].
            why_not: WhyNot,
        }

        impl Default for Fields {
            /// Returns the default look's fields.
            fn default() -> Self {
                let NetLook {
                    premises,
                    conclusions,
                    why_not,
                } = NetLook::default();
                Self {
                    premises,
                    conclusions,
                    why_not,
                }
            }
        }

        /// Reads either form.
        struct Visitor;

        impl<'de> serde::de::Visitor<'de> for Visitor {
            type Value = NetLook;

            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str("a net's premises, conclusions and why_not, or the name of a preset")
            }

            fn visit_str<E: serde::de::Error>(self, name: &str) -> Result<NetLook, E> {
                use serde::Deserialize;
                use serde::de::IntoDeserializer;
                NetPreset::deserialize(name.into_deserializer()).map(NetPreset::look)
            }

            fn visit_map<A: serde::de::MapAccess<'de>>(self, map: A) -> Result<NetLook, A::Error> {
                use serde::Deserialize;
                let Fields {
                    premises,
                    conclusions,
                    why_not,
                } = Fields::deserialize(serde::de::value::MapAccessDeserializer::new(map))?;
                Ok(NetLook {
                    premises,
                    conclusions,
                    why_not,
                })
            }
        }

        deserializer.deserialize_any(Visitor)
    }
}

/// A named [`NetLook`]. In JSON (feature `serialize`) `"deduxit"` or
/// `"textbook"`.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(rename_all = "lowercase"))]
pub enum NetPreset {
    /// [`NetLook::DEDUXIT`]. Read from `"linlog"` too, its name up to
    /// 0.2.0.
    #[default]
    #[cfg_attr(feature = "serialize", serde(alias = "linlog"))]
    Deduxit,
    /// [`NetLook::TEXTBOOK`].
    Textbook,
}

impl NetPreset {
    /// Returns the look the preset names.
    #[must_use]
    pub const fn look(self) -> NetLook {
        match self {
            Self::Deduxit => NetLook::DEDUXIT,
            Self::Textbook => NetLook::TEXTBOOK,
        }
    }
}

/// How the premise edges of a `⅋` or `?` node and the wires of a `?` node
/// are drawn. In JSON (feature `serialize`) `"dashed"` or `"plain"`.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(rename_all = "lowercase"))]
pub enum Premises {
    /// Dashed and in the [`Style::par`] colour, since a switching keeps
    /// one of them.
    #[default]
    Dashed,
    /// As every other edge: solid and in the [`Style::line`] colour.
    Plain,
}

/// Where the conclusions of a net with boxes stand. A net without boxes
/// has them all on the bottom row either way, and so does the compact
/// drawing, which writes each under an edge hanging to the bottom. In
/// JSON (feature `serialize`) `"raised"` or `"bottom"`.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(rename_all = "lowercase"))]
pub enum Conclusions {
    /// On the bottom row, except a `!` with auxiliary doors: it is written
    /// under its door, a row above the `?` nodes its wires go to.
    #[default]
    Raised,
    /// Every one on the bottom row, a `!` with auxiliary doors reached by
    /// an edge down from its door.
    Bottom,
}

/// How a `?` node of a net with boxes is drawn. In JSON (feature
/// `serialize`) `"node"` or `"rules"`.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(rename_all = "lowercase"))]
pub enum WhyNot {
    /// One node whose premises are every copy of its subformula and every
    /// wire from a box. A weakening `?` is a node without premises.
    #[default]
    Node,
    /// The nodes of the sequent calculus's rules:
    /// - a dereliction `?d` under every copy, in the copy's box;
    /// - each copy's wire leaving every box through a door of its own;
    /// - binary contractions `?c` joining them at the `?`'s depth, the
    ///   nearest first;
    /// - a weakening `?w`.
    ///
    /// A lone wire is the conclusion itself, with no node.
    Rules,
}

impl Style {
    /// Returns the style with another [`font`](Self::font).
    #[must_use]
    pub fn with_font(self, font: Font) -> Self {
        Self { font, ..self }
    }

    /// Returns the style with another [`labels`](Self::labels).
    #[must_use]
    pub fn with_labels(self, labels: Labels) -> Self {
        Self { labels, ..self }
    }

    /// Returns the style with another [`open`](Self::open).
    #[must_use]
    pub fn with_open(self, open: OpenGoal) -> Self {
        Self { open, ..self }
    }

    /// Returns the style with another [`ids`](Self::ids).
    #[must_use]
    pub fn with_ids(self, ids: bool) -> Self {
        Self { ids, ..self }
    }

    /// Returns the style with another [`description`](Self::description).
    #[must_use]
    pub fn with_description(self, description: bool) -> Self {
        Self {
            description,
            ..self
        }
    }

    /// Returns the style with another [`font_size`](Self::font_size).
    #[must_use]
    pub fn with_font_size(self, font_size: u32) -> Self {
        Self { font_size, ..self }
    }

    /// Returns the style with another [`label_size`](Self::label_size).
    #[must_use]
    pub fn with_label_size(self, label_size: u32) -> Self {
        Self { label_size, ..self }
    }

    /// Returns the style with another [`line_height`](Self::line_height).
    #[must_use]
    pub fn with_line_height(self, line_height: u32) -> Self {
        Self {
            line_height,
            ..self
        }
    }

    /// Returns the style with another [`premise_gap`](Self::premise_gap).
    #[must_use]
    pub fn with_premise_gap(self, premise_gap: u32) -> Self {
        Self {
            premise_gap,
            ..self
        }
    }

    /// Returns the style with another [`literal_gap`](Self::literal_gap).
    #[must_use]
    pub fn with_literal_gap(self, literal_gap: u32) -> Self {
        Self {
            literal_gap,
            ..self
        }
    }

    /// Returns the style with another [`label_gap`](Self::label_gap).
    #[must_use]
    pub fn with_label_gap(self, label_gap: u32) -> Self {
        Self { label_gap, ..self }
    }

    /// Returns the style with another [`margin`](Self::margin).
    #[must_use]
    pub fn with_margin(self, margin: u32) -> Self {
        Self { margin, ..self }
    }

    /// Returns the style with another [`stroke_width`](Self::stroke_width).
    #[must_use]
    pub fn with_stroke_width(self, stroke_width: u32) -> Self {
        Self {
            stroke_width,
            ..self
        }
    }

    /// Returns the style with another [`link_height`](Self::link_height).
    #[must_use]
    pub fn with_link_height(self, link_height: u32) -> Self {
        Self {
            link_height,
            ..self
        }
    }

    /// Returns the style with another [`link_cap`](Self::link_cap).
    #[must_use]
    pub fn with_link_cap(self, link_cap: Option<u32>) -> Self {
        Self { link_cap, ..self }
    }

    /// Returns the style with another [`node_radius`](Self::node_radius).
    #[must_use]
    pub fn with_node_radius(self, node_radius: u32) -> Self {
        Self {
            node_radius,
            ..self
        }
    }

    /// Returns the style with another [`text`](Self::text).
    #[must_use]
    pub fn with_text(self, text: String) -> Self {
        Self { text, ..self }
    }

    /// Returns the style with another [`line`](Self::line).
    #[must_use]
    pub fn with_line(self, line: String) -> Self {
        Self { line, ..self }
    }

    /// Returns the style with another [`par`](Self::par).
    #[must_use]
    pub fn with_par(self, par: String) -> Self {
        Self { par, ..self }
    }

    /// Returns the style with another [`link`](Self::link).
    #[must_use]
    pub fn with_link(self, link: String) -> Self {
        Self { link, ..self }
    }

    /// Returns the style with another [`highlight`](Self::highlight).
    #[must_use]
    pub fn with_highlight(self, highlight: String) -> Self {
        Self { highlight, ..self }
    }

    /// Returns the style with another [`background`](Self::background).
    #[must_use]
    pub fn with_background(self, background: Option<String>) -> Self {
        Self { background, ..self }
    }

    /// Returns the style with another [`essential`](Self::essential).
    #[must_use]
    pub fn with_essential(self, essential: bool) -> Self {
        Self { essential, ..self }
    }

    /// Returns the style with another [`input`](Self::input).
    #[must_use]
    pub fn with_input(self, input: String) -> Self {
        Self { input, ..self }
    }

    /// Returns the style with another [`dominator`](Self::dominator).
    #[must_use]
    pub fn with_dominator(self, dominator: String) -> Self {
        Self { dominator, ..self }
    }

    /// Returns the style with another [`net`](Self::net).
    #[must_use]
    pub fn with_net(self, net: NetDrawing) -> Self {
        Self { net, ..self }
    }

    /// Returns the style with another [`net_look`](Self::net_look).
    #[must_use]
    pub fn with_net_look(self, net_look: NetLook) -> Self {
        Self { net_look, ..self }
    }

    /// Returns the style with another [`lambda`](Self::lambda).
    #[must_use]
    pub fn with_lambda(self, lambda: Option<crate::lambda::Options>) -> Self {
        Self { lambda, ..self }
    }
}

impl Style {
    /// Returns the default style in light colours on a dark background.
    pub fn dark() -> Self {
        Self {
            text: "#e6e6e6".into(),
            line: "#e6e6e6".into(),
            par: "#56b4e9".into(),
            link: "#e6e6e6".into(),
            highlight: "#e69f00".into(),
            background: Some("#1e1e1e".into()),
            input: "#56b4e9".into(),
            dominator: "#cc79a7".into(),
            ..Self::default()
        }
    }

    /// Returns the default style set in a monospace font
    /// ([`Font::monospace`]).
    pub fn monospace() -> Self {
        Self {
            font: Font::monospace(),
            ..Self::default()
        }
    }

    /// The most a length may be, in thousandths of an em: a thousand ems.
    ///
    /// Under these maxima, an element or a character of a drawing adds at
    /// most a million thousandths of an em to a coordinate. So a drawing
    /// passes `i64` only past 9·10¹² elements, far beyond what memory
    /// holds. The products with a size are taken in `i128`.
    pub const MOST_LENGTH: u32 = 1_000_000;

    /// The most `label_size` and an advance may be, in thousandths of an
    /// em: ten ems.
    pub const MOST_SIZE: u32 = 10_000;

    /// The most `font_size` may be, in pixels.
    pub const MOST_FONT_SIZE: u32 = 10_000;

    /// Checks that every number of the style is within its maximum, so
    /// that no position of a drawing that memory can hold leaves the
    /// integers it is laid out in. Every drawing checks its style first.
    ///
    /// - [`MOST_LENGTH`](Self::MOST_LENGTH) bounds the lengths,
    ///   `link_height` and `link_cap`.
    /// - [`MOST_SIZE`](Self::MOST_SIZE) bounds `label_size` and the font's
    ///   advances.
    /// - [`MOST_FONT_SIZE`](Self::MOST_FONT_SIZE) bounds `font_size`.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidOption`] naming the first key past its maximum.
    pub fn check(&self) -> Result<(), Error> {
        let advances: u32 = match &self.font.advances {
            // The committed tables are within the bound (`font.rs`).
            Advances::Euler
            | Advances::StixTwo
            | Advances::Garamond
            | Advances::Asana
            | Advances::NewComputerModern => 0,
            Advances::Fixed(advance) => *advance,
            Advances::Table { table, fallback } => {
                table.values().copied().fold(*fallback, u32::max)
            }
        };
        let numbers = [
            ("svg.font_size", self.font_size, Self::MOST_FONT_SIZE),
            ("svg.label_size", self.label_size, Self::MOST_SIZE),
            ("svg.font.advances", advances, Self::MOST_SIZE),
            ("svg.line_height", self.line_height, Self::MOST_LENGTH),
            ("svg.premise_gap", self.premise_gap, Self::MOST_LENGTH),
            ("svg.literal_gap", self.literal_gap, Self::MOST_LENGTH),
            ("svg.label_gap", self.label_gap, Self::MOST_LENGTH),
            ("svg.margin", self.margin, Self::MOST_LENGTH),
            ("svg.stroke_width", self.stroke_width, Self::MOST_LENGTH),
            ("svg.link_height", self.link_height, Self::MOST_LENGTH),
            (
                "svg.link_cap",
                self.link_cap.unwrap_or(0),
                Self::MOST_LENGTH,
            ),
            ("svg.node_radius", self.node_radius, Self::MOST_LENGTH),
        ];
        match numbers.into_iter().find(|&(_, value, most)| value > most) {
            Some((key, value, most)) => Err(Error::InvalidOption {
                key,
                message: format!("{value} is more than the most it may be, {most}"),
            }),
            None => Ok(()),
        }
    }
}

/// The characters that open and close a formula of a sequent in the text
/// the notation writes, which [`run`] makes pieces of their own.
const FORMULA: (char, char) = ('\u{2}', '\u{3}');

/// The characters that open and close a subscript of a rule's label in
/// the text [`label`] writes.
const SUBSCRIPT: (char, char) = ('\u{4}', '\u{5}');

/// The characters that open and close a superscript, in a label or a
/// sequent: the marks of a discharged hypothesis, `[A]¹`, and of the rule
/// that discharges it.
pub(crate) const SUPERSCRIPT: (char, char) = ('\u{6}', '\u{f}');

/// Writes a label's markup as text for [`run`]: symbols and text as they
/// are, a subscript between the [`SUBSCRIPT`] marks, a superscript
/// between the [`SUPERSCRIPT`] marks.
fn label(markup: &str) -> String {
    let mut out = String::new();
    for part in parts(markup) {
        match part {
            Part::Symbol(c) => out.push(c),
            Part::Text(text) => out.push_str(text),
            Part::Sub(text) => {
                out.push(SUBSCRIPT.0);
                out.push_str(text);
                out.push(SUBSCRIPT.1);
            }
            Part::Sup(text) => {
                out.push(SUPERSCRIPT.0);
                out.push_str(text);
                out.push(SUPERSCRIPT.1);
            }
        }
    }
    out
}

/// The character that stands for the raised `⊥` of a negated atom in the
/// text the notation writes, a control character that no atom name keeps.
const RAISED_BOT: char = '\u{1}';

/// The spelling of formulas and sequents as they are drawn: Unicode
/// connectives and mathematical italic letters, which [`run`] lays out.
const NOTATION: Notation = Notation {
    tensor: "⊗",
    par: "⅋",
    with: "&",
    plus: "⊕",
    lollipop: "⊸",
    under: "\\",
    over: "/",
    bang: "!",
    quest: "?",
    one: "1",
    bot: "⊥",
    top: "⊤",
    zero: "0",
    dual_prefix: "",
    dual: "\u{1}",
    turnstile: "⊢",
    align: "",
    atom: Atoms::Italic,
    forall: "∀",
    exists: "∃",
    dot: ". ",
    ordinary: Symbols::UNICODE,
};

/// The spelling of formulas and sequents in a drawing's title: plain
/// Unicode text.
const PLAIN: Notation = Notation {
    dual: "⊥",
    atom: Atoms::Plain,
    ..NOTATION
};

/// Writes the first sentence of a net's description: the sequent it
/// concludes, in the title's notation.
fn net_conclusion(
    out: &mut impl Write,
    forest: &crate::linear::Forest,
    reading: Option<&Reading<'_>>,
) -> std::fmt::Result {
    out.write_str("It concludes ")?;
    match reading {
        Some(reading) => PLAIN.reading(out, reading)?,
        None => PLAIN.one_sided(out, forest.sequent())?,
    }
    out.write_char('.')
}

/// Writes `formula N, F` for a net's description, or `Formula N, F` to
/// start a sentence: the vertex's number, as the net's text form numbers
/// it, and its formula in the title's notation.
fn net_formula(
    out: &mut impl Write,
    noun: &str,
    number: u32,
    forest: &crate::linear::Forest,
    reading: Option<&Reading<'_>>,
    o: crate::linear::OccId,
) -> std::fmt::Result {
    write!(out, "{noun} {number}, ")?;
    match reading {
        Some(reading) => PLAIN.ill(out, reading, o, false),
        None => PLAIN.term(out, forest.sequent(), forest.term(o), false),
    }
}

/// Writes the sentence of a net's description for one link: `An axiom
/// link joins formula 1, A⊥, and formula 5, A.`, or for a cut link `A cut
/// link joins …`.
fn net_link(
    out: &mut impl Write,
    cut: bool,
    ends: [(u32, crate::linear::OccId); 2],
    forest: &crate::linear::Forest,
    reading: Option<&Reading<'_>>,
) -> std::fmt::Result {
    out.write_str(if cut {
        "\nA cut link joins "
    } else {
        "\nAn axiom link joins "
    })?;
    net_formula(out, "formula", ends[0].0, forest, reading, ends[0].1)?;
    out.write_str(", and ")?;
    net_formula(out, "formula", ends[1].0, forest, reading, ends[1].1)?;
    out.write_char('.')
}

/// Writes the last sentence of a net's description: whether the
/// structure is a proof net under `criterion`, or the `reason` it is not.
fn net_verdict(
    out: &mut impl Write,
    criterion: crate::linear::Criterion,
    reason: Option<&dyn std::fmt::Display>,
) -> std::fmt::Result {
    match reason {
        Some(reason) => write!(out, "\nIt is not a proof net: {reason}."),
        None if criterion.mix => {
            out.write_str("\nIt is a proof net with Mix: the correctness criterion with Mix holds.")
        }
        None if criterion.order != crate::linear::Order::Commutative => out.write_str(
            "\nIt is a planar proof net: the correctness criterion holds, and no two links \
             cross.",
        ),
        None => out.write_str("\nIt is a proof net: the correctness criterion holds."),
    }
}

/// Writes an atom's name with its Latin letters as mathematical italic
/// characters. A name is an identifier, so it holds none of the control
/// characters the layout marks its text with.
pub(crate) fn italic<W: Write + ?Sized>(out: &mut W, name: &str) -> std::fmt::Result {
    for c in name.chars() {
        out.write_char(match c {
            'h' => 'ℎ',
            'A'..='Z' => char::from_u32(0x1D434 + (c as u32 - 'A' as u32)).unwrap(),
            'a'..='z' => char::from_u32(0x1D44E + (c as u32 - 'a' as u32)).unwrap(),
            c => c,
        })?;
    }
    Ok(())
}

/// Writes a character escaped for XML text and attribute values. A
/// character that XML 1.0 cannot carry (a control character other than
/// tab, line feed and carriage return, U+FFFE, U+FFFF) becomes `�`. This
/// is the one place text enters a drawing, so no string of a style or a
/// label table can make the document invalid XML.
fn escape(out: &mut String, c: char) {
    match c {
        '&' => out.push_str("&amp;"),
        '<' => out.push_str("&lt;"),
        '>' => out.push_str("&gt;"),
        '"' => out.push_str("&quot;"),
        '\t' | '\n' | '\r' => out.push(c),
        '\0'..='\u{1F}' | '\u{FFFE}' | '\u{FFFF}' => out.push('\u{FFFD}'),
        c => out.push(c),
    }
}

/// Returns a text escaped for XML.
fn escaped(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    text.chars().for_each(|c| escape(&mut out, c));
    out
}

/// A piece of a line of text on one baseline and at one size, which is
/// one `<text>` element: renderers disagree on how `textLength` spreads
/// over a `<tspan>` that shifts the baseline, and agree on a text of its
/// own.
#[derive(Clone, Debug, Default)]
struct Piece {
    /// The escaped text, without spaces at either end.
    text: String,
    /// Where the piece starts, from the start of the line.
    offset: i64,
    /// How far its baseline is above the line's.
    raise: i64,
    /// Its font size, or none for the line's.
    size: Option<i64>,
    /// Its width.
    width: i64,
    /// The formula of the sequent it belongs to, counted in the order of
    /// the text, or none.
    formula: Option<usize>,
}

/// A line of text laid out, in thousandths of an em of formula text.
#[derive(Clone, Debug, Default)]
struct Run {
    /// The pieces, left to right.
    pieces: Vec<Piece>,
    /// The width.
    width: i64,
}

/// Lays out a line the notation or a rule's label wrote, at `size`
/// thousandths of an em in the font, as [`lay`] does, and returns its
/// pieces with its width.
fn run(text: &str, size: i64, font: &Font) -> Run {
    let mut pieces = Vec::new();
    let width = lay(text, size, font, |piece| pieces.push(piece));
    Run { pieces, width }
}

/// Lays out a line the notation or a rule's label wrote, at `size`
/// thousandths of an em in the font. Hands `emit` its pieces from left to
/// right, and returns its width.
///
/// [`RAISED_BOT`] becomes a superscript `⊥`, the text between the
/// [`SUBSCRIPT`] marks a subscript, the text between the [`SUPERSCRIPT`]
/// marks a superscript, and the text between the [`FORMULA`]
/// marks pieces of that formula. A space separates two pieces and never
/// starts or ends one.
fn lay(text: &str, size: i64, font: &Font, mut emit: impl FnMut(Piece)) -> i64 {
    // Widths in millionths of an em of `size`, which `scale` turns into
    // thousandths of an em of formula text; the product of a long line's
    // width and a large size passes `i64`, the quotient does not, and only
    // such a product is divided in `i128`, which is a call.
    let scale = |millionths: i64| match millionths.checked_mul(size) {
        Some(product) => product / 1_000_000,
        None => {
            let scaled = i128::from(millionths) * i128::from(size) / 1_000_000;
            i64::try_from(scaled).unwrap_or(i64::MAX)
        }
    };
    let (mut position, mut start, mut end) = (0, 0, 0);
    let mut current = (0, 1000);
    let (mut lowered, mut raised, mut formula, mut formulas) = (false, false, None, 0);
    let mut piece = String::new();
    let mut close = |piece: &mut String, shape: (i64, i64), formula, start, end| {
        piece.truncate(piece.trim_end_matches(' ').len());
        if !piece.is_empty() {
            emit(Piece {
                text: std::mem::take(piece),
                offset: scale(start),
                raise: shape.0,
                size: (shape.1 != 1000).then_some(size * shape.1 / 1000),
                width: scale(end) - scale(start),
                formula,
            });
        }
    };
    for c in text.chars() {
        if c == FORMULA.0 || c == FORMULA.1 {
            close(&mut piece, current, formula, start, end);
            formula = (c == FORMULA.0).then_some(formulas);
            formulas += usize::from(c == FORMULA.0);
            continue;
        }
        if c == SUBSCRIPT.0 || c == SUBSCRIPT.1 {
            lowered = c == SUBSCRIPT.0;
            continue;
        }
        if c == SUPERSCRIPT.0 || c == SUPERSCRIPT.1 {
            raised = c == SUPERSCRIPT.0;
            continue;
        }
        let (c, shape) = match c {
            RAISED_BOT => ('⊥', (RAISE * size / 1000, SCRIPT)),
            c if lowered => (c, (-LOWER * size / 1000, SCRIPT)),
            c if raised => (c, (RAISE * size / 1000, SCRIPT)),
            c => (c, (0, 1000)),
        };
        if shape != current {
            close(&mut piece, current, formula, start, end);
            current = shape;
        }
        let advance = i64::from(font.advances.advance(c)) * shape.1;
        if c == ' ' {
            if !piece.is_empty() {
                piece.push(' ');
            }
            position += advance;
            continue;
        }
        if piece.is_empty() {
            start = position;
        }
        position += advance;
        end = position;
        escape(&mut piece, c);
    }
    close(&mut piece, current, formula, start, end);
    scale(position)
}

/// Writes a line of text with its left end at `x` and its baseline at
/// `y`. Every piece is a `<text>`, stretched or squeezed to the width the
/// layout gave it. `attributes` go as they are into the start tag of the
/// one `<text>`, or of the group of several. With `ids` (the id of an
/// inference's conclusion and the positions of its formulas in the order
/// written), the line is a group and every formula a group in it.
fn text(
    out: &mut String,
    x: i64,
    y: i64,
    run: &Run,
    attributes: &str,
    ids: Option<(u32, &[usize])>,
) {
    let group = run.pieces.len() > 1 || ids.is_some();
    if group {
        writeln!(out, "<g{attributes}>").unwrap();
    }
    let mut open = None;
    for piece in &run.pieces {
        if let Some((id, positions)) = ids
            && piece.formula != open
        {
            if open.is_some() {
                out.push_str("</g>\n");
            }
            if let Some(k) = piece.formula {
                writeln!(out, r#"<g id="i{id}-{}">"#, positions[k]).unwrap();
            }
            open = piece.formula;
        }
        write_piece(out, x, y, piece, if group { "" } else { attributes });
    }
    if open.is_some() {
        out.push_str("</g>\n");
    }
    if group {
        out.push_str("</g>\n");
    }
}

/// Writes a piece of a line whose left end is at `x` and whose baseline
/// is at `y` as a `<text>` with `attributes` in its start tag.
fn write_piece(out: &mut String, x: i64, y: i64, piece: &Piece, attributes: &str) {
    write!(
        out,
        r#"<text x="{}" y="{}" textLength="{}" lengthAdjust="spacing""#,
        x + piece.offset,
        y - piece.raise,
        piece.width
    )
    .unwrap();
    if let Some(size) = piece.size {
        write!(out, r#" font-size="{size}""#).unwrap();
    }
    out.push_str(attributes);
    writeln!(out, ">{}</text>", piece.text).unwrap();
}

/// Returns thousandths as a decimal number, without trailing zeros.
fn decimal(thousandths: i128) -> String {
    let sign = if thousandths < 0 { "-" } else { "" };
    let magnitude = thousandths.unsigned_abs();
    let text = format!("{sign}{}.{:03}", magnitude / 1000, magnitude % 1000);
    text.trim_end_matches('0').trim_end_matches('.').to_owned()
}

/// Writes the start of an SVG document of `width` by `height`
/// thousandths of an em with the given title, in the style's font and
/// colours, up to where its description goes. The document is one image
/// (`role="img"`), and its title is its accessible name.
fn head(out: &mut impl Write, style: &Style, title: &str, size: (i64, i64)) -> std::fmt::Result {
    let (width, height) = size;
    let px = |length: i64| decimal(i128::from(length) * i128::from(style.font_size));
    write!(
        out,
        r#"<svg xmlns="http://www.w3.org/2000/svg" role="img" width="{}" height="{}" viewBox="0 0 {width} {height}" font-family="{}" font-size="1000" fill="{}">"#,
        px(width),
        px(height),
        escaped(&style.font.family),
        escaped(&style.text),
    )?;
    write!(out, "\n<title>{}</title>\n", escaped(title))
}

/// A writer that escapes what it passes on for XML text.
struct Escaping<'a, W>(&'a mut W);

impl<W: Write> Write for Escaping<'_, W> {
    fn write_str(&mut self, s: &str) -> std::fmt::Result {
        let mut text = String::with_capacity(s.len());
        s.chars().for_each(|c| escape(&mut text, c));
        self.0.write_str(&text)
    }
}

/// Writes the background of a document of `width` by `height`
/// thousandths of an em, if the style has one: what comes after the head
/// and the description.
fn backdrop(out: &mut impl Write, style: &Style, size: (i64, i64)) -> std::fmt::Result {
    let (width, height) = size;
    if let Some(background) = &style.background {
        writeln!(
            out,
            r#"<rect width="{width}" height="{height}" fill="{}"/>"#,
            escaped(background)
        )?;
    }
    Ok(())
}

/// Returns an SVG document of `width` by `height` thousandths of an em
/// with the given title and description, in the style's font and
/// colours. `body` writes the body into the document itself, so that no
/// body is held apart and copied.
fn document(
    style: &Style,
    title: &str,
    description: Option<&str>,
    size: (i64, i64),
    body: impl FnOnce(&mut String),
) -> String {
    let mut out = String::new();
    head(&mut out, style, title, size).unwrap();
    if let Some(description) = description {
        writeln!(out, "<desc>{}</desc>", escaped(description)).unwrap();
    }
    backdrop(&mut out, style, size).unwrap();
    body(&mut out);
    out.push_str("</svg>");
    out
}

/// Returns a document that shows one line of text, the notation's `content`,
/// titled `title`.
///
/// The line is laid out twice: once for its width, which the head needs,
/// and once to write its pieces into the document one by one. So no list
/// of pieces is held, and a line of millions of occurrences takes the
/// memory of the document and its text alone. The pieces are written as
/// [`text`] writes them.
fn line(style: &Style, title: &str, content: &str) -> String {
    let margin = i64::from(style.margin);
    let mut pieces = 0usize;
    let width = lay(content, 1000, &style.font, |_| pieces += 1);
    let size = (width + 2 * margin, HEIGHT + DEPTH + 2 * margin);
    document(style, title, None, size, |out| {
        let group = pieces > 1;
        if group {
            out.push_str("<g>\n");
        }
        lay(content, 1000, &style.font, |piece| {
            write_piece(out, margin, margin + HEIGHT, &piece, "");
        });
        if group {
            out.push_str("</g>\n");
        }
    })
}

/// The bytes a sequent's drawing is estimated at per occurrence, besides
/// the longest atom name: at least what any connective, its brackets and
/// its separator take.
const PER_OCCURRENCE: u64 = 128;

/// Returns a sequent as an SVG document of one line of text, titled with
/// the sequent in plain text. The sequent is one-sided, `⊢ A⊥, A`, or in
/// an intuitionistic mode two-sided by its reading, `A ⊢ A`.
///
/// # Errors
///
/// - [`Refusal::Output`](crate::Refusal::Output) for a sequent whose text
///   is estimated past `limits.derivation_bytes`, before anything is laid
///   out. The estimate is, per occurrence, 128 bytes plus the length of
///   the longest atom name.
/// - In an intuitionistic mode, [`Error::NotIntuitionistic`] for a sequent
///   without an intuitionistic reading, and the refusal of
///   [`Forest::within`](crate::linear::Forest::within).
/// - [`Error::InvalidOption`] for a style [`Style::check`] refuses.
pub fn sequent(
    sequent: &Sequent,
    mode: crate::linear::Mode,
    style: &Style,
    limits: &crate::Limits,
) -> Result<String, Error> {
    style.check()?;
    Ok(
        match super::printed(sequent, mode, PER_OCCURRENCE, limits)? {
            None => one_sided(sequent, style),
            Some(forest) => {
                let reading = Reading::of_mode(&forest, mode).map_err(Error::NotIntuitionistic)?;
                two_sided(&reading, style)
            }
        },
    )
}

/// Returns a sequent one-sided, `⊢ A⊥, A`, as an SVG document of one line
/// of text, titled with the sequent in plain text.
fn one_sided(sequent: &Sequent, style: &Style) -> String {
    let (mut drawn, mut title) = (String::new(), String::new());
    NOTATION.one_sided(&mut drawn, sequent).unwrap();
    PLAIN.one_sided(&mut title, sequent).unwrap();
    line(style, &title, &drawn)
}

/// Returns the sequent of an intuitionistic reading two-sided,
/// `A, A ⊸ B ⊢ B`, as an SVG document of one line of text, titled with
/// the sequent in plain text.
fn two_sided(reading: &Reading, style: &Style) -> String {
    let forest = reading.forest();
    let (mut drawn, mut title) = (String::new(), String::new());
    NOTATION
        .sequent(
            &mut drawn,
            forest,
            Some(reading),
            None,
            &forest.root_members(),
            false,
            false,
        )
        .unwrap();
    PLAIN
        .sequent(
            &mut title,
            forest,
            Some(reading),
            None,
            &forest.root_members(),
            false,
            false,
        )
        .unwrap();
    line(style, &title, &drawn)
}

/// Writes a derivation into `out` as an SVG document of its proof tree,
/// titled with its conclusion in plain text. Use it to write into your
/// own buffer, or to stop a large drawing; [`to_string`] returns the
/// document whole.
///
/// It writes the elements of one inference at a time and asks `stop`
/// after each. Besides that, it holds a few numbers per inference.
///
/// The tree grows upwards from its conclusion:
/// - The premises of an inference stand side by side, their conclusions
///   centred over its own, under an inference line that spans both, with
///   the rule's name to its right.
/// - An open goal of a proof in progress is its sequent under vertical
///   dots, with no inference line, unless [`Style::open`] says otherwise.
/// - The conclusion of inference `n` is the `<text>` or the group with the
///   id `i<n>`. With [`Style::ids`], its formula at position `p` is the
///   group `i<n>-<p>`, hypotheses first.
///
/// The layout is one pass up the tree and one down, each with a stack of
/// its own. So a derivation of any height fits, and drawing it again
/// after every step of an interactive proof stays cheap.
///
/// A linear derivation is drawn two-sided if it is two-sided. A
/// derivation of LK or LJ is drawn two-sided:
/// - its connectives and constants are the Unicode characters
///   `¬ ∧ ∨ → ↔ ⊤ ⊥`;
/// - its labels are those of [`ordinary::Rule`](crate::ordinary::Rule),
///   and stay upright under a [`Labels::Table`], which is keyed by the
///   linear rules;
/// - its `<desc>` lists its numbered inferences.
///
/// # Errors
///
/// - [`Refusal::Stopped`](crate::Refusal::Stopped) when `stop` fired.
/// - [`Error::WriteFailed`] when `out` refused the text.
/// - [`Error::InvalidOption`] for a style [`Style::check`] refuses, before
///   anything is written.
/// - With [`Style::lambda`], [`Error::NoTerm`] for a derivation without a
///   term, [`Error::ReadBack`] for a derivation of LJ read from JSON that
///   its [`check`](crate::ordinary::Derivation::check) refuses, and the
///   refusal of a term past the output bound, before anything is
///   written.
pub fn write<'a>(
    derivation: impl Into<Drawable<'a>>,
    style: &Style,
    out: &mut impl Write,
    stop: impl FnMut(crate::limits::Progress) -> bool,
) -> Result<(), Error> {
    style.check()?;
    let mut stop = stop;
    let drawable = derivation.into();
    let judgement = super::judgement(
        drawable,
        style.lambda.as_ref(),
        &crate::lambda::print::SVG,
        &mut stop,
    )?;
    let judgement = judgement.as_deref();
    let stop = crate::limits::counting(stop, crate::limits::Phase::Write);
    match drawable {
        Drawable::Linear(derivation) => tree::draw(derivation, style, judgement, out, stop),
        Drawable::Ordinary(derivation) => tree::draw(derivation, style, judgement, out, stop),
        Drawable::Classical(view) => tree::draw(view, style, judgement, out, stop),
        #[cfg(feature = "serialize")]
        Drawable::Rules(drawing) => tree::draw(drawing, style, judgement, out, stop),
        #[cfg(feature = "serialize")]
        Drawable::Fitch(proof) => fitch::draw(proof, style, out, stop),
    }
}

/// Returns a derivation as an SVG document of its proof tree, drawn as
/// [`write()`] draws it. This is the common way to draw a proof: pass it
/// [`Proof::derivation`](crate::linear::Proof::derivation).
///
/// It takes no stop and no limits. The text grows linearly with the
/// derivation, which was made within its own limits
/// ([`Proof::derivation`](crate::linear::Proof::derivation) uses the
/// default ones), and a lambda-term written under it is bounded by the
/// default [`Limits`](crate::Limits).
///
/// # Errors
///
/// As [`write()`] answers, except
/// [`Refusal::Stopped`](crate::Refusal::Stopped) and
/// [`Error::WriteFailed`], which a `String` and a stop that never fires
/// never give.
pub fn to_string<'a>(derivation: impl Into<Drawable<'a>>, style: &Style) -> Result<String, Error> {
    let mut out = String::new();
    write(derivation, style, &mut out, |_| false)?;
    Ok(out)
}

/// Returns a proof structure as an SVG document, titled with its sequent
/// in plain text. The structure may be a proof net or not, complete or
/// not; [`ProofStructure::from_proof`] makes the net of a proof.
///
/// The conclusions stand in a row at the bottom, in the sequent's order.
/// The formula trees grow upwards from them to the literals, which stand
/// side by side along the top, each axiom link an arc over the two it
/// joins. A literal that is a conclusion stands at the bottom, its link's
/// arc reaching down to it. [`Style::net`] says how much is written:
/// - [`NetDrawing::Formulas`], the default: every subformula is written as
///   its formula, where it stands in its conclusion's text, and the link
///   of a `⊗` or `⅋` joins its two premises to it, with the connective
///   small at the joint.
/// - [`NetDrawing::Compact`]: only the literals and the conclusions are
///   written, and every inner `⊗` and `⅋` is a small labelled circle.
///
/// Under the default look, the edges to the two premises of a `⅋` are
/// dashed and have a colour of their own, since a switching keeps one of
/// them ([`Style::par`]). Mix leaves no trace. A cut link is a bar under
/// its two formulas, as the literature draws one; the two stand at the
/// bottom after the conclusions.
///
/// The drawing shows what the correctness criterion finds, in the
/// [`highlight`](Style::highlight) colour: the edges of a switching
/// cycle, or, for a structure that falls into parts (those of
/// [`NetError::Disconnected`](crate::linear::nets::NetError::Disconnected)),
/// the edges, conclusions and links of every part but the first.
///
/// With [`Style::essential`], a structure of an intuitionistic sequent is
/// drawn as its essential net instead, which the field describes, its
/// highlights those of [`ProofStructure::is_essential`].
///
/// The ids, for a page that styles or points to parts of the drawing:
/// - `o<n>`: the formula of occurrence `n`, or its circle in a compact
///   net;
/// - `l<m>-<n>`: the axiom link between occurrences `m` and `n`;
/// - `c<x>-<y>`: a cut link, its end in a cut formula's tree first.
///
/// A drawing estimated past `limits.derivation_bytes` is not drawn, as a
/// derivation past it is not built. The estimate counts every literal,
/// connective, conclusion and link from the structure, and is at least
/// the size of the drawing. The criterion that decides the highlights
/// asks `stop` as [`ProofStructure::is_correct`] does.
///
/// # Errors
///
/// - [`Refusal::Output`](crate::Refusal::Output) past the bound, before
///   anything is drawn.
/// - The criterion's refusal when `stop` fired.
/// - [`Error::InvalidOption`] for a style [`Style::check`] refuses.
pub fn net(
    net: &ProofStructure,
    style: &Style,
    limits: &crate::Limits,
    stop: impl FnMut(crate::limits::Progress) -> bool,
) -> Result<String, Error> {
    net_marked(net, &Marks::default(), style, limits, stop)
}

/// Returns a proof net as [`net()`] draws it, with what a step of cut
/// elimination taken on it acts on in the highlight colour. That is the
/// cut link it reduces and, by the step's case, the two axiom links at
/// the cut's ends or the premise edges of its `⊗` and `⅋`.
///
/// # Errors
///
/// As [`net()`] fails.
pub fn net_step(
    net: &ProofStructure,
    step: &crate::linear::nets::cut::Step,
    style: &Style,
    limits: &crate::Limits,
    stop: impl FnMut(crate::limits::Progress) -> bool,
) -> Result<String, Error> {
    net_marked(net, &Marks::of_mll(net, step), style, limits, stop)
}

/// Draws a proof structure with `marks` highlighted.
fn net_marked(
    net: &ProofStructure,
    marks: &Marks,
    style: &Style,
    limits: &crate::Limits,
    stop: impl FnMut(crate::limits::Progress) -> bool,
) -> Result<String, Error> {
    style.check()?;
    // A structure with cut links is drawn under the reading too, its cut
    // formula's tree an output one and its dual's an input one, so that an
    // intuitionistic net is written in the intuitionistic syntax at every
    // step of an elimination.
    let reading = net.reading().ok().filter(|_| style.essential);
    let drawn = within(limits, || net::estimate(net, style, reading.is_some()))?;
    let mut stop = stop;
    let verdict = match &reading {
        Some(_) => net.is_essential(&mut stop),
        None => net.is_correct(&mut stop),
    };
    refused(&verdict)?;
    // The description states the switching criterion's verdict, which
    // the essential one is not: that one does not test planarity.
    let own = (reading.is_some() && style.description).then(|| net.is_correct(&mut stop));
    if let Some(own) = &own {
        refused(own)?;
    }
    let described = own.as_ref().unwrap_or(&verdict);
    if style.description {
        described_within(drawn, |most| {
            net::described_bytes(net, described, reading.as_ref(), most)
        })?;
    }
    Ok(net::draw(
        net,
        style,
        &verdict,
        described,
        reading.as_ref(),
        marks,
    ))
}

/// Returns a proof structure with `!`-boxes as an SVG document, drawn as
/// [`net()`] draws a proof structure: every subformula written, or with
/// [`NetDrawing::Compact`] the literals and the conclusions alone.
///
/// Every `!`-box is a rectangle around its contents, and nested boxes are
/// nested. On its bottom border stand its `!` vertex and its auxiliary
/// doors, where wires leave the box: a door for every `?` vertex outside
/// the box with a copy inside it, or under [`WhyNot::Rules`] a door for
/// every copy. Under the default look, the wires of a `?` vertex are
/// dashed as a `⅋`'s premise edges are. A cut link is a bar under its two
/// formulas, at the bottom after the conclusions or, inside a box, in it
/// beside the box's premise. A switching cycle is in the highlight colour.
///
/// With [`Style::essential`], a structure of an intuitionistic sequent is
/// drawn as its essential net, as [`net()`] draws one, with its boxes and
/// the wires of a hypothesis `!A` led up into its copies. Its highlight is
/// still the switching cycle, which decides it.
///
/// The ids:
/// - `o<n>`: the formula of occurrence `n`, when it is the occurrence's
///   only vertex;
/// - `v<k>`: the formula of vertex `k`, when its occurrence has several;
/// - `l<x>-<y>`: a link, by its vertices;
/// - `b<k>`: the outline of a box, by its `!` vertex;
/// - `c<x>-<y>`: a cut link, its end in a cut formula's tree first.
///
/// A drawing estimated past `limits.derivation_bytes` is not drawn, as
/// with [`net()`]. The criterion that decides the highlight asks `stop` as
/// [`MellStructure::is_correct`] does.
///
/// # Errors
///
/// - [`Refusal::Output`](crate::Refusal::Output) past the bound, before
///   anything is drawn.
/// - The criterion's refusal when `stop` fired.
/// - [`Error::InvalidOption`] for a style [`Style::check`] refuses.
pub fn mell_net(
    net: &MellStructure,
    style: &Style,
    limits: &crate::Limits,
    stop: impl FnMut(crate::limits::Progress) -> bool,
) -> Result<String, Error> {
    mell_net_marked(net, &Marks::default(), style, limits, stop)
}

/// Returns a proof net with boxes as [`mell_net()`] draws it, with what a
/// step of cut elimination taken on it acts on in the highlight colour.
/// That is the cut link it reduces and, by the step's case, one of:
/// - the two axiom links at the cut's ends;
/// - the premise edges of its `⊗` and `⅋`;
/// - the box of its `!` end, with the box it enters or the edge to the
///   copy it cuts against.
///
/// # Errors
///
/// As [`mell_net()`] fails.
pub fn mell_net_step(
    net: &MellStructure,
    step: &crate::linear::nets::cut::Step,
    style: &Style,
    limits: &crate::Limits,
    stop: impl FnMut(crate::limits::Progress) -> bool,
) -> Result<String, Error> {
    mell_net_marked(net, &Marks::of_mell(net, step), style, limits, stop)
}

/// Draws a proof structure with boxes with `marks` highlighted.
fn mell_net_marked(
    net: &MellStructure,
    marks: &Marks,
    style: &Style,
    limits: &crate::Limits,
    stop: impl FnMut(crate::limits::Progress) -> bool,
) -> Result<String, Error> {
    style.check()?;
    let reading = net.reading().ok().filter(|_| style.essential);
    let drawn = within(limits, || mell::estimate(net, style, reading.is_some()))?;
    let verdict = net.is_correct(stop);
    refused(&verdict)?;
    if style.description {
        described_within(drawn, |most| {
            mell::described_bytes(net, &verdict, reading.as_ref(), most)
        })?;
    }
    Ok(mell::draw(net, style, &verdict, reading.as_ref(), marks))
}

/// Returns the bound on a net's drawing and the bytes `estimate` gives
/// for it, or the refusal when they pass it; `None` without a bound. The
/// estimate is asked before the criterion runs, so a drawing too large
/// is refused at once.
fn within(
    limits: &crate::Limits,
    estimate: impl FnOnce() -> u64,
) -> Result<Option<(u64, u64)>, Error> {
    let Some(limit) = limits.derivation_bytes else {
        return Ok(None);
    };
    let bytes = estimate();
    if bytes > limit {
        return Err(too_large(bytes, limit));
    }
    Ok(Some((limit, bytes)))
}

/// Refuses a net's drawing whose description, counted by `described`
/// within what the bound leaves, takes it past the bound of `drawn`.
fn described_within(
    drawn: Option<(u64, u64)>,
    described: impl FnOnce(u64) -> u64,
) -> Result<(), Error> {
    let Some((limit, bytes)) = drawn else {
        return Ok(());
    };
    let total = bytes.saturating_add(described(limit - bytes));
    match total > limit {
        true => Err(too_large(total, limit)),
        false => Ok(()),
    }
}

/// Returns the refusal of a drawing estimated at `estimate` bytes, past
/// the bound `limit`.
const fn too_large(estimate: u64, limit: u64) -> Error {
    Error::Refused(crate::limits::Refusal::Output {
        what: "drawing",
        estimate_bytes: estimate,
        limit_bytes: limit,
        least_bytes: None,
    })
}

/// Returns a Kripke countermodel of an ordinary sequent as an SVG
/// document, after checking it in `logic` under `limits`: each world a
/// box with the atoms it forces (and `⊥` in minimal logic), its number
/// `wₙ` beside it, an arrow up to each world directly above it, and the
/// model's world, where the sequent fails, outlined in the
/// [`highlight`](Style::highlight) colour. Its title names the sequent,
/// and with [`Style::description`] a `<desc>` reads each world and says
/// why the sequent fails at the model's world.
///
/// # Examples
///
#[cfg_attr(all(feature = "parse", feature = "sat"), doc = "```")]
#[cfg_attr(not(all(feature = "parse", feature = "sat")), doc = "```ignore")]
/// use deduxit::Limits;
/// use deduxit::export::svg::{self, Style};
/// use deduxit::ordinary::{Logic, Options, Sequent, decide};
///
/// let sequent: Sequent = "|- a \\/ ~a".parse()?;
/// let outcome = decide(&sequent, &Options::default().with_logic(Logic::Intuitionistic))?;
/// let countermodel = outcome.countermodel.expect("a countermodel");
/// let svg = svg::countermodel(
///     &countermodel,
///     Logic::Intuitionistic,
///     &Style::default(),
///     &Limits::default(),
///     |_| false,
/// )?;
/// assert!(svg.contains("<title>A countermodel of ⊢ a ∨ ¬a</title>"));
/// # Ok::<(), deduxit::Error>(())
/// ```
///
/// # Errors
///
/// - The errors of [`Countermodel::check`](crate::ordinary::Countermodel::check):
///   a model that does not refute the sequent in `logic`, a refusal by
///   `limits` or `stop`.
/// - [`Refusal::Output`](crate::Refusal::Output) for a drawing estimated
///   past `limits.derivation_bytes`, before anything is laid out.
/// - [`Refusal::Stopped`](crate::Refusal::Stopped) where `stop` asked,
///   once per world.
/// - [`Error::InvalidOption`] for a style [`Style::check`] refuses.
pub fn countermodel(
    countermodel: &crate::ordinary::Countermodel,
    logic: crate::ordinary::Logic,
    style: &Style,
    limits: &crate::Limits,
    mut stop: impl FnMut(crate::limits::Progress) -> bool,
) -> Result<String, Error> {
    use crate::ordinary::{Logic, Node, NodeId};
    countermodel.check(logic, limits, &mut stop)?;
    let sequent = &countermodel.sequent;
    // The sequent's text, bottom up over its arena, before it is written:
    // a shared formula is written each time it occurs.
    within(limits, || {
        let formulas = sequent.formulas();
        let mut bytes: Vec<u64> = Vec::with_capacity(formulas.len());
        for &node in formulas.nodes() {
            let of = |k: NodeId| bytes[k.index()];
            let b = match node {
                Node::Atom(a) => (formulas.atom_names()[a as usize].len() as u64).saturating_add(2),
                Node::True | Node::False => 3,
                Node::Not(a) => of(a).saturating_add(4),
                Node::And(a, b) | Node::Or(a, b) | Node::Implies(a, b) | Node::Iff(a, b) => {
                    of(a).saturating_add(of(b)).saturating_add(9)
                }
            };
            bytes.push(b);
        }
        // Written twice, in the title and the description, and escaped.
        sequent
            .left()
            .iter()
            .chain(sequent.right())
            .fold(0u64, |sum, id| sum.saturating_add(bytes[id.index()]))
            .saturating_mul(12)
    })?;
    let title = format!("A countermodel of {sequent}");
    let w = countermodel.model.world;
    let last = match (logic, sequent.right().is_empty()) {
        (Logic::Classical, _) => format!(
            "World {w} makes every formula left of ⊢ true and every formula right of it \
             false, so {sequent} is not valid in classical logic."
        ),
        (Logic::Intuitionistic | Logic::Minimal, true) => format!(
            "World {w} forces each formula left of ⊢ and not ⊥, so {sequent} is not valid in \
             {logic} logic."
        ),
        (Logic::Intuitionistic | Logic::Minimal, false) => format!(
            "World {w} forces each formula left of ⊢ and not the one right of it, so \
             {sequent} is not valid in {logic} logic."
        ),
    };
    let mut polls = 0u64;
    kripke::draw(&countermodel.model, &title, &last, style, limits, || {
        polls += 1;
        stop(crate::limits::Progress::new(
            crate::limits::Phase::Write,
            1,
            polls,
        ))
    })
}

/// Returns a criterion's refusal as the drawing's error; a verdict,
/// either way, is no error.
fn refused(verdict: &Result<(), crate::linear::nets::NetError>) -> Result<(), Error> {
    match verdict {
        Err(refused @ crate::linear::nets::NetError::Refused { .. }) => Err(refused.clone().into()),
        _ => Ok(()),
    }
}

/// What a drawing of a net highlights of a step of cut elimination taken
/// on it, by raw vertex ids.
#[derive(Default)]
struct Marks {
    /// The cut link reduced, from its end in a cut formula's tree.
    cut: Option<(u32, u32)>,
    /// The edges and links the step acted on, each from its smaller end,
    /// sorted.
    pairs: Vec<(u32, u32)>,
    /// The `!` vertices of the boxes the step acted on.
    boxes: Vec<u32>,
}

impl Marks {
    /// Returns the marks of a step on a proof structure: the cut link, and
    /// the axiom links at its ends or the premise edges of its ends.
    fn of_mll(net: &ProofStructure, step: &crate::linear::nets::cut::Step) -> Self {
        let (x, y) = step.cut;
        let forest = net.forest();
        let mut pairs = Vec::new();
        for v in [x, y] {
            match step.case {
                crate::linear::proofs::cut::Case::TensorPar => {
                    pairs.extend(forest.children(v.occ()).map(|c| (v.get(), c.get())));
                }
                crate::linear::proofs::cut::Case::Axiom
                | crate::linear::proofs::cut::Case::OneBot
                | crate::linear::proofs::cut::Case::WithPlus
                | crate::linear::proofs::cut::Case::Weakening
                | crate::linear::proofs::cut::Case::Dereliction
                | crate::linear::proofs::cut::Case::Contraction
                | crate::linear::proofs::cut::Case::BoxIntoBox
                | crate::linear::proofs::cut::Case::ForallExists
                | crate::linear::proofs::cut::Case::Commutative => {
                    pairs.extend(net.partner(v).map(|p| (v.get(), p.get())));
                }
            }
        }
        Self::new(step, pairs, Vec::new())
    }

    /// Returns the marks of a step on a proof structure with boxes: the cut
    /// link, and the axiom links at its ends, the premise edges of its
    /// ends, or the box of its `!` end with the box it enters or the edge
    /// to the copy it acts on.
    fn of_mell(net: &MellStructure, step: &crate::linear::nets::cut::Step) -> Self {
        use crate::linear::proofs::cut::Case;
        let (x, y) = step.cut;
        let (mut pairs, mut boxes) = (Vec::new(), Vec::new());
        let bang = |v: crate::linear::nets::VertexId| {
            net.occurrence(v)
                .is_some_and(|o| net.forest().kind(o) == crate::linear::Kind::Bang)
        };
        let (b, q) = if bang(x) { (x, y) } else { (y, x) };
        match step.case {
            Case::Axiom => {
                for v in [x, y] {
                    pairs.extend(net.partner(v).map(|p| (v.get(), p.get())));
                }
            }
            Case::TensorPar => {
                for v in [x, y] {
                    pairs.extend(net.premises(v).map(|c| (v.get(), c.get())));
                }
            }
            Case::BoxIntoBox => {
                boxes.push(b.get());
                boxes.extend(step.above.map(crate::linear::nets::VertexId::get));
            }
            Case::Weakening
            | Case::Dereliction
            | Case::Contraction
            | Case::OneBot
            | Case::WithPlus
            | Case::ForallExists
            | Case::Commutative => {
                boxes.push(b.get());
                pairs.extend(step.above.map(|c| (q.get(), c.get())));
            }
        }
        Self::new(step, pairs, boxes)
    }

    /// Returns the marks of a step with the given edges and boxes.
    fn new(step: &crate::linear::nets::cut::Step, pairs: Vec<(u32, u32)>, boxes: Vec<u32>) -> Self {
        let mut pairs: Vec<(u32, u32)> = pairs
            .into_iter()
            .map(|(a, b)| (a.min(b), a.max(b)))
            .collect();
        pairs.sort_unstable();
        Self {
            cut: Some((step.cut.0.get(), step.cut.1.get())),
            pairs,
            boxes,
        }
    }

    /// Returns whether the edge or link between `a` and `b` is marked.
    fn has(&self, a: u32, b: u32) -> bool {
        self.pairs.binary_search(&(a.min(b), a.max(b))).is_ok()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A raised `⊥` and a subscript are pieces of their own, smaller and
    /// shifted, and spaces separate pieces; the widths count every piece at
    /// its size.
    #[test]
    fn scripts_are_pieces() {
        let pieces = |r: &Run| {
            r.pieces
                .iter()
                .map(|p| (p.text.clone(), p.offset, p.raise, p.size, p.width))
                .collect::<Vec<_>>()
        };
        let (a, bot, comma, space) = (770, 611, 277, 333);
        let r = run("A\u{1} ⊗ A", 1000, &Font::euler());
        assert_eq!(
            pieces(&r),
            [
                ("A".into(), 0, 0, None, a),
                ("⊥".into(), a, 400, Some(700), bot),
                ("⊗ A".into(), a + bot + space, 0, None, 668 + space + a),
            ]
        );
        assert_eq!(r.width, a + bot + space + 668 + space + a);

        let r = run("&L\u{4}1\u{5}, ", 800, &Font::euler());
        assert_eq!(
            pieces(&r),
            [
                ("&amp;L".into(), 0, 0, None, 1036),
                ("1".into(), 1036, -120, Some(560), 280),
                (",".into(), 1316, 0, None, comma * 8 / 10),
            ]
        );
    }

    /// The description writes every formula as the title does, so that a
    /// screen reader hears one spelling of a negated atom: `A⊥`, never
    /// the text tree's `~A`.
    #[cfg(feature = "parse")]
    #[test]
    fn the_description_writes_formulas_as_the_title_does() {
        use crate::linear::{Mode, Options, prove};
        let s: Sequent = "A -o B |- ~B -o ~A".parse().unwrap();
        let outcome = prove(&s, Mode::CLASSICAL, &Options::default()).unwrap();
        let proof = outcome.verdict.proof().unwrap();
        let svg = to_string(&proof.derivation().unwrap(), &Style::default()).unwrap();
        let desc = &svg[svg.find("<desc>").unwrap()..svg.find("</desc>").unwrap()];
        assert!(svg.contains("<title>⊢ A ⊗ B⊥, B ⅋ A⊥</title>"), "{svg}");
        assert!(
            desc.ends_with("4. ⊢ A ⊗ B⊥, B ⅋ A⊥, by ⅋ from 3."),
            "{desc}"
        );
        assert!(!desc.contains('~'), "{desc}");
    }

    /// A net's description is short sentences in the title's notation:
    /// the conclusion, each link with its formulas by number, then the
    /// verdict.
    #[cfg(feature = "parse")]
    #[test]
    fn a_net_is_described_in_sentences() {
        use crate::linear::{Criterion, Mode, Options, ProofStructure, prove};
        let s: Sequent = "A * B |- B * A".parse().unwrap();
        let outcome = prove(&s, Mode::CLASSICAL, &Options::default()).unwrap();
        let proof = outcome.verdict.proof().unwrap();
        let limits = crate::Limits::default();
        let structure =
            ProofStructure::from_proof(proof, Criterion::MLL, &limits, |_| false).unwrap();
        let svg = net(&structure, &Style::default(), &limits, |_| false).unwrap();
        let desc = &svg[svg.find("<desc>").unwrap() + 6..svg.find("</desc>").unwrap()];
        assert_eq!(
            desc,
            "It concludes ⊢ A⊥ ⅋ B⊥, B ⊗ A.\n\
             An axiom link joins formula 1, A⊥, and formula 5, A.\n\
             An axiom link joins formula 2, B⊥, and formula 4, B.\n\
             It is a proof net: the correctness criterion holds."
        );
    }

    /// An essential drawing of a cyclic structure whose links cross is
    /// described as no proof net: the description states the switching
    /// criterion's verdict, which tests planarity, where the drawn
    /// essential one does not.
    #[cfg(feature = "parse")]
    #[test]
    fn crossing_links_are_described_as_no_net() {
        use crate::linear::nets::VertexId;
        use crate::linear::{Criterion, Forest, Order, ProofStructure};
        let limits = crate::Limits::default();
        // ⊢ ~b, ~a, b ⊗ a: 0 ~b, 1 ~a, 2 ⊗, 3 b, 4 a.
        let s = Sequent::parse_ordered("a, b |- b * a", Order::Cyclic, &limits).unwrap();
        let v = VertexId::new;
        let links = [(v(1), v(4)), (v(0), v(3))];
        let structure =
            ProofStructure::from_links(Forest::new(&s).unwrap(), Criterion::CYCLIC, &links)
                .unwrap();
        assert_eq!(structure.is_essential(|_| false), Ok(()));
        let style = Style::default().with_essential(true);
        let svg = net(&structure, &style, &limits, |_| false).unwrap();
        let desc = &svg[svg.find("<desc>").unwrap()..svg.find("</desc>").unwrap()];
        assert!(desc.contains("\nIt is not a proof net: "), "{desc}");
    }

    /// A style past a maximum is refused before anything is drawn, and
    /// one at every maximum draws in exact numbers. Without the maxima, a
    /// style of huge numbers overflows, and in a release build writes a
    /// negative width such as `-96823495355.-824`.
    #[cfg(feature = "parse")]
    #[test]
    fn styles_are_within_their_maxima() {
        let s: Sequent = "A * B |- B * A".parse().unwrap();
        let limits = crate::Limits::default();
        let drawn = |style: &Style| sequent(&s, crate::linear::Mode::CLASSICAL, style, &limits);
        let past = Style {
            font_size: Style::MOST_FONT_SIZE + 1,
            ..Style::default()
        };
        assert!(matches!(
            drawn(&past),
            Err(Error::InvalidOption {
                key: "svg.font_size",
                ..
            })
        ));
        let most = Style {
            font: Font {
                advances: Advances::Fixed(Style::MOST_SIZE),
                ..Font::euler()
            },
            font_size: Style::MOST_FONT_SIZE,
            label_size: Style::MOST_SIZE,
            margin: Style::MOST_LENGTH,
            ..Style::default()
        };
        let svg = drawn(&most).unwrap();
        let width = svg
            .split("width=\"")
            .nth(1)
            .unwrap()
            .split('"')
            .next()
            .unwrap();
        assert!(width.parse::<f64>().unwrap() > 0.0, "{width}");
        assert_eq!(decimal(-1500), "-1.5");
    }

    /// Atom names keep their letters as math italic.
    #[test]
    fn names_are_italic() {
        let mut out = String::new();
        italic(&mut out, "Ah_1α").unwrap();
        assert_eq!(out, "𝐴ℎ_1α");
    }

    /// What XML cannot carry is `�`, whatever text it comes in; tab, line
    /// feed and carriage return stay.
    #[test]
    fn text_is_xml() {
        assert_eq!(
            escaped("a\u{7}<b>\t\n\r&\"\u{FFFE}\u{FFFF}\u{0}"),
            "a\u{FFFD}&lt;b&gt;\t\n\r&amp;&quot;\u{FFFD}\u{FFFD}\u{FFFD}"
        );
    }
}