f-office-docx 0.1.0

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
//! The table after the cascade: its grid lines, the regions and styles of its cells, and
//! their margins and borders.

use std::borrow::Cow;
use std::cell::OnceCell;
use std::num::NonZeroUsize;

use f_office_units::Length;

use super::borders::SideLines;
use super::{Gaps, MergeAbove, Sides, Slot, Span, TopPart, band, heavier, line_room, width};
use crate::layout::Column;
use crate::layout::decisions::TableRules;
use crate::mode::ModeRules;
use crate::props::{Border, Color};
use crate::styles::TableStyle;
use crate::table::{
    Cell, Look, Merge, PreferredWidth, Region, Side, Table, TableAlignment, TableBorders,
    TableProps,
};

/// Where a row stands at a page break. A row that starts a page, below no row of its table,
/// takes the line of the table's top edge; a row below the header rows that repeat at the top
/// of a page meets the last of them; and a row that ends a page, above the next row of its
/// table, takes the line of its bottom edge.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct PageEdges {
    /// What of its table stands above the row on its page.
    pub(super) above: Above,
    /// Whether the row ends a page above the next row of its table.
    pub(super) foot: bool,
}

/// What of its table stands above a row on its page.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) enum Above {
    /// The row before it in the table.
    #[default]
    Row,
    /// No row: the row starts a page.
    Nothing,
    /// The header rows that repeat at the top of the page, of which the row meets the last as
    /// it meets the row before it on one page, with the room that the line drawn there gets.
    Headers(HeaderRoom),
}

/// The room of the row below the header rows that repeat at the top of a page, where the line
/// drawn above it is the wider of its own top line and the last header row's bottom line.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum HeaderRoom {
    /// The room of that drawn line, as below the row before it on one page.
    Line,
    /// The room of the line between it and the row before it in the table, which stands at
    /// the foot of the page before.
    RowBefore,
}

/// A table after the cascade, with the x of its grid lines: the cells of each row with their
/// grid lines, margins and borders, which it builds each time that it is asked, since it keeps
/// no slots.
pub(super) struct TableGrid<'t> {
    pub(super) table: &'t Table,
    pub(super) props: TableProps,
    pub(super) style: TableStyle,
    pub(super) lines: Vec<Length>,
    /// The number of grid columns.
    pub(super) columns: usize,
    /// The number of rows at the top that repeat on each page.
    pub(super) headers: usize,
    /// For a left-aligned table, how far the left edge of the text column lies right of the
    /// device grid: Word draws the lines inside the table from the column edge rounded to the
    /// grid, a half up or down as the target's quirk `TableLines` says. For a centered table
    /// under `CenteredTableLines::FromOuterEdge`, how far the outer edge of its left border
    /// lies right of its rounded dot, and under `CenteredTableLinesBefore15::FromColumnEdge`,
    /// how far the left edge of the text column lies right of its rounded dot. Any other table
    /// has none.
    pub(super) rounding: Option<Length>,
    /// For a left-aligned table whose cells run from left to right, or a centered one that
    /// takes a rounding from its outer edge, what the shift of its grid right of its indent or
    /// outer edge gains when it is rounded up to whole twips; for a centered one that takes a
    /// rounding from the column edge, the half twip that the half of an odd free width loses
    /// when it is rounded down to whole twips, as a length of zero or less. A target whose
    /// table lines are centered on their grid lines, rounded to the device, centers them that
    /// much further right (`TableLines::RoundsCenters`).
    pub(super) twip_rest: Length,
    /// For a centered table that takes a rounding from the column edge, that edge's dot: a
    /// line whose center lies left of it on exactly half a dot takes the dot below. A center
    /// on exactly half a dot takes the dot above in every other case.
    pub(super) halves_away_from: Option<Length>,
    /// For a centered table before mode 15 under `CenteredTableTextBefore15::WholeTwip`, whose
    /// cells run from left to right, the half twip that its place loses when the half of an
    /// odd free width is rounded down to whole twips, as a length of zero or less; for a
    /// left-aligned or centered table from mode 15 under `EdgeTableText::WholeTwipBorder`, what
    /// half its left border gains when it is rounded up to whole twips. The upright text of its
    /// cells starts that much further right. Any other table has none.
    pub(super) text_rest: Length,
    /// For a centered table from mode 15 whose cells run from left to right, under
    /// `CenteredTablePlace::FixedPointHalf`, the outer edge of its left border in fixed-point
    /// points, from which its lines and the text edges of its cells take their dots. Any other
    /// table has none.
    pub(super) outer_place: Option<crate::grid::FixedPlace>,
    /// What the shape takes from the target: how the first cell sets the grid, the columns of a
    /// table with cell spacing, the room of the line between two rows, what a merged cell takes
    /// over its rows, and the borders of the outer cells and of the style regions.
    table_rules: TableRules,
    /// The layout device, which draws the cells' side lines.
    device: crate::grid::Device,
    /// The cells of each row with the grid columns that they cover.
    spans: Vec<Vec<Span<'t>>>,
}

/// A table after the cascade with its grid lines ([`TableGrid`]), which keeps the slots of each
/// row between two rows of the table on one page, each row's built once, when it is first
/// asked for. It is made from the finished grid, so that no slot is asked for before the grid
/// lines are set.
pub(super) struct Shape<'t> {
    /// The table with its grid lines.
    pub(super) grid: TableGrid<'t>,
    /// The kept slots, one cell for each row of the table.
    slots: Vec<OnceCell<Vec<Slot<'t>>>>,
}

/// The cells of a row with the grid columns that they cover.
/// The half twip that a centered table's first grid line `start` loses when it is put on a
/// whole twip past the left edge `left` of its text column: zero for an even free width, minus
/// half a twip for an odd one, the half dropped toward the left.
fn half_twip_rest(start: Length, left: Length) -> Length {
    Length::from_units(-(start - left).units().rem_euclid(Length::UNITS_PER_TWIP))
}

fn row_spans(row: &crate::table::Row) -> Vec<Span<'_>> {
    let mut end = row.grid_before;
    row.cells
        .iter()
        .map(|cell| {
            let first = end;
            end += cell.span.get();
            Span { cell, first, end }
        })
        .collect()
}

/// What a table's shape takes from the layout.
#[derive(Clone, Copy)]
pub(super) struct Context {
    /// The rules of the compatibility mode.
    pub(super) rules: ModeRules,
    /// The layout device.
    pub(super) device: crate::grid::Device,
    /// What the shape takes from the target: how the first cell sets the grid, the columns of a
    /// table with cell spacing, the room of the line between two rows, what a merged cell takes
    /// over its rows, and the borders of the outer cells and of the style regions.
    pub(super) table_rules: TableRules,
    /// Whether the section runs from right to left (`w:bidi`).
    pub(super) right_to_left: bool,
}

/// Whether the saved grid of `table` disagrees with the widths of its cells ([`cell_widths`]).
pub(super) fn cells_disagree(table: &Table) -> bool {
    !table.grid.is_empty()
        && cell_widths(table, table.grid.len()).is_some_and(|cells| cells != table.grid)
}

