f-office-docx 0.2.3

DOCX model and Word's layout rules.
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
//! The layout's target decisions. Each function takes the parts of one question of the layout
//! and the resolved quirks, and gives the whole answer, so that the rest of the layout reads no
//! quirk.

use f_office_units::{Edges, Length};

use std::borrow::Cow;

use crate::body::{Content, Run};
use crate::chart::{Columns, PlotRule};
use crate::dates::{DateTime, PROPERTY_DATE_PICTURE};
use crate::grid::{Device, Rounding, in_fixed_points};
use crate::lines::{EndSpaceFit, LeadingBreaks, LineBreaking, Piece};
use crate::mode::ModeRules;
use crate::params;
use crate::props::{Anchor, Border, HtmlAutoSpacing, Kashidas, LineSpacing, ParaProps, RunProps};
use crate::quirks::GridSingleLine;
use crate::quirks::PropertyDateZone;
use crate::quirks::StoryMarginArea;

use super::output::BodyArea;
use crate::quirks::InlinePictureClip;
use crate::quirks::{
    AlignedTabOverrun, AlignmentWithNotes, AutofitGrid, AutomaticHyphenation, BookmarkText,
    BorderDashes, BorderWidthUnit, CarriedMergeMove, CellBreak, CellClip, CellDrawingBounds,
    CellEndListSpace, CellFillRows, CellFillSides, CellFrames, CellTextRoom, CellTopBand,
    CenteredLine, CenteredMultiple, ChartAxisOrder, ChartAxisRoom, ChartDataLabels, ChartLineClip,
    CheckBoxSide, ColumnEdgeHalves, ComputedFieldDecorations, ComputedFieldFormat, ControlObjects,
    EdgeShares, ExactRowMargin, FaceRoomSpacing, FixedAutoSpacing, FloatingTableBreaks,
    FloatingTableLeft, FloatingTableTop, GrownDelimiters, HyperlinkObjects, LabelAloneRise,
    LaterPartWidows, LeadingPageBreak, LeftStopPastEnd, ListLabelDescent, MarkFace, MergedCellFill,
    MergedCellLines, MergedTopRoom, MetafileTopAscent, NestedRowMinimum, NoBreakSpaceShare,
    NoteReferenceBreak, ObjectAscent, ObjectLineMultiple, PictureLinePlace, PictureShadows, Quirks,
    RaisedRunSpacing, RemovedTextObjects, RowBelowHeaders, RowEndBorders, RowLineRoom, ScaledSteps,
    ShapeShadows, SoftBreakLine, SpacedColumns, SpacedTableBreaks, SplitMergeAlign, SplitRowFills,
    StretchedSpaceShare, StyleRegionBorders, TurnedLineRoom, TurnedPicture, UnderlinedObjectRoom,
    VmlObjectSize, WrapEdgeDot, ZeroRevision,
};
use crate::quirks::{
    BandHeight, BetweenBorders, BlockedLines, BorderSides, BottomBorderSpaceAfter, BoxLastLine,
    BoxOutlineLeft, BoxTextTop, ColumnSeparator, ColumnTopSpace, ColumnWidths,
    ContinuousSectionEnd, DeletedTableTop, FootBorderRoom, FrameFittedWidth, FrameLeft, FromLine,
    HiddenHeaderFooterEnd, HiddenMarkBorders, KashidaJustification, LastPageBalance, LineWrapBand,
    MultipleBottomBorder, MultipleTopBorder, PageBreakBeforeSpace, PolygonWrap, RestartSide,
    RightToLeftEdge, RightToLeftEndSpace, RightToLeftSectionColumns, SeenKashidas,
    SeparatorSpaceAfter, SmartArtLowSpacing, StepEnd, StyleRefNoBreakSpace, StyleRefTrailingSpaces,
    TextBoxClip, TextBoxColumns, TurnedAcrossDots, UnsetCellMargins, VmlBoxOutline, WidowForecast,
    WordPerfectJustification,
};
use crate::reader::settings::PlotRules;
use crate::styles::{Justification, Settings, SoftBreakLines};

#[cfg(test)]
mod tests;

/// The parts of a table cell that place its text column.
#[derive(Clone, Copy, Debug)]
pub(in crate::layout) struct CellParts {
    /// The x of the grid line on the cell's left.
    pub(in crate::layout) left: Length,
    /// The x of the grid line on the cell's right.
    pub(in crate::layout) right: Length,
    /// The cell's left and right margins.
    pub(in crate::layout) margins: (Length, Length),
    /// Whether the cell, the table or its style sets the left margin, or the target gives a left
    /// margin that none of them sets its default.
    pub(in crate::layout) left_margin_set: bool,
    /// The widths of the lines drawn on the cell's left and right.
    pub(in crate::layout) lines: (Length, Length),
    /// In a table with cell spacing, where the cell's own box lies.
    pub(in crate::layout) gaps: Option<CellGaps>,
    /// Whether the cell's text is upright, without a text direction.
    pub(in crate::layout) upright: bool,
    /// What the cell's upright text start loses to the half twip of the table's place.
    pub(in crate::layout) text_rest: Length,
}

/// In a table with cell spacing, the gaps from the grid lines on the left and the right of a
/// cell to the outer edges of its own box, and the table's cell spacing.
#[derive(Clone, Copy, Debug)]
pub(in crate::layout) struct CellGaps {
    pub(in crate::layout) left: Length,
    pub(in crate::layout) right: Length,
    pub(in crate::layout) spacing: Length,
}

/// The room of a cell's text: where its lines start, what lies between the cell's left edge and
/// that start, and how wide the lines are.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) struct CellRoom {
    /// The x where the cell's lines start.
    pub(in crate::layout) left: Length,
    /// The cell's left margin, or what stands for it.
    pub(in crate::layout) inner: Length,
    /// The width of the cell's lines.
    pub(in crate::layout) width: Length,
}

/// The room of a cell's text: between the grid lines, inside the cell margins. With cell
/// spacing, the edges of the cell are the middles of its box's lines, or as the quirk
/// `SpacedCellText` says. Without any left margin, the text starts after the left line, unless
/// the target gives an unset side margin its default (`UnsetCellMargins::DefaultSides`). Under
/// `CellTextRoom::CombinedBorderMinimum`, a collapsed cell whose left margin is set has separate
/// border minima for its left start and its line width, and a margin less than half the left
/// line leaves the text half the line right of the exact grid line. Only upright text starts
/// from the table's place on a whole twip; turned text keeps the exact place, and so does the
/// text that starts half the left line right of it.
pub(in crate::layout) fn cell_text_room(quirks: &Quirks, cell: &CellParts) -> CellRoom {
    let (left_margin, right_margin) = cell.margins;
    let (left_line, right_line) = cell.lines;
    let (left, right, gap) = match cell.gaps {
        Some(gaps) => {
            // quirk: SpacedCellText::InsideLines (src/quirks.rs)
            let text = quirks.spaced_cell_text;
            (
                cell.left + gaps.left + text.side_room(left_line, gaps.spacing),
                cell.right - gaps.right - text.side_room(right_line, gaps.spacing),
                left_margin,
            )
        }
        None if cell.left_margin_set => (cell.left, cell.right, left_margin),
        None => (cell.left, cell.right, left_line),
    };
    let minimum = cell.gaps.is_none()
        && cell.left_margin_set
        && quirks.cell_text_room == CellTextRoom::CombinedBorderMinimum;
    let half_left = left_line.div_toward_zero(2);
    let gap = if minimum { gap.max(half_left) } else { gap };
    let on_half_line = minimum && left_margin < half_left;
    let width = if minimum {
        let margins = left_margin + right_margin;
        let lines = Length::from_units(i64::midpoint(left_line.units(), right_line.units()));
        right - left - margins.max(lines)
    } else {
        right - right_margin - left - gap
    };
    let inner = gap;
    let rest = if cell.upright && !on_half_line {
        cell.text_rest
    } else {
        Length::ZERO
    };
    CellRoom {
        left: left + inner + rest,
        inner,
        width,
    }
}

/// How the paragraphs of a document with the settings `settings` read automatic spacing on a
/// target with the quirks `quirks`: as fixed values where the settings ask for them and the
/// target follows the compatibility option, else as HTML user agents space paragraphs.
pub(in crate::layout) fn html_auto_spacing(
    settings: &crate::styles::Settings,
    quirks: &Quirks,
) -> HtmlAutoSpacing {
    // quirk: FixedAutoSpacing::OptionFollowed (src/quirks.rs)
    if settings.html_auto_spacing == HtmlAutoSpacing::Fixed
        && quirks.fixed_auto_spacing == FixedAutoSpacing::OptionFollowed
    {
        HtmlAutoSpacing::Fixed
    } else {
        HtmlAutoSpacing::Html
    }
}

/// Puts a framed paragraph of a table cell (`in_cell`), with the resolved properties `props`,
/// in the cell's flow on a target whose table cells hold no frames (`CellFrames::InFlow`).
pub(in crate::layout) fn cell_frame(quirks: &Quirks, in_cell: bool, props: &mut ParaProps) {
    // quirk: CellFrames::InFlow (src/quirks.rs)
    if in_cell && quirks.cell_frames == CellFrames::InFlow {
        props.plain_cell_frame();
    }
}

/// The face of a paragraph mark whose properties use complex formatting
/// (`complex_formatting`) or not, which `face` gives as the complex script face (`true`) or the
/// face of ASCII text (`false`): the complex script face of a mark with complex formatting under
/// `MarkFace::ComplexFormatting`, and the face of ASCII text otherwise.
pub(in crate::layout) fn mark_face<T>(
    quirks: &Quirks,
    complex_formatting: bool,
    face: impl FnOnce(bool) -> T,
) -> T {
    // quirk: MarkFace::ComplexFormatting (src/quirks.rs)
    face(complex_formatting && quirks.mark_face == MarkFace::ComplexFormatting)
}

/// Whether the content `content` between joined texts starts a text object of the writer at
/// the text after it, which is still measured with the text before it: a field mark always,
/// and the edge of a hyperlink, of a content control or of removed text on a target whose
/// writer starts a text object there.
pub(in crate::layout) fn starts_text_object(quirks: &Quirks, content: &Content) -> bool {
    match content {
        Content::FieldMark => true,
        // quirk: HyperlinkObjects (src/quirks.rs)
        Content::HyperlinkEdge => quirks.hyperlink_objects == HyperlinkObjects::StartsObject,
        // quirk: ControlObjects (src/quirks.rs)
        Content::ControlEdge => quirks.control_objects == ControlObjects::StartsObject,
        // quirk: RemovedTextObjects (src/quirks.rs)
        Content::RemovedEdge => quirks.removed_text_objects == RemovedTextObjects::StartsObject,
        _ => false,
    }
}

/// Whether a content `content` that is not text ends the text that waits for the next run:
/// every content but a bookmark's start on a target that measures the text on both sides of it
/// as one (`BookmarkText::Joins`).
pub(in crate::layout) fn ends_text(quirks: &Quirks, content: &Content) -> bool {
    // quirk: BookmarkText (src/quirks.rs)
    !(matches!(content, Content::Bookmark(_)) && quirks.bookmark_text == BookmarkText::Joins)
}

/// Whether a delimiter of an equation that grows around content that is not line high draws
/// the glyph variants that reach the content (`GrownDelimiters::Variant`); on the other targets
/// it draws its base glyphs, and the marks around it place nothing.
pub(in crate::layout) fn grows_delimiters(quirks: &Quirks) -> bool {
    // quirk: GrownDelimiters::Variant (src/quirks.rs)
    quirks.grown_delimiters == GrownDelimiters::Variant
}

