deduxit 0.3.0

Logic suites, linear logic first: decides, checks, proves step by step and exports sequents of classical and intuitionistic linear logic, and ordinary propositional logic through its embeddings.
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
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

//! SVG: a sequent as one line of text, and a whole SVG document for each
//! drawing.
//!
//! The layout is computed here, not by the viewer: every width is the sum
//! of the advances of the style's [`Font`], by default the Euler Math
//! font's, or another [`MathFont`]'s, from a table committed with the
//! code, so the output is
//! deterministic and needs no font at run time. The document asks for the
//! font's families (`"Euler Math", "Neo Euler", serif`) 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. Letters of
//! atom names are the mathematical italic characters, which a math font
//! sets as math italic, and rule names stay upright; the `⊥` of a negated
//! atom is a superscript, the `₁` and `₂` of a rule name are subscripts.
//! All coordinates are integers in thousandths of an em of formula text
//! ([`Style::font_size`] pixels), so the text is selectable and the
//! drawing scales without loss.
//!
//! Needs the cargo feature `svg` (on by default).
//!
//! # Examples
//!
#![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>(())
//! ```

/// The metrics of the font.
mod font;
/// 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;

/// The sizes, distances and colours of a drawing. Lengths are in
/// thousandths of an em of formula text, whose size in pixels is
/// [`font_size`](Self::font_size); colours are CSS colours.
/// Made from its `default()` with the fields set that differ, since a
/// later field breaks no caller that way.
#[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 drawing asks for and the advances it is laid out with.
    pub font: Font,
    /// The labels of the rules.
    pub labels: Labels,
    /// How an open goal is drawn.
    pub open: OpenGoal,
    /// Whether every formula of a conclusion is a group of its own, with
    /// the id `i<n>-<p>` for position `p` of the sequent of inference `n`.
    pub ids: bool,
    /// Whether a drawing of a derivation or a net carries a `<desc>` that
    /// reads it in order, which a screen reader reads out: the numbered
    /// inferences of the derivation, or the net's links as
    /// its text form gives them.
    pub description: bool,
    /// The size of formula text in pixels, which scales the whole drawing.
    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.
    pub label_size: u32,
    /// The distance from the baseline of a conclusion to the baseline of
    /// its premises and from one layer of a compact proof net 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.
    pub line_height: u32,
    /// The space between two premises side by side.
    pub premise_gap: u32,
    /// The space between two literals of a proof net.
    pub literal_gap: u32,
    /// The space between an inference line and its rule name.
    pub label_gap: u32,
    /// The empty border around the drawing.
    pub margin: u32,
    /// The thickness of every line.
    pub stroke_width: u32,
    /// The height of an axiom link's arc, in thousandths of half its
    /// width, so that the arc over a pair of literals nested between two
    /// others stays below theirs.
    pub link_height: u32,
    /// The half-width of an axiom link beyond which its arc grows only
    /// with the square root of its half-width, so that a wide link stays
    /// low and the arcs of nested links still never cross; `None` for
    /// arcs that grow with their width however wide.
    pub link_cap: Option<u32>,
    /// The radius of the circle of a `⊗` or `⅋` node of a compact proof
    /// net, and how far the edges of a proof net drawn with its formulas
    /// stay from the connective at the joint of a link.
    pub node_radius: u32,
    /// The colour of text.
    pub text: String,
    /// The colour of inference lines, of a proof net's nodes, of the
    /// premise edges of its `⊗` nodes and of its conclusions.
    pub line: String,
    /// The colour of the premise edges of a `⅋` node, which are also
    /// dashed: a switching keeps one of the two.
    pub par: String,
    /// The colour of axiom links.
    pub link: String,
    /// The colour of the edges of a switching cycle, when a proof
    /// structure has one, and of the edges and links of every part but
    /// the first when it falls into several.
    pub highlight: String,
    /// The colour the drawing is filled with, or none for a transparent
    /// background.
    pub background: Option<String>,
    /// Whether a proof structure of a sequent with an intuitionistic
    /// reading is drawn as its essential net: every edge an arrow in the
    /// direction of the net, from the hypotheses toward the goal, the
    /// input occurrences in the [`input`](Self::input) colour, every
    /// formula written as the reading reads it (a literal as its atom),
    /// the links as the connectives of the reading (`⊸` and `⊗`), each implication of output position joined to its
    /// antecedent by a dotted line in the [`dominator`](Self::dominator)
    /// colour, and a directed cycle or a path around an implication in
    /// the highlight colour. A structure without the reading is drawn as
    /// without this.
    pub essential: bool,
    /// How a proof net is drawn: every formula occurrence written as a
    /// node, or compact, with only the literals and the conclusions
    /// written.
    pub net: NetDrawing,
    /// How a proof net's switched edges, conclusions and `?` nodes look.
    pub net_look: NetLook,
    /// The colour of the input occurrences of an essential net, their
    /// edges and the edges below the hypotheses; by default the blue of
    /// [`par`](Self::par), green being a checked proof's colour.
    pub input: String,
    /// The colour of the dotted line of an essential net from an
    /// implication to its antecedent, which no edge joins: the
    /// implication must dominate it.
    pub dominator: String,
    /// Whether the derivation's lambda-term is written under its
    /// conclusion, as its typing judgement ([`lambda`](crate::lambda)),
    /// with these options, their notation being the target's own; `None`
    /// by default. A derivation without a term is refused
    /// ([`Error::NoTerm`]), and a term whose text would pass the default
    /// output bound ([`Limits::DEFAULT_DERIVATION_BYTES`](crate::Limits::DEFAULT_DERIVATION_BYTES))
    /// is refused before anything is written.
    pub lambda: Option<crate::lambda::Options>,
}

