f-office-docx 0.2.2

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
//! Tables: rows, cells and their properties, as written in a part.

use std::num::NonZeroUsize;

use f_office_units::scale::{FIFTIETHS_PER_PERCENT, PERCENT};
use f_office_units::{Edges, Length};
use f_office_xml::NodeId;
use f_office_xml::enumeration::{Drawn, Values, another, own};

use crate::body::{Block, holds_nothing, read_blocks, shown_branch};
use crate::ns::{MC, W};
use crate::numbers;
use crate::on_off;
use crate::params::{MAX_GRID_COLUMNS, TABLE_LOOK_BITS};
use crate::props::{
    ANCHOR, Align, Anchor, Border, Color, SetIn, X_ALIGN, XAlign, Y_ALIGN, YAlign, overlay,
    read_shading, read_table_border, shows_shading,
};
use crate::reader::{PartReader, val};
use crate::source_span::SourceSpan;
use crate::warnings::Limit;

/// A table.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Table {
    /// Direct table properties.
    pub props: TableProps,
    /// The widths of the grid columns, from `w:tblGrid`.
    pub grid: Vec<Length>,
    /// The rows in order.
    pub rows: Vec<Row>,
    /// The name of the part that holds the table, which sets the own properties of its rows
    /// and cells.
    pub part: std::rc::Rc<f_office_warnings::Name>,
    /// Where the reader found its element, which layout never reads.
    pub source: SourceSpan,
}

/// One side of a table or cell border.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Side {
    /// No line, which removes an inherited line: the value `nil`, or another side that draws
    /// nothing but [`Side::None`].
    Nil,
    /// The value `none` without a width, a space or a colour other than `auto`: no line, which
    /// removes the line of a table style's region and leaves the side to the table's own line.
    None,
    /// The value `none` with a space: no line, which removes an inherited line as
    /// [`Side::Nil`] does, and the space (`w:space`), which a cell keeps inside its edge.
    Spaced(Length),
    /// A line.
    Line(Border),
}

impl Side {
    /// The line, if there is one.
    #[must_use]
    pub fn line(self) -> Option<Border> {
        match self {
            Self::Nil | Self::None | Self::Spaced(_) => None,
            Self::Line(border) => Some(border),
        }
    }
}

/// The border sides of a table or a cell. `None` means "not set here". The inside sides are
/// used by tables only.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TableBorders {
    /// Top.
    pub top: Option<Side>,
    /// Left.
    pub left: Option<Side>,
    /// Bottom.
    pub bottom: Option<Side>,
    /// Right.
    pub right: Option<Side>,
    /// Between rows.
    pub inside_h: Option<Side>,
    /// Between columns.
    pub inside_v: Option<Side>,
}

impl TableBorders {
    /// Overlays `other` on `self`. It names each field of `other`, so that a new field does not
    /// compile until it is overlaid here.
    pub fn apply(&mut self, other: &Self) {
        let Self {
            top,
            left,
            bottom,
            right,
            inside_h,
            inside_v,
        } = other;
        overlay(&mut self.top, top.as_ref());
        overlay(&mut self.left, left.as_ref());
        overlay(&mut self.bottom, bottom.as_ref());
        overlay(&mut self.right, right.as_ref());
        overlay(&mut self.inside_h, inside_h.as_ref());
        overlay(&mut self.inside_v, inside_v.as_ref());
    }

    /// Reads `w:tblBorders` or `w:tcBorders`.
    pub(crate) fn read(reader: &mut PartReader, node: NodeId) -> Self {
        let doc = reader.doc;
        let mut side = |names: &[&str]| {
            names
                .iter()
                .find_map(|name| doc.child(node, W, name))
                .map(|side| match read_table_border(reader, side) {
                    Some(border) => Side::Line(border),
                    None if empty_none(reader, side) => Side::None,
                    None => none_space(reader, side).map_or(Side::Nil, Side::Spaced),
                })
        };
        Self {
            top: side(&["top"]),
            left: side(&["left", "start"]),
            bottom: side(&["bottom"]),
            right: side(&["right", "end"]),
            inside_h: side(&["insideH"]),
            inside_v: side(&["insideV"]),
        }
    }
}

/// Whether a border side is `none` with no width and no space, 0 or missing, and the colour
/// `auto` or none.
fn empty_none(reader: &mut PartReader, side: NodeId) -> bool {
    let doc = reader.doc;
    doc.attribute(side, Some(W), "val") == Some("none")
        && reader.whole_number(side, "sz").unwrap_or(0) == 0
        && reader.whole_number(side, "space").unwrap_or(0) == 0
        && doc
            .attribute(side, Some(W), "color")
            .is_none_or(|color| color == "auto")
}

/// The space of a border side of `none` that names one, in whole points.
fn none_space(reader: &mut PartReader, side: NodeId) -> Option<Length> {
    if reader.doc.attribute(side, Some(W), "val") != Some("none") {
        return None;
    }
    let points = reader
        .whole_number(side, "space")
        .filter(|&points| points > 0)?;
    Length::from_points(points)
}

/// Cell margins. `None` means "not set here".
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Margins {
    /// Top.
    pub top: Option<Length>,
    /// Left.
    pub left: Option<Length>,
    /// Bottom.
    pub bottom: Option<Length>,
    /// Right.
    pub right: Option<Length>,
}

impl Margins {
    /// Overlays `other` on `self`. It names each field of `other`, so that a new field does not
    /// compile until it is overlaid here.
    pub fn apply(&mut self, other: &Self) {
        let Self {
            top,
            left,
            bottom,
            right,
        } = other;
        overlay(&mut self.top, top.as_ref());
        overlay(&mut self.left, left.as_ref());
        overlay(&mut self.bottom, bottom.as_ref());
        overlay(&mut self.right, right.as_ref());
    }

    fn read(reader: &mut PartReader, node: NodeId) -> Self {
        let doc = reader.doc;
        let mut side = |names: &[&str]| {
            names
                .iter()
                .find_map(|name| doc.child(node, W, name))
                .and_then(|side| width(reader, side))
        };
        Self {
            top: side(&["top"]),
            left: side(&["left", "start"]),
            bottom: side(&["bottom"]),
            right: side(&["right", "end"]),
        }
    }
}

/// Where a floating table (`w:tblpPr`) lies, and how far text keeps away from it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TablePlacement {
    /// What the horizontal position is measured from (`w:horzAnchor`).
    pub horizontal: Anchor,
    /// What the vertical position is measured from (`w:vertAnchor`): the margin when the table
    /// names none.
    pub vertical: Anchor,
    /// The offset from the horizontal anchor (`w:tblpX`), when the table gives one.
    pub x: Option<Length>,
    /// The offset from the vertical anchor (`w:tblpY`).
    pub y: Length,
    /// An alignment that wins over the horizontal offset (`w:tblpXSpec`).
    pub x_align: Option<Align>,
    /// An alignment that wins over the vertical offset (`w:tblpYSpec`).
    pub y_align: Option<Align>,
    /// The space that text keeps at each edge (`w:leftFromText` and the others).
    pub distance: Edges<Length>,
}

impl TablePlacement {
    /// Reads a `w:tblpPr` element.
    fn read(reader: &mut PartReader, node: NodeId) -> Self {
        let horizontal = reader.enumeration(node, "horzAnchor", ANCHOR);
        let vertical = reader.enumeration(node, "vertAnchor", ANCHOR);
        let x_align = reader.enumeration(node, "tblpXSpec", X_ALIGN);
        let y_align = reader.enumeration(node, "tblpYSpec", Y_ALIGN);
        let x = reader.twips(node, "tblpX");
        let mut length = |name| reader.twips(node, name).unwrap_or(Length::ZERO);
        Self {
            horizontal: horizontal.unwrap_or_default(),
            vertical: vertical.unwrap_or(Anchor::Margin),
            x,
            y: length("tblpY"),
            x_align: x_align.map(XAlign::align),
            y_align: y_align.and_then(YAlign::align),
            distance: Edges::from(
                [
                    "leftFromText",
                    "topFromText",
                    "rightFromText",
                    "bottomFromText",
                ]
                .map(length),
            ),
        }
    }
}

/// Horizontal alignment of a table between the margins.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TableAlignment {
    /// At the leading margin.
    Start,
    /// Centered.
    Center,
    /// At the trailing margin.
    End,
}

