Unicode Bidirectional Algorithm (source code)

= Unicode Bidirectional Algorithm
{c}
{wiki=Unicode_bidirectional_algorithm}

The <Unicode Bidirectional Algorithm> computes <visual text order> from <logical text order>. <Unicode bidirectional classes> and context determine <bidirectional embedding levels>: levels with an <even integer> value run left-to-right, and those with an <odd integer> value run right-to-left. Stored <code points> retain their order; <text shaping> is separate.<Unicode Bidirectional Algorithm (Revision 51) by the Unicode Consortium>[§1; definitions BD2–BD3; §3.5]{ref}

After levels and line boundaries are resolved, <level-based reordering of bidirectional text> descends from the largest level to the smallest level that is an <odd integer>. Each pass reverses maximal consecutive runs at or above its level.<Unicode Bidirectional Algorithm (Revision 51) by the Unicode Consortium>[§3.4, rules L1–L3, especially L2]{ref}

Here is a small example with the resolved levels supplied. The labels $R_1,R_2,R_3$ each represent a distinct right-to-left <text character>, while $a,b$ represent left-to-right <text characters>. All rows below are written in physical left-to-right order. Start with
$$
\begin{array}{c|rrrrrrr}
\text{item}&a&R_1&R_2&1&2&R_3&b\\
\text{level}&0&1&1&2&2&1&0
\end{array}
$$
The level 2 pass changes the middle digits to $2,1$. The level 1 pass then reverses the whole five-item middle run, producing
$$
\boxed{a,\ R_3,\ 1,\ 2,\ R_2,\ R_1,\ b.}
$$
The digits have been reversed twice, preserving their original internal order. Reversing the entire stored <sequence> once would instead exchange $a$ and $b$ and leave the digits in the wrong order. This example demonstrates the reordering step, not how all <Unicode bidirectional classes> are resolved.

\Image[/bidirectional-level-reordering.png]
{title=Two level-based reversals preserve the internal order of the digits}
{description=Original illustration with supplied <bidirectional embedding levels>. The boxes denote individual abstract <text characters>, not literal multi-character labels.}

A <bidirectional isolate> limits directional interaction between inserted text and its surroundings. Markup can express isolation without storing explicit formatting <code points>.<Unicode Bidirectional Algorithm (Revision 51) by the Unicode Consortium>[§2.4–2.7]{ref}

<Mark Davis (computer scientist)> created the annex's initial version; later revisions extended it.<Unicode Bidirectional Algorithm (Revision 51) by the Unicode Consortium>[Acknowledgments]{ref}