f-office-docx 0.2.3

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

use std::borrow::Cow;

use f_office_units::Length;
use unicode_bidi::{BidiClass, BidiInfo, Level, bidi_class};

use crate::lines::{Line, Piece, is_space, right_to_left, run_glyph, run_rtl};
use crate::props::BidiLanguageClass;

/// The character that stands for a piece in the algorithm: its own for a glyph, a tab for a
/// tab, and the object replacement character, a neutral, for anything else.
fn char_of(piece: &Piece) -> char {
    match piece {
        Piece::Glyph(glyph) => glyph.ch,
        Piece::Tab(_) | Piece::PositionTab(..) => '\t',
        _ => '\u{FFFC}',
    }
}

/// The strong character that stands for a piece in the algorithm, in place of its own. The
/// direction of a run gives it before UAX 9 resolves weak and neutral types, and a stand-in
/// changes no drawn glyph.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Stand {
    /// The piece's own character.
    Own,
    /// A left-to-right mark: the piece takes the direction of its run without `w:rtl`.
    Left,
    /// A right-to-left mark: the piece takes the direction of its run with `w:rtl`.
    Right,
}

impl Stand {
    /// The character of `piece` for the algorithm. A right-to-left mark after an Arabic
    /// letter (`arabic`) is the Arabic letter mark, so that a number after it keeps the
    /// class that UAX 9 (W2) gives a number after an Arabic letter.
    fn char_of(self, piece: &Piece, arabic: bool) -> char {
        match self {
            Self::Own => char_of(piece),
            Self::Left => '\u{200E}',
            Self::Right => right_mark(arabic),
        }
    }
}

/// The mark that stands for a right-to-left character: the Arabic letter mark after an
/// Arabic letter, and the right-to-left mark elsewhere.
fn right_mark(arabic: bool) -> char {
    if arabic {
        ARABIC_LETTER_MARK
    } else {
        '\u{200F}'
    }
}

/// The Arabic letter mark: a character without a glyph that has the class of an Arabic
/// letter.
const ARABIC_LETTER_MARK: char = '\u{061C}';

/// Whether the last strong character is an Arabic letter after `ch`, when it was `arabic`
/// before it.
fn arabic_after(arabic: bool, ch: char) -> bool {
    match bidi_class(ch) {
        BidiClass::AL => true,
        BidiClass::L | BidiClass::R => false,
        _ => arabic,
    }
}

/// The class of the bidi language of a piece that is text of a run with `w:rtl`.
fn run_class(piece: &Piece) -> Option<BidiLanguageClass> {
    run_glyph(piece).and_then(|glyph| glyph.direction.class())
}

/// The character that stands for a piece of a sequence of runs with `w:rtl` when the
/// algorithm resolves the sequence alone. A slash of a run whose bidi language makes it a
/// neutral character is the object replacement character, a neutral: it joins no two
/// groups of digits.
fn sequence_char(piece: &Piece) -> char {
    let ch = char_of(piece);
    let neutral = run_class(piece).is_some_and(BidiLanguageClass::has_neutral_slash);
    if ch == '/' && neutral { '\u{FFFC}' } else { ch }
}

/// Whether a sequence of runs with `w:rtl` starts as after an Arabic letter: its first
/// number has no letter before it in the sequence, and the bidi language of the number's
/// run makes such a number an Arabic number. `run` starts at the first piece of the
/// sequence.
fn starts_arabic(run: &[crate::lines::Placed]) -> bool {
    run.iter()
        .take_while(|placed| run_rtl(&placed.piece) == Some(true))
        .find_map(|placed| match class_of(&placed.piece) {
            BidiClass::L | BidiClass::R | BidiClass::AL => Some(false),
            BidiClass::EN => Some(
                run_class(&placed.piece).is_some_and(BidiLanguageClass::starts_with_arabic_number),
            ),
            _ => None,
        })
        .unwrap_or(false)
}

/// The UAX 9 class of the character of a piece.
fn class_of(piece: &Piece) -> BidiClass {
    bidi_class(char_of(piece))
}

/// Whether a class is one that the weak rules of UAX 9 join to a number: a number itself or
/// a separator or terminator.
fn numeric(class: BidiClass) -> bool {
    matches!(
        class,
        BidiClass::EN | BidiClass::AN | BidiClass::ES | BidiClass::ET | BidiClass::CS
    )
}

