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
//! Rows that split between two pages.
//!
//! While a row splits, each of its cells lays out its content into a `Fragment`. The lines
//! that stay on this page put their items among the layout's items, as everywhere. At the
//! first line that goes to the next page, the cell stops on this page: the page's items go
//! aside into the fragment, and the layout's items, empty again, fill the part of the cell for
//! the next page, and then each part for a page after it. When the cell ends, the page's items
//! come back, and the last part takes the layout's items. So a count of the layout's items
//! taken before the stop, such as `Stop::items`, counts the items of this page, and a line
//! placed after the stop gets the record `FirstItem::Carried`, never an index into the items
//! of a part. `Fragment::stop_here` sets the items aside, and `Layout::fragment_content` gives
//! them back.

use std::ops::Range;

use f_office_paint::Item;
use f_office_units::Length;

use super::borders::{OutlineEnd, RowTop};
use super::merges::{Carried, Merges, Open};
use super::rows::cell_fills;
use super::shape::{Above, PageEdges};
use super::{Shape, Slot, align, move_items, move_items_by};
use crate::layout::page_items::{FillsEntry, PageItems};
use crate::layout::{FirstItem, Layout, decisions};

/// The limit of a part that has none, as on the pages after a row with merged cells splits.
pub(super) const NO_LIMIT: Length = Length::from_units(i64::MAX);

/// Where the parts of a cell of a row that splits end and start: two limits and one top.
#[derive(Clone, Copy, Debug)]
pub(super) struct PartLimits {
    /// The lowest bottom of a line that stays on this page.
    pub(super) limit: Length,
    /// Where the content of the cell goes on on the next page.
    pub(super) next_top: Length,
    /// The lowest bottom of a line on a page after this one, the next page and the pages after
    /// it alike. A line below it starts a new part of the cell, for the page after.
    pub(super) later_limit: Length,
}

/// Where a cell of a row that splits stopped on this page, once a line went to the next page.
#[derive(Clone, Copy, Debug)]
struct Stop {
    /// The bottom of the cell's content on this page.
    y: Length,
    /// The number of items on this page then.
    items: usize,
}

/// A cell of a row that splits, laid out over the pages that it needs: its part on this page
/// stays among the layout's items, and its parts for the pages after it are kept here, the
/// next page's first.
#[derive(Debug)]
pub(in crate::layout) struct Fragment {
    limits: PartLimits,
    /// Where the cell stopped on this page.
    ///
    /// `stop`, `drawn` and `kept` tell about the part on this page alone: where the cell
    /// ends there and whether it keeps a line there, which decides whether its row splits or
    /// moves whole. A part on a later page needs neither: it holds its first line, whatever
    /// its height.
    stop: Option<Stop>,
    /// The number of items of floating drawings on this page before the stop. A drawing
    /// alone does not keep a part of the cell on this page.
    drawn: usize,
    /// The number of lines that stay on this page, also lines that draw nothing.
    kept: usize,
    /// After the stop: the page items of this page, with their border lines and cell clips,
    /// which the layout holds again when the cell ends. Meanwhile the layout's page items
    /// fill the part being filled.
    page_items: PageItems,
    /// The parts that are full.
    parts: Vec<Part>,
    /// The number of line records when the part being filled started.
    part_start: usize,
    /// Whether a floating table in the cell holds the later parts back.
    held: bool,
}

impl Fragment {
    const fn new(limits: PartLimits) -> Self {
        Self {
            limits,
            stop: None,
            drawn: 0,
            kept: 0,
            page_items: PageItems::new(),
            parts: Vec::new(),
            part_start: 0,
            held: false,
        }
    }

    /// For a table in this cell: the lowest bottom of a row in the part of the cell that is
    /// being filled, the top of the content in the next part, and the lowest bottom of a row
    /// in the parts after it.
    pub(super) const fn part_limits(&self) -> PartLimits {
        PartLimits {
            limit: if self.stop.is_none() {
                self.limits.limit
            } else {
                self.limits.later_limit
            },
            ..self.limits
        }
    }

    /// Whether the cell has stopped on this page and moved on to a later part.
    pub(super) const fn moved_on(&self) -> bool {
        self.stop.is_some()
    }

    /// Counts a row of a table in this cell that stays on the page where the row splits.
    pub(super) const fn keep_inner_row(&mut self) {
        if self.stop.is_none() {
            self.kept += 1;
        }
    }

