Skip to main content

f_office_docx/
lines.rs

1//! Breaking a paragraph into lines.
2
3use f_office_units::scale::THOUSANDTHS;
4use f_office_units::{Length, count_factor};
5
6use crate::character_class::CharacterClass;
7use crate::kinsoku::{Kinsoku, breaks_between};
8use crate::props::EastAsianLanguage;
9
10use crate::props::{TabKind, TabStop};
11use crate::tabs::Tabs;
12use crate::text::{AUTOMATIC_HYPHEN, FaceIndex, Glyph, LINE_END_HYPHEN, SOFT_HYPHEN, SpaceKind};
13
14pub(crate) mod joints;
15
16use joints::JointCounts;
17
18/// The no-break space, U+00A0, which joins the words on both of its sides.
19const NO_BREAK_SPACE: char = '\u{a0}';
20
21/// One unit of paragraph content after measuring.
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub enum Piece {
24    /// A glyph.
25    Glyph(Glyph),
26    /// A tab, with the face of its run.
27    Tab(Option<FaceIndex>),
28    /// A positional tab, with the face of its run and the stop that it goes to.
29    PositionTab(Option<FaceIndex>, TabStop),
30    /// A line break inside the paragraph, with the face of its run.
31    LineBreak(Option<FaceIndex>),
32    /// A page break.
33    PageBreak,
34    /// A column break.
35    ColumnBreak,
36    /// A mark without width for the footnote with this number, whose reference is on the line.
37    Note(NoteNumber),
38    /// A mark without width right after an auto-numbered endnote reference (`w:endnoteReference`)
39    /// with this many glyphs on the line.
40    Endnote(u16),
41    /// A mark without width right after a footnote's own mark (`w:footnoteRef`) in the
42    /// footnote's text.
43    NoteMarkEnd,
44    /// A mark without width right after an endnote's own mark (`w:endnoteRef`) with this many
45    /// glyphs in the endnote's text.
46    EndnoteMarkEnd(u16),
47    /// A mark without width for the anchor of the comment with this index, whose balloon goes
48    /// beside the line.
49    Comment(CommentIndex),
50    /// A mark without width for the anchor of the paragraph's floating drawing with this index,
51    /// in the order of the paragraph's content, which is placed down from the line that holds
52    /// the mark. [`break_lines`] takes the marks out before it breaks the other pieces, so that
53    /// they change no line, and gives each to its line's [`Line::anchors`].
54    Anchor(usize),
55    /// A mark without width that draws nothing and sizes its line with this face, such as the
56    /// reference mark in a comment's text.
57    Strut(FaceIndex),
58    /// A mark without width at the start of a line after a clearing line break: the line
59    /// goes below the floating objects.
60    Clear,
61    /// The rule of a note separator (`w:separator`), drawn at the strikeout position of the
62    /// run's face.
63    Rule {
64        /// The face of its run.
65        face: FaceIndex,
66        /// Its length.
67        width: Length,
68    },
69    /// The square of a check box form field, as wide as the single line of its run's face.
70    CheckBox {
71        /// The face of its run, at the size of the box.
72        face: FaceIndex,
73        /// Its advance: the single line height of the face.
74        width: Length,
75    },
76    /// A move of the pieces after it by a length, back when negative, which draws nothing and
77    /// keeps the line from breaking there: the places of the parts of a stacked fraction.
78    Shift(Length),
79    /// The move of an `ADVANCE` field: as [`Piece::Shift`], a move of the pieces after it,
80    /// back when negative, which draws nothing. It belongs to the word before it, and the
81    /// word ends after it, so the line can break after it but not before it.
82    Advance(Length),
83    /// The bar of a stacked fraction, which takes no room and runs from its place over its
84    /// width, at the axis of its face's size.
85    Bar {
86        /// The face of the fraction's run.
87        face: FaceIndex,
88        /// Its length: the width of the wider part.
89        width: Length,
90    },
91    /// A bar over or under an expression of an equation: the bar of a radical over its element,
92    /// or the bar of a bar structure over or under its base. It has no advance and runs from
93    /// its place over its width, with its top `top` above the baseline of its face and
94    /// `thickness` thick, and its line has room for it and for `beyond` above and below it.
95    Vinculum {
96        /// The face of the root sign as drawn, or of the bar structure's marks.
97        face: FaceIndex,
98        /// Its length: the width of the element or the base.
99        width: Length,
100        /// The height of its top above the baseline of its face, on a dot.
101        top: Length,
102        /// Its thickness.
103        thickness: Length,
104        /// The room of its line above its top and below its bottom.
105        beyond: (Length, Length),
106        /// The white space above its top that the box of its structure holds: a radical's
107        /// `RadicalExtraAscender`, an overbar's `OverbarExtraAscender`; none for an underbar.
108        clear: Length,
109    },
110    /// A diagonal strike across a border box (`m:borderBox`): zero advance, connecting the box's
111    /// corners from `x` to `x + width` between `bottom` and `top` above the face's baseline.
112    Diagonal {
113        /// The face of the border box's marks.
114        face: FaceIndex,
115        /// The horizontal span of the strike.
116        width: Length,
117        /// The lower edge above the face's baseline.
118        bottom: Length,
119        /// The upper edge above the face's baseline.
120        top: Length,
121        /// The stroke thickness.
122        thickness: Length,
123        /// Whether the strike rises from bottom-left to top-right (`strikeBLTR`); false for
124        /// top-left to bottom-right (`strikeTLBR`).
125        rising: bool,
126    },
127    /// An inline object that sits on the baseline, raised or lowered with its run.
128    Object {
129        /// Its advance.
130        width: Length,
131        /// Its height, which stands above its bottom.
132        height: Length,
133        /// How far its run raises its bottom above the baseline (`w:position`), or lowers it
134        /// below the baseline when negative.
135        raised: Length,
136        /// The index of its picture in the layout's pictures, if it shows one.
137        picture: Option<usize>,
138        /// The index of its shape in the layout's inline drawings, if it shows one.
139        drawing: Option<DrawingIndex>,
140        /// Whether its run draws an underline, which stands below the object and needs room
141        /// below the baseline when the object is alone on its line and taller than its font
142        /// line (`UnderlinedObjectRoom`).
143        underlined: bool,
144        /// Its run's own unshifted face. On a target that sizes inline object lines by the
145        /// objects' runs (`ObjectLineMultiple::ObjectRun`, compatibility mode 15 and later), this
146        /// face sets the single line of an object-alone line in place of the paragraph mark or
147        /// line break, scales multiple spacing below a tall object alone, and expands a text line
148        /// when its single line exceeds the text's. `None` where the run has no face, as for a
149        /// label's legacy spacer or picture bullet.
150        run_face: Option<FaceIndex>,
151        /// Whether the object attaches to the word before it with no break opportunity before
152        /// the object, while still allowing a break after it: true for single inline VML vector
153        /// shapes (`w:pict` without `v:imagedata`, `v:group`, or `o:hr="t"`) and false for inline
154        /// pictures, OLE objects, VML groups, horizontal rules, DrawingML (`wp:inline`) shapes,
155        /// and list label spacers.
156        joins_before: bool,
157    },
158}
159
160/// The index of an inline drawing among the drawings of a layout's pass output, which the
161/// layout makes when it measures the drawing, and reads when it sizes and draws its line.
162#[derive(Clone, Copy, Debug, PartialEq, Eq)]
163pub struct DrawingIndex(usize);
164
165impl DrawingIndex {
166    /// The drawing at `index` in the pass output's list.
167    pub(crate) const fn new(index: usize) -> Self {
168        Self(index)
169    }
170
171    /// Its place in the pass output's list.
172    pub(crate) const fn get(self) -> usize {
173        self.0
174    }
175}
176
177/// The index of a comment among the comments in the order of their first references, which
178/// the layout makes at a comment's first reference.
179#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
180pub struct CommentIndex(usize);
181
182impl CommentIndex {
183    /// The comment at `index` in the order of references.
184    pub(crate) const fn new(index: usize) -> Self {
185        Self(index)
186    }
187
188    /// Its place in the order of references.
189    pub(crate) const fn get(self) -> usize {
190        self.0
191    }
192}
193
194/// The number of a footnote: the place of its ID in the order of the first references of the
195/// footnotes, from 0, which a footnote's reference piece names. Its reference and its mark show
196/// its label, which the section's numbering of footnotes gives it at its first reference.
197#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
198pub struct NoteNumber(usize);
199
200impl NoteNumber {
201    /// The number of the footnote whose ID has the place `index`, from 0, in the order of the
202    /// first references.
203    pub(crate) const fn of_index(index: usize) -> Self {
204        Self(index)
205    }
206
207    /// The place of the footnote's ID in the order of the first references, from 0.
208    pub(crate) const fn index(self) -> usize {
209        self.0
210    }
211}
212
213/// A piece placed on a line, at an offset from the line start.
214#[derive(Clone, Copy, Debug, PartialEq, Eq)]
215pub struct Placed {
216    /// The piece.
217    pub piece: Piece,
218    /// Its offset from the line start.
219    pub x: Length,
220    /// Its advance.
221    pub advance: Length,
222    /// For a tab, the character that fills its space.
223    pub leader: Option<char>,
224    /// For a tab, the kind of the stop that it goes to.
225    pub tab: Option<TabKind>,
226}
227
228/// How a line ends.
229#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
230pub enum LineEnd {
231    /// Where the next word does not fit, or at the end of the paragraph.
232    #[default]
233    Wrap,
234    /// Inside a word that does not fit on a line of its own.
235    Split,
236    /// At a line break (`w:br`), with the face of its run.
237    Break(Option<FaceIndex>),
238    /// At a page break, which follows the line.
239    PageBreak,
240    /// At a column break, which follows the line.
241    ColumnBreak,
242}
243
244/// A line of a paragraph.
245#[derive(Clone, Debug, Default, PartialEq, Eq)]
246pub struct Line {
247    /// The pieces in order.
248    pub placed: Vec<Placed>,
249    /// How the line ends.
250    pub end: LineEnd,
251    /// The decision that kept the line's last word on it.
252    pub kept: Option<Fit>,
253    /// For a line that ends before a word that does not fit, the decision that moved it to
254    /// the next line.
255    pub wrapped: Option<Fit>,
256    /// Whether the word that did not fit ends with a punctuation mark that Word lets stand
257    /// past the end of this line, and fits without it: Word keeps the word on this line and
258    /// hangs the mark, where F-Office, which hangs no mark, moves the word.
259    pub would_hang: bool,
260    /// Whether this line keeps its final word with a trailing punctuation mark hanging past the
261    /// right margin (`w:overflowPunct`), so the line justifies its text before the hanging mark
262    /// to the right edge and ends immediately after the mark.
263    pub hung: bool,
264    /// The anchor marks on the line ([`Piece::Anchor`]), in their order, beside its placed
265    /// pieces, which they do not change.
266    pub anchors: Vec<LineAnchor>,
267    /// The hyphen that the line shows at its end where a word breaks, which the text does not
268    /// hold: its last glyph.
269    pub hyphen: Option<EndHyphen>,
270    /// How many of the spaces at the line's end, from the first, count as its written text:
271    /// those that keep the right-to-left level of their runs in a left-to-right paragraph.
272    /// Layout sets it when it places the line; 0 for every other line.
273    pub written_end_spaces: usize,
274}
275
276/// A hyphen that a line shows at its end where a word breaks, which the text does not hold.
277#[derive(Clone, Copy, Debug, PartialEq, Eq)]
278pub enum EndHyphen {
279    /// At an automatic hyphenation point.
280    Automatic,
281    /// At a soft hyphen, which shows nothing inside a line.
282    Soft,
283}
284
285/// An anchor mark on a line.
286#[derive(Clone, Copy, Debug, PartialEq, Eq)]
287pub struct LineAnchor {
288    /// How many of the line's placed pieces come before the mark.
289    pub at: usize,
290    /// The index of the mark's drawing, in the order of the paragraph's content.
291    pub drawing: usize,
292}
293
294/// What lies on a line before one of its drawn glyphs, in the order of drawing.
295#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
296pub enum Step {
297    /// Nothing, or only spaces or an inline object: the glyph starts the line.
298    Start,
299    /// Nothing, and the glyph is the first of a list label.
300    Label,
301    /// A list label: the glyph is the first of the text after it.
302    AfterLabel,
303    /// A tab to a left stop, also a default stop or a positional tab that aligns at the left,
304    /// also when the tab starts the line.
305    Tab,
306    /// A tab to a center, right or decimal stop, an aligned tab: the text after it centers on
307    /// the stop, ends at it or puts its decimal separator at it.
308    AlignedTab,
309    /// Spaces that stretch or shrink on a justified line.
310    Stretched,
311    /// Spaces at their own width.
312    Space,
313    /// An inline object.
314    Object,
315    /// A tab before it, whose leader the glyph is a character of: it sits on the leader's grid.
316    Leader,
317    /// Only the glyph before it.
318    Glyph,
319}
320
321/// The numbers of one decision whether a word fits on its line, from the start of the line, by
322/// which a caller can replay the decision with another rule.
323#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
324pub struct Fit {
325    /// The width of the line.
326    pub width: Length,
327    /// Where the word ends on the line, without the spaces after it.
328    pub end: Length,
329    /// The width of the word, without the spaces after it.
330    pub word: Length,
331    /// The width of the spaces on the line before the word, in all.
332    pub spaces: Length,
333    /// The width of the spaces right before the word.
334    pub space: Length,
335    /// How many spaces the line holds before the word, in all.
336    pub space_count: usize,
337    /// How many of them lie right before the word.
338    pub last_space_count: usize,
339    /// How far past its width a tab stop past the end lets the line run.
340    pub room: Length,
341    /// How far past its width the line may run for the word: the room, and on a justified
342    /// line the shrinking of its spaces.
343    pub over: Length,
344    /// Whether the spaces of the line may shrink.
345    pub shrinks: bool,
346}
347
348impl Line {
349    /// The pieces of `lines` in order, with the breaks that ended them, so that they can be
350    /// broken into lines again.
351    #[must_use]
352    pub fn pieces(lines: &[Self]) -> Vec<Piece> {
353        let mut pieces = Vec::new();
354        for line in lines {
355            let mut marks = line.anchors.iter().peekable();
356            for (index, placed) in line.placed.iter().enumerate() {
357                while let Some(mark) = marks.next_if(|mark| mark.at <= index) {
358                    pieces.push(Piece::Anchor(mark.drawing));
359                }
360                pieces.push(placed.piece);
361            }
362            pieces.extend(marks.map(|mark| Piece::Anchor(mark.drawing)));
363            match line.end {
364                LineEnd::PageBreak => pieces.push(Piece::PageBreak),
365                LineEnd::ColumnBreak => pieces.push(Piece::ColumnBreak),
366                LineEnd::Break(face) => pieces.push(Piece::LineBreak(face)),
367                LineEnd::Wrap | LineEnd::Split => {}
368            }
369        }
370        pieces
371    }
372
373    /// Whether the line is the first of several of its paragraph and holds only a page break,
374    /// so that the paragraph starts with a page break and goes on after it.
375    #[must_use]
376    pub fn starts_with_page_break(&self, index: usize, last: bool) -> bool {
377        index == 0 && !last && self.holds_only_page_break()
378    }
379
380    /// Whether the line holds nothing and ends at a page break.
381    #[must_use]
382    pub fn holds_only_page_break(&self) -> bool {
383        self.placed.is_empty() && self.end == LineEnd::PageBreak
384    }
385
386    /// The index of the first line of a paragraph broken into `lines`: 0, or, when the
387    /// paragraph holds more than page breaks, the count of the leading page breaks that
388    /// `breaks` puts before its first line: the first of them or all of them.
389    #[must_use]
390    pub fn first_index(lines: &[Self], breaks: LeadingBreaks) -> usize {
391        let leading = lines
392            .iter()
393            .take_while(|line| line.holds_only_page_break())
394            .count();
395        if leading == lines.len() {
396            return 0;
397        }
398        breaks.before_first_line(leading)
399    }
400
401    /// Whether a page or column break follows the line.
402    #[must_use]
403    pub const fn breaks_page_or_column(&self) -> bool {
404        matches!(self.end, LineEnd::PageBreak | LineEnd::ColumnBreak)
405    }
406}
407
408impl Line {
409    /// The width up to the end of the last glyph that is not a trailing space.
410    #[must_use]
411    pub fn width(&self) -> Length {
412        self.end_of(self.written())
413    }
414
415    /// The width that the fit test needs for the line: its width ([`Self::width`]) with what the
416    /// test counts beside the advances of its written pieces ([`counted`]).
417    #[must_use]
418    pub fn fit_width(&self) -> Length {
419        let written = self.placed.get(..self.written()).unwrap_or_default();
420        self.width() + written.iter().map(|p| counted(&p.piece)).sum()
421    }
422
423    /// The number of pieces before the line's trailing spaces: the pieces of its written
424    /// text.
425    #[must_use]
426    pub fn written(&self) -> usize {
427        self.last_visible().map_or(0, |last| last + 1)
428    }
429
430    /// Where the first `pieces` pieces of the line end, from the line's start.
431    #[must_use]
432    pub fn end_of(&self, pieces: usize) -> Length {
433        pieces
434            .checked_sub(1)
435            .and_then(|last| self.placed.get(last))
436            .map_or(Length::ZERO, |p| p.x + p.advance)
437    }
438
439    /// Whether the line holds text of a run without `w:rtl`: a glyph of such a run that is
440    /// not a space.
441    #[must_use]
442    pub fn holds_left_to_right_text(&self) -> bool {
443        self.placed
444            .iter()
445            .any(|p| !is_space(&p.piece) && run_rtl(&p.piece) == Some(false))
446    }
447
448    /// Whether the line holds text of a run with `w:rtl`: a glyph of such a run that is
449    /// not a space.
450    #[must_use]
451    pub(crate) fn holds_right_to_left_text(&self) -> bool {
452        self.placed
453            .iter()
454            .any(|p| !is_space(&p.piece) && run_rtl(&p.piece) == Some(true))
455    }
456
457    /// The index of the last piece that is not a trailing space, of text or of an operator
458    /// where an equation breaks, or of the last space at the line's end that counts as its
459    /// written text ([`Self::written_end_spaces`]).
460    #[must_use]
461    pub fn last_visible(&self) -> Option<usize> {
462        let last = self
463            .placed
464            .iter()
465            .rposition(|p| !is_space(&p.piece) && !is_operator_space(&p.piece))?;
466        let spaces = self.placed.len() - 1 - last;
467        Some(last + self.written_end_spaces.min(spaces))
468    }
469
470    /// The index of the first piece whose spaces a justified line may stretch: the first piece
471    /// that is not a space, so that spaces at the start of the line keep their width.
472    #[must_use]
473    pub fn first_stretched(&self) -> usize {
474        let after_tab = self
475            .placed
476            .iter()
477            .rposition(|p| matches!(p.piece, Piece::Tab(_) | Piece::PositionTab(..)))
478            .map_or(0, |i| i + 1);
479        let rest = self.placed.get(after_tab..).unwrap_or(&[]);
480        after_tab
481            + rest
482                .iter()
483                .position(|p| !is_space(&p.piece))
484                .unwrap_or(rest.len())
485    }
486}
487
488/// Where the line breaker has met Thai text on the line that it fills.
489#[derive(Clone, Copy, Debug, PartialEq, Eq)]
490enum ThaiText {
491    /// Neither on the line nor in the word that it tests.
492    None,
493    /// In the word that the line tests only.
494    InWord,
495    /// On the line.
496    OnLine,
497}
498
499/// Whether `piece` is a glyph of the Thai block.
500fn is_thai(piece: &Piece) -> bool {
501    matches!(piece, Piece::Glyph(glyph) if CharacterClass::Thai.contains(glyph.ch))
502}
503
504/// The widths and tab settings that line breaking needs.
505#[derive(Clone, Debug, PartialEq, Eq)]
506pub struct Frame {
507    /// The width of the first line.
508    pub first_width: Length,
509    /// The width of the other lines.
510    pub width: Length,
511    /// The width of the text area of the column or cell, from the column edge: where the
512    /// lines would end without a right indent.
513    pub area_width: Length,
514    /// The distance from the column edge to the start of the first line.
515    pub first_start: Length,
516    /// The distance from the column edge to the start of the other lines.
517    pub start: Length,
518    /// The tab stops.
519    pub tabs: Tabs,
520    /// How much each space on a justified line may shrink so that one more word fits.
521    pub shrink: Shrink,
522    /// Whether a line that holds a Thai character, with the word that it tests, keeps its
523    /// spaces from shrinking ([`Frame::shrink`]).
524    pub thai_keeps_spaces: bool,
525    /// Which spaces at the end of a word count in the word's fit ([`Breaker::fitted_end_spaces`]).
526    pub end_space_fit: EndSpaceFit,
527    /// The characters that may not start or end a line of East Asian text, or `None` for text
528    /// without an East Asian language, which breaks only where Latin text does.
529    pub kinsoku: Option<Kinsoku>,
530    /// Whether a joined space run, a run of white space that holds a no-break space, keeps the
531    /// words on both of its sides on one line, as from compatibility mode
532    /// [`JOINED_SPACE_MODE`](crate::params::JOINED_SPACE_MODE).
533    pub joined_spaces: bool,
534    /// What the target's line breaking does with tabs and footnote references.
535    pub breaking: LineBreaking,
536    /// Whether the limit of [`LineBreaking::ends_aligned_text`] also holds for a stop at or past
537    /// the line's end; where it does not, the text after such a stop keeps its place at the stop and the
538    /// line runs on to where it ends.
539    pub limits_past_end: bool,
540    /// How far the blank halves of the punctuation on a justified line of East Asian text may
541    /// shrink so that more text fits, or `None` where punctuation keeps its width.
542    pub punctuation: Option<Compression>,
543    /// How a line may end at an automatic hyphenation point ([`AUTOMATIC_HYPHEN`]), or `None`
544    /// where the paragraph's words have none.
545    pub hyphenation: Option<Hyphenation>,
546    /// What line breaking does when a trailing mark of [`Kinsoku::hangs`] overflows a line whose
547    /// preceding pieces fit (`w:overflowPunct`).
548    pub overflow_punct: OverflowPunct,
549}
550
551/// What line breaking does when a trailing mark of [`Kinsoku::hangs`] overflows a line whose
552/// preceding pieces fit (`w:overflowPunct`).
553#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
554pub enum OverflowPunct {
555    /// Disabled (`w:overflowPunct w:val="0"`): neither hang nor warn.
556    Off,
557    /// Wrap the word and record [`Line::would_hang`] so layout can warn.
558    #[default]
559    Warn,
560    /// Keep the word on the line with its trailing mark hanging past the right margin
561    /// ([`Line::hung`]).
562    Hang,
563}
564
565/// Which spaces at the end of a word count in the word's fit on a line.
566#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
567pub enum EndSpaceFit {
568    /// None: a word fits without the spaces at its end, which hang past the line's width.
569    #[default]
570    WithoutSpaces,
571    /// On a line that already holds text of a run without `w:rtl`, the right-to-left spaces at
572    /// the word's end, from the first: the spaces of runs with `w:rtl`, and, on a line that
573    /// already holds a left-to-right letter, after a word that ends with a right-to-left letter
574    /// before a word that starts with one, the spaces between them, whether or not their runs
575    /// have `w:rtl`. The spaces of runs with `w:rtl` keep their runs' right-to-left level when
576    /// the line ends after them, and the line holds them as written text. A justified line
577    /// counts all of them as its spaces ([`Breaker::shrink_over`]).
578    WithRightToLeftSpaces,
579}
580
581impl EndSpaceFit {
582    /// Whether the fit counts the spaces between right-to-left letters on `line`: where it
583    /// counts right-to-left spaces, on a line that already holds a left-to-right letter.
584    fn between_letters(self, line: &Line) -> bool {
585        self == Self::WithRightToLeftSpaces
586            && line
587                .placed
588                .iter()
589                .filter_map(|p| run_glyph(&p.piece))
590                .any(|glyph| left_to_right(glyph.ch))
591    }
592}
593
594/// The spaces at the end of a word that count in its fit ([`EndSpaceFit`]): their width, how
595/// many there are, and how far they may shrink in all.
596#[derive(Clone, Copy, Debug, Default)]
597struct EndSpaces {
598    width: Length,
599    count: usize,
600    shrink: Length,
601    /// Whether the word starts with a right-to-left letter.
602    starts_right_to_left: bool,
603}
604
605/// How a paragraph's lines may end at the automatic hyphenation points of its words. A word
606/// that does not fit breaks at its last point whose part, with the hyphen, fits.
607#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
608pub struct Hyphenation {
609    /// The hyphenation zone where it holds: a word is hyphenated only when the room that the
610    /// line leaves for it is wider than the zone. `None` where the zone does not hold.
611    pub zone: Option<Length>,
612    /// The most lines in a row that may end at an automatic point, or `None` for no limit.
613    pub limit: Option<std::num::NonZeroUsize>,
614}
615
616/// What the target's line breaking does with the text after a tab, with a footnote reference's
617/// mark and with a paragraph's leading page breaks, which a frame carries.
618#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
619pub struct LineBreaking {
620    /// Whether the text after a tab to a right, center or decimal stop that would end past its
621    /// limit ends there instead; otherwise it runs past.
622    pub ends_aligned_text: bool,
623    /// Whether a footnote reference's mark is text of its word, so that a line breaks after it
624    /// only where its last glyph and the next piece allow a break.
625    pub note_reference_in_word: bool,
626    /// Whether a tab whose next stop is a custom left stop past the line's end goes to the
627    /// line's end; otherwise it goes to its stop.
628    pub left_stops_to_line_end: bool,
629    /// Which of a paragraph's leading page breaks come before its first line, which takes the
630    /// first line's start and width; the lines before it take those of the other lines.
631    pub leading_breaks: LeadingBreaks,
632}
633
634/// Which of the page breaks that start a paragraph come before its first line.
635#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
636pub enum LeadingBreaks {
637    /// None: the first line is the first break's line.
638    #[default]
639    None,
640    /// The first: the line after it is the first line, also when it holds the next break.
641    First,
642    /// All: the first line is the first line that does not hold only a page break.
643    All,
644}
645
646impl LeadingBreaks {
647    /// How many of a paragraph's `leading` page breaks come before its first line.
648    #[must_use]
649    pub fn before_first_line(self, leading: usize) -> usize {
650        match self {
651            Self::None => 0,
652            Self::First => leading.min(1),
653            Self::All => leading,
654        }
655    }
656}
657
658impl Frame {
659    /// The start and the width of the first line or of another line in a column `column`
660    /// wide, from the column's left edge. The frame's starts lie at the side where the lines
661    /// start, which is the right side of a right-to-left paragraph, so there they mirror across
662    /// the column, and the indents swap sides on the page.
663    #[must_use]
664    pub fn on_page(&self, first: bool, column: Length, right_to_left: bool) -> (Length, Length) {
665        let (start, width) = if first {
666            (self.first_start, self.first_width)
667        } else {
668            (self.start, self.width)
669        };
670        if right_to_left {
671            (column - start - width, width)
672        } else {
673            (start, width)
674        }
675    }
676}
677
678/// Which trailing full-width closing punctuation marks may trim their blank right half
679/// (`0.5 em`) to fit at the end of a line under `compressPunctuation` before
680/// `TRAILING_PUNCTUATION_TRIM_MODE`.
681#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
682pub enum TrailingTrim {
683    /// No trailing closing-mark blank-half trim.
684    #[default]
685    None,
686    /// Any full-width closing mark ([`closing_mark`]) trims its trailing blank right half.
687    Closing,
688    /// Full-width closing marks except those centered in Japanese ([`japanese_centered_mark`]).
689    NonJapaneseCentered,
690    /// Full-width closing marks except those centered in Traditional Chinese ([`centered_mark`]).
691    NonTraditionalCentered,
692}
693
694impl TrailingTrim {
695    /// Whether `ch` carries an unsplit trailing blank right half that trims at line end.
696    #[must_use]
697    pub fn trims(self, ch: char) -> bool {
698        match self {
699            Self::None => false,
700            Self::Closing => closing_mark(ch),
701            Self::NonJapaneseCentered => closing_mark(ch) && !japanese_centered_mark(ch),
702            Self::NonTraditionalCentered => closing_mark(ch) && !centered_mark(ch),
703        }
704    }
705}
706
707/// How a line with compressed punctuation chooses between shrinking the blank halves of its
708/// punctuation marks so that the next word fits and stretching its gaps without the word: it
709/// shrinks when the shrink per blank half is at most `ratio` times the stretch per gap of the line
710/// without the word (`0` on non-justified lines). Before `TRAILING_PUNCTUATION_TRIM_MODE`, a
711/// trailing closing mark matched by `trailing_trim` also gives up its own blank right half
712/// directly at line end.
713#[derive(Clone, Copy, Debug, PartialEq, Eq)]
714pub struct Compression {
715    /// How many times the stretch per gap each blank half may shrink on a justified line: a whole
716    /// multiple, or `0` on non-justified lines.
717    pub ratio: i64,
718    /// Whether the Japanese middle dot (`・`, U+30FB) also carries a blank half.
719    pub middle_dot: bool,
720    /// Which trailing closing marks trim their blank right half at line end.
721    pub trailing_trim: TrailingTrim,
722}
723
724/// The blank halves of the punctuation marks of some pieces: how many, and the advance of the
725/// widest mark. The blank half of a closing mark is its right half, that of an opening mark its
726/// left half, and in Japanese that of a middle dot its two blank quarters.
727#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
728pub struct Halves {
729    /// How many blank halves there are.
730    pub count: usize,
731    /// The advance of the widest of their marks.
732    pub em: Length,
733}
734
735impl Halves {
736    /// The blank halves among `pieces`.
737    fn of(pieces: &[Piece], include_middle_dot: bool) -> Self {
738        pieces
739            .iter()
740            .fold(Self::default(), |halves, piece| match piece {
741                Piece::Glyph(g)
742                    if !g.label
743                        && g.punctuation_half.is_open()
744                        && (closing_mark(g.ch)
745                            || opening_mark(g.ch)
746                            || (include_middle_dot && middle_dot(g.ch))) =>
747                {
748                    Self {
749                        count: halves.count + 1,
750                        em: halves.em.max(g.punctuation_half.full_em(g.advance)),
751                    }
752                }
753                _ => halves,
754            })
755    }
756
757    /// These blank halves and `other`.
758    fn and(self, other: Self) -> Self {
759        Self {
760            count: self.count + other.count,
761            em: self.em.max(other.em),
762        }
763    }
764}
765
766impl Compression {
767    /// How far a line may run past its width for the next word, when the line with the word has
768    /// the blank halves `halves`, a closing mark at its end among them, and the line without it
769    /// leaves `room` to stretch over `gaps` gaps. No half shrinks by more than its own width.
770    #[must_use]
771    pub fn over(self, halves: Halves, (room, gaps): (Length, i64)) -> Length {
772        if halves.count == 0 || gaps <= 0 || room <= Length::ZERO {
773            return Length::ZERO;
774        }
775        let count = count_factor(halves.count);
776        (room * (self.ratio * count))
777            .div_toward_zero(gaps)
778            .min((halves.em * count).div_toward_zero(2))
779    }
780}
781
782/// How many gaps each letter joint of a justified line counts as beside its spaces, in the
783/// stretch per gap that the line would need without one more word: a line whose letter joints
784/// take kashidas spreads that stretch over its joints too.
785#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
786pub struct JointGaps {
787    /// The gaps of a letter joint after a seen, sheen, sad or dad.
788    pub seen: i64,
789    /// The gaps of each other letter joint.
790    pub other: i64,
791}
792
793impl JointGaps {
794    /// The gaps that the letter joints `joints` count as.
795    #[must_use]
796    pub fn of(self, joints: JointCounts) -> i64 {
797        self.seen * count_factor(joints.seen) + self.other * count_factor(joints.other)
798    }
799}
800
801/// The limits on shrinking the spaces of a justified line: each space by a share of its width,
802/// and, to take one more word, each by a share of the stretch per gap that the line would need
803/// without that word.
804#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
805pub struct Shrink {
806    /// The share of the space width, in thousandths.
807    pub permille: i64,
808    /// The most that each space of the line may shrink to take one more word, as a share of
809    /// the stretch per gap that the line would need without that word, in thousandths. 0 sets
810    /// no such limit.
811    pub stretch_permille: i64,
812    /// How far the line may run past its width to take a word, as a share of its natural width
813    /// up to the word's end: a part and a whole. A whole of 0 sets no such limit.
814    pub natural: (i64, i64),
815    /// The gaps that the line's letter joints count as in the stretch per gap without the word;
816    /// zero where the joints count as none.
817    pub joints: JointGaps,
818}
819
820impl Shrink {
821    /// How far a line whose natural width up to a word's end is `end` may run past its width
822    /// to take the word, or `None` where the line has no limit of a share of its natural width.
823    /// The line takes the word while its width is at least the rest of the natural width, to
824    /// the nearest twip.
825    #[must_use]
826    pub fn of_natural(self, end: Length) -> Option<Length> {
827        let (part, whole) = self.natural;
828        (whole > 0).then(|| {
829            end - (end * (whole - part))
830                .div_round(whole)
831                .nearest_whole(Length::UNITS_PER_TWIP)
832        })
833    }
834
835    /// How much a space of this advance may shrink.
836    #[must_use]
837    pub fn of(self, advance: Length) -> Length {
838        (advance * self.permille).div_toward_zero(THOUSANDTHS)
839    }
840
841    /// How far a line may run over the column to take a word of `word` after spaces of
842    /// `space`, when its spaces may shrink by `spaces` in all, and it holds `count` spaces
843    /// before the word, `last` of them right before it, and the letter joints `joints`.
844    ///
845    /// When the line runs over by `over`, each of its `count` spaces shrinks by
846    /// `over / count`. Without the word, the line leaves `space + word - over` to stretch over
847    /// its `count - last` gaps and the gaps that its joints count as ([`JointGaps`]), `j`. The
848    /// word fits when the shrink is at most the share `stretch_permille` of that stretch:
849    /// `over * (count - last + j) * 1000 <= stretch_permille * count * (space + word - over)`.
850    #[must_use]
851    pub fn over(
852        self,
853        spaces: Length,
854        (space, word): (Length, Length),
855        (count, last): (usize, usize),
856        joints: JointCounts,
857    ) -> Length {
858        if self.stretch_permille == 0 || count == 0 {
859            return spaces;
860        }
861        let (count, last) = (count_factor(count), count_factor(last));
862        let gaps = count - last + self.joints.of(joints);
863        let share = self.stretch_permille * count;
864        spaces.min(((space + word) * share).div_toward_zero(THOUSANDTHS * gaps + share))
865    }
866}
867
868/// Breaks pieces into lines. A paragraph always has at least one line. The anchor marks of the
869/// pieces ([`Piece::Anchor`]) take no part in the breaks: each goes to the line that holds the
870/// piece after it, or to the last line.
871#[must_use]
872pub fn break_lines(pieces: &[Piece], frame: &Frame) -> Vec<Line> {
873    if !pieces.iter().any(|piece| matches!(piece, Piece::Anchor(_))) {
874        return break_pieces(pieces, frame);
875    }
876    let mut marks = Vec::new();
877    let mut rest = Vec::with_capacity(pieces.len());
878    for piece in pieces {
879        match piece {
880            Piece::Anchor(drawing) => marks.push((rest.len(), *drawing)),
881            other => rest.push(*other),
882        }
883    }
884    let mut lines = break_pieces(&rest, frame);
885    give_marks(&mut lines, &rest, &marks);
886    lines
887}
888
889/// Gives each anchor mark of `marks`, the index in `pieces` of the piece that it stands before
890/// and the index of its drawing, to the line of `lines`, broken from `pieces`, that holds that
891/// piece. A line holds its placed pieces, the soft hyphens that it drops between them and the
892/// break that ends it; a mark after every piece goes to the last line.
893fn give_marks(lines: &mut [Line], pieces: &[Piece], marks: &[(usize, usize)]) {
894    let mut next = 0;
895    // For each line, the index in `pieces` of each placed piece and the index after its end.
896    let mut spans: Vec<(Vec<usize>, usize)> = Vec::with_capacity(lines.len());
897    for line in lines.iter() {
898        let mut find = |found: &dyn Fn(&Piece) -> bool| {
899            while pieces.get(next).is_some_and(|piece| !found(piece)) {
900                next += 1;
901            }
902            next += 1;
903            next - 1
904        };
905        let placed = line
906            .placed
907            .iter()
908            .map(|placed| find(&|piece| same_piece(piece, &placed.piece)))
909            .collect();
910        if line.end != LineEnd::Wrap && line.end != LineEnd::Split {
911            find(&|piece| {
912                matches!(
913                    piece,
914                    Piece::LineBreak(_) | Piece::PageBreak | Piece::ColumnBreak
915                )
916            });
917        }
918        spans.push((placed, next));
919    }
920    for &(before, drawing) in marks {
921        let index = spans
922            .iter()
923            .position(|(_, end)| *end > before)
924            .unwrap_or(spans.len().saturating_sub(1));
925        let at = spans.get(index).map_or(0, |(placed, _)| {
926            placed.iter().filter(|&&at| at < before).count()
927        });
928        if let Some(line) = lines.get_mut(index) {
929            line.anchors.push(LineAnchor { at, drawing });
930        }
931    }
932}
933
934/// Whether a placed piece is the piece `piece` of the pieces that were broken: a soft hyphen
935/// or an automatic hyphenation point at the end of a wrapped line shows as a hyphen-minus.
936fn same_piece(piece: &Piece, placed: &Piece) -> bool {
937    match (piece, placed) {
938        (Piece::Glyph(glyph), Piece::Glyph(shown)) if is_hyphen_point(glyph.ch) => {
939            Glyph {
940                ch: shown.ch,
941                ..*glyph
942            } == *shown
943        }
944        _ => piece == placed,
945    }
946}
947
948/// Breaks pieces without anchor marks into lines.
949fn break_pieces(pieces: &[Piece], frame: &Frame) -> Vec<Line> {
950    let mut breaker = Breaker {
951        frame,
952        thai: ThaiText::None,
953        lines: Vec::new(),
954        line: Line::default(),
955        x: Length::ZERO,
956        shrink: Length::ZERO,
957        spaces: Length::ZERO,
958        space_count: 0,
959        stretching: false,
960        counted: Length::ZERO,
961        room: Length::ZERO,
962        blank: Halves::default(),
963        hyphen_lines: 0,
964        ends_at_point: false,
965    };
966    let mut i = 0;
967    while i < pieces.len() {
968        i = breaker.step(pieces, i);
969    }
970    // A paragraph that ends with a page break has no empty line after it. After a column
971    // break at its end, the paragraph has an empty line at the top of the next column.
972    let after_page_break = breaker
973        .lines
974        .last()
975        .is_some_and(|line| line.end == LineEnd::PageBreak);
976    if !(after_page_break && breaker.line.placed.is_empty()) {
977        settle_soft_hyphens(&mut breaker.line, false);
978        strip_trailing_auto_space(&mut breaker.line);
979        breaker.lines.push(breaker.line);
980    }
981    breaker.lines
982}
983
984struct Breaker<'a> {
985    frame: &'a Frame,
986    /// Whether the line, or the word that it tests, holds a Thai character.
987    thai: ThaiText,
988    lines: Vec<Line>,
989    line: Line,
990    x: Length,
991    /// How far the spaces placed on the line may shrink in all.
992    shrink: Length,
993    /// The width of the spaces placed on the line that a justified line stretches: those after
994    /// its last tab and after the first piece that follows it and is not a space.
995    spaces: Length,
996    /// How many such spaces are placed on the line.
997    space_count: usize,
998    /// Whether a piece that is not a space lies on the line after its last tab, or after its
999    /// start, so that the spaces placed next stretch.
1000    stretching: bool,
1001    /// What the fit test counts beside the advances of the pieces placed on the line since its
1002    /// last tab or its start ([`counted`]).
1003    counted: Length,
1004    /// How far an aligned tab stop past the line end lets the line run on.
1005    room: Length,
1006    /// The blank halves of the punctuation marks placed on the line.
1007    blank: Halves,
1008    /// How many lines in a row before this one end at an automatic hyphenation point.
1009    hyphen_lines: usize,
1010    /// Whether the line ends at an automatic hyphenation point.
1011    ends_at_point: bool,
1012}
1013
1014impl Breaker<'_> {
1015    fn step(&mut self, pieces: &[Piece], i: usize) -> usize {
1016        match pieces.get(i) {
1017            Some(Piece::LineBreak(face)) => {
1018                self.finish(LineEnd::Break(*face));
1019                i + 1
1020            }
1021            Some(Piece::PageBreak) => {
1022                self.finish(LineEnd::PageBreak);
1023                i + 1
1024            }
1025            Some(Piece::ColumnBreak) => {
1026                self.finish(LineEnd::ColumnBreak);
1027                i + 1
1028            }
1029            Some(piece @ (Piece::Tab(_) | Piece::PositionTab(..))) => {
1030                if matches!(piece, Piece::Tab(_)) && self.stop_past_end() {
1031                    self.finish(LineEnd::Wrap);
1032                }
1033                self.place_tab(*piece, pieces.get(i + 1..).unwrap_or(&[]));
1034                i + 1
1035            }
1036            Some(
1037                piece @ (Piece::Note(_)
1038                | Piece::Endnote(_)
1039                | Piece::NoteMarkEnd
1040                | Piece::EndnoteMarkEnd(_)
1041                | Piece::Comment(_)
1042                | Piece::Strut(_)
1043                | Piece::Clear),
1044            ) => {
1045                self.push(*piece, Length::ZERO);
1046                i + 1
1047            }
1048            Some(
1049                Piece::Glyph(_)
1050                | Piece::Shift(_)
1051                | Piece::Advance(_)
1052                | Piece::Bar { .. }
1053                | Piece::Vinculum { .. }
1054                | Piece::Diagonal { .. }
1055                | Piece::Object { .. }
1056                | Piece::Rule { .. }
1057                | Piece::CheckBox { .. },
1058            ) => self.place_word(pieces, i),
1059            // `break_lines` has taken the anchor marks out.
1060            Some(Piece::Anchor(_)) | None => i + 1,
1061        }
1062    }
1063
1064    fn finish(&mut self, end: LineEnd) {
1065        let mut line = std::mem::take(&mut self.line);
1066        settle_soft_hyphens(&mut line, false);
1067        strip_trailing_auto_space(&mut line);
1068        line.end = end;
1069        self.lines.push(line);
1070        self.x = Length::ZERO;
1071        self.thai = ThaiText::None;
1072        self.shrink = Length::ZERO;
1073        self.spaces = Length::ZERO;
1074        self.space_count = 0;
1075        self.stretching = false;
1076        self.counted = Length::ZERO;
1077        self.room = Length::ZERO;
1078        self.blank = Halves::default();
1079        self.hyphen_lines = if std::mem::take(&mut self.ends_at_point) {
1080            self.hyphen_lines + 1
1081        } else {
1082            0
1083        };
1084    }
1085
1086    fn width(&self) -> Length {
1087        if self.on_first_line() {
1088            self.frame.first_width
1089        } else {
1090            self.frame.width
1091        }
1092    }
1093
1094    fn start(&self) -> Length {
1095        if self.on_first_line() {
1096            self.frame.first_start
1097        } else {
1098            self.frame.start
1099        }
1100    }
1101
1102    /// Whether the line that the breaker fills is the paragraph's first: the first line of all,
1103    /// or, where the frame starts the first line after leading page breaks
1104    /// ([`LineBreaking::leading_breaks`]), the line after the first of them or after all of
1105    /// them.
1106    fn on_first_line(&self) -> bool {
1107        let before = self
1108            .frame
1109            .breaking
1110            .leading_breaks
1111            .before_first_line(self.lines.len());
1112        self.lines.len() == before && self.lines.iter().all(Line::holds_only_page_break)
1113    }
1114
1115    /// Whether a tab here would move from inside the line to a stop past its end, on a line
1116    /// that holds something: a default stop, or a custom left stop, not the hanging indent,
1117    /// where the frame's [`LineBreaking::left_stops_to_line_end`] says so. Such a tab starts the next line, and so does a tab after
1118    /// spaces that have run past the end. A line that already runs past its end, after a custom
1119    /// stop there, keeps its tabs.
1120    fn stop_past_end(&self) -> bool {
1121        let absolute = self.start() + self.x;
1122        let end = self.start() + self.width();
1123        let (stop, default) = self.frame.tabs.next_stop(absolute);
1124        let past = if absolute <= end {
1125            stop.position > end
1126        } else {
1127            self.room == Length::ZERO
1128        };
1129        let moves = default || self.left_stop_to_line_end(stop);
1130        moves && !self.line.placed.is_empty() && past
1131    }
1132
1133    /// The stop that a tab goes to: `stop`, or, for a tab to a custom left stop past the line's
1134    /// end that the frame's [`LineBreaking::left_stops_to_line_end`] sends to the line's end, a stop of the same kind
1135    /// and leader at the line's end.
1136    fn stop_or_line_end(&self, piece: &Piece, stop: TabStop, end: Length) -> TabStop {
1137        if matches!(piece, Piece::Tab(_)) && stop.position > end && self.left_stop_to_line_end(stop)
1138        {
1139            TabStop {
1140                position: end,
1141                ..stop
1142            }
1143        } else {
1144            stop
1145        }
1146    }
1147
1148    /// Whether `stop` is a custom left stop, not the hanging indent, that the frame's
1149    /// [`LineBreaking::left_stops_to_line_end`] sends to the line's end when it lies past it.
1150    fn left_stop_to_line_end(&self, stop: TabStop) -> bool {
1151        // quirk: LeftStopPastEnd (src/quirks.rs)
1152        stop.kind == TabKind::Left
1153            && self.frame.tabs.is_custom(stop)
1154            && self.frame.breaking.left_stops_to_line_end
1155    }
1156
1157    fn place_tab(&mut self, piece: Piece, after: &[Piece]) {
1158        let absolute = self.start() + self.x;
1159        // A positional tab goes to its own stop, whatever the tab stops of the paragraph.
1160        let stop = match piece {
1161            Piece::PositionTab(_, stop) => stop,
1162            _ => self.frame.tabs.next(absolute),
1163        };
1164        let end = self.start() + self.width();
1165        let stop = self.stop_or_line_end(&piece, stop, end);
1166        let gap = stop.position - absolute;
1167        // The line may run on up to a stop that lies past its end, which lets the text after a
1168        // right, center or decimal stop line up there.
1169        self.room = self.room.max(stop.position - end);
1170        let at_stop = match stop.kind {
1171            TabKind::Right => gap - following_width(after, None),
1172            TabKind::Center => gap - following_width(after, None).div_toward_zero(2),
1173            TabKind::Decimal => gap - following_width(after, Some('.')),
1174            TabKind::Left => gap,
1175        };
1176        // quirk: AlignedTabOverrun (src/quirks.rs)
1177        let advance = match stop.kind {
1178            TabKind::Right | TabKind::Center | TabKind::Decimal
1179                if self.frame.breaking.ends_aligned_text =>
1180            {
1181                // Text that would end past its limit from its stop, wherever the stop lies,
1182                // ends there instead, but never starts left of the tab. The limit is the end
1183                // of the text area for a stop past the line's end and inside the area, which
1184                // a right indent leaves between the two, and the line's end otherwise; the
1185                // line runs on to where the text ends, and never past the limit.
1186                let width = following_width(after, None);
1187                if stop.position >= end && !self.frame.limits_past_end {
1188                    let advance = at_stop.max(Length::ZERO);
1189                    self.room = self.room.max(absolute + advance + width - end);
1190                    advance
1191                } else {
1192                    let limit = if stop.position > end && stop.position <= self.frame.area_width {
1193                        self.frame.area_width
1194                    } else {
1195                        end
1196                    };
1197                    let advance = at_stop.min(limit - absolute - width).max(Length::ZERO);
1198                    self.room = self.room.max((absolute + advance + width).min(limit) - end);
1199                    advance
1200                }
1201            }
1202            _ => at_stop,
1203        };
1204        self.push(piece, advance.max(Length::ZERO));
1205        if let Some(placed) = self.line.placed.last_mut() {
1206            placed.leader = stop.leader;
1207            placed.tab = Some(stop.kind);
1208        }
1209    }
1210
1211    fn place_word(&mut self, pieces: &[Piece], i: usize) -> usize {
1212        let end = word_end(pieces, i, self.frame);
1213        let word = pieces.get(i..end).unwrap_or(&[]);
1214        let (_, visible) = widths(word);
1215        let ends = self.fitted_end_spaces(word, pieces.get(end));
1216        let visible = visible + ends.width;
1217        if self.thai != ThaiText::OnLine {
1218            self.thai = if word.iter().any(is_thai) {
1219                ThaiText::InWord
1220            } else {
1221                ThaiText::None
1222            };
1223        }
1224        let fit = self.fit_ending(visible, self.punctuation_over(word), ends);
1225        // Spaces that follow a word stay on its line, even one that runs past its width
1226        // because its spaces shrink, so that no wrapped line starts with them.
1227        let room = self
1228            .shrink
1229            .max(self.frame.shrink.of_natural(self.x).unwrap_or(Length::ZERO));
1230        let spaces = !self.line.hung && word.iter().all(is_space) && self.x <= self.width() + room;
1231        let overflows = self.line.hung || fit.end > fit.width + fit.over;
1232        if overflows && !spaces && self.place_hanging_word(word, visible) {
1233            return end;
1234        }
1235        if overflows
1236            && !spaces
1237            && !self.line.hung
1238            && let Some(point) = self.hyphen_point(word)
1239        {
1240            return i + self.place_to_point(word, point, fit);
1241        }
1242        if overflows && !self.line.placed.is_empty() && !spaces {
1243            // The tab immediately before a word that does not fit goes to the next line with it,
1244            // leaving earlier pieces (including earlier tabs) on this line.
1245            let tab = self.take_trailing_tab();
1246            settle_soft_hyphens(&mut self.line, tab.is_none());
1247            self.line.wrapped = Some(fit);
1248            // A word after a tab that goes to the next line with it is left out: the line's end
1249            // is no longer the word's start.
1250            self.line.would_hang = !self.line.hung && tab.is_none() && self.fits_before_hang(word);
1251            self.finish(LineEnd::Wrap);
1252            if let Some(tab) = tab {
1253                self.place_tab(tab, pieces.get(i..).unwrap_or(&[]));
1254            }
1255        }
1256        if self.x + visible > self.width() + self.trailing_trim_over(word)
1257            && self.line.placed.is_empty()
1258        {
1259            return i + self.place_split(word);
1260        }
1261        self.line.kept = Some(self.fit(visible));
1262        for piece in word {
1263            self.push(*piece, advance(piece));
1264        }
1265        end
1266    }
1267
1268    /// The spaces at the end of `word` that count in its fit ([`Frame::end_space_fit`]).
1269    fn fitted_end_spaces(&self, word: &[Piece], next: Option<&Piece>) -> EndSpaces {
1270        if self.frame.end_space_fit == EndSpaceFit::WithoutSpaces
1271            || !self.line.holds_left_to_right_text()
1272        {
1273            return EndSpaces::default();
1274        }
1275        let Some(last) = word.iter().rposition(|piece| !is_space(piece)) else {
1276            return EndSpaces::default();
1277        };
1278        let letter = |piece: Option<&Piece>| {
1279            piece
1280                .and_then(run_glyph)
1281                .is_some_and(|glyph| right_to_left(glyph.ch))
1282        };
1283        let between = self.frame.end_space_fit.between_letters(&self.line)
1284            && letter(word.get(last))
1285            && letter(next);
1286        let start = EndSpaces {
1287            starts_right_to_left: letter(word.first()),
1288            ..EndSpaces::default()
1289        };
1290        word.iter()
1291            .skip(last + 1)
1292            .take_while(|piece| is_space(piece) && (between || run_rtl(piece) == Some(true)))
1293            .fold(start, |ends, piece| EndSpaces {
1294                width: ends.width + advance(piece) + counted(piece),
1295                count: ends.count + 1,
1296                shrink: ends.shrink + self.frame.shrink.of(advance(piece)),
1297                ..ends
1298            })
1299    }
1300
1301    /// The index in `word`, which does not fit, of its last automatic hyphenation point whose
1302    /// part, with the hyphen, fits on the line, where the line may end at a point: after fewer
1303    /// lines in a row that end at a point than the limit, and where the zone holds, when the
1304    /// room that the line leaves for the word is wider than the zone.
1305    fn hyphen_point(&self, word: &[Piece]) -> Option<usize> {
1306        let rules = self.frame.hyphenation?;
1307        if rules
1308            .limit
1309            .is_some_and(|limit| self.hyphen_lines >= limit.get())
1310        {
1311            return None;
1312        }
1313        if rules.zone.is_some_and(|zone| self.width() - self.x <= zone) {
1314            return None;
1315        }
1316        (0..word.len()).rev().find(|&k| {
1317            let Some(part) = word.get(..=k).filter(
1318                |part| matches!(part.last(), Some(Piece::Glyph(g)) if g.ch == AUTOMATIC_HYPHEN),
1319            ) else {
1320                return false;
1321            };
1322            let (_, visible) = widths(part);
1323            let fit = self.fit_with(visible, self.punctuation_over(part));
1324            fit.end <= fit.width + fit.over
1325        })
1326    }
1327
1328    /// Places the part of `word` up to its automatic hyphenation point at `point`, which shows
1329    /// a hyphen, and ends the line there. Returns the count of pieces placed. `wrapped` is the
1330    /// decision that the whole word did not fit.
1331    fn place_to_point(&mut self, word: &[Piece], point: usize, wrapped: Fit) -> usize {
1332        let part = word.get(..=point).unwrap_or(&[]);
1333        let (_, visible) = widths(part);
1334        self.line.kept = Some(self.fit_with(visible, self.punctuation_over(part)));
1335        for piece in part {
1336            self.push(*piece, advance(piece));
1337        }
1338        settle_soft_hyphens(&mut self.line, true);
1339        self.line.wrapped = Some(wrapped);
1340        self.ends_at_point = true;
1341        self.finish(LineEnd::Wrap);
1342        part.len()
1343    }
1344
1345    /// Keeps `word` on the current line with its trailing mark hanging past the right margin when
1346    /// hanging punctuation is enabled (`OverflowPunct::Hang`), the line is not already hung, no
1347    /// trailing tab sits right before `word`, and the pieces before the mark fit without shrinking
1348    /// spaces.
1349    fn place_hanging_word(&mut self, word: &[Piece], visible: Length) -> bool {
1350        if self.frame.overflow_punct != OverflowPunct::Hang
1351            || self.line.hung
1352            || self.has_trailing_tab()
1353            || !self.fits_before_hang(word)
1354        {
1355            return false;
1356        }
1357        self.line.kept = Some(self.fit(visible));
1358        for piece in word {
1359            self.push(*piece, advance(piece));
1360        }
1361        self.line.hung = true;
1362        true
1363    }
1364
1365    /// The pieces of `word` before a trailing mark matched by `Kinsoku::hangs`, or `None`.
1366    /// Checks the mark glyph's own run `w:lang w:eastAsia` when present (so an explicit
1367    /// non-East-Asian run language disables hanging, and an explicit East Asian run language
1368    /// activates its script's hanging set under `OverflowPunct::Hang`).
1369    fn hanging_prefix<'w>(&self, word: &'w [Piece]) -> Option<&'w [Piece]> {
1370        if self.frame.overflow_punct == OverflowPunct::Off {
1371            return None;
1372        }
1373        let last = word.iter().rposition(|piece| !is_space(piece))?;
1374        let (Some(Piece::Glyph(mark)), Some(rest)) = (word.get(last), word.get(..last)) else {
1375            return None;
1376        };
1377        let hangs = match (self.frame.overflow_punct, mark.east_asian_language) {
1378            (_, Some(EastAsianLanguage::NonEastAsian)) => false,
1379            (OverflowPunct::Hang, Some(EastAsianLanguage::Script(script))) => {
1380                Kinsoku::of(script).hangs(mark.ch)
1381            }
1382            _ => self.frame.kinsoku.is_some_and(|k| k.hangs(mark.ch)),
1383        };
1384        hangs.then_some(rest)
1385    }
1386
1387    /// Whether `word` ends with a hanging punctuation mark and its preceding pieces fit within
1388    /// the line's width, tab room, space shrink, and punctuation compression.
1389    fn fits_before_hang(&self, word: &[Piece]) -> bool {
1390        let Some(rest) = self.hanging_prefix(word) else {
1391            return false;
1392        };
1393        let (_, visible) = widths(rest);
1394        let fit = self.fit_with(visible, self.punctuation_over(rest));
1395        fit.end <= fit.width + fit.over
1396    }
1397
1398    /// Whether a trailing tab sits at the end of the line after at least one earlier piece.
1399    fn has_trailing_tab(&self) -> bool {
1400        self.line.placed.len() >= 2
1401            && matches!(
1402                self.line.placed.last().map(|p| &p.piece),
1403                Some(Piece::Tab(_) | Piece::PositionTab(..))
1404            )
1405    }
1406
1407    /// The numbers of the decision whether a word of visible width `word` fits after the
1408    /// pieces placed so far.
1409    fn fit(&self, word: Length) -> Fit {
1410        self.fit_with(word, Length::ZERO)
1411    }
1412
1413    /// How far the line may run past its width for `word` because a trailing full-width closing
1414    /// mark gives up its blank right half at line end.
1415    fn trailing_trim_over(&self, word: &[Piece]) -> Length {
1416        self.frame
1417            .punctuation
1418            .and_then(|c| trailing_closing_half(word, c.trailing_trim))
1419            .map_or(Length::ZERO, |(_, half)| half)
1420    }
1421
1422    /// How far the line may run past its width for `word` because its punctuation, `word`'s
1423    /// own included, shrinks.
1424    fn punctuation_over(&self, word: &[Piece]) -> Length {
1425        let Some(compression) = self.frame.punctuation else {
1426            return Length::ZERO;
1427        };
1428        let (rest, trimmed) = match trailing_closing_half(word, compression.trailing_trim) {
1429            Some((last, half)) => (word.get(..last).unwrap_or(&[]), half),
1430            None => (word, Length::ZERO),
1431        };
1432        let inner = compression.over(
1433            self.blank.and(Halves::of(rest, compression.middle_dot)),
1434            self.stretch(),
1435        );
1436        trimmed + inner
1437    }
1438
1439    /// The room that the line leaves when it ends here, and the gaps that it stretches over:
1440    /// its spaces after the last tab, or the full-width-adjacent glyph gaps after the last tab
1441    /// when it has no spaces.
1442    fn stretch(&self) -> (Length, i64) {
1443        let first = self.line.first_stretched();
1444        let placed = self.line.placed.get(first..).unwrap_or(&[]);
1445        let spaces =
1446            i64::try_from(placed.iter().filter(|p| is_space(&p.piece)).count()).unwrap_or(0);
1447        let gaps = if spaces > 0 {
1448            spaces
1449        } else {
1450            let full_width = |p: &Placed| matches!(p.piece, Piece::Glyph(g) if CharacterClass::FullWidthCell.contains(g.ch));
1451            let labeled = |p: &Placed| matches!(p.piece, Piece::Glyph(g) if g.label);
1452            i64::try_from(
1453                placed
1454                    .windows(2)
1455                    .filter(|pair| {
1456                        let (Some(a), Some(b)) = (pair.first(), pair.get(1)) else {
1457                            return false;
1458                        };
1459                        !labeled(a) && !labeled(b) && (full_width(a) || full_width(b))
1460                    })
1461                    .count(),
1462            )
1463            .unwrap_or(0)
1464        };
1465        let end_gap = match self.line.placed.last().map(|p| &p.piece) {
1466            Some(Piece::Glyph(g)) => g.trailing_auto_space,
1467            _ => Length::ZERO,
1468        };
1469        (self.width() - (self.x - end_gap), gaps)
1470    }
1471
1472    /// [`Breaker::fit`] for a word whose line may run `punctuation` past its width because
1473    /// its punctuation shrinks.
1474    fn fit_with(&self, word: Length, punctuation: Length) -> Fit {
1475        self.fit_ending(word, punctuation, EndSpaces::default())
1476    }
1477
1478    /// [`Breaker::fit_with`] for a word whose fit counts the spaces `ends` at its end.
1479    fn fit_ending(&self, word: Length, punctuation: Length, ends: EndSpaces) -> Fit {
1480        // A word holds no space before its end, so only the spaces placed so far may shrink,
1481        // and the spaces right before it only when they stretch. The space of an operator
1482        // right before a term of an equation hangs where the line would end without the term,
1483        // so it counts in the room that the line leaves then, but as no space of the line.
1484        let last: Vec<&Placed> = self
1485            .line
1486            .placed
1487            .iter()
1488            .rev()
1489            .take_while(|p| self.stretching && (is_space(&p.piece) || is_operator_space(&p.piece)))
1490            .collect();
1491        let space: Length = last.iter().map(|p| p.advance).sum();
1492        let last_space_count = last.iter().filter(|p| is_space(&p.piece)).count();
1493        let end = self.x + self.counted + word;
1494        let kept = self.frame.thai_keeps_spaces && self.thai != ThaiText::None;
1495        let over = if kept {
1496            Length::ZERO
1497        } else {
1498            self.frame
1499                .shrink
1500                .of_natural(end)
1501                .unwrap_or_else(|| self.shrink_over(&last, (space, word), last_space_count, ends))
1502        };
1503        Fit {
1504            width: self.width(),
1505            end,
1506            word,
1507            spaces: self.spaces,
1508            space,
1509            space_count: self.space_count,
1510            last_space_count,
1511            room: self.room,
1512            over: over + self.room + punctuation,
1513            shrinks: !kept && (self.frame.shrink.permille > 0 || self.frame.shrink.natural.1 > 0),
1514        }
1515    }
1516
1517    /// How far the line may run past its width because its spaces shrink ([`Shrink::over`]),
1518    /// for `word` after the spaces `last`, `last_count` of them spaces of width `space`, with
1519    /// the spaces `ends` at its end that count in its fit. Where the line counts right-to-left
1520    /// spaces beside text of a run without `w:rtl` ([`EndSpaceFit::WithRightToLeftSpaces`]),
1521    /// they are spaces of the line: those at the word's end shrink as its other spaces, and
1522    /// those right before the word, of runs with `w:rtl` or between right-to-left letters, stay
1523    /// written text of the line without the word, so that they leave it no room and are among
1524    /// its gaps.
1525    fn shrink_over(
1526        &self,
1527        last: &[&Placed],
1528        (space, word): (Length, Length),
1529        last_count: usize,
1530        ends: EndSpaces,
1531    ) -> Length {
1532        let rtl_before = last.iter().all(|p| run_rtl(&p.piece) == Some(true));
1533        let letters_before = self.frame.end_space_fit.between_letters(&self.line)
1534            && ends.starts_right_to_left
1535            && self
1536                .line
1537                .placed
1538                .iter()
1539                .rev()
1540                .find(|p| !is_space(&p.piece))
1541                .and_then(|p| run_glyph(&p.piece))
1542                .is_some_and(|glyph| right_to_left(glyph.ch));
1543        let kept_before = self.frame.end_space_fit != EndSpaceFit::WithoutSpaces
1544            && (rtl_before || letters_before)
1545            && !last.is_empty()
1546            && self.line.holds_left_to_right_text();
1547        let (space, hanging) = if kept_before {
1548            (Length::ZERO, 0)
1549        } else {
1550            (space, last_count)
1551        };
1552        let joints = if self.frame.shrink.joints == JointGaps::default() {
1553            JointCounts::default()
1554        } else {
1555            joints::joint_counts(&self.line.placed)
1556        };
1557        self.frame.shrink.over(
1558            self.shrink + ends.shrink,
1559            (space, word),
1560            (self.space_count + ends.count, hanging + ends.count),
1561            joints,
1562        )
1563    }
1564
1565    /// Removes the last tab at the end of the line when at least one piece stays before it.
1566    fn take_trailing_tab(&mut self) -> Option<Piece> {
1567        if self.line.placed.len() >= 2
1568            && matches!(
1569                self.line.placed.last().map(|p| &p.piece),
1570                Some(Piece::Tab(_) | Piece::PositionTab(..))
1571            )
1572        {
1573            let tab = self.line.placed.pop()?;
1574            self.x = tab.x;
1575            Some(tab.piece)
1576        } else {
1577            None
1578        }
1579    }
1580
1581    /// Places as many glyphs of an overlong word as fit, and at least one. The line ends when
1582    /// the rest of the word goes to the next line. A word that is placed whole, such as one
1583    /// inline picture wider than the line, keeps the line open, so that a paragraph that ends
1584    /// there gets no empty line after it.
1585    fn place_split(&mut self, word: &[Piece]) -> usize {
1586        let mut placed = 0;
1587        for piece in word {
1588            let a = advance(piece);
1589            let end_gap = match piece {
1590                Piece::Glyph(g) => g.trailing_auto_space,
1591                _ => Length::ZERO,
1592            };
1593            if placed > 0 && self.x + self.counted + a - end_gap + counted(piece) > self.width() {
1594                break;
1595            }
1596            self.push(*piece, a);
1597            placed += 1;
1598        }
1599        if placed < word.len() {
1600            self.finish(LineEnd::Split);
1601        }
1602        placed
1603    }
1604
1605    fn push(&mut self, piece: Piece, advance: Length) {
1606        self.line.placed.push(Placed {
1607            piece,
1608            x: self.x,
1609            advance,
1610            leader: None,
1611            tab: None,
1612        });
1613        self.x += advance;
1614        if is_thai(&piece) {
1615            self.thai = ThaiText::OnLine;
1616        }
1617        // Only the spaces and punctuation that a justified line stretches may shrink: a tab starts
1618        // the count again, and spaces count from the first piece after it that is not a space.
1619        if matches!(piece, Piece::Tab(_) | Piece::PositionTab(..)) {
1620            self.shrink = Length::ZERO;
1621            self.spaces = Length::ZERO;
1622            self.space_count = 0;
1623            self.stretching = false;
1624            self.counted = Length::ZERO;
1625            self.blank = Halves::default();
1626        } else if !is_space(&piece) {
1627            self.stretching = true;
1628        } else if self.stretching {
1629            self.shrink += self.frame.shrink.of(advance);
1630            self.spaces += advance;
1631            self.space_count += 1;
1632        }
1633        self.counted += counted(&piece);
1634        let include_middle_dot = self.frame.punctuation.is_some_and(|c| c.middle_dot);
1635        self.blank = self.blank.and(Halves::of(&[piece], include_middle_dot));
1636    }
1637}
1638
1639/// The end of the word that starts at `i`: its other glyphs, then the spaces after it. A word
1640/// also ends after a hyphen-minus, U+2010 HYPHEN, an en dash or an em dash, and after the space
1641/// of an operator where an equation may break ([`SpaceKind::Operator`]), when no more of that
1642/// space follows.
1643fn word_end(pieces: &[Piece], i: usize, frame: &Frame) -> usize {
1644    let mut j = i;
1645    loop {
1646        match pieces.get(j) {
1647            Some(Piece::Glyph(g))
1648                if g.ch != ' ' || matches!(g.space, SpaceKind::Equation | SpaceKind::Assembly) =>
1649            {
1650                j += 1;
1651                if (g.space == SpaceKind::Operator && !pieces.get(j).is_some_and(is_operator_space))
1652                    || ends_word_after(g, pieces.get(j), frame.kinsoku)
1653                {
1654                    return j;
1655                }
1656            }
1657            // The parts of a stacked fraction stay on one line, and a note's own mark with the
1658            // text after it.
1659            Some(
1660                Piece::Shift(_)
1661                | Piece::Bar { .. }
1662                | Piece::Vinculum { .. }
1663                | Piece::Diagonal { .. }
1664                | Piece::Endnote(_)
1665                | Piece::NoteMarkEnd
1666                | Piece::EndnoteMarkEnd(_),
1667            ) => j += 1,
1668            // A single inline VML vector shape attaches to the word before it and allows a break
1669            // after it.
1670            Some(
1671                Piece::Object {
1672                    joins_before: true, ..
1673                }
1674                | Piece::Advance(_),
1675            ) => return j + 1,
1676            // A footnote reference's mark is text of its word, where the quirk says so: the
1677            // word goes on after it unless its last glyph and the next piece allow a break.
1678            // quirk: NoteReferenceBreak (src/quirks.rs)
1679            Some(Piece::Note(_)) if frame.breaking.note_reference_in_word => {
1680                j += 1;
1681                let before = j.checked_sub(2).and_then(|k| pieces.get(k));
1682                if let Some(Piece::Glyph(g)) = before
1683                    && ends_word_after(g, pieces.get(j), frame.kinsoku)
1684                {
1685                    return j;
1686                }
1687            }
1688            // A joined space run keeps the word after it on the line of this one.
1689            Some(_) if frame.joined_spaces && joins(pieces, (i, j)) => j = spaces_end(pieces, j),
1690            _ => break,
1691        }
1692    }
1693    spaces_end(pieces, j).max(i + 1)
1694}
1695
1696/// The width of the widest word of `pieces` without its trailing spaces, with the words that
1697/// the line breaks of `frame` find: the narrowest line that holds each word whole.
1698#[must_use]
1699pub(crate) fn widest_word(pieces: &[Piece], frame: &Frame) -> Length {
1700    let mut widest = Length::ZERO;
1701    let mut start = 0;
1702    while start < pieces.len() {
1703        let end = word_end(pieces, start, frame);
1704        widest = widest.max(widths(pieces.get(start..end).unwrap_or_default()).1);
1705        start = end;
1706    }
1707    widest
1708}
1709
1710/// The end of the spaces that start at `j`.
1711fn spaces_end(pieces: &[Piece], mut j: usize) -> usize {
1712    while matches!(pieces.get(j), Some(p) if is_space(p)) {
1713        j += 1;
1714    }
1715    j
1716}
1717
1718/// Whether the spaces at `j`, of the word that starts at `i`, belong to a joined space run:
1719/// the glyph of the word before them or the first glyph after them is a no-break space.
1720fn joins(pieces: &[Piece], (i, j): (usize, usize)) -> bool {
1721    let no_break =
1722        |piece: Option<&Piece>| matches!(piece, Some(Piece::Glyph(g)) if g.ch == NO_BREAK_SPACE);
1723    let before = j > i && no_break(j.checked_sub(1).and_then(|k| pieces.get(k)));
1724    pieces.get(j).is_some_and(is_space) && (before || no_break(pieces.get(spaces_end(pieces, j))))
1725}
1726
1727/// Whether a word ends after a glyph: after a hyphen or a dash, or where East Asian text
1728/// may break before the next piece.
1729fn ends_word_after(before: &Glyph, next: Option<&Piece>, kinsoku: Option<Kinsoku>) -> bool {
1730    if matches!(
1731        before.ch,
1732        '-' | '\u{2010}' | '\u{2013}' | '\u{2014}' | SOFT_HYPHEN
1733    ) {
1734        return true;
1735    }
1736    let Some(Piece::Glyph(next)) = next else {
1737        return false;
1738    };
1739    if next.ch == ' ' {
1740        return false;
1741    }
1742    let kinsoku = kinsoku.map(|k| k.for_pair(before.east_asian_language, next.east_asian_language));
1743    breaks_between(before.ch, next.ch, kinsoku)
1744}
1745
1746/// Whether a character is a place where a word may break with a hyphen that shows only at the
1747/// end of a line: a soft hyphen or an automatic hyphenation point.
1748const fn is_hyphen_point(ch: char) -> bool {
1749    matches!(ch, SOFT_HYPHEN | AUTOMATIC_HYPHEN)
1750}
1751
1752/// The full width and the width without trailing spaces, each with what the fit test counts
1753/// beside the advances ([`counted`]). The space of an operator where an equation may break
1754/// trails as a space does. A word that ends with a soft hyphen or an automatic
1755/// hyphenation point needs the hyphen's width as well, for the line may end there.
1756fn widths(word: &[Piece]) -> (Length, Length) {
1757    let total: Length = word.iter().map(|p| advance(p) + counted(p)).sum();
1758    let trailing: Length = word
1759        .iter()
1760        .rev()
1761        .take_while(|p| is_space(p) || is_operator_space(p))
1762        .map(|p| advance(p) + counted(p))
1763        .sum();
1764    let last_auto_space = match word.last() {
1765        Some(Piece::Glyph(g)) => g.trailing_auto_space,
1766        _ => Length::ZERO,
1767    };
1768    let hyphen = match word.last() {
1769        Some(Piece::Glyph(g)) if is_hyphen_point(g.ch) => g.advance,
1770        _ => Length::ZERO,
1771    };
1772    (total, total - trailing - last_auto_space + hyphen)
1773}
1774
1775/// Drops any East Asian / Latin or digit auto-space (`w:autoSpaceDE` / `w:autoSpaceDN`) from the
1776/// last placed glyph of a finished line, since the following character moved to the next line.
1777fn strip_trailing_auto_space(line: &mut Line) {
1778    if let Some(last) = line.placed.last_mut()
1779        && let Piece::Glyph(g) = &mut last.piece
1780        && g.trailing_auto_space > Length::ZERO
1781    {
1782        let gap = g.trailing_auto_space;
1783        g.advance -= gap;
1784        last.advance -= gap;
1785        if g.auto_space > Length::ZERO {
1786            g.auto_space = (g.auto_space - gap).max(Length::ZERO);
1787        }
1788        g.trailing_auto_space = Length::ZERO;
1789    }
1790}
1791
1792/// Shows a soft hyphen at the end of a line as a hyphen-minus with its width, and an automatic
1793/// hyphenation point there as [`LINE_END_HYPHEN`], and records which the line shows; and drops
1794/// those inside the line, which show nothing.
1795fn settle_soft_hyphens(line: &mut Line, wrapped: bool) {
1796    if wrapped
1797        && let Some(last) = line.placed.last_mut()
1798        && let Piece::Glyph(g) = &mut last.piece
1799        && is_hyphen_point(g.ch)
1800    {
1801        let hyphen = if g.ch == AUTOMATIC_HYPHEN {
1802            g.ch = LINE_END_HYPHEN;
1803            EndHyphen::Automatic
1804        } else {
1805            g.ch = '-';
1806            EndHyphen::Soft
1807        };
1808        last.advance = g.advance;
1809        line.hyphen = Some(hyphen);
1810    }
1811    line.placed
1812        .retain(|p| !matches!(p.piece, Piece::Glyph(g) if is_hyphen_point(g.ch)));
1813}
1814
1815/// The width of the text and inline objects after a tab, up to the next tab or break and without
1816/// trailing spaces, with what the fit test counts beside the advances ([`counted`]). With a
1817/// decimal character, the width stops before its first occurrence.
1818pub(crate) fn following_width(after: &[Piece], decimal: Option<char>) -> Length {
1819    let mut total = Length::ZERO;
1820    let mut visible = Length::ZERO;
1821    for piece in after {
1822        match piece {
1823            Piece::Glyph(glyph) => {
1824                if Some(glyph.ch) == decimal {
1825                    return total;
1826                }
1827                total += glyph.advance + glyph.counted;
1828                if glyph.ch != ' ' {
1829                    visible = total;
1830                }
1831            }
1832            Piece::Object { width, .. } => {
1833                total += *width;
1834                visible = total;
1835            }
1836            _ => break,
1837        }
1838    }
1839    if decimal.is_some() { total } else { visible }
1840}
1841
1842/// What the fit test counts beside the advance of `piece`: a glyph's [`Glyph::counted`], and
1843/// nothing for a hyphenation point or another piece.
1844const fn counted(piece: &Piece) -> Length {
1845    match piece {
1846        Piece::Glyph(g) if !is_hyphen_point(g.ch) => g.counted,
1847        _ => Length::ZERO,
1848    }
1849}
1850
1851pub(crate) const fn advance(piece: &Piece) -> Length {
1852    match piece {
1853        Piece::Glyph(g) if is_hyphen_point(g.ch) => Length::ZERO,
1854        Piece::Glyph(g) => g.advance,
1855        Piece::Shift(length) | Piece::Advance(length) => *length,
1856        Piece::Object { width, .. } | Piece::Rule { width, .. } | Piece::CheckBox { width, .. } => {
1857            *width
1858        }
1859        Piece::Bar { .. }
1860        | Piece::Vinculum { .. }
1861        | Piece::Diagonal { .. }
1862        | Piece::Tab(_)
1863        | Piece::PositionTab(..)
1864        | Piece::LineBreak(_)
1865        | Piece::PageBreak
1866        | Piece::ColumnBreak
1867        | Piece::Note(_)
1868        | Piece::Endnote(_)
1869        | Piece::NoteMarkEnd
1870        | Piece::EndnoteMarkEnd(_)
1871        | Piece::Comment(_)
1872        | Piece::Anchor(_)
1873        | Piece::Strut(_)
1874        | Piece::Clear => Length::ZERO,
1875    }
1876}
1877
1878/// If `word`'s last non-space piece is a full-width closing mark matched by `trim`, returns its
1879/// index in `word` and its blank right half (`advance / 2`).
1880fn trailing_closing_half(word: &[Piece], trim: TrailingTrim) -> Option<(usize, Length)> {
1881    if trim == TrailingTrim::None {
1882        return None;
1883    }
1884    let last = word.iter().rposition(|piece| !is_space(piece))?;
1885    match word.get(last) {
1886        Some(Piece::Glyph(mark)) if mark.punctuation_half.is_open() && trim.trims(mark.ch) => {
1887            Some((
1888                last,
1889                mark.punctuation_half
1890                    .full_em(mark.advance)
1891                    .div_toward_zero(2),
1892            ))
1893        }
1894        _ => None,
1895    }
1896}
1897
1898/// Whether a character is a full-width punctuation mark whose right half is blank, such as a
1899/// closing bracket or an ideographic comma.
1900#[must_use]
1901pub fn closing_mark(ch: char) -> bool {
1902    matches!(
1903        ch,
1904        '\u{3001}'
1905            | '\u{3002}'
1906            | '\u{FF0C}'
1907            | '\u{FF0E}'
1908            | '\u{FF1A}'
1909            | '\u{FF1B}'
1910            | '\u{FF01}'
1911            | '\u{300D}'
1912            | '\u{300F}'
1913            | '\u{FF09}'
1914            | '\u{3011}'
1915            | '\u{3015}'
1916            | '\u{3009}'
1917            | '\u{300B}'
1918            | '\u{FF5D}'
1919            | '\u{FF3D}'
1920    )
1921}
1922
1923/// Whether a character is a full-width punctuation mark that Traditional Chinese places in the
1924/// middle of its em, with a blank quarter on each side: the comma, the enumeration comma, the
1925/// full stop, the semicolon and the colon. Other scripts place them at the left of the em.
1926#[must_use]
1927pub const fn centered_mark(ch: char) -> bool {
1928    matches!(
1929        ch,
1930        '\u{FF0C}' | '\u{3001}' | '\u{3002}' | '\u{FF1B}' | '\u{FF1A}'
1931    )
1932}
1933
1934/// Whether a character is a full-width punctuation mark that Japanese places in the middle of its
1935/// em, with a blank quarter on each side: the colon, the semicolon and the middle dot.
1936#[must_use]
1937pub const fn japanese_centered_mark(ch: char) -> bool {
1938    matches!(ch, '\u{FF1A}' | '\u{FF1B}' | '\u{30FB}')
1939}
1940
1941/// Whether a character is the Katakana middle dot (`・`), which carries a compressible blank half
1942/// (two blank quarters) in Japanese.
1943#[must_use]
1944pub const fn middle_dot(ch: char) -> bool {
1945    ch == '\u{30FB}'
1946}
1947
1948/// Whether a character is a full-width punctuation mark whose left half is blank, such as an
1949/// opening bracket.
1950#[must_use]
1951pub fn opening_mark(ch: char) -> bool {
1952    matches!(
1953        ch,
1954        '\u{300C}'
1955            | '\u{300E}'
1956            | '\u{FF08}'
1957            | '\u{3010}'
1958            | '\u{3014}'
1959            | '\u{3008}'
1960            | '\u{300A}'
1961            | '\u{FF5B}'
1962            | '\u{FF3B}'
1963    )
1964}
1965
1966/// Which mark of a kerned East Asian punctuation pair gave up its blank half.
1967#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1968pub(crate) enum KernedMark {
1969    /// The first mark had a blank right half and gave it up (`」,`, `),`, `」「`, `)(`, `,「`).
1970    Left,
1971    /// The second mark was an opening bracket and gave up its blank left half (`「「`, `,「` in
1972    /// Traditional Chinese).
1973    Right,
1974}
1975
1976/// Which mark of the pair `(left, right)` gives up its blank half when a kerned run closes up
1977/// the pair of East Asian punctuation marks by half an em under the run's East Asian `script`
1978/// (`w:lang w:eastAsia`), or `None` when the pair does not kern: `left` has a blank right half or
1979/// `right` is an opening bracket, and both are marks for that script.
1980///
1981/// - Opening and closing brackets always qualify, even when `script` is `None`.
1982/// - Stops (`,`, `。`, `、`, `.`) have a blank right half in Simplified Chinese and Japanese,
1983///   stand in the middle in Traditional Chinese, and do not close up without an East Asian
1984///   script.
1985/// - Colon and semicolon (`:`, `;`) have a blank right half in Simplified Chinese and stand in
1986///   the middle in Japanese and Traditional Chinese.
1987/// - Exclamation (`!`) has a blank right half in Simplified Chinese only.
1988/// - Middle dot (`・`) stands in the middle in Japanese only.
1989/// - Question mark (`?`) never closes up.
1990#[must_use]
1991pub(crate) fn kerned_pair(
1992    left: char,
1993    right: char,
1994    script: Option<crate::props::EastAsianScript>,
1995) -> Option<KernedMark> {
1996    #[derive(Clone, Copy, PartialEq, Eq)]
1997    enum Kind {
1998        Opening,
1999        Closing,
2000        Middle,
2001    }
2002    let kind = |ch: char| -> Option<Kind> {
2003        use crate::props::EastAsianScript::{Japanese, Simplified, Traditional};
2004        if opening_mark(ch) {
2005            return Some(Kind::Opening);
2006        }
2007        if matches!(
2008            ch,
2009            '\u{300D}'
2010                | '\u{300F}'
2011                | '\u{FF09}'
2012                | '\u{3011}'
2013                | '\u{3015}'
2014                | '\u{3009}'
2015                | '\u{300B}'
2016                | '\u{FF5D}'
2017                | '\u{FF3D}'
2018        ) {
2019            return Some(Kind::Closing);
2020        }
2021        match (ch, script) {
2022            ('\u{3001}' | '\u{3002}' | '\u{FF0C}' | '\u{FF0E}', Some(Simplified | Japanese))
2023            | ('\u{FF01}' | '\u{FF1A}' | '\u{FF1B}', Some(Simplified)) => Some(Kind::Closing),
2024            ('\u{3001}' | '\u{3002}' | '\u{FF0C}' | '\u{FF0E}', Some(Traditional))
2025            | ('\u{FF1A}' | '\u{FF1B}', Some(Japanese | Traditional))
2026            | ('\u{30FB}', Some(Japanese)) => Some(Kind::Middle),
2027            _ => None,
2028        }
2029    };
2030    match (kind(left), kind(right)) {
2031        (Some(Kind::Closing), Some(_)) => Some(KernedMark::Left),
2032        (Some(_), Some(Kind::Opening)) => Some(KernedMark::Right),
2033        _ => None,
2034    }
2035}
2036
2037/// Whether a piece is a space glyph that a line may break at and stretch: not an equation
2038/// space ([`SpaceKind::Equation`]).
2039#[must_use]
2040pub fn is_space(piece: &Piece) -> bool {
2041    matches!(piece, Piece::Glyph(g) if g.ch == ' ' && g.space == SpaceKind::Free)
2042}
2043
2044/// Whether a piece is a space that a justified line stretches or shrinks: a space of
2045/// [`is_space`], or a no-break space that takes a plain space's share ([`SpaceKind::NoBreak`]).
2046#[must_use]
2047pub fn stretches(piece: &Piece) -> bool {
2048    is_space(piece) || matches!(piece, Piece::Glyph(g) if g.space == SpaceKind::NoBreak)
2049}
2050
2051/// Whether a piece is the space of an operator where an equation may break
2052/// ([`SpaceKind::Operator`]).
2053fn is_operator_space(piece: &Piece) -> bool {
2054    matches!(piece, Piece::Glyph(g) if g.space == SpaceKind::Operator)
2055}
2056
2057/// The glyph of a piece that is text of a run; none for a list label, which is not a run of
2058/// the text and keeps its UAX 9 classes, and for a piece that is no glyph.
2059pub(crate) const fn run_glyph(piece: &Piece) -> Option<&Glyph> {
2060    match piece {
2061        Piece::Glyph(glyph) if !glyph.label => Some(glyph),
2062        _ => None,
2063    }
2064}
2065
2066/// Whether a piece is text of a run with `w:rtl`; none for a piece that is no text of a run.
2067pub(crate) fn run_rtl(piece: &Piece) -> Option<bool> {
2068    run_glyph(piece).map(|glyph| glyph.direction.class().is_some())
2069}
2070
2071/// Whether a character is written from right to left, such as Hebrew or Arabic.
2072pub(crate) fn right_to_left(ch: char) -> bool {
2073    matches!(
2074        unicode_bidi::bidi_class(ch),
2075        unicode_bidi::BidiClass::R | unicode_bidi::BidiClass::AL
2076    )
2077}
2078
2079/// Whether a character is a left-to-right letter, such as a Latin one.
2080fn left_to_right(ch: char) -> bool {
2081    unicode_bidi::bidi_class(ch) == unicode_bidi::BidiClass::L
2082}
2083
2084#[cfg(test)]
2085mod tests {
2086    use super::{
2087        EndHyphen, EndSpaceFit, Frame, Hyphenation, JointCounts, JointGaps, LeadingBreaks, Line,
2088        LineBreaking, LineEnd, NoteNumber, Piece, Shrink, break_lines, following_width, is_space,
2089    };
2090    use crate::props::{TabKind, TabStop};
2091    use crate::quirks::{AlignedTabOverrun, LeftStopPastEnd, NoteReferenceBreak};
2092    use crate::tabs::Tabs;
2093    use crate::text::AUTOMATIC_HYPHEN;
2094    use crate::text::{FaceIndex, Glyph, SpaceKind};
2095    use f_office_units::Length;
2096
2097    #[test]
2098    fn keeps_a_footnote_s_place_from_zero() {
2099        assert_eq!(NoteNumber::of_index(4).index(), 4);
2100    }
2101
2102    fn glyphs(text: &str) -> Vec<Piece> {
2103        text.chars()
2104            .map(|ch| Piece::Glyph(Glyph::plain(FaceIndex::nth(0), ch)))
2105            .collect()
2106    }
2107
2108    /// The pieces of `text`, of 10 units each, whose glyphs from the `first` on belong to a
2109    /// run with `w:rtl`.
2110    fn marked_from(text: &str, first: usize) -> Vec<Piece> {
2111        let mut pieces = glyphs(text);
2112        for piece in pieces.iter_mut().skip(first) {
2113            if let Piece::Glyph(glyph) = piece {
2114                glyph.direction = crate::text::RunDirection::of(true, None);
2115            }
2116        }
2117        pieces
2118    }
2119
2120    #[test]
2121    fn fits_a_word_with_its_rtl_end_spaces_beside_left_to_right_text() {
2122        // "ab" in a run without `w:rtl`, then Hebrew words in a run with `w:rtl`. The third
2123        // word ends at 80 units and its space at 90: it fits a line of 85 only without it.
2124        let mixed = marked_from("ab \u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}", 3);
2125        let fitted = |width| Frame {
2126            end_space_fit: EndSpaceFit::WithRightToLeftSpaces,
2127            ..frame(width)
2128        };
2129        assert_eq!(
2130            texts(&break_lines(&mixed, &frame(85))),
2131            ["ab \u{5d0}\u{5d1} \u{5d2}\u{5d3} ", "\u{5d4}\u{5d5}"]
2132        );
2133        assert_eq!(
2134            texts(&break_lines(&mixed, &fitted(85))),
2135            ["ab \u{5d0}\u{5d1} ", "\u{5d2}\u{5d3} \u{5d4}\u{5d5}"]
2136        );
2137        // The spaces between right-to-left letters count in the same way in runs without
2138        // `w:rtl`; a space before a Latin word does not.
2139        let plain = glyphs("ab \u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}");
2140        assert_eq!(
2141            texts(&break_lines(&plain, &fitted(85))),
2142            ["ab \u{5d0}\u{5d1} ", "\u{5d2}\u{5d3} \u{5d4}\u{5d5}"]
2143        );
2144        let latin_after = glyphs("ab \u{5d0}\u{5d1} \u{5d2}\u{5d3} cd");
2145        assert_eq!(
2146            texts(&break_lines(&latin_after, &fitted(85))),
2147            ["ab \u{5d0}\u{5d1} \u{5d2}\u{5d3} ", "cd"]
2148        );
2149        // A line of right-to-left text only fits its words without their spaces.
2150        let pure = marked_from("\u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}", 0);
2151        assert_eq!(
2152            texts(&break_lines(&pure, &fitted(55))),
2153            texts(&break_lines(&pure, &frame(55)))
2154        );
2155        // So does one without `w:rtl`, which holds no left-to-right letter: the second word ends
2156        // at 50 and the space after it at 60.
2157        let plain_only = glyphs("\u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}");
2158        assert_eq!(
2159            texts(&break_lines(&plain_only, &fitted(55))),
2160            ["\u{5d0}\u{5d1} \u{5d2}\u{5d3} ", "\u{5d4}\u{5d5}"]
2161        );
2162    }
2163
2164    #[test]
2165    fn counts_kept_rtl_spaces_as_spaces_of_a_justified_line() {
2166        // Four Latin words, then Hebrew words in a run with `w:rtl`, each piece 10 units; each
2167        // space may shrink by 2. The third Hebrew word ends at 180 with its space.
2168        let mixed = marked_from(
2169            "ab cd ef gh \u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}",
2170            12,
2171        );
2172        let justified = |width| Frame {
2173            shrink: Shrink {
2174                permille: 250,
2175                stretch_permille: 500,
2176                natural: (0, 0),
2177                joints: JointGaps::default(),
2178            },
2179            end_space_fit: EndSpaceFit::WithRightToLeftSpaces,
2180            ..frame(width)
2181        };
2182        let fitted = [
2183            "ab cd ef gh \u{5d0}\u{5d1} \u{5d2}\u{5d3} ",
2184            "\u{5d4}\u{5d5}",
2185        ];
2186        let wrapped = [
2187            "ab cd ef gh \u{5d0}\u{5d1} ",
2188            "\u{5d2}\u{5d3} \u{5d4}\u{5d5}",
2189        ];
2190        // Its end space shrinks too: 6 spaces may shrink by 11 units, as half the stretch per
2191        // gap allows; without it, the 5 spaces before the word only by 10.
2192        assert_eq!(texts(&break_lines(&mixed, &justified(169))), fitted);
2193        // The space before the word is a gap of the line without it, and leaves it no room: by
2194        // the stretch, the spaces may not shrink by 12, as they could if it hung.
2195        assert_eq!(texts(&break_lines(&mixed, &justified(168))), wrapped);
2196        // The same holds for the spaces between right-to-left letters in runs without `w:rtl`.
2197        let plain = glyphs("ab cd ef gh \u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}");
2198        assert_eq!(texts(&break_lines(&plain, &justified(169))), fitted);
2199        assert_eq!(texts(&break_lines(&plain, &justified(168))), wrapped);
2200        // On a line of right-to-left text only without `w:rtl`, which holds no left-to-right
2201        // letter, the spaces between its letters count in neither part.
2202        let only = glyphs(
2203            "\u{5e9}\u{5ea} \u{5e7}\u{5e8} \u{5e6}\u{5e4} \u{5e2}\u{5e1} \u{5d0}\u{5d1} \u{5d2}\u{5d3} \u{5d4}\u{5d5}",
2204        );
2205        for width in 160..180 {
2206            let hanging = Frame {
2207                end_space_fit: EndSpaceFit::WithoutSpaces,
2208                ..justified(width)
2209            };
2210            assert_eq!(
2211                texts(&break_lines(&only, &justified(width))),
2212                texts(&break_lines(&only, &hanging)),
2213                "{width}"
2214            );
2215        }
2216    }
2217
2218    fn frame(width: i64) -> Frame {
2219        Frame {
2220            first_width: Length::from_units(width),
2221            width: Length::from_units(width),
2222            area_width: Length::from_units(width),
2223            first_start: Length::ZERO,
2224            start: Length::ZERO,
2225            tabs: Tabs::new([], Length::from_units(25), None),
2226            shrink: Shrink::default(),
2227            thai_keeps_spaces: false,
2228            end_space_fit: EndSpaceFit::WithoutSpaces,
2229            kinsoku: None,
2230            joined_spaces: false,
2231            breaking: LineBreaking::default(),
2232            limits_past_end: true,
2233            punctuation: None,
2234            hyphenation: None,
2235            overflow_punct: super::OverflowPunct::Warn,
2236        }
2237    }
2238
2239    fn texts(lines: &[Line]) -> Vec<String> {
2240        lines
2241            .iter()
2242            .map(|line| {
2243                line.placed
2244                    .iter()
2245                    .map(|p| match p.piece {
2246                        Piece::Glyph(g) => g.ch,
2247                        _ => '|',
2248                    })
2249                    .collect()
2250            })
2251            .collect()
2252    }
2253
2254    #[test]
2255    fn anchor_marks_change_no_line_and_go_to_the_line_of_the_piece_after_them() {
2256        let text = glyphs("ab cd ef");
2257        // Marks before "a", inside "cd", before "ef" and after the last piece.
2258        let mut marked = text.clone();
2259        for (at, drawing) in [(8, 3), (6, 2), (4, 1), (0, 0)] {
2260            marked.insert(at, Piece::Anchor(drawing));
2261        }
2262        for width in [25, 45, 55, 100] {
2263            assert_eq!(
2264                texts(&break_lines(&marked, &frame(width))),
2265                texts(&break_lines(&text, &frame(width))),
2266                "{width}"
2267            );
2268        }
2269        let anchors = |lines: &[Line]| -> Vec<Vec<(usize, usize)>> {
2270            lines
2271                .iter()
2272                .map(|line| line.anchors.iter().map(|a| (a.at, a.drawing)).collect())
2273                .collect()
2274        };
2275        let lines = break_lines(&marked, &frame(55));
2276        assert_eq!(texts(&lines), ["ab cd ", "ef"]);
2277        assert_eq!(
2278            anchors(&lines),
2279            [vec![(0, 0), (4, 1)], vec![(0, 2), (2, 3)]]
2280        );
2281        // Lines broken again from their pieces keep their marks in their places.
2282        let again = break_lines(&Line::pieces(&lines), &frame(100));
2283        assert_eq!(anchors(&again), [vec![(0, 0), (4, 1), (6, 2), (8, 3)]]);
2284    }
2285
2286    #[test]
2287    fn a_footnote_reference_as_text_keeps_the_closing_parenthesis_after_it_on_its_line() {
2288        let with = |note_reference_break| Frame {
2289            breaking: LineBreaking {
2290                note_reference_in_word: note_reference_break == NoteReferenceBreak::AsText,
2291                ..LineBreaking::default()
2292            },
2293            ..frame(65)
2294        };
2295        let mut pieces = glyphs("ab (c1");
2296        pieces.push(Piece::Note(NoteNumber::of_index(0)));
2297        pieces.extend(glyphs(") d"));
2298        assert_eq!(
2299            texts(&break_lines(&pieces, &with(NoteReferenceBreak::After))),
2300            ["ab (c1|", ") d"]
2301        );
2302        assert_eq!(
2303            texts(&break_lines(&pieces, &with(NoteReferenceBreak::AsText))),
2304            ["ab ", "(c1|) d"]
2305        );
2306        // A space after the mark still ends the word.
2307        let mut spaced = glyphs("ab c1");
2308        spaced.push(Piece::Note(NoteNumber::of_index(0)));
2309        spaced.extend(glyphs(" de"));
2310        assert_eq!(
2311            texts(&break_lines(&spaced, &with(NoteReferenceBreak::AsText))),
2312            ["ab c1| ", "de"]
2313        );
2314    }
2315
2316    #[test]
2317    fn a_joined_space_run_keeps_the_words_on_both_of_its_sides_on_one_line() {
2318        let with = |joined_spaces| Frame {
2319            joined_spaces,
2320            ..frame(70)
2321        };
2322        // A no-break space then a space, a space then a no-break space, and both around one;
2323        // then plain spaces and a no-break space alone, which no mode changes.
2324        for (text, apart, together) in [
2325            (
2326                "aa bb\u{a0} cc",
2327                ["aa bb\u{a0} ", "cc"],
2328                ["aa ", "bb\u{a0} cc"],
2329            ),
2330            (
2331                "aa bb \u{a0}cc",
2332                ["aa bb ", "\u{a0}cc"],
2333                ["aa ", "bb \u{a0}cc"],
2334            ),
2335            (
2336                "aa b \u{a0} cc",
2337                ["aa b \u{a0} ", "cc"],
2338                ["aa ", "b \u{a0} cc"],
2339            ),
2340            ("aa bb  cc", ["aa bb  ", "cc"], ["aa bb  ", "cc"]),
2341            (
2342                "aa bb\u{a0}cc",
2343                ["aa ", "bb\u{a0}cc"],
2344                ["aa ", "bb\u{a0}cc"],
2345            ),
2346        ] {
2347            assert_eq!(texts(&break_lines(&glyphs(text), &with(false))), apart);
2348            assert_eq!(texts(&break_lines(&glyphs(text), &with(true))), together);
2349        }
2350    }
2351
2352    #[test]
2353    fn breaks_east_asian_text_between_characters_with_kinsoku() {
2354        use crate::kinsoku::Kinsoku;
2355        use crate::props::EastAsianScript;
2356        let with = |kinsoku: Option<Kinsoku>| Frame {
2357            kinsoku,
2358            ..frame(40)
2359        };
2360        let text = glyphs("ab 日本語、文字");
2361        // Without an East Asian language, the run of East Asian characters is one word, which
2362        // goes to the next line whole and splits there.
2363        let latin = break_lines(&text, &with(None));
2364        assert_eq!(texts(&latin), vec!["ab ", "日本語、", "文字"]);
2365        // With one, a line breaks between characters.
2366        let japanese = Some(Kinsoku::of(EastAsianScript::Japanese));
2367        let lines = break_lines(&text, &with(japanese));
2368        assert_eq!(texts(&lines), vec!["ab 日", "本語、文", "字"]);
2369        // "、" may not start a line, so "文" goes to the next line with it. With kinsoku off,
2370        // "、" starts the line.
2371        let mark = glyphs("日本語文、字");
2372        let kept = break_lines(&mark, &with(japanese));
2373        assert_eq!(texts(&kept), vec!["日本語", "文、字"]);
2374        let free = break_lines(&mark, &with(Some(Kinsoku::FREE)));
2375        assert_eq!(texts(&free), vec!["日本語文", "、字"]);
2376    }
2377
2378    #[test]
2379    fn marks_a_line_before_a_word_that_fits_without_its_hanging_mark() {
2380        use crate::kinsoku::Kinsoku;
2381        use crate::props::EastAsianScript;
2382        let simplified = Kinsoku::of(EastAsianScript::Simplified);
2383        let with = |kinsoku: Kinsoku| Frame {
2384            kinsoku: Some(kinsoku),
2385            ..frame(40)
2386        };
2387        let hangs = |text: &str, kinsoku: Kinsoku| {
2388            let lines = break_lines(&glyphs(text), &with(kinsoku));
2389            (
2390                texts(&lines),
2391                lines.iter().map(|l| l.would_hang).collect::<Vec<_>>(),
2392            )
2393        };
2394        // Four glyphs of 10 units fill the line, and "," may not start the next: "四" goes
2395        // with it, where Word keeps "四" and hangs the mark. A Latin word in parentheses keeps
2396        // its closing parenthesis, which Word hangs too.
2397        let lines = |a: &[&str]| a.iter().map(|t| (*t).to_owned()).collect::<Vec<_>>();
2398        assert_eq!(
2399            hangs("一二三四,五", simplified),
2400            (lines(&["一二三", "四,五"]), vec![true, false])
2401        );
2402        assert_eq!(
2403            hangs("一(ab)", simplified),
2404            (lines(&["一", "(ab)"]), vec![true, false])
2405        );
2406        // No hang: with `w:overflowPunct` off; before a mark that cannot start a line but is
2407        // not of the list, "…"; where the character before the mark does not fit either; and
2408        // with kinsoku off, where the mark starts the next line.
2409        let no = |text: &str, kinsoku: Kinsoku| {
2410            let (_, hung) = hangs(text, kinsoku);
2411            assert!(hung.iter().all(|hang| !hang), "{text}");
2412        };
2413        no("一二三四,五", simplified.without_hanging());
2414        no("一二三四…五", simplified);
2415        no("一二三四五,", simplified);
2416        no("一二三四,五", Kinsoku::FREE);
2417    }
2418
2419    #[test]
2420    fn breaks_after_spaces_and_hyphens() {
2421        let lines = break_lines(&glyphs("aa bb-cc dd"), &frame(60));
2422        assert_eq!(texts(&lines), vec!["aa bb-", "cc dd"]);
2423        let narrow = break_lines(&glyphs("aa bb-cc dd"), &frame(50));
2424        assert_eq!(texts(&narrow), vec!["aa ", "bb-cc ", "dd"]);
2425        assert_eq!(lines[0].width(), Length::from_units(60));
2426        assert_eq!(lines[1].last_visible(), Some(4));
2427    }
2428
2429    #[test]
2430    fn breaks_an_equation_after_the_space_of_an_operator_which_hangs() {
2431        let pieces: Vec<Piece> = glyphs("a+\u{a0}b+\u{a0}cd")
2432            .into_iter()
2433            .map(|piece| match piece {
2434                Piece::Glyph(mut g) if g.ch == '\u{a0}' => {
2435                    g.space = SpaceKind::Operator;
2436                    Piece::Glyph(g)
2437                }
2438                other => other,
2439            })
2440            .collect();
2441        let lines = break_lines(&pieces, &frame(50));
2442        assert_eq!(texts(&lines), vec!["a+\u{a0}b+\u{a0}", "cd"]);
2443        assert_eq!(lines[0].last_visible(), Some(4));
2444        assert!(!is_space(&pieces[2]));
2445    }
2446
2447    #[test]
2448    fn a_justified_line_counts_the_operator_space_before_a_term_in_its_room() {
2449        let pieces: Vec<Piece> = glyphs("a b c d+\u{a0}e+\u{a0}f")
2450            .into_iter()
2451            .map(|piece| match piece {
2452                Piece::Glyph(mut g) if g.ch == '\u{a0}' => {
2453                    g.space = SpaceKind::Operator;
2454                    Piece::Glyph(g)
2455                }
2456                other => other,
2457            })
2458            .collect();
2459        let mut f = frame(101);
2460        f.shrink = Shrink {
2461            permille: 500,
2462            stretch_permille: 500,
2463            natural: (0, 0),
2464            joints: JointGaps::default(),
2465        };
2466        // "a b c d+ e+" is 110 wide, 9 over a frame of 101. Without "e+", the line would leave
2467        // the 20 of the term and the 10 of the operator space before it to stretch over its 3
2468        // gaps, so it may run over by 30 * 1500 / (3000 + 1500) = 10.
2469        assert_eq!(
2470            texts(&break_lines(&pieces, &f)),
2471            vec!["a b c d+\u{a0}e+\u{a0}", "f"]
2472        );
2473        f.width = Length::from_units(99);
2474        f.first_width = f.width;
2475        assert_eq!(
2476            texts(&break_lines(&pieces, &f)),
2477            vec!["a b c d+\u{a0}", "e+\u{a0}f"]
2478        );
2479    }
2480
2481    #[test]
2482    fn hangs_the_whole_space_after_a_relation() {
2483        let pieces: Vec<Piece> = glyphs("a=\u{200a}\u{a0}b=\u{200a}\u{a0}cd")
2484            .into_iter()
2485            .map(|piece| match piece {
2486                Piece::Glyph(mut g) if matches!(g.ch, '\u{200a}' | '\u{a0}') => {
2487                    g.space = SpaceKind::Operator;
2488                    Piece::Glyph(g)
2489                }
2490                other => other,
2491            })
2492            .collect();
2493        let lines = break_lines(&pieces, &frame(60));
2494        assert_eq!(
2495            texts(&lines),
2496            vec!["a=\u{200a}\u{a0}b=\u{200a}\u{a0}", "cd"]
2497        );
2498        assert_eq!(lines[0].last_visible(), Some(5));
2499    }
2500
2501    #[test]
2502    fn keeps_the_numbers_of_its_decisions() {
2503        let lines = break_lines(&glyphs("aa bb cc"), &frame(50));
2504        assert_eq!(texts(&lines), vec!["aa bb ", "cc"]);
2505        // "bb" fit after "aa " and one space, and "cc" would have ended at 80 after two.
2506        let u = Length::from_units;
2507        let kept = lines[0].kept.unwrap();
2508        assert_eq!(
2509            (kept.end, kept.word, kept.spaces, kept.space),
2510            (u(50), u(20), u(10), u(10))
2511        );
2512        let wrapped = lines[0].wrapped.unwrap();
2513        assert_eq!(
2514            (wrapped.width, wrapped.end, wrapped.spaces),
2515            (u(50), u(80), u(20))
2516        );
2517        assert_eq!((wrapped.over, wrapped.shrinks), (Length::ZERO, false));
2518        // The last line ends its paragraph, not before a word.
2519        assert_eq!(lines[1].kept.unwrap().end, u(20));
2520        assert_eq!(lines[1].wrapped, None);
2521    }
2522
2523    #[test]
2524    fn shows_a_soft_hyphen_only_where_a_line_ends() {
2525        // Each glyph is 10 units wide. "bbcc" fits with "aa " in 70 units, so its soft hyphen
2526        // shows nothing and takes no width.
2527        let text = "aa bb\u{E0AD}cc dd";
2528        let wide = break_lines(&glyphs(text), &frame(70));
2529        assert_eq!(texts(&wide), vec!["aa bbcc ", "dd"]);
2530        assert_eq!(wide[0].placed[5].x, Length::from_units(50));
2531        // In 60 units the line ends at the soft hyphen, which shows a hyphen-minus.
2532        let narrow = break_lines(&glyphs(text), &frame(60));
2533        assert_eq!(texts(&narrow), vec!["aa bb-", "cc dd"]);
2534        assert_eq!(narrow[0].width(), Length::from_units(60));
2535        // The hyphen needs room as well: in 50 units "bb-" goes to the next line, where
2536        // "bbcc" fits whole.
2537        let tight = break_lines(&glyphs(text), &frame(50));
2538        assert_eq!(texts(&tight), vec!["aa ", "bbcc ", "dd"]);
2539        // A soft hyphen at the end of the paragraph shows nothing.
2540        let end = break_lines(&glyphs("aa\u{E0AD}"), &frame(60));
2541        assert_eq!(texts(&end), vec!["aa"]);
2542        // A U+00AD in the text is an ordinary character.
2543        let literal = break_lines(&glyphs("aa bb\u{AD}cc dd"), &frame(70));
2544        assert_eq!(texts(&literal), vec!["aa ", "bb\u{AD}cc ", "dd"]);
2545    }
2546
2547    #[test]
2548    fn marks_the_line_that_ends_at_a_soft_hyphen() {
2549        // Each glyph is 10 units wide, as in the test above.
2550        let hyphens = |text: &str, width| {
2551            let lines = break_lines(&glyphs(text), &frame(width));
2552            lines.iter().map(|line| line.hyphen).collect::<Vec<_>>()
2553        };
2554        assert_eq!(hyphens("aa bb\u{E0AD}cc dd", 70), [None, None]);
2555        assert_eq!(
2556            hyphens("aa bb\u{E0AD}cc dd", 60),
2557            [Some(EndHyphen::Soft), None]
2558        );
2559        assert_eq!(hyphens("aa\u{E0AD}", 60), [None]);
2560    }
2561
2562    #[test]
2563    fn breaks_after_the_move_of_an_advance_field_but_not_before_it() {
2564        // Each glyph is 10 units wide. The move of 30 belongs to "aa", and "bb" after it
2565        // starts a word: "aa" and the move take 50, and "bb" goes to the next line.
2566        let moved = |before: &str, after: &str| {
2567            let mut pieces = glyphs(before);
2568            pieces.push(Piece::Advance(Length::from_units(30)));
2569            pieces.extend(glyphs(after));
2570            pieces
2571        };
2572        let lines = break_lines(&moved("aa", "bb cc"), &frame(60));
2573        assert_eq!(texts(&lines), vec!["aa|", "bb cc"]);
2574        // In 50 units "aa" and its move (`|`) leave the line of "a " together.
2575        let lines = break_lines(&moved("a aa", "bb"), &frame(50));
2576        assert_eq!(texts(&lines), vec!["a ", "aa|", "bb"]);
2577    }
2578
2579    /// The pieces of `text`, with an automatic hyphenation point at each `=`.
2580    fn with_points(text: &str) -> Vec<Piece> {
2581        glyphs(&text.replace('=', &AUTOMATIC_HYPHEN.to_string()))
2582    }
2583
2584    /// The texts of `lines`, with the hyphen of an automatic point at a line end as `-`.
2585    fn hyphenated_texts(lines: &[Line]) -> Vec<String> {
2586        texts(lines)
2587            .into_iter()
2588            .map(|text| text.replace(super::LINE_END_HYPHEN, "-"))
2589            .collect()
2590    }
2591
2592    #[test]
2593    fn ends_a_line_at_the_last_automatic_point_that_fits() {
2594        // Each glyph advances 10; the hyphen takes room only at the end of a line, so on a line
2595        // of 120 `hyphen-` fits after `aaaa ` and `hyphena-` does not.
2596        let hyphenated = |rules| Frame {
2597            hyphenation: Some(rules),
2598            ..frame(120)
2599        };
2600        let pieces = with_points("aaaa hy=phen=ation");
2601        let lines = break_lines(&pieces, &hyphenated(Hyphenation::default()));
2602        assert_eq!(hyphenated_texts(&lines), ["aaaa hyphen-", "ation"]);
2603        assert_eq!(lines[0].hyphen, Some(EndHyphen::Automatic));
2604        // Without hyphenation the word goes down whole, and no point shows.
2605        assert_eq!(
2606            hyphenated_texts(&break_lines(&pieces, &frame(120))),
2607            ["aaaa ", "hyphenation"]
2608        );
2609        // A zone as wide as the room of 70 keeps the word whole; a narrower one does not.
2610        let zone = |units| Hyphenation {
2611            zone: Some(Length::from_units(units)),
2612            limit: None,
2613        };
2614        assert_eq!(
2615            hyphenated_texts(&break_lines(&pieces, &hyphenated(zone(70)))),
2616            ["aaaa ", "hyphenation"]
2617        );
2618        assert_eq!(
2619            hyphenated_texts(&break_lines(&pieces, &hyphenated(zone(69)))),
2620            ["aaaa hyphen-", "ation"]
2621        );
2622    }
2623
2624    #[test]
2625    fn ends_no_more_lines_in_a_row_at_a_point_than_the_limit() {
2626        let pieces = with_points("aaaa=aaaa=aaaa=aaaa=aaaa=aaaa");
2627        let limited = |limit| Frame {
2628            hyphenation: Some(Hyphenation {
2629                zone: None,
2630                limit: std::num::NonZeroUsize::new(limit),
2631            }),
2632            ..frame(60)
2633        };
2634        assert_eq!(
2635            hyphenated_texts(&break_lines(&pieces, &limited(0))),
2636            ["aaaa-", "aaaa-", "aaaa-", "aaaa-", "aaaa-", "aaaa"]
2637        );
2638        // The third line may not end at a point, so the word is split there as a word that fits
2639        // no line is, and the count starts again.
2640        assert_eq!(
2641            hyphenated_texts(&break_lines(&pieces, &limited(2))),
2642            ["aaaa-", "aaaa-", "aaaaaa", "aa-", "aaaa-", "aaaa"]
2643        );
2644    }
2645
2646    #[test]
2647    fn breaks_after_en_and_em_dashes() {
2648        let en = break_lines(&glyphs("aa bb\u{2013}cc dd"), &frame(60));
2649        assert_eq!(texts(&en), vec!["aa bb\u{2013}", "cc dd"]);
2650        let em = break_lines(&glyphs("aa bb\u{2014}cc dd"), &frame(60));
2651        assert_eq!(texts(&em), vec!["aa bb\u{2014}", "cc dd"]);
2652    }
2653
2654    #[test]
2655    fn breaks_after_a_unicode_hyphen() {
2656        let lines = break_lines(&glyphs("aa bb\u{2010}cc dd"), &frame(60));
2657        assert_eq!(texts(&lines), vec!["aa bb\u{2010}", "cc dd"]);
2658    }
2659
2660    #[test]
2661    fn thai_text_keeps_the_spaces_of_its_line() {
2662        let mut f = frame(72);
2663        f.shrink = Shrink {
2664            permille: 400,
2665            stretch_permille: 0,
2666            natural: (0, 0),
2667            joints: JointGaps::default(),
2668        };
2669        f.thai_keeps_spaces = true;
2670        // As in the test below, "aa bb cc" fits only because its spaces shrink. A Thai word on
2671        // the line, or as the word that it tests, keeps them; a line of Latin words shrinks.
2672        assert_eq!(
2673            texts(&break_lines(&glyphs("aa bb cc"), &f)),
2674            vec!["aa bb cc"]
2675        );
2676        assert_eq!(
2677            texts(&break_lines(&glyphs("aa bb กข"), &f)),
2678            vec!["aa bb ", "กข"]
2679        );
2680        assert_eq!(
2681            texts(&break_lines(&glyphs("กข bb cc"), &f)),
2682            vec!["กข bb ", "cc"]
2683        );
2684        f.thai_keeps_spaces = false;
2685        assert_eq!(
2686            texts(&break_lines(&glyphs("กข bb cc"), &f)),
2687            vec!["กข bb cc"]
2688        );
2689    }
2690
2691    #[test]
2692    fn justified_lines_may_shrink_their_spaces() {
2693        let mut f = frame(50);
2694        f.shrink = Shrink {
2695            permille: 400,
2696            stretch_permille: 0,
2697            natural: (0, 0),
2698            joints: JointGaps::default(),
2699        };
2700        // "aa bb cc" is 80 wide with two inner spaces of 10; each may shrink by 40% of it, 4,
2701        // so the line may be 8 wider than the frame.
2702        assert_eq!(
2703            texts(&break_lines(&glyphs("aa bb c"), &f)),
2704            vec!["aa bb ", "c"]
2705        );
2706        f.width = Length::from_units(72);
2707        f.first_width = f.width;
2708        assert_eq!(
2709            texts(&break_lines(&glyphs("aa bb cc"), &f)),
2710            vec!["aa bb cc"]
2711        );
2712        let u = Length::from_units;
2713        assert_eq!(f.shrink.of(u(10)), u(4));
2714        assert_eq!(
2715            Shrink {
2716                permille: 100,
2717                stretch_permille: 0,
2718                natural: (0, 0),
2719                joints: JointGaps::default(),
2720            }
2721            .of(u(10)),
2722            u(1)
2723        );
2724    }
2725
2726    #[test]
2727    fn a_share_of_the_natural_width_limits_the_overrun_to_the_nearest_twip() {
2728        let twips = |t| Length::from_twips(t).unwrap();
2729        let shrink = Shrink {
2730            natural: (3, 80),
2731            ..Shrink::default()
2732        };
2733        // A natural width of 8,000 twips needs a width of 7,700; one of 8,001 needs 7,700.96,
2734        // 7,701 to the nearest twip.
2735        assert_eq!(shrink.of_natural(twips(8_000)), Some(twips(300)));
2736        assert_eq!(shrink.of_natural(twips(8_001)), Some(twips(300)));
2737        assert_eq!(shrink.of_natural(twips(8_010)), Some(twips(300)));
2738        assert_eq!(shrink.of_natural(twips(8_020)), Some(twips(301)));
2739        assert_eq!(Shrink::default().of_natural(twips(8_000)), None);
2740    }
2741
2742    #[test]
2743    fn keeps_the_spaces_after_a_word_that_shrinks_its_line() {
2744        let mut f = frame(72);
2745        f.shrink = Shrink {
2746            permille: 400,
2747            stretch_permille: 0,
2748            natural: (0, 0),
2749            joints: JointGaps::default(),
2750        };
2751        // "aa bb c-" is 80 wide and fits by shrinking its two spaces. The space after the dash
2752        // stays on the line instead of starting the next one.
2753        let dashed = break_lines(&glyphs("aa bb c\u{2013} dd"), &f);
2754        assert_eq!(texts(&dashed), vec!["aa bb c\u{2013} ", "dd"]);
2755    }
2756
2757    #[test]
2758    fn a_justified_line_takes_a_word_only_when_its_spaces_shrink_by_at_most_half_the_stretch() {
2759        let mut f = frame(82);
2760        f.shrink = Shrink {
2761            permille: 500,
2762            stretch_permille: 500,
2763            natural: (0, 0),
2764            joints: JointGaps::default(),
2765        };
2766        // "a b c d e" is 90 wide with 4 spaces before "e", 8 over a frame of 82, and the spaces
2767        // could take 20. Without "e", the line would stretch 20 over its 3 gaps. With it, each
2768        // of the 4 spaces shrinks by 8 / 4 = 2, which is not more than half of 20 / 3. The line
2769        // may run over by 4 * 20 / (3 * 2 + 4) = 8, so that E(3k - 2) <= k(g + s).
2770        assert_eq!(
2771            texts(&break_lines(&glyphs("a b c d e"), &f)),
2772            vec!["a b c d e"]
2773        );
2774        f.width = Length::from_units(81);
2775        f.first_width = f.width;
2776        assert_eq!(
2777            texts(&break_lines(&glyphs("a b c d e"), &f)),
2778            vec!["a b c d ", "e"]
2779        );
2780        // Without the share, the spaces alone take the 9.
2781        f.shrink.stretch_permille = 0;
2782        assert_eq!(
2783            texts(&break_lines(&glyphs("a b c d e"), &f)),
2784            vec!["a b c d e"]
2785        );
2786        f.shrink.stretch_permille = 500;
2787        let u = Length::from_units;
2788        assert_eq!(
2789            f.shrink
2790                .over(u(20), (u(10), u(10)), (4, 1), JointCounts::default()),
2791            u(8)
2792        );
2793        // The limit of each space still holds.
2794        assert_eq!(
2795            f.shrink
2796                .over(u(5), (u(10), u(10)), (4, 1), JointCounts::default()),
2797            u(5)
2798        );
2799        // A line with no gap without the word: only the limit of each space holds.
2800        assert_eq!(
2801            f.shrink
2802                .over(u(5), (u(10), u(10)), (1, 1), JointCounts::default()),
2803            u(5)
2804        );
2805        assert_eq!(
2806            Shrink::default().over(u(10), (u(10), u(20)), (2, 1), JointCounts::default()),
2807            u(10)
2808        );
2809    }
2810
2811    #[test]
2812    fn a_justified_line_takes_a_word_less_often_when_its_letter_joints_count_as_gaps() {
2813        let mut shrink = Shrink {
2814            permille: 500,
2815            stretch_permille: 500,
2816            natural: (0, 0),
2817            joints: JointGaps { seen: 9, other: 3 },
2818        };
2819        let u = Length::from_units;
2820        // As in the test above, the line holds 4 spaces before the word, one of them right
2821        // before it. Letter joints that count as gaps spread the stretch without the word over
2822        // more gaps, so the line may run over less: with one other joint of 3 gaps, by
2823        // 4 * 20 / (2 * (3 + 3) + 4) = 5, and with one joint after a seen of 9 gaps instead, by
2824        // 4 * 14 / (2 * (3 + 9) + 4) = 2.
2825        let other = JointCounts { seen: 0, other: 1 };
2826        assert_eq!(shrink.over(u(20), (u(10), u(10)), (4, 1), other), u(5));
2827        let seen = JointCounts { seen: 1, other: 0 };
2828        assert_eq!(shrink.over(u(20), (u(7), u(7)), (4, 1), seen), u(2));
2829        // Joints of no weight leave the limit of the spaces alone.
2830        shrink.joints = JointGaps::default();
2831        assert_eq!(shrink.over(u(20), (u(10), u(10)), (4, 1), other), u(8));
2832    }
2833
2834    #[test]
2835    fn trailing_spaces_do_not_force_a_break() {
2836        let lines = break_lines(&glyphs("aaaa    b"), &frame(40));
2837        assert_eq!(texts(&lines), vec!["aaaa    ", "b"]);
2838        assert_eq!(lines[0].width(), Length::from_units(40));
2839    }
2840
2841    #[test]
2842    fn places_an_object_as_a_word_of_its_own() {
2843        let object = Piece::Object {
2844            width: Length::from_units(50),
2845            height: Length::from_units(200),
2846            raised: Length::ZERO,
2847            picture: None,
2848            drawing: None,
2849            underlined: false,
2850            run_face: None,
2851            joins_before: false,
2852        };
2853        let mut pieces = glyphs("ab ");
2854        pieces.push(object);
2855        pieces.extend(glyphs(" cd"));
2856        let lines = break_lines(&pieces, &frame(100));
2857        assert_eq!(texts(&lines), vec!["ab | ", "cd"]);
2858        assert_eq!(lines[0].placed[3].advance, Length::from_units(50));
2859        assert_eq!(lines[0].width(), Length::from_units(80));
2860        let narrow = break_lines(&pieces, &frame(70));
2861        assert_eq!(texts(&narrow), vec!["ab ", "| ", "cd"]);
2862    }
2863
2864    #[test]
2865    fn attaches_a_joining_object_to_its_preceding_word_only() {
2866        let obj = |width: i64, joins_before: bool| Piece::Object {
2867            width: Length::from_units(width),
2868            height: Length::from_units(100),
2869            raised: Length::ZERO,
2870            picture: None,
2871            drawing: None,
2872            underlined: false,
2873            run_face: None,
2874            joins_before,
2875        };
2876        let mut pieces = glyphs("ab cd");
2877        pieces.push(obj(60, true));
2878        assert_eq!(texts(&break_lines(&pieces, &frame(85))), vec!["ab ", "cd|"]);
2879        let mut non_joining = glyphs("ab cd");
2880        non_joining.push(obj(60, false));
2881        assert_eq!(
2882            texts(&break_lines(&non_joining, &frame(85))),
2883            vec!["ab cd", "|"]
2884        );
2885        let mut after_text = glyphs("ab ");
2886        after_text.push(obj(50, true));
2887        after_text.extend(glyphs("ef"));
2888        assert_eq!(
2889            texts(&break_lines(&after_text, &frame(85))),
2890            vec!["ab |", "ef"]
2891        );
2892        let mut two_objs = glyphs("ab ");
2893        two_objs.push(obj(50, true));
2894        two_objs.push(obj(50, true));
2895        assert_eq!(
2896            texts(&break_lines(&two_objs, &frame(85))),
2897            vec!["ab |", "|"]
2898        );
2899        let mut hyphen = glyphs("ab cd-");
2900        hyphen.push(obj(60, true));
2901        assert_eq!(
2902            texts(&break_lines(&hyphen, &frame(85))),
2903            vec!["ab cd-", "|"]
2904        );
2905        let mut overlong = glyphs("ab cd");
2906        overlong.push(obj(75, true));
2907        assert_eq!(
2908            texts(&break_lines(&overlong, &frame(85))),
2909            vec!["ab ", "cd", "|"]
2910        );
2911    }
2912
2913    #[test]
2914    fn measures_an_object_after_a_tab_as_text_with_its_width() {
2915        let object = Piece::Object {
2916            width: Length::from_units(50),
2917            height: Length::from_units(200),
2918            raised: Length::ZERO,
2919            picture: None,
2920            drawing: None,
2921            underlined: false,
2922            run_face: None,
2923            joins_before: false,
2924        };
2925        let mut after = vec![object];
2926        after.extend(glyphs("ab  "));
2927        assert_eq!(following_width(&after, None), Length::from_units(70));
2928        let mut spaced = vec![object];
2929        spaced.extend(glyphs("   "));
2930        assert_eq!(following_width(&spaced, None), Length::from_units(50));
2931    }
2932
2933    #[test]
2934    fn splits_a_word_that_is_too_long() {
2935        let lines = break_lines(&glyphs("abcdefg"), &frame(30));
2936        assert_eq!(texts(&lines), vec!["abc", "def", "g"]);
2937        // The lines that end inside the word say so.
2938        let ends: Vec<LineEnd> = lines.iter().map(|l| l.end).collect();
2939        assert_eq!(ends, vec![LineEnd::Split, LineEnd::Split, LineEnd::Wrap]);
2940        assert_eq!(
2941            break_lines(&glyphs("ab cd"), &frame(30))[0].end,
2942            LineEnd::Wrap
2943        );
2944    }
2945
2946    #[test]
2947    fn honors_breaks_and_tabs() {
2948        let mut pieces = glyphs("a");
2949        pieces.push(Piece::Tab(None));
2950        pieces.extend(glyphs("b"));
2951        pieces.push(Piece::LineBreak(Some(FaceIndex::nth(3))));
2952        pieces.extend(glyphs("c"));
2953        pieces.push(Piece::PageBreak);
2954        let lines = break_lines(&pieces, &frame(100));
2955        assert_eq!(texts(&lines), vec!["a|b", "c"]);
2956        assert_eq!(lines[0].placed[1].advance, Length::from_units(15));
2957        assert_eq!(lines[0].placed[2].x, Length::from_units(25));
2958        assert_eq!(lines[1].end, LineEnd::PageBreak);
2959        assert_eq!(lines[0].end, LineEnd::Break(Some(FaceIndex::nth(3))));
2960        pieces.extend(glyphs("d"));
2961        assert_eq!(
2962            texts(&break_lines(&pieces, &frame(100))),
2963            vec!["a|b", "c", "d"]
2964        );
2965        assert_eq!(break_lines(&[], &frame(100)).len(), 1);
2966    }
2967
2968    /// A frame whose first line is 50 units wide and the others 100, which puts `leading`
2969    /// page breaks before the first line: two words of 40 units with a space between them fit
2970    /// on another line but not on the first.
2971    fn narrow_first(leading: LeadingBreaks) -> Frame {
2972        let mut f = frame(100);
2973        f.first_width = Length::from_units(50);
2974        f.breaking.leading_breaks = leading;
2975        f
2976    }
2977
2978    #[test]
2979    fn starts_the_first_line_after_leading_page_breaks_where_the_frame_says_so() {
2980        let (none, first, all) = (
2981            LeadingBreaks::None,
2982            LeadingBreaks::First,
2983            LeadingBreaks::All,
2984        );
2985        // (page breaks, leading breaks) and (lines, index of the first line). After the first
2986        // break only, the second break's line is the narrow first line, and the text takes the
2987        // other lines' width.
2988        let cases = [
2989            ((1, none), (2, 0)),
2990            ((1, first), (3, 1)),
2991            ((1, all), (3, 1)),
2992            ((2, none), (3, 0)),
2993            ((2, first), (3, 1)),
2994            ((3, first), (4, 1)),
2995            ((2, all), (4, 2)),
2996            ((0, all), (2, 0)),
2997            ((0, first), (2, 0)),
2998        ];
2999        for ((breaks, leading), expected) in cases {
3000            let mut pieces = vec![Piece::PageBreak; breaks];
3001            pieces.extend(glyphs("aaaa bbbb"));
3002            let lines = break_lines(&pieces, &narrow_first(leading));
3003            let found = (lines.len(), Line::first_index(&lines, leading));
3004            assert_eq!(found, expected, "{breaks} breaks, {leading:?}");
3005        }
3006    }
3007
3008    #[test]
3009    fn keeps_the_first_line_at_the_start_after_text_or_without_text() {
3010        // A page break after text ends a line of the paragraph's first; the text after it
3011        // takes the other lines' width.
3012        let mut pieces = glyphs("c");
3013        pieces.push(Piece::PageBreak);
3014        pieces.extend(glyphs("aaaa bbbb"));
3015        let lines = break_lines(&pieces, &narrow_first(LeadingBreaks::All));
3016        assert_eq!(lines.len(), 2);
3017        assert_eq!(Line::first_index(&lines, LeadingBreaks::All), 0);
3018        // A paragraph of page breaks alone keeps its first line at the start.
3019        let only = [Piece::PageBreak, Piece::PageBreak];
3020        for leading in [LeadingBreaks::First, LeadingBreaks::All] {
3021            let lines = break_lines(&only, &narrow_first(leading));
3022            assert_eq!(Line::first_index(&lines, leading), 0);
3023        }
3024    }
3025
3026    #[test]
3027    fn keeps_an_empty_line_after_a_column_break_that_ends_the_pieces() {
3028        let mut pieces = glyphs("a");
3029        pieces.push(Piece::ColumnBreak);
3030        let lines = break_lines(&pieces, &frame(100));
3031        assert_eq!(texts(&lines), vec!["a", ""]);
3032        assert_eq!(lines[0].end, LineEnd::ColumnBreak);
3033        // A page break at the end leaves no empty line.
3034        let mut pieces = glyphs("a");
3035        pieces.push(Piece::PageBreak);
3036        assert_eq!(break_lines(&pieces, &frame(100)).len(), 1);
3037    }
3038
3039    #[test]
3040    fn gives_back_the_pieces_of_lines_with_their_breaks() {
3041        let mut pieces = glyphs("aaa bbb");
3042        pieces.push(Piece::LineBreak(Some(FaceIndex::nth(1))));
3043        pieces.extend(glyphs("ccc"));
3044        pieces.push(Piece::PageBreak);
3045        pieces.extend(glyphs("ddd"));
3046        let lines = break_lines(&pieces, &frame(100));
3047        assert_eq!(lines[0].end, LineEnd::Break(Some(FaceIndex::nth(1))));
3048        assert_eq!(lines[1].end, LineEnd::PageBreak);
3049        let again = Line::pieces(&lines);
3050        assert_eq!(again, pieces);
3051        // Broken again in a narrower frame, the explicit breaks stay.
3052        let narrow = break_lines(&again, &frame(40));
3053        assert_eq!(texts(&narrow), vec!["aaa ", "bbb", "ccc", "ddd"]);
3054        assert_eq!(narrow[1].end, LineEnd::Break(Some(FaceIndex::nth(1))));
3055        assert_eq!(narrow[2].end, LineEnd::PageBreak);
3056    }
3057
3058    #[test]
3059    fn stretches_only_spaces_after_the_last_tab_and_the_first_glyph() {
3060        let line = |pieces: &[Piece]| break_lines(pieces, &frame(1000)).remove(0);
3061        assert_eq!(line(&glyphs("  a b")).first_stretched(), 2);
3062        assert_eq!(line(&glyphs("a b")).first_stretched(), 0);
3063        let mut pieces = glyphs("a b");
3064        pieces.push(Piece::Tab(None));
3065        pieces.extend(glyphs(" c d"));
3066        // "a b", the tab and the space after it keep their widths.
3067        assert_eq!(line(&pieces).first_stretched(), 5);
3068    }
3069
3070    #[test]
3071    fn moves_a_tab_down_with_the_word_after_it() {
3072        let mut pieces = glyphs("aaaa");
3073        pieces.push(Piece::Tab(None));
3074        pieces.extend(glyphs("bbbbbb"));
3075        let lines = break_lines(&pieces, &frame(100));
3076        assert_eq!(texts(&lines), vec!["aaaa", "|bbbbbb"]);
3077        assert_eq!(lines[1].placed[0].advance, Length::from_units(25));
3078        assert_eq!(lines[1].placed[1].x, Length::from_units(25));
3079        // A tab alone on its line stays there.
3080        let mut alone = vec![Piece::Tab(None)];
3081        alone.extend(glyphs(&"c".repeat(12)));
3082        let lines = break_lines(&alone, &frame(100));
3083        assert_eq!(texts(&lines)[0], "|");
3084    }
3085
3086    #[test]
3087    fn starts_a_new_line_with_a_tab_whose_default_stop_lies_past_the_end() {
3088        // Default stops every 25 units in a line of 60: after "aa" the tabs go to 25 and 50,
3089        // and the third one, whose stop at 75 lies past the end, starts the next line. The
3090        // space after it follows it there.
3091        let mut pieces = glyphs("aa");
3092        pieces.extend([Piece::Tab(None); 3]);
3093        pieces.extend(glyphs(" bb"));
3094        let lines = break_lines(&pieces, &frame(60));
3095        assert_eq!(texts(&lines), vec!["aa||", "| bb"]);
3096        assert_eq!(lines[1].placed[2].x, Length::from_units(35));
3097        // A stop at the end itself still holds the tab.
3098        let mut pieces = glyphs("a");
3099        pieces.extend([Piece::Tab(None); 2]);
3100        let lines = break_lines(&pieces, &frame(50));
3101        assert_eq!(texts(&lines), vec!["a||"]);
3102        // Spaces may run past the end, but a tab after them starts the next line.
3103        let mut pieces = glyphs("aaaa      ");
3104        pieces.push(Piece::Tab(None));
3105        let lines = break_lines(&pieces, &frame(60));
3106        assert_eq!(texts(&lines), vec!["aaaa      ", "|"]);
3107    }
3108
3109    #[test]
3110    fn aligns_text_at_right_center_and_decimal_stops() {
3111        let stop = |position, kind| TabStop {
3112            position: Length::from_units(position),
3113            kind,
3114            leader: Some('.'),
3115        };
3116        let mut f = frame(500);
3117        let mut run = |kind, text: &str| {
3118            f.tabs = Tabs::new([stop(200, kind)], Length::from_units(25), None);
3119            let mut pieces = glyphs("a");
3120            pieces.push(Piece::Tab(None));
3121            pieces.extend(glyphs(text));
3122            let lines = break_lines(&pieces, &f);
3123            (
3124                lines[0].placed[1].advance.units(),
3125                lines[0].placed[1].leader,
3126            )
3127        };
3128        assert_eq!(run(TabKind::Right, "bcd "), (160, Some('.')));
3129        assert_eq!(run(TabKind::Center, "bcd"), (175, Some('.')));
3130        assert_eq!(run(TabKind::Decimal, "12.5"), (170, Some('.')));
3131        assert_eq!(run(TabKind::Decimal, "125"), (160, Some('.')));
3132        assert_eq!(run(TabKind::Right, &"x".repeat(30)), (0, Some('.')));
3133    }
3134
3135    #[test]
3136    fn ends_text_after_a_center_or_decimal_stop_at_the_line_end_where_the_quirk_says() {
3137        let (past, ends) = (
3138            AlignedTabOverrun::RunsPast,
3139            AlignedTabOverrun::EndsAtAreaEnd,
3140        );
3141        // Centered on the stop, the text would end at 105, past the line's end at 100.
3142        assert!(aligned_tab(TabKind::Center, 80, "bcdef", past, 0).0 > 1);
3143        assert_eq!(
3144            aligned_tab(TabKind::Center, 80, "bcdef", ends, 0),
3145            (1, Some(40))
3146        );
3147        // With its point at the stop, the text would end at 120.
3148        assert!(aligned_tab(TabKind::Decimal, 80, "12.345", past, 0).0 > 1);
3149        assert_eq!(
3150            aligned_tab(TabKind::Decimal, 80, "12.345", ends, 0),
3151            (1, Some(30))
3152        );
3153        // Text that ends inside the line keeps its place at the stop.
3154        assert_eq!(
3155            aligned_tab(TabKind::Center, 80, "bc", ends, 0),
3156            (1, Some(60))
3157        );
3158    }
3159
3160    #[test]
3161    fn ends_text_after_a_stop_past_the_line_end_at_the_line_end_where_the_quirk_says() {
3162        let ends = AlignedTabOverrun::EndsAtAreaEnd;
3163        assert_eq!(
3164            aligned_tab(TabKind::Center, 120, "bc", ends, 0),
3165            (1, Some(70))
3166        );
3167        assert_eq!(
3168            aligned_tab(TabKind::Right, 120, "bc", ends, 0),
3169            (1, Some(70))
3170        );
3171    }
3172
3173    #[test]
3174    fn wraps_only_the_last_trailing_tab_with_a_word_that_does_not_fit() {
3175        let stop = |position, kind| TabStop {
3176            position: Length::from_units(position),
3177            kind,
3178            leader: None,
3179        };
3180        // Line width 100, default stops every 50, center stop at 40 and right stop at 80.
3181        let mut f = frame(100);
3182        f.tabs = Tabs::new(
3183            [stop(40, TabKind::Center), stop(80, TabKind::Right)],
3184            Length::from_units(50),
3185            None,
3186        );
3187        // Tabs-only line: Tab1(40), Tab2(80), Tab3(100=end) before "ab" -> only Tab3 wraps to
3188        // line 2, centering "ab" (width 20) on 40 so "ab" starts at 30.
3189        let mut pieces = vec![Piece::Tab(None), Piece::Tab(None), Piece::Tab(None)];
3190        pieces.extend(glyphs("ab"));
3191        let lines = break_lines(&pieces, &f);
3192        assert_eq!(
3193            (lines.len(), lines[0].placed.len(), lines[1].placed[1].x),
3194            (2, 2, Length::from_units(30)),
3195        );
3196
3197        // Mixed line with two left stops (80, then default 100=end): "a" + Tab1(80) + Tab2(100)
3198        // before "bc" -> only Tab2 wraps, placing "bc" at 80 (not 100).
3199        let mut f2 = frame(100);
3200        f2.tabs = Tabs::new([stop(80, TabKind::Left)], Length::from_units(20), None);
3201        let mut pieces2 = glyphs("a");
3202        pieces2.push(Piece::Tab(None));
3203        pieces2.push(Piece::Tab(None));
3204        pieces2.extend(glyphs("bc"));
3205        let lines2 = break_lines(&pieces2, &f2);
3206        assert_eq!(
3207            (lines2.len(), lines2[0].placed.len(), lines2[1].placed[1].x),
3208            (2, 2, Length::from_units(80)),
3209        );
3210
3211        // Single tab alone on a line stays on line 1 so line 1 is not emptied.
3212        let mut f3 = frame(100);
3213        f3.tabs = Tabs::new([stop(100, TabKind::Left)], Length::from_units(50), None);
3214        let mut pieces3 = vec![Piece::Tab(None)];
3215        pieces3.extend(glyphs("ab"));
3216        let lines3 = break_lines(&pieces3, &f3);
3217        assert_eq!(
3218            (lines3.len(), lines3[0].placed.len(), lines3[1].placed[0].x),
3219            (2, 1, Length::ZERO),
3220        );
3221    }
3222
3223    #[test]
3224    fn takes_the_text_area_end_as_the_limit_of_a_stop_beside_a_right_indent() {
3225        let ends = AlignedTabOverrun::EndsAtAreaEnd;
3226        // Beside a right indent of 20, the limit after a stop before the line's end at 80 is
3227        // that end; after a stop between it and the text area's end at 100, it is the area's
3228        // end; and after a stop past the area, it is the line's end again.
3229        assert_eq!(
3230            aligned_tab(TabKind::Center, 70, "bcd", ends, 20),
3231            (1, Some(40))
3232        );
3233        assert_eq!(
3234            aligned_tab(TabKind::Center, 90, "bcd", ends, 20),
3235            (1, Some(60))
3236        );
3237        assert_eq!(
3238            aligned_tab(TabKind::Center, 90, "bcdefgh", ends, 20),
3239            (1, Some(20))
3240        );
3241        assert_eq!(
3242            aligned_tab(TabKind::Center, 120, "bc", ends, 20),
3243            (1, Some(50))
3244        );
3245        // Text wider than the area after the tab's start goes to the next line with the tab.
3246        assert!(aligned_tab(TabKind::Center, 90, "bcdefghijk", ends, 20).0 > 1);
3247    }
3248
3249    #[test]
3250    fn keeps_text_after_a_stop_past_the_line_end_at_the_stop_where_the_mode_says() {
3251        let older = (AlignedTabOverrun::EndsAtAreaEnd, false);
3252        // A center stop past the line's end keeps its text centered on the stop, on the line.
3253        assert_eq!(
3254            aligned_tab_in(TabKind::Center, 120, "bcde", older, 0),
3255            (1, Some(90))
3256        );
3257        // So does a stop exactly at the line's end, and a right stop past it.
3258        assert_eq!(
3259            aligned_tab_in(TabKind::Center, 100, "bcdefg", older, 0),
3260            (1, Some(60))
3261        );
3262        assert_eq!(
3263            aligned_tab_in(TabKind::Right, 130, "bc", older, 0),
3264            (1, Some(100))
3265        );
3266        // A stop before the line's end still ends its text at the line's end.
3267        assert_eq!(
3268            aligned_tab_in(TabKind::Center, 80, "bcdef", older, 0),
3269            (1, Some(40))
3270        );
3271    }
3272
3273    /// The number of lines of a line of 100 less `indent` in a text area of 100 that holds `a`,
3274    /// a tab to one stop of `kind` at `position` and `text`, and the tab's advance.
3275    fn aligned_tab(
3276        kind: TabKind,
3277        position: i64,
3278        text: &str,
3279        overrun: AlignedTabOverrun,
3280        indent: i64,
3281    ) -> (usize, Option<i64>) {
3282        aligned_tab_in(kind, position, text, (overrun, true), indent)
3283    }
3284
3285    /// As [`aligned_tab`], with the frame's `limits_past_end` beside the quirk.
3286    fn aligned_tab_in(
3287        kind: TabKind,
3288        position: i64,
3289        text: &str,
3290        (overrun, limits_past_end): (AlignedTabOverrun, bool),
3291        indent: i64,
3292    ) -> (usize, Option<i64>) {
3293        let mut f = frame(100 - indent);
3294        f.area_width = Length::from_units(100);
3295        f.breaking.ends_aligned_text = overrun == AlignedTabOverrun::EndsAtAreaEnd;
3296        f.limits_past_end = limits_past_end;
3297        let stop = TabStop {
3298            position: Length::from_units(position),
3299            kind,
3300            leader: None,
3301        };
3302        f.tabs = Tabs::new([stop], Length::from_units(25), None);
3303        let mut pieces = glyphs("a");
3304        pieces.push(Piece::Tab(None));
3305        pieces.extend(glyphs(text));
3306        let lines = break_lines(&pieces, &f);
3307        let tab = lines
3308            .first()
3309            .and_then(|line| line.placed.get(1))
3310            .map(|placed| placed.advance.units());
3311        (lines.len(), tab)
3312    }
3313
3314    #[test]
3315    fn runs_on_to_a_right_stop_past_the_line_end() {
3316        let stop = |kind| TabStop {
3317            position: Length::from_units(120),
3318            kind,
3319            leader: None,
3320        };
3321        let line = |kind, after: &str| {
3322            // The text starts 10 after the column edge, so the line ends at 110.
3323            let mut f = frame(100);
3324            f.first_start = Length::from_units(10);
3325            f.tabs = Tabs::new([stop(kind)], Length::from_units(25), None);
3326            let mut pieces = glyphs("aaaa");
3327            pieces.push(Piece::Tab(None));
3328            pieces.extend(glyphs(after));
3329            texts(&break_lines(&pieces, &f))
3330        };
3331        assert_eq!(line(TabKind::Right, "bb"), ["aaaa|bb"]);
3332        // The room ends at the stop.
3333        assert_eq!(
3334            line(TabKind::Right, "bb cccccccc"),
3335            ["aaaa|bb ", "cccccccc"]
3336        );
3337        // Text after a left stop starts at the stop, so it cannot fit before it.
3338        assert_ne!(line(TabKind::Left, "bb"), ["aaaa|bb"]);
3339    }
3340
3341    #[test]
3342    fn empty_paragraph_has_one_line() {
3343        let lines = break_lines(&[], &frame(100));
3344        assert_eq!(lines.len(), 1);
3345        assert_eq!(lines[0].width(), Length::ZERO);
3346        assert!(!is_space(&Piece::LineBreak(None)));
3347    }
3348
3349    #[test]
3350    fn an_object_wider_than_the_line_ends_its_paragraph_on_that_line() {
3351        let wide = Piece::Object {
3352            width: Length::from_units(150),
3353            height: Length::from_units(50),
3354            raised: Length::ZERO,
3355            picture: None,
3356            drawing: None,
3357            underlined: false,
3358            run_face: None,
3359            joins_before: false,
3360        };
3361        assert_eq!(texts(&break_lines(&[wide], &frame(100))), ["|"]);
3362        // Text after it goes to the next line, and an overlong word still breaks inside.
3363        let mut pieces = vec![wide];
3364        pieces.extend(glyphs("aa"));
3365        assert_eq!(texts(&break_lines(&pieces, &frame(100))), ["|", "aa"]);
3366        assert_eq!(
3367            texts(&break_lines(&glyphs("abcdefghijkl"), &frame(100))),
3368            ["abcdefghij", "kl"]
3369        );
3370    }
3371
3372    #[test]
3373    fn punctuation_shrinks_up_to_r_times_the_stretch_per_gap_of_the_shorter_line() {
3374        let compression = super::Compression {
3375            ratio: 32,
3376            middle_dot: false,
3377            trailing_trim: super::TrailingTrim::None,
3378        };
3379        let u = Length::from_units;
3380        let halves = |count| super::Halves {
3381            count,
3382            em: u(1_000),
3383        };
3384        // A line of 21 characters with 10 blank halves that ends with an ideograph: at 0.940 em
3385        // the shorter line leaves 0.060 em over 19 gaps, and the line may run 1.010 em past;
3386        // at 0.945 em only 0.926 em.
3387        assert_eq!(compression.over(halves(10), (u(60), 19)), u(1_010));
3388        assert_eq!(compression.over(halves(10), (u(55), 19)), u(926));
3389        // With a closing mark at the end, its blank half counts as an eleventh: 0.1 em of room
3390        // gives 1.852 em.
3391        assert_eq!(compression.over(halves(11), (u(100), 19)), u(1_852));
3392        // A half shrinks by its own width at most.
3393        assert_eq!(compression.over(halves(1), (u(900), 2)), u(500));
3394        assert_eq!(compression.over(halves(10), (u(60), 0)), Length::ZERO);
3395    }
3396
3397    #[test]
3398    fn a_justified_line_takes_one_more_character_when_its_halves_may_shrink() {
3399        let pieces = glyphs("永、永、永、永永永");
3400        let frame = |width, compressing: bool| Frame {
3401            kinsoku: Some(crate::kinsoku::Kinsoku::FREE),
3402            punctuation: compressing.then_some(super::Compression {
3403                ratio: 32,
3404                middle_dot: false,
3405                trailing_trim: super::TrailingTrim::None,
3406            }),
3407            ..frame(width)
3408        };
3409        // The eighth character needs 9, and the three blank halves may give up their 15,
3410        // because the shorter line would stretch its 6 gaps by 1 in all. With no room, the
3411        // line takes nothing.
3412        assert_eq!(
3413            texts(&break_lines(&pieces, &frame(71, true))),
3414            ["永、永、永、永永", "永"]
3415        );
3416        assert_eq!(
3417            texts(&break_lines(&pieces, &frame(70, true))),
3418            ["永、永、永、永", "永永"]
3419        );
3420        assert_eq!(
3421            texts(&break_lines(&pieces, &frame(71, false))),
3422            ["永、永、永、永", "永永"]
3423        );
3424    }
3425
3426    #[test]
3427    fn japanese_middle_dot_carries_a_blank_half_only_when_middle_dot_is_enabled() {
3428        let pieces = glyphs("所属・役職");
3429        let make = |middle_dot| Frame {
3430            kinsoku: Some(crate::kinsoku::Kinsoku::FREE),
3431            punctuation: Some(super::Compression {
3432                ratio: 32,
3433                middle_dot,
3434                trailing_trim: super::TrailingTrim::None,
3435            }),
3436            ..frame(46)
3437        };
3438        assert_eq!(texts(&break_lines(&pieces, &make(true))), ["所属・役職"]);
3439        assert_eq!(
3440            texts(&break_lines(&pieces, &make(false))),
3441            ["所属・役", "職"]
3442        );
3443    }
3444
3445    #[test]
3446    fn punctuation_compression_ignores_marks_before_tab() {
3447        let u = Length::from_units;
3448        let mut before_tab = glyphs("一、");
3449        before_tab.push(Piece::Tab(None));
3450        before_tab.extend(glyphs("甲乙丙"));
3451        let compressed = Frame {
3452            kinsoku: Some(crate::kinsoku::Kinsoku::FREE),
3453            punctuation: Some(super::Compression {
3454                ratio: 32,
3455                middle_dot: false,
3456                trailing_trim: super::TrailingTrim::None,
3457            }),
3458            tabs: crate::tabs::Tabs::new([], u(40), None),
3459            ..frame(66)
3460        };
3461        assert_eq!(
3462            texts(&break_lines(&before_tab, &compressed)),
3463            ["一、|甲乙", "丙"]
3464        );
3465
3466        // Punctuation inside a list label without a tab (`g.label == true`) also carries no
3467        // compressible blank half.
3468        let mut labeled = glyphs("一、甲乙丙");
3469        for i in 0..2 {
3470            if let Some(Piece::Glyph(g)) = labeled.get_mut(i) {
3471                g.label = true;
3472            }
3473        }
3474        assert_eq!(
3475            texts(&break_lines(
3476                &labeled,
3477                &Frame {
3478                    tabs: crate::tabs::Tabs::new([], u(40), None),
3479                    ..Frame {
3480                        width: u(46),
3481                        first_width: u(46),
3482                        ..compressed
3483                    }
3484                }
3485            )),
3486            ["一、甲乙", "丙"]
3487        );
3488    }
3489
3490    #[test]
3491    fn trailing_auto_space_is_dropped_at_line_end_but_kept_inside_line() {
3492        let u = Length::from_units;
3493        // 3 glyphs of advance 10, with glyph[1] carrying trailing_auto_space = 3 (advance 13).
3494        let mut pieces = glyphs("甲8壬");
3495        if let Some(Piece::Glyph(g)) = pieces.get_mut(1) {
3496            g.advance = u(13);
3497            g.auto_space = u(3);
3498            g.trailing_auto_space = u(3);
3499        }
3500        // Width 20 fits "甲8" once trailing auto-space (3) is dropped at line end, and strips
3501        // the trailing gap from the placed glyph so line.width() == 20.
3502        let wrapped = break_lines(&pieces, &frame(20));
3503        assert_eq!(texts(&wrapped), ["甲8", "壬"]);
3504        assert_eq!(wrapped[0].width(), u(20));
3505        if let Some(Piece::Glyph(g)) = wrapped[0].placed.get(1).map(|p| p.piece) {
3506            assert_eq!(
3507                (g.advance, g.auto_space, g.trailing_auto_space),
3508                (u(10), u(0), u(0))
3509            );
3510        }
3511        // Width 33 keeps all 3 glyphs on one line and retains the 3-unit auto-space inside.
3512        let single = break_lines(&pieces, &frame(33));
3513        assert_eq!(texts(&single), ["甲8壬"]);
3514        assert_eq!(single[0].width(), u(33));
3515    }
3516
3517    #[test]
3518    fn punctuation_compression_ignores_closed_kerned_halves() {
3519        let u = Length::from_units;
3520        let pair_frame = |width| Frame {
3521            kinsoku: Some(crate::kinsoku::Kinsoku::FREE),
3522            punctuation: Some(super::Compression {
3523                ratio: 32,
3524                middle_dot: false,
3525                trailing_trim: super::TrailingTrim::None,
3526            }),
3527            ..frame(width)
3528        };
3529        let mut pair = glyphs("甲」,乙");
3530        if let Some(Piece::Glyph(close)) = pair.get_mut(1) {
3531            close.advance = u(5);
3532            close.punctuation_half = crate::text::PunctuationHalf::Closed;
3533        }
3534        assert_eq!(texts(&break_lines(&pair, &pair_frame(30))), ["甲」,乙"]);
3535        assert_eq!(
3536            texts(&break_lines(&pair, &pair_frame(28))),
3537            ["甲」,", "乙"]
3538        );
3539
3540        let mut opens = glyphs("甲「「乙");
3541        if let Some(Piece::Glyph(first)) = opens.get_mut(1) {
3542            first.advance = u(5);
3543            first.punctuation_half = crate::text::PunctuationHalf::OpenShortened(u(5));
3544        }
3545        if let Some(Piece::Glyph(second)) = opens.get_mut(2) {
3546            second.punctuation_half = crate::text::PunctuationHalf::Closed;
3547        }
3548        assert_eq!(texts(&break_lines(&opens, &pair_frame(30))), ["甲「「乙"]);
3549        assert_eq!(
3550            texts(&break_lines(&opens, &pair_frame(28))),
3551            ["甲「「", "乙"]
3552        );
3553    }
3554
3555    #[test]
3556    fn trailing_closing_trim_fits_half_em_overrun_by_script() {
3557        let make = |width, trailing_trim| Frame {
3558            kinsoku: Some(crate::kinsoku::Kinsoku::of(
3559                crate::props::EastAsianScript::Simplified,
3560            )),
3561            punctuation: Some(super::Compression {
3562                ratio: 0,
3563                middle_dot: false,
3564                trailing_trim,
3565            }),
3566            ..frame(width)
3567        };
3568        // Each glyph has advance 10; 10 kanji + closing mark = 110, half-trimmed = 105.
3569        let comma = glyphs("漢漢漢漢漢漢漢漢漢漢、後");
3570        assert_eq!(
3571            texts(&break_lines(
3572                &comma,
3573                &make(105, super::TrailingTrim::Closing)
3574            )),
3575            ["漢漢漢漢漢漢漢漢漢漢、", "後"]
3576        );
3577        assert_eq!(
3578            texts(&break_lines(
3579                &comma,
3580                &make(104, super::TrailingTrim::Closing)
3581            )),
3582            ["漢漢漢漢漢漢漢漢漢", "漢、後"]
3583        );
3584        assert_eq!(
3585            texts(&break_lines(&comma, &make(105, super::TrailingTrim::None))),
3586            ["漢漢漢漢漢漢漢漢漢", "漢、後"]
3587        );
3588        // Japanese centers `;` (no trailing blank half), while Simplified Chinese trims it.
3589        let semi = glyphs("漢漢漢漢漢漢漢漢漢漢;後");
3590        assert_eq!(
3591            texts(&break_lines(
3592                &semi,
3593                &make(105, super::TrailingTrim::Closing)
3594            )),
3595            ["漢漢漢漢漢漢漢漢漢漢;", "後"]
3596        );
3597        assert_eq!(
3598            texts(&break_lines(
3599                &semi,
3600                &make(105, super::TrailingTrim::NonJapaneseCentered)
3601            )),
3602            ["漢漢漢漢漢漢漢漢漢", "漢;後"]
3603        );
3604    }
3605
3606    #[test]
3607    fn overflow_punct_hangs_single_trailing_mark_and_ends_line() {
3608        use crate::kinsoku::Kinsoku;
3609        use crate::props::EastAsianScript;
3610        let cn = Kinsoku::of(EastAsianScript::Simplified);
3611        let ja = Kinsoku::of(EastAsianScript::Japanese);
3612        let free = Kinsoku::FREE.with_hanging_of(cn);
3613        for (text, kinsoku, want_texts, want_hung) in [
3614            (
3615                "漢漢漢漢漢漢漢漢漢漢、後",
3616                cn,
3617                &["漢漢漢漢漢漢漢漢漢漢、", "後"][..],
3618                true,
3619            ),
3620            (
3621                "漢漢漢漢漢漢漢漢漢漢、。後",
3622                cn,
3623                &["漢漢漢漢漢漢漢漢漢", "漢、。後"][..],
3624                false,
3625            ),
3626            (
3627                "漢漢漢漢漢漢漢漢漢漢、後",
3628                free,
3629                &["漢漢漢漢漢漢漢漢漢漢、", "後"][..],
3630                true,
3631            ),
3632            (
3633                "漢漢漢漢漢漢漢漢漢漢;後",
3634                ja,
3635                &["漢漢漢漢漢漢漢漢漢", "漢;後"][..],
3636                false,
3637            ),
3638            (
3639                "漢漢漢漢漢漢漢漢漢漢、",
3640                cn,
3641                &["漢漢漢漢漢漢漢漢漢漢、"][..],
3642                true,
3643            ),
3644        ] {
3645            let f = Frame {
3646                kinsoku: Some(kinsoku),
3647                overflow_punct: super::OverflowPunct::Hang,
3648                ..frame(102)
3649            };
3650            let lines = break_lines(&glyphs(text), &f);
3651            assert_eq!(texts(&lines), want_texts, "{text}");
3652            assert_eq!(lines.first().is_some_and(|l| l.hung), want_hung, "{text}");
3653            assert!(lines.iter().all(|l| !l.would_hang), "{text}");
3654        }
3655    }
3656
3657    #[test]
3658    fn closes_up_pairs_after_a_blank_right_half_or_before_an_opening_mark() {
3659        use crate::props::EastAsianScript::{Japanese, Simplified, Traditional};
3660        let check = |script, yes: &[&str], no: &[&str]| {
3661            let kerned = |pair: &str| {
3662                let mut chars = pair.chars();
3663                super::kerned_pair(chars.next().unwrap(), chars.next().unwrap(), script).is_some()
3664            };
3665            assert!(yes.iter().all(|pair| kerned(pair)));
3666            assert!(no.iter().all(|pair| !kerned(pair)));
3667        };
3668        check(
3669            Some(Japanese),
3670            &[
3671                "。」", ",(", "」「", ")。", "。。", "、、", ":「", "・(", "((", ")・",
3672            ],
3673            &[
3674                "!,", "!(", ")!", "!?", "?(", ")?", "::", "・・",
3675            ],
3676        );
3677        check(
3678            Some(Simplified),
3679            &[
3680                "!,", "!(", "!!", ")!", ":,", "::", ";;", ",,",
3681            ],
3682            &[
3683                "!?", "?(", ")?", "・(", ")・", "测(", ")测", "」a",
3684            ],
3685        );
3686        check(
3687            Some(Traditional),
3688            &["),", "。「", ":(", "):", "、("],
3689            &[",,", ",。", "。、", "!,", "!(", "・(", "?("],
3690        );
3691        check(None, &[")【", "】)"], &["),", "。「"]);
3692    }
3693
3694    #[test]
3695    fn a_tab_to_a_left_stop_past_the_line_end_starts_the_next_line_and_ends_at_its_end() {
3696        // A line 100 wide, a left stop at 120, and "a", a tab and "b", each glyph 10 wide.
3697        let stop = TabStop {
3698            position: Length::from_units(120),
3699            kind: TabKind::Left,
3700            leader: None,
3701        };
3702        let lay_out = |rule| {
3703            let mut f = frame(100);
3704            f.tabs = Tabs::new([stop], Length::from_units(25), None);
3705            f.breaking.left_stops_to_line_end = rule == LeftStopPastEnd::ToLineEnd;
3706            let mut pieces = glyphs("a");
3707            pieces.push(Piece::Tab(None));
3708            pieces.extend(glyphs("b"));
3709            let lines = break_lines(&pieces, &f);
3710            let tab = lines
3711                .iter()
3712                .flat_map(|line| &line.placed)
3713                .find(|placed| matches!(placed.piece, Piece::Tab(_)))
3714                .map(|placed| (placed.x.units(), placed.advance.units()));
3715            (texts(&lines), tab)
3716        };
3717        // To the stop: the tab goes to the next line with "b", and the line runs on to the
3718        // stop past its end.
3719        let (texts_to_stop, tab_to_stop) = lay_out(LeftStopPastEnd::ToStop);
3720        assert_eq!(texts_to_stop, ["a", "|b"]);
3721        assert_eq!(tab_to_stop, Some((0, 120)));
3722        // To the line's end: the tab starts the next line, fills it, and "b" follows below.
3723        let (texts_to_end, tab_to_end) = lay_out(LeftStopPastEnd::ToLineEnd);
3724        assert_eq!(texts_to_end, ["a", "|", "b"]);
3725        assert_eq!(tab_to_end, Some((0, 100)));
3726    }
3727
3728    #[test]
3729    fn a_tab_to_a_left_stop_inside_the_line_keeps_its_place_on_both_variants() {
3730        let stop = TabStop {
3731            position: Length::from_units(80),
3732            kind: TabKind::Left,
3733            leader: None,
3734        };
3735        for rule in [LeftStopPastEnd::ToStop, LeftStopPastEnd::ToLineEnd] {
3736            let mut f = frame(100);
3737            f.tabs = Tabs::new([stop], Length::from_units(25), None);
3738            f.breaking.left_stops_to_line_end = rule == LeftStopPastEnd::ToLineEnd;
3739            let mut pieces = glyphs("a");
3740            pieces.push(Piece::Tab(None));
3741            pieces.extend(glyphs("b"));
3742            assert_eq!(texts(&break_lines(&pieces, &f)), ["a|b"], "{rule:?}");
3743        }
3744    }
3745
3746    #[test]
3747    fn a_tab_to_a_hanging_indent_past_the_line_end_runs_on_on_both_variants() {
3748        // A line 100 wide whose hanging indent, at 120, is the next stop of the tab after "a".
3749        let lay_out = |rule| {
3750            let mut f = frame(100);
3751            f.tabs = Tabs::new([], Length::from_units(25), Some(Length::from_units(120)));
3752            f.breaking.left_stops_to_line_end = rule == LeftStopPastEnd::ToLineEnd;
3753            let mut pieces = glyphs("a");
3754            pieces.push(Piece::Tab(None));
3755            pieces.extend(glyphs("b"));
3756            texts(&break_lines(&pieces, &f))
3757        };
3758        assert_eq!(
3759            lay_out(LeftStopPastEnd::ToLineEnd),
3760            lay_out(LeftStopPastEnd::ToStop)
3761        );
3762    }
3763
3764    #[test]
3765    fn overflow_punct_uses_mark_run_east_asian_language() {
3766        use crate::kinsoku::Kinsoku;
3767        use crate::props::{EastAsianLanguage, EastAsianScript};
3768        let tag = |text: &str, lang: Option<EastAsianLanguage>| -> Vec<Piece> {
3769            glyphs(text)
3770                .into_iter()
3771                .map(|p| match p {
3772                    Piece::Glyph(mut g) => {
3773                        g.east_asian_language = lang;
3774                        Piece::Glyph(g)
3775                    }
3776                    other => other,
3777                })
3778                .collect()
3779        };
3780        let cn = Some(EastAsianLanguage::Script(EastAsianScript::Simplified));
3781        let ko = Some(EastAsianLanguage::Script(EastAsianScript::Korean));
3782        let non_ea = Some(EastAsianLanguage::NonEastAsian);
3783        let f_cn = Frame {
3784            kinsoku: Some(Kinsoku::of(EastAsianScript::Simplified)),
3785            overflow_punct: super::OverflowPunct::Hang,
3786            ..frame(100)
3787        };
3788        // Non-East-Asian run inside a zh-CN paragraph does not hang or pull the preceding char.
3789        let non_ea_lines = break_lines(&tag("甲乙丙丁戊己庚辛壬癸、异", non_ea), &f_cn);
3790        assert_eq!(texts(&non_ea_lines), ["甲乙丙丁戊己庚辛壬癸", "、异"]);
3791        assert!(!non_ea_lines[0].hung);
3792        // zh-CN run inside a non-EA paragraph hangs the mark.
3793        let f_free = Frame {
3794            kinsoku: Some(Kinsoku::FREE.with_restricted(true)),
3795            overflow_punct: super::OverflowPunct::Hang,
3796            ..frame(100)
3797        };
3798        let ea_lines = break_lines(&tag("甲乙丙丁戊己庚辛壬癸、异", cn), &f_free);
3799        assert_eq!(texts(&ea_lines), ["甲乙丙丁戊己庚辛壬癸、", "异"]);
3800        assert!(ea_lines[0].hung);
3801        // Korean word followed by space hangs trailing comma even with kinsoku == None (wordWrap on).
3802        let f_ko = Frame {
3803            kinsoku: None,
3804            overflow_punct: super::OverflowPunct::Hang,
3805            ..frame(100)
3806        };
3807        let ko_lines = break_lines(&tag("가나다라마바사아자차, 카타", ko), &f_ko);
3808        assert_eq!(texts(&ko_lines), ["가나다라마바사아자차, ", "카타"]);
3809        assert!(ko_lines[0].hung);
3810    }
3811
3812    #[test]
3813    fn overflow_punct_allows_space_shrink_before_hang() {
3814        use crate::kinsoku::Kinsoku;
3815        use crate::props::EastAsianScript;
3816        let f = Frame {
3817            kinsoku: Some(Kinsoku::of(EastAsianScript::Simplified)),
3818            overflow_punct: super::OverflowPunct::Hang,
3819            shrink: Shrink {
3820                permille: 250,
3821                ..Shrink::default()
3822            },
3823            ..frame(98)
3824        };
3825        // "aaa bbb cc" is 100 units (2 spaces of 10 -> up to 5 units shrink -> fits in 98),
3826        // and trailing ',' overflows -> hangs with shrunk spaces.
3827        let lines = break_lines(&glyphs("aaa bbb cc, next"), &f);
3828        assert_eq!(texts(&lines), ["aaa bbb cc, ", "next"]);
3829        assert!(lines[0].hung);
3830    }
3831}