f-office-docx 0.3.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
//! Lines: their height and baseline, where they go on the page, and the glyph runs, rules,
//! pictures and change bars that draw them.

use std::borrow::Cow;

use f_office_units::Length;
use f_office_units::scale::LINE;

use crate::lines::{Line, LineEnd, Piece};
use crate::params;
use crate::props::{Alignment, EastAsianScript, LineSpacing, ParaProps};
use crate::text::{FaceIndex, LineSizing};

use super::Layout;
use super::decisions;
use super::line_text::line_text;
use super::notes::Foot;

mod aligned;
mod aligned_tabs;
pub(super) mod centered;
pub(super) mod draw;
pub(super) mod height;
mod kashida;
mod margin;
mod rules;
mod shadow_path;
pub(super) mod shift;
mod vml;

use height::{FromBottom, LineBox, REST_PARTS, SpaceBefore, twips_rest};

use super::TwipsRest;
use shift::{CountedShares, MarkSides, Shift, compressed_marks, spread_over_gaps};

/// Where a line goes across the column: its start and width from the column edge, whether it is
/// the first or the last line of its paragraph, and the paragraph's ID, which its record keeps.
#[derive(Clone, Copy)]
pub(super) struct LinePlace {
    pub(super) start: Length,
    /// The part of `start` that the first line's own indent (a first-line or a hanging indent,
    /// or a label's shift) adds to the left indent; zero on the other lines, on a line that
    /// starts at a wrap edge and on a right-to-left line.
    pub(super) own: Length,
    /// The wrap edge's distance past the column's left edge, when a drawing on the line's left
    /// moved its start there; the line's indent counts from it.
    pub(super) edge: Option<Length>,
    pub(super) width: Length,
    pub(super) index: usize,
    pub(super) last: bool,
    pub(super) paragraph: crate::body::ParagraphId,
}

impl LinePlace {
    /// The first line's own indent on a line that starts at its indent, and zero on another.
    const fn own_at_indent(&self, at_indent: bool) -> Length {
        if at_indent { self.own } else { Length::ZERO }
    }
}

#[derive(Clone, Copy)]
struct Origin {
    x: Length,
    /// The dot of the edge that the line counts its start from: its column's left edge, or a
    /// wrap edge ([`Layout::line_edge`]).
    edge: Length,
    /// The line's exact start past its column's edge, which `x` holds as `Device::line_start`
    /// lands it, and from which the text after a left tab counts its stop.
    start: Length,
    /// The part of `start` that the first line's own indent adds to the left indent, which
    /// `Device::first_line_start` lands with it, on a line that starts at its indent; zero on
    /// the other lines.
    own: Length,
    baseline: Length,
    /// The exact baseline, before the page rounds it, on which inline pictures stand.
    unrounded_baseline: Length,
    /// How far right of `x` the line starts before its left edge lands on the device grid,
    /// which inline pictures keep.
    grid_shift: Length,
    /// On a justified line, what each space that it stretches or shrinks adds to its width.
    space_extra: Length,
    /// On a justified line, the part of the free space that those equal shares leave: how far
    /// the line's right edge lies past the exact right edge of its text.
    space_rest: Length,
    /// On a justified line of a target that counts other shares in the edge check of right-edge
    /// steps (`EdgeShares::ExactFree`), the shares that the check counts.
    counted_shares: Option<CountedShares>,
    /// On a justified line of East Asian text with compressed punctuation, what each inner blank
    /// half of a punctuation mark gives up, zero or below.
    mark_shrink: Length,
    /// Which sides of the compressed marks give up their share.
    mark_sides: MarkSides,
    /// On a justified line with compressed punctuation that has room left and no space, what
    /// each gap between its glyphs takes.
    gap_extra: Length,
    /// On a justified line with the justification of `WordPerfect` that runs past its width,
    /// how its pieces narrow.
    narrowing: Option<shift::Narrowing>,
    /// How far below the baseline an inline VML shape or picture stands on its line.
    drop: Length,
    /// The exact bottom of the single line's room for an outlined VML rectangle with an
    /// anchor lock, before multiple spacing adds room below it.
    anchor_bottom: Option<Length>,
    /// Where the paragraph's part on the line's page starts in its text, from which Word
    /// counts the pieces of the text again.
    text_from: u32,
    /// Whether the line ends its paragraph, so that the paragraph mark follows its last text
    /// in reading order.
    mark: bool,
    /// For a line of a paragraph that runs from right to left (`w:bidi`), how far right of their
    /// steps the device draws its glyphs: [`params::RIGHT_TO_LEFT_LINE_DOTS`] dots, and how far
    /// its column's right edge on the device grid lies from the edge that the left edge on the
    /// grid and the column's width give ([`Layout::right_edge_shift`]); `None` for a line of a
    /// left-to-right paragraph.
    right_to_left: Option<Length>,
    /// Whether the line starts at its indent, as a left-aligned or a justified line does, so
    /// that its first glyph hands its rounding on to the next segment.
    starts_at_indent: bool,
    /// How far the exact start of a centered or right-aligned line at its indent lies right of
    /// the dot from which its glyphs take their places: the text after a tab or a list label's
    /// gap adds it to its exact place before it lands on a dot. Zero for every other line.
    segment_rest: Length,
    /// Whether each glyph lies one step of the glyph before after it ([`Layout::alone_width`])
    /// and no edge check moves it, as a line number's digits do (`DeviceAdvance`).
    steps_alone: bool,
}