/// `ST_JcTable` of a table's `w:jc`, with `both` of `ST_Jc`, which Word reads as left in a
/// table: `start` is left and `end` right, and text outside the type counts as missing, so that
/// the table takes its style's alignment, as Word reads it.
const TABLE_JC: &Values<TableAlignment> = &Values::new(&[
    own("left", TableAlignment::Start),
    own("start", TableAlignment::Start),
    own("center", TableAlignment::Center),
    own("right", TableAlignment::End),
    own("end", TableAlignment::End),
    own("both", TableAlignment::Start),
]);

/// How a table's columns take their widths (`w:tblLayout`, ECMA-376 Part 1, 17.4.53).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TableLayout {
    /// The columns keep the widths that the table gives them (`fixed`).
    Fixed,
    /// The columns fit their content (`autofit`).
    Autofit,
}

/// `ST_TblLayoutType` of a table's `w:tblLayout`; text outside the type counts as missing.
const TABLE_LAYOUT: &Values<TableLayout> = &Values::new(&[
    own("fixed", TableLayout::Fixed),
    own("autofit", TableLayout::Autofit),
]);

/// A part of a table that a table style formats on its own, from `w:tblStylePr`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Region {
    /// The whole table.
    WholeTable,
    /// The odd column bands.
    Band1Vert,
    /// The even column bands.
    Band2Vert,
    /// The odd row bands.
    Band1Horz,
    /// The even row bands.
    Band2Horz,
    /// The first column.
    FirstCol,
    /// The last column.
    LastCol,
    /// The first row.
    FirstRow,
    /// The last row.
    LastRow,
    /// The top left cell.
    NwCell,
    /// The top right cell.
    NeCell,
    /// The bottom left cell.
    SwCell,
    /// The bottom right cell.
    SeCell,
}

/// `ST_TblStyleOverrideType`, the `w:type` of `w:tblStylePr`.
pub(crate) const REGION: &Values<Region> = &Values::new(&[
    own("wholeTable", Region::WholeTable),
    own("band1Vert", Region::Band1Vert),
    own("band2Vert", Region::Band2Vert),
    own("band1Horz", Region::Band1Horz),
    own("band2Horz", Region::Band2Horz),
    own("firstCol", Region::FirstCol),
    own("lastCol", Region::LastCol),
    own("firstRow", Region::FirstRow),
    own("lastRow", Region::LastRow),
    own("nwCell", Region::NwCell),
    own("neCell", Region::NeCell),
    own("swCell", Region::SwCell),
    own("seCell", Region::SeCell),
]);

/// Which parts of the table style a table shows, from `w:tblLook`, as the bits of its `w:val`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Look(u32);

impl Look {
    /// The first row has its own formatting.
    pub const FIRST_ROW: u32 = TABLE_LOOK_BITS[0];
    /// The last row has its own formatting.
    pub const LAST_ROW: u32 = TABLE_LOOK_BITS[1];
    /// The first column has its own formatting.
    pub const FIRST_COLUMN: u32 = TABLE_LOOK_BITS[2];
    /// The last column has its own formatting.
    pub const LAST_COLUMN: u32 = TABLE_LOOK_BITS[3];
    /// Rows are not banded.
    pub const NO_ROW_BANDS: u32 = TABLE_LOOK_BITS[4];
    /// Columns are not banded.
    pub const NO_COLUMN_BANDS: u32 = TABLE_LOOK_BITS[5];

    /// Whether a bit is on.
    #[must_use]
    pub fn has(self, bit: u32) -> bool {
        self.0 & bit != 0
    }

    /// Reads `w:tblLook`: the bits of its `w:val`, a number of two octets, which the named
    /// attributes override.
    fn read(reader: &mut PartReader, node: NodeId) -> Self {
        let doc = reader.doc;
        let mut bits = reader.hex(node, "val", numbers::SHORT_HEX).unwrap_or(0);
        let names = [
            ("firstRow", Self::FIRST_ROW),
            ("lastRow", Self::LAST_ROW),
            ("firstColumn", Self::FIRST_COLUMN),
            ("lastColumn", Self::LAST_COLUMN),
            ("noHBand", Self::NO_ROW_BANDS),
            ("noVBand", Self::NO_COLUMN_BANDS),
        ];
        for (name, bit) in names {
            match doc.attribute(node, Some(W), name) {
                Some(value) if on_off::read(value) == Some(true) => bits |= bit,
                Some(_) => bits &= !bit,
                None => {}
            }
        }
        Self(bits)
    }
}

/// Table properties. `None` means "not set here".
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TableProps {
    /// The table style ID.
    pub style: Option<String>,
    /// The indent from the leading margin.
    pub indent: Option<Length>,
    /// The alignment between the margins.
    pub alignment: Option<TableAlignment>,
    /// The borders.
    pub borders: TableBorders,
    /// The default cell margins.
    pub margins: Margins,
    /// Which parts of the table style the table shows.
    pub look: Option<Look>,
    /// The number of rows in each row band.
    pub row_band: Option<NonZeroUsize>,
    /// The number of columns in each column band.
    pub column_band: Option<NonZeroUsize>,
    /// Where the table floats, when it does (`w:tblpPr`).
    pub placement: Option<TablePlacement>,
    /// The preferred width of the table (`w:tblW`).
    pub width: Option<PreferredWidth>,
    /// How the columns take their widths (`w:tblLayout`); a missing layout fits them to their
    /// content, as `autofit` does.
    pub layout: Option<TableLayout>,
    /// The spacing between the cells and the table's edges (`w:tblCellSpacing`). A table with
    /// a spacing, also 0, keeps the borders of its cells apart.
    pub cell_spacing: Option<Length>,
    /// Whether the cells run from right to left (`w:bidiVisual`), the first one at the right
    /// (ECMA-376 Part 1, 17.4.1).
    pub right_to_left: Option<bool>,
    /// Whether the shading of the whole table gives a fill or a pattern (`w:shd`), with the
    /// part that sets it. F-Office draws only the shading of the cells, and the layout warns
    /// of the table's.
    pub shading: Option<SetIn<bool>>,
}

/// A preferred width of a table or a cell (`w:tblW`, `w:tcW`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PreferredWidth {
    /// A length (`w:type="dxa"`).
    Length(Length),
    /// A share of the width that holds the table or the cell, in fiftieths of a percent
    /// (`w:type="pct"`), so that 5,000 is all of it.
    Percent(i64),
}

impl PreferredWidth {
    /// The width as a length, when it is one.
    #[must_use]
    pub fn length(self) -> Option<Length> {
        match self {
            Self::Length(length) => Some(length),
            Self::Percent(_) => None,
        }
    }

    /// The width, with a percent of `whole`, or `None` when the part of `whole` that a percent
    /// asks for does not fit in a length: the reader bounds the percent only below.
    #[must_use]
    pub fn of(self, whole: Length) -> Option<Length> {
        match self {
            Self::Length(length) => Some(length),
            Self::Percent(share) => whole
                .checked_mul(share)
                .map(|part| part.div_toward_zero(FIFTIETHS_PER_PERCENT * PERCENT)),
        }
    }
}

impl TableProps {
    /// Overlays `other` on `self`: every property set in `other` wins. It names each field of
    /// `other`, so that a new field does not compile until it is overlaid here.
    pub fn apply(&mut self, other: &Self) {
        let Self {
            style,
            indent,
            alignment,
            borders,
            margins,
            look,
            row_band,
            column_band,
            placement,
            width,
            layout,
            cell_spacing,
            right_to_left,
            shading,
        } = other;
        overlay(&mut self.placement, placement.as_ref());
        overlay(&mut self.width, width.as_ref());
        overlay(&mut self.layout, layout.as_ref());
        overlay(&mut self.style, style.as_ref());
        overlay(&mut self.indent, indent.as_ref());
        overlay(&mut self.alignment, alignment.as_ref());
        self.borders.apply(borders);
        self.margins.apply(margins);
        overlay(&mut self.look, look.as_ref());
        overlay(&mut self.row_band, row_band.as_ref());
        overlay(&mut self.column_band, column_band.as_ref());
        overlay(&mut self.cell_spacing, cell_spacing.as_ref());
        overlay(&mut self.right_to_left, right_to_left.as_ref());
        overlay(&mut self.shading, shading.as_ref());
    }