/// The rules of the automatic hyphenation of a paragraph, which `rules` gives, on a target
/// that hyphenates a language; `None` where it hyphenates none (`AutomaticHyphenation::Off`).
pub(in crate::layout) fn hyphenation<T>(
    quirks: &Quirks,
    rules: impl FnOnce() -> Option<T>,
) -> Option<T> {
    // quirk: AutomaticHyphenation::Off (src/quirks.rs)
    match quirks.automatic_hyphenation {
        AutomaticHyphenation::Off => None,
        AutomaticHyphenation::EnglishFrenchSpanish => rules(),
    }
}

/// The language by which the target hyphenates the words of a run of the language tag `tag`,
/// or `None` where it hyphenates no word of that language.
pub(in crate::layout) fn hyphenation_language(
    quirks: &Quirks,
    tag: &str,
) -> Option<f_office_hyphenate::Language> {
    // quirk: AutomaticHyphenation::EnglishFrenchSpanish (src/quirks.rs)
    quirks.automatic_hyphenation.language(tag)
}

/// How the writer reads the revision IDs of runs, when it compares those of a run with those
/// of the run before ([`Self::read`]).
#[derive(Clone, Copy, Debug)]
pub(in crate::layout) struct RevisionReading(ZeroRevision);

impl RevisionReading {
    /// The reading of the IDs as they are written, for text that no other text joins.
    pub(in crate::layout) const AS_WRITTEN: Self = Self(ZeroRevision::AnId);

    /// The target's reading.
    pub(in crate::layout) const fn of(quirks: &Quirks) -> Self {
        Self(quirks.zero_revision)
    }

    /// The reading of a variant of the quirk, for tests.
    #[cfg(test)]
    pub(in crate::layout) const fn with(zero: ZeroRevision) -> Self {
        Self(zero)
    }

    /// The revision IDs of a run, the session that added it, the one that last formatted it
    /// and the accepted insertion that held it, as the writer reads them: with an ID of zero as
    /// an ID, or as none (`ZeroRevision::NoId`).
    pub(in crate::layout) fn read(self, revisions: [Option<u32>; 3]) -> [Option<u32>; 3] {
        // quirk: ZeroRevision (src/quirks.rs)
        self.0.read(revisions)
    }
}

/// The share of a turned cell's font size by which the target grows each of the cell's lines,
/// `part` over `whole` (`TurnedLineRoom::SizeShare`). `None` where its lines keep their size.
pub(in crate::layout) fn turned_line_room(quirks: &Quirks) -> Option<(i64, i64)> {
    match quirks.turned_line_room {
        TurnedLineRoom::Upright => None,
        // quirk: TurnedLineRoom::SizeShare (src/quirks.rs)
        TurnedLineRoom::SizeShare => Some(params::TURNED_LINE_ROOM),
    }
}

/// The faces of a line's list labels, which `labels` gives, that size the line's descent as
/// the faces of its text do on a target that counts them (`ListLabelDescent::Counted`). `None`
/// where a label's descent stays out of a line that holds text
/// (`ListLabelDescent::LeftOutOfLine`).
pub(in crate::layout) fn counted_labels<T>(
    quirks: &Quirks,
    labels: impl FnOnce() -> T,
) -> Option<T> {
    match quirks.list_label_descent {
        // quirk: ListLabelDescent::LeftOutOfLine (src/quirks.rs)
        ListLabelDescent::LeftOutOfLine => None,
        ListLabelDescent::Counted => Some(labels()),
    }
}

/// The rise of a list label above the paragraph mark's ascent on a line that holds nothing
/// but the label, which `scaled` gives, on a target whose multiple spacing scales it with the
/// rest of the line (`LabelAloneRise::Scaled`). `None` where it comes on top of the line
/// unscaled (`LabelAloneRise::Unscaled`).
pub(in crate::layout) fn scaled_label_rise<T>(
    quirks: &Quirks,
    scaled: impl FnOnce() -> T,
) -> Option<T> {
    match quirks.label_alone_rise {
        LabelAloneRise::Unscaled => None,
        // quirk: LabelAloneRise::Scaled (src/quirks.rs)
        LabelAloneRise::Scaled => Some(scaled()),
    }
}

/// The ascent of a line of automatic spacing that the objects of its runs that are not raised
/// give, which `ascent` gives, on a target where such an object's part above the baseline can
/// become the line's ascent (`ObjectAscent::Ascent`). `None` where the line keeps its own.
pub(in crate::layout) fn object_ascent<T>(
    quirks: &Quirks,
    ascent: impl FnOnce() -> Option<T>,
) -> Option<T> {
    match quirks.object_ascent {
        ObjectAscent::SingleLine => None,
        // quirk: ObjectAscent::Ascent (src/quirks.rs)
        ObjectAscent::Ascent => ascent(),
    }
}

/// Whether an underlined inline object alone on its line and taller than its font line keeps room
/// below the baseline for its underline (`UnderlinedObjectRoom::FontDescent`).
pub(in crate::layout) fn underlined_object_room(quirks: &Quirks) -> bool {
    match quirks.underlined_object_room {
        UnderlinedObjectRoom::None => false,
        // quirk: UnderlinedObjectRoom::FontDescent (src/quirks.rs)
        UnderlinedObjectRoom::FontDescent => true,
    }
}

/// Evaluates `value` where the quirk sizes inline object lines and their multiple spacing by
/// the objects' runs (`ObjectLineMultiple::ObjectRun`), and returns `None` where the paragraph
/// mark sizes the line (`ObjectLineMultiple::Mark`).
pub(in crate::layout) fn object_line_multiple<T>(
    quirks: &Quirks,
    value: impl FnOnce() -> Option<T>,
) -> Option<T> {
    // quirk: ObjectLineMultiple::ObjectRun (src/quirks.rs)
    matches!(quirks.object_line_multiple, ObjectLineMultiple::ObjectRun)
        .then(value)
        .flatten()
}

/// The face room `room` of a line of automatic multiple spacing above single spacing, which
/// comes on top of the line unscaled on a target that spaces it once
/// (`FaceRoomSpacing::Once`). `None` where the spacing scales it.
pub(in crate::layout) fn face_room_once<T>(quirks: &Quirks, room: T) -> Option<T> {
    match quirks.face_room_spacing {
        FaceRoomSpacing::Scaled => None,
        // quirk: FaceRoomSpacing::Once (src/quirks.rs)
        FaceRoomSpacing::Once => Some(room),
    }
}

/// The shift room `room` of the raised and lowered runs of a line of automatic multiple spacing
/// above single spacing, which comes on top of the line unscaled on a target that spaces it
/// once (`RaisedRunSpacing::Once`). `None` where the spacing scales it.
pub(in crate::layout) fn raised_room_once<T>(quirks: &Quirks, room: T) -> Option<T> {
    match quirks.raised_run_spacing {
        RaisedRunSpacing::Scaled => None,
        // quirk: RaisedRunSpacing::Once (src/quirks.rs)
        RaisedRunSpacing::Once => Some(room),
    }
}

/// What the target's line breaking does with tabs and footnote references, in a document of the
/// compatibility mode whose `rules` are given: the text after an aligned tab that would end past
/// its limit ends there (`AlignedTabOverrun::EndsAtAreaEnd`), a footnote reference's mark is
/// text of its word (`NoteReferenceBreak::AsText`), and a tab to a custom left stop past the
/// line's end goes to that end (`LeftStopPastEnd::ToLineEnd`) from the mode of Word 2013 only,
/// and to its stop in an older mode on every target. A paragraph that starts with page breaks
/// and holds text after them starts its first line after them (`LeadingPageBreak::AfterBreak`):
/// after the first of them from the mode of Word 2013, after all of them in an older mode.
pub(in crate::layout) fn line_breaking(quirks: &Quirks, rules: ModeRules) -> LineBreaking {
    LineBreaking {
        // quirk: AlignedTabOverrun::EndsAtAreaEnd (src/quirks.rs)
        ends_aligned_text: match quirks.aligned_tab_overrun {
            AlignedTabOverrun::RunsPast => false,
            AlignedTabOverrun::EndsAtAreaEnd => true,
        },
        // quirk: NoteReferenceBreak::AsText (src/quirks.rs)
        note_reference_in_word: match quirks.note_reference_break {
            NoteReferenceBreak::After => false,
            NoteReferenceBreak::AsText => true,
        },
        // quirk: LeftStopPastEnd::ToLineEnd (src/quirks.rs)
        left_stops_to_line_end: rules.moves_tab_to_left_stop_past_end()
            && match quirks.left_stop_past_end {
                LeftStopPastEnd::ToStop => false,
                LeftStopPastEnd::ToLineEnd => true,
            },
        // quirk: LeadingPageBreak::AfterBreak (src/quirks.rs)
        leading_breaks: match quirks.leading_page_break {
            LeadingPageBreak::OnBreakLine => LeadingBreaks::None,
            LeadingPageBreak::AfterBreak if rules.starts_after_first_leading_break() => {
                LeadingBreaks::First
            }
            LeadingPageBreak::AfterBreak => LeadingBreaks::All,
        },
    }
}

/// The letter joints that a justified line lengthens with tatweels.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) enum KashidaJoints {
    /// One joint of each of its last words that can take a kashida.
    LastWords,
    /// Every joint after a seen, sheen, sad or dad first, then the joints before an alef or a
    /// heh that ends a joined group.
    SeensThenFinals,
}

/// The letter joints that a justified line of a paragraph with the kashidas `kashidas`
/// lengthens with tatweels, where the paragraph is aligned `lowKashida`: below
/// `KASHIDA_WORDS_MODE`, one of each of its last words where the target does so
/// (`KashidaJustification::LastWords`); from it, those after a seen, sheen, sad or dad where the
/// target does so, then those before an alef or a heh that ends a joined group
/// (`SeenKashidas::SeenAndFinalJoints`). `None` where the line widens its spaces only.
pub(in crate::layout) fn kashida_joints(
    quirks: &Quirks,
    settings: &Settings,
    kashidas: Option<Kashidas>,
) -> Option<KashidaJoints> {
    if kashidas != Some(Kashidas::Low) {
        return None;
    }
    if settings.mode_rules.lengthens_last_words() {
        return match quirks.kashida_justification {
            KashidaJustification::SpacesOnly => None,
            // quirk: KashidaJustification::LastWords (src/quirks.rs)
            KashidaJustification::LastWords => Some(KashidaJoints::LastWords),
        };
    }
    match quirks.seen_kashidas {
        SeenKashidas::SpacesOnly => None,
        // quirk: SeenKashidas::SeenAndFinalJoints (src/quirks.rs)
        SeenKashidas::SeenAndFinalJoints => Some(KashidaJoints::SeensThenFinals),
    }
}

/// The justification that the justified lines of a document take: that of `WordPerfect` where
/// the settings ask for it, the compatibility mode does not shrink the spaces of justified
/// lines, and the target follows the option (`WordPerfectJustification::ShrinksLine`); else
/// Word's own.
pub(in crate::layout) fn justification(quirks: &Quirks, settings: &Settings) -> Justification {
    // quirk: WordPerfectJustification::ShrinksLine (src/quirks.rs)
    let follows = match quirks.word_perfect_justification {
        WordPerfectJustification::Ignored => false,
        WordPerfectJustification::ShrinksLine => true,
    };
    if follows
        && settings.justification == Justification::WordPerfect
        && !settings.mode_rules.shrinks_justified_spaces()
    {
        Justification::WordPerfect
    } else {
        Justification::Word
    }
}

