f-office-docx 0.2.3

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
//! Text columns: a section's body fills its columns from left to right, a line that does not
//! fit continues at the top of the next column, and only the last column moves on to the next
//! page. Before a continuous section break, the columns of the page share their text evenly.

use f_office_paint::{Item, Rect, Rgb};
use f_office_units::Length;

use crate::body::{Block, Section};
use crate::params::{COLUMN_SEPARATOR_WIDTH, MAX_BALANCE_TRIALS};
use crate::quirks::Quirks;
use crate::warnings::Limit;

use super::{Layout, decisions};

/// While the columns of a section are balanced: the lowest position that they may fill, and
/// whether the layout ran past the last column.
#[derive(Clone, Copy, Debug)]
pub(super) struct Balance {
    pub(super) limit: Length,
    pub(super) overflowed: bool,
}

/// Where a layout of a section's blocks starts: the chunk of [`Layout::blocks`] and the
/// paragraph of that chunk's run of paragraphs.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct BlockStart {
    pub(super) chunk: usize,
    pub(super) paragraph: usize,
}

/// While the first layout of a section of balanced columns keeps them: how deep the layout of
/// blocks is, the section's own blocks being the first level, the chunk of the section's
/// blocks being laid out, and the mark of the first paragraph of the section's blocks that
/// starts on the newest page, with that page and where the paragraph's layout starts.
#[derive(Default)]
pub(super) struct PageMarks {
    depth: usize,
    chunk: usize,
    first: Option<(usize, BlockStart, Mark)>,
}

/// Whether the first paragraph of a section whose columns are balanced is still to come: the
/// space after of the paragraph before it lies above all columns.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) enum SectionTop {
    /// The columns have their top.
    #[default]
    Placed,
    /// The next paragraph of the body sets the top of the columns below that space after.
    Pending,
}

/// How the trials of balanced columns end.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Trials {
    /// The blocks fit below the limit of the last trial.
    Fit,
    /// The blocks fit below no limit that the page has room for.
    NoFit,
    /// The blocks fit within no trial of [`MAX_BALANCE_TRIALS`].
    Limit,
}

/// What a layout has done up to a point, so that it can go back there and try again. It
/// keeps the warnings too, so that the layout that a rewind takes back adds none: the layout
/// after the rewind gives them again. [`Layout::mark`] names every field of the layout,
/// [`OutputMark::of`] every field of its output, and [`Layout::rewind`] every field of the
/// mark, so that a new field does not compile until it is sorted. Its first part is the row mark ([`RowMark`]), which a
/// row's trial takes back too, so that each field is noted and taken back in one place.
pub(super) struct Mark {
    row: RowMark,
    behind: usize,
    front: usize,
    bands: usize,
    squares: usize,
    frame_boxes: usize,
    page_notes: super::notes::PageNotes,
    previous: Option<super::Previous>,
    y: Length,
    y_rest: i64,
    y_twips: Option<super::TwipsRest>,
    started: bool,
    after_break: bool,
    alone_break: Option<super::Previous>,
    column: super::Column,
    column_index: usize,
    column_top: Length,
    column_ends: Vec<Length>,
    output: OutputMark,
}