    /// Whether a table of these properties is laid out as a table of the properties `other`:
    /// the properties are the same, but for the shading of the whole table, which F-Office
    /// does not draw.
    #[must_use]
    pub fn lays_out_as(&self, other: &Self) -> bool {
        if self.shading == other.shading {
            return self == other;
        }
        let same_shading = Self {
            shading: self.shading.clone(),
            ..other.clone()
        };
        *self == same_shading
    }

    /// Reads a `w:tblPr` element.
    pub(crate) fn read(reader: &mut PartReader, node: NodeId) -> Self {
        let doc = reader.doc;
        let mut props = Self::default();
        for child in doc.child_elements(node) {
            let Some(element) = doc.element(child) else {
                continue;
            };
            match element.name.local {
                "tblStyle" => props.style = val(doc, child).map(str::to_owned),
                "tblInd" => props.indent = width(reader, child),
                "tblW" => props.width = preferred(reader, child),
                "tblLayout" => props.layout = reader.enumeration(child, "type", TABLE_LAYOUT),
                "jc" => props.alignment = reader.enumeration(child, "val", TABLE_JC),
                "tblBorders" => props.borders = TableBorders::read(reader, child),
                "tblCellMar" => props.margins = Margins::read(reader, child),
                "tblLook" => props.look = Some(Look::read(reader, child)),
                "tblStyleRowBandSize" => props.row_band = band(reader, child),
                "tblStyleColBandSize" => props.column_band = band(reader, child),
                "tblpPr" => props.placement = Some(TablePlacement::read(reader, child)),
                "bidiVisual" => props.right_to_left = Some(on_off::element(doc, child, W)),
                "tblCellSpacing" => props.cell_spacing = cell_spacing(reader, child),
                "shd" => props.shading = Some(SetIn::read(shows_shading(doc, child), reader)),
                _ => {}
            }
        }
        props
    }
}

/// How `w:trHeight` limits the height of a row.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HeightRule {
    /// At least the given height.
    AtLeast,
    /// Exactly the given height.
    Exact,
    /// The height of the content.
    Auto,
}

/// `ST_HeightRule` of a row's height (`w:trHeight`) and of a frame's (`w:framePr`), which Word
/// reads alike; a missing rule is at least the height.
pub(crate) const HEIGHT_RULE: &Values<HeightRule> = &Values::new(&[
    own("auto", HeightRule::Auto),
    own("exact", HeightRule::Exact),
    own("atLeast", HeightRule::AtLeast),
]);

/// A table row.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Row {
    /// The row height and its rule.
    pub height: Option<(Length, HeightRule)>,
    /// Whether the row must stay on one page.
    pub cant_split: bool,
    /// Whether the row repeats at the top of each page as a header.
    pub header: bool,
    /// Whether the row hides its row-end mark (`w:hidden` of `w:trPr`, ECMA-376 Part 1,
    /// 17.4.20). On every target, such a row whose cells show nothing takes no room and
    /// draws none of its lines.
    pub hidden: bool,
    /// The number of grid columns before the first cell.
    pub grid_before: usize,
    /// The row's own alignment between the margins (`w:jc` of `w:trPr`, ECMA-376 Part 1,
    /// 17.4.80). F-Office places each row where the table's alignment places the table, and
    /// the layout warns of a row whose alignment differs in a table narrower than its column.
    pub alignment: Option<TableAlignment>,
    /// The row's own cell spacing (`w:tblCellSpacing` of `w:trPr`, 17.4.44); one below zero
    /// is no spacing. F-Office keeps the table's spacing in each row, and the layout warns of a
    /// row whose spacing differs.
    pub cell_spacing: Option<Length>,
    /// The table properties that this row sets for itself (`w:tblPrEx`), over the table's.
    /// F-Office uses their borders and cell margins.
    pub exceptions: TableProps,
    /// The cells in order.
    pub cells: Vec<Cell>,
    /// Where the reader found its element, which layout never reads.
    pub source: SourceSpan,
}

impl Row {
    fn read(reader: &mut PartReader, node: NodeId) -> Self {
        let doc = reader.doc;
        let mut row = Self {
            source: SourceSpan::of(doc, node),
            ..Self::default()
        };
        if let Some(trpr) = doc.child(node, W, "trPr") {
            row.read_props(reader, trpr);
        }
        if let Some(exceptions) = doc.child(node, W, "tblPrEx") {
            row.exceptions = TableProps::read(reader, exceptions);
        }
        for cell in cell_nodes(reader, node) {
            row.cells.push(Cell::read(reader, cell));
        }
        row
    }

    fn read_props(&mut self, reader: &mut PartReader, trpr: NodeId) {
        let doc = reader.doc;
        for child in doc.child_elements(trpr) {
            let Some(element) = doc.element(child) else {
                continue;
            };
            match element.name.local {
                "trHeight" => self.height = read_height(reader, child),
                "cantSplit" => self.cant_split = on_off::element(doc, child, W),
                "tblHeader" => self.header = on_off::element(doc, child, W),
                "hidden" => self.hidden = on_off::element(doc, child, W),
                "gridBefore" => self.grid_before = grid_columns(reader, child).unwrap_or(0),
                "jc" => self.alignment = reader.enumeration(child, "val", TABLE_JC),
                "tblCellSpacing" => self.cell_spacing = cell_spacing(reader, child),
                _ => {}
            }
        }
    }
}

/// How a cell takes part in a vertical merge.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Merge {
    /// The cell starts a merged region.
    Restart,
    /// The cell continues the merged region of the cell above.
    Continue,
}

/// `ST_Merge`; a `w:vMerge` without a value continues the region.
const MERGE: &Values<Merge> = &Values::new(&[
    own("continue", Merge::Continue),
    own("restart", Merge::Restart),
]);

/// Vertical alignment of the content of a cell.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VerticalAlign {
    /// At the top.
    Top,
    /// Centered.
    Center,
    /// At the bottom.
    Bottom,
}

/// `ST_VerticalJc` of a cell's `w:vAlign`: a justified cell, `both`, is drawn at the top. Text
/// outside the type counts as missing, so the cell takes its style's alignment, where F-Office
/// read it as the top before.
pub(crate) const CELL_V_ALIGN: &Values<VerticalAlign> = &Values::new(&[
    own("top", VerticalAlign::Top),
    own("center", VerticalAlign::Center),
    own("bottom", VerticalAlign::Bottom),
    another("both", VerticalAlign::Top),
]);

/// The direction of a cell's text (`w:textDirection`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TextDirection {
    /// Upright, from left to right, line below line (`lrTb`).
    #[default]
    Upright,
    /// Turned a quarter to the left: the text reads from bottom to top, and the lines stack from
    /// left to right (`btLr`).
    BottomToTop,
    /// Turned a quarter to the right: the text reads from top to bottom, and the lines stack
    /// from right to left (`tbRl`).
    TopToBottom,
}

/// `ST_TextDirection` of a cell, with the names of ECMA-376 first edition beside those of the
/// Strict schema: the directions other than upright, `btLr` and `tbRl` are drawn upright, and so
/// are `lr` and `rl`, the Strict names of `btLr` and `tbRl`.
pub(crate) const TEXT_DIRECTION: &Values<TextDirection> = &Values::new(&[
    own("lrTb", TextDirection::Upright),
    own("tb", TextDirection::Upright),
    own("btLr", TextDirection::BottomToTop),
    own("tbRl", TextDirection::TopToBottom),
    another("lr", TextDirection::Upright),
    another("rl", TextDirection::Upright),
    another("lrTbV", TextDirection::Upright),
    another("tbV", TextDirection::Upright),
    another("tbRlV", TextDirection::Upright),
    another("rlV", TextDirection::Upright),
    another("tbLrV", TextDirection::Upright),
    another("lrV", TextDirection::Upright),
]);

/// Whether a name of `ST_TextDirection` turns the text: a direction other than upright, or a
/// name that a cell draws upright as another one (the vertical forms of the first edition and
/// the Strict names `lr` and `rl`). `None` for a name outside the type, which a section or a
/// paragraph reads as missing, with a warning.
pub(crate) fn turns_text(name: &str) -> Option<bool> {
    TEXT_DIRECTION.find(name).map(|(direction, _, drawn)| {
        *direction != TextDirection::Upright || drawn == Drawn::AsAnother
    })
}