/// Takes the page and column breaks out of the pieces of a paragraph in a table cell, on a
/// target where such a break does nothing (`CellBreak::Ignored`), and zeroes `before` when a
/// leading page or column break precedes the paragraph's content (at `offset`). Where it ends
/// its line, the pieces and `before` stay as they are.
pub(in crate::layout) fn cell_breaks(
    quirks: &Quirks,
    pieces: &mut Vec<Piece>,
    offset: usize,
    before: Option<&mut crate::props::ParaProps>,
) {
    match quirks.cell_break {
        CellBreak::EndsLine => {}
        // quirk: CellBreak::Ignored (src/quirks.rs)
        CellBreak::Ignored => {
            let leading = pieces
                .get(offset..)
                .unwrap_or_default()
                .iter()
                .find(|piece| !matches!(piece, Piece::Anchor(_) | Piece::Strut(_)))
                .is_some_and(|piece| matches!(piece, Piece::PageBreak | Piece::ColumnBreak));
            if leading && let Some(props) = before {
                props.before = Some(Length::ZERO);
                props.before_auto = Some(false);
            }
            pieces.retain(|piece| !matches!(piece, Piece::PageBreak | Piece::ColumnBreak));
        }
    }
}

/// The items `shadow` of a shape's outer shadow, where the target draws such shadows
/// (`ShapeShadows::Picture`); `None` where it does not, and the layout warns of the shadow.
pub(in crate::layout) fn shape_shadow<T>(quirks: &Quirks, shadow: impl FnOnce() -> T) -> Option<T> {
    match quirks.shape_shadows {
        ShapeShadows::Unknown => None,
        // quirk: ShapeShadows::Picture (src/quirks.rs)
        ShapeShadows::Picture => Some(shadow()),
    }
}

/// The items `shadow` of a picture's outer shadow, the shadow of its frame, where the target
/// draws such shadows (`PictureShadows::Frame`); `None` where it does not, and the layout
/// warns of the shadow.
pub(in crate::layout) fn picture_shadow<T>(
    quirks: &Quirks,
    shadow: impl FnOnce() -> T,
) -> Option<T> {
    match quirks.picture_shadows {
        PictureShadows::Unknown => None,
        // quirk: PictureShadows::Frame (src/quirks.rs)
        PictureShadows::Frame => Some(shadow()),
    }
}

/// The picture `picture` of a turned cell's text, where it stays upright on the page
/// (`TurnedPicture::Upright`). `None` where it turns with the cell's frame.
pub(in crate::layout) fn upright_picture<T>(quirks: &Quirks, picture: T) -> Option<T> {
    match quirks.turned_picture {
        TurnedPicture::InFrame => None,
        // quirk: TurnedPicture::Upright (src/quirks.rs)
        TurnedPicture::Upright => Some(picture),
    }
}

/// The shares of a line's free space that the edge check of right-edge steps counts, which
/// `counted` gives, on a target whose edge check counts Word's shares (`EdgeShares::ExactFree`).
/// `None` where it counts the spread steps alone.
pub(in crate::layout) fn counted_edge_shares<T>(
    quirks: &Quirks,
    counted: impl FnOnce() -> Option<T>,
) -> Option<T> {
    match quirks.edge_shares {
        EdgeShares::Spread => None,
        // quirk: EdgeShares::ExactFree (src/quirks.rs)
        EdgeShares::ExactFree => counted(),
    }
}

/// The wrap edge `edge` from which a line beside a drawing on its left counts its start, on a
/// target that counts it from the wrap edge's own dot (`WrapEdgeDot::WrapEdge`). `None` where
/// the line counts from its column's dot and the distance.
pub(in crate::layout) fn wrap_edge<T>(quirks: &Quirks, edge: Option<T>) -> Option<T> {
    match quirks.wrap_edge_dot {
        WrapEdgeDot::ColumnAndDistance => None,
        // quirk: WrapEdgeDot::WrapEdge (src/quirks.rs)
        WrapEdgeDot::WrapEdge => edge,
    }
}

/// The centered line that `centered` gives, on a target that shares the middles of the pieces
/// of a centered line (`CenteredLine::MiddlesShared`). `None` where they stay on one baseline.
pub(in crate::layout) fn shared_middles<T>(
    quirks: &Quirks,
    centered: impl FnOnce() -> Option<T>,
) -> Option<T> {
    match quirks.centered_line {
        CenteredLine::OnBaseline => None,
        // quirk: CenteredLine::MiddlesShared (src/quirks.rs)
        CenteredLine::MiddlesShared => centered(),
    }
}

/// The face of a centered line of multiple spacing that `face` gives, on a target that rounds
/// the middle of such a line (`CenteredMultiple::MiddleRounded`). `None` where the line keeps
/// the baseline of its box.
pub(in crate::layout) fn rounded_middle<T>(
    quirks: &Quirks,
    face: impl FnOnce() -> Option<T>,
) -> Option<T> {
    match quirks.centered_multiple {
        CenteredMultiple::OnBaseline => None,
        // quirk: CenteredMultiple::MiddleRounded (src/quirks.rs)
        CenteredMultiple::MiddleRounded => face(),
    }
}

/// The character scale `scale` of a glyph's run, at whose nominal size the device counts the
/// glyph's steps (`ScaledSteps::NominalSum`). `None` where it counts them at the drawn size.
pub(in crate::layout) fn nominal_steps<T>(quirks: &Quirks, scale: Option<T>) -> Option<T> {
    match quirks.scaled_steps {
        ScaledSteps::DrawnSize => None,
        // quirk: ScaledSteps::NominalSum (src/quirks.rs)
        ScaledSteps::NominalSum => scale,
    }
}

/// The departures from the equal share of a justified line's stretched spaces that
/// `departures` gives, where the target shares the free space by the spaces' widths first
/// (`StretchedSpaceShare::WidthFirst`). `None` where each space takes the same share.
pub(in crate::layout) fn width_first_share<T>(
    quirks: &Quirks,
    departures: impl FnOnce() -> T,
) -> Option<T> {
    match quirks.stretched_space_share {
        StretchedSpaceShare::Equal => None,
        // quirk: StretchedSpaceShare::WidthFirst (src/quirks.rs)
        StretchedSpaceShare::WidthFirst => Some(departures()),
    }
}

/// Whether a justified line stretches and shrinks the no-break spaces of a document as plain
/// spaces, in a compatibility mode that `rules` give, where `east_asian_defaults` says that the
/// run defaults are the template's or name a font made for East Asian text
/// (`NoBreakSpaceShare::EastAsianDefaults`).
pub(in crate::layout) fn no_break_spaces_stretch(
    quirks: &Quirks,
    rules: ModeRules,
    east_asian_defaults: bool,
) -> bool {
    match quirks.no_break_space_share {
        NoBreakSpaceShare::None => false,
        // quirk: NoBreakSpaceShare::EastAsianDefaults (src/quirks.rs)
        NoBreakSpaceShare::EastAsianDefaults => {
            rules.may_stretch_no_break_spaces() && east_asian_defaults
        }
    }
}

/// The parts of the left edge of a later column of the page that `parts` gives, on a target
/// that takes the edge by its parts (`ColumnEdgeHalves::ColumnParts`). `None` where it takes
/// the whole edge.
pub(in crate::layout) fn column_edge_parts<T>(
    quirks: &Quirks,
    parts: impl FnOnce() -> Option<T>,
) -> Option<T> {
    match quirks.column_edge_halves {
        ColumnEdgeHalves::WholeEdge => None,
        // quirk: ColumnEdgeHalves::ColumnParts (src/quirks.rs)
        ColumnEdgeHalves::ColumnParts => parts(),
    }
}

/// The side of a drawn check box between the middles of its strokes, from the side
/// `three_strokes` that leaves three strokes of room in its cell: one `dot` less on a target of
/// `CheckBoxSide::ThreeStrokesAndDot`.
pub(in crate::layout) fn check_box_side(
    quirks: &Quirks,
    three_strokes: Length,
    dot: Length,
) -> Length {
    match quirks.check_box_side {
        CheckBoxSide::ThreeStrokes => three_strokes,
        // quirk: CheckBoxSide::ThreeStrokesAndDot (src/quirks.rs)
        CheckBoxSide::ThreeStrokesAndDot => three_strokes - dot,
    }
}

/// The document's setting `lines` for the lines that end in a soft line break, where the target
/// follows it (`SoftBreakLine::OptionFollowed`). `None` where it justifies such lines.
pub(in crate::layout) fn followed_soft_break_lines(
    quirks: &Quirks,
    lines: SoftBreakLines,
) -> Option<SoftBreakLines> {
    match quirks.soft_break_line {
        SoftBreakLine::Justified => None,
        // quirk: SoftBreakLine::OptionFollowed (src/quirks.rs)
        SoftBreakLine::OptionFollowed => Some(lines),
    }
}

/// The VML rectangle `shape` with an anchor lock, on a target where such a rectangle takes the
/// room of its outline on its line (`VmlObjectSize::TakesAnchorStrokeRoom`, and
/// `TakesStrokeRoom`, under which every outlined shape does). `None` where it takes the room of
/// its style's size.
pub(in crate::layout) fn anchor_stroke_room<T>(quirks: &Quirks, shape: T) -> Option<T> {
    match quirks.vml_object_size {
        VmlObjectSize::TakesStyleSize => None,
        // quirk: VmlObjectSize::TakesAnchorStrokeRoom (src/quirks.rs)
        VmlObjectSize::TakesAnchorStrokeRoom | VmlObjectSize::TakesStrokeRoom => Some(shape),
    }
}

/// The area between the margins from which a floating drawing of a header, a footer or the
/// body counts on a page whose section has its margins at `margins` (with no footnotes) and
/// whose body takes `body`: the body's area where the target says so
/// (`StoryMarginArea::BodyArea`), else the section's margins.
pub(in crate::layout) fn story_margin_area(
    quirks: &Quirks,
    margins: BodyArea,
    body: BodyArea,
) -> BodyArea {
    match quirks.story_margin_area {
        StoryMarginArea::SectionMargins => margins,
        // quirk: StoryMarginArea::BodyArea (src/quirks.rs)
        StoryMarginArea::BodyArea => body,
    }
}

/// The ascent and the descent of a single line on a section's line grid of `pitch`, each
/// rounded to the device's dots on its own, from which the line takes its place in its steps,
/// and how the top of its steps and their height round to the device,
/// where the target says so (`GridSingleLine::PartsRounded`): to the nearest dot, a half down
/// the page where the points in binary fixed point hold the pitch exactly, else a half up the
/// page, as from a pitch cut toward zero. `None` where the line lies in the middle of its steps
/// from its own height and baseline.
pub(in crate::layout) fn grid_single_parts(
    quirks: &Quirks,
    device: &Device,
    (ascent, descent): (Length, Length),
    pitch: Length,
) -> Option<((Length, Length), Rounding)> {
    match quirks.grid_single_line {
        GridSingleLine::Middle => None,
        // quirk: GridSingleLine::PartsRounded (src/quirks.rs)
        GridSingleLine::PartsRounded => {
            let ties = if in_fixed_points(pitch) {
                Rounding::HalfUp
            } else {
                Rounding::HalfDown
            };
            Some(((device.snap(ascent), device.snap(descent)), ties))
        }
    }
}