    /// Stops the cell on this page at `y`, where its content ends there: the page's items,
    /// which `items` hold with their border lines and cell clips, go aside, and `items`, empty
    /// again, fill the part for the next page, whose lines start at line record `records`.
    /// Gives the top of the content in that part.
    fn stop_here(&mut self, y: Length, items: &mut PageItems, records: usize) -> Length {
        self.stop = Some(Stop {
            y,
            items: items.count(),
        });
        std::mem::swap(items, &mut self.page_items);
        self.part_start = records;
        self.limits.next_top
    }

    /// Ends the part for a later page that `items` hold, at its bottom `y` and before line
    /// record `records`, and starts the next part there, with `items` afresh: the parts on
    /// later pages show uncut. Gives the top of the content in the next part.
    fn end_later_part(&mut self, y: Length, items: &mut PageItems, records: usize) -> Length {
        self.parts.push(Part {
            items: std::mem::take(items).into_items(),
            records: self.part_start..records,
            bottom: y,
        });
        self.part_start = records;
        self.limits.next_top
    }
}

/// Where a part of a row that splits ends.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum PartEnd {
    /// At the foot of its page, where the row goes on on the next page.
    PageFoot,
    /// With the row's last line, on the row's last page.
    RowEnd,
}

/// A part of a cell on a later page: its items, the records of its lines, and its bottom.
#[derive(Debug, Default)]
pub(super) struct Part {
    pub(super) items: Vec<Item>,
    pub(super) records: Range<usize>,
    pub(super) bottom: Length,
}

/// One cell of a row that splits.
pub(super) struct SplitCell {
    /// The bottom of the cell's part on this page.
    pub(super) end: Length,
    /// The bottom of the cell's part on the next page.
    pub(super) next_end: Length,
    /// Whether the cell keeps a line on this page.
    keeps: bool,
    /// Whether lines of the cell go on on the next page, also lines that draw nothing.
    pub(super) continues: bool,
    /// For a cell that is not merged with the cell below: its item range and bottom on this page,
    /// used to apply vertical alignment (`w:vAlign`) within the row's part on this page.
    pub(super) page_part: Option<(Range<usize>, Length)>,
    /// The parts of the cell for the pages after the next one, when the cell needs more than
    /// two pages, each with its own bottom.
    pub(super) later: Vec<Part>,
    /// For a cell that goes on: the index of the first line record of its part for the next
    /// page.
    pub(super) carried_from: usize,
}