/// The stand-in of each piece of a line: the direction that a character without one of its
/// own takes from its run.
fn stands(placed: &[crate::lines::Placed]) -> Vec<Stand> {
    let mut stands = vec![Stand::Own; placed.len()];
    let mut start = 0;
    while start < placed.len() {
        let end = run_end(placed, start);
        let run = placed.get(start..end).unwrap_or_default();
        let marks = stands.get_mut(start..end).unwrap_or_default();
        match run.first().and_then(|first| run_rtl(&first.piece)) {
            Some(false) => left_run(run, marks),
            Some(true) => right_run(run, marks),
            None => {}
        }
        start = end;
    }
    numeric_tokens(placed, &mut stands);
    stands
}

/// The end of the run that starts at `start`: the next piece that has another direction or
/// is no text of a run and, without `w:rtl`, the next piece that starts a run. Adjacent runs
/// with `w:rtl` are one sequence.
fn run_end(placed: &[crate::lines::Placed], start: usize) -> usize {
    let rtl = placed.get(start).and_then(|first| run_rtl(&first.piece));
    let more = placed
        .iter()
        .skip(start + 1)
        .take_while(|next| {
            rtl.is_some()
                && run_rtl(&next.piece) == rtl
                && (rtl == Some(true)
                    || !run_glyph(&next.piece).is_some_and(|glyph| glyph.starts_run))
        })
        .count();
    start + 1 + more
}

/// In a run without `w:rtl` that holds no right-to-left letter and no Arabic number, every
/// character that is not a left-to-right letter is treated as left-to-right (including spaces).
/// Runs containing a right-to-left letter keep their original classes apart from numeric tokens.
fn left_run(run: &[crate::lines::Placed], stands: &mut [Stand]) {
    let foreign = |class| matches!(class, BidiClass::R | BidiClass::AL | BidiClass::AN);
    if run.iter().any(|p| foreign(class_of(&p.piece))) {
        return;
    }
    for (placed, stand) in run.iter().zip(stands) {
        let own = matches!(class_of(&placed.piece), BidiClass::L | BidiClass::NSM);
        if !own {
            *stand = Stand::Left;
        }
    }
}

/// In a sequence of runs with `w:rtl`, a space, a neutral character, a separator and a
/// terminator are right to left where UAX 9 makes them so in the sequence alone, as a
/// right-to-left text: at its edges and beside its right-to-left letters. Between two
/// left-to-right letters of the sequence, or between such a letter and a number after it,
/// and in a number, they keep their classes. The bidi language of a run decides whether the
/// sequence starts as after an Arabic letter ([`starts_arabic`]) and whether a slash is a
/// neutral character ([`sequence_char`]).
fn right_run(run: &[crate::lines::Placed], stands: &mut [Stand]) {
    let lead = starts_arabic(run).then_some(ARABIC_LETTER_MARK);
    let text: String = lead
        .into_iter()
        .chain(run.iter().map(|p| sequence_char(&p.piece)))
        .collect();
    let info = BidiInfo::new(&text, Some(Level::rtl()));
    let levels = text
        .char_indices()
        .skip(usize::from(lead.is_some()))
        .map(|(at, _)| info.levels.get(at));
    for ((placed, stand), level) in run.iter().zip(stands).zip(levels) {
        let weak = matches!(
            class_of(&placed.piece),
            BidiClass::WS | BidiClass::ON | BidiClass::ES | BidiClass::ET | BidiClass::CS
        );
        if weak && level.is_some_and(Level::is_rtl) {
            *stand = Stand::Right;
        }
    }
}

/// A numeric token of runs without `w:rtl` is left to right also across runs and in a run
/// with a right-to-left letter: adjacent numbers, separators, terminators and neutral
/// characters with at least one European number.
fn numeric_tokens(placed: &[crate::lines::Placed], stands: &mut [Stand]) {
    let eligible = |piece: &Piece| {
        run_rtl(piece) == Some(false)
            && matches!(
                class_of(piece),
                BidiClass::EN | BidiClass::ES | BidiClass::ET | BidiClass::CS | BidiClass::ON
            )
    };
    let mut start = 0;
    while start < placed.len() {
        let count = placed
            .iter()
            .skip(start)
            .take_while(|p| eligible(&p.piece))
            .count();
        let token = placed.get(start..start + count).unwrap_or_default();
        if token.iter().any(|p| class_of(&p.piece) == BidiClass::EN) {
            for stand in stands.get_mut(start..start + count).unwrap_or_default() {
                *stand = Stand::Left;
            }
        }
        start += count.max(1);
    }
}