/// The outlined inline VML shape `shape`, on a target where each outlined rectangle, oval and
/// rounded rectangle, with or without an anchor lock, takes the room of its outline across and
/// down on lines with or without text (`VmlObjectSize::TakesStrokeRoom`). `None` where only a
/// rectangle with an anchor lock on a line without text does, or no shape.
pub(in crate::layout) fn outline_stroke_room<T>(quirks: &Quirks, shape: T) -> Option<T> {
    match quirks.vml_object_size {
        VmlObjectSize::TakesStyleSize | VmlObjectSize::TakesAnchorStrokeRoom => None,
        // quirk: VmlObjectSize::TakesStrokeRoom (src/quirks.rs)
        VmlObjectSize::TakesStrokeRoom => Some(shape),
    }
}

/// The run's character style and direct properties for layout ([`Run::character_style`],
/// [`Run::direct_props`]): a computed field's value and a check box take the format of the
/// field's code run where the target says so (`ComputedFieldFormat::CodeRun`), and a page number
/// or page count drops its underline, strikethrough and highlight where it says so
/// (`ComputedFieldDecorations::Dropped`).
pub(in crate::layout) fn run_format<'r>(
    quirks: &Quirks,
    run: &'r Run,
) -> (Option<&'r str>, Cow<'r, RunProps>) {
    // quirk: ComputedFieldFormat::CodeRun (src/quirks.rs)
    let code_format = match quirks.computed_field_format {
        ComputedFieldFormat::ResultRun => false,
        ComputedFieldFormat::CodeRun => true,
    };
    // quirk: ComputedFieldDecorations::Dropped (src/quirks.rs)
    let page_decorations = match quirks.computed_field_decorations {
        ComputedFieldDecorations::Drawn => true,
        ComputedFieldDecorations::Dropped => false,
    };
    (
        run.character_style(code_format),
        run.direct_props(code_format, page_decorations),
    )
}

/// What the shape of a table takes from the target: how its first cell sets its grid, how wide
/// the columns of a table with cell spacing are, which room the line between two rows takes,
/// what a merged cell takes over its rows, and which borders its outer cells and its style
/// regions give. It keeps the target's quirks, and each method gives one decision.
#[derive(Clone, Copy, Debug)]
pub(in crate::layout) struct TableRules(Quirks);

impl TableRules {
    /// The rules of the target whose resolved quirks are `quirks`.
    pub(in crate::layout) const fn of(quirks: &Quirks) -> Self {
        Self(*quirks)
    }

    /// The cell spacing `spacing` of a table of fixed layout, where its columns take the widths
    /// of their cells with the spacing beside them (`SpacedColumns::CellWidths`). `None` where
    /// they keep the grid's widths.
    pub(in crate::layout) fn cell_width_spacing<T>(self, spacing: Option<T>) -> Option<T> {
        match self.0.spaced_columns {
            SpacedColumns::Grid => None,
            // quirk: SpacedColumns::CellWidths (src/quirks.rs)
            SpacedColumns::CellWidths => spacing,
        }
    }

    /// The table's own top and bottom lines, `lines`, with which each page's part of a table
    /// with cell spacing opens at a page's top and closes at a page's foot where the table goes
    /// on to another page, as a table of its own (`SpacedTableBreaks::AroundPagePart`); either
    /// is `None` where the table has no such line. `None` where the target draws the table's
    /// outline around the whole table only.
    pub(in crate::layout) fn page_part_lines(
        self,
        lines: (Option<Border>, Option<Border>),
    ) -> Option<(Option<Border>, Option<Border>)> {
        match self.0.spaced_table_breaks {
            SpacedTableBreaks::AroundTable => None,
            // quirk: SpacedTableBreaks::AroundPagePart (src/quirks.rs)
            SpacedTableBreaks::AroundPagePart => Some(lines),
        }
    }

    /// The margin of a left or right side of a cell that no cell, row, table or table style
    /// sets, where the target gives such a side the default margin and places the cell as one
    /// whose margins are set (`UnsetCellMargins::DefaultSides`). `None` where the side has no
    /// margin and the text starts after the cell's left line.
    pub(in crate::layout) fn unset_side_margin(self) -> Option<Length> {
        match self.0.unset_cell_margins {
            UnsetCellMargins::AfterLeftLine => None,
            // quirk: UnsetCellMargins::DefaultSides (src/quirks.rs)
            UnsetCellMargins::DefaultSides => Some(params::UNSET_SIDE_MARGIN),
        }
    }

    /// The column widths that `cells` gives a table of automatic layout from its cells, where
    /// they disagree with its saved grid and fit its room (`AutofitGrid::FittingCells`). `None`
    /// where the table keeps its saved grid.
    pub(in crate::layout) fn fitting_cells<T>(
        self,
        cells: impl FnOnce() -> Option<T>,
    ) -> Option<T> {
        match self.0.autofit_grid {
            AutofitGrid::Saved => None,
            // quirk: AutofitGrid::FittingCells (src/quirks.rs)
            AutofitGrid::FittingCells => cells(),
        }
    }

    /// A table's first cell `cell`, with cell spacing (`spaced`) or without, where an explicit
    /// indent fixes the start of that cell's text: with spacing under
    /// `TableIndent::SpacedTextStart` only. `None` where the indent fixes the grid instead.
    pub(in crate::layout) fn fixed_text_start<T>(self, cell: T, spaced: bool) -> Option<T> {
        // quirk: TableIndent::SpacedTextStart (src/quirks.rs)
        self.0.table_indent.fixes_text_start(spaced).then_some(cell)
    }

    /// What `lines` gives from the cells of a right-to-left table, how far it lies from its place
    /// from the edge-aligned mode on, where the target places it by the lines of its first and
    /// last cell (`RightToLeftEdge::LeadingAndInside`): in the text at its leading edge, in by
    /// half the first cell's line at the leading edge plus half the last cell's line that the
    /// file calls left; floating at an offset, left by half the last cell's line alone. `None`
    /// where it lies by half the line between its first two cells, as a table from the left
    /// does.
    pub(in crate::layout) fn leading_and_inside<T>(self, lines: impl FnOnce() -> T) -> Option<T> {
        match self.0.right_to_left_edge {
            RightToLeftEdge::BetweenCells => None,
            // quirk: RightToLeftEdge::LeadingAndInside (src/quirks.rs)
            RightToLeftEdge::LeadingAndInside => Some(lines()),
        }
    }

    /// What `from_cells` gives from the bottom lines of every cell above a cell below several
    /// cells, the room of the line between the two rows or the parts in which it is drawn, where
    /// each cell above draws its own bottom line along its width (`RowLineRoom::CellsAbove`).
    /// `None` where the cell takes the line of the cell above its first grid column.
    pub(in crate::layout) fn cells_above<T>(self, from_cells: impl FnOnce() -> T) -> Option<T> {
        match self.0.row_line_room {
            RowLineRoom::FirstColumn => None,
            // quirk: RowLineRoom::CellsAbove (src/quirks.rs)
            RowLineRoom::CellsAbove => Some(from_cells()),
        }
    }

    /// The room `room` of the line above a cell that goes on with a merged cell, which its row
    /// takes where the target gives it the room of the undrawn line (`MergedTopRoom::UndrawnLine`).
    /// `None` where it takes no room.
    pub(in crate::layout) fn merged_top_room<T>(self, room: T) -> Option<T> {
        match self.0.merged_top_room {
            MergedTopRoom::NoRoom => None,
            // quirk: MergedTopRoom::UndrawnLine (src/quirks.rs)
            MergedTopRoom::UndrawnLine => Some(room),
        }
    }

    /// The fill that `first` gives a cell that goes on with a merged cell, from the merged
    /// cell's first cell, where the target draws that fill over all its rows
    /// (`MergedCellFill::FirstCell`). `None` where each row draws its own.
    pub(in crate::layout) fn first_cell_fill<T>(self, first: impl FnOnce() -> T) -> Option<T> {
        match self.0.merged_cell_fill {
            MergedCellFill::EachRow => None,
            // quirk: MergedCellFill::FirstCell (src/quirks.rs)
            MergedCellFill::FirstCell => Some(first()),
        }
    }

    /// Whether the cell is its row's first and last cell, which `ends` gives, where the row's
    /// end cells take the table's outer borders too (`RowEndBorders::RowEnds`). `None` where
    /// only the cells at the grid's edges take them.
    pub(in crate::layout) fn row_end_cells<T>(self, ends: impl FnOnce() -> T) -> Option<T> {
        match self.0.row_end_borders {
            RowEndBorders::GridEdges => None,
            // quirk: RowEndBorders::RowEnds (src/quirks.rs)
            RowEndBorders::RowEnds => Some(ends()),
        }
    }

    /// The sides that `blocks` gives a cell from a style region's borders, drawn around the
    /// region's block of cells, where the target draws them so (`StyleRegionBorders::Blocks`).
    /// `None` where each cell takes the region's borders.
    pub(in crate::layout) fn block_sides<T>(self, blocks: impl FnOnce() -> T) -> Option<T> {
        match self.0.style_region_borders {
            StyleRegionBorders::EachCell => None,
            // quirk: StyleRegionBorders::Blocks (src/quirks.rs)
            StyleRegionBorders::Blocks => Some(blocks()),
        }
    }

    /// The side `border` of a table or a cell as the table takes it, for its lines and for the
    /// room that it takes: with its line cut to whole twips before its lines and gaps are taken
    /// from it where the target holds a border's width in whole twips
    /// (`BorderWidthUnit::WholeTwips`), as it holds a paragraph border's.
    pub(in crate::layout) fn table_border(self, border: Border) -> Border {
        match self.0.border_width_unit {
            BorderWidthUnit::EighthPoints => border,
            // quirk: BorderWidthUnit::WholeTwips (src/quirks.rs)
            BorderWidthUnit::WholeTwips => border.in_whole_twips(),
        }
    }
}

/// The content `merges` of the merged cells that a row ends or keeps open, which the target
/// aligns in their part on the page (`SplitMergeAlign::PagePart`). `None` where it aligns them
/// in their whole cell.
pub(in crate::layout) fn page_part_merges<T>(quirks: &Quirks, merges: T) -> Option<T> {
    match quirks.split_merge_align {
        SplitMergeAlign::WholeCell => None,
        // quirk: SplitMergeAlign::PagePart (src/quirks.rs)
        SplitMergeAlign::PagePart => Some(merges),
    }
}

/// The cell margin that a row of an exact height adds to it, of a cell's `top` and `bottom`
/// margins (`ExactRowMargin`).
pub(in crate::layout) fn exact_row_margin<T>(quirks: &Quirks, (top, bottom): (T, T)) -> T {
    match quirks.exact_row_margin {
        // quirk: ExactRowMargin (src/quirks.rs)
        ExactRowMargin::AddsTopMargin => top,
        ExactRowMargin::AddsBottomMargin => bottom,
    }
}

/// What `above` gives a row below header rows that repeat, which takes the room of the line
/// between it and the last header row where the target says so (`RowBelowHeaders::LastHeader`).
/// `None` where it keeps the room of the row before it in the table.
pub(in crate::layout) fn last_header_above<T>(
    quirks: &Quirks,
    above: impl FnOnce() -> T,
) -> Option<T> {
    match quirks.row_below_headers {
        RowBelowHeaders::RowBefore => None,
        // quirk: RowBelowHeaders::LastHeader (src/quirks.rs)
        RowBelowHeaders::LastHeader => Some(above()),
    }
}

/// The left and right x of a cell's fill that `inside` gives inside its side lines, where the
/// target fills a cell so (`CellFillSides::InsideLines`). `None` where it fills between the
/// grid lines.
pub(in crate::layout) fn fill_inside_lines<T>(
    quirks: &Quirks,
    inside: impl FnOnce() -> T,
) -> Option<T> {
    match quirks.cell_fill_sides {
        CellFillSides::GridLines => None,
        // quirk: CellFillSides::InsideLines (src/quirks.rs)
        CellFillSides::InsideLines => Some(inside()),
    }
}