/// The widths that the cells of `table` give its `columns` grid columns: for each, the widest
/// width in twips of a cell of one column that starts there in any row. `None` when a column has
/// no such cell.
fn cell_widths(table: &Table, columns: usize) -> Option<Vec<Length>> {
    (0..columns)
        .map(|column| {
            table
                .rows
                .iter()
                .filter_map(|row| {
                    let mut start = row.grid_before;
                    row.cells.iter().find_map(|cell| {
                        let here = start;
                        start += cell.span.get();
                        cell.width.and_then(PreferredWidth::length).filter(|width| {
                            here == column
                                && cell.span == NonZeroUsize::MIN
                                && *width > Length::ZERO
                        })
                    })
                })
                .max()
        })
        .collect()
}

impl<'t> Shape<'t> {
    /// The shape of `table` in `column`, with the grid lines of [`TableGrid::new`] and a cell
    /// of kept slots for each row.
    pub(super) fn new(
        table: &'t Table,
        style: TableStyle,
        column: &Column,
        context: &Context,
        least: &[Vec<Length>],
    ) -> Self {
        Self {
            grid: TableGrid::new(table, style, column, *context, least),
            slots: table.rows.iter().map(|_| OnceCell::new()).collect(),
        }
    }

    /// The cells of a row with their grid lines, margins and borders, between two rows of the
    /// table on one page.
    pub(super) fn slots(&self, row: usize) -> &[Slot<'t>] {
        self.slots.get(row).map_or(&[], |slots| {
            slots.get_or_init(|| self.grid.build_slots(row, PageEdges::default()))
        })
    }

    /// The cells of a row with their grid lines, margins and borders, where the row stands at
    /// the page's edges `edges`: the kept slots between two rows on one page, and slots built
    /// for the row at a page's top or foot.
    pub(super) fn slots_at(&self, row: usize, edges: PageEdges) -> Cow<'_, [Slot<'t>]> {
        if edges == PageEdges::default() {
            Cow::Borrowed(self.slots(row))
        } else {
            Cow::Owned(self.grid.build_slots(row, edges))
        }
    }

    /// The cells of row `row` for its part that meets `above` on its page: in a table with
    /// cell spacing whose own outline opens each page's part (`TableGrid::page_part_lines`),
    /// with the room of the line that opens a part at a page's top; else the row's cells.
    pub(super) fn part_slots(&self, row: usize, above: Above) -> Cow<'_, [Slot<'t>]> {
        if self.grid.page_part_lines(row).is_some() {
            self.slots_at(row, PageEdges { above, foot: false })
        } else {
            Cow::Borrowed(self.slots(row))
        }
    }

    /// The width of the border below a row.
    pub(super) fn bottom_border(&self, row: usize) -> Length {
        // With cell spacing, a row holds its cells' bottom lines and the spacing below them,
        // and the table's bottom line follows the spacing again below the last row.
        if let Some(spacing) = self.grid.spacing() {
            return spacing + width(self.grid.outline(row).bottom);
        }
        self.slots(row)
            .iter()
            .map(|slot| width(slot.borders.bottom))
            .max()
            .unwrap_or(Length::ZERO)
    }

    /// The width of the line below a row that ends a page: the line of the row's outer edge,
    /// the cell's own bottom line or the table's, as below the table's last row.
    pub(super) fn foot_border(&self, row: usize) -> Length {
        if self.grid.spacing().is_some() {
            // Below a row other than the table's last, a part of the table that the page's
            // foot ends takes the line that closes it there, where the target draws one.
            let last = row + 1 >= self.grid.table.rows.len();
            return match self.grid.page_part_lines(row) {
                Some((_, foot)) if !last => width(foot),
                _ => self.bottom_border(row),
            };
        }
        let foot = PageEdges {
            foot: true,
            ..PageEdges::default()
        };
        self.slots_at(row, foot)
            .iter()
            .map(|slot| width(slot.borders.bottom))
            .max()
            .unwrap_or(Length::ZERO)
    }

    /// The room below the content of a row that splits at a page's foot: the border below the
    /// row, and in a table with cell spacing whose page parts the target closes as tables of
    /// their own, the cells' bottom lines with the spacing below them and the line that closes
    /// the part there (`TableGrid::page_part_lines`).
    pub(super) fn split_foot_room(&self, row: usize) -> Length {
        match self.grid.page_part_lines(row) {
            Some((_, foot)) => Self::bottoms(self.slots(row)) + width(foot),
            None => self.bottom_border(row),
        }
    }

    /// What a row of a table with cell spacing holds below its cells' content: the largest of
    /// its cells' bottom lines with the spacing below them. Zero without cell spacing.
    pub(super) fn bottoms(slots: &[Slot]) -> Length {
        slots
            .iter()
            .filter_map(|slot| Some(slot.gaps?.bottom + width(slot.borders.bottom)))
            .max()
            .unwrap_or(Length::ZERO)
    }

    /// The part of a row above the content of its cells: the largest room of the cells' top
    /// borders, and with cell spacing the gap above the cells' boxes too.
    pub(super) fn top_part(slots: &[Slot]) -> Length {
        slots
            .iter()
            .map(|slot| slot.gaps.map_or(Length::ZERO, |gaps| gaps.top) + slot.top_room)
            .max()
            .unwrap_or(Length::ZERO)
    }
}

impl<'t> TableGrid<'t> {
    /// The widths of the grid columns between the grid lines, from the leading edge: of a
    /// right-to-left table, from its right edge.
    pub(super) fn column_widths_drawn(&self) -> Vec<Length> {
        self.lines
            .windows(2)
            .filter_map(|pair| match pair {
                [a, b] => Some(if b >= a { *b - *a } else { *a - *b }),
                _ => None,
            })
            .collect()
    }

    /// The table after the cascade in `column`, with its grid lines.
    pub(super) fn new(
        table: &'t Table,
        style: TableStyle,
        column: &Column,
        Context {
            rules,
            device,
            table_rules,
            right_to_left,
        }: Context,
        least: &[Vec<Length>],
    ) -> Self {
        let mut props = style.table.clone();
        props.apply(&table.props);
        let mut grid = Self {
            table,
            props,
            style,
            lines: Vec::new(),
            columns: 0,
            headers: table.rows.iter().take_while(|row| row.header).count(),
            rounding: None,
            twip_rest: Length::ZERO,
            halves_away_from: None,
            text_rest: Length::ZERO,
            outer_place: None,
            table_rules,
            device,
            spans: table.rows.iter().map(row_spans).collect(),
        };
        let widths = grid.column_widths(column.width);
        grid.columns = widths.len();
        // A nested table takes the rule from mode 15 in every mode.
        let rules = rules.for_table(column.cell.is_some());
        let widths = table_rules
            .fitting_cells(|| grid.fitting_cells(&widths, column, rules, least))
            .unwrap_or(widths);
        let total: Length = widths.iter().copied().sum();
        let start = grid.start(column, total, rules);
        // The lines of a left-aligned table are drawn from the column edge rounded to the
        // device grid: to the nearest dot, a half as the target's quirks `TableLines` and
        // `TableEdgeHalves` say.
        match grid.props.alignment {
            Some(TableAlignment::Start) | None => {
                let left = column.left;
                let rounded = device.table_line_edge(left, grid.takes_edge_halves(column));
                grid.rounding = Some(left - rounded);
                if !grid.right_to_left() {
                    let shift = grid.edge_shift(rules);
                    grid.twip_rest = shift.up_to_whole(Length::UNITS_PER_TWIP) - shift;
                }
                grid.text_rest = grid.whole_twip_border_text(&device, rules);
            }
            Some(TableAlignment::Center) => {
                grid.outer_place = grid.fixed_outer_edge(&device, column, total, rules);
                grid.round_outer_edge(&device, start, rules);
                grid.round_column_edge(&device, column, start, rules);
                grid.text_rest = grid.whole_twip_text(&device, column, start, rules)
                    + grid.whole_twip_border_text(&device, rules);
            }
            Some(TableAlignment::End) => {}
        }
        grid.lines = std::iter::once(start)
            .chain(widths.iter().scan(start, |x, &width| {
                *x += width;
                Some(*x)
            }))
            .collect();
        if grid.right_to_left() {
            grid.mirror(column, rules, right_to_left);
        }
        grid
    }