/// The top of a line of `height` at `y` below the bands `bands` (each a top and the end below
/// it) when one of them holds the line, and `None` when none does. The line goes below each
/// band that it runs into, and a move can take it into a band that it had passed, so the bands
/// are taken from the top down: after a band that the line ends above, no later band holds it.
/// The bands themselves keep the order in which they were found, as a pass takes them back by
/// their count, so a sorted copy gives the order.
fn top_below_bands(bands: &[super::Band], y: Length, height: Length) -> Option<Length> {
    let holds = |y: Length, band: &super::Band| y < band.bottom && y + height > band.top;
    if !bands.iter().any(|band| holds(y, band)) {
        return None;
    }
    let mut from_top = bands.to_vec();
    from_top.sort_unstable();
    Some(
        from_top
            .iter()
            .fold(y, |y, band| if holds(y, band) { band.bottom } else { y }),
    )
}

/// The glyphs of `line` from its last tab to its last visible piece.
fn free_glyphs(line: &Line) -> impl Iterator<Item = &crate::text::Glyph> {
    let after_tab = line
        .placed
        .iter()
        .rposition(|p| matches!(p.piece, Piece::Tab(_) | Piece::PositionTab(..)))
        .map_or(0, |i| i + 1);
    line.placed
        .iter()
        .take(line.written())
        .skip(after_tab)
        .filter_map(|p| match &p.piece {
            Piece::Glyph(glyph) => Some(glyph),
            _ => None,
        })
}