impl Layout<'_> {
    /// Splits a row that does not fit between this page and the next. In each cell, the lines
    /// that fit with their full height, the cell's bottom margin and the border below the row
    /// stay on this page, and the rest go to the next page below the header rows. A row of
    /// which no line fits is not split. The part on this page draws its top line from the
    /// row's top `row_top` with its twips rest; the parts on later pages have none. On a target
    /// that fills the parts, each part fills its filled cells as a whole row does.
    pub(super) fn split_row(
        &mut self,
        shape: &mut Shape,
        index: usize,
        row_top: RowTop,
        merges: &mut Merges,
    ) -> bool {
        let top = row_top.at;
        let start_left = shape.grid.left_edge();
        let mark = self.row_mark();
        let next_top = self.next_area_top();
        self.move_to(next_top);
        // The header rows are laid out here only to measure them, and again on the next page.
        let headers = self.headers(shape, index);
        self.back_to_row_mark(&mark);
        let above = self.page_edges(index, merges).above;
        let limit = self.body_end() - shape.split_foot_room(index);
        let later = self.later_limit(shape, index, merges);
        let later_above = self.later_above(shape, index);
        let next_above = later_above.unwrap_or(Above::Row);
        let next =
            next_top + headers + Shape::top_part(&Self::next_page_slots(shape, index, later_above));
        let (mut cells, ranges, mut carried, end) = {
            let here = shape.part_slots(index, above);
            let slots = &*here;
            let border = Shape::top_part(slots);
            // A row that keeps no line here is laid out again where it moves to.
            let trial = self.output.start_trial();
            let fills = self.part_fills();
            let (cells, ranges, carried) =
                self.split_cells(slots, merges, (top + border, (limit, later), next));
            let splits = keeps_lines(&cells);
            self.output.end_trial(trial, splits);
            if !splits {
                self.back_to_row_mark(&mark);
                return false;
            }
            let min_end = (top + Self::minimum(shape, index)).min(limit);
            let end = cells
                .iter()
                .map(|cell| cell.end)
                .max()
                .unwrap_or(top)
                .max(min_end);
            // Each cell that is not merged below takes its vertical alignment in the part of the row
            // on this page, whether it finishes on this page or continues onto the next.
            for (slot, cell) in slots.iter().zip(&cells) {
                if let Some((range, bottom)) = cell.page_part.clone() {
                    let shift = align(slot.align(), end - bottom);
                    self.shift(range, self.device.snap(shift));
                }
            }
            for slot in slots {
                self.cell_borders(slot, (row_top, end), true);
            }
            self.fill_part(slots, fills, (top, end));
            self.part_outline(
                shape,
                (index, slots),
                (top, end),
                (above, PartEnd::PageFoot),
            );
            (cells, ranges, carried, end)
        };
        // The records of the lines that go on on the next column or page get its index there.
        // The records that the page's end adds, such as those of its footnotes, stay on the page.
        let rows = mark.lines..self.output.placed.len();
        self.end_turned_regions(shape, merges, end);
        self.next_column();
        self.realign_table(shape);
        let dx = self.device.snap(shape.grid.left_edge() - start_left);
        move_items_by(&mut carried, dx, Length::ZERO);
        self.place_split_records(rows, &cells, dx);
        let (top, end, fills) = {
            let here = shape.part_slots(index, above);
            let slots = &*here;
            self.carry_region_records(merges, slots, next, dx);
            self.headers(shape, index);
            let top = self.y;
            let fills = self.part_fills();
            let placed = self.place_carried_cells(slots, merges, (&ranges, carried));
            // The part of the row on the next page is as tall as its cells that do not go on in
            // the next row; a region's content there makes only its last row taller.
            let end = cells
                .iter()
                .zip(slots)
                .filter(|(_, slot)| !(slot.merged_below && flows(slot, merges)))
                .map(|(cell, _)| cell.next_end)
                .max()
                .unwrap_or(top);
            merges.open = next_regions(merges, (slots, &cells, &placed), next);
            (top, end, fills)
        };
        // The part of the row on the next page has the row's minimum height again.
        let (top, end, fills) = self.later_parts(
            shape,
            (index, later_above, next_above),
            start_left,
            &mut cells,
            (top, end, fills),
        );
        let end = end.max(top + Self::minimum(shape, index));
        let last = index + 1 == shape.grid.table.rows.len();
        let next_slots = Self::next_page_slots(shape, index, later_above);
        for slot in &*next_slots {
            self.cell_borders(slot, (RowTop::without_rest(top), end), last);
        }
        self.fill_part(&next_slots, fills, (top, end));
        let part = (next_above, PartEnd::RowEnd);
        let end = self.part_outline(shape, (index, &next_slots), (top, end), part);
        self.move_to(end);
        true
    }

    /// The slots of row `index` for its continuation parts on pages after the first.
    fn next_page_slots<'a, 't>(
        shape: &'a Shape<'t>,
        index: usize,
        later_above: Option<Above>,
    ) -> std::borrow::Cow<'a, [Slot<'t>]> {
        match later_above {
            Some(above) => shape.slots_at(index, PageEdges { above, foot: false }),
            None => std::borrow::Cow::Borrowed(shape.slots(index)),
        }
    }

    /// Assigns the current page and horizontal shift `dx` to the carried line records of a split
    /// row's second-page part (excluding records belonging to `cell.later` parts on pages 3+).
    fn place_split_records(&mut self, rows: Range<usize>, cells: &[SplitCell], dx: Length) {
        let page = self.output.pages.len();
        for (idx, line) in self
            .output
            .placed
            .get_mut(rows.clone())
            .into_iter()
            .flatten()
            .enumerate()
        {
            if line.item != FirstItem::Carried {
                continue;
            }
            line.page = page;
            let pos = rows.start + idx;
            let in_later = cells
                .iter()
                .any(|c| c.later.iter().any(|p| p.records.contains(&pos)));
            if !in_later {
                line.move_right(dx);
            }
        }
    }

    /// Draws the table's own lines beside the part of row `index` of a table with cell spacing
    /// that stands from `top` to the end of its cells' content `end`, with its slots `slots`,
    /// where the target closes each page's part of such a table as a table of its own
    /// (`TableGrid::page_part_lines`): the line that opens the part where it meets `above`, the
    /// side lines, and below the boxes' bottom lines and the spacing, where the part ends, the
    /// line that closes the part at the page's foot or the outline's end below the row. Gives
    /// the bottom of the part with the boxes' bottom lines and the spacing, or `end` where the
    /// target draws no such lines.
    fn part_outline(
        &mut self,
        shape: &Shape,
        (index, slots): (usize, &[Slot]),
        (top, end): (Length, Length),
        (above, part_end): (Above, PartEnd),
    ) -> Length {
        let Some((_, foot)) = shape.grid.page_part_lines(index) else {
            return end;
        };
        let bottom = end + Shape::bottoms(slots);
        let close = match part_end {
            PartEnd::PageFoot => OutlineEnd::Page(foot),
            PartEnd::RowEnd => OutlineEnd::of_row(shape, index),
        };
        let opening = shape.grid.opening_line(index, above);
        self.table_outline(shape, (index, slots), (top, bottom), (opening, close));
        bottom
    }

    /// The fills entry of the part of a row that splits that starts here, under the part's
    /// content, on a target that fills the parts ([`decisions::split_part_fills`]).
    fn part_fills(&mut self) -> Option<FillsEntry> {
        decisions::split_part_fills(&self.context.quirks, &mut self.items)
            .map(PageItems::open_fills)
    }

    /// Fills the filled cells of the part of a row that splits from `top` to `end` into the
    /// part's fills entry `fills`, below the part's top line, as a whole row fills them. A cell
    /// that continues a merged region gets no fill there.
    fn fill_part(
        &mut self,
        slots: &[Slot],
        fills: Option<FillsEntry>,
        (top, end): (Length, Length),
    ) {
        let Some(entry) = fills else {
            return;
        };
        let device = self.device;
        let (fills, _) = cell_fills(
            (slots, &self.context.quirks, |place| device.snap(place)),
            (top, top + Shape::top_part(slots), end),
        );
        self.items.put_fills(entry, fills);
    }

    /// What lies above the parts of row `index` on later pages. They meet the last of the
    /// header rows that repeat there where the target's row meets it, and else take the row's
    /// top border again. Without header rows above them, they take the lines of a row that
    /// starts a page, and their content the room of its top line.
    fn later_above(&self, shape: &Shape, index: usize) -> Option<Above> {
        if shape.grid.has_headers_above(index) {
            self.below_headers(shape, index)
        } else {
            Some(Above::Nothing)
        }
    }

    /// Places the content that the cells of a row that split carry to the next page, `carried`
    /// with the part of each cell in `ranges`, and gives the entries of each part. A region
    /// that goes on keeps a fills entry before its part.
    fn place_carried_cells(
        &mut self,
        slots: &[Slot],
        merges: &Merges,
        (ranges, carried): (&[Range<usize>], Vec<Item>),
    ) -> Vec<Placed> {
        let mut carried = carried.into_iter();
        let mut placed = Vec::new();
        for (slot, range) in slots.iter().zip(ranges) {
            let region = slot.merged_below && flows(slot, merges);
            let fills = region.then(|| self.items.open_fills());
            let start = self.items.len();
            self.items.extend(carried.by_ref().take(range.len()));
            placed.push((fills, start..self.items.len()));
        }
        placed
    }

    /// Whether row `index`, with its top at `top`, splits there, as [`Self::split_row`] tests
    /// it, measured without placing it.
    pub(super) fn splits_with_lines(
        &mut self,
        shape: &Shape,
        (index, top): (usize, Length),
        merges: &Merges,
    ) -> bool {
        let mark = self.mark();
        let slots = shape.slots(index);
        let border = Shape::top_part(slots);
        let limit = self.body_end() - shape.split_foot_room(index);
        let next = self.next_area_top() + border;
        // The test asks only about the first break, so the later pages have no limit.
        let limits = (limit, NO_LIMIT);
        let (cells, _, _) = self.split_cells(slots, merges, (top + border, limits, next));
        self.rewind(&mark);
        keeps_lines(&cells)
    }

    /// The lowest bottom of a line of a row's part on a page after the one where the row
    /// splits. A row without merged cells goes on over as many pages as its content needs; a
    /// row with merged cells has no such limit, and its rest stays on the next page.
    fn later_limit(&self, shape: &Shape, index: usize, merges: &Merges) -> Length {
        let slots = shape.slots(index);
        let joined =
            !merges.open.is_empty() || slots.iter().any(|s| s.merged_above() || s.merged_below);
        if joined {
            NO_LIMIT
        } else {
            self.page_bottom() - shape.split_foot_room(index)
        }
    }

    /// Goes on with a row whose cells need more than two pages. The part of the row from
    /// `top` to `end` is the last one when no cell has a later part. Otherwise each part
    /// ends below the content of its tallest cell, and the next part starts on the page after
    /// it, below the header rows. Each part draws the borders of `slots`, the row's cells where
    /// it stands on those pages, and fills its filled cells into its fills entry, `fills` for
    /// the part from `top`. Gives the top, the end and the fills entry of the row's last part.
    fn later_parts(
        &mut self,
        shape: &mut Shape,
        (index, later_above, above): (usize, Option<Above>, Above),
        start_left: Length,
        cells: &mut [SplitCell],
        (mut top, mut end, mut fills): (Length, Length, Option<FillsEntry>),
    ) -> (Length, Length, Option<FillsEntry>) {
        let parts = cells.iter().map(|c| c.later.len()).max().unwrap_or(0);
        for part in 0..parts {
            {
                let slots = Self::next_page_slots(shape, index, later_above);
                for slot in &*slots {
                    self.cell_borders(slot, (RowTop::without_rest(top), end), true);
                }
                self.fill_part(&slots, fills, (top, end));
                self.part_outline(
                    shape,
                    (index, &slots),
                    (top, end),
                    (above, PartEnd::PageFoot),
                );
            }
            self.next_column();
            self.realign_table(shape);
            let dx = self.device.snap(shape.grid.left_edge() - start_left);
            self.headers(shape, index);
            top = self.y;
            end = top;
            fills = self.part_fills();
            for cell in cells.iter_mut() {
                end = end.max(self.later_part(cell, part, top, dx));
            }
        }
        (top, end, fills)
    }

    /// Puts the part `part` of a cell on this page, shifted right by `dx`, with the records of
    /// its lines, and gives its bottom, or the row's `top` when the cell ended on a page before.
    fn later_part(&mut self, cell: &mut SplitCell, part: usize, top: Length, dx: Length) -> Length {
        let Some(Part {
            items,
            records,
            bottom,
        }) = cell.later.get_mut(part)
        else {
            return top;
        };
        move_items_by(items, dx, Length::ZERO);
        self.items.append(items);
        let page = self.output.pages.len();
        for line in self
            .output
            .placed
            .get_mut(records.clone())
            .into_iter()
            .flatten()
        {
            if line.item == FirstItem::Carried {
                line.page = page;
                line.move_right(dx);
            }
        }
        *bottom
    }

    /// Lays out the cells of a row that splits, as [`Self::split_cell`] does, and gives the
    /// cells, the range of each one's items in the items for the next page, and those items.
    /// A cell that continues a region whose content goes on on the next page carries that
    /// content there.
    fn split_cells(
        &mut self,
        slots: &[Slot],
        merges: &Merges,
        (top, limits, next): (Length, (Length, Length), Length),
    ) -> (Vec<SplitCell>, Vec<Range<usize>>, Vec<Item>) {
        let mut carried = Vec::new();
        let mut cells = Vec::new();
        let mut ranges = Vec::new();
        for slot in slots {
            let from = carried.len();
            let region = merges
                .open
                .iter()
                .find(|open| slot.merged_above() && open.first == slot.first)
                .filter(|open| open.carried.is_some());
            cells.push(match region {
                Some(open) => region_part(slot, open, next, &mut carried),
                None => self.split_cell(slot, (top, limits, next), &mut carried, false),
            });
            ranges.push(from..carried.len());
        }
        (cells, ranges, carried)
    }

    /// Gives the records of the lines that the regions open above a row of `slots` carry on
    /// their place below `next` on this page, for the regions that go on in the row.
    fn carry_region_records(&mut self, merges: &Merges, slots: &[Slot], next: Length, dx: Length) {
        for open in &merges.open {
            let continues = slots
                .iter()
                .any(|slot| slot.merged_above() && slot.first == open.first);
            if let Some(part) = open.carried.as_ref().filter(|_| continues) {
                self.carried_records(part.records.clone(), (dx, next - part.base));
            }
        }
    }

    /// Lays out one cell of a row that splits, with the content below `top`. The lines that
    /// end below `limit` and the cell's bottom margin go to `carried`, for the part of the row
    /// on the next page, whose content starts at `next`. `moved_on` is as for
    /// [`Self::content`].
    pub(super) fn split_cell(
        &mut self,
        slot: &Slot,
        (top, (limit, later), next): (Length, (Length, Length), Length),
        carried: &mut Vec<Item>,
        moved_on: bool,
    ) -> SplitCell {
        let limits = PartLimits {
            limit: limit - slot.margins.bottom,
            next_top: next + slot.margins.top,
            // Only `NO_LIMIT` reaches the bound, and it stays there.
            later_limit: later.saturating_sub(slot.margins.bottom),
        };
        let (first, drawn) = (self.items.len(), self.items.count());
        let (bottom, fragment) = self.fragment_content(slot, top, limits, moved_on);
        // The first part goes to the next page, and the others to the pages after it.
        let mut parts = fragment.parts.into_iter();
        let next_part = parts.next().unwrap_or_default();
        carried.extend(next_part.items);
        match fragment.stop {
            // A line that draws nothing, such as that of an empty paragraph, counts as a line
            // on both sides of the split: it keeps the cell on this page, and it carries the
            // cell on to the next page.
            Some(stop) => {
                let end = stop.y + slot.margins.bottom;
                SplitCell {
                    end,
                    next_end: next_part.bottom,
                    keeps: fragment.kept > 0 || stop.items.saturating_sub(fragment.drawn) > drawn,
                    continues: true,
                    page_part: (!slot.merged_below).then_some((first..self.items.len(), end)),
                    later: parts.collect(),
                    carried_from: next_part.records.start,
                }
            }
            None => SplitCell {
                end: bottom,
                next_end: next + slot.margins.top + slot.margins.bottom,
                keeps: true,
                continues: false,
                page_part: (!slot.merged_below).then_some((first..self.items.len(), bottom)),
                later: Vec::new(),
                carried_from: 0,
            },
        }
    }

    /// Lays out the content of the first cell of a merged region below `top`, as a cell of a
    /// row that splits: the lines that end below `limit`, with the cell's bottom margin, go on
    /// below `base` on the next page. Gives the bottom of the content on this page, and the
    /// part that goes on. `moved_on` is as for [`Self::content`].
    pub(super) fn region_content(
        &mut self,
        slot: &Slot,
        top: Length,
        (limit, base): (Length, Length),
        moved_on: bool,
    ) -> (super::rows::CellBottom, Option<Carried>) {
        let limits = PartLimits {
            limit: limit - slot.margins.bottom,
            next_top: base + slot.margins.top,
            later_limit: NO_LIMIT,
        };
        let records = self.output.placed.len();
        let (bottom, mut fragment) = self.fragment_content_bottom(slot, top, limits, moved_on);
        let Some(stop) = fragment.stop else {
            return (bottom, None);
        };
        // The region's content has no later limit, so the part that goes on is its last.
        let part = Carried {
            items: fragment.parts.pop().unwrap_or_default().items,
            base,
            bottom: bottom.row,
            records: records..self.output.placed.len(),
        };
        let stop_bottom = stop.y + slot.margins.bottom;
        (
            super::rows::CellBottom {
                row: stop_bottom,
                align: stop_bottom,
            },
            Some(part),
        )
    }

    /// Lays out the content of a cell below `top`, as [`Self::content`] does, as a cell of a
    /// row that splits, returning its [`super::rows::CellBottom`] and [`Fragment`].
    fn fragment_content_bottom(
        &mut self,
        slot: &Slot,
        top: Length,
        limits: PartLimits,
        moved_on: bool,
    ) -> (super::rows::CellBottom, Fragment) {
        self.fragment = Some(Fragment::new(limits));
        let bottom = self.content(slot, top, moved_on);
        let Some(mut fragment) = self.fragment.take() else {
            return (bottom, Fragment::new(limits));
        };
        if fragment.stop.is_some() {
            for part in &mut fragment.parts {
                part.bottom += slot.margins.bottom;
            }
            let items =
                std::mem::replace(&mut self.items, std::mem::take(&mut fragment.page_items));
            fragment.parts.push(Part {
                items: items.into_items(),
                records: fragment.part_start..self.output.placed.len(),
                bottom: bottom.row,
            });
        }
        (bottom, fragment)
    }

    /// Lays out the content of a cell below `top`, as [`Self::content`] does, as a cell of a
    /// row that splits, whose parts end and start at `limits`, the cell's margins taken off.
    /// Gives the bottom of the content with the cell's bottom margin, and the cell's fragment:
    /// once the cell stopped on this page, its parts for the pages after it, each with its
    /// bottom and the cell's bottom margin. `moved_on` is as for [`Self::content`].
    fn fragment_content(
        &mut self,
        slot: &Slot,
        top: Length,
        limits: PartLimits,
        moved_on: bool,
    ) -> (Length, Fragment) {
        let (bottom, fragment) = self.fragment_content_bottom(slot, top, limits, moved_on);
        (bottom.row, fragment)
    }

    /// Adds the items of a floating drawing in a table cell, in the order of the text, which
    /// lies in front of the text when `front` is true. No cell clip cuts them. A drawing behind
    /// the text that a shaded paragraph anchors goes into the paragraph's drawings entry, under
    /// its fill, while that entry is among the page items.
    pub(in crate::layout) fn cell_drawing(&mut self, items: Vec<Item>, front: bool) {
        if let Some(fragment) = self.fragment.as_mut().filter(|f| f.stop.is_none()) {
            fragment.drawn += items.len();
        }
        let under_fill =
            (self.drawings_under_fill).filter(|entry| !front && self.items.holds_fills(*entry));
        match under_fill {
            Some(entry) => self.items.put_fills(entry, items),
            None => self.items.push_drawing(items, front),
        }
    }

    /// The lowest bottom of a line in the part being filled of the cell of a row that splits,
    /// for widow control there: the limit of this page while the cell has not yet moved on to
    /// the next page, and on a target that asks, the limit of the later pages once it has.
    pub(in crate::layout) fn carry_limit(&self) -> Option<Length> {
        let fragment = self.fragment.as_ref()?;
        if fragment.stop.is_none() {
            return Some(fragment.limits.limit);
        }
        let later = fragment.limits.later_limit;
        decisions::later_part_limit(&self.context.quirks, later).filter(|&later| later != NO_LIMIT)
    }

    /// Which part of the cell of a row that splits the layout fills now: 0 for the part on the
    /// row's first page, then 1, 2 and so on for its later parts; none outside such a cell.
    pub(in crate::layout) fn filled_part(&self) -> Option<usize> {
        self.fragment.as_ref().map(|fragment| {
            if fragment.stop.is_none() {
                0
            } else {
                fragment.parts.len() + 1
            }
        })
    }

    /// Moves the rest of a cell to the next page while its row splits, as for a line below
    /// the limit.
    pub(in crate::layout) fn carry_rest(&mut self) {
        if let Some(limit) = self.carry_limit() {
            self.carry_line(limit + Length::from_units(1));
        }
    }

    /// Where the items of the line about to be placed lie for its record: carried
    /// ([`FirstItem::Carried`]) when it goes on on the next column or page as part of a row
    /// that splits, its own or that of a cell that holds it.
    pub(in crate::layout) fn record_item(&self) -> FirstItem {
        let stopped = self.fragment.as_ref().is_some_and(Fragment::moved_on);
        if stopped || self.cell_carried {
            FirstItem::Carried
        } else {
            FirstItem::At(self.items.len())
        }
    }

    /// Stops the cell of a row that splits from starting a part for a later page, and gives
    /// the limit to give back to [`Self::release_parts`].
    pub(in crate::layout) fn hold_parts(&mut self) -> Option<Length> {
        self.fragment.as_mut().map(|fragment| {
            fragment.held = true;
            std::mem::replace(&mut fragment.limits.later_limit, NO_LIMIT)
        })
    }

    /// Gives the cell of a row that splits the limit of its later parts back.
    pub(in crate::layout) fn release_parts(&mut self, held: Option<Length>) {
        if let (Some(fragment), Some(limit)) = (self.fragment.as_mut(), held) {
            fragment.limits.later_limit = limit;
            fragment.held = false;
        }
    }

    /// Takes the fragment of the cell of a row that splits while a table in the cell lays out
    /// its rows, which fill the parts of the cell row by row: the table's rows get it, and
    /// [`Self::give_holder_back`] gives it back. A floating table, which holds the later parts
    /// back, leaves it in place.
    pub(super) fn take_holder(&mut self) -> Option<Fragment> {
        self.fragment.take_if(|fragment| !fragment.held)
    }

    /// Gives the cell of a row that splits its fragment back after a table in it.
    pub(super) fn give_holder_back(&mut self, holder: Fragment) {
        self.fragment = Some(holder);
    }

    /// Whether the part of the cell `holder` that is being filled is one for a later page and
    /// holds nothing yet.
    pub(super) fn part_is_new(&self, holder: &Fragment) -> bool {
        self.items.is_empty() && holder.stop.is_some()
    }

    /// Ends the part of the cell `holder` that is being filled, between two rows of a table in
    /// the cell or inside one, as [`Self::carry_line`] ends it at a line. `records` is the
    /// number of line records that belong to the parts so far.
    pub(super) fn end_part(&mut self, holder: &mut Fragment, records: usize) {
        let end = if holder.stop.is_none() {
            holder.stop_here(self.y, &mut self.items, records)
        } else {
            holder.end_later_part(self.y, &mut self.items, records)
        };
        self.move_to_part(end, Length::ZERO);
    }

    /// The top of the content of the cell's part that the layout fills now, once a line of a
    /// cell of a row that splits went on to a later part; none before.
    pub(in crate::layout) fn part_top(&self) -> Option<Length> {
        let fragment = self.fragment.as_ref()?;
        fragment.stop.is_some().then_some(fragment.limits.next_top)
    }

    /// Moves the rest of a cell to the next page when its row splits and a line of the cell
    /// ends below the limit. The first line of a paragraph keeps the paragraph's own space
    /// before above it at the top of the part.
    pub(in crate::layout) fn carry_line(&mut self, line_bottom: Length) {
        let records = self.output.placed.len();
        let before = self.own_space_before;
        let Some(fragment) = self.fragment.as_mut() else {
            return;
        };
        if fragment.stop.is_some() {
            // A line below the foot of a later page starts the part for the page after it.
            // The first line of a part stays, whatever its height.
            if line_bottom > fragment.limits.later_limit && self.y > fragment.limits.next_top {
                let end = fragment.end_later_part(self.y, &mut self.items, records);
                self.move_to_part(end, before);
            }
            return;
        }
        if line_bottom <= fragment.limits.limit {
            fragment.kept += 1;
            return;
        }
        let end = fragment.stop_here(self.y, &mut self.items, records);
        self.move_to_part(end, before);
    }

    /// Moves the cursor to `top`, the text top of a cell's part on a later page in a row that
    /// splits, and then down by `before`, the space before of the line that starts the part.
    /// That text top, a length of whole twips from the page's top, starts the cursor's twips
    /// rest, as the text top of a cell that carries no rest does. The bands and the boxes of the
    /// page that the cell leaves keep no line of the part out.
    fn move_to_part(&mut self, top: Length, before: Length) {
        self.bands.clear();
        self.squares.clear();
        self.move_to(top);
        // quirk: TwipLengthUnit::Nearest4096ths (src/quirks.rs)
        self.start_twips(top);
        self.y += before;
    }
}