/// Whether a right-to-left mark stands between two neighbours of a line: a number, a
/// separator that belongs to one, or a left-to-right letter of a run with `w:rtl` does not
/// join a piece of a run without `w:rtl` beside it in one left-to-right sequence, because
/// the runs with `w:rtl` are a unit of their own.
fn parted(before: (&Piece, Stand), after: (&Piece, Stand)) -> bool {
    let number = |(piece, stand): (&Piece, Stand)| {
        let class = class_of(piece);
        run_rtl(piece) == Some(true)
            && stand == Stand::Own
            && (numeric(class) || class == BidiClass::L)
    };
    let left = |(piece, _): (&Piece, Stand)| run_rtl(piece) == Some(false);
    (number(before) && left(after)) || (left(before) && number(after))
}

/// The embedding character that stands before a piece in a left-to-right paragraph: the
/// runs with `w:rtl` that stand side by side are one right-to-left unit of the line, also
/// with their left-to-right letters, as they are in a right-to-left paragraph. So a
/// right-to-left embedding starts before their first piece and ends after their last.
fn embedding(before: Option<&Piece>, here: &Piece) -> Option<char> {
    let inside = before.and_then(run_rtl) == Some(true);
    match (inside, run_rtl(here) == Some(true)) {
        (false, true) => Some('\u{202B}'),
        (true, false) => Some('\u{202C}'),
        _ => None,
    }
}

/// The text of a line for the algorithm in a paragraph that is right to left when `rtl`,
/// and for each of its characters the piece that it stands for; none for a mark that parts
/// two neighbours ([`parted`]) and for an embedding character ([`embedding`]).
fn ordering(all: &[crate::lines::Placed], rtl: bool) -> (String, Vec<Option<usize>>) {
    let stands = stands(all);
    let mut text = String::new();
    let mut pieces = Vec::with_capacity(all.len());
    let mut before: Option<(&Piece, Stand)> = None;
    let mut arabic = false;
    for (index, (placed, &stand)) in all.iter().zip(&stands).enumerate() {
        let here = (&placed.piece, stand);
        if before.is_some_and(|before| parted(before, here)) {
            text.push(right_mark(arabic));
            pieces.push(None);
        }
        let mark = embedding(before.map(|(piece, _)| piece), &placed.piece);
        if let Some(mark) = mark.filter(|_| !rtl) {
            text.push(mark);
            pieces.push(None);
        }
        // A sequence of runs with `w:rtl` whose first number has no letter before it starts
        // as after an Arabic letter, when the bidi language of the number's run says so.
        let first = before.and_then(|(piece, _)| run_rtl(piece)) != Some(true);
        if first && starts_arabic(all.get(index..).unwrap_or_default()) {
            text.push(ARABIC_LETTER_MARK);
            pieces.push(None);
            arabic = true;
        }
        let ch = stand.char_of(&placed.piece, arabic);
        arabic = arabic_after(arabic, ch);
        text.push(ch);
        pieces.push(Some(index));
        before = Some(here);
    }
    (text, pieces)
}

/// A line in visual order, with the direction of each of its pieces.
pub(super) struct Visual<'a> {
    /// The line with its pieces in visual order.
    pub line: Cow<'a, Line>,
    /// For each piece of `line`, whether it lies at a right-to-left level of the algorithm;
    /// empty when every piece is left to right.
    pub right_to_left: Vec<bool>,
    /// How many pieces at the start of `line` hold its written text. In a right-to-left
    /// paragraph these are all but the line's trailing spaces in its own order, which stay at
    /// the visual end, so that the spaces that start the line lie among them, at their visual
    /// end. In a left-to-right paragraph they end at the last piece of `line` that is not a
    /// space.
    pub written: usize,
    /// For each piece of `line`, the index of the piece in the line's own order; empty when the
    /// two orders are the same.
    pub order: Vec<usize>,
}

/// The line with its pieces in visual order and their offsets from the line start in that
/// order, with the direction of each piece. A line in a left-to-right paragraph without
/// right-to-left characters stays as it is. The spaces at the end of the line stay at its
/// visual end, so that they take no room, and count as left to right, but for those that
/// count as the line's written text ([`Line::written_end_spaces`]), which take part in the
/// order as the line's other pieces do.
pub(super) fn visual(line: &Line, rtl: bool) -> Visual<'_> {
    let own = line.written();
    let (line, right_to_left, order) = reorder(line, rtl);
    let written = if rtl { own } else { line.written() };
    Visual {
        line,
        right_to_left,
        written,
        order,
    }
}