/// A table cell.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Cell {
    /// The preferred cell width (`w:tcW`).
    pub width: Option<PreferredWidth>,
    /// The number of grid columns that the cell spans.
    pub span: NonZeroUsize,
    /// The vertical merge.
    pub merge: Option<Merge>,
    /// Borders that replace the table's borders for this cell.
    pub borders: TableBorders,
    /// Margins that replace the table's cell margins for this cell.
    pub margins: Margins,
    /// The vertical alignment of the content.
    pub align: Option<VerticalAlign>,
    /// The direction of the text.
    pub direction: TextDirection,
    /// The fill of the cell (`w:shd`), which wins over the table style's.
    pub shading: Option<Color>,
    /// The tracked deletion of the cell (`w:cellDel`), which shows a balloon.
    pub deletion: Option<CellDeletion>,
    /// Whether the cell's end-of-cell mark takes no room in the row (`w:hideMark`).
    pub hide_mark: bool,
    /// Whether the cell's text is fitted into its width (`w:tcFitText`), which F-Office does
    /// not do; the layout warns of it.
    pub fit_text: bool,
    /// The content: paragraphs and nested tables.
    pub blocks: Vec<Block>,
}

/// A tracked deletion of a table cell (`w:cellDel`).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CellDeletion {
    /// The ID of the change (`w:id`).
    pub id: String,
    /// The author of the change (`w:author`).
    pub author: String,
}

impl Cell {
    /// The blocks that take room in the cell: all of them, but without the last paragraph when
    /// that paragraph holds nothing but the end-of-cell mark and the cell hides its mark or the
    /// paragraph stands directly after a nested table.
    #[must_use]
    pub fn shown_blocks(&self) -> &[Block] {
        match self.blocks.split_last() {
            Some((Block::Paragraph(last), rest))
                if holds_nothing(last)
                    && (self.hide_mark || matches!(rest.last(), Some(Block::Table(_)))) =>
            {
                rest
            }
            _ => &self.blocks,
        }
    }
}

impl Default for Cell {
    fn default() -> Self {
        Self {
            width: None,
            span: NonZeroUsize::MIN,
            merge: None,
            borders: TableBorders::default(),
            margins: Margins::default(),
            align: None,
            direction: TextDirection::Upright,
            shading: None,
            deletion: None,
            hide_mark: false,
            fit_text: false,
            blocks: Vec::new(),
        }
    }
}

impl Cell {
    fn read(reader: &mut PartReader, node: NodeId) -> Self {
        let doc = reader.doc;
        let mut cell = Self::default();
        if let Some(tcpr) = doc.child(node, W, "tcPr") {
            cell.read_props(reader, tcpr);
        }
        cell.blocks = read_blocks(reader, node);
        cell
    }

    fn read_props(&mut self, reader: &mut PartReader, tcpr: NodeId) {
        let doc = reader.doc;
        for child in doc.child_elements(tcpr) {
            let Some(element) = doc.element(child) else {
                continue;
            };
            match element.name.local {
                "tcW" => self.width = preferred(reader, child),
                "gridSpan" => {
                    self.span = grid_columns(reader, child)
                        .and_then(NonZeroUsize::new)
                        .unwrap_or(NonZeroUsize::MIN);
                }
                "vMerge" => {
                    self.merge = Some(
                        reader
                            .enumeration(child, "val", MERGE)
                            .unwrap_or(Merge::Continue),
                    );
                }
                "tcBorders" => self.borders = TableBorders::read(reader, child),
                "tcMar" => self.margins = Margins::read(reader, child),
                "vAlign" => self.align = reader.enumeration(child, "val", CELL_V_ALIGN),
                "textDirection" => {
                    self.direction = reader
                        .enumeration(child, "val", TEXT_DIRECTION)
                        .unwrap_or_default();
                }
                "shd" => self.shading = read_shading(reader, child),
                "hideMark" => {
                    self.hide_mark = on_off::element(doc, child, W);
                }
                "tcFitText" => self.fit_text = on_off::element(doc, child, W),
                // Only the cell's own properties count, not the old ones of `w:tcPrChange`.
                "cellDel" => {
                    let attribute = |name| {
                        doc.attribute(child, Some(W), name)
                            .unwrap_or_default()
                            .to_owned()
                    };
                    self.deletion = Some(CellDeletion {
                        id: attribute("id"),
                        author: attribute("author"),
                    });
                }
                _ => {}
            }
        }
    }
}

impl Table {
    /// Reads a `w:tbl` element.
    pub(crate) fn read(reader: &mut PartReader, node: NodeId) -> Self {
        let doc = reader.doc;
        let mut table = Self {
            part: std::rc::Rc::new(f_office_warnings::Name::new(reader.part())),
            source: SourceSpan::of(doc, node),
            ..Self::default()
        };
        for child in doc.child_elements(node) {
            if doc.is(child, W, "tblPr") {
                table.props = TableProps::read(reader, child);
            } else if doc.is(child, W, "tblGrid") {
                // The grid stops at the limit of grid columns, as the grid that rows add does,
                // so that the sums of its widths fit.
                let mut columns = doc
                    .child_elements(child)
                    .filter(|col| doc.is(*col, W, "gridCol"));
                table.grid = columns
                    .by_ref()
                    .take(MAX_GRID_COLUMNS)
                    .map(|col| reader.twips(col, "w").unwrap_or(Length::ZERO))
                    .collect();
                if columns.next().is_some() {
                    reader.limit_reached(Limit::GridColumns);
                }
            } else {
                collect_rows(reader, child, &mut table.rows);
            }
        }
        table.grid = widened_grid(reader, &table.grid, &table.rows);
        table
    }
}

/// The cells of a row with the grid column where each starts.
fn cell_starts(row: &Row) -> impl Iterator<Item = (usize, &Cell)> + '_ {
    let mut column = row.grid_before;
    row.cells.iter().map(move |cell| {
        let start = column;
        column = column.saturating_add(cell.span.get());
        (start, cell)
    })
}

/// A cell of a row with the grid column where it starts, after the row's `w:gridBefore`, and
/// how it takes part in a vertical merge, as the table reader reads them.
#[derive(Clone, Copy, Debug)]
pub(crate) struct RowCell {
    /// The cell (`w:tc`).
    pub(crate) node: NodeId,
    /// The grid column where it starts, from 0.
    pub(crate) start: usize,
    /// How it takes part in a vertical merge, if it does.
    pub(crate) merge: Option<Merge>,
}

/// The cells of the row `row` (`w:tr`), each with its place, in the order and with the grid
/// columns of the table reader, for the named edits of rows and cells.
pub(crate) fn row_cells(reader: &mut PartReader, row: NodeId) -> Vec<RowCell> {
    let doc = reader.doc;
    let mut start = doc
        .child(row, W, "trPr")
        .and_then(|trpr| doc.child(trpr, W, "gridBefore"))
        .and_then(|node| grid_columns(reader, node))
        .unwrap_or(0);
    let mut places = Vec::new();
    for cell in cell_nodes(reader, row) {
        let tcpr = doc.child(cell, W, "tcPr");
        let span = tcpr
            .and_then(|tcpr| doc.child(tcpr, W, "gridSpan"))
            .and_then(|node| grid_columns(reader, node))
            .and_then(NonZeroUsize::new)
            .unwrap_or(NonZeroUsize::MIN);
        let merge = tcpr
            .and_then(|tcpr| doc.child(tcpr, W, "vMerge"))
            .map(|node| {
                reader
                    .enumeration(node, "val", MERGE)
                    .unwrap_or(Merge::Continue)
            });
        places.push(RowCell {
            node: cell,
            start,
            merge,
        });
        start = start.saturating_add(span.get());
    }
    places
}

/// A count of grid columns (`w:gridSpan`, `w:gridBefore`), at most [`MAX_GRID_COLUMNS`]: a
/// larger count reads as the limit, with a warning.
fn grid_columns(reader: &mut PartReader, node: NodeId) -> Option<usize> {
    let count = reader.number::<usize>(node, "val", numbers::NOT_NEGATIVE)?;
    if count > MAX_GRID_COLUMNS {
        reader.limit_reached(Limit::GridColumns);
    }
    Some(count.min(MAX_GRID_COLUMNS))
}