    /// Mirrors the grid of a right-to-left table across the text column, so that its cells
    /// run from the right and its leading edge, with the indent, is at the right. In a
    /// right-to-left `section`, from mode 15, a table that then starts left of the column
    /// starts at the column's left edge and goes over its right edge instead, whatever its
    /// indent and alignment.
    fn mirror(&mut self, column: &Column, rules: ModeRules, section: bool) {
        let axis = column.left * 2 + column.width;
        for line in &mut self.lines {
            *line = axis - *line;
        }
        let over = column.left - self.left_edge();
        if over > Length::ZERO && section && rules.starts_wide_right_to_left_table_at_left() {
            for line in &mut self.lines {
                *line += over;
            }
        }
    }

    /// Whether the cells run from right to left (`w:bidiVisual`).
    pub(super) fn right_to_left(&self) -> bool {
        self.props.right_to_left == Some(true)
    }

    /// The widths of the grid columns. Without a grid, the cells of the first row give them.
    /// A column without a width takes the width that a cell asks for that starts there and
    /// spans one column, where a percent counts from the table's width, and the columns that
    /// still have none share the rest of the table's width. The table's width is its own
    /// preferred width, or the width of the room it sits in.
    fn column_widths(&self, room: Length) -> Vec<Length> {
        let mut widths = self.grid_widths(room);
        let fixed = self.props.layout == Some(crate::table::TableLayout::Fixed);
        if fixed && let Some(spacing) = self.table_rules.cell_width_spacing(self.spacing()) {
            let last = widths.len().saturating_sub(1);
            for (column, width) in widths.iter_mut().enumerate() {
                if let Some(cell) = self.cell_length(column) {
                    let edges = i64::from(column == 0) + i64::from(column == last);
                    *width = cell + spacing * (2 + edges);
                }
            }
        }
        widths
    }

    /// The widths that the cells give the columns of a table of automatic layout at the top
    /// level, without cell spacing and without a preferred width, whose saved grid `grid`
    /// disagrees with them: each column takes the widest width in twips of a cell of one column
    /// that starts there ([`cell_widths`]). `None` when a column has no such cell, when the
    /// widths are the grid's, when a cell's content does not fit the columns that it spans
    /// ([`Self::cells_hold_their_content`] of the least widths `least`), or when their
    /// sum does not fit the room from the table's start to the text column's right edge, which
    /// from mode 15 ends half the last cell's right line before that edge, and before mode 15
    /// the last cell's right margin after it.
    fn fitting_cells(
        &self,
        grid: &[Length],
        column: &Column,
        rules: ModeRules,
        least: &[Vec<Length>],
    ) -> Option<Vec<Length>> {
        let fixed = self.props.layout == Some(crate::table::TableLayout::Fixed);
        let preferred = self
            .props
            .width
            .is_some_and(|width| width != PreferredWidth::Length(Length::ZERO));
        if fixed || preferred || column.cell.is_some() || self.spacing().is_some() {
            return None;
        }
        let cells = cell_widths(self.table, grid.len())?;
        if cells == grid || least.is_empty() {
            return None;
        }
        if !self.cells_hold_their_content(&cells, least) {
            return None;
        }
        let slots = self.build_slots(0, PageEdges::default());
        let end = slots.last()?;
        let right = if rules.aligns_table_edge() {
            -width(end.borders.right).div_toward_zero(2)
        } else {
            end.margins.right
        };
        let indent = match self.props.alignment {
            Some(TableAlignment::Start) | None => self.props.indent.unwrap_or(Length::ZERO),
            Some(TableAlignment::Center | TableAlignment::End) => Length::ZERO,
        };
        let room = column.width + right - indent - self.indent_shift(rules);
        (cells.iter().copied().sum::<Length>() <= room).then_some(cells)
    }

    /// Whether each cell holds its content's least width in `least` (by row and cell) with its
    /// left and right margins within the widths `cells` of the grid columns that it spans.
    fn cells_hold_their_content(&self, cells: &[Length], least: &[Vec<Length>]) -> bool {
        self.table.rows.iter().enumerate().all(|(index, row)| {
            let mut start = row.grid_before;
            row.cells.iter().enumerate().all(|(cell_index, cell)| {
                let spanned: Length = cells
                    .iter()
                    .skip(start)
                    .take(cell.span.get())
                    .copied()
                    .sum();
                start += cell.span.get();
                let content = least
                    .get(index)
                    .and_then(|cells| cells.get(cell_index))
                    .copied()
                    .unwrap_or(Length::ZERO);
                let margins = self.own_margins(index, cell);
                content + margins.left + margins.right <= spanned
            })
        })
    }

    /// The length that a cell of one column gives the grid column `column`, from the first row
    /// with one, or none.
    fn cell_length(&self, column: usize) -> Option<Length> {
        self.table.rows.iter().find_map(|row| {
            let mut start = row.grid_before;
            row.cells.iter().find_map(|cell| {
                let here = start;
                start += cell.span.get();
                cell.width.and_then(PreferredWidth::length).filter(|width| {
                    here == column && cell.span == NonZeroUsize::MIN && *width > Length::ZERO
                })
            })
        })
    }

    /// The table's grid columns, or its first row's cell widths without a grid, with the
    /// columns of no width given a share of the table's width.
    fn grid_widths(&self, room: Length) -> Vec<Length> {
        let mut widths: Vec<Length> = if self.table.grid.is_empty() {
            self.table.rows.first().map_or_else(Vec::new, |row| {
                row.cells
                    .iter()
                    .map(|cell| {
                        cell.width
                            .and_then(PreferredWidth::length)
                            .unwrap_or(Length::ZERO)
                    })
                    .collect()
            })
        } else {
            self.table.grid.clone()
        };
        if widths.iter().all(|width| *width > Length::ZERO) {
            return widths;
        }
        let table = self
            .props
            .width
            .and_then(|width| width.of(room))
            .unwrap_or(room);
        for (column, width) in widths.iter_mut().enumerate() {
            if *width <= Length::ZERO {
                *width = self.asked_width(column, table);
            }
        }
        let missing = widths
            .iter()
            .filter(|width| **width <= Length::ZERO)
            .count();
        let rest = table
            - widths
                .iter()
                .copied()
                .filter(|width| *width > Length::ZERO)
                .sum::<Length>();
        if let Ok(missing @ 1..) = i64::try_from(missing) {
            let share = rest.max(Length::ZERO).div_toward_zero(missing);
            for width in widths.iter_mut().filter(|width| **width <= Length::ZERO) {
                *width = share;
            }
        }
        widths
    }