/// What the layout has written before a trial of a table row (a row mark), which it takes back when it lays the row out again: the items, the placed
/// lines, the numbering, the count of the tables that number the cells of the line records,
/// the pictures and inline drawings that the pieces of the row's lines name, the record of
/// styled text with the number of the last chapter heading, the last paragraph of the
/// previous section and the keep chain of the table before, which the first paragraph after
/// the mark takes, the comments' record, the wraps found of drawings placed from a page, the later anchors found, and
/// the bookmark records of page number texts and number contexts. So a trial leaves none of
/// them as it found them, and the layout after the rewind writes them as a layout without the
/// trial would. It is the first part of every
/// [`Mark`] too. Of the other fields that a mark keeps, a row's trial changes none that the
/// layout after it reads, or the field is an open gap:
///
/// - the items behind and in front of the text: a floating drawing in a cell stays in the
///   items (`cell_drawing`);
/// - the bands and frame boxes: a frame in a cell keeps neither (`keep_frame_box`,
///   `wrap_frame`);
/// - the wrap squares: each cell lays out its content with its own (`swap_cell_state`);
/// - the paragraph before and the column: each cell sets them before its content (`content`),
///   so between two rows the column is the last cell's after a trial as after a row, and the
///   table sets back the column outside it and no paragraph before after its last row;
/// - whether a paragraph has been laid out: a cell's paragraph sets it, which the layout after
///   the trial sets again, and only a paragraph outside a cell reads it (`space_before`);
/// - whether the last line broke the page or the column: the table sets it to no before its
///   rows (`Layout::table`), and a line in a cell, which does not paginate (`Layout::line`),
///   sets it to no;
/// - the column's index, top and ends, and the pages: they change at a page or column break,
///   at the start of a page or section, or above balanced columns, which no cell reaches, so
///   a trial ends no page or column;
/// - the endnotes and the footnote numbers: a note is numbered at its first reference, by its
///   ID (`endnote_label`, `note_number`), so the layout after the trial numbers the same notes
///   in the same order;
/// - the warnings and the story warnings: a warnings trial around each row's trial takes them
///   back (`PassOutput::start_trial`), and a row that splits measures its header rows
///   without warnings (`layout_without_warnings`);
/// - the notes of the page stay as the trial left them;
/// - the place down the page: each cell sets it before its content, and the callers lay the
///   row out again from the top that they hold or on the next page. Open gap: a row that is
///   the first thing on its page and does not split is laid out again from the place that its
///   trials left (`Layout::row`).
pub(super) struct RowMark {
    /// The count of the items, where the row's items start.
    pub(super) items: usize,
    /// The count of the placed lines, where the row's line records start.
    pub(super) lines: usize,
    /// The count of the cell clips ([`super::table::CellClips`]).
    clips: usize,
    /// The count of the fills that went into the fills entries of earlier rows' merged
    /// regions (`PageItems::region_fill_count`).
    region_fills: usize,
    numbering: crate::numbering::Numbering,
    tables: usize,
    pictures: usize,
    drawings: usize,
    styled: Option<super::style_refs::RecordMark>,
    chapter_number: Option<i64>,
    section_previous: Option<super::Previous>,
    table_chain: super::TableChain,
    markup_mark: super::markup::MarkupMark,
    found: (usize, usize, usize),
    body_floatings: usize,
    found_later: usize,
    bookmarks: usize,
    bookmark_numbers: usize,
}

/// The part of a [`Mark`] that the layout's output gives, but for its part in the
/// [`RowMark`].
struct OutputMark {
    pages: usize,
    endnotes: usize,
    note_numbers: super::notes::NoteNumbers,
    warnings: crate::Warnings,
    story_warnings: Vec<(super::output::StoryKey, crate::Warnings)>,
}

impl OutputMark {
    /// Notes what `output` holds so far. It names every field of the output, in the groups of
    /// [`Layout::mark`].
    fn of(output: &super::output::PassOutput) -> Self {
        let super::output::PassOutput {
            // Kept.
            pages,
            endnotes,
            notes,
            warnings,
            story_warnings,
            // Kept by the row mark (`Layout::row_mark`).
            placed: _,
            pictures: _,
            drawings: _,
            tables: _,
            styled: _,
            chapter_number: _,
            found: _,
            found_later: _,
            found_bookmarks: _,
            found_numbers: _,
            // Changed only when a page starts, as `Layout::mark` says, or when the body's
            // layout ends.
            page_infos: _,
            body_areas: _,
            // A record that the end of the pass compares with the footnotes of each page; an
            // entry of a trial counts as one of the layout that it gives.
            margin_notes: _,
            blank_pages: _,
            style_pages: _,
            // Open gap: a trial's numbered lines stay counted.
            line_count: _,
            // A record for tools, in which a later entry of a table that a trial starts again
            // wins.
            table_columns: _,
            // A count that only numbers story parts, so a number that a trial took stays taken,
            // and the current part, set around the endnotes as `endnote` is.
            story_parts: _,
        } = output;
        Self {
            pages: pages.len(),
            endnotes: endnotes.len(),
            note_numbers: notes.clone(),
            warnings: warnings.clone(),
            story_warnings: story_warnings.clone(),
        }
    }
}