/// The number of spaces at the end of `line`.
fn end_spaces(line: &Line) -> usize {
    line.placed
        .iter()
        .rev()
        .take_while(|p| is_space(&p.piece))
        .count()
}

/// For each space at the end of `line`, in the line's order, whether its run's `w:rtl` equals
/// `want`; none for a line of spaces only.
pub(in crate::layout) fn end_space_runs(
    line: &Line,
    want: bool,
) -> impl Iterator<Item = bool> + '_ {
    let spaces = end_spaces(line);
    let first = match line.placed.len() - spaces {
        0 => line.placed.len(),
        first => first,
    };
    line.placed
        .get(first..)
        .unwrap_or_default()
        .iter()
        .map(move |p| run_rtl(&p.piece) == Some(want))
}

/// The pieces of [`visual`] and their directions.
fn reorder(line: &Line, rtl: bool) -> (Cow<'_, Line>, Vec<bool>, Vec<usize>) {
    let turns = |piece: &Piece| right_to_left(char_of(piece)) || run_rtl(piece) == Some(true);
    if !rtl && !line.placed.iter().any(|p| turns(&p.piece)) {
        return (Cow::Borrowed(line), Vec::new(), Vec::new());
    }
    let spaces = end_spaces(line);
    let trailing = spaces - line.written_end_spaces.min(spaces);
    let content = line.placed.len() - trailing;
    let pieces = line.placed.get(..content).unwrap_or_default();
    // A character without a direction of its own takes one from its run, in a paragraph of
    // either direction.
    let (text, stood) = ordering(pieces, rtl);
    let base = if rtl { Level::rtl() } else { Level::ltr() };
    let info = BidiInfo::new(&text, Some(base));
    let Some(paragraph) = info.paragraphs.first() else {
        return (Cow::Borrowed(line), Vec::new(), Vec::new());
    };
    let levels = info.reordered_levels_per_char(paragraph, 0..text.len());
    // The marks between neighbours take part in the order and are no pieces of the line.
    let visual: Vec<(usize, bool)> = BidiInfo::reorder_visual(&levels)
        .into_iter()
        .filter_map(|at| {
            let piece = stood.get(at).copied().flatten()?;
            Some((piece, levels.get(at).is_some_and(Level::is_rtl)))
        })
        .collect();
    let order: Vec<usize> = visual.iter().map(|&(piece, _)| piece).collect();
    let directions = visual
        .iter()
        .map(|&(_, rtl)| rtl)
        .chain((content..line.placed.len()).map(|_| false))
        .collect();
    if order.iter().enumerate().all(|(i, &j)| i == j) {
        return (Cow::Borrowed(line), directions, Vec::new());
    }
    let order: Vec<usize> = order
        .into_iter()
        .chain(content..line.placed.len())
        .collect();
    let mut x = line.placed.first().map_or(Length::ZERO, |p| p.x);
    let mut placed = Vec::with_capacity(line.placed.len());
    for &index in &order {
        let Some(mut piece) = line.placed.get(index).copied() else {
            continue;
        };
        piece.x = x;
        x += piece.advance;
        placed.push(piece);
    }
    (
        // The spaces that count as written text stand inside the line now.
        Cow::Owned(Line {
            placed,
            written_end_spaces: 0,
            ..line.clone()
        }),
        directions,
        order,
    )
}

#[cfg(test)]
mod tests {
    use super::visual;
    use crate::lines::{Line, NoteNumber, Piece, Placed};
    use crate::props::BidiLanguageClass;
    use crate::text::{FaceIndex, Glyph};
    use f_office_units::Length;

    /// The text of a line for the algorithm.
    fn ordering_text(placed: &[Placed]) -> String {
        super::ordering(placed, true).0
    }

    /// A line of glyphs 10 wide each, in logical order.
    fn line(text: &str) -> Line {
        Line {
            placed: text
                .chars()
                .enumerate()
                .map(|(i, ch)| Placed {
                    piece: Piece::Glyph(Glyph::plain(FaceIndex::nth(0), ch)),
                    x: Length::from_units(i64::try_from(i).unwrap() * 10),
                    advance: Length::from_units(10),
                    leader: None,
                    tab: None,
                })
                .collect(),
            ..Line::default()
        }
    }