impl Layout<'_> {
    /// The free space of `line` spread by `shift` ([`super::PlacedLine::free_space`]), and what
    /// rounding to whole half-EMUs took from the advances of its glyphs from its last tab to
    /// its last visible piece, in thousandths of a half-EMU to the nearest one
    /// ([`super::PlacedLine::free_rounding_thousandths`]); both 0 when each stretched space's
    /// share `spread` is 0.
    fn free_space_and_rounding(&self, line: &Line, shift: &Shift, spread: Length) -> (Length, i64) {
        if spread == Length::ZERO {
            return (Length::ZERO, 0);
        }
        let thousandths = self
            .free_roundings(line)
            .map(|(lost, per)| {
                f_office_units::div_round(
                    lost.saturating_mul(f_office_units::scale::THOUSANDTHS),
                    per.max(1),
                )
            })
            .sum();
        (shift.spread, thousandths)
    }

    /// What rounding to whole half-EMUs took from the advance of each glyph of `line` from its
    /// last tab to its last visible piece, each as a numerator over a positive denominator in
    /// half-EMUs (`Shaper::advance_rounding`).
    fn free_roundings<'a>(&'a self, line: &'a Line) -> impl Iterator<Item = (i64, i64)> + 'a {
        free_glyphs(line).filter_map(|glyph| self.shaper.advance_rounding(glyph))
    }

    /// What rounding to whole half-EMUs took from the advances of the glyphs of `line` from its
    /// last tab to its last visible piece, with what the edge check counts in their character
    /// spacing beside the spacing (`grid::counted_spacing_excess`), as a numerator over a
    /// positive denominator in half-EMUs: the line's free space less this is the free space
    /// that their exact advances leave as the edge check counts them.
    fn free_rounding(&self, line: &Line) -> (i128, i128) {
        let spacing = free_glyphs(line)
            .filter(|glyph| glyph.spacing != Length::ZERO)
            .map(|glyph| crate::grid::counted_spacing_excess(&self.device, glyph.spacing));
        self.free_roundings(line).chain(spacing).fold(
            (0, 1),
            |(lost, per), (glyph_lost, glyph_per)| {
                let glyph_per = i128::from(glyph_per.max(1));
                f_office_units::lowest_terms(
                    lost * glyph_per + i128::from(glyph_lost) * per,
                    per * glyph_per,
                )
            },
        )
    }

    /// The shares of `line`'s free space that the edge check of right-edge steps counts on a
    /// target whose edge check counts Word's shares, where the line's `shift` spreads its free
    /// space with `shares` (and `mark_shrink`): nothing on another target.
    fn counted_shares(
        &self,
        line: &Line,
        shift: &Shift,
        shares: (shift::SpaceShares, Length),
    ) -> Option<CountedShares> {
        decisions::counted_edge_shares(&self.context.quirks, || {
            shift.counted_shares(
                line,
                shares,
                self.free_rounding(line),
                self.settings.mode_rules.share_rounding(),
            )
        })
    }

    /// The lowest bottom of any `wrapTopAndBottom` band overlapping a line of box `size` at
    /// `self.y`, or `None` when no band overlaps it. The first line of a paragraph tests from
    /// `self.y - self.own_space_before` (so a band inside the paragraph's own space before moves
    /// it down in every compatibility mode). From compatibility mode 15, the downward extent is
    /// [`Self::wrap_band`] (omitting multiple-spacing extra room under
    /// `LineWrapBand::SingleLine`); earlier modes test the line's full height plus the kept
    /// `spaceAfter` (`after`) on a paragraph's last line.
    pub(super) fn band_below(&self, size: &height::LineBox, after: Length) -> Option<Length> {
        let base = if self.uses_modern_floating_layout() {
            self.wrap_band(size)
        } else {
            size.height + after
        };
        let before = self.own_space_before;
        top_below_bands(&self.bands, self.y - before, before + base)
    }

    /// Moves a line that would run into a band that a drawing keeps free below the bands
    /// ([`Self::band_below`]). The first line of a paragraph keeps the paragraph's own space
    /// before above it there, and an empty line of a header that keeps its empty lines stays.
    fn below_bands(&mut self, line: &Line, size: &height::LineBox, after: Length) {
        if self.empty_lines() == super::EmptyLines::Stay && line.placed.is_empty() {
            return;
        }
        if let Some(below) = self.band_below(size, after) {
            self.move_to(below);
            self.y += std::mem::take(&mut self.own_space_before);
        }
    }

    /// Where the paragraph's part on the page or column of `line` starts in its text, from which
    /// Word counts the pieces of the text again: at the first glyph of the paragraph's first
    /// line there.
    fn text_from(&mut self, line: &Line) -> u32 {
        let area = (self.output.pages.len(), self.column_index);
        if self.text_part.0 != area {
            self.text_part = (area, first_text_place(line));
        }
        self.text_part.1
    }

    /// The East Asian script governing punctuation compression and mark sides: the document's
    /// East Asian theme language, or the document default run's East Asian language when the
    /// theme language is absent.
    pub(super) fn east_asian_punctuation_script(&self) -> Option<EastAsianScript> {
        self.settings
            .east_asian_script
            .or(self.styles.default_run().east_asian_script())
    }

    /// Which sides of the document's compressed marks give up their share: in Traditional
    /// Chinese, `,、。;:` split equally on both sides; in Japanese, `:;・` split equally on
    /// both sides (and `・` counts as a compressible blank half); other scripts use each mark's
    /// blank half.
    fn mark_sides(&self) -> MarkSides {
        match self.east_asian_punctuation_script() {
            Some(EastAsianScript::Traditional) => MarkSides::Centered,
            Some(EastAsianScript::Japanese) => MarkSides::Japanese,
            _ => MarkSides::BlankHalf,
        }
    }

    /// What each inner blank half gives up and what each gap takes on a justified line: with
    /// compressed punctuation the halves shrink when the line runs past its width, and where
    /// the document spreads gaps the gaps share the room left on a line without spaces. Both
    /// are 0 on other lines.
    fn punctuation_steps(&self, line: &Line, props: &ParaProps, shift: &Shift) -> (Length, Length) {
        if !line.hung && !props.alignment.is_some_and(Alignment::justified) {
            return (Length::ZERO, Length::ZERO);
        }
        let shrink = (self.settings.punctuation == crate::styles::Punctuation::Compressed)
            .then(|| compressed_marks(line, shift.spread, self.mark_sides()))
            .flatten();
        match shrink {
            Some(shrink) => (shrink, Length::ZERO),
            None if self.settings.gap_spread == crate::styles::GapSpread::Spread || line.hung => {
                (Length::ZERO, spread_over_gaps(line, shift.spread))
            }
            None => (Length::ZERO, Length::ZERO),
        }
    }

    /// The shift of `line` and how its stretched spaces share its free space, where the inner
    /// blank halves of its punctuation give up `mark_shrink` ([`Shift::space_shares`]), with
    /// how its pieces narrow beyond that: a justified line with the justification of
    /// `WordPerfect` that runs past its width narrows ([`shift::Narrowing::of`]), and its
    /// spaces share only what they give up. `shift` as it is, and no narrowing, for every other
    /// line.
    fn narrowed_shift(
        &self,
        line: &Line,
        props: &ParaProps,
        (shift, mark_shrink): (Shift, Length),
    ) -> (Shift, shift::SpaceShares, Option<shift::Narrowing>) {
        let word_perfect = props.alignment == Some(crate::props::Alignment::Both)
            && decisions::justification(&self.context.quirks, self.settings)
                == crate::styles::Justification::WordPerfect;
        let (shift, narrowing) = match word_perfect
            .then(|| shift::Narrowing::of(line, -shift.spread, self.device.dots(1)))
            .flatten()
        {
            Some((taken, narrowing)) => (
                Shift {
                    offset: shift.offset,
                    spread: -taken,
                },
                Some(narrowing),
            ),
            None => (shift, None),
        };
        let shares = shift.space_shares(line, mark_shrink);
        (shift, shares, narrowing)
    }

    /// A right-to-left line takes its place on the device grid from the column's right edge:
    /// how far that edge on the grid lies from the edge that `left`, the left edge on the grid,
    /// and the column's width give.
    fn right_edge_shift(&self, left: Length) -> Length {
        let width = self.column.width;
        self.device.snap(self.column.left + width) - self.device.snap(left + width)
    }

    /// How far right of their steps the device draws the glyphs of a right-to-left line whose
    /// column's left edge on the grid is `left` ([`Origin::right_to_left`]).
    fn right_to_left_shift(&self, left: Length) -> Length {
        self.device.dots(params::RIGHT_TO_LEFT_LINE_DOTS) + self.right_edge_shift(left)
    }

    /// The edge on the device grid that a line counts its start from, and its start past that
    /// edge: the dot of the column's left edge ([`Self::column_dot`]) and the line's whole start.
    /// On a target with `WrapEdgeDot::WrapEdge`, a left-to-right line of a column of the page
    /// that a drawing on its left moved to the wrap edge counts from the dot of the wrap edge
    /// as one length from the page's left edge, and its indent past it.
    fn line_edge(&self, place: &LinePlace, props: &ParaProps) -> (Length, Length) {
        if !props.flags().bidi
            && self.column.within == super::Within::Page
            && self.column.cell.is_none()
            && let Some(edge) = decisions::wrap_edge(&self.context.quirks, place.edge)
        {
            let dot = self
                .device
                .snap(self.device.line_start(self.column.left + edge));
            return (dot, place.start - edge);
        }
        (self.column_dot(), place.start)
    }

    /// Whether a line of a paragraph outside a table goes to the next column or page, as
    /// [`Self::line`] decides before it places the line, so that the paragraph can break the
    /// line for the wraps of that page.
    pub(super) fn leaves_page(
        &mut self,
        line: &Line,
        props: &ParaProps,
        (mark, index, last): (Option<FaceIndex>, usize, bool),
    ) -> bool {
        if self.column.cell.is_some() || props.flags().section_end || self.page_has_no_line() {
            return false;
        }
        let size = self.line_box_of(line, (mark, last), props);
        let (numbers, room) = self.new_notes(line);
        let after = self.kept_after(props, last);
        self.foot((&numbers, room), (&size, after), index) == Foot::Leaves
    }

    /// Whether a line at `y` of the box `size` with the space `after` below it ends below the
    /// room that the page has above its footnotes, those of the line with the height `room`
    /// among them. A line that brings footnotes needs its whole height above them in every
    /// mode; where whole footnotes take only the room of a line's text, that holds for the
    /// lines above the footnotes of earlier lines alone.
    pub(super) fn lacks_room_at(
        &self,
        y: Length,
        size: &height::LineBox,
        after: Length,
        room: Length,
    ) -> bool {
        let notes = self.notes_height() + room;
        let fitted = self.fitted_notes(notes);
        let needed = if room > Length::ZERO && fitted == Length::ZERO {
            size.height
        } else {
            needed_room(size, after, fitted)
        };
        y + needed > self.page_bottom() - notes
    }

    /// Finds the page of a line with the box `size` and the space `after`, which may start a
    /// new column or page (`moves`), and records the line's new footnotes on it. A footnote
    /// without room whole may stay in part. Gives the space before the line, `before` or what
    /// a new column or page leaves of it.
    fn find_page(
        &mut self,
        line: &Line,
        (size, after): (&height::LineBox, Length),
        (index, moves): (usize, bool),
        before: Length,
    ) -> Length {
        let (mut notes, mut room) = self.new_notes(line);
        let mut before = before;
        match self.foot((&notes, room), (size, after), index) {
            Foot::Leaves if moves => {
                before = self.leave_column(before);
                (notes, room) = self.new_notes(line);
            }
            Foot::Splits(with_part, part) if moves => {
                room = with_part;
                self.keep_part(part);
            }
            Foot::Stays => self.count_bound_line(),
            _ => {}
        }
        self.add_notes(notes, room);
        before
    }

    /// The space after that a line of the paragraph being laid out has below it: none for a
    /// line that is not the last, and none where the next paragraph removes it.
    pub(super) fn kept_after(&self, props: &ParaProps, last: bool) -> Length {
        if !last {
            return Length::ZERO;
        }
        self.following_after.unwrap_or_else(|| props.space_after())
    }

    /// The space before that the box of a line holds, below `before` of its paragraph's own
    /// space before: on the paragraph's first line, the room of its top border as well, where
    /// the box holds that room (`HeldBorders`), except on an exact line `size` that the space
    /// after follows without a bottom border's room, whose own top rounds below the room
    /// (`FromBottom::ExactSpaced`).
    fn held_space_before(&self, before: Length, size: &LineBox) -> SpaceBefore {
        // quirk: BorderSpace::Held (src/quirks.rs)
        let border = if size.from_bottom == FromBottom::ExactSpaced && size.after == Length::ZERO {
            Length::ZERO
        } else {
            self.held_borders.top
        };
        SpaceBefore::of(self.first_space_before + border, before + border)
    }

    /// Moves the cursor down by a line's height and its height rest ([`LineBox::rest`]),
    /// carrying the rests into whole half-EMUs, so that the cursor stays the half-EMU nearest
    /// to the exact sum of the heights, a half up, with the part past it as its rest. The
    /// line's twips rest joins the cursor's ([`Self::twips_here`]).
    fn advance_line(&mut self, size: &LineBox) {
        let twips = self.twips_here();
        let rest = self.y_rest + size.rest;
        let carry = f_office_units::div_round(rest, REST_PARTS);
        self.y += size.height + Length::from_units(carry);
        self.y_rest = rest - carry * REST_PARTS;
        self.set_twips(twips.zip(size.twips).map(|(above, own)| above + own));
    }

    /// Moves the cursor down by a space between paragraphs or between a paragraph and a table,
    /// or by a table's bottom border, `length`, or up by a space that it takes back before its
    /// paragraph adds it, a negative `length`, with the length's twips rest ([`twips_rest`]).
    pub(super) fn advance_space(&mut self, length: Length) {
        let twips = self.twips_here();
        self.y += length;
        self.set_twips(
            twips
                .zip(twips_rest(&self.device, length))
                .map(|(a, b)| a + b),
        );
    }

    /// Starts the cursor's twips rest at the body's top on a page or at a table cell's text
    /// top, `top`, where the cursor stands: that of the length `top` from the page's top.
    pub(super) fn start_twips(&mut self, top: Length) {
        self.set_twips(twips_rest(&self.device, top));
    }

    /// The cursor's twips rest: the sum of the twips rests of the lengths from the body's top
    /// on the page down to the cursor, while each of them is whole twips or the height of a line
    /// in whole 1/4096 pt, which adds none, and the cursor stands where the last of them left
    /// it. `None` after any other length or move.
    pub(super) fn twips_here(&self) -> Option<i64> {
        self.y_twips
            .filter(|twips| twips.at == self.y)
            .map(|twips| twips.rest)
    }

    /// Sets the cursor's twips rest to `rest` at the place where the cursor stands.
    pub(super) fn set_twips(&mut self, rest: Option<i64>) {
        self.y_twips = rest.map(|rest| TwipsRest { at: self.y, rest });
    }

    /// Finds the page of a line of `place` with the box `size`, as [`Self::find_page`] does,
    /// and gives whether the line paginates, which a line outside table cells does, and the
    /// space before it.
    fn line_page(
        &mut self,
        line: &Line,
        props: &ParaProps,
        place: &LinePlace,
        size: &LineBox,
    ) -> (bool, Length) {
        // The line must fit above the footnotes of the page, its own ones included. A line in
        // a table cell never starts a page itself.
        let paginate = self.column.cell.is_none();
        // The empty paragraph that ends a section before a new page stays on its page.
        // So does a page break that starts a paragraph which goes on after the break.
        let stays =
            props.flags().section_end || line.starts_with_page_break(place.index, place.last);
        // The paragraph's own space before above its first line, which a new column or page
        // leaves out.
        let moves = !self.page_has_no_line() && paginate && !stays;
        let after = self.kept_after(props, place.last);
        let before = self.find_page(
            line,
            (size, after),
            (place.index, moves),
            self.own_space_before,
        );
        if !paginate {
            // In a row that splits, the last line of a paragraph stays on the page only with
            // the space after that the paragraph keeps.
            self.carry_line(self.y + size.height + after);
        }
        (paginate, before)
    }

    /// `line` with the spaces at its end that count as its written text in a paragraph of the
    /// properties `props`, where the target keeps opposite-direction trailing spaces at their
    /// runs' level ([`decisions::kept_end_spaces`]): the line then measures, aligns and justifies
    /// them with its other written pieces.
    pub(super) fn written_end_spaces<'l>(
        &self,
        line: &'l Line,
        props: &ParaProps,
    ) -> Cow<'l, Line> {
        let bidi = props.flags().bidi;
        match decisions::kept_end_spaces(
            &self.context.quirks,
            || {
                if bidi {
                    line.holds_right_to_left_text()
                } else {
                    line.holds_left_to_right_text()
                }
            },
            super::bidi::end_space_runs(line, !bidi),
        ) {
            0 => Cow::Borrowed(line),
            kept => Cow::Owned(Line {
                written_end_spaces: kept,
                ..line.clone()
            }),
        }
    }

    pub(super) fn line(
        &mut self,
        line: &Line,
        props: &ParaProps,
        mark: Option<FaceIndex>,
        place: LinePlace,
    ) {
        let rule = props.line.unwrap_or(LineSpacing::Auto(LINE));
        let size = self.line_box_of(line, (mark, place.last), props);
        self.below_bands(line, &size, self.kept_after(props, place.last));
        let (paginate, before) = self.line_page(line, props, &place, &size);
        let at = (self.y, self.held_space_before(before, &size));
        let rounding = (self.ties(), self.box_top(at));
        let rests = (self.y_rest, self.twips_here());
        let (base, form, unrounded_offset) =
            self.placed_line_baseline(line, rule, &size, at, rounding, rests);
        let (alignment, shift) = self.alignment_and_shift(line, props, place);
        let own = place.own_at_indent(alignment.starts_at_indent());
        // The left edge of the column lands on the device grid, and so does the line's start
        // past it, with the halves of `Device::line_start` (`Self::column_dot`); a line at a
        // drawing's wrap edge can count from that edge's own dot (`Self::line_edge`).
        let (left, from) = self.line_edge(&place, props);
        let (mark_shrink, gap_extra) = self.punctuation_steps(line, props, &shift);
        let (shift, shares, narrowing) = self.narrowed_shift(line, props, (shift, mark_shrink));
        let counted_shares = self.counted_shares(line, &shift, (shares, mark_shrink));
        let origin = Origin {
            x: left + self.device.first_line_start(from, own) + shift.offset,
            edge: left,
            start: place.start,
            own,
            baseline: base,
            unrounded_baseline: self.y + unrounded_offset,
            grid_shift: self.column.left + place.start - from - left,
            space_extra: shares.per_space,
            space_rest: shares.rest,
            counted_shares,
            mark_shrink,
            mark_sides: self.mark_sides(),
            gap_extra,
            narrowing,
            drop: self.shape_drop(line, rule, &size),
            anchor_bottom: self.anchor_bottom(line, rule, &size),
            text_from: self.text_from(line),
            mark: place.last,
            right_to_left: props.flags().bidi.then(|| self.right_to_left_shift(left)),
            starts_at_indent: alignment.starts_at_indent(),
            segment_rest: Length::ZERO,
            steps_alone: false,
        };
        let (free_space, free_rounding_thousandths) =
            self.free_space_and_rounding(line, &shift, origin.space_extra);
        let item = self.record_item();
        // quirk: CenteredLine::MiddlesShared (src/quirks.rs)
        self.centered_middle = self.centered_line(line, props).map(|c| c.middle);
        self.aligned_parts = None;
        let bottom = self.y + size.height + self.kept_after(props, place.last);
        self.line_band = Some((self.y - before, bottom));
        let drawn = self.emit_aligned(line, origin, (alignment, shift.offset), place.width);
        self.line_band = None;
        self.centered_middle = None;
        self.output.placed.push(super::PlacedLine {
            paragraph: place.paragraph,
            page: self.output.pages.len(),
            story: super::LineStory::Body,
            part: self.output.story_parts.current,
            area: super::LineArea::of(paginate),
            cell: self.cell_place,
            item,
            top: self.y,
            top_rests: rests,
            height: size.height,
            height_rests: (size.rest, size.twips),
            baseline: base - self.y,
            unrounded_baseline: unrounded_offset,
            baseline_form: form,
            ascent: size.ascent,
            descent: size.descent,
            spacing: rule,
            index: place.index,
            last: place.last,
            spaced: self.kept_after(props, place.last) > Length::ZERO,
            before,
            kept: line.kept,
            wrapped: line.wrapped,
            justified: props.alignment.is_some_and(Alignment::justified),
            alignment,
            steps: drawn.steps,
            drawn: drawn.glyphs,
            spread: origin.space_extra,
            free_space,
            free_rounding_thousandths,
            edge: origin.edge,
            column_left: self.column.left,
            column_origin: self.column.origin,
            cell_edge: self.column.within.cell_edge(),
            aligned: self.aligned_parts.take(),
            markup_scale: None,
            text: line_text(line, (origin.x, &drawn.edges), &drawn.order, place.last),
        });
        self.note_comments(line, self.y);
        self.line_number(props, line, base);
        self.line_change_bar(
            line,
            props,
            (mark, place.last),
            (before, size.height),
            paginate,
        );
        self.advance_line(&size);
        self.break_after_line(line, paginate);
    }

    /// The change bar beside a line whose box is `height` high below the paragraph's own space
    /// `before` on its first line, with its space after on its `last` line, whose paragraph
    /// mark is `mark`; the bar of a paragraph's last line is kept as the last bar in a story
    /// that the page breaks (`paginate`).
    fn line_change_bar(
        &mut self,
        line: &Line,
        props: &ParaProps,
        (mark, last): (Option<FaceIndex>, bool),
        (before, height): (Length, Length),
        paginate: bool,
    ) {
        let after = if last {
            props.space_after()
        } else {
            Length::ZERO
        };
        // The bar covers the paragraph's own space before on its first line.
        let height = before + height + after;
        let bar = self.change_bar(line, mark.filter(|_| last), (self.y - before, height));
        if last {
            self.last_bar = bar
                .filter(|_| paginate)
                .map(|index| (self.output.pages.len(), index));
        }
    }

    /// Starts the next page or column after a line that ends with a page or column break, in a
    /// story that the page breaks (`paginate`).
    fn break_after_line(&mut self, line: &Line, paginate: bool) {
        self.after_break = line.breaks_page_or_column() && paginate;
        if self.after_break {
            if line.end == LineEnd::PageBreak {
                self.new_page();
                self.page_from_break = Some(self.output.pages.len());
                self.break_numbers = (0, self.output.line_count);
            } else {
                self.next_column();
            }
        }
    }
}