/// A cell fill's top or bottom at `place`: moved to the nearest device dot by `snap` where the
/// target puts it there (`CellFillRows::WholeDots`), else the place itself.
pub(in crate::layout) fn fill_row_edge(
    quirks: &Quirks,
    place: Length,
    snap: impl FnOnce(Length) -> Length,
) -> Length {
    match quirks.cell_fill_rows {
        CellFillRows::Exact => place,
        // quirk: CellFillRows::WholeDots (src/quirks.rs)
        CellFillRows::WholeDots => snap(place),
    }
}

/// The top and the bottom of the band of a filled cell's top margin, for a cell that continues
/// a merged region from the row above (`merged_above`) on the same page (`joined_above`) or
/// not: `below_margin`, from the content's top down by the margin, for a cell that continues no
/// region, or, where the target paints it from the cell's top line
/// (`CellTopBand::FromLineEdge`), `from_line`, from the line's drawn lower edge, for each cell
/// that has a top line of its own, also one that continues a region at the top of a page, and
/// else `below_margin` for a cell that joins no cell above. `None` where the target paints no
/// band.
pub(in crate::layout) fn top_band_rows(
    quirks: &Quirks,
    (merged_above, joined_above): (bool, bool),
    below_margin: impl FnOnce() -> Option<(Length, Length)>,
    from_line: impl FnOnce() -> Option<(Length, Length)>,
) -> Option<(Length, Length)> {
    match quirks.cell_top_band {
        CellTopBand::BelowMargin => (!merged_above).then(below_margin).flatten(),
        // quirk: CellTopBand::FromLineEdge (src/quirks.rs)
        CellTopBand::FromLineEdge if joined_above => None,
        CellTopBand::FromLineEdge => match from_line() {
            Some((top, bottom)) => (top < bottom).then_some((top, bottom)),
            None => below_margin(),
        },
    }
}

/// The open merged cell `open` whose lines move from its aligned top, each by its own place,
/// where the target moves them so (`MergedCellLines::FromAlignedTop`). `None` where they move
/// as one block.
pub(in crate::layout) fn lines_from_aligned_top<T>(quirks: &Quirks, open: T) -> Option<T> {
    match quirks.merged_cell_lines {
        MergedCellLines::MovedAsBlock => None,
        // quirk: MergedCellLines::FromAlignedTop (src/quirks.rs)
        MergedCellLines::FromAlignedTop => Some(open),
    }
}

/// The list `list` of a cell's last paragraph whose automatic space after stays at the cell's
/// end, where the target keeps it (`CellEndListSpace::Kept`). `None` where it drops it.
pub(in crate::layout) fn kept_list_space<T>(quirks: &Quirks, list: Option<T>) -> Option<T> {
    match quirks.cell_end_list_space {
        CellEndListSpace::Dropped => None,
        // quirk: CellEndListSpace::Kept (src/quirks.rs)
        CellEndListSpace::Kept => list,
    }
}

/// Whether a row of a nested table fits by its minimum height, which `fits` gives, where such
/// a row moves whole when its minimum does not fit, as a row of the body does
/// (`NestedRowMinimum::MovesWhole`). `None` where it splits wherever it stands.
pub(in crate::layout) fn whole_nested_rows<T>(
    quirks: &Quirks,
    fits: impl FnOnce() -> T,
) -> Option<T> {
    match quirks.nested_row_minimum {
        NestedRowMinimum::Splits => None,
        // quirk: NestedRowMinimum::MovesWhole (src/quirks.rs)
        NestedRowMinimum::MovesWhole => Some(fits()),
    }
}

/// How far the content of a merged cell that a row carries to the next page moves there, for
/// its exact move `exact`: that move, or that move rounded to the device's dots
/// (`CarriedMergeMove::ToDot`).
pub(in crate::layout) fn carried_merge_move(
    quirks: &Quirks,
    device: &Device,
    exact: Length,
) -> Length {
    match quirks.carried_merge_move {
        CarriedMergeMove::Exact => exact,
        // quirk: CarriedMergeMove::ToDot (src/quirks.rs)
        CarriedMergeMove::ToDot => device.snap(exact),
    }
}

/// How far a floating table placed at an offset across lies left of that offset: one twip
/// under `FloatingTableLeft::TwipLeft`, else none.
pub(in crate::layout) fn floating_table_shift_left(quirks: &Quirks) -> Length {
    match quirks.floating_table_left {
        // quirk: FloatingTableLeft::TwipLeft (src/quirks.rs)
        FloatingTableLeft::TwipLeft => Length::from_units(Length::UNITS_PER_TWIP),
        FloatingTableLeft::AtOffset => Length::ZERO,
    }
}

/// How far a floating table placed from `anchor` at an offset down lies above that offset: one
/// twip from the page or the margin under `FloatingTableTop::TwipHigher`, else none.
pub(in crate::layout) fn floating_table_rise(quirks: &Quirks, anchor: Anchor) -> Length {
    match (quirks.floating_table_top, anchor) {
        // quirk: FloatingTableTop::TwipHigher (src/quirks.rs)
        (FloatingTableTop::TwipHigher, Anchor::Page | Anchor::Margin) => {
            Length::from_units(Length::UNITS_PER_TWIP)
        }
        _ => Length::ZERO,
    }
}

/// Whether a floating table breaks across pages, which `breaks` gives from where it stands, on
/// a target whose floating tables break so (`FloatingTableBreaks::AcrossPages`). `None` where
/// they stay whole.
pub(in crate::layout) fn floating_breaks<T>(
    quirks: &Quirks,
    breaks: impl FnOnce() -> T,
) -> Option<T> {
    match quirks.floating_table_breaks {
        FloatingTableBreaks::Whole => None,
        // quirk: FloatingTableBreaks::AcrossPages (src/quirks.rs)
        FloatingTableBreaks::AcrossPages => Some(breaks()),
    }
}

/// The left edge of a floating drawing anchored in a table cell, `width` wide, that its place
/// puts at `x`: where the target keeps a drawing that wraps text inside its cell
/// (`CellDrawingBounds::InsideCell`) and the drawing `wraps`, moved inside the cell's `sides`,
/// the inner edges of its side lines, its left edge winning when it is wider than the cell;
/// else `x`.
pub(in crate::layout) fn cell_drawing_left(
    quirks: &Quirks,
    (x, width): (Length, Length),
    (sides, wraps): ((Length, Length), bool),
) -> Length {
    match quirks.cell_drawing_bounds {
        // quirk: CellDrawingBounds::InsideCell (src/quirks.rs)
        CellDrawingBounds::InsideCell if wraps => x.min(sides.1 - width).max(sides.0),
        CellDrawingBounds::Unbounded | CellDrawingBounds::InsideCell => x,
    }
}

/// The top of a floating drawing anchored in a table cell that its place puts at `y`: where
/// the target keeps a drawing that wraps text inside its cell
/// (`CellDrawingBounds::InsideCell`) and the drawing `wraps`, not above the cell's text top
/// `cell_top`; else `y`.
pub(in crate::layout) fn cell_drawing_top(
    quirks: &Quirks,
    y: Length,
    (cell_top, wraps): (Length, bool),
) -> Length {
    match quirks.cell_drawing_bounds {
        // quirk: CellDrawingBounds::InsideCell (src/quirks.rs)
        CellDrawingBounds::InsideCell if wraps => y.max(cell_top),
        CellDrawingBounds::Unbounded | CellDrawingBounds::InsideCell => y,
    }
}

/// Whether a floating drawing anchored in a table cell and aligned down from the margins lies
/// at the cell's text top whatever its alignment (`CellDrawingBounds::InsideCell`), rather
/// than aligned in the area of the margins.
pub(in crate::layout) const fn aligns_at_cell_top(quirks: &Quirks) -> bool {
    match quirks.cell_drawing_bounds {
        CellDrawingBounds::Unbounded => false,
        // quirk: CellDrawingBounds::InsideCell (src/quirks.rs)
        CellDrawingBounds::InsideCell => true,
    }
}

/// The cells `cells` whose content the target clips inside their lines
/// (`CellClip::InsideLines`). `None` where it draws their content unclipped.
pub(in crate::layout) fn clipped_cells<T>(quirks: &Quirks, cells: T) -> Option<T> {
    match quirks.cell_clip {
        CellClip::Unclipped => None,
        // quirk: CellClip::InsideLines (src/quirks.rs)
        CellClip::InsideLines => Some(cells),
    }
}

/// The dashes `dash` of a table's border line, which the target draws where it draws the lines
/// of a dash style as their dashes (`BorderDashes::DashesCellPieces`). `None` where it draws
/// them solid.
pub(in crate::layout) fn table_dash<T>(quirks: &Quirks, dash: Option<T>) -> Option<T> {
    match quirks.border_dashes {
        BorderDashes::DrawsSolid => None,
        // quirk: BorderDashes::DashesCellPieces (src/quirks.rs)
        BorderDashes::DashesCellPieces => dash,
    }
}

/// The cuts `cuts` of a table's dashed lines across where they pass from one cell to the next
/// with no line down between them, which the target makes so that the dashes start again in
/// each cell (`BorderDashes::DashesCellPieces`). `None` where it draws the lines solid.
pub(in crate::layout) fn cell_dash_cuts<T>(quirks: &Quirks, cuts: T) -> Option<T> {
    match quirks.border_dashes {
        BorderDashes::DrawsSolid => None,
        // quirk: BorderDashes::DashesCellPieces (src/quirks.rs)
        BorderDashes::DashesCellPieces => Some(cuts),
    }
}

/// The limit `later` of the later parts of a cell that splits over pages, which the target
/// applies once the cell has a later part (`LaterPartWidows::Applied`). `None` where it ignores
/// it.
pub(in crate::layout) fn later_part_limit<T>(quirks: &Quirks, later: T) -> Option<T> {
    match quirks.later_part_widows {
        LaterPartWidows::Ignored => None,
        // quirk: LaterPartWidows::Applied (src/quirks.rs)
        LaterPartWidows::Applied => Some(later),
    }
}

/// The edges `part` of a part of a row that splits between pages, which the target fills as
/// a whole row (`SplitRowFills::EachPart`). `None` where it leaves the parts unfilled.
pub(in crate::layout) fn split_part_fills<T>(quirks: &Quirks, part: T) -> Option<T> {
    match quirks.split_row_fills {
        SplitRowFills::Unfilled => None,
        // quirk: SplitRowFills::EachPart (src/quirks.rs)
        SplitRowFills::EachPart => Some(part),
    }
}

/// What `cut` gives an inline picture to show nothing outside of, on a target that cuts such a
/// picture (`InlinePictureClip::LineBox`): the box of its line, or the text area of the text box
/// or the frame that holds its line. `None` where the picture shows whole.
pub(in crate::layout) fn inline_picture_cut<T>(
    quirks: &Quirks,
    cut: impl FnOnce() -> Option<T>,
) -> Option<T> {
    match quirks.inline_picture_clip {
        InlinePictureClip::Unknown => None,
        // quirk: InlinePictureClip::LineBox (src/quirks.rs)
        InlinePictureClip::LineBox => cut(),
    }
}

/// The line around a picture that `line` gives, on a target that draws it wholly outside the
/// picture's box (`PictureLinePlace::Outside`). `None` where the picture has no line.
pub(in crate::layout) fn picture_line<T>(
    quirks: &Quirks,
    line: impl FnOnce() -> Option<T>,
) -> Option<T> {
    match quirks.picture_line_place {
        PictureLinePlace::Undrawn => None,
        // quirk: PictureLinePlace::Outside (src/quirks.rs)
        PictureLinePlace::Outside => line(),
    }
}