    /// The width that a cell asks for which starts at a grid column and spans only it, with a
    /// percent of the table's width, or 0.
    fn asked_width(&self, column: usize, table: Length) -> Length {
        self.table
            .rows
            .iter()
            .find_map(|row| {
                let mut start = row.grid_before;
                row.cells.iter().find_map(|cell| {
                    let here = start;
                    start += cell.span.get();
                    cell.width
                        .filter(|_| here == column && cell.span == NonZeroUsize::MIN)
                })
            })
            .and_then(|width| width.of(table))
            .unwrap_or(Length::ZERO)
    }

    /// The x of the first grid line. In a mode before 15, the text of the first cell lines up
    /// with the indent, so the grid line sits one cell margin further left. From mode 15, the
    /// outer edge of the left border sits at the indent, so the grid line sits half a border
    /// further right.
    fn start(&self, column: &Column, total: Length, rules: ModeRules) -> Length {
        let (left, width) = (column.left, column.width);
        match self.props.alignment {
            Some(TableAlignment::Center) => left + (width - total).div_toward_zero(2),
            Some(TableAlignment::End) => left + width - total,
            Some(TableAlignment::Start) | None => {
                let indent = self.props.indent.unwrap_or(Length::ZERO);
                left + indent + self.indent_shift(rules)
            }
        }
    }

    /// How far the first grid line of a table in the text at its leading edge lies in from its
    /// indent (`rules`): [`Self::leading_shift`] for a right-to-left table where the target
    /// takes it, else [`Self::edge_shift`].
    fn indent_shift(&self, rules: ModeRules) -> Length {
        self.leading_shift(rules)
            .unwrap_or_else(|| self.edge_shift(rules))
    }

    /// How far the leading grid line of a right-to-left table at its leading edge lies in from
    /// the indent from mode 15 (`rules`), where the target places it by the lines of its first
    /// row's first and last cell: half the first cell's line at the leading edge, its own or
    /// else the table's, plus half the last cell's line that the file calls left, its own or
    /// else the table's vertical line between cells, which in a row of one cell is the line at
    /// the leading edge again. `None` for another table, before mode 15 and where the target
    /// takes the rule of a table from the left ([`Self::edge_shift`]).
    ///
    /// The slots of a right-to-left table are mirrored: a cell's line that the file calls left
    /// is on its slot's right.
    fn leading_shift(&self, rules: ModeRules) -> Option<Length> {
        if !self.right_to_left() || !rules.aligns_table_edge() {
            return None;
        }
        let slots = self.build_slots(0, PageEdges::default());
        let (first, last) = (slots.first()?, slots.last()?);
        self.table_rules.leading_and_inside(|| {
            width(first.borders.right).div_toward_zero(2)
                + width(last.own_borders.right).div_toward_zero(2)
        })
    }

    /// How far the leftmost grid line of a floating table placed at an offset from its anchor
    /// lies right of that offset (`rules`): [`Self::floating_inside_shift`] for a right-to-left
    /// table where the target takes it, else [`Self::edge_shift`].
    pub(super) fn offset_shift(&self, rules: ModeRules) -> Length {
        self.floating_inside_shift(rules)
            .unwrap_or_else(|| self.edge_shift(rules))
    }

    /// How far the leftmost grid line of a floating right-to-left table placed at an offset lies
    /// left of that offset from mode 15 (`rules`), as a negative length, where the target places
    /// it by the lines of its first row's cells: half the last cell's line that the file calls
    /// left, its own or else the table's vertical line between cells, which in a row of one cell
    /// is the line at the leading edge. The line at the leading edge does not count, as it does
    /// for a table in the text ([`Self::leading_shift`]). `None` for another table, before mode
    /// 15 and where the target takes the rule of a table from the left ([`Self::edge_shift`]).
    fn floating_inside_shift(&self, rules: ModeRules) -> Option<Length> {
        if !self.right_to_left() || !rules.aligns_table_edge() {
            return None;
        }
        let slots = self.build_slots(0, PageEdges::default());
        let last = slots.last()?;
        self.table_rules
            .leading_and_inside(|| -width(last.own_borders.right).div_toward_zero(2))
    }

    /// A centered table whose outer edge sits at its place (`rules`) and whose cells run from
    /// left to right takes its lines from the dot that [`crate::grid::Device::outer_edge_dot`]
    /// gives the outer edge of its left border, half the border left of its first grid line
    /// `start`, with its fixed-point place ([`Self::outer_place`]). The half border is rounded
    /// up to whole twips, as in a left-aligned table.
    fn round_outer_edge(&mut self, device: &crate::grid::Device, start: Length, rules: ModeRules) {
        if !rules.aligns_table_edge() || self.right_to_left() {
            return;
        }
        let shift = self.edge_shift(rules);
        let outer = start - shift;
        let Some(rounded) = device.outer_edge_dot(outer, self.outer_place) else {
            return;
        };
        self.rounding = Some(outer - rounded);
        self.twip_rest = shift.up_to_whole(Length::UNITS_PER_TWIP) - shift;
    }

    /// The outer edge of a centered table whose outer edge sits at its place (`rules`) and whose
    /// cells run from left to right, in fixed-point points where the device keeps one: half of
    /// the free width of `column` less the left border, a grid `total` wide
    /// ([`crate::grid::Device::centered_outer_edge`]).
    fn fixed_outer_edge(
        &self,
        device: &crate::grid::Device,
        column: &Column,
        total: Length,
        rules: ModeRules,
    ) -> Option<crate::grid::FixedPlace> {
        if !rules.aligns_table_edge() || self.right_to_left() {
            return None;
        }
        device.centered_outer_edge(
            (column.origin, column.left),
            (column.width, total),
            self.edge_shift(rules),
        )
    }

    /// Whether `column`'s left edge on exactly half a dot takes the dot that the target's
    /// `TableEdgeHalves` says: the edge of the page's text column for a table in it, and the
    /// table's own place for a floating table placed at an offset across. Not a floating table
    /// aligned across, such as a centered one, whose place lies apart from F-Office's by a
    /// fraction of a twip, and not a nested table, whose column's edge is a cell's text edge.
    fn takes_edge_halves(&self, column: &Column) -> bool {
        column.cell.is_none()
            && self
                .props
                .placement
                .is_none_or(|place| place.x_align.is_none())
    }

    /// A centered table before mode 15 (`rules`) whose cells run from left to right takes its
    /// lines from the dot that [`crate::grid::Device::column_edge_dot`] gives the left edge of
    /// the text column. Its first grid line `start` lies half the free width right of that
    /// edge; the half twip of an odd free width is dropped toward the left, and a line's center
    /// on exactly half a dot is rounded away from the edge's dot.
    fn round_column_edge(
        &mut self,
        device: &crate::grid::Device,
        column: &Column,
        start: Length,
        rules: ModeRules,
    ) {
        if rules.aligns_table_edge() || self.right_to_left() {
            return;
        }
        let left = column.left;
        let Some(rounded) = device.column_edge_dot(left, self.takes_edge_halves(column)) else {
            return;
        };
        self.rounding = Some(left - rounded);
        self.twip_rest = half_twip_rest(start, left);
        self.halves_away_from = Some(rounded);
    }