impl Layout<'_> {
    /// Takes the columns of the current section, with their top at the current position.
    pub(super) fn set_columns(&mut self) {
        self.columns = areas(&self.section, &self.context.quirks);
        self.column_index = 0;
        self.column_top = self.y;
        self.column_ends.clear();
        if let Some(&(left, width)) = self.columns.first() {
            self.column.left = left;
            self.column.origin = left;
            self.column.width = width;
        }
    }

    /// Paints the lines between the text columns of the section on the page being filled, as
    /// its columns end there, where the section asks for them (`w:sep`) and the target draws
    /// them ([`decisions::column_separators`]).
    pub(super) fn paint_column_separators(&mut self) {
        if !self.section.columns.separator || self.columns.len() < 2 || self.story.is_some() {
            return;
        }
        let lines = decisions::column_separators(&self.context.quirks, || self.separator_lines());
        self.items.extend(lines.into_iter().flatten());
    }

    /// The lines between the text columns of the page being filled: one in each space between
    /// two neighboring columns that both hold a line of the body outside tables below the
    /// columns' top, its left edge on the dot nearest to half its width left of the space's
    /// middle, from the dot nearest to the columns' top to the dot nearest to the bottom of the
    /// lowest such line of all the columns. The lines of the paragraph that ends the section do
    /// not count when they draw nothing.
    fn separator_lines(&self) -> Vec<Item> {
        let page = self.output.pages.len();
        let mut bottoms: Vec<Option<Length>> = vec![None; self.columns.len()];
        let lines = self.output.placed.iter().rev();
        for line in lines.take_while(|line| line.page == page) {
            let counts = line.story == super::LineStory::Body
                && line.area == super::LineArea::OutsideTables
                && line.top >= self.column_top
                && !(Some(line.paragraph) == self.section_end_paragraph && line.drawn.is_empty());
            let column = self
                .columns
                .iter()
                .position(|&(left, _)| left == line.column_left);
            if let Some(bottom) = column
                .filter(|_| counts)
                .and_then(|index| bottoms.get_mut(index))
            {
                let end = line.top + line.height;
                *bottom = Some(bottom.map_or(end, |b| b.max(end)));
            }
        }
        let Some(lowest) = bottoms.iter().flatten().copied().reduce(Length::max) else {
            return Vec::new();
        };
        let device = &self.device;
        let width = device.snap(COLUMN_SEPARATOR_WIDTH);
        let (top, bottom) = (device.snap(self.column_top), device.snap(lowest));
        self.columns
            .iter()
            .zip(&bottoms)
            .zip(self.columns.iter().zip(&bottoms).skip(1))
            .filter(|((_, a), (_, b))| a.is_some() && b.is_some())
            .map(|((&first, _), (&second, _))| {
                // The columns of a right-to-left section lie from the right.
                let (left, right) = if first.0 <= second.0 {
                    (first, second)
                } else {
                    (second, first)
                };
                let middle = (left.0 + left.1 + right.0).div_toward_zero(2);
                Item::Rect(Rect {
                    x: device.snap(middle - width.div_toward_zero(2)),
                    y: top,
                    width,
                    height: bottom - top,
                    color: Rgb::BLACK,
                })
            })
            .collect()
    }

    /// Goes back to the first column at the top of a new page.
    pub(super) fn first_column(&mut self) {
        self.column_index = 0;
        self.column_top = self.y;
        self.column_ends.clear();
        if let Some(&(left, width)) = self.columns.first().filter(|_| self.column.cell.is_none()) {
            self.column.left = left;
            self.column.origin = left;
            self.column.width = width;
        }
    }

    /// Continues at the top of the next column, or on the next page after the last column.
    pub(super) fn next_column(&mut self) {
        self.end_column();
        if let Some(&(left, width)) = self.columns.get(self.column_index + 1) {
            self.place_column_notes();
            self.column_index += 1;
            self.column.left = left;
            self.column.origin = left;
            self.column.width = width;
            self.move_to(self.column_top);
        } else if let Some(balance) = self.balance.as_mut() {
            // A trial that runs past the last column has failed; it goes on in that column.
            balance.overflowed = true;
            self.move_to(self.column_top);
        } else {
            self.new_page();
        }
    }

    /// The top of the place where the next column or the next page starts.
    pub(super) fn next_area_top(&self) -> Length {
        if self.column_index + 1 < self.columns.len() {
            self.column_top
        } else {
            self.page_top(self.output.pages.len() + 1)
        }
    }

    /// Records how far down the current column is filled.
    fn end_column(&mut self) {
        if self.column_ends.len() <= self.column_index {
            self.column_ends
                .resize(self.column_index + 1, self.column_top);
        }
        if let Some(end) = self.column_ends.get_mut(self.column_index) {
            *end = (*end).max(self.y);
        }
    }

    /// Lays out the blocks of a section whose columns end at a continuous section break. When
    /// the section ends on the page where it started, its columns share the text: all columns
    /// end at one limit, which starts at the mean height of the columns, the height of the
    /// section's text divided by the number of columns. While a line fits in no column, the
    /// limit grows by the smallest height of the section, a line or a paragraph's space
    /// before, rounded up to whole points. The space after of the paragraph before the
    /// section lies above all columns. The next section starts below the longest column.
    /// Where the target balances the last page of a section that starts on an earlier page
    /// (`decisions::balanced_last_page`), the columns of that page share the text from its
    /// first paragraph that starts on it in the same way, with the page's top as their top;
    /// the lines before that paragraph stay in the first column, and the pages before stay as
    /// they fill.
    pub(super) fn balanced_blocks(&mut self, blocks: &[Block]) {
        let section_mark = self.mark();
        let count = i64::try_from(self.columns.len()).unwrap_or(1);
        if count >= 2 {
            self.page_marks =
                decisions::balanced_last_page(&self.context.quirks, PageMarks::default());
        }
        self.plain_blocks(blocks, BlockStart::default());
        let marks = self.page_marks.take();
        if count < 2 {
            return;
        }
        let page = self.output.pages.len();
        let (mark, start) = if page == section_mark.output.pages {
            (section_mark, BlockStart::default())
        } else {
            match marks
                .and_then(|marks| marks.first)
                .filter(|(on, ..)| *on == page)
            {
                Some((_, start, mark)) => (mark, start),
                None => return,
            }
        };
        self.end_column();
        let top = self.column_top;
        let bottom = self.page_bottom();
        let after = self
            .hidden_end(blocks)
            .map_or(Length::ZERO, |(after, _)| after);
        let step = self.limit_step(&mark, after);
        let limit = top + self.mean_height(top);
        let trials = self.balance(&mark, (blocks, start), (limit, step, bottom));
        if trials != Trials::Fit {
            // The columns stay as they fill.
            self.rewind(&mark);
            self.plain_blocks(blocks, start);
        }
        if trials == Trials::Limit {
            // After the rewind, which takes back the warnings of the trials.
            self.output.warnings.push(crate::Warning::LimitReached {
                part: (*self.body_part).clone(),
                limit: Limit::BalanceTrials,
            });
        }
        // The section ends below its longest column, with the space after of that column's
        // last paragraph. The empty paragraph that ends the section and shows nothing is the
        // paragraph before the next one, and its space after lies within the section: the
        // next paragraph has only the part of its space before beyond it.
        if let Some((_, props)) = self.hidden_end(blocks) {
            self.section_previous = Some(super::Previous::of(&props));
        }
        self.end_column();
        let end = self.column_ends.iter().copied().fold(self.y, Length::max);
        if end > self.y {
            self.move_to(end);
        }
    }

    /// Lays out `blocks` from `mark` below a limit that starts at `limit` and grows by `step`
    /// until they fit, while it lies above `bottom`, in at most [`MAX_BALANCE_TRIALS`] trials,
    /// and says how the trials end.
    fn balance(
        &mut self,
        mark: &Mark,
        blocks: (&[Block], BlockStart),
        (mut limit, step, bottom): (Length, Length, Length),
    ) -> Trials {
        for _ in 0..MAX_BALANCE_TRIALS {
            if self.limited_blocks(mark, blocks, limit) {
                return Trials::Fit;
            }
            // A column break leaves no column for the rest, or the page has no room.
            if step <= Length::ZERO || limit >= bottom {
                return Trials::NoFit;
            }
            limit += step;
        }
        Trials::Limit
    }

    /// The space after of the last paragraph of a section's blocks that shows something,
    /// and the properties of the empty paragraph that ends the section, when that paragraph
    /// shows nothing. The space is the one between the two paragraphs, which contextual
    /// spacing can remove.
    pub(super) fn hidden_end(
        &mut self,
        blocks: &[Block],
    ) -> Option<(Length, crate::props::ParaProps)> {
        let Some(Block::Paragraph(paragraph)) = blocks.last() else {
            return None;
        };
        // The paragraph's own layout counted it in its list already: this look at it keeps
        // the counters as they were.
        let numbering = self.numbering.clone();
        let resolved = self.resolve(paragraph);
        self.numbering = numbering;
        if !self.shows_nothing(paragraph, &resolved) {
            return None;
        }
        let after = super::paragraph::gap_parts(self.previous.as_ref(), &resolved.props).after;
        Some((after, resolved.props))
    }

    /// The mean height of the columns as they filled below `top`: the area of their text
    /// divided by the width of all columns. For columns of one width, it is the height of
    /// the text divided by the number of columns.
    /// The area and the widths count in `i128`: the mean of columns of widths above zero lies
    /// between their lowest and their highest height.
    fn mean_height(&self, top: Length) -> Length {
        let filled = self.columns.iter().zip(&self.column_ends);
        let area: i128 = filled
            .map(|(&(_, width), &end)| i128::from((end - top).units()) * i128::from(width.units()))
            .sum();
        let widths: i128 = self
            .columns
            .iter()
            .map(|&(_, width)| i128::from(width.units()))
            .sum();
        Length::from_units(f_office_units::saturated(area / widths.max(1)))
    }

    /// The step by which the limit of balanced columns grows: the smallest height among the
    /// upright lines placed after `mark`, their paragraphs' own spaces before and `after`, the
    /// space after that the last column holds, rounded up to whole points.
    fn limit_step(&self, mark: &Mark, after: Length) -> Length {
        let lines = self.output.placed.get(mark.row.lines..).unwrap_or_default();
        let upright = lines.iter().filter(|line| line.upright());
        let heights = upright.flat_map(|line| [line.height, line.before]);
        let heights = heights.chain([after]);
        let smallest = heights
            .filter(|&height| height > Length::ZERO)
            .min()
            .unwrap_or(Length::ZERO);
        smallest.up_to_whole(Length::UNITS_PER_POINT)
    }

    /// Lays out the blocks from `start` with their columns down to the foot of the page. The
    /// last column holds the space after of its last paragraph, above the empty paragraph that
    /// ends the section: with that space the column must end at the limit, and the mean counts
    /// it. A layout from a later paragraph than the section's first finds the columns' top
    /// placed.
    fn plain_blocks(&mut self, blocks: &[Block], start: BlockStart) {
        if start == BlockStart::default() {
            self.section_top = SectionTop::Pending;
        }
        self.blocks_from(blocks, start);
        self.section_top = SectionTop::Placed;
        if let Some((after, _)) = self.hidden_end(blocks) {
            self.y += after;
            if let Some(balance) = self.balance.as_mut()
                && self.y > balance.limit
            {
                balance.overflowed = true;
            }
        }
    }

    /// Continues in the next column with a line whose paragraph has `before` of its own space
    /// above it, and gives the space that the line has above it there. That space is not part
    /// of the column that the line leaves. The line keeps it at the top of the next column,
    /// and not at the top of the next page, but for the first paragraph after a continuous
    /// section end, which keeps it there too. Where the target leaves it out at the top of a
    /// column whose top is the top of the page, as at the top of a page, the line has none of
    /// it there either.
    pub(super) fn leave_column(&mut self, before: Length) -> Length {
        if self.columns.len() > 1 {
            self.y -= before;
        }
        let page = self.output.pages.len();
        self.next_column();
        if self.new_page_space == super::NewPageSpace::Goes {
            let new_page = self.output.pages.len() != page;
            let at_page_top = self.column_top <= self.page_top(page);
            if new_page || decisions::column_top_space_goes(&self.context.quirks, at_page_top) {
                return Length::ZERO;
            }
        }
        self.y += before;
        before
    }

    /// Lays out the blocks from `mark`, where the layout of `blocks` starts at their
    /// `BlockStart`, with columns that end at `limit`, and says whether they fit in the
    /// columns.
    fn limited_blocks(
        &mut self,
        mark: &Mark,
        (blocks, start): (&[Block], BlockStart),
        limit: Length,
    ) -> bool {
        self.rewind(mark);
        self.balance = Some(Balance {
            limit,
            overflowed: false,
        });
        self.plain_blocks(blocks, start);
        let overflowed = self.balance.take().is_some_and(|b| b.overflowed);
        !overflowed && self.output.pages.len() == mark.output.pages
    }

    /// Starts a layout of blocks: one level deeper while the first layout of a section of
    /// balanced columns keeps its marks.
    pub(super) fn enter_blocks(&mut self) {
        if let Some(marks) = self.page_marks.as_mut() {
            marks.depth += 1;
        }
    }

    /// Ends a layout of blocks that [`Self::enter_blocks`] started.
    pub(super) fn leave_blocks(&mut self) {
        if let Some(marks) = self.page_marks.as_mut() {
            marks.depth = marks.depth.saturating_sub(1);
        }
    }

    /// Notes that the chunk `chunk` of the blocks being laid out starts, when they are the
    /// blocks of a section whose first layout keeps its marks.
    pub(super) fn note_chunk(&mut self, chunk: usize) {
        if let Some(marks) = self.page_marks.as_mut().filter(|marks| marks.depth == 1) {
            marks.chunk = chunk;
        }
    }

    /// Whether the first layout of a section of balanced columns keeps its marks, and the
    /// paragraphs being laid out are the section's own.
    pub(super) fn keeps_page_marks(&self) -> bool {
        self.page_marks
            .as_ref()
            .is_some_and(|marks| marks.depth == 1)
    }

    /// Keeps the mark of the paragraph `paragraph` of the run of paragraphs being laid out,
    /// at its start, when it is the first of the section's paragraphs that starts on the
    /// newest page. `run_start` is the numbering and the keep chain before the run, which the
    /// layout that starts again at the paragraph takes, as the run's layout did; without it,
    /// no mark is kept.
    pub(super) fn note_paragraph_start(
        &mut self,
        paragraph: usize,
        run_start: Option<&(crate::numbering::Numbering, super::TableChain)>,
    ) {
        let page = self.output.pages.len();
        let Some(run_start) = run_start else {
            return;
        };
        let Some(chunk) = self
            .page_marks
            .as_ref()
            .filter(|marks| marks.depth == 1)
            .filter(|marks| marks.first.as_ref().is_none_or(|(on, ..)| *on != page))
            .map(|marks| marks.chunk)
        else {
            return;
        };
        let mut mark = self.mark();
        mark.row.numbering = run_start.0.clone();
        mark.row.table_chain = run_start.1;
        if let Some(marks) = self.page_marks.as_mut() {
            marks.first = Some((page, BlockStart { chunk, paragraph }, mark));
        }
    }

    /// Notes what the layout has done so far. It names every field of the layout, and
    /// [`OutputMark::of`] every field of its output, each in one of three groups: kept by the
    /// mark (a list that only grows by its count, another value by a copy); not changed by a
    /// trial, with the reason; or an open gap, which a trial changes and the rewind does not
    /// take back, with the reason.
    #[expect(
        clippy::too_many_lines,
        reason = "one line for each field of the layout, which the mark sorts by name"
    )]
    pub(super) fn mark(&self) -> Mark {
        let Self {
            // Kept.
            behind,
            front,
            bands,
            squares,
            frame_boxes,
            page_notes,
            previous,
            y,
            y_rest,
            y_twips,
            started,
            after_break,
            alone_break,
            column,
            column_index,
            column_top,
            column_ends,
            output,
            // Kept by the row mark (`Self::row_mark`), with the border lines and the cell
            // clips among them.
            items: _,
            // Each row sets them and its caller reads them at once (`Layout::row_at`).
            table_twips: _,
            numbering: _,
            section_previous: _,
            table_chain: _,
            comment_markup: _,
            // Fixed for the layout.
            context: _,
            body_part: _,
            stories: _,
            styles: _,
            settings: _,
            story: _,
            page: _,
            story_notes: _,
            style_page: _,
            sections: _,
            // Changed only when a section or a page starts. A trial starts no section:
            // `sections_flow` lays out the blocks of a section between the starts. A trial
            // starts a page only in the open gap that `Self::rewind` names at `pages`.
            device: _,
            section: _,
            tops: _,
            bottoms: _,
            story_page: _,
            columns: _,
            section_end_paragraph: _,
            page_from_break: _,
            section_index: _,
            section_first_page: _,
            section_title_page: _,
            number_start: _,
            pending: _,
            // Set and given back around their own use, so a trial ends with the value that it
            // found: around the measure of a paragraph (`number_context`, `hyphen_runs`), a table
            // (`table_number`), a cell (`swap_cell_state`) and a balanced trial (`balance`,
            // `Self::limited_blocks`). `endnote` is set around the blocks of each endnote
            // (`endnotes_flow`), so a trial inside them, such as a row keep of a table in an
            // endnote, finds the same value before and after it.
            number_context: _,
            hyphen_runs: _,
            table_number: _,
            table_prev_style: _,
            cell_place: _,
            cell_top: _,
            cell_sides: _,
            cell_prev_style: _,
            cell_floatings: _,
            cell_upward_earlier: _,
            cell_upward_found: _,
            story_earlier_wraps: _,
            cell_carried: _,
            body_floatings: _,
            balance: _,
            endnote: _,
            // Changed in place while they are set: the fragment of a cell of a split row counts
            // its kept lines and drawings and stops its parts, and a drawing or a floating
            // table in a cell lowers the floor. They hold only because no mark is taken while a
            // fragment is in place, or inside a cell whose own content the trial lays out. The
            // keep chains need a column outside a cell. The row keeps and `splits_with_lines`
            // run only for a table that paginates, which is outside cells. A floating table in
            // a cell hangs on the text, so it measures no height for an alignment.
            // `carried_row` takes the holder out before its mark, and the cells of its row swap
            // in their own floor. A new trial inside a cell must sort these again.
            fragment: _,
            cell_floor: _,
            // The paragraph before a frame sets it and the frame takes it at once (`flow`,
            // `frame_at`), so it holds nothing between the blocks and rows where the marks are
            // taken.
            frame_places: _,
            // Each paragraph sets them before its lines read them (`flow` and `paragraph`), so
            // the layout after the rewind reads no value of a trial.
            grid_pitch: _,
            following_after: _,
            kept_tail: _,
            // The line that sets them clears them once drawn (`line`, `emit_with`), so they hold
            // nothing between lines.
            centered_middle: _,
            line_band: _,
            east_asian_axis: _,
            aligned_parts: _,
            // The line that fills it takes it once drawn (`emit_with`), so it holds nothing
            // between lines.
            glyph_places: _,
            own_space_before: _,
            first_space_before: _,
            held_borders: _,
            new_page_space: _,
            text_part: _,
            // A paragraph leaves them empty when it ends (`go_on_beside` after its last line,
            // and the end of `paragraph`), so they hold nothing between the blocks and rows
            // where the marks are taken.
            same_baseline: _,
            line_floor: _,
            last_bar: _,
            // Each paragraph sets it as its lines start and clears it when its fill comes
            // (`paragraph`), so it holds nothing between the blocks and rows where the marks
            // are taken.
            drawings_under_fill: _,
            // `Self::plain_blocks` sets it before each balanced trial. In a trial of a table,
            // a cell's paragraph takes it, and a cell has no columns above it, as in the
            // layout after the rewind.
            section_top: _,
            // Only `Self::balanced_blocks` sets it, around the first layout of a section, and
            // takes it back before any trial.
            page_marks: _,
            // Caches of faces, and font notes, which are a set: a trial shapes the text that
            // the layout after the rewind shapes again.
            shaper: _,
            // Open gap: a trial's numbered lines on a page that a page break began move
            // it, with `line_count`.
            break_numbers: _,
        } = self;
        Mark {
            row: self.row_mark(),
            behind: behind.len(),
            front: front.len(),
            bands: bands.len(),
            squares: squares.len(),
            frame_boxes: frame_boxes.len(),
            page_notes: page_notes.clone(),
            previous: previous.clone(),
            y: *y,
            y_rest: *y_rest,
            y_twips: *y_twips,
            started: *started,
            after_break: *after_break,
            alone_break: alone_break.clone(),
            column: column.clone(),
            column_index: *column_index,
            column_top: *column_top,
            column_ends: column_ends.clone(),
            output: OutputMark::of(output),
        }
    }

    /// Goes back to a mark on the same page, and forgets what the layout did after it. It
    /// names every field of the mark, so that each one that [`Self::mark`] keeps comes back.
    pub(super) fn rewind(&mut self, mark: &Mark) {
        let Mark {
            row,
            behind,
            front,
            bands,
            squares,
            frame_boxes,
            page_notes,
            previous,
            y,
            y_rest,
            y_twips,
            started,
            after_break,
            alone_break,
            column,
            column_index,
            column_top,
            column_ends,
            output,
        } = mark;
        let OutputMark {
            endnotes,
            note_numbers,
            warnings,
            story_warnings,
            // The callers compare it with the pages after a trial; the rewind takes back no
            // page. Open gap: a trial that starts a page leaves it, and a balanced trial
            // after it goes on there.
            pages: _,
        } = output;
        self.back_to_row_mark(row);
        self.behind.truncate(*behind);
        self.front.truncate(*front);
        self.bands.truncate(*bands);
        self.squares.truncate(*squares);
        self.frame_boxes.truncate(*frame_boxes);
        self.page_notes = page_notes.clone();
        self.previous.clone_from(previous);
        self.y = *y;
        self.y_rest = *y_rest;
        self.y_twips = *y_twips;
        self.started = *started;
        self.after_break = *after_break;
        self.alone_break.clone_from(alone_break);
        self.column = column.clone();
        self.column_index = *column_index;
        self.column_top = *column_top;
        self.column_ends.clone_from(column_ends);
        self.output.endnotes.truncate(*endnotes);
        self.output.notes = note_numbers.clone();
        self.output.warnings.clone_from(warnings);
        self.output.story_warnings.clone_from(story_warnings);
    }

    /// Notes what the layout has written so far, before a trial of a table row, and as the
    /// first part of a [`Mark`].
    pub(super) fn row_mark(&self) -> RowMark {
        RowMark {
            items: self.items.len(),
            lines: self.output.placed.len(),
            clips: self.items.clip_count(),
            region_fills: self.items.region_fill_count(),
            numbering: self.numbering.clone(),
            tables: self.output.tables,
            pictures: self.output.pictures.len(),
            drawings: self.output.drawings.len(),
            styled: self
                .output
                .styled
                .as_ref()
                .map(super::style_refs::Record::mark),
            chapter_number: self.output.chapter_number,
            section_previous: self.section_previous.clone(),
            table_chain: self.table_chain,
            markup_mark: self.comment_markup.mark(),
            found: self.output.found.counts(),
            body_floatings: self.body_floatings,
            found_later: self.output.found_later.len(),
            bookmarks: self.output.found_bookmarks.count(),
            bookmark_numbers: self.output.found_numbers.count(),
        }
    }

    /// Takes back what the layout wrote after `mark`, to lay a row out again, and for a
    /// rewind to a [`Mark`]. It names every field of the row mark.
    pub(super) fn back_to_row_mark(&mut self, mark: &RowMark) {
        let RowMark {
            items,
            lines,
            clips,
            region_fills,
            numbering,
            tables,
            pictures,
            drawings,
            styled,
            chapter_number,
            section_previous,
            table_chain,
            markup_mark,
            found,
            body_floatings,
            found_later,
            bookmarks,
            bookmark_numbers,
        } = mark;
        // A fill that went under an earlier row's content after the mark lies before the
        // mark: the fills come out first, the last first.
        self.items.take_back_region_fills(*region_fills);
        self.items.cut(*items);
        self.items.truncate_clips(*clips);
        self.output.placed.truncate(*lines);
        self.numbering.clone_from(numbering);
        self.output.tables = *tables;
        self.output.pictures.truncate(*pictures);
        self.output.drawings.truncate(*drawings);
        self.back_to_styled(*styled, *chapter_number);
        self.section_previous.clone_from(section_previous);
        self.table_chain = *table_chain;
        self.comment_markup.rewind(markup_mark);
        self.output.found.take_back(*found);
        self.body_floatings = *body_floatings;
        self.output.found_later.truncate(*found_later);
        self.output.found_bookmarks.take_back(*bookmarks);
        self.output.found_numbers.take_back(*bookmark_numbers);
    }
}

/// The columns of `section`, as the left edge and the width of each in the order of the text,
/// equal columns with the width that the target's `quirks` give
/// ([`decisions::equal_column_width`]). Where the target mirrors them
/// ([`decisions::mirrored_columns`]), the columns of a right-to-left section lie at the mirrors
/// of their places across the text area.
pub(super) fn areas(section: &Section, quirks: &Quirks) -> Vec<(Length, Length)> {
    let width = section.width - section.left - section.right;
    let areas = section.columns.areas(section.left, width, |exact| {
        decisions::equal_column_width(quirks, exact)
    });
    if !section.right_to_left {
        return areas;
    }
    let right = section.left + width;
    decisions::mirrored_columns(quirks, || {
        areas
            .iter()
            .map(|&(left, column)| (section.left + right - left - column, column))
            .collect()
    })
    .unwrap_or(areas)
}