impl Default for Style {
    /// Returns Euler Math, upright labels, an open goal under vertical
    /// dots, no ids per formula, a description, and black lines and text at 16 pixels to
    /// the em on a transparent background, with `⅋` edges blue and a
    /// switching cycle orange.
    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 occurrence of the conclusions a node written as
    /// its formula, where it stands in its conclusion: the literals along
    /// the top under the axiom links' arcs, each link of a `⊗` or `⅋`
    /// joining its two premises to its conclusion written below them,
    /// with the connective small at the joint, and the conclusions in the
    /// sequent's order at the bottom.
    #[default]
    Formulas,
    /// Only the literals and the conclusions written: the literals along
    /// the top, every inner `⊗` and `⅋` a small circle, and the
    /// conclusions in the sequent's order at the bottom, for nets too wide
    /// to write every subformula.
    Compact,
}

/// How the nodes and edges of a proof net look, in either
/// [`NetDrawing`]: deduxit's own look by default ([`NetLook::DEDUXIT`]), or
/// the textbooks' ([`NetLook::TEXTBOOK`]). In JSON (feature `serialize`)
/// the three fields, or the name of a [`NetPreset`] alone
/// (`"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.
    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, but for a `!` with auxiliary doors, 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 with every copy of its subformula and every wire from a
    /// box as a premise, and a weakening one without premises.
    #[default]
    Node,
    /// The nodes of the 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, and a weakening `?w`; a lone wire is the
    /// conclusion itself.
    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 }
    }
}

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 the memory; 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
    /// ([`MOST_LENGTH`](Self::MOST_LENGTH) for the lengths and
    /// `link_height`, [`MOST_SIZE`](Self::MOST_SIZE) for `label_size` and
    /// the font's advances, [`MOST_FONT_SIZE`](Self::MOST_FONT_SIZE)), so
    /// that no position of a drawing the memory can hold leaves the
    /// integers it is laid out in. Every drawing checks its style first.
    ///
    /// # 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}');

/// Writes a label's markup as text for [`run`]: symbols and text as they
/// are, a subscript between the [`SUBSCRIPT`] 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);
            }
        }
    }
    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 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, and one