    /// The characters of a line from left to right, by their offsets.
    fn shown(line: &Line) -> String {
        let mut placed = line.placed.clone();
        placed.sort_by_key(|p| p.x);
        placed
            .iter()
            .map(|p| match p.piece {
                Piece::Glyph(g) => g.ch,
                _ => '?',
            })
            .collect()
    }

    #[test]
    fn leaves_left_to_right_lines_alone() {
        let plain = line("abc def");
        let shown = visual(&plain, false);
        assert!(matches!(shown.line, std::borrow::Cow::Borrowed(_)));
        assert_eq!(shown.right_to_left, [] as [bool; 0]);
    }

    #[test]
    fn turns_hebrew_around_inside_left_to_right_text() {
        let mixed = line("ab \u{5d0}\u{5d1}\u{5d2} cd");
        let reordered = visual(&mixed, false);
        assert_eq!(shown(&reordered.line), "ab \u{5d2}\u{5d1}\u{5d0} cd");
        let directions: String = reordered
            .right_to_left
            .iter()
            .map(|&rtl| if rtl { 'r' } else { 'l' })
            .collect();
        assert_eq!(directions, "lllrrrlll");
    }

    #[test]
    fn orders_the_runs_of_a_right_to_left_paragraph_from_the_right() {
        // In a right-to-left paragraph, the Latin word stays readable and comes after the
        // Hebrew one, on its left, and the space at the end stays at the visual end.
        let mixed = line("\u{5d0}\u{5d1} copy ");
        let reordered = visual(&mixed, true);
        assert_eq!(shown(&reordered.line), "copy \u{5d1}\u{5d0} ");
        // The Latin word is left to right; the space between it and the Hebrew word takes the
        // paragraph's direction.
        assert_eq!(
            reordered.right_to_left,
            [false, false, false, false, true, true, true, false]
        );
    }

    #[test]
    fn keeps_non_rtl_numbers_and_punctuation_together_after_arabic() {
        for token in ["(83.6%)", "[%83.6]", "[83/6%]", "(83-6%)"] {
            let mixed = line(&format!("\u{062A}\u{062A} {token}"));
            let reordered = visual(&mixed, true);
            assert_eq!(shown(&reordered.line), format!("{token} \u{062A}\u{062A}"));
            assert!(
                reordered.right_to_left[..token.chars().count()]
                    .iter()
                    .all(|rtl| !rtl)
            );
        }
    }

    #[test]
    fn ends_the_rtl_sequence_at_a_number_of_a_left_to_right_paragraph() {
        // In a left-to-right paragraph, a number of a run without `w:rtl` between two
        // right-to-left words ends their sequence: the first word stays at the left.
        let mixed = line("\u{05D0}\u{05D1} 2 \u{05D2}\u{05D3} 3");
        assert_eq!(
            shown(&visual(&mixed, false).line),
            "\u{05D1}\u{05D0} 2 \u{05D3}\u{05D2} 3"
        );
    }

    #[test]
    fn keeps_a_number_of_an_rtl_run_in_the_sequence_of_a_left_to_right_paragraph() {
        let mut mixed = line("\u{05D0}\u{05D1} 2 \u{05D2}\u{05D3} 3");
        for placed in &mut mixed.placed {
            if let Piece::Glyph(glyph) = &mut placed.piece {
                glyph.direction = crate::text::RunDirection::of(true, None);
            }
        }
        assert_eq!(
            shown(&visual(&mixed, false).line),
            "3 \u{05D3}\u{05D2} 2 \u{05D1}\u{05D0}"
        );
    }

    /// The line of `text` whose glyphs from the `first` on belong to a run with `w:rtl`.
    fn marked_from(text: &str, first: usize) -> Line {
        let mut marked = line(text);
        for placed in marked.placed.iter_mut().skip(first) {
            if let Piece::Glyph(glyph) = &mut placed.piece {
                glyph.direction = crate::text::RunDirection::of(true, None);
            }
        }
        marked
    }

    #[test]
    fn puts_a_kept_line_end_space_of_an_rtl_run_before_its_word() {
        // A Latin word, then a run with `w:rtl` of a Hebrew word and the space after it at the
        // line's end. Kept at its run's level, the space lies at the Hebrew word's left.
        let mut mixed = marked_from("ab \u{5d0}\u{5d1} ", 3);
        assert_eq!(
            super::end_space_runs(&mixed, true).collect::<Vec<_>>(),
            [true]
        );
        let plain = visual(&mixed, false);
        assert_eq!(shown(&plain.line), "ab \u{5d1}\u{5d0} ");
        assert_eq!(plain.written, 5);
        mixed.written_end_spaces = 1;
        assert_eq!(mixed.written(), 6);
        let kept = visual(&mixed, false);
        assert_eq!(shown(&kept.line), "ab  \u{5d1}\u{5d0}");
        assert_eq!(kept.written, 6);
    }