/// The distance from the reference point of a line of metafile text aligned at its top down to
/// its baseline: `font_units`, the face's ascent in font units at the em on the page
/// (`MetafileTopAscent::FontUnits`), or `logical_pixels`, its pixel ascent at the font's size
/// in whole logical units times the logical unit (`MetafileTopAscent::LogicalPixels`), where
/// the font has an em height and the face pixel heights at that size.
pub(in crate::layout) fn metafile_top_ascent(
    quirks: &Quirks,
    font_units: impl FnOnce() -> i64,
    logical_pixels: impl FnOnce() -> Option<i64>,
) -> i64 {
    match quirks.metafile_top_ascent {
        MetafileTopAscent::FontUnits => font_units(),
        // quirk: MetafileTopAscent::LogicalPixels (src/quirks.rs)
        MetafileTopAscent::LogicalPixels => logical_pixels().unwrap_or_else(font_units),
    }
}

/// The rule that places the plot area of the drawn chart `chart` on the target, or `None` where
/// the target does not draw it ([`PlotRules::rule`]).
pub(in crate::layout) fn chart_plot_rule(quirks: &Quirks, chart: &Columns) -> Option<PlotRule> {
    // quirk: ChartPlotArea (src/quirks.rs)
    PlotRules::of(quirks).rule(chart).ok()
}

/// The value axis and the plot area of a chart whose plot area comes from its labels' lines,
/// from `fitted`, the axis of its values and its plot area: on a target whose automatic axis
/// takes as many units as the labels' lines leave room for (`ChartAxisRoom::LabelLines`),
/// those that `roomed` gives for `fitted`, and `fitted` elsewhere.
pub(in crate::layout) fn chart_axis_room<T>(
    quirks: &Quirks,
    fitted: T,
    roomed: impl FnOnce(T) -> Option<T>,
) -> Option<T> {
    match quirks.chart_axis_room {
        ChartAxisRoom::Values => Some(fitted),
        // quirk: ChartAxisRoom::LabelLines (src/quirks.rs)
        ChartAxisRoom::LabelLines => roomed(fitted),
    }
}

/// Whether a chart of lines or of scatter points paints the line of its axis across the bottom
/// before its series' lines and markers (`ChartAxisOrder::BeforeLines`), rather than after
/// them as a column chart does.
pub(in crate::layout) const fn chart_axis_before_lines(quirks: &Quirks) -> bool {
    match quirks.chart_axis_order {
        ChartAxisOrder::Unknown => false,
        // quirk: ChartAxisOrder::BeforeLines (src/quirks.rs)
        ChartAxisOrder::BeforeLines => true,
    }
}

/// Whether a line chart's series lines show only inside the clip of a scatter chart's series
/// lines (`ChartLineClip::PlotArea`), rather than unclipped.
pub(in crate::layout) const fn chart_line_clip(quirks: &Quirks) -> bool {
    match quirks.chart_line_clip {
        ChartLineClip::Unknown => false,
        // quirk: ChartLineClip::PlotArea (src/quirks.rs)
        ChartLineClip::PlotArea => true,
    }
}

/// The data labels that show a drawn clustered column chart's values, which `drawn` places at the
/// outer end of their bars, on a target that draws them (`ChartDataLabels::OuterEnd`); `None`
/// where the target leaves them out, and the chart is drawn without them, with a warning.
pub(in crate::layout) fn chart_data_labels<T>(
    quirks: &Quirks,
    drawn: impl FnOnce() -> Option<T>,
) -> Option<T> {
    match quirks.chart_data_labels {
        ChartDataLabels::LeftOut => None,
        // quirk: ChartDataLabels::OuterEnd (src/quirks.rs)
        ChartDataLabels::OuterEnd => drawn(),
    }
}

/// Whether a drawing placed down from its line (`from_line`, which is evaluated only there)
/// waits for that line, where the target counts it from the line's top
/// (`FromLine::LineTop`). `None` where it counts from the paragraph's top.
pub(in crate::layout) fn line_top_drawing<T>(
    quirks: &Quirks,
    from_line: impl FnOnce() -> T,
) -> Option<T> {
    match quirks.from_line {
        // quirk: FromLine::LineTop (src/quirks.rs)
        FromLine::LineTop => Some(from_line()),
        FromLine::ParagraphTop => None,
    }
}

/// The height of a drawing of `height` that the band of its wrap takes below the drawing's top:
/// all of it, or the whole twips of it (`BandHeight::WholeTwips`).
pub(in crate::layout) fn band_height(quirks: &Quirks, height: Length) -> Length {
    match quirks.band_height {
        BandHeight::Exact => height,
        // quirk: BandHeight::WholeTwips (src/quirks.rs)
        BandHeight::WholeTwips => height.toward_zero_whole(Length::UNITS_PER_TWIP),
    }
}

/// The wrap polygon `polygon` of a drawing beside which a line without room goes down in steps
/// of its height, where the target steps it (`BlockedLines::LineSteps`). `None` where the line
/// goes below the drawing's box.
pub(in crate::layout) fn stepped_lines<T>(quirks: &Quirks, polygon: T) -> Option<T> {
    match quirks.blocked_lines {
        BlockedLines::BelowBox => None,
        // quirk: BlockedLines::LineSteps (src/quirks.rs)
        BlockedLines::LineSteps => Some(polygon),
    }
}

/// The outline `outline` of a tight or through wrap's polygon that is not a rectangle, which a
/// line meets on its band where the target follows it (`PolygonWrap::Outline`). `None` where
/// the line meets the polygon's bounds.
pub(in crate::layout) fn wrap_outline<T>(quirks: &Quirks, outline: T) -> Option<T> {
    match quirks.polygon_wrap {
        PolygonWrap::Bounds => None,
        // quirk: PolygonWrap::Outline (src/quirks.rs)
        PolygonWrap::Outline => Some(outline),
    }
}

/// The height of the band down from a line's top over which it meets wraps beside which text
/// flows: its height `height`, or under automatic multiple spacing above single spacing its
/// single line `single` where the target tests that (`LineWrapBand::SingleLine`).
pub(in crate::layout) fn line_wrap_band(
    quirks: &Quirks,
    (height, single): (Length, Length),
) -> Length {
    match quirks.line_wrap_band {
        LineWrapBand::WholeLine => height,
        // quirk: LineWrapBand::SingleLine (src/quirks.rs)
        LineWrapBand::SingleLine => single.min(height),
    }
}

/// How far a line without room beside a tight or through wrap goes down from its own top in
/// steps of `step`, when the wrap's bottom lies `room` below that top: the least whole number of
/// steps that reaches the bottom, or that passes it where a step on the bottom still meets the
/// wrap (`StepEnd::PastBottom`).
pub(in crate::layout) fn step_end(quirks: &Quirks, room: Length, step: Length) -> Length {
    match quirks.step_end {
        StepEnd::AtBottom => room.up_to_whole(step.units()),
        // quirk: StepEnd::PastBottom (src/quirks.rs)
        StepEnd::PastBottom => (room + Length::from_units(1)).up_to_whole(step.units()),
    }
}

/// Whether a paragraph forecasts its widow break again from a line where a drawing beside it
/// breaks the rest of its lines again (`WidowForecast::AsWrapped`); otherwise the forecast of
/// the paragraph's start, from the lines at the column's whole width, stays.
pub(in crate::layout) fn widows_as_wrapped(quirks: &Quirks) -> bool {
    match quirks.widow_forecast {
        WidowForecast::WholeWidth => false,
        // quirk: WidowForecast::AsWrapped (src/quirks.rs)
        WidowForecast::AsWrapped => true,
    }
}

/// The text `text` of a text box, cut inside its outline by `cut` where the target cuts it
/// (`TextBoxClip::InsideOutline`), and as it is where the text overflows.
pub(in crate::layout) fn outline_clip<T>(quirks: &Quirks, text: T, cut: impl FnOnce(T) -> T) -> T {
    match quirks.text_box_clip {
        // quirk: TextBoxClip::InsideOutline (src/quirks.rs)
        TextBoxClip::InsideOutline => cut(text),
        TextBoxClip::Overflow => text,
    }
}

/// The section `section` of a text box's text, without its columns where the target lays out a
/// box's text in one column (`TextBoxColumns::OneColumn`).
pub(in crate::layout) fn text_box_section(
    quirks: &Quirks,
    mut section: crate::body::Section,
) -> crate::body::Section {
    // quirk: TextBoxColumns::OneColumn (src/quirks.rs)
    if quirks.text_box_columns == TextBoxColumns::OneColumn {
        section.columns = crate::body::Columns::default();
    }
    section
}

/// The offset below its top of the baseline of a line of SmartArt text of automatic spacing below
/// single spacing, whose height is `height`, whose text has the descent `descent`, and whose
/// spacing puts its baseline `baseline` below its top, as in Word's own text: under
/// `SmartArtLowSpacing::ScaledAscent` that baseline, and under `SmartArtLowSpacing::FullDescent`
/// the height less the full descent.
pub(in crate::layout) fn smartart_low_baseline(
    quirks: &Quirks,
    (height, descent): (Length, Length),
    baseline: Length,
) -> Length {
    match quirks.smartart_low_spacing {
        // quirk: SmartArtLowSpacing::ScaledAscent (src/quirks.rs)
        SmartArtLowSpacing::ScaledAscent => baseline,
        // quirk: SmartArtLowSpacing::FullDescent (src/quirks.rs)
        SmartArtLowSpacing::FullDescent => height - descent,
    }
}

/// How far the last line of a DrawingML text box's text moves down from the place of its spacing,
/// from `lines`, the records of the box's lines, and the box's exact top `box_top`, its `height`
/// and its bottom inset `bottom`: none under `BoxLastLine::Spaced`, and none unless every line of
/// the box lies outside tables, in single spacing without space before or after, the last line is
/// of the form [`super::BaselineForm::SingleTop`] or [`super::BaselineForm::SingleBottom`] and
/// room lies below it. Under `BoxLastLine::RoomBelow` the last line sits below its rounded top
/// (the exact top rounded to the nearest dot) by the larger of
/// its exact ascent, rounded, and its bottom less its rounded descent: its bottom lies the
/// rounded sum of its exact height and the room below it less that room rounded below its top,
/// and the room runs to the box's text top ([`box_text_top`]) with the height cut to whole
/// twips, less the bottom inset.
pub(in crate::layout) fn box_last_line_drop(
    quirks: &Quirks,
    device: &Device,
    lines: &[super::PlacedLine],
    (box_top, height, bottom): (Length, Length, Length),
) -> Length {
    match quirks.box_last_line {
        BoxLastLine::Spaced => Length::ZERO,
        // quirk: BoxLastLine::RoomBelow (src/quirks.rs)
        BoxLastLine::RoomBelow => {
            let Some(line) = lines.last() else {
                return Length::ZERO;
            };
            let single = line.ascent + line.descent;
            let text_bottom = box_text_top(quirks, box_top)
                + height.down_to_whole(Length::UNITS_PER_TWIP)
                - bottom;
            let room = text_bottom - (line.top + single);
            let single_spaced = |line: &super::PlacedLine| {
                line.area == super::LineArea::OutsideTables
                    && line.spacing == LineSpacing::SINGLE
                    && line.before == Length::ZERO
                    && !line.spaced
            };
            if !lines.iter().all(single_spaced) || room < Length::ZERO {
                return Length::ZERO;
            }
            // Where the spacing puts the baseline below the line's rounded top.
            let spaced = match line.baseline_form {
                super::BaselineForm::SingleTop => {
                    device.rounded_down_baseline((line.ascent, line.descent), single, false)
                }
                super::BaselineForm::SingleBottom => {
                    line.top + line.baseline - device.snap(line.top)
                }
                _ => return Length::ZERO,
            };
            let line_bottom = device.snap(single + room) - device.snap(room);
            let offset = device
                .snap(line.ascent)
                .max(line_bottom - device.snap(line.descent));
            offset - spaced
        }
    }
}