/// that XML 1.0 cannot carry (a control character other than tab, line
/// feed and carriage return, U+FFFE, U+FFFF) as `�`: the one place text
/// enters a drawing, whatever a style's strings hold.
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 `⊥`,
/// what stands between the [`SUBSCRIPT`] marks a subscript, and what
/// stands between the [`FORMULA`] marks pieces of that formula. Spaces
/// separate pieces rather than start or end 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 formula, mut formulas) = (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;
        }
        let (c, shape) = match c {
            RAISED_BOT => ('⊥', (RAISE * size / 1000, SCRIPT)),
            c if lowered => (c, (-LOWER * 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 a `<text>` stretched or squeezed to the width the
/// layout gave it; `attributes` go into the start tag of the one `<text>`
/// or of the group of several, as they are. 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: one image, whose 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, whose body `body` writes into it: 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, for its width, which the head needs, and
/// to write its pieces into the document one by one, so that no list of
/// them is held: a line of millions of occurrences takes the document
/// and its text, as [`text`] would write it.
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 text is estimated at per occurrence, besides
/// its longest atom name: at least what any connective, its brackets and
/// its separator take.
const PER_OCCURRENCE: u64 = 128;

/// Returns a sequent in the options' form: one-sided, or in
/// intuitionistic mode two-sided by its reading.
///
/// # Errors
///
/// [`Refusal::Output`](crate::Refusal::Output) for a sequent whose text is
/// estimated past `limits.derivation_bytes` (`128` bytes an occurrence
/// and its longest atom name), before anything is laid out;
/// [`Error::NotIntuitionistic`] in intuitionistic mode for one without an
/// intuitionistic reading, the refusal of
/// [`Forest::within`](crate::linear::Forest::within), and
/// [`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, the elements of one
/// inference at a time, and asks `stop` after each; what it holds besides
/// is a few numbers per inference. A `String` takes the whole.
///
/// 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 the style says
/// otherwise. The conclusion of inference `n` is the `<text>` or the group
/// with the id `i<n>`, and with [`Style::ids`] its formula at position `p`
/// the group `i<n>-<p>`, hypotheses first. The layout is one pass up and
/// one down the tree, 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 two-sided if it is; one of
/// LK or LJ is two-sided, its connectives and constants their Unicode
/// characters `¬ ∧ ∨ → ↔ ⊤ ⊥`, its labels those of [`ordinary::Rule`](crate::ordinary::Rule) (a
/// label table of [`Labels::Table`] is keyed by the linear rules, so it
/// leaves them upright), and its `<desc>` its numbered inferences.
///
/// # Errors
///
/// [`Refusal::Stopped`](crate::Refusal::Stopped) when `stop` fired,
/// [`Error::WriteFailed`] when `out` refused the text, and
/// [`Error::InvalidOption`] for a style [`Style::check`] refuses, 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),
    }
}

/// Returns a proof structure, a proof net or not, complete or not, as an
/// SVG document, titled with its sequent in plain text.
///
/// The conclusions are written in a row at the bottom, in the sequent's
/// order, and 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). By default ([`NetDrawing::Formulas`])
/// every subformula occurrence 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; with
/// [`NetDrawing::Compact`] only the literals and the conclusions are
/// written and every inner `⊗` and `⅋` is a small labelled circle. The
/// edges to the two premises of a `⅋` are dashed and share a colour of
/// their own (a switching keeps one of them); Mix leaves no trace. A
/// structure with a switching cycle has the cycle's edges in the
/// highlight colour, and one that falls into parts (those of
/// [`NetError::Disconnected`](crate::linear::nets::NetError::Disconnected)) has
/// the edges, conclusions and links of every part but the first in it.
/// Every occurrence's formula, or a compact net's circle of a connective,
/// is the element with the id `o<n>` for occurrence `n`, and a link is
/// `l<m>-<n>`. A cut link, as the literature draws one, is a bar under
/// its two formulas, which stand at the bottom after the conclusions,
/// with the id `c<x>-<y>`, its end in a cut formula's tree 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`].
///
/// 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, at least what the
/// drawing has. 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, and
/// [`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 acted on in the highlight colour: the cut link
/// reduced and, by its case, the two axiom links at its 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);
    if let Some(limit) = limits.derivation_bytes {
        let estimate = net::estimate(net, style, reading.is_some(), limit);
        if estimate > limit {
            return Err(Error::Refused(crate::limits::Refusal::Output {
                what: "drawing",
                estimate_bytes: estimate,
                limit_bytes: limit,
                least_bytes: None,
            }));
        }
    }
    let mut stop = stop;
    let verdict = match &reading {
        Some(_) => net.is_essential(&mut stop),
        None => net.is_correct(&mut stop),
    };
    if let Err(refused @ crate::linear::nets::NetError::Refused { .. }) = verdict {
        return Err(refused.into());
    }
    Ok(net::draw(net, style, &verdict, 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
/// [`Style::net`] [`NetDrawing::Compact`], the literals and conclusions:
/// every `!`-box a rectangle around its contents, nested boxes nested, its
/// `!` vertex and an auxiliary door for every `?` vertex outside it with a
/// copy inside on its bottom border, the wires of a `?` vertex dashed as a
/// `⅋`'s premise edges are. A formula has the id `o<n>` when it is the only
/// vertex of occurrence `n` and `v<k>` (its vertex) when its occurrence has
/// several; a link `l<x>-<y>` (its vertices) and a box `b<k>` (its `!`
/// vertex), and a cut link `c<x>-<y>`, a bar under its two formulas,
/// its end in a cut formula's tree first, 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, the wires
/// of a hypothesis `!A` led up into its copies; its highlight is still the
/// switching cycle, which decides it. Refused past
/// `limits.derivation_bytes` before anything is drawn, as [`net()`] is; the
/// criterion that decides the highlight asks `stop` as
/// [`MellStructure::is_correct`] does.
///
/// # Errors
///
/// [`Refusal::Output`](crate::Refusal::Output) past the bound, the
/// criterion's refusal when `stop` fired, and [`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 acted on in the highlight colour:
/// the cut link reduced and, by its case, the two axiom links at its
/// ends, the premise edges of its `⊗` and `⅋`, or 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);
    if let Some(limit) = limits.derivation_bytes {
        let estimate = mell::estimate(net, style, reading.is_some(), limit);
        if estimate > limit {
            return Err(Error::Refused(crate::limits::Refusal::Output {
                what: "drawing",
                estimate_bytes: estimate,
                limit_bytes: limit,
                least_bytes: None,
            }));
        }
    }
    let verdict = net.is_correct(stop);
    if let Err(refused @ crate::linear::nets::NetError::Refused { .. }) = verdict {
        return Err(refused.into());
    }
    Ok(mell::draw(net, style, &verdict, reading.as_ref(), marks))
}

/// 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),
            ]
        );
    }

    /// A style past a maximum is refused before anything is drawn, and
    /// one at every maximum draws in exact numbers: its width once went
    /// negative, `-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}"
        );
    }
}