    #[test]
    fn tells_a_line_with_text_of_a_run_without_rtl() {
        let marked = marked_from("\u{5d0}\u{5d1} \u{5d2} ", 0);
        assert!(!marked.holds_left_to_right_text());
        let mixed = marked_from("a \u{5d0}\u{5d1} ", 1);
        assert!(mixed.holds_left_to_right_text());
        // A space of a run without `w:rtl` is no text of its own.
        let spaced = marked_from(" \u{5d0}\u{5d1}", 1);
        assert!(!spaced.holds_left_to_right_text());
    }

    #[test]
    fn leaves_a_list_label_to_its_own_classes() {
        let mut mixed = line("1- \u{062A}\u{062A}");
        for placed in mixed.placed.iter_mut().take(2) {
            if let Piece::Glyph(glyph) = &mut placed.piece {
                glyph.label = true;
            }
        }
        assert_eq!(ordering_text(&mixed.placed), "1- \u{062A}\u{062A}");
        assert_eq!(shown(&visual(&mixed, true).line), "\u{062A}\u{062A} -1");
    }

    #[test]
    fn keeps_a_numeric_token_across_run_boundaries() {
        let mut mixed = line("\u{062A}\u{062A} (83.6%)");
        // Each character of the token is a run of its own.
        for placed in mixed.placed.iter_mut().skip(3) {
            if let Piece::Glyph(glyph) = &mut placed.piece {
                glyph.starts_run = true;
            }
        }
        assert_eq!(
            shown(&visual(&mixed, true).line),
            "(83.6%) \u{062A}\u{062A}"
        );
    }

    /// A line of the runs of `runs`, each a text and whether its run has `w:rtl`.
    fn runs(runs: &[(&str, bool)]) -> Line {
        let text: String = runs.iter().map(|run| run.0).collect();
        let mut built = line(&text);
        let mut glyphs = built.placed.iter_mut();
        for &(text, rtl) in runs {
            for (index, placed) in glyphs.by_ref().take(text.chars().count()).enumerate() {
                if let Piece::Glyph(glyph) = &mut placed.piece {
                    glyph.starts_run = index == 0;
                    glyph.direction = crate::text::RunDirection::of(rtl, None);
                }
            }
        }
        built
    }

    /// The two right-to-left contexts of the lines below, and each as a page shows it.
    const H1: &str = "\u{05D1}\u{05D3}";
    const H2: &str = "\u{05D4}\u{05E7}";
    const D1: &str = "\u{05D3}\u{05D1}";
    const D2: &str = "\u{05E7}\u{05D4}";

    /// The order of a line in a right-to-left paragraph and in a left-to-right one.
    fn both(line: &[(&str, bool)]) -> [String; 2] {
        let line = runs(line);
        [true, false].map(|rtl| shown(&visual(&line, rtl).line))
    }

    #[test]
    fn draws_the_marks_of_a_run_without_rtl_from_the_left() {
        let alone = both(&[(H1, true), (":;", false), (H2, true)]);
        assert_eq!(alone, [format!("{D2}:;{D1}"), format!("{D1}:;{D2}")]);
        let before = both(&[(H1, true), ("#*ef", false), (H2, true)]);
        assert_eq!(before, [format!("{D2}#*ef{D1}"), format!("{D1}#*ef{D2}")]);
        let after = both(&[(H1, true), ("ef#*", false), (H2, true)]);
        assert_eq!(after, [format!("{D2}ef#*{D1}"), format!("{D1}ef#*{D2}")]);
        let space = both(&[(H1, true), (" ", false), (H2, true)]);
        assert_eq!(space, [format!("{D2} {D1}"), format!("{D1} {D2}")]);
    }