/// The grid with the columns that a row takes beyond it, up to [`MAX_GRID_COLUMNS`] columns:
/// each new column is as wide as the widest cell of one column that starts there. One pass
/// over the cells. A cell that would widen the grid beyond the limit warns `reader`.
fn widened_grid(reader: &mut PartReader, grid: &[Length], rows: &[Row]) -> Vec<Length> {
    // The new columns, each with the widest width of a one-column cell that starts there.
    let mut added: Vec<Option<Length>> = Vec::new();
    for (start, cell) in rows.iter().flat_map(cell_starts) {
        let span = cell.span.get();
        let asked = start.saturating_add(span);
        if asked > MAX_GRID_COLUMNS {
            reader.limit_reached(Limit::GridColumns);
        }
        let end = asked.min(MAX_GRID_COLUMNS);
        if let Some(count) = end.checked_sub(grid.len()).filter(|n| *n > added.len()) {
            added.resize(count, None);
        }
        let width = cell.width.and_then(PreferredWidth::length);
        let column = start.checked_sub(grid.len());
        if let (Some(width), Some(slot), 1) = (width, column.and_then(|i| added.get_mut(i)), span) {
            *slot = Some(slot.map_or(width, |widest| widest.max(width)));
        }
    }
    let added = added.into_iter().map(|width| width.unwrap_or(Length::ZERO));
    grid.iter().copied().chain(added).collect()
}

/// Collects rows, also from inside content controls, custom XML and alternate content.
fn collect_rows(reader: &mut PartReader, node: NodeId, rows: &mut Vec<Row>) {
    let doc = reader.doc;
    if doc.is(node, W, "tr") {
        rows.push(Row::read(reader, node));
    } else if let Some(inner) = wrapped(reader, node) {
        for child in doc.child_elements(inner) {
            collect_rows(reader, child, rows);
        }
    }
}

/// The cells (`w:tc`) of the row `row`, in order, also from inside content controls, custom XML
/// and alternate content.
fn cell_nodes(reader: &mut PartReader, row: NodeId) -> Vec<NodeId> {
    let doc = reader.doc;
    let mut cells = Vec::new();
    let mut stack: Vec<NodeId> = doc.child_elements(row).collect();
    stack.reverse();
    while let Some(node) = stack.pop() {
        if doc.is(node, W, "tc") {
            cells.push(node);
        } else if let Some(inner) = wrapped(reader, node) {
            let mut children: Vec<NodeId> = doc.child_elements(inner).collect();
            children.reverse();
            stack.extend(children);
        }
    }
    cells
}

/// The element whose children take the place of a wrapping element: the element itself for
/// a content control or custom XML, or the shown branch of alternate content.
fn wrapped(reader: &mut PartReader, node: NodeId) -> Option<NodeId> {
    let doc = reader.doc;
    if doc.is(node, MC, "AlternateContent") {
        return shown_branch(reader, node);
    }
    ["sdt", "sdtContent", "customXml"]
        .iter()
        .any(|name| doc.is(node, W, name))
        .then_some(node)
}

fn read_height(reader: &mut PartReader, node: NodeId) -> Option<(Length, HeightRule)> {
    let value = reader.twips(node, "val")?;
    let rule = reader
        .enumeration(node, "hRule", HEIGHT_RULE)
        .unwrap_or(HeightRule::AtLeast);
    Some((value, rule))
}

/// Reads a preferred width, such as `w:tcW`: a length, or a percent in fiftieths or with a
/// percent sign, as [`numbers::fiftieths`] reads it. An automatic width has none.
/// The unit of a width (`ST_TblWidth`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum WidthType {
    /// Twips (`dxa`).
    Twips,
    /// Fiftieths of a percent (`pct`).
    Percent,
    /// No width: the table or cell takes its content's width.
    Auto,
}

/// `ST_TblWidth` of a preferred width (`w:tblW`, `w:tcW`): a width of `nil` is drawn as no
/// width, as `auto` is. A width without a unit is in twips, and text outside the type counts as
/// missing, where F-Office read it as no width before.
const PREFERRED_TYPE: &Values<WidthType> = &Values::new(&[
    own("dxa", WidthType::Twips),
    own("pct", WidthType::Percent),
    own("auto", WidthType::Auto),
    another("nil", WidthType::Auto),
]);

/// `ST_TblWidth` of a width in twips (`w:tblInd`, `w:tblCellSpacing`, the sides of
/// `w:tblCellMar` and `w:tcMar`): a percent, `nil` and `auto` are drawn as no width. A width
/// without a unit is in twips, and text outside the type counts as missing, where F-Office read
/// it as no width before.
const TWIPS_TYPE: &Values<WidthType> = &Values::new(&[
    own("dxa", WidthType::Twips),
    another("pct", WidthType::Auto),
    another("auto", WidthType::Auto),
    another("nil", WidthType::Auto),
]);

fn preferred(reader: &mut PartReader, node: NodeId) -> Option<PreferredWidth> {
    let unit = reader.enumeration(node, "type", PREFERRED_TYPE);
    match unit.unwrap_or(WidthType::Twips) {
        WidthType::Twips => reader.twips(node, "w").map(PreferredWidth::Length),
        WidthType::Percent => reader.fiftieths(node, "w").map(PreferredWidth::Percent),
        WidthType::Auto => None,
    }
}

fn width(reader: &mut PartReader, node: NodeId) -> Option<Length> {
    match reader.enumeration(node, "type", TWIPS_TYPE) {
        Some(WidthType::Twips) | None => reader.twips(node, "w"),
        Some(WidthType::Percent | WidthType::Auto) => None,
    }
}

/// The cell spacing of a table or a row (`w:tblCellSpacing`). A spacing below zero is no
/// spacing.
fn cell_spacing(reader: &mut PartReader, node: NodeId) -> Option<Length> {
    width(reader, node).filter(|s| s.units() >= 0)
}

/// The rows or columns of a band of a table style (`w:tblStyleRowBandSize`,
/// `w:tblStyleColBandSize`), 1 or more.
fn band(reader: &mut PartReader, node: NodeId) -> Option<NonZeroUsize> {
    reader
        .number::<usize>(node, "val", 1..=i64::MAX)
        .and_then(NonZeroUsize::new)
}

#[cfg(test)]
mod tests {
    use super::{
        Align, Anchor, HEIGHT_RULE, HeightRule, Look, Merge, REGION, Region, Side, Table,
        TableAlignment, VerticalAlign,
    };
    use crate::body::Block;
    use crate::ns::W;
    use crate::params::MAX_GRID_COLUMNS;
    use crate::props::{Color, DashStyle};
    use crate::reader::PartReader;
    use crate::warnings::Limit;
    use f_office_units::Edges;
    use f_office_units::Length;
    use f_office_xml::{Document, Limits};
    use std::num::NonZeroUsize;