    /// What the text of a centered table's cells before mode 15 (`rules`), whose cells run from
    /// left to right, loses when the table's first grid line `start` is put on a whole twip
    /// past the left edge of the text column: the half twip of an odd free width, dropped
    /// toward the left, as [`crate::grid::Device::centered_text_loss`] says. Any other table
    /// loses nothing.
    fn whole_twip_text(
        &self,
        device: &crate::grid::Device,
        column: &Column,
        start: Length,
        rules: ModeRules,
    ) -> Length {
        if rules.aligns_table_edge() || self.right_to_left() {
            return Length::ZERO;
        }
        device.centered_text_loss(half_twip_rest(start, column.left))
    }

    /// What the upright text of the cells of a table whose outer edge sits at its place
    /// (`rules`) and whose cells run from left to right gains when half its left border, by
    /// which its first grid line lies right of its outer edge, is rounded up to whole twips, as
    /// [`crate::grid::Device::edge_text_gain`] says. Any other table gains nothing.
    fn whole_twip_border_text(&self, device: &crate::grid::Device, rules: ModeRules) -> Length {
        if !rules.aligns_table_edge() || self.right_to_left() {
            return Length::ZERO;
        }
        device.edge_text_gain(self.edge_shift(rules))
    }

    /// How far the first grid line of a left-aligned table lies right of its indent.
    ///
    /// [`TableGrid::new`] asks for it before the grid lines are set; it reads none of the
    /// fields of the first row's slots that the lines give.
    pub(super) fn edge_shift(&self, rules: ModeRules) -> Length {
        match self.build_slots(0, PageEdges::default()).first() {
            Some(slot) if rules.aligns_table_edge() => width(slot.borders.left).div_toward_zero(2),
            // An explicit indent fixes the first cell text start; an absent indent fixes
            // the grid at the column edge. Cell spacing keeps its earlier rule unless the
            // quirk extends the rule to it.
            Some(slot)
                if let Some(slot) =
                    self.table_rules.fixed_text_start(slot, slot.gaps.is_some())
                    && slot.left_margin_set =>
            {
                match (self.props.indent, slot.gaps) {
                    (None, _) => Length::ZERO,
                    (Some(_), None) => -slot
                        .margins
                        .left
                        .max(width(slot.borders.left).div_toward_zero(2)),
                    (Some(_), Some(gaps)) => {
                        -(slot.margins.left + gaps.left + width(slot.borders.left))
                    }
                }
            }
            Some(slot) => -slot.margins.left,
            None => Length::ZERO,
        }
    }

    /// The x of the table's leftmost grid line.
    fn left_edge(&self) -> Length {
        self.lines.iter().copied().min().unwrap_or(Length::ZERO)
    }

    /// The width of the table between its outer grid lines.
    pub(super) fn width(&self) -> Length {
        self.lines.iter().copied().max().unwrap_or(Length::ZERO) - self.left_edge()
    }

    fn line(&self, index: usize) -> Length {
        self.lines
            .get(index)
            .or(self.lines.last())
            .copied()
            .unwrap_or(Length::ZERO)
    }

    /// The cells of a row with the grid columns that they cover.
    fn spans(&self, row: usize) -> &[Span<'t>] {
        self.spans.get(row).map_or(&[], Vec::as_slice)
    }

    /// The first cell of a row in the order of the markup, with what the table style gives
    /// the paragraphs of the cell.
    pub(super) fn first_cell(&self, row: usize) -> Option<(&'t crate::table::Cell, TableStyle)> {
        let span = *self.spans(row).first()?;
        Some((span.cell, self.region_style(row, span)))
    }

    /// The line whose room the content of the cell `span` of a row below `above` keeps, for a
    /// cell with its own top line `own` that meets the line `top` there.
    ///
    /// Below the header rows, from the mode that keeps it, the row's content keeps the room of
    /// the line between it and the row before it in the table. Below the row before it on one
    /// page, a cell meets the bottom line of each cell above it, and on a target that gives it
    /// their room, its content starts below the widest of them.
    fn room_line(
        &self,
        row: usize,
        span: Span<'t>,
        above: Above,
        (own, top): (Option<Border>, Option<Border>),
    ) -> Option<Border> {
        match above {
            Above::Headers(HeaderRoom::RowBefore) => {
                heavier(own, self.bottom_above(row, span.first, Above::Row))
            }
            Above::Row => self
                .table_rules
                .cells_above(|| heavier(own, self.widest_bottom_above(row, span)))
                .unwrap_or(top),
            _ => top,
        }
    }