    #[test]
    fn draws_the_spaces_of_a_run_without_rtl_from_the_left() {
        // Spaces alongside punctuation or Latin letters in a run without `w:rtl` keep the
        // run's left-to-right order in a right-to-left paragraph too.
        assert_eq!(both(&[("- ", false), (H1, true)])[0], format!("{D1}- "));
        assert_eq!(both(&[("ab ", false), (H1, true)])[0], format!("{D1}ab "));
        assert_eq!(
            both(&[(H1, true), ("   ef", false)])[0],
            format!("   ef{D1}")
        );
        assert_eq!(
            both(&[(H1, true), ("  ef", false), (H2, true)])[0],
            format!("{D2}  ef{D1}")
        );
        assert_eq!(
            both(&[(H1, true), ("ef  ", false), (H2, true)])[0],
            format!("{D2}ef  {D1}")
        );
    }

    #[test]
    fn puts_a_kept_line_end_space_of_an_ltr_run_after_its_word_in_bidi() {
        let mut mixed = runs(&[(H1, true), ("   ef ", false)]);
        assert!(mixed.holds_right_to_left_text());
        assert_eq!(
            super::end_space_runs(&mixed, false).collect::<Vec<_>>(),
            [true]
        );
        mixed.written_end_spaces = 1;
        let kept = visual(&mixed, true);
        assert_eq!(shown(&kept.line), format!("   ef {D1}"));
        assert_eq!(kept.written, 8);
    }

    #[test]
    fn draws_the_neutral_characters_of_a_run_with_rtl_from_the_right() {
        let marks = both(&[("ef", false), (" ;", true), ("gh", false)]);
        assert_eq!(marks, ["gh; ef", "ef; gh"]);
        // The spaces of the runs with `w:rtl` stand on the far side of their words.
        let spaces = both(&[
            ("\u{05D1}\u{05D3} ", true),
            ("ef", false),
            (" \u{05D4}\u{05E7}", true),
        ]);
        assert_eq!(spaces, [format!("{D2} ef {D1}"), format!(" {D1}ef{D2} ")]);
    }

    #[test]
    fn keeps_a_number_after_arabic_letters_an_arabic_number_behind_the_marks() {
        // The space and the bracket of the run with `w:rtl` stand for right-to-left
        // characters, and the number after them is still one after an Arabic letter: its
        // percent sign stays outside it, at its left.
        let all = both(&[("\u{062A}\u{062A} (27,4%)", true)]);
        assert_eq!(all[0], ")%27,4( \u{062A}\u{062A}");
    }

    #[test]
    fn keeps_a_space_between_a_latin_word_and_a_number_of_runs_with_rtl() {
        // After a right-to-left word, a Latin word and the number after it, all in runs with
        // `w:rtl`, stay one left-to-right sequence with their space.
        let line = [(H1, true), (" ", true), ("ab", true), (" 7", true)];
        assert_eq!(both(&line)[0], format!("ab 7 {D1}"));
    }

    #[test]
    fn draws_runs_with_rtl_as_one_right_to_left_unit_in_both_paragraph_directions() {
        let first = format!("{H1} ");
        let last = format!(" {H2}");
        let word = [
            (first.as_str(), true),
            ("pq", true),
            (" 46", true),
            (&last, true),
        ];
        let order = format!("{D2} pq 46 {D1}");
        assert_eq!(both(&word), [order.clone(), order]);
        let marks = [
            ("pq", true),
            (" ", true),
            (H1, true),
            ("!?", true),
            ("uv", true),
        ];
        let order = format!("uv?!{D1} pq");
        assert_eq!(both(&marks), [order.clone(), order]);
        // A word of a run without `w:rtl` stands between two such units.
        let plain = [
            (first.as_str(), true),
            ("pq", false),
            (" 46", true),
            (&last, true),
        ];
        assert_eq!(both(&plain)[1], format!(" {D1}pq{D2} 46 "));
    }

    #[test]
    fn parts_a_number_with_rtl_from_marks_without_it() {
        let first = format!("{H1} ");
        let last = format!(" {H2}");
        let after = both(&[(&first, true), ("37", true), ("-/", false), (&last, true)]);
        assert_eq!(
            after,
            [format!("{D2} -/37 {D1}"), format!("37 {D1}-/{D2} ")]
        );
        let before = both(&[(&first, true), ("!?", false), ("58", true), (&last, true)]);
        assert_eq!(
            before,
            [format!("{D2} 58!? {D1}"), format!(" {D1}!?{D2} 58")]
        );
    }

    #[test]
    fn parts_a_number_with_rtl_from_a_word_or_number_without_it() {
        let first = format!("{H1} ");
        let last = format!(" {H2}");
        let word = both(&[(&first, true), ("6", true), ("ef", false), (&last, true)]);
        assert_eq!(word, [format!("{D2} ef6 {D1}"), format!("6 {D1}ef{D2} ")]);
        let number = both(&[(&first, true), ("12", false), ("9", true), (&last, true)]);
        assert_eq!(number, [format!("{D2} 912 {D1}"), format!(" {D1}12{D2} 9")]);
    }