/// Whether a row splits with its cells as `cells` lay them out: some line goes on on the next
/// page, and each cell that goes on there keeps a line on this page. A row moves whole when
/// one of its cells that goes on on the next page keeps nothing on this page. A row splits
/// also when only lines that draw nothing, such as empty paragraphs, go on on the next page.
pub(super) fn keeps_lines(cells: &[SplitCell]) -> bool {
    cells.iter().any(|cell| cell.continues) && cells.iter().all(|cell| cell.keeps)
}

/// The part of a cell of a row that splits that continues `open`, a region whose content goes
/// on on the next page: that content goes to `carried`, below `next`. On this page the cell
/// reaches down to the region's content.
fn region_part(slot: &Slot, open: &Open, next: Length, carried: &mut Vec<Item>) -> SplitCell {
    let Some(part) = &open.carried else {
        return SplitCell {
            end: open.bottom,
            next_end: next + slot.margins.top + slot.margins.bottom,
            keeps: true,
            continues: false,
            page_part: None,
            later: Vec::new(),
            carried_from: 0,
        };
    };
    let dy = next - part.base;
    let mut items = part.items.clone();
    move_items(&mut items, dy);
    carried.extend(items);
    SplitCell {
        end: open.bottom,
        next_end: part.bottom + dy,
        keeps: true,
        continues: true,
        page_part: None,
        later: Vec::new(),
        carried_from: 0,
    }
}