/// How far inside the left edge of a DrawingML text box its text keeps its left inset, from
/// `half_outline`, the exact half of the outline's width: that half cut to whole twips under
/// `BoxOutlineLeft::WholeTwipsHalf`.
pub(in crate::layout) fn box_outline_left(quirks: &Quirks, half_outline: Length) -> Length {
    match quirks.box_outline_left {
        // quirk: BoxOutlineLeft::WholeTwipsHalf (src/quirks.rs)
        BoxOutlineLeft::WholeTwipsHalf => half_outline.down_to_whole(Length::UNITS_PER_TWIP),
        BoxOutlineLeft::ExactHalf => half_outline,
    }
}

/// The top that the text of a DrawingML text box counts its top inset from, from the box's
/// exact top `box_top`: that top rounded to the nearest whole twip under
/// `BoxTextTop::NearestTwipTop`.
pub(in crate::layout) fn box_text_top(quirks: &Quirks, box_top: Length) -> Length {
    match quirks.box_text_top {
        // quirk: BoxTextTop::NearestTwipTop (src/quirks.rs)
        BoxTextTop::NearestTwipTop => box_top.nearest_whole(Length::UNITS_PER_TWIP),
        BoxTextTop::ExactTop => box_top,
    }
}

/// How far below the top edge of a DrawingML text box's outline its text keeps its top inset,
/// from `half_outline`, the exact half of the outline's width: that half cut to whole twips
/// under `BoxTextTop::NearestTwipTop`.
pub(in crate::layout) fn box_outline_top(quirks: &Quirks, half_outline: Length) -> Length {
    match quirks.box_text_top {
        // quirk: BoxTextTop::NearestTwipTop (src/quirks.rs)
        BoxTextTop::NearestTwipTop => half_outline.down_to_whole(Length::UNITS_PER_TWIP),
        BoxTextTop::ExactTop => half_outline,
    }
}

/// The insets of a VML text box's text from the edges of its box, from its own `insets` and
/// the width of its `outline`: inside the outline under `VmlBoxOutline::InsideRoundedHalf`,
/// half the width rounded up to whole twips at the left and top and the rest at the right and
/// bottom, and else from the outline's middle.
pub(in crate::layout) fn vml_box_insets(
    quirks: &Quirks,
    insets: Edges<Length>,
    outline: Length,
) -> Edges<Length> {
    match quirks.vml_box_outline {
        // quirk: VmlBoxOutline::InsideRoundedHalf (src/quirks.rs)
        VmlBoxOutline::InsideRoundedHalf => {
            let lead = outline
                .up_to_whole(2 * Length::UNITS_PER_TWIP)
                .div_toward_zero(2);
            let rest = outline - lead;
            Edges {
                top: insets.top + lead,
                right: insets.right + rest,
                bottom: insets.bottom + rest,
                left: insets.left + lead,
            }
        }
        VmlBoxOutline::Middle => insets,
    }
}

/// How far a frame placed at an offset across lies left of that offset: a twip under
/// `FrameLeft::TwipLeft`.
pub(in crate::layout) fn frame_shift_left(quirks: &Quirks) -> Length {
    match quirks.frame_left {
        // quirk: FrameLeft::TwipLeft (src/quirks.rs)
        FrameLeft::TwipLeft => Length::from_units(Length::UNITS_PER_TWIP),
        FrameLeft::AtOffset => Length::ZERO,
    }
}

/// How much wider than its line a frame without a width that holds one line is: half a twip
/// under `FrameFittedWidth::HalfTwipWider`.
pub(in crate::layout) fn frame_fitted_room(quirks: &Quirks) -> Length {
    match quirks.frame_fitted_width {
        // quirk: FrameFittedWidth::HalfTwipWider (src/quirks.rs)
        FrameFittedWidth::HalfTwipWider => params::FRAME_FITTED_ROOM,
        FrameFittedWidth::Line => Length::ZERO,
    }
}

/// The text of a `STYLEREF` field taken from the page, `text`, as the target shows it: a
/// no-break space as a plain space (`StyleRefNoBreakSpace::Plain`), and without the spaces at
/// its end (`StyleRefTrailingSpaces::Dropped`).
pub(in crate::layout) fn style_ref_text(quirks: &Quirks, text: String) -> String {
    let text = match quirks.style_ref_no_break_space {
        StyleRefNoBreakSpace::Kept => text,
        // quirk: StyleRefNoBreakSpace (src/quirks.rs)
        StyleRefNoBreakSpace::Plain => text.replace('\u{a0}', " "),
    };
    match quirks.style_ref_trailing_spaces {
        StyleRefTrailingSpaces::Kept => text,
        // quirk: StyleRefTrailingSpaces (src/quirks.rs)
        StyleRefTrailingSpaces::Dropped => text.trim_end_matches(' ').to_owned(),
    }
}

/// The advance added by `w:autoSpaceDE` / `w:autoSpaceDN` and the portion stepped on its own in
/// whole dots by the layout device.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(in crate::layout) struct AutoSpace {
    /// Width added to the glyph's advance.
    pub advance: Length,
    /// Width stepped in whole dots on its own by the layout device, or zero when summed into the
    /// glyph's advance before rounding.
    pub extra: Length,
}

/// The space that `w:autoSpaceDE` or `w:autoSpaceDN` adds to the first glyph of an East Asian /
/// Latin or East Asian / digit pair for a face of `size` and `metrics` under `quirks`, where
/// `balanced` is whether `w:balanceSingleByteDoubleByteWidth` is set.
pub(in crate::layout) fn east_asian_auto_space(
    quirks: &Quirks,
    size: Length,
    metrics: &crate::FaceMetrics,
    balanced: bool,
) -> AutoSpace {
    let quarter = size.div_toward_zero(crate::params::EAST_ASIAN_SPACING_PARTS);
    // quirk: EastAsianAutoSpace (src/quirks.rs)
    match quirks.east_asian_auto_space {
        crate::quirks::EastAsianAutoSpace::QuarterEm => AutoSpace {
            advance: quarter,
            extra: Length::ZERO,
        },
        crate::quirks::EastAsianAutoSpace::AverageWidthHalf => {
            let width = if !balanced && !metrics.east_asian && metrics.average_width > 0 {
                let em = i64::from(metrics.units_per_em.max(1));
                let scaled = Length::from_units(f_office_units::div_round(
                    i64::from(metrics.average_width) * size.units(),
                    em,
                ));
                scaled.div_toward_zero(2)
            } else {
                quarter
            };
            AutoSpace {
                advance: width,
                extra: width,
            }
        }
    }
}

/// The paragraph mark `hidden` of a header's or footer's last paragraph, whose space after the
/// target drops where the mark is hidden (`HiddenHeaderFooterEnd::DropsSpaceAfter`). `None`
/// where the paragraph keeps its space after.
pub(in crate::layout) fn dropped_end_space<T>(quirks: &Quirks, hidden: T) -> Option<T> {
    match quirks.hidden_header_footer_end {
        HiddenHeaderFooterEnd::KeepsSpaceAfter => None,
        // quirk: HiddenHeaderFooterEnd::DropsSpaceAfter (src/quirks.rs)
        HiddenHeaderFooterEnd::DropsSpaceAfter => Some(hidden),
    }
}

/// The space before `space` of a paragraph with a page break before it, of which the target
/// keeps the part above the space after of the paragraph before the break
/// (`PageBreakBeforeSpace::AboveSpaceAfter`). `None` where it keeps all of it.
pub(in crate::layout) fn space_above_after<T>(quirks: &Quirks, space: T) -> Option<T> {
    match quirks.page_break_before_space {
        PageBreakBeforeSpace::KeepsSpaceBefore => None,
        // quirk: PageBreakBeforeSpace::AboveSpaceAfter (src/quirks.rs)
        PageBreakBeforeSpace::AboveSpaceAfter => Some(space),
    }
}

/// The room `room` below the body of a page of a section with vertical alignment, in which the
/// body moves down, where `holds_notes` says whether the page holds footnotes: on every page
/// where the target aligns every page (`AlignmentWithNotes::AlignsPage`), and `None` on a page
/// with footnotes where the target keeps its body at the top margin
/// (`AlignmentWithNotes::TopWithNotes`).
pub(in crate::layout) fn aligned_room<T>(quirks: &Quirks, holds_notes: bool, room: T) -> Option<T> {
    match quirks.alignment_with_notes {
        // quirk: AlignmentWithNotes::AlignsPage (src/quirks.rs)
        AlignmentWithNotes::AlignsPage => Some(room),
        // quirk: AlignmentWithNotes::TopWithNotes (src/quirks.rs)
        AlignmentWithNotes::TopWithNotes => (!holds_notes).then_some(room),
    }
}

/// The text of a `DOCPROPERTY` field that shows the custom date property `date`, a time in UTC,
/// with the field's date and time picture `picture`, on a machine whose time zone lies
/// `zone_minutes` east of UTC: the time itself where the target writes it in UTC
/// (`PropertyDateZone::Utc`), whose field without a picture keeps its stored result (`None`), and
/// its local date at midnight where the target writes that (`PropertyDateZone::LocalDate`), as
/// `d/M/yyyy` without a picture.
pub(in crate::layout) fn property_date(
    quirks: &Quirks,
    zone_minutes: i32,
    date: DateTime,
    picture: Option<&str>,
) -> Option<String> {
    match quirks.property_date_zone {
        // quirk: PropertyDateZone::Utc (src/quirks.rs)
        PropertyDateZone::Utc => picture.map(|picture| date.write(picture)),
        // quirk: PropertyDateZone::LocalDate (src/quirks.rs)
        PropertyDateZone::LocalDate => Some(
            date.local_date(zone_minutes)
                .write(picture.unwrap_or(PROPERTY_DATE_PICTURE)),
        ),
    }
}

/// The marks `marks` of the first layout of a section of balanced columns that starts on an
/// earlier page, from which its last page is balanced, where the target balances that page
/// (`LastPageBalance::LastPage`). `None` where only a section on one page is balanced.
pub(in crate::layout) fn balanced_last_page<T>(quirks: &Quirks, marks: T) -> Option<T> {
    match quirks.last_page_balance {
        LastPageBalance::OnePage => None,
        // quirk: LastPageBalance::LastPage (src/quirks.rs)
        LastPageBalance::LastPage => Some(marks),
    }
}

/// Whether the own space before of a paragraph that goes on at the top of the next column
/// goes there, where `at_page_top` says whether that column's top is the top of its page and
/// the target leaves the space out there as at the top of a page
/// (`ColumnTopSpace::GoesAtPageTop`).
pub(in crate::layout) fn column_top_space_goes(quirks: &Quirks, at_page_top: bool) -> bool {
    match quirks.column_top_space {
        ColumnTopSpace::Stays => false,
        // quirk: ColumnTopSpace::GoesAtPageTop (src/quirks.rs)
        ColumnTopSpace::GoesAtPageTop => at_page_top,
    }
}

/// What a table in the flow whose rows all go does at the top of a page, for the space before
/// of the paragraph after it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) enum DeletedTableAtTop {
    /// It is a table without height, after which the paragraph keeps its space before.
    Table,
    /// It is not there: the paragraph has the space before that it would have without it.
    Absent,
    /// It is not there, and the paragraph has no space before, as after a page break.
    TakesSpace,
}