    /// The table `xml`, with the limits that its values reached and their counts.
    fn table_and_limits(xml: &str) -> (Table, Vec<(Limit, u32)>) {
        let doc = Document::parse(
            format!(r#"<w:tbl xmlns:w="{W}">{xml}</w:tbl>"#).as_bytes(),
            &Limits::default(),
        )
        .unwrap();
        let mut reader = PartReader::new(&doc);
        let table = Table::read(&mut reader, doc.root().unwrap());
        (table, reader.limits_reached())
    }

    fn table(xml: &str) -> Table {
        table_and_limits(xml).0
    }

    fn twips(t: i64) -> Option<Length> {
        Length::from_twips(t)
    }

    #[test]
    fn lays_out_tables_that_differ_only_in_their_whole_shading_alike() {
        let shaded = table(
            r#"<w:tblPr><w:jc w:val="center"/><w:shd w:val="clear" w:color="auto" w:fill="D9D9D9"/></w:tblPr>"#,
        );
        let plain = table(r#"<w:tblPr><w:jc w:val="center"/></w:tblPr>"#);
        let right = table(r#"<w:tblPr><w:jc w:val="right"/></w:tblPr>"#);
        assert_eq!(
            shaded.props.shading.as_ref().map(|set| set.value),
            Some(true)
        );
        assert_ne!(shaded.props, plain.props);
        assert!(shaded.props.lays_out_as(&plain.props) && plain.props.lays_out_as(&shaded.props));
        assert!(!right.props.lays_out_as(&shaded.props));
    }

    #[test]
    fn reads_the_style_indent_and_borders() {
        let t = table(
            r#"<w:tblPr><w:tblStyle w:val="Grid"/><w:tblInd w:w="-108" w:type="dxa"/><w:jc w:val="center"/>
            <w:tblBorders><w:top w:val="single" w:sz="8" w:color="FF0000"/><w:start w:val="nil"/><w:insideV w:val="none"/><w:end w:val="double" w:sz="4"/></w:tblBorders></w:tblPr>"#,
        );
        let p = &t.props;
        assert_eq!(p.style.as_deref(), Some("Grid"));
        assert_eq!(p.indent, twips(-108));
        assert_eq!(p.alignment, Some(TableAlignment::Center));
        let top = p.borders.top.and_then(Side::line).unwrap();
        assert_eq!(
            (Some(top.width), top.color),
            (Length::from_eighth_points(8), Color::Rgb([255, 0, 0]))
        );
        assert_eq!(
            (p.borders.left, p.borders.inside_v),
            (Some(Side::Nil), Some(Side::None))
        );
        // A double border is two lines of `w:sz` and a gap of `w:sz`.
        assert_eq!(
            p.borders
                .right
                .and_then(Side::line)
                .map(|b| (b.width, b.lines().len())),
            Length::from_eighth_points(12).map(|width| (width, 2))
        );
        assert_eq!((p.borders.bottom, p.borders.inside_h), (None, None));
    }

    fn placement(attributes: &str) -> super::TablePlacement {
        table(&format!(r"<w:tblPr><w:tblpPr {attributes}/></w:tblPr>"))
            .props
            .placement
            .unwrap()
    }

    #[test]
    fn reads_the_place_of_a_floating_table() {
        let place = placement(
            r#"w:leftFromText="180" w:topFromText="20" w:rightFromText="181" w:bottomFromText="40" w:vertAnchor="page" w:horzAnchor="margin" w:tblpX="-624" w:tblpY="2621""#,
        );
        assert_eq!(
            (place.vertical, place.horizontal),
            (Anchor::Page, Anchor::Margin)
        );
        assert_eq!((place.x, Some(place.y)), (twips(-624), twips(2621)));
        assert_eq!(
            place.distance.map(Some),
            Edges::from([twips(180), twips(20), twips(181), twips(40)])
        );
        assert_eq!((place.x_align, place.y_align), (None, None));
        assert_eq!(table("<w:tblPr/>").props.placement, None);
    }

    #[test]
    fn reads_the_anchors_and_alignments_of_a_floating_table() {
        // Without anchors the table counts down from the margin and across from the text, and
        // the alignments win over offsets.
        let aligned = placement(r#"w:tblpXSpec="center" w:tblpYSpec="bottom""#);
        assert_eq!(
            (aligned.vertical, aligned.horizontal),
            (Anchor::Margin, Anchor::Text)
        );
        assert_eq!(
            (aligned.x_align, aligned.y_align),
            (Some(Align::Center), Some(Align::End))
        );
        let left = placement(r#"w:tblpXSpec="left" w:tblpYSpec="inline""#);
        assert_eq!((left.x_align, left.y_align), (Some(Align::Start), None));
        // A table that gives no offset across has none, which is not an offset of zero.
        assert_eq!((left.x, placement(r#"w:tblpX="0""#).x), (None, twips(0)));
    }

    #[test]
    fn reads_an_alignment_only_of_its_own_axis() {
        // `w:tblpXSpec` is `ST_XAlign` and `w:tblpYSpec` is `ST_YAlign`, as for a frame: a
        // value of the other axis is no alignment, and the offset counts.
        let crossed = placement(r#"w:tblpXSpec="top" w:tblpYSpec="right""#);
        assert_eq!((crossed.x_align, crossed.y_align), (None, None));
        let inside = placement(r#"w:tblpXSpec="outside" w:tblpYSpec="inside""#);
        assert_eq!(
            (inside.x_align, inside.y_align),
            (Some(Align::Outside), Some(Align::Start))
        );
    }

    #[test]
    fn reads_the_preferred_width_of_the_table() {
        use super::PreferredWidth;
        let width = |xml: &str| table(&format!("<w:tblPr>{xml}</w:tblPr>")).props.width;
        let pct = |w: &str| format!(r#"<w:tblW w:w="{w}" w:type="pct"/>"#);
        assert_eq!(width(&pct("5000")), Some(PreferredWidth::Percent(5000)));
        assert_eq!(width(&pct("50%")), Some(PreferredWidth::Percent(2500)));
        let dxa = r#"<w:tblW w:w="720" w:type="dxa"/>"#;
        assert_eq!(width(dxa), twips(720).map(PreferredWidth::Length));
        assert_eq!(width(r#"<w:tblW w:w="0" w:type="auto"/>"#), None);
        // A percent counts from the whole, and a length is its own. A percent whose part of
        // the whole does not fit in a length gives no width.
        let units = Length::from_units;
        let of = |width: PreferredWidth| width.of(units(400));
        assert_eq!(of(PreferredWidth::Percent(1250)), Some(units(100)));
        assert_eq!(of(PreferredWidth::Length(units(7))), Some(units(7)));
        assert_eq!(of(PreferredWidth::Percent(i64::MAX)), None);
    }

    #[test]
    fn reads_a_width_with_text_outside_its_type_in_twips() {
        use super::PreferredWidth;
        let props = |xml: &str| table(&format!("<w:tblPr>{xml}</w:tblPr>")).props;
        let width = |unit: &str| props(&format!(r#"<w:tblW w:w="720" w:type="{unit}"/>"#)).width;
        let read = ["Dxa", "", "twips", "nil"].map(width);
        let length = twips(720).map(PreferredWidth::Length);
        assert_eq!(read, [length, length, length, None]);
        let indent =
            |unit: &str| props(&format!(r#"<w:tblInd w:w="720" w:type="{unit}"/>"#)).indent;
        assert_eq!(
            ["dxa", "Dxa", "pct", "auto"].map(indent),
            [twips(720), twips(720), None, None]
        );
    }

    #[test]
    fn reads_cell_margins_bands_and_the_grid() {
        let t = table(
            r#"<w:tblPr><w:tblCellMar><w:top w:w="10" w:type="dxa"/><w:start w:w="70" w:type="dxa"/><w:bottom w:w="5" w:type="dxa"/><w:right w:w="2" w:type="pct"/></w:tblCellMar>
            <w:tblStyleRowBandSize w:val="2"/><w:tblStyleColBandSize w:val="0"/></w:tblPr>
            <w:tblGrid><w:gridCol w:w="100"/><w:gridCol/></w:tblGrid>"#,
        );
        let m = &t.props.margins;
        assert_eq!(
            (m.top, m.left, m.bottom, m.right),
            (twips(10), twips(70), twips(5), None)
        );
        assert_eq!(
            (t.props.row_band, t.props.column_band),
            (NonZeroUsize::new(2), None)
        );
        assert_eq!(t.grid, vec![twips(100).unwrap(), Length::ZERO]);
    }

    #[test]
    fn widens_the_grid_for_a_row_that_takes_more_columns() {
        let cell = |w: u32| {
            format!(r#"<w:tc><w:tcPr><w:tcW w:w="{w}" w:type="dxa"/></w:tcPr><w:p/></w:tc>"#)
        };
        let t = table(&format!(
            r#"<w:tblGrid><w:gridCol w:w="100"/><w:gridCol w:w="100"/></w:tblGrid><w:tr><w:trPr><w:gridBefore w:val="1"/></w:trPr>{}{}</w:tr><w:tr>{}{}</w:tr>"#,
            cell(100),
            cell(300),
            cell(100),
            cell(100)
        ));
        let widths: Vec<Option<Length>> = [100, 100, 300].map(twips).into();
        assert_eq!(t.grid.into_iter().map(Some).collect::<Vec<_>>(), widths);
    }

    #[test]
    fn widens_the_grid_up_to_the_limit_of_grid_columns() {
        let (t, limits) = table_and_limits(
            r#"<w:tblGrid><w:gridCol w:w="100"/></w:tblGrid>
            <w:tr><w:tc><w:tcPr><w:gridSpan w:val="10000000"/></w:tcPr><w:p/></w:tc></w:tr>
            <w:tr><w:trPr><w:gridBefore w:val="10000000"/></w:trPr><w:tc><w:p/></w:tc></w:tr>"#,
        );
        assert_eq!(t.grid.len(), MAX_GRID_COLUMNS);
        assert_eq!(t.grid.first().copied(), twips(100));
        let row = |i: usize| &t.rows[i];
        assert_eq!(
            (row(0).cells[0].span.get(), row(1).grid_before),
            (MAX_GRID_COLUMNS, MAX_GRID_COLUMNS)
        );
        // The span and the count before the cells each reach the limit, and the cell after
        // the count would widen the grid beyond it.
        assert_eq!(limits, [(Limit::GridColumns, 3)]);
    }

    #[test]
    fn reads_a_grid_up_to_the_limit_of_grid_columns() {
        // The largest width of a column; the sum of the limit's number of them fits an `i64`.
        let largest = Length::FILE_LIMIT / Length::UNITS_PER_TWIP;
        let column = format!(r#"<w:gridCol w:w="{largest}"/>"#);
        let grid = |columns: usize| {
            table_and_limits(&format!(
                "<w:tblGrid>{}</w:tblGrid><w:tr><w:tc><w:p/></w:tc></w:tr>",
                column.repeat(columns)
            ))
        };
        let (t, limits) = grid(MAX_GRID_COLUMNS + 1);
        assert_eq!(t.grid.len(), MAX_GRID_COLUMNS);
        assert!(t.grid.iter().all(|width| Some(*width) == twips(largest)));
        assert_eq!(limits, [(Limit::GridColumns, 1)]);
        // A grid at the limit reaches nothing.
        let (t, limits) = grid(MAX_GRID_COLUMNS);
        assert_eq!((t.grid.len(), limits), (MAX_GRID_COLUMNS, Vec::new()));
    }

    #[test]
    fn reads_the_largest_spans_without_an_overflow() {
        // The largest number that the reader of numbers reads.
        let span = format!(
            r#"<w:tc><w:tcPr><w:gridSpan w:val="{}"/></w:tcPr><w:p/></w:tc>"#,
            i64::MAX
        );
        let (t, limits) = table_and_limits(&format!("<w:tr>{span}{span}{span}</w:tr>"));
        assert_eq!(t.grid.len(), MAX_GRID_COLUMNS);
        // Each span reaches the limit, and the second and the third cell would widen the grid
        // beyond it.
        assert_eq!(limits, [(Limit::GridColumns, 5)]);
        assert!(
            t.rows[0]
                .cells
                .iter()
                .all(|c| c.span.get() == MAX_GRID_COLUMNS)
        );
    }

    #[test]
    fn reads_alignment_values() {
        let jc = |v: &str| {
            table(&format!(r#"<w:tblPr><w:jc w:val="{v}"/></w:tblPr>"#))
                .props
                .alignment
        };
        assert_eq!(jc("right"), Some(TableAlignment::End));
        assert_eq!(jc("end"), Some(TableAlignment::End));
        assert_eq!(jc("left"), Some(TableAlignment::Start));
        assert_eq!(jc("start"), Some(TableAlignment::Start));
        assert_eq!(jc("both"), Some(TableAlignment::Start));
    }

    #[test]
    fn reads_text_outside_the_type_of_a_table_alignment_as_missing() {
        let jc = |v: &str| {
            table(&format!(r#"<w:tblPr><w:jc w:val="{v}"/></w:tblPr>"#))
                .props
                .alignment
        };
        let read = ["Right", " right ", "", "far", "distribute"].map(jc);
        assert_eq!(read, [None; 5]);
    }

    #[test]
    fn reads_the_look_from_bits_and_attributes() {
        let look = |attrs: &str| {
            table(&format!("<w:tblPr><w:tblLook {attrs}/></w:tblPr>"))
                .props
                .look
                .unwrap()
        };
        let flags = |look: Look| {
            [
                Look::FIRST_ROW,
                Look::LAST_ROW,
                Look::FIRST_COLUMN,
                Look::LAST_COLUMN,
                Look::NO_ROW_BANDS,
                Look::NO_COLUMN_BANDS,
            ]
            .map(|bit| look.has(bit))
        };
        let bits = look(r#"w:val="04A0""#);
        assert_eq!(flags(bits), [true, false, true, false, false, true]);
        let named = look(
            r#"w:val="04A0" w:firstRow="0" w:lastRow="1" w:lastColumn="true" w:noHBand="on" w:noVBand="0""#,
        );
        assert_eq!(flags(named), [false, true, true, true, true, false]);
        assert_eq!(look(r#"w:val="zz""#), Look::default());
    }

    const ROWS: &str = r#"<w:tr><w:trPr><w:trHeight w:val="300" w:hRule="exact"/><w:cantSplit/><w:tblHeader/><w:gridBefore w:val="1"/></w:trPr>
        <w:tc><w:tcPr><w:tcW w:w="2000" w:type="dxa"/><w:gridSpan w:val="2"/><w:vMerge w:val="restart"/><w:vAlign w:val="center"/>
        <w:tcBorders><w:bottom w:val="single" w:sz="4"/></w:tcBorders><w:tcMar><w:left w:w="0" w:type="dxa"/></w:tcMar></w:tcPr>
        <w:p/><w:tbl><w:tr><w:tc><w:p/></w:tc></w:tr></w:tbl></w:tc>
        <w:sdt><w:sdtContent><w:tc><w:tcPr><w:tcW w:w="50" w:type="pct"/><w:gridSpan w:val="0"/><w:vMerge/><w:vAlign w:val="bottom"/></w:tcPr><w:p/></w:tc></w:sdtContent></w:sdt></w:tr>
        <w:customXml><w:tr><w:trPr><w:trHeight w:val="200" w:hRule="auto"/><w:cantSplit w:val="0"/><w:gridBefore w:val="x"/></w:trPr><w:tc><w:tcPr><w:vAlign w:val="top"/></w:tcPr></w:tc></w:tr></w:customXml>
        <w:tr><w:trPr><w:trHeight w:val="100"/></w:trPr></w:tr>"#;

    #[test]
    fn reads_rows() {
        let t = table(ROWS);
        let rows: Vec<_> = t
            .rows
            .iter()
            .map(|r| (r.height, r.cant_split, r.header, r.grid_before))
            .collect();
        let height = |h, rule| twips(h).map(|h| (h, rule));
        assert_eq!(
            rows,
            vec![
                (height(300, HeightRule::Exact), true, true, 1),
                (height(200, HeightRule::Auto), false, false, 0),
                (height(100, HeightRule::AtLeast), false, false, 0),
            ]
        );
    }

    #[test]
    fn reads_cells() {
        let t = table(ROWS);
        let cells: Vec<_> = [
            &t.rows[0].cells[0],
            &t.rows[0].cells[1],
            &t.rows[1].cells[0],
        ]
        .iter()
        .map(|c| (c.width, c.span.get(), c.merge, c.align, c.blocks.len()))
        .collect();
        assert_eq!(
            cells,
            vec![
                (
                    twips(2000).map(super::PreferredWidth::Length),
                    2,
                    Some(Merge::Restart),
                    Some(VerticalAlign::Center),
                    2
                ),
                (
                    Some(super::PreferredWidth::Percent(50)),
                    1,
                    Some(Merge::Continue),
                    Some(VerticalAlign::Bottom),
                    1
                ),
                (None, 1, None, Some(VerticalAlign::Top), 0),
            ]
        );
    }

    #[test]
    fn reads_text_outside_the_type_of_a_cell_alignment_as_missing() {
        let align = |v: &str| {
            let t = table(&format!(
                r#"<w:tr><w:tc><w:tcPr><w:vAlign w:val="{v}"/></w:tcPr><w:p/></w:tc></w:tr>"#
            ));
            t.rows[0].cells[0].align
        };
        let read = ["both", "Center", " center ", "", "middle"].map(align);
        assert_eq!(read, [Some(VerticalAlign::Top), None, None, None, None]);
    }

    #[test]
    fn reads_a_cell_deletion_from_the_cell_s_own_properties() {
        let t = table(
            r#"<w:tr><w:tc><w:tcPr><w:cellDel w:id="7" w:author="Ann"/><w:tcPrChange><w:tcPr><w:cellDel w:id="8" w:author="Bob"/></w:tcPr></w:tcPrChange></w:tcPr><w:p/></w:tc><w:tc><w:tcPr><w:tcPrChange><w:tcPr><w:cellDel w:id="9" w:author="Bob"/></w:tcPr></w:tcPrChange></w:tcPr><w:p/></w:tc></w:tr>"#,
        );
        let deletions: Vec<_> = t.rows[0].cells.iter().map(|c| c.deletion.clone()).collect();
        let ann = super::CellDeletion {
            id: "7".to_owned(),
            author: "Ann".to_owned(),
        };
        assert_eq!(deletions, [Some(ann), None]);
    }

    #[test]
    fn skips_rows_and_cells_in_other_elements() {
        let t = table(
            "<w:unknown><w:tr/></w:unknown><w:tr><w:bookmarkStart/><w:unknown><w:tc/></w:unknown></w:tr>",
        );
        assert_eq!(t.rows.len(), 1);
        assert_eq!(t.rows[0].cells, Vec::new());
    }

    #[test]
    fn reads_the_dashes_of_the_style_of_a_side() {
        let dash = |style: &str| {
            let t = table(&format!(
                r#"<w:tblPr><w:tblBorders><w:insideV w:val="{style}" w:sz="4"/></w:tblBorders></w:tblPr>"#
            ));
            t.props
                .borders
                .inside_v
                .and_then(Side::line)
                .map(|b| b.dash)
        };
        assert_eq!(dash("dotted"), Some(Some(DashStyle::Dotted)));
        assert_eq!(dash("dashed"), Some(Some(DashStyle::Dashed)));
        assert_eq!(dash("dotDash"), Some(Some(DashStyle::DotDash)));
        assert_eq!(dash("dotDotDash"), Some(Some(DashStyle::DotDotDash)));
        assert_eq!(dash("single"), Some(None));
        assert_eq!(dash("dashSmallGap"), Some(None));
        assert_eq!(dash("none"), None);
    }

    #[test]
    fn reads_cell_borders_margins_and_content() {
        let t = table(ROWS);
        let cell = &t.rows[0].cells[0];
        assert!(cell.borders.bottom.and_then(Side::line).is_some());
        assert_eq!(cell.margins.left, Some(Length::ZERO));
        assert!(matches!(
            cell.blocks.as_slice(),
            [Block::Paragraph(_), Block::Table(_)]
        ));
    }

    fn overlaid() -> super::TableProps {
        let base = table(
            r#"<w:tblPr><w:tblStyle w:val="A"/><w:tblInd w:w="10" w:type="dxa"/><w:tblBorders><w:top w:val="single" w:sz="4"/><w:insideH w:val="single" w:sz="4"/></w:tblBorders><w:tblCellMar><w:left w:w="108" w:type="dxa"/></w:tblCellMar><w:tblLook w:val="0020"/></w:tblPr>"#,
        );
        let over = table(
            r#"<w:tblPr><w:jc w:val="right"/><w:tblBorders><w:top w:val="nil"/><w:left w:val="single" w:sz="2"/><w:bottom w:val="single" w:sz="2"/><w:right w:val="single" w:sz="2"/><w:insideV w:val="single" w:sz="2"/></w:tblBorders><w:tblCellMar><w:top w:w="1" w:type="dxa"/><w:right w:w="2" w:type="dxa"/><w:bottom w:w="3" w:type="dxa"/></w:tblCellMar><w:tblStyleRowBandSize w:val="3"/><w:tblStyleColBandSize w:val="4"/></w:tblPr>"#,
        );
        let mut props = base.props;
        props.apply(&over.props);
        props
    }

    #[test]
    fn reads_an_empty_none_apart_from_other_sides_without_a_line() {
        let t = table(
            r#"<w:tblPr><w:tblBorders><w:top w:val="none" w:sz="0" w:space="0" w:color="auto"/><w:left w:val="none" w:color="000000" w:sz="0"/><w:bottom w:val="none" w:sz="4"/><w:right w:val="none" w:space="1"/><w:insideH w:val="nil"/><w:insideV w:val="none"/></w:tblBorders></w:tblPr>"#,
        );
        let b = t.props.borders;
        assert_eq!(
            [b.top, b.left, b.bottom, b.right, b.inside_h, b.inside_v],
            [
                Side::None,
                Side::Nil,
                Side::Nil,
                Side::Spaced(Length::from_points(1).unwrap()),
                Side::Nil,
                Side::None
            ]
            .map(Some)
        );
    }

    #[test]
    fn later_table_properties_win() {
        let props = overlaid();
        assert_eq!(props.style.as_deref(), Some("A"));
        assert_eq!(props.indent, twips(10));
        assert_eq!(props.alignment, Some(TableAlignment::End));
        assert_eq!(props.margins.left, twips(108));
        assert_eq!(
            (props.margins.top, props.margins.right, props.margins.bottom),
            (twips(1), twips(2), twips(3))
        );
        assert!(props.look.unwrap().has(Look::FIRST_ROW));
        assert_eq!(
            (props.row_band, props.column_band),
            (NonZeroUsize::new(3), NonZeroUsize::new(4))
        );
    }

    #[test]
    fn later_borders_win() {
        let b = overlaid().borders;
        let width = |side: Option<Side>| side.and_then(Side::line).map(|b| b.width);
        let widths = [b.top, b.left, b.bottom, b.right, b.inside_h, b.inside_v].map(width);
        let (half, quarter) = (Length::from_eighth_points(4), Length::from_eighth_points(2));
        assert_eq!(widths, [None, quarter, quarter, quarter, half, quarter]);
        assert_eq!(b.top, Some(Side::Nil));
    }

    #[test]
    fn reads_each_region_of_a_table_style() {
        let names = [
            ("wholeTable", Region::WholeTable),
            ("band1Vert", Region::Band1Vert),
            ("band2Vert", Region::Band2Vert),
            ("band1Horz", Region::Band1Horz),
            ("band2Horz", Region::Band2Horz),
            ("firstCol", Region::FirstCol),
            ("lastCol", Region::LastCol),
            ("firstRow", Region::FirstRow),
            ("lastRow", Region::LastRow),
            ("nwCell", Region::NwCell),
            ("neCell", Region::NeCell),
            ("swCell", Region::SwCell),
            ("seCell", Region::SeCell),
        ];
        let read = |value: &str| {
            let xml = format!(r#"<w:tblStylePr xmlns:w="{W}" w:type="{value}"/>"#);
            let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
            let mut reader = PartReader::new(&doc);
            let region = reader.enumeration(doc.root().unwrap(), "type", REGION);
            (region, reader.invalid_values().len())
        };
        for (name, region) in names {
            assert_eq!(read(name), (Some(region), 0));
        }
        assert_eq!(read("WholeTable"), (None, 1));
    }

    #[test]
    fn each_enumeration_table_holds_each_name_of_its_type() {
        // The names of each simple type in ISO/IEC 29500-4:2016 (Transitional), wml.xsd.
        // ST_TblStyleOverrideType
        crate::enumerations::assert_names(
            REGION,
            concat!(
                "wholeTable firstRow lastRow firstCol lastCol band1Vert band2Vert band1Horz ",
                "band2Horz neCell nwCell seCell swCell",
            ),
        );
        // ST_JcTable, and `both` of ST_Jc, which Word reads as left in a table
        crate::enumerations::assert_names(super::TABLE_JC, "center end left right start both");
        // ST_TblLayoutType
        crate::enumerations::assert_names(super::TABLE_LAYOUT, "fixed autofit");
        // ST_VerticalJc
        crate::enumerations::assert_names(super::CELL_V_ALIGN, "top center both bottom");
        // ST_TblWidth
        crate::enumerations::assert_names(super::PREFERRED_TYPE, "nil pct dxa auto");
        crate::enumerations::assert_names(super::TWIPS_TYPE, "nil pct dxa auto");
        // ST_HeightRule
        crate::enumerations::assert_names(HEIGHT_RULE, "auto exact atLeast");
        // ST_Merge
        crate::enumerations::assert_names(super::MERGE, "continue restart");
        // ST_TextDirection
        crate::enumerations::assert_names(
            super::TEXT_DIRECTION,
            "tb rl lr tbV rlV lrV lrTb tbRl btLr lrTbV tbRlV tbLrV",
        );
    }
}