/// The entries of the carried content of a cell of a row that split, on the next page, after
/// the fills entry of a region that it starts or goes on with.
type Placed = (Option<FillsEntry>, Range<usize>);

/// The regions that are open below a row that split, on the next page, whose content starts
/// at `next` and whose carried items are the entries of `placed` there, each after the
/// fills entry of a region: those that start in the row or go on through it, each with the
/// bottom of its content on the next page, the entries of that content and its fills
/// entry.
fn next_regions(
    merges: &Merges,
    (slots, cells, placed): (&[Slot], &[SplitCell], &[Placed]),
    next: Length,
) -> Vec<Open> {
    slots
        .iter()
        .zip(cells)
        .zip(placed)
        .filter(|((slot, _), _)| slot.merged_below && flows(slot, merges))
        .map(|((slot, cell), (fills, range))| {
            let align = merges
                .open
                .iter()
                .find(|open| slot.merged_above() && open.first == slot.first)
                .map_or(slot.align(), |open| open.align);
            let bottom = if cell.continues { cell.next_end } else { next };
            Open {
                first: slot.first,
                bottom,
                align_bottom: bottom,
                items: range.clone(),
                fills: *fills,
                align,
                carried: None,
                // The parts of a row that splits show uncut.
                clip: None,
                turned: None,
                start: None,
            }
        })
        .collect()
}

/// Whether the content of the region that `slot` starts or goes on with flows on over a page
/// break: a region of upright text. The regions open above a row that splits are all such
/// regions.
fn flows(slot: &Slot, merges: &Merges) -> bool {
    if slot.merged_above() {
        merges.open.iter().any(|open| open.first == slot.first)
    } else {
        slot.upright()
    }
}