Level-based reordering of bidirectional text (source code)

= Level-based reordering of bidirectional text

<Level-based reordering of bidirectional text> is the final positional reversal procedure of the <Unicode Bidirectional Algorithm> after directional levels and line boundaries have been resolved. RuleL2 processes thresholds from the largest level down through the smallest level whose value is an <odd integer>. Each pass reverses every maximal consecutive run whose levels meet or exceed the threshold.<Unicode Bidirectional Algorithm (Revision 51) by the Unicode Consortium>[section3.4, ruleL2: descending thresholds and contiguous reversals]{ref}

An original trace supplies the resolved levels rather than attempting to infer them. Take the logical items
$$
(a,R_1,R_2,1,2,R_3,b),\qquad (\ell_i)=(0,1,1,2,2,1,0).
$$
At threshold2, reverse only the two middle digits, obtaining $(a,R_1,R_2,2,1,R_3,b)$. At threshold1, reverse the entire middle five-item run, giving
$$
\boxed{(a,R_3,1,2,R_2,R_1,b).}
$$
The digits underwent two reversals, preserving their internal order. The $R_i$ labels each denote one abstract right-to-left <text character>; every array is written in physical left-to-right order.

\Image[/bidirectional-level-reordering.png]
{title=Descending level passes reverse nested runs and restore the internal order of digits}
{id=level-based-bidirectional-reordering-example}
{description=Reused supplied-level illustration. It demonstrates ruleL2, rather than a complete implementation that resolves levels, shapes glyphs or chooses line boundaries.}

Thresholds include intermediate values that no item happens to have. For example, a pair at level4 surrounded by level1 items participates in passes4,3,2 and then the enclosing pass1. Omitting pass3 changes the result, as the <bidirectional embedding level> example demonstrates.

An implementation may carry levels with the items, as the figure generator does. It can also locate each reversal range from the original fixed level array: earlier passes permute items only inside higher-level runs, preserving the boundaries of every later lower-threshold run. Keeping logical indices on the displayed items supplies the eventual position map. Line-final whitespace resetting belongs to ruleL1, and combining-mark handling and mirroring require their separate rules.<Unicode Bidirectional Algorithm (Revision 51) by the Unicode Consortium>[section3.4, rulesL1–L4: distinct stages around L2]{ref}