    /// Builds the slots of a row that stands at the page's edges `edges`.
    fn build_slots(&self, row: usize, edges: PageEdges) -> Vec<Slot<'t>> {
        let spans = self.spans(row);
        let own: Vec<Sides<Option<Border>>> = spans
            .iter()
            .map(|span| self.own_borders(row, *span, edges))
            .collect();
        let side = |i: Option<usize>, pick: fn(&Sides<Option<Border>>) -> Option<Border>| {
            i.and_then(|i| own.get(i)).and_then(pick)
        };
        let spacing = self.spacing();
        let edge = spans.len().saturating_sub(1);
        let largest = self.largest_margins(row);
        spans
            .iter()
            .enumerate()
            .map(|(i, span)| {
                let mine = own.get(i).copied().unwrap_or_default();
                let merged_above = row > 0 && self.merge_joins(row - 1, span.first);
                // A row that starts a page meets no line of the row above it there, and a row
                // below the header rows that repeat at the top of a page meets the bottom line
                // of the last of them.
                let above = self.bottom_above(row, span.first, edges.above);
                let top = heavier(mine.top, above);
                let room_line = self.room_line(row, *span, edges.above, (mine.top, top));
                // A cell that goes on with a merge below the cell above it has no top line, but
                // at the top of a page, or below the header rows that repeat there, it starts
                // the region's part there and takes its own top line, as every cell of a row
                // that starts a page does.
                let joined_above = merged_above && edges.above == Above::Row;
                let margins = self.margins(row, span.cell, largest);
                let (own_room, edge_room) =
                    self.top_rooms(row, *span, edges, (mine.top, room_line));
                let style = self.region_style(row, *span);
                let shading = self.fill_shading(row, *span, &style, merged_above);
                Slot {
                    cell: span.cell,
                    style,
                    shading,
                    first: span.first,
                    row,
                    merge_above: MergeAbove::of(merged_above, joined_above),
                    merged_below: self.merge_joins(row, span.first),
                    left: self.line(span.first),
                    right: self.line(span.end),
                    edge: self.left_edge(),
                    rounding: self.rounding,
                    twip_rest: self.twip_rest,
                    halves_away_from: self.halves_away_from,
                    text_rest: self.text_rest,
                    outer_place: self.outer_place,
                    margins,
                    left_margin_set: span.cell.margins.left.is_some()
                        || self.row_margins(row).left.is_some()
                        || self.table_rules.unset_side_margin().is_some(),
                    // With cell spacing, each cell keeps its own borders. Its box lies twice
                    // the spacing inside the table's lines and the spacing inside the grid
                    // lines between cells, so neighbor boxes are twice the spacing apart.
                    // Word draws the line between two rows, the wider of the two, from the upper
                    // row's bottom down, and the cell's content starts below that line or below
                    // the cell's own top line and its top margin, whichever is lower.
                    // A cell that goes on with a merged cell draws no line there, and on a target
                    // that gives it the room of that line all the same, its row takes it.
                    top_room: {
                        let room = if spacing.is_some() {
                            width(mine.top)
                        } else {
                            own_room.max(edge_room - margins.top)
                        };
                        if joined_above {
                            self.table_rules
                                .merged_top_room(room)
                                .unwrap_or(Length::ZERO)
                        } else {
                            room
                        }
                    },
                    borders: if spacing.is_some() {
                        Sides {
                            top: mine.top.filter(|_| !joined_above),
                            ..mine
                        }
                    } else {
                        Sides {
                            top: top.filter(|_| !joined_above),
                            left: heavier(mine.left, side(i.checked_sub(1), |s| s.right)),
                            bottom: mine.bottom,
                            right: heavier(mine.right, side(Some(i + 1), |s| s.left)),
                        }
                    },
                    own_borders: mine,
                    top_parts: self.slot_top_parts(row, *span, mine.top, (joined_above, edges)),
                    gaps: spacing.map(|s| Gaps {
                        left: if i == 0 { s * 2 } else { s },
                        right: if i == edge { s * 2 } else { s },
                        // The first row's boxes lie twice the spacing below the table's top
                        // line, and those of a part that a page's top starts one spacing below
                        // the line that opens the part there, if any.
                        top: if row == 0 { s * 2 } else { s }
                            + width(self.opening_line(row, edges.above)),
                        bottom: s,
                        spacing: s,
                    }),
                    sides: SideLines::default(),
                }
            })
            .map(|slot| {
                let mut slot = if self.right_to_left() {
                    slot.mirrored()
                } else {
                    slot
                };
                // The side lines follow the slot's left and right as they stand, mirrored or not.
                slot.sides = SideLines::of(&self.device, &slot);
                slot
            })
            .collect()
    }

    /// The regions of the table style that format a cell, in the order in which they apply:
    /// the whole table, the column bands, the row bands, the first and last column, the first
    /// and last row, and the corner cells. The table's look turns regions on and off. Bands
    /// leave out the first and last rows and columns that have their own formatting.
    fn regions(&self, row: usize, span: Span) -> Vec<Region> {
        let look = self.props.look.unwrap_or_default();
        let first_row = look.has(Look::FIRST_ROW) && row == 0;
        let last_row = look.has(Look::LAST_ROW) && row + 1 == self.table.rows.len();
        let first_col = look.has(Look::FIRST_COLUMN) && span.first == 0;
        let last_col = look.has(Look::LAST_COLUMN) && span.end >= self.columns;
        let mut out = vec![Region::WholeTable];
        if !look.has(Look::NO_COLUMN_BANDS) && !first_col && !last_col {
            let size = self.props.column_band.unwrap_or(NonZeroUsize::MIN);
            let skip = usize::from(look.has(Look::FIRST_COLUMN));
            let index = span.first.saturating_sub(skip) / size;
            out.push(band(index, Region::Band1Vert, Region::Band2Vert));
        }
        if !look.has(Look::NO_ROW_BANDS) && !first_row && !last_row {
            let size = self.props.row_band.unwrap_or(NonZeroUsize::MIN);
            let index = row.saturating_sub(usize::from(look.has(Look::FIRST_ROW))) / size;
            out.push(band(index, Region::Band1Horz, Region::Band2Horz));
        }
        let flags = [
            (first_col, Region::FirstCol),
            (last_col, Region::LastCol),
            (first_row, Region::FirstRow),
            (last_row, Region::LastRow),
            (first_row && first_col, Region::NwCell),
            (first_row && last_col, Region::NeCell),
            (last_row && first_col, Region::SwCell),
            (last_row && last_col, Region::SeCell),
        ];
        out.extend(
            flags
                .iter()
                .filter(|(on, _)| *on)
                .map(|(_, region)| *region),
        );
        out
    }

    /// The paragraph and run properties that the table style gives a cell, with the
    /// formatting of its regions.
    fn region_style(&self, row: usize, span: Span) -> TableStyle {
        let mut style = TableStyle {
            para: self.style.para.clone(),
            run: self.style.run.clone(),
            shading: self.style.shading,
            align: self.style.align,
            ..TableStyle::default()
        };
        for region in self.regions(row, span) {
            if let Some(region) = self.style.region(region) {
                style.para.apply(&region.para);
                style.run.apply(&region.run);
                if region.shading.is_some() {
                    style.shading = region.shading;
                }
                if region.align.is_some() {
                    style.align = region.align;
                }
            }
        }
        style
    }

    /// The cell of a row that covers a grid column.
    /// The shading that a cell's fill draws: its own, else the one that its table style gives
    /// it. A cell that goes on with a merged cell draws its first cell's instead, on a target
    /// whose merged cells take their first cell's fill over all their rows.
    fn fill_shading(
        &self,
        row: usize,
        span: Span<'t>,
        style: &TableStyle,
        merged_above: bool,
    ) -> Option<Color> {
        let first_fill = || {
            let (start, first) = self.region_start(row, span);
            first
                .cell
                .shading
                .or_else(|| self.region_style(start, first).shading)
        };
        merged_above
            .then(|| self.table_rules.first_cell_fill(first_fill))
            .flatten()
            .unwrap_or_else(|| span.cell.shading.or(style.shading))
    }

    /// The row and the cell that start the merged cell that the cell `span` of `row` goes on
    /// with: the nearest cell above it in its first grid column that does not go on with a
    /// merged cell above it.
    fn region_start(&self, row: usize, span: Span<'t>) -> (usize, Span<'t>) {
        let mut start = row;
        while start > 0 && self.merge_joins(start - 1, span.first) {
            start -= 1;
        }
        let first = self
            .spans(start)
            .iter()
            .find(|above| above.first == span.first)
            .copied()
            .unwrap_or(span);
        (start, first)
    }

    fn span_at(&self, row: usize, column: usize) -> Option<Span<'t>> {
        self.spans(row)
            .iter()
            .find(|span| (span.first..span.end).contains(&column))
            .copied()
    }

    /// Whether the cell of `row` that starts at the grid column `first` and the cell of the next
    /// row that starts there form one merged region: the cell of `row` is merged (`w:vMerge`)
    /// and the cell below goes on with it. A cell that goes on with a merge below a cell of the
    /// same column that merges nothing, or below no cell of that column, stands on its own. The
    /// flags of a slot that the cell is merged above and below both take this.
    fn merge_joins(&self, row: usize, first: usize) -> bool {
        let starts = |row: usize| {
            self.spans(row)
                .iter()
                .find(|span| span.first == first)
                .map(|span| span.cell.merge)
        };
        matches!(starts(row), Some(Some(_))) && starts(row + 1) == Some(Some(Merge::Continue))
    }

    /// Whether the row below a row with this slot has cells, but none over the slot's grid
    /// columns, as below a cell over the columns that a shorter row leaves out
    /// (`w:gridBefore`, `w:gridAfter`).
    pub(super) fn open_below(&self, row: usize, slot: &Slot) -> bool {
        let below = self.spans(row + 1);
        let end = slot.first + slot.cell.span.get();
        !below.is_empty()
            && !below
                .iter()
                .any(|span| span.first < end && slot.first < span.end)
    }

    /// The bottom border of the cell above a grid column of a row, in the row that stands
    /// above it on its page (`above`): the row before it, none, or the last of the header rows
    /// that repeat at the top of the page.
    fn bottom_above(&self, row: usize, column: usize, above: Above) -> Option<Border> {
        let above = match above {
            Above::Row => row.checked_sub(1)?,
            Above::Nothing => return None,
            Above::Headers(_) => self.headers.min(row).checked_sub(1)?,
        };
        let span = self.span_at(above, column)?;
        self.own_borders(above, span, PageEdges::default()).bottom
    }

    /// The rooms above the content of the cell of `span` in row `row`: that of its own top side
    /// `own_top`, and that of the edge at the row's top. The edge's is the largest width and
    /// space of the sides that meet there, whichever line `line` the edge draws: the cell's own
    /// and, below the row before it, the bottom side of the cell above.
    fn top_rooms(
        &self,
        row: usize,
        span: Span,
        edges: PageEdges,
        (own_top, line): (Option<Border>, Option<Border>),
    ) -> (Length, Length) {
        let own = line_room(own_top).max(self.own_spaces(row, span).0);
        let above = if edges.above == Above::Row {
            self.bottom_room_above(row, span.first)
        } else {
            Length::ZERO
        };
        (own, above.max(line_room(line)).max(own))
    }

    /// The room that the bottom side of the cell above grid column `column`, in the row before
    /// `row`, keeps above the content of row `row`: the width and the space of its line, or the
    /// space of its side of `none`.
    fn bottom_room_above(&self, row: usize, column: usize) -> Length {
        let Some(above) = row.checked_sub(1) else {
            return Length::ZERO;
        };
        self.span_at(above, column).map_or(Length::ZERO, |span| {
            let line = self.own_borders(above, span, PageEdges::default()).bottom;
            line_room(line).max(self.own_spaces(above, span).1)
        })
    }

    /// The widest bottom border of the cells of the row before `row` that cover one of the
    /// grid columns of `span`, by the rule of two lines that meet ([`heavier`]).
    fn widest_bottom_above(&self, row: usize, span: Span) -> Option<Border> {
        let above = row.checked_sub(1)?;
        self.spans(above)
            .iter()
            .filter(|cell| cell.first < span.end && span.first < cell.end)
            .map(|cell| self.own_borders(above, *cell, PageEdges::default()).bottom)
            .fold(None, heavier)
    }

    /// The parts of the top line of the cell `span` of `row`, on a target whose cells above
    /// draw their own bottom lines along their widths ([`Self::top_parts`]): none with cell
    /// spacing, in a cell `joined_above` by a merge, or where the row meets no row above it.
    fn slot_top_parts(
        &self,
        row: usize,
        span: Span,
        own: Option<Border>,
        (joined_above, edges): (bool, PageEdges),
    ) -> Vec<TopPart> {
        if self.spacing().is_some() || joined_above || edges.above != Above::Row {
            return Vec::new();
        }
        self.table_rules
            .cells_above(|| self.top_parts(row, span, own))
            .unwrap_or_default()
    }

    /// The parts of the top line of the cell `span` of `row`, with its own top line `own`, where
    /// each cell of the row before it draws its own bottom line along its width: one part for
    /// each cell above, with that cell's grid lines and vertical lines, and one for each run of
    /// grid columns that no cell above covers, each the heavier of `own` and that cell's bottom
    /// line, with no part where neither is a line. None where one cell above covers the whole
    /// cell, whose top line is drawn whole.
    fn top_parts(&self, row: usize, span: Span, own: Option<Border>) -> Vec<TopPart> {
        let Some(above) = row.checked_sub(1) else {
            return Vec::new();
        };
        let cells = self.spans(above);
        if cells
            .iter()
            .any(|cell| cell.first <= span.first && span.end <= cell.end)
        {
            return Vec::new();
        }
        let lines: Vec<Sides<Option<Border>>> = cells
            .iter()
            .map(|cell| self.own_borders(above, *cell, PageEdges::default()))
            .collect();
        let line = |i: Option<usize>, pick: fn(&Sides<Option<Border>>) -> Option<Border>| {
            i.and_then(|i| lines.get(i)).and_then(pick)
        };
        let mut parts = Vec::new();
        let mut column = span.first;
        while column < span.end {
            let at = cells
                .iter()
                .position(|cell| (cell.first..cell.end).contains(&column));
            let (first, end, bottom, sides) =
                if let Some((i, cell)) = at.and_then(|i| cells.get(i).map(|cell| (i, cell))) {
                    (
                        cell.first,
                        cell.end,
                        line(Some(i), |s| s.bottom),
                        (
                            heavier(
                                line(Some(i), |s| s.left),
                                line(i.checked_sub(1), |s| s.right),
                            ),
                            heavier(line(Some(i), |s| s.right), line(Some(i + 1), |s| s.left)),
                        ),
                    )
                } else {
                    let next = cells.iter().position(|cell| cell.first > column);
                    let before = next.unwrap_or(cells.len()).checked_sub(1);
                    (
                        before.and_then(|i| cells.get(i)).map_or(0, |cell| cell.end),
                        next.and_then(|i| cells.get(i))
                            .map_or(span.end, |cell| cell.first),
                        None,
                        (line(before, |s| s.right), line(next, |s| s.left)),
                    )
                };
            if let Some(border) = heavier(own, bottom) {
                parts.push(TopPart {
                    left: self.line(first),
                    right: self.line(end),
                    sides,
                    border,
                });
            }
            column = end.min(span.end);
        }
        parts
    }

    /// The cell margins of a row: the table's, with the row's exceptions over them.
    fn row_margins(&self, row: usize) -> crate::table::Margins {
        let mut margins = self.props.margins;
        if let Some(row) = self.table.rows.get(row) {
            margins.apply(&row.exceptions.margins);
        }
        margins
    }

    /// The borders of the table for a row: the table's, with the row's exceptions over them.
    fn row_borders(&self, row: usize) -> TableBorders {
        let mut borders = self.props.borders;
        if let Some(row) = self.table.rows.get(row) {
            borders.apply(&row.exceptions.borders);
        }
        borders
    }

    /// The margins of a cell of a row, with the row's margins over the table's and the
    /// cell's over them. A top or bottom side that none of them sets is 0, and a left or right
    /// one the target's default side margin ([`TableRules::unset_side_margin`]), else 0.
    fn own_margins(&self, row: usize, cell: &Cell) -> Sides<Length> {
        let mut margins = self.row_margins(row);
        margins.apply(&cell.margins);
        let unset_side = self.table_rules.unset_side_margin();
        let length = |m: Option<Length>| m.unwrap_or(Length::ZERO);
        Sides {
            top: length(margins.top),
            left: length(margins.left.or(unset_side)),
            bottom: length(margins.bottom),
            right: length(margins.right.or(unset_side)),
        }
    }

    /// The largest top and the largest bottom margin of the cells of a row.
    fn largest_margins(&self, row: usize) -> (Length, Length) {
        let cells = self.table.rows.get(row).map_or(&[][..], |row| &row.cells);
        let own: Vec<Sides<Length>> = cells
            .iter()
            .map(|cell| self.own_margins(row, cell))
            .collect();
        let largest =
            |side: fn(&Sides<Length>) -> Length| own.iter().map(side).max().unwrap_or(Length::ZERO);
        (largest(|m| m.top), largest(|m| m.bottom))
    }

    /// The margins of a cell: its own left and right margins, and the largest top and the
    /// largest bottom margin of the cells of its row, `largest`
    /// ([`TableGrid::largest_margins`]).
    fn margins(&self, row: usize, cell: &Cell, (top, bottom): (Length, Length)) -> Sides<Length> {
        let own = self.own_margins(row, cell);
        Sides {
            top: top.max(own.top),
            bottom: bottom.max(own.bottom),
            ..own
        }
    }

    /// The borders that a cell sets or takes from the table: the outer borders at the table
    /// edge, at the page's edges `edges` and, as the target's quirk `RowEndBorders` says, on the
    /// outer sides of the row's first and last cell, and the inside borders elsewhere. A cell at
    /// the top of a page below no row of a table whose own outline opens each page's part there
    /// (`page_part_lines`) takes the inside border on top: the table's top line lies above it.
    /// The style regions that format the cell give it their lines first, as the target's quirk
    /// `StyleRegionBorders` says.
    fn own_borders(&self, row: usize, span: Span, edges: PageEdges) -> Sides<Option<Border>> {
        let table = &self.row_borders(row);
        let own = self.own_sides(row, span);
        let (first_cell, last_cell) = self.row_end_sides(row, span);
        let last_row = row + 1 >= self.table.rows.len() || edges.foot;
        // A side of the empty `none` gives way to the table's line, over the line of a region.
        let pick = |own: Option<Side>, outer: bool, edge: Option<Side>, inside: Option<Side>| {
            own.filter(|side| *side != Side::None)
                .or(if outer { edge } else { inside })
                .and_then(Side::line)
                .map(|border| self.table_rules.table_border(border))
        };
        Sides {
            top: pick(
                own.top,
                row == 0 || (edges.above == Above::Nothing && self.page_part_lines(row).is_none()),
                table.top,
                table.inside_h,
            ),
            left: pick(own.left, first_cell, table.left, table.inside_v),
            bottom: pick(own.bottom, last_row, table.bottom, table.inside_h),
            right: pick(own.right, last_cell, table.right, table.inside_v),
        }
    }

    /// The sides that the cell of `span` in row `row` sets: those of the style regions that
    /// format it, as the target's quirk `StyleRegionBorders` gives them, with its own over them.
    fn own_sides(&self, row: usize, span: Span) -> TableBorders {
        let mut own = TableBorders::default();
        for region in self.regions(row, span) {
            if let Some(style) = self.style.region(region) {
                let blocks = || self.block_sides(region, &style.borders, row, span);
                match self.table_rules.block_sides(blocks) {
                    Some(sides) => own.apply(&sides),
                    None => own.apply(&style.borders),
                }
            }
        }
        own.apply(&span.cell.borders);
        own
    }

    /// The spaces of the top and the bottom side of the cell of `span` in row `row` that are
    /// `none` and name one ([`Side::Spaced`]).
    fn own_spaces(&self, row: usize, span: Span) -> (Length, Length) {
        let own = self.own_sides(row, span);
        let space = |side: Option<Side>| match side {
            Some(Side::Spaced(space)) => space,
            _ => Length::ZERO,
        };
        (space(own.top), space(own.bottom))
    }

    /// The side lines that the style region `region`, whose borders are `lines`, gives the cell
    /// of `span` in row `row` as one block of its cells: on each side, the region's line of
    /// that side where the cell across it is not in the region or there is none, else the
    /// region's line between rows or between columns.
    fn block_sides(
        &self,
        region: Region,
        lines: &TableBorders,
        row: usize,
        span: Span,
    ) -> TableBorders {
        let spans = self.spans(row);
        let index = spans.iter().position(|other| other.first == span.first);
        let beside = |step: fn(usize) -> Option<usize>| {
            index
                .and_then(step)
                .and_then(|i| spans.get(i))
                .is_some_and(|other| self.regions(row, *other).contains(&region))
        };
        let across = |other: Option<usize>| {
            other.is_some_and(|other| {
                self.span_at(other, span.first)
                    .is_some_and(|cell| self.regions(other, cell).contains(&region))
            })
        };
        let pick = |within: bool, side: Option<Side>, between: Option<Side>| {
            if within { between } else { side }
        };
        TableBorders {
            top: pick(across(row.checked_sub(1)), lines.top, lines.inside_h),
            left: pick(beside(|i| i.checked_sub(1)), lines.left, lines.inside_v),
            bottom: pick(across(Some(row + 1)), lines.bottom, lines.inside_h),
            right: pick(beside(|i| i.checked_add(1)), lines.right, lines.inside_v),
            ..*lines
        }
    }

    /// Whether the cell of `span` in row `row` takes the table's outer left and outer right
    /// border: at the grid's first and last column, and under `RowEndBorders::RowEnds` also as
    /// the row's first and last cell.
    fn row_end_sides(&self, row: usize, span: Span) -> (bool, bool) {
        let (first, last) = (span.first == 0, span.end >= self.columns);
        let ends = || {
            let cells = self.spans(row);
            (
                first || cells.first().is_some_and(|cell| cell.first == span.first),
                last || cells.last().is_some_and(|cell| cell.end == span.end),
            )
        };
        self.table_rules
            .row_end_cells(ends)
            .unwrap_or((first, last))
    }

    /// Whether header rows of the table stand above `row`, and so repeat above it at the top of
    /// a new page.
    pub(super) fn has_headers_above(&self, row: usize) -> bool {
        self.headers.min(row) > 0
    }

    /// The table's cell spacing, when it has one.
    pub(super) const fn spacing(&self) -> Option<Length> {
        self.props.cell_spacing
    }

    /// The table's own top and bottom lines with which each page's part of a table with cell
    /// spacing opens and closes at a page break, where the target draws them there
    /// (`TableRules::page_part_lines`), for row `row`. `None` for a table without cell spacing
    /// and where the target draws the table's outline around the whole table only.
    pub(super) fn page_part_lines(&self, row: usize) -> Option<(Option<Border>, Option<Border>)> {
        self.spacing()?;
        let outline = self.outline(row);
        self.table_rules
            .page_part_lines((outline.top, outline.bottom))
    }

    /// The table's own line that a table with cell spacing draws above row `row`, which meets
    /// `above` on its page: the table's top line above its first row, and the line that opens a
    /// part of the table at the top of a page below no row of the table (`page_part_lines`).
    pub(super) fn opening_line(&self, row: usize, above: Above) -> Option<Border> {
        if row == 0 {
            self.outline(row).top
        } else if above == Above::Nothing {
            self.page_part_lines(row).and_then(|(top, _)| top)
        } else {
            None
        }
    }

    /// The lines of the table's own outline in a row, for a table with cell spacing.
    pub(super) fn outline(&self, row: usize) -> Sides<Option<Border>> {
        let borders = self.row_borders(row);
        let line = |side: Option<Side>| {
            side.and_then(Side::line)
                .map(|border| self.table_rules.table_border(border))
        };
        Sides {
            top: line(borders.top),
            left: line(borders.left),
            bottom: line(borders.bottom),
            right: line(borders.right),
        }
    }
}