    /// A line of one run with `w:rtl` whose bidi language has the class `class`.
    fn classed(text: &str, class: BidiLanguageClass) -> Line {
        let mut built = line(text);
        for placed in &mut built.placed {
            if let Piece::Glyph(glyph) = &mut placed.piece {
                glyph.direction = crate::text::RunDirection::of(true, Some(class));
            }
        }
        built
    }

    /// The order of `text` in a run with `w:rtl` of the class `class`, from the left.
    fn order(text: &str, class: BidiLanguageClass) -> String {
        shown(&visual(&classed(text, class), false).line)
    }

    #[test]
    fn leaves_the_numeric_types_of_a_language_of_the_unicode_class_unchanged() {
        let mixed = classed("(83/6%)", BidiLanguageClass::Unicode);
        // The brackets are neutral characters of the run and take its direction.
        assert_eq!(ordering_text(&mixed.placed), "\u{200F}83/6%\u{200F}");
        assert_eq!(order("47%", BidiLanguageClass::Unicode), "47%");
        assert_eq!(order("47/6", BidiLanguageClass::Unicode), "47/6");
    }

    #[test]
    fn starts_a_sequence_of_the_arabic_class_as_after_an_arabic_letter() {
        // A number with no letter before it is an Arabic number: the percent sign stands
        // outside it, and the plus and the hyphen join no groups.
        let class = BidiLanguageClass::Arabic;
        assert_eq!(order("38%", class), "%38");
        assert_eq!(order("%38", class), "38%");
        assert_eq!(order("38+5", class), "5+38");
        assert_eq!(order("38.5", class), "38.5");
        // A run without a bidi language has this class.
        let plain = classed("38%", BidiLanguageClass::default());
        assert_eq!(shown(&visual(&plain, true).line), "%38");
    }

    #[test]
    fn lets_a_letter_before_a_number_decide_in_the_arabic_class() {
        // A letter before the number decides as in UAX 9.
        let class = BidiLanguageClass::Arabic;
        assert_eq!(order("\u{05D0}\u{05D1} 38%", class), "38% \u{05D1}\u{05D0}");
        assert_eq!(order("ab 38%", class), "ab 38%");
        assert_eq!(order("38%", BidiLanguageClass::OtherRightToLeft), "38%");
    }

    #[test]
    fn makes_a_slash_a_neutral_character_but_for_the_unicode_class() {
        for class in [
            BidiLanguageClass::Arabic,
            BidiLanguageClass::OtherRightToLeft,
        ] {
            assert_eq!(order("38/5", class), "5/38");
            assert_eq!(
                order("\u{05D0}\u{05D1} 38/5", class),
                "5/38 \u{05D1}\u{05D0}"
            );
            assert_eq!(
                order("\u{062F}\u{0632} 38/5", class),
                "5/38 \u{0632}\u{062F}"
            );
            assert_eq!(order("38:5", class), "38:5");
        }
    }

    #[test]
    fn starts_a_sequence_after_a_run_without_rtl_as_after_an_arabic_letter() {
        // The letters of a run without `w:rtl` are no letters of the sequence.
        assert_eq!(both(&[("ab ", false), ("47%", true)])[1], "ab %47");
    }

    #[test]
    fn ends_numeric_tokens_at_spaces_letters_objects_and_rtl_runs() {
        let mut mixed = line("(8) x (.)\u{FFFC}[3%]");
        mixed.placed[9].piece = Piece::Note(NoteNumber::of_index(0));
        assert_eq!(
            ordering_text(&mixed.placed),
            "\u{200E}\u{200E}\u{200E}\u{200E}x\u{200E}\u{200E}\u{200E}\u{200E}\u{FFFC}\u{200E}\u{200E}\u{200E}\u{200E}"
        );
        if let Piece::Glyph(glyph) = &mut mixed.placed[12].piece {
            glyph.direction = crate::text::RunDirection::of(true, None);
        }
        assert_eq!(
            ordering_text(&mixed.placed),
            "\u{200E}\u{200E}\u{200E}\u{200E}x\u{200E}\u{200E}\u{200E}\u{200E}\u{FFFC}\u{200E}\u{200E}\u{200F}\u{200E}"
        );
    }
}