/// The room that a line needs above the end of the body on its page, from the line's top, when
/// footnotes of the height `notes` stand on the page. Without footnotes, the line's text must
/// fit. Above footnotes, the whole height of the line must fit, and with it `after`: for the
/// last line of a paragraph, the space after that the paragraph keeps before the next one.
pub(super) fn needed_room(size: &height::LineBox, after: Length, notes: Length) -> Length {
    if notes == Length::ZERO {
        return size.text_bottom;
    }
    size.height + after
}

/// The face of a piece that sizes its line, if any.
fn face_of(piece: &Piece) -> Option<FaceIndex> {
    match piece {
        Piece::Glyph(g) => (g.sizing == LineSizing::ByFace).then_some(g.face),
        Piece::Rule { face, .. } | Piece::CheckBox { face, .. } | Piece::Strut(face) => Some(*face),
        Piece::Tab(face) | Piece::PositionTab(face, _) => *face,
        Piece::LineBreak(_)
        | Piece::PageBreak
        | Piece::ColumnBreak
        | Piece::Shift(_)
        | Piece::Advance(_)
        | Piece::Bar { .. }
        | Piece::Vinculum { .. }
        | Piece::Diagonal { .. }
        | Piece::Object { .. }
        | Piece::Note(_)
        | Piece::Endnote(_)
        | Piece::NoteMarkEnd
        | Piece::EndnoteMarkEnd(_)
        | Piece::Comment(_)
        | Piece::Anchor(_)
        | Piece::Clear => None,
    }
}

/// Where the first glyph of `line` lies in its paragraph's text, or 0 for a line without one.
pub(super) fn first_text_place(line: &Line) -> u32 {
    line.placed
        .iter()
        .find_map(|p| match p.piece {
            Piece::Glyph(glyph) => Some(glyph.place.in_paragraph),
            _ => None,
        })
        .unwrap_or(0)
}