/// What a table in the flow whose rows all go does at the top of a page in a document of the
/// rules `rules`: a table without height (`DeletedTableTop::AsTable`), or, where the target
/// takes the mode's rule (`DeletedTableTop::ByMode`), nothing from the mode of
/// `DELETED_TABLE_TOP_MODE` on and the space before of the paragraph after it before that mode.
pub(in crate::layout) fn deleted_table_at_top(
    quirks: &Quirks,
    rules: ModeRules,
) -> DeletedTableAtTop {
    match quirks.deleted_table_top {
        DeletedTableTop::AsTable => DeletedTableAtTop::Table,
        // quirk: DeletedTableTop::ByMode (src/quirks.rs)
        DeletedTableTop::ByMode if rules.deleted_table_keeps_top_space() => {
            DeletedTableAtTop::Absent
        }
        DeletedTableTop::ByMode => DeletedTableAtTop::TakesSpace,
    }
}

/// Whether the paragraph that a run of paragraphs that show nothing and whose marks are hidden
/// joins, in a document of the rules `rules`, draws the border lines of the run's first
/// paragraph when it has a border or a fill of its own: never where the run's borders go
/// (`HiddenMarkBorders::Dropped`), and from the mode of `HIDDEN_MARK_BORDERS_MODE` on where the
/// target takes the mode's rule (`HiddenMarkBorders::ByMode`).
pub(in crate::layout) fn joins_hidden_mark_borders(quirks: &Quirks, rules: ModeRules) -> bool {
    match quirks.hidden_mark_borders {
        HiddenMarkBorders::Dropped => false,
        // quirk: HiddenMarkBorders::ByMode (src/quirks.rs)
        HiddenMarkBorders::ByMode => rules.joins_hidden_mark_borders(),
    }
}

/// Whether the top border line of a paragraph of the line spacing `line` lies from the rounded
/// text edge with the first term of its room alone: on automatic multiple spacing other than
/// single where the target places it so (`MultipleTopBorder::FromTextEdge`).
pub(in crate::layout) fn multiple_top_from_text_edge(quirks: &Quirks, line: LineSpacing) -> bool {
    // quirk: MultipleTopBorder::FromTextEdge (src/quirks.rs)
    quirks.multiple_top_border == MultipleTopBorder::FromTextEdge
        && matches!(line, LineSpacing::Auto(n) if n != f_office_units::scale::LINE)
}

/// Whether the bottom border line of a paragraph of the line spacing `line` lies from the
/// rounded text edge with the part that the spacing adds below the text in its room: on
/// automatic multiple spacing above single where the target places it so
/// (`MultipleBottomBorder::FromTextEdge`).
pub(in crate::layout) fn multiple_bottom_from_text_edge(
    quirks: &Quirks,
    line: LineSpacing,
) -> bool {
    // quirk: MultipleBottomBorder::FromTextEdge (src/quirks.rs)
    quirks.multiple_bottom_border == MultipleBottomBorder::FromTextEdge
        && matches!(line, LineSpacing::Auto(n) if n > f_office_units::scale::LINE)
}

/// Whether the space after that follows a paragraph of single or at-least spacing joins its
/// border's space and width in the place of its bottom line from the rounded text edge, where
/// the target places it so (`BottomBorderSpaceAfter::Joined`).
pub(in crate::layout) fn bottom_border_space_after_joined(quirks: &Quirks) -> bool {
    // quirk: BottomBorderSpaceAfter::Joined (src/quirks.rs)
    quirks.bottom_border_space_after == BottomBorderSpaceAfter::Joined
}

/// Gives a paragraph's resolved properties `props` the borders that it takes side by side, each
/// side from the nearest level of the cascade that names it, where the target takes them so
/// (`BorderSides::EachSide`); under `WholeElement` they keep the whole `w:pBdr` of the nearest
/// level that has one.
pub(in crate::layout) fn take_border_sides(quirks: &Quirks, props: &mut ParaProps) {
    // quirk: BorderSides::EachSide (src/quirks.rs)
    if quirks.border_sides == BorderSides::EachSide {
        props.take_border_sides();
    }
}

/// Drops the side between the paragraphs of a group from a paragraph's resolved properties
/// `props` where the target does not draw it (`BetweenBorders::Dropped`), and returns whether it
/// dropped a line; under `Drawn` the side stays.
pub(in crate::layout) fn drop_between_border(quirks: &Quirks, props: &mut ParaProps) -> bool {
    match quirks.between_borders {
        BetweenBorders::Dropped => props.drop_between_border(),
        // quirk: BetweenBorders::Drawn (src/quirks.rs)
        BetweenBorders::Drawn => false,
    }
}

/// The room below its text that the last line of a paragraph whose bottom border is `bottom`
/// needs at the foot of a page: the border's space and width where the target keeps the line
/// only with its border (`FootBorderRoom::Fits`), and none where the border may hang.
pub(in crate::layout) fn foot_border_room(quirks: &Quirks, bottom: Option<Border>) -> Length {
    match (quirks.foot_border_room, bottom) {
        // quirk: FootBorderRoom::Fits (src/quirks.rs)
        (FootBorderRoom::Fits, Some(border)) => border.space + border.width,
        (FootBorderRoom::Fits, None) | (FootBorderRoom::Hangs, _) => Length::ZERO,
    }
}

/// The blocks `blocks` of a section whose hidden continuous section end keeps its spaces
/// without a line, where the target keeps them
/// (`ContinuousSectionEnd::KeepsSpacesWithoutLine`). `None` where only a block keeps the line.
pub(in crate::layout) fn spaced_section_end<T>(quirks: &Quirks, blocks: T) -> Option<T> {
    match quirks.continuous_section_end {
        ContinuousSectionEnd::OnlyBlockKeepsLine => None,
        // quirk: ContinuousSectionEnd::KeepsSpacesWithoutLine (src/quirks.rs)
        ContinuousSectionEnd::KeepsSpacesWithoutLine => Some(blocks),
    }
}

/// The turn `turn` of a turned cell whose lines may lie on the page's dots, where the target
/// puts them there (`TurnedAcrossDots::PageDots`). `None` where they lie on the frame's dots.
pub(in crate::layout) fn page_dots_turn<T>(quirks: &Quirks, turn: T) -> Option<T> {
    match quirks.turned_across_dots {
        TurnedAcrossDots::FrameDots => None,
        // quirk: TurnedAcrossDots::PageDots (src/quirks.rs)
        TurnedAcrossDots::PageDots => Some(turn),
    }
}

/// The width of each of a section's equal columns from the exact width `exact`: the exact
/// width, or its whole twips (`ColumnWidths::WholeTwips`).
pub(in crate::layout) fn equal_column_width(quirks: &Quirks, exact: Length) -> Length {
    match quirks.column_widths {
        ColumnWidths::Exact => exact,
        // quirk: ColumnWidths::WholeTwips (src/quirks.rs)
        ColumnWidths::WholeTwips => exact.toward_zero_whole(Length::UNITS_PER_TWIP),
    }
}

/// How many of the spaces at the end of a line of a left-to-right paragraph keep the
/// right-to-left level of their runs, from the first: those in runs with `w:rtl` right after
/// the line's written text, where the target keeps them on a line that also holds text of a run
/// without `w:rtl` (`RightToLeftEndSpace::RunLevelBesideLeftToRight`; `beside_left_to_right`
/// says whether it does, and is asked only there), and none where they lie at the line's visual
/// end. The kept spaces then count as the line's written text
/// ([`crate::lines::Line::written_end_spaces`]). `in_right_to_left_runs` says for each space at
/// the line's end, in the line's order, whether its run has `w:rtl`.
pub(in crate::layout) fn kept_end_spaces(
    quirks: &Quirks,
    beside_left_to_right: impl FnOnce() -> bool,
    in_right_to_left_runs: impl IntoIterator<Item = bool>,
) -> usize {
    match quirks.right_to_left_end_space {
        RightToLeftEndSpace::ParagraphLevel => 0,
        // quirk: RightToLeftEndSpace::RunLevelBesideLeftToRight (src/quirks.rs)
        RightToLeftEndSpace::RunLevelBesideLeftToRight => {
            if beside_left_to_right() {
                in_right_to_left_runs
                    .into_iter()
                    .take_while(|&right_to_left| right_to_left)
                    .count()
            } else {
                0
            }
        }
    }
}

/// Which spaces at the end of a word count in the word's fit, in a paragraph that is right to
/// left when `bidi`: beside left-to-right text, those that keep the right-to-left level of their
/// runs ([`kept_end_spaces`]) and, beside a left-to-right letter, those between right-to-left
/// letters.
pub(in crate::layout) const fn end_space_fit(quirks: &Quirks, bidi: bool) -> EndSpaceFit {
    // quirk: RightToLeftEndSpace::RunLevelBesideLeftToRight (src/quirks.rs)
    if !bidi
        && matches!(
            quirks.right_to_left_end_space,
            RightToLeftEndSpace::RunLevelBesideLeftToRight
        )
    {
        EndSpaceFit::WithRightToLeftSpaces
    } else {
        EndSpaceFit::WithoutSpaces
    }
}

/// The columns of a right-to-left section at the mirrors of their places (`mirrored`, which is
/// evaluated only there), where the target mirrors them
/// (`RightToLeftSectionColumns::FromRight`). `None` where they keep their places.
pub(in crate::layout) fn mirrored_columns<T>(
    quirks: &Quirks,
    mirrored: impl FnOnce() -> T,
) -> Option<T> {
    match quirks.right_to_left_section_columns {
        RightToLeftSectionColumns::FromLeft => None,
        // quirk: RightToLeftSectionColumns::FromRight (src/quirks.rs)
        RightToLeftSectionColumns::FromRight => Some(mirrored()),
    }
}

/// The lines between the text columns of a page (`lines`, which is evaluated only there), where
/// the target draws them (`ColumnSeparator::SpaceMiddle`). `None` where it draws none.
pub(in crate::layout) fn column_separators<T>(
    quirks: &Quirks,
    lines: impl FnOnce() -> T,
) -> Option<T> {
    match quirks.column_separator {
        ColumnSeparator::NotDrawn => None,
        // quirk: ColumnSeparator::SpaceMiddle (src/quirks.rs)
        ColumnSeparator::SpaceMiddle => Some(lines()),
    }
}

/// The side of the page being filled for a section that restarts its page numbers, from the
/// rule that the target follows: by the page's place in the document (`by_place`), or by the
/// number of the page before it (`by_number`, `RestartSide::PreviousNumber`). Only the rule
/// that the target follows is evaluated.
pub(in crate::layout) fn restart_side<T>(
    quirks: &Quirks,
    by_place: impl FnOnce() -> T,
    by_number: impl FnOnce() -> T,
) -> T {
    match quirks.restart_side {
        RestartSide::Place => by_place(),
        // quirk: RestartSide::PreviousNumber (src/quirks.rs)
        RestartSide::PreviousNumber => by_number(),
    }
}

/// The last paragraph `last` of a written footnote separator whose space after the target keeps
/// below the separator (`SeparatorSpaceAfter::Kept`). `None` where the separator drops it.
pub(in crate::layout) fn kept_separator_space<T>(quirks: &Quirks, last: T) -> Option<T> {
    match quirks.separator_space_after {
        SeparatorSpaceAfter::Dropped => None,
        // quirk: SeparatorSpaceAfter::Kept (src/quirks.rs)
        SeparatorSpaceAfter::Kept => Some(last),
    }
}