Algorithm Search⌘K

Algorithmcore

Unicode bidirectional algorithm

Also called UBA, bidi algorithm, UAX 9.

Give each character of mixed left-to-right and right-to-left text an embedding level by the explicit, weak, neutral and implicit rules of UAX 9, then reverse runs of each line by level.

Time
Θ(n) worst · best
Space
Θ(n) extra
Where
n = the length of the paragraph in code points
Properties
deterministicofflineiterative

The Unicode bidirectional algorithm (UBA) finds the display order of text that mixes left-to-right scripts, such as Latin, with right-to-left scripts, such as Hebrew and Arabic. It is Unicode Standard Annex 9 (UAX 9). Text is stored in logical order, the order in which it is read and typed. The algorithm gives each character an embedding level: even levels are left to right and odd levels are right to left. It then reverses runs of characters by level to get the visual order of each line. The levels come from the Bidi_Class of each code point, from explicit formatting characters such as RLI and PDI, and from rules for numbers, neutral characters and paired brackets.

In plain words

Hebrew and Arabic are written from right to left, but a Hebrew sentence can contain an English name or a number, which still go from left to right. The computer stores the text in the order that a person reads it. To show it, the program must decide, for each character, which way it runs, and then flip the right-to-left parts. Letters are easy: they carry their own direction. Spaces, punctuation and brackets have no direction, so they take one from their neighbours. Digits are special: a number stays left to right even inside Hebrew. Writers can also insert invisible control characters that say "this part is right to left" or "keep this part apart from the text around it". The algorithm gives every character a level number, and then reverses each stretch of text at an odd level.

The problem

The input is a paragraph s=s[0]⋯s[n−1]s = s[0] \cdots s[n-1] of code points and a paragraph direction: left to right, right to left, or automatic. Each code point has a Bidi_Class: strong (L, R, AL), weak (EN, ES, ET, AN, CS, NSM, BN), neutral (B, S, WS, ON) or explicit formatting (LRE, RLE, LRO, RLO, PDF, LRI, RLI, FSI, PDI). The output is the paragraph level pp, a level for each code point, and for each line the visual order: a permutation of the positions of the line from left to right. The explicit formatting characters other than the isolates, and the BN characters, are removed by rule X9 and get no level.

The levels must satisfy the rules of UAX 9 in their order: P2 and P3 for the paragraph level, X1 to X10 for the explicit levels, W1 to W7, N0 to N2, I1 and I2 for the implicit levels, and L1 to L4 for each line.

The algorithm

The algorithm makes a fixed number of passes over the text:

  • P2, P3. In automatic mode, the paragraph level is 1 if the first strong character, outside isolates, is R or AL, and 0 otherwise.
  • X1 to X8. A stack of directional status entries holds a level, an override status and an isolate flag. The embeddings and overrides (LRE, RLE, LRO, RLO) push an entry with the next even or odd level, PDF pops one, the isolates (LRI, RLI, FSI) push an entry that only the matching PDI pops, and each other character gets the level of the top entry. Levels stop at max_depth = 125; counters of overflow embeddings and overflow isolates keep the pushes and pops balanced beyond that depth. FSI looks at the text up to its matching PDI and acts as RLI or LRI by rules P2 and P3.
  • X9, X10. The removed characters drop out. The rest splits into level runs, and a level run that ends with an isolate initiator joins the level run that starts with its matching PDI. These chains are the isolating run sequences (BD13). Each one gets a start type sos and an end type eos from the higher of its level and the level on the other side.
  • W1 to W7. In each isolating run sequence, a mark (NSM) takes the type before it, a European number after Arabic letters becomes an Arabic number, AL becomes R, separators between numbers join them, terminators next to European numbers join them, other separators become neutral, and a European number after L becomes L.
  • N0. Paired brackets (BD16) are found with a stack of 63 entries. A pair takes the embedding direction if a strong type of that direction is inside it, or the opposite direction if only the opposite direction is inside and the context before the pair has it too.
  • N1, N2. A run of neutrals between two strong types of the same direction takes that direction, where numbers count as R. Other neutrals take the embedding direction.
  • I1, I2. At an even level, R goes up by one and numbers by two. At an odd level, L and numbers go up by one.
  • L1 to L4. On each line, separators and trailing white space go back to the paragraph level. Then, from the highest level down to the lowest odd level, every maximal run at that level or higher is reversed. L3 and L4 handle combining marks and mirrored glyphs.
  1. BIDI(s, d) ▷ one paragraph shown as one line
  2. 1t[i] <- Bidi_Class(s[i]) for each i
  3. 2p <- d, or the level of rules P2 and P3 if d is automatic
  4. 3lev, t <- the levels and overrides of rules X1 to X8, with the directional status stack
  5. 4remove the characters of rule X9
  6. 5for each isolating run sequence S of rule X10, with its sos and eos, do
  7. 6apply W1 to W7 to the types of S
  8. 7apply N0 to the bracket pairs of S, found by BD16
  9. 8apply N1 and N2 to the runs of neutrals of S
  10. 9apply I1 and I2 to the levels of S
  11. 10apply rule L1: separators and trailing white space get level p
  12. 11order <- the kept positions in logical order
  13. 12for v <- the highest level down to the lowest odd level do reverse each maximal run of order with levels >= v
  14. 13return p, lev, order

Example

Take the text ab אב 12 cd in a left-to-right paragraph, so p=0p = 0. The classes are L L WS R R WS EN EN WS L L. There are no explicit formatting characters, so the whole text is one isolating run sequence at level 0, with sos = eos = L.

  • W7 looks back from each EN for a strong type. It finds R, so the digits stay EN.
  • N1: the space between אב and 12 lies between R and EN, and EN counts as R, so it becomes R. The space between ab and אב lies between L and R, and the space between 12 and cd lies between EN and L. They take the embedding direction L by N2.
  • I1 at level 0: R goes to level 1 and EN goes to level 2. The levels are 0 0 0 1 1 1 2 2 0 0 0.
  • L2: at level 2, the run 12 is reversed, which gives 21. At level 1, the run אב 21 is reversed, which gives 12 בא.

The visual order is ab 12 בא cd. A reader of Hebrew reads the middle part from right to left: first אב, then 12, which is the logical order.

For brackets, take ab (אב) cd with p=0p = 0. The pair contains only R, which is opposite to the embedding direction L. The first strong type before the pair is L from ab, so by N0 the brackets take the embedding direction L and keep level 0. The result is ab (בא) cd, and the brackets stay outside the reversed Hebrew word.

Correctness

The rules of UAX 9 define the result, so the algorithm is correct if each pass computes its rules exactly. The proof shows that the stack of line L3 gives the levels of X1 to X8, that the isolating run sequences of line L5 are those of BD13, that the passes of lines L6 to L9 apply each rule to the whole sequence before the next rule, as the annex requires, and that line L12 is rule L2. The tests run the first 40 lines of BidiCharacterTest.txt, a direct reference for text without explicit formatting, and a recursive form of rule L2 on random levels.

Proof: BIDI computes the paragraph level, the resolved levels and the visual order that the rules of UAX 9 definefull

Setup. Let s=s[0]⋯s[n−1]s = s[0] \cdots s[n-1] be one paragraph, shown as one line, and let t[i]t[i] be the Bidi_Class of s[i]s[i]. UAX 9 defines the result by rules that are applied in a fixed order. Each claim below shows that one part of BIDI computes the result of its rules from the result of the rules before them. Together they show that BIDI returns the levels and the order of UAX 9.

Claim 1 (BD9). matching_pdi gives each isolate initiator its matching PDI as BD9 defines it, or none.

Proof. BD9 matches an isolate initiator with the first later PDI at which the number of PDIs equals the number of isolate initiators counted from the initiator on, or with nothing if the paragraph ends first. The function keeps a stack of the unmatched initiators. A PDI matches the initiator on top of the stack, which is the latest initiator whose count is still open. This is the usual matching of balanced parentheses with initiators as opening and PDIs as closing symbols, and it gives the same pairs as the counter of BD9. A PDI that finds the stack empty matches nothing, and so does an initiator left on the stack at the end. □\square

Claim 2 (P2, P3 and line L2). first_strong(t, a, b, match) returns 0 if the first character of class L, R or AL in t[a…b−1]t[a \ldots b-1] that is not between an isolate initiator and its matching PDI is L, 1 if it is R or AL, and none if there is no such character.

Proof. The loop goes through the positions in order. At an isolate initiator, it jumps to the matching PDI, so it skips exactly the characters between them; if there is no matching PDI, P2 skips the rest of the paragraph, and the loop returns none. Otherwise it returns at the first strong character. □\square

So line L2 sets pp by P2 and P3 in automatic mode, and FSI gets its direction by the same rules on the text up to its matching PDI, as X5c says.

Claim 3 (X1 to X8, line L3). explicit_levels gives each character the level and the type that rules X1 to X8 give it.

Proof. The function keeps the state of X1: the directional status stack, with entries of level, override status and isolate status, and the three counters of overflow isolates, overflow embeddings and valid isolates. Each branch of the loop is one rule, with the same tests and the same updates:

  • X2 to X5: the new level is the least odd or even level above the level of the top entry. The entry is pushed when the level is at most max_depth = 125 and both overflow counters are zero. Otherwise the overflow embedding counter goes up if the overflow isolate counter is zero.
  • X5a to X5c: the initiator gets the level of the top entry and the override of the top entry. Then the same test decides between a push with isolate status true, together with an increment of the valid isolate counter, and an increment of the overflow isolate counter.
  • X6a (PDI): if the overflow isolate counter is positive, it goes down. Else, if the valid isolate counter is positive, the overflow embedding counter is reset, the entries without isolate status are popped, then the isolate entry is popped, and the valid isolate counter goes down. In all cases the PDI gets the level and the override of the new top entry.
  • X7 (PDF): nothing if an isolate overflows, a decrement if an embedding overflows, and a pop if the top entry has no isolate status and is not the only entry.
  • X6 for all other characters except B and BN: the level of the top entry, and the class L or R if the override status says so. X8 gives B the paragraph level. BN is removed by X9, so its level does not matter.

The stack never becomes empty, because the pop of X6a needs a valid isolate, whose entry lies above the entry of X1, and the pop of X7 needs at least two entries. □\square

Claim 4 (X9, X10, lines L4 and L5). The lists of isolating_run_sequences are the isolating run sequences of BD13, and sos and eos are those of X10.

Proof. After the removal of the classes of X9, the level runs are the maximal runs of kept characters with equal levels, which is how the function builds them. BD13 starts a sequence with each level run that does not begin with a PDI matched to an initiator at the end of an earlier level run, and appends, while the last run ends with an initiator that has a matching PDI, the level run that begins with that PDI. The function follows these links, and it marks each run when it uses it, so each level run is in exactly one sequence, in the order of BD13. When the initiator at the end of a run has a matching PDI, X5a to X5c and X6a give the initiator and the PDI the same level and the text between them a higher level, or the same level if the isolate overflows; in the first case the PDI starts a level run, which is the run that is appended. For sos, X10 takes the higher of the level of the sequence and the level of the kept character before its first character, or pp if there is none. For eos, it takes the kept character after the last one, or pp if there is none or if the last character is an isolate initiator. Lines after L5 compute exactly these. □\square

Claim 5 (W1 to W7, line L6). After line L6, each type in the sequence is the result of rules W1 to W7.

Proof. UAX 9 applies each W rule to all the types of the sequence, in order, before the next rule. The function has one pass per rule, in the order W1 to W7:

  • W1 goes from left to right and reads the type before the mark after the previous step has changed it, so a run of marks takes the type before the run; at the start it uses sos, and after an isolate initiator or a PDI it uses ON.
  • W2 keeps the last strong type of L, R and AL, starting with sos, and changes EN to AN when it is AL. W3 then changes every AL to R.
  • W4 changes a single ES between two EN, and a single CS between two numbers of the same type. W5 changes each maximal run of ET that touches an EN. W6 changes the remaining ES, ET and CS to ON. W7 changes EN to L when the last strong type of L and R, or sos, is L.

Each pass reads the types left by the passes before it, as the rules require. □\square

Claim 6 (N0 to N2 and I1, I2, lines L7 to L9). After line L9, the levels of the sequence are those of rules N0 to I2.

Proof. BD16 finds the pairs with a stack of 63 entries among the characters of type ON with a Bidi_Paired_Bracket_Type: an opening bracket is pushed, and a closing bracket pops the stack down to the nearest entry whose bracket matches it, after canonical decomposition, if there is one. If an opening bracket finds the stack full, BD16 returns an empty list. The function does exactly this, then sorts the pairs by the position of the opening bracket. N0 handles the pairs in this order, and each pair sees the types that the pairs before it have set. For a pair, with ee the embedding direction and EN and AN counted as R: if a strong type equal to ee is inside, the pair gets ee. If only the opposite direction is inside, the pair gets the first strong direction before the opening bracket, or sos; this is the opposite direction if that is what the context has, and ee otherwise. If no strong type is inside, the pair is left alone. Then the characters that were NSM before W1 and directly follow a changed bracket get its type. N1 and N2 then go over each maximal run of the neutral and isolate types B, S, WS, ON, LRI, RLI, FSI and PDI. With EN and AN counted as R and sos and eos at the ends, the run takes the direction on both sides when they agree, and ee when they do not. Finally I1 and I2 raise the level by the table of the rules, from the final type of each character. □\square

Claim 7 (L1 and L2, lines L10 to L12). Line L10 sets the levels of rule L1, and visual_order returns the order of rule L2.

Proof. L1 resets to pp the levels of S and B, of each maximal sequence of WS and isolate formatting characters before an S or a B, and of such a sequence at the end of the line, with the original classes. The backward loop keeps a flag that is true at the end of the line and after an S or a B, and false after any other kept character, so it resets exactly these characters. Removed characters are skipped, because they have no level. Line L12 is L2 itself: for each vv from the highest level down to the lowest odd level, it reverses each maximal run of the list whose levels are at least vv. If no level is odd, the loop does nothing; in that case all levels are even, every run reversed at a level vv is also the run reversed at v−1v - 1, and the two reversals cancel, so L2 also leaves the order unchanged. The list holds only the kept characters, so the removed characters are skipped, as in BidiCharacterTest.txt. □\square

By Claims 2 to 7, BIDI returns the paragraph level, the levels after L1 and the visual order after L2 that UAX 9 defines.

Termination. Every loop runs over a finite list, and each while loop moves an index forward or backward by at least one step, or pops a stack that never becomes empty (Claim 3). Line L12 runs at most 126 times. So BIDI stops on every input.

Complexity

Each of the passes P2, X1 to X10, W1 to W7, N1, N2, I1, I2 and L1 takes Θ(n)\Theta(n) time. The PDI pops of X6a remove at most as many entries as were pushed. N0 looks inside each bracket pair, and a position is inside at most 63 open pairs at a time, because BD16 stops at 63 open brackets; the search before an opening bracket stops at the first strong type, and the brackets of each pair that N0 resolves become strong, so two of these searches never cover the same position. Rule L2 makes at most 126 passes, one per level. So the time is Θ(n)\Theta(n) with a constant that depends on max_depth, and the extra space is Θ(n)\Theta(n) for the types and levels.

Properties

  • The levels lie between the paragraph level and max_depth + 1 = 126.
  • Text with only L characters, European digits and neutrals in a left-to-right paragraph keeps its order.
  • Isolates (LRI, RLI, FSI with PDI) do not affect the text around them: the text outside sees the isolate as one neutral character. Embeddings (LRE, RLE) do affect it.
  • The levels are resolved per paragraph, but the reordering L1 to L4 is per line, after line breaking.
  • Unmatched PDF and PDI characters are ignored, and a paragraph separator closes every open embedding and isolate.

Variants and improvements

  • Higher-level protocols (HL1 to HL6 of UAX 9) can override parts of the algorithm, for example to set the paragraph level from outside or to treat some characters as isolated. HTML and CSS use them through the dir attribute, the bdi element and unicode-bidi.
  • Section 5.2 of UAX 9 describes how to keep the BN and explicit formatting characters in the text, with levels for them, instead of removing them by X9.
  • Before Unicode 6.3, the annex had no isolates and no rule N0. Older implementations give different results for brackets and for inserted text of unknown direction.

When to use it

Use it whenever right-to-left text is shown: in text editors, terminals, browsers and user interfaces. Wrap inserted text whose direction is not known, such as user names and file names, in FSI and PDI, so that it cannot change the order of the text around it. A shaping engine runs on the runs of one level and one script that the algorithm produces.

Pitfalls

  • Do not store text in visual order. Store it in logical order and run the algorithm at display time.
  • Run line breaking on the logical text, and apply L1 to L4 to each line. If a whole paragraph is reordered first and then broken into lines, the lines come out in the wrong order.
  • Rule L4 mirrors the glyphs of characters such as brackets at odd levels. The code point stays (, but the glyph is ). The visual order in the tests does not include this mirroring.
  • Arabic-Indic digits are AN and European digits are EN, and W2 turns EN into AN after Arabic letters. Numbers next to Arabic text are not handled the same way as numbers next to Hebrew text.
  • BD16 returns no pairs at all, not only the first 63, when the stack of opening brackets overflows.
  • Override characters such as RLO can make a file name or a line of source code look different from its logical order. Tools that show such text should mark these characters. This is a problem of the same kind as the one that confusable detection handles.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

unicode_bidirectional_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unicode-bidirectional-algorithm/. The authors are listed in prov/2X2V4H.jsonl.
"""The Unicode Bidirectional Algorithm of UAX 9 (revision 50, Unicode 16.0.0) for one
paragraph that is also one line.

The Bidi_Class values come from unicodedata. Unassigned code points get '' from
unicodedata; they are treated as L here, while DerivedBidiClass.txt gives some ranges
other defaults. The paired brackets are the lines of BidiBrackets-16.0.0.txt for
U+0028/0029, U+005B/005D, U+007B/007D, U+2329/232A and U+3008/3009; BD16 compares
brackets after canonical decomposition, so U+2329 and U+3008 count as the same opening
bracket.
"""

import unicodedata

MAX_DEPTH = 125  # BD2
BRACKET_STACK = 63  # BD16

OPENING = {"(": ")", "[": "]", "{": "}", "〈": "〉", "〈": "〉"}
CLOSING = {v: k for k, v in OPENING.items()}

REMOVED = ("RLE", "LRE", "RLO", "LRO", "PDF", "BN")  # X9
INITIATORS = ("LRI", "RLI", "FSI")
NEUTRAL_OR_ISOLATE = ("B", "S", "WS", "ON", "LRI", "RLI", "FSI", "PDI")  # NI of N1


def bidi_class(c: str) -> str:
    return unicodedata.bidirectional(c) or "L"


def _canon(c: str) -> str:
    return unicodedata.normalize("NFD", c)


def matching_pdi(t: list) -> tuple:
    """BD9. match[i] is the index of the PDI that matches the isolate initiator at i, or
    None; opener[j] is the initiator that a PDI at j matches, or None."""
    n = len(t)
    match, opener = [None] * n, [None] * n
    open_stack = []
    for i, x in enumerate(t):
        if x in INITIATORS:
            open_stack.append(i)
        elif x == "PDI" and open_stack:
            k = open_stack.pop()
            match[k], opener[i] = i, k
        elif x == "B":
            open_stack = []
    return match, opener


def first_strong(t: list, start: int, end: int, match: list):
    """P2 and P3 on t[start:end]: 0 for L, 1 for R or AL, None if there is no strong
    character outside isolates."""
    i = start
    while i < end:
        x = t[i]
        if x == "L":
            return 0
        if x in ("R", "AL"):
            return 1
        if x in INITIATORS:
            if match[i] is None:
                return None
            i = match[i]
        i += 1
    return None


def _odd_above(v):
    return (v + 1) | 1


def _even_above(v):
    return (v + 2) & ~1


def explicit_levels(t: list, p: int, match: list) -> tuple:
    """Rules X1 to X8. Return the levels and the classes after the overrides."""
    n = len(t)
    lev, ty = [p] * n, list(t)
    stack = [(p, None, False)]  # (level, override, isolate) of X1
    over_iso = over_emb = valid_iso = 0
    for i, x in enumerate(t):
        level, override, _ = stack[-1]
        if x in ("RLE", "LRE", "RLO", "LRO"):  # X2 to X5
            lev[i] = level
            new = _odd_above(level) if x[0] == "R" else _even_above(level)
            if new <= MAX_DEPTH and over_iso == 0 and over_emb == 0:
                stack.append((new, {"RLO": "R", "LRO": "L"}.get(x), False))
            elif over_iso == 0:
                over_emb += 1
        elif x in INITIATORS:  # X5a to X5c
            lev[i] = level
            if override:
                ty[i] = override
            if x == "FSI":
                end = match[i] if match[i] is not None else n
                x = "RLI" if first_strong(t, i + 1, end, match) == 1 else "LRI"
            new = _odd_above(level) if x == "RLI" else _even_above(level)
            if new <= MAX_DEPTH and over_iso == 0 and over_emb == 0:
                valid_iso += 1
                stack.append((new, None, True))
            else:
                over_iso += 1
        elif x == "PDI":  # X6a
            if over_iso > 0:
                over_iso -= 1
            elif valid_iso > 0:
                over_emb = 0
                while not stack[-1][2]:
                    stack.pop()
                stack.pop()
                valid_iso -= 1
            lev[i] = stack[-1][0]
            if stack[-1][1]:
                ty[i] = stack[-1][1]
        elif x == "PDF":  # X7
            lev[i] = level
            if over_iso > 0:
                pass
            elif over_emb > 0:
                over_emb -= 1
            elif not stack[-1][2] and len(stack) >= 2:
                stack.pop()
        elif x == "B":  # X8
            lev[i] = p
        else:  # X6, and BN, which X9 removes
            lev[i] = level
            if override and x != "BN":
                ty[i] = override
    return lev, ty


def isolating_run_sequences(t: list, lev: list, match: list) -> list:
    """X10 and BD13: the isolating run sequences as lists of indices, in order."""
    kept = [i for i in range(len(t)) if t[i] not in REMOVED]
    runs = []
    for i in kept:
        if runs and lev[runs[-1][-1]] == lev[i]:
            runs[-1].append(i)
        else:
            runs.append([i])
    run_at = {r[0]: k for k, r in enumerate(runs)}
    used = [False] * len(runs)
    seqs = []
    for k, r in enumerate(runs):
        if used[k]:
            continue
        seq, used[k] = list(r), True
        while t[seq[-1]] in INITIATORS and match[seq[-1]] is not None \
                and match[seq[-1]] in run_at and not used[run_at[match[seq[-1]]]]:
            nxt = run_at[match[seq[-1]]]
            seq.extend(runs[nxt])
            used[nxt] = True
        seqs.append(seq)
    return seqs


def _strong(x):
    """Strong direction for N0 and N1: EN and AN count as R."""
    if x == "L":
        return "L"
    if x in ("R", "EN", "AN"):
        return "R"
    return None


def resolve_sequence(s: str, t: list, ty: list, lev: list, seq: list, sos: str, eos: str) -> None:
    """Rules W1 to W7, N0 to N2 and I1 to I2 on one isolating run sequence."""
    m = len(seq)
    x = [ty[i] for i in seq]
    level = lev[seq[0]]
    e = "L" if level % 2 == 0 else "R"
    original = list(x)  # the classes before W1, for N0
    # W1
    for k in range(m):  # @line L6
        if x[k] == "NSM":
            if k == 0:
                x[k] = sos
            elif t[seq[k - 1]] in INITIATORS + ("PDI",):
                x[k] = "ON"
            else:
                x[k] = x[k - 1]
    # W2 and W3
    last = sos
    for k in range(m):
        if x[k] in ("L", "R", "AL"):
            last = x[k]
        elif x[k] == "EN" and last == "AL":
            x[k] = "AN"
    x = ["R" if v == "AL" else v for v in x]
    # W4
    for k in range(1, m - 1):
        if x[k] == "ES" and x[k - 1] == "EN" and x[k + 1] == "EN":
            x[k] = "EN"
        elif x[k] == "CS" and x[k - 1] == x[k + 1] and x[k - 1] in ("EN", "AN"):
            x[k] = x[k - 1]
    # W5
    k = 0
    while k < m:
        if x[k] == "ET":
            j = k
            while j < m and x[j] == "ET":
                j += 1
            if (k > 0 and x[k - 1] == "EN") or (j < m and x[j] == "EN"):
                for q in range(k, j):
                    x[q] = "EN"
            k = j
        else:
            k += 1
    # W6
    x = ["ON" if v in ("ES", "ET", "CS") else v for v in x]
    # W7
    last = sos
    for k in range(m):
        if x[k] in ("L", "R"):
            last = x[k]
        elif x[k] == "EN" and last == "L":
            x[k] = "L"
    # N0: BD16 finds the bracket pairs.
    stack, pairs = [], []
    for k in range(m):
        c = s[seq[k]]
        if x[k] != "ON":
            continue
        if c in OPENING:
            if len(stack) == BRACKET_STACK:  # BD16: stop and return an empty list
                pairs = []
                break
            stack.append((_canon(OPENING[c]), k))
        elif c in CLOSING:
            cc = _canon(c)
            for d in range(len(stack) - 1, -1, -1):
                if stack[d][0] == cc:
                    pairs.append((stack[d][1], k))
                    del stack[d:]
                    break
    pairs.sort()
    for o, c in pairs:  # @line L7
        inside = {_strong(x[k]) for k in range(o + 1, c)} - {None}
        if e in inside:  # N0 b
            new = e
        elif inside:  # N0 c: the opposite direction is inside
            new = sos
            for k in range(o - 1, -1, -1):
                if _strong(x[k]):
                    new = _strong(x[k])
                    break
        else:  # N0 d
            continue
        for b in (o, c):
            x[b] = new
            k = b + 1
            while k < m and original[k] == "NSM":
                x[k] = new
                k += 1
    # N1 and N2
    k = 0
    while k < m:  # @line L8
        if x[k] in NEUTRAL_OR_ISOLATE:
            j = k
            while j < m and x[j] in NEUTRAL_OR_ISOLATE:
                j += 1
            left = _strong(x[k - 1]) if k > 0 else sos
            right = _strong(x[j]) if j < m else eos
            for q in range(k, j):
                x[q] = left if left == right else e
            k = j
        else:
            k += 1
    # I1 and I2
    for k in range(m):  # @line L9
        i = seq[k]
        if lev[i] % 2 == 0:
            lev[i] += 1 if x[k] == "R" else 2 if x[k] in ("AN", "EN") else 0
        elif x[k] in ("L", "EN", "AN"):
            lev[i] += 1


def visual_order(levels: list) -> list:
    """Rule L2 on one line: the indices of the kept characters from left to right."""
    order = [i for i, v in enumerate(levels) if v is not None]  # @line L11
    if not order:
        return []
    vals = [levels[i] for i in order]
    high = max(vals)
    low = min(v for v in vals if v % 2 == 1) if any(v % 2 for v in vals) else high + 1
    for v in range(high, low - 1, -1):  # @line L12
        k = 0
        while k < len(order):
            if levels[order[k]] >= v:
                j = k
                while j < len(order) and levels[order[j]] >= v:
                    j += 1
                order[k:j] = order[k:j][::-1]
                k = j
            else:
                k += 1
    return order


def bidi(s: str, direction=None) -> tuple:
    """Run the algorithm on s, one paragraph that is shown as one line.

    direction is 0 (left to right), 1 (right to left) or None (rules P2 and P3).
    Return (paragraph level, levels, visual order). The level of a character that X9
    removes is None, and the visual order skips it.
    """
    n = len(s)
    t = [bidi_class(c) for c in s]  # @line L1
    match, _ = matching_pdi(t)
    p = direction  # @line L2
    if p is None:
        p = first_strong(t, 0, n, match) or 0
    lev, ty = explicit_levels(t, p, match)  # @line L3
    kept = [i for i in range(n) if t[i] not in REMOVED]  # @line L4
    pos = {i: k for k, i in enumerate(kept)}
    for seq in isolating_run_sequences(t, lev, match):  # @line L5
        level = lev[seq[0]]
        before = lev[kept[pos[seq[0]] - 1]] if pos[seq[0]] > 0 else p
        if t[seq[-1]] in INITIATORS or pos[seq[-1]] + 1 == len(kept):
            after = p
        else:
            after = lev[kept[pos[seq[-1]] + 1]]
        sos = "L" if max(level, before) % 2 == 0 else "R"
        eos = "L" if max(level, after) % 2 == 0 else "R"
        resolve_sequence(s, t, ty, lev, seq, sos, eos)
    levels = [None if t[i] in REMOVED else lev[i] for i in range(n)]
    trailing = True  # @line L10
    for i in range(n - 1, -1, -1):
        if t[i] in REMOVED:
            continue
        if t[i] in ("S", "B"):
            levels[i], trailing = p, True
        elif trailing and t[i] in ("WS",) + INITIATORS + ("PDI",):
            levels[i] = p
        else:
            trailing = False
    order = visual_order(levels)
    return p, levels, order  # @line L13


def reorder(s: str, direction=None) -> str:
    """The characters of s in visual order, without the characters that X9 removes."""
    return "".join(s[i] for i in bidi(s, direction)[2])
test_unicode_bidirectional_algorithm.py 193 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unicode-bidirectional-algorithm/. The authors are listed in prov/2X2V4H.jsonl.
# The Bidi_Class values come from unicodedata (unidata_version 16.0.0 with Python 3.14).
# The tests use only characters that are assigned in Unicode 3.2, except the isolate
# controls U+2066 to U+2069, which came in Unicode 6.3.
import random

from unicode_bidirectional_algorithm import MAX_DEPTH, bidi, reorder, visual_order

# The first 40 data lines of BidiCharacterTest-16.0.0.txt (Date: 2024-02-02). Fields:
# code points; paragraph direction (0 LTR, 1 RTL, 2 auto); resolved paragraph level;
# levels, with x for characters removed by X9; visual order.
CONFORMANCE = """\
05D0 05D1 0028 05D2 05D3 005B 0026 0065 0066 005D 002E 0029 0067 0068;0;0;1 1 0 1 1 0 0 0 0 0 0 0 0 0;1 0 2 4 3 5 6 7 8 9 10 11 12 13
05D0 05D1 0028 05D2 05D3 005B 0026 0065 0066 005D 002E 0029 0067 0068;1;1;1 1 1 1 1 1 1 2 2 1 1 1 2 2;12 13 11 10 9 7 8 6 5 4 3 2 1 0
0061 0062 0063 0020 0028 0064 0065 0066 0020 0627 0628 062C 0029 0020 05D0 05D1 05D2;0;0;0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 1 1;0 1 2 3 4 5 6 7 8 11 10 9 12 13 16 15 14
0061 0062 0063 0020 0028 0064 0065 0066 0020 0627 0628 062C 0029 0020 05D0 05D1 05D2;1;1;2 2 2 1 1 2 2 2 1 1 1 1 1 1 1 1 1;16 15 14 13 12 11 10 9 8 5 6 7 4 3 0 1 2
05D0 05D1 05D2 0020 0028 0064 0065 0066 0020 0627 0628 062C 0029 0020 0061 0062 0063;0;0;1 1 1 0 0 0 0 0 0 1 1 1 0 0 0 0 0;2 1 0 3 4 5 6 7 8 11 10 9 12 13 14 15 16
05D0 05D1 05D2 0020 0028 0064 0065 0066 0020 0627 0628 062C 0029 0020 0061 0062 0063;1;1;1 1 1 1 1 2 2 2 1 1 1 1 1 1 2 2 2;14 15 16 13 12 11 10 9 8 5 6 7 4 3 2 1 0
0061 0062 0063 0020 0028 0627 0628 062C 0020 0064 0065 0066 0029 0020 05D0 05D1 05D2;0;0;0 0 0 0 0 1 1 1 0 0 0 0 0 0 1 1 1;0 1 2 3 4 7 6 5 8 9 10 11 12 13 16 15 14
0061 0062 0063 0020 0028 0627 0628 062C 0020 0064 0065 0066 0029 0020 05D0 05D1 05D2;1;1;2 2 2 1 1 1 1 1 1 2 2 2 1 1 1 1 1;16 15 14 13 12 9 10 11 8 7 6 5 4 3 0 1 2
05D0 05D1 05D2 0020 0028 0627 0628 062C 0020 0064 0065 0066 0029 0020 0061 0062 0063;0;0;1 1 1 0 0 1 1 1 0 0 0 0 0 0 0 0 0;2 1 0 3 4 7 6 5 8 9 10 11 12 13 14 15 16
05D0 05D1 05D2 0020 0028 0627 0628 062C 0020 0064 0065 0066 0029 0020 0061 0062 0063;1;1;1 1 1 1 1 1 1 1 1 2 2 2 1 1 2 2 2;14 15 16 13 12 9 10 11 8 7 6 5 4 3 2 1 0
0627 0628 062C 0020 0062 006F 006F 006B 0028 0073 0029;0;0;1 1 1 0 0 0 0 0 0 0 0;2 1 0 3 4 5 6 7 8 9 10
0627 0628 062C 0020 0062 006F 006F 006B 0028 0073 0029;1;1;1 1 1 1 2 2 2 2 2 2 2;4 5 6 7 8 9 10 3 2 1 0
202E 0061 202A 0062 202C 2066 0063 2069 202A 0064 202C 0065 202C;2;0;x 1 x 2 x 1 2 1 x 2 x 1 x;11 9 7 6 5 3 1
202E 0061 202A 0062 202C 2066 0063 2069 202A 0064 202C 0065 202C;1;1;x 3 x 4 x 3 4 3 x 4 x 3 x;11 9 7 6 5 3 1
202D 05D0 202B 05D1 202C 2068 05D2 2069 202B 05D3 202C 05D4 202C;2;1;x 2 x 3 x 2 3 2 x 3 x 2 x;1 3 5 6 7 9 11
202D 0661 202B 0662 202C 2068 0663 2069 202B 0664 202C 0665 202C;0;0;x 2 x 4 x 2 6 2 x 4 x 2 x;1 3 5 6 7 9 11
202A 05D0 0028 05D1 202C 202D 0029;2;1;x 3 3 3 x x 2;3 2 1 6
202A 05D0 0028 05D1 202C 202D 0029 202C;2;1;x 3 3 3 x x 2 x;3 2 1 6
202B 0061 0028 0062 202C 202E 0029;2;0;x 2 2 2 x x 1;6 1 2 3
202B 0061 0028 0062 202C 202E 0029 202C;2;0;x 2 2 2 x x 1 x;6 1 2 3
202A 202E 0061 202C 0028 05D0 202C 202D 0029 202C;2;0;x x 3 x 3 3 x x 2 x;5 4 2 8
202B 202D 05D0 202C 0028 0061 202C 202E 0029 202C;2;1;x x 4 x 4 4 x x 3 x;8 2 4 5
202A 202E 0061 202C 0028 005B 05D0 202C 202D 005D 0029 202C;2;0;x x 3 x 3 3 3 x x 2 2 x;6 5 4 2 9 10
202B 202D 05D0 202C 0028 005B 0061 202C 202E 005D 0029 202C;2;1;x x 4 x 4 4 4 x x 3 3 x;10 9 2 4 5 6
202D 0028 202C 202A 05D0 0029 05D1;2;1;x 2 x x 3 3 3;1 6 5 4
202D 0028 202C 202A 05D0 0029 05D1 202C;2;1;x 2 x x 3 3 3 x;1 6 5 4
202E 0028 202C 202B 0061 0029 0062;2;0;x 1 x x 2 2 2;4 5 6 1
202E 0028 202C 202B 0061 0029 0062 202C;2;0;x 1 x x 2 2 2 x;4 5 6 1
202D 202E 0061 202C 0028 202C 202A 05D0 0029 05D1;2;0;x x 3 x 2 x x 3 3 3;2 4 9 8 7
202E 202D 05D0 202C 0028 202C 202B 0061 0029 0062;2;1;x x 4 x 3 x x 4 4 4;7 8 9 4 2
202D 202E 0061 202C 0028 005B 202C 202A 05D0 005D 0029 05D1;2;0;x x 3 x 2 2 x x 3 3 3 3;2 4 5 11 10 9 8
202E 202D 05D0 202C 0028 005B 202C 202B 0061 005D 0029 0062;2;1;x x 4 x 3 3 x x 4 4 4 4;8 9 10 11 5 4 2
0061 0028 0062 0029 0331;1;1;2 2 2 2 2;0 1 2 3 4
0061 0028 0332 0062 0029 0333;1;1;2 2 2 2 2 2;0 1 2 3 4 5
05D0 0028 05D1 0029 0331;0;0;1 1 1 1 1;4 3 2 1 0
05D0 0028 0332 05D1 0029 0333;0;0;1 1 1 1 1 1;5 4 3 2 1 0
0661 0028 0662 0029 0331;0;0;2 1 2 1 1;4 3 2 1 0
0661 0028 0332 0662 0029 0333;0;0;2 1 1 2 1 1;5 4 3 2 1 0
0041 200F 005B 05D0 005D 200D 20D6;0;0;0 1 1 1 1 x 1;0 6 4 3 2 1
0041 200F 005B 05D0 005D 200D 20D6;1;1;2 1 1 1 1 x 1;6 4 3 2 1 0
"""


def test_conformance_lines():
    lines = CONFORMANCE.splitlines()
    assert len(lines) == 40
    for line in lines:
        cps, d, plevel, levels, order = line.split(";")
        s = "".join(chr(int(h, 16)) for h in cps.split())
        p, lv, vis = bidi(s, None if d == "2" else int(d))
        assert p == int(plevel), line
        assert [("x" if v is None else str(v)) for v in lv] == levels.split(), line
        assert vis == [int(k) for k in order.split()], line


def test_simple_reordering():
    assert reorder("abc") == "abc"
    assert reorder("אבג") == "גבא"
    assert reorder("ab אבג cd") == "ab גבא cd"
    assert reorder("אב 12 גד", 1) == "דג 12 בא"  # numbers keep their order (I2, L2)
    assert bidi("אב")[0] == 1 and bidi("12 ab")[0] == 0 and bidi("12")[0] == 0  # P2, P3
    assert bidi("⁧ab⁩ אב")[0] == 1  # P2 skips the isolate


def test_trailing_whitespace_takes_paragraph_level():
    p, lv, _ = bidi("ab אב  ", 0)
    assert lv == [0, 0, 0, 1, 1, 0, 0]
    p, lv, _ = bidi("אב\tab", 1)  # L1: the segment separator gets the paragraph level
    assert lv == [1, 1, 1, 2, 2]


def test_overflow_of_the_stack():
    s = "‮" * 70 + "a"
    p, lv, _ = bidi(s, 0)
    assert lv[-1] == MAX_DEPTH  # 63 valid overrides reach level 125, the rest overflow
    s = "⁦" * 130 + "a" + "⁩" * 130 + "b"
    p, lv, _ = bidi(s, 0)
    assert max(v for v in lv if v is not None) <= MAX_DEPTH + 1
    assert lv[-1] == 0


def test_bracket_pairs_and_the_stack_of_bd16():
    # N0: the pair holds only R and R comes before it, so the brackets become R.
    assert bidi("א(ב)a", 0)[1] == [1, 1, 1, 1, 0]
    # Without N0, N1 would give the closing bracket the embedding direction L.
    for k, closing in ((63, 1), (64, 0)):
        s = "א" + "(" * k + "ב" + ")" * k + "a"
        lv = bidi(s, 0)[1]
        assert lv[k + 2] == closing  # at 64 openers BD16 returns no pairs at all
    # U+2329 and U+3009 form a pair, because U+2329 decomposes to U+3008.
    assert bidi("א〈ב〉a", 0)[1] == [1, 1, 1, 1, 0]
    assert bidi("א〈ב〉a", 0)[1] == [1, 1, 1, 1, 0]


def _reference_levels(s, p):
    """A direct reading of W2, W7, N1, N2, I1, I2 and L1 for text with no explicit
    formatting, no brackets and no marks: one isolating run sequence at level p."""
    import unicodedata
    t = [unicodedata.bidirectional(c) for c in s]
    e = "R" if p else "L"
    x, last = [], e
    for c in t:
        if c in ("L", "R", "AL"):
            last = c
        x.append("AN" if c == "EN" and last == "AL" else c)
    x = ["R" if v == "AL" else v for v in x]
    last = e
    for k, v in enumerate(x):
        if v in ("L", "R"):
            last = v
        elif v == "EN" and last == "L":
            x[k] = "L"
    def strong(v):
        return "L" if v == "L" else "R" if v in ("R", "EN", "AN") else None
    out = list(x)
    for k, v in enumerate(x):
        if v == "WS":
            left = next((strong(x[j]) for j in range(k - 1, -1, -1) if strong(x[j])), e)
            right = next((strong(x[j]) for j in range(k + 1, len(x)) if strong(x[j])), e)
            out[k] = left if left == right else e
    lv = []
    for v in out:
        if p == 0:
            lv.append({"L": 0, "R": 1, "EN": 2, "AN": 2}[v])
        else:
            lv.append({"L": 2, "R": 1, "EN": 2, "AN": 2}[v])
    k = len(s) - 1
    while k >= 0 and t[k] == "WS":
        lv[k] = p
        k -= 1
    return lv


def test_against_reference_on_simple_text():
    rng = random.Random(9)
    alphabet = "ab אב" + "ابت" + "12" + "١٢"
    for _ in range(600):
        s = "".join(rng.choice(alphabet) for _ in range(rng.randint(1, 10)))
        for p in (0, 1):
            assert bidi(s, p)[1] == _reference_levels(s, p), (s, p)


def _tree_order(levels, idx, v, low):
    """L2 by recursion on a block whose characters all have level v or more: the
    characters at level v stay, and each maximal sub-block above v is ordered as a block
    of level v + 1. L2 reverses the block once for v itself if v >= low, the lowest odd
    level of the line."""
    out, k = [], 0
    while k < len(idx):
        if levels[idx[k]] == v:
            out.append(idx[k])
            k += 1
        else:
            j = k
            while j < len(idx) and levels[idx[j]] > v:
                j += 1
            out.extend(_tree_order(levels, idx[k:j], v + 1, low))
            k = j
    return out[::-1] if v >= low else out


def test_l2_against_recursive_definition():
    rng = random.Random(51)
    for _ in range(800):
        n = rng.randint(0, 12)
        levels = [rng.choice([0, 1, 2, 3, 4, None]) for _ in range(n)]
        kept = [i for i in range(n) if levels[i] is not None]
        low = min((levels[i] for i in kept if levels[i] % 2 == 1), default=99)
        assert visual_order(levels) == _tree_order(levels, kept, 0, low), levels


def test_order_is_a_permutation_of_the_kept_characters():
    rng = random.Random(3)
    alphabet = "ab אב12١(),.‪‫‬‭‮⁦⁧⁨⁩‎‏́"
    for _ in range(400):
        s = "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 12)))
        for d in (0, 1, None):
            p, lv, order = bidi(s, d)
            assert sorted(order) == [i for i, v in enumerate(lv) if v is not None]
            assert all(v is None or p <= v <= MAX_DEPTH + 1 for v in lv)

History

The bidirectional algorithm has been part of the Unicode Standard since its early versions, and UAX 9 gets a new revision with each version. Directional isolates were introduced in Unicode 6.3 (2013), because embeddings often had too strong an effect on the text around them. The paired bracket rule N0 came in the same version. Revision 50, by Manish Goregaokar and Robin Leroy, is the version for Unicode 16.0.0.

References

  1. Manish Goregaokar and Robin Leroy (editors), Unicode Standard Annex 9, Unicode Bidirectional Algorithm, revision 50, 2024-09-02, Sections 3.1 (definitions BD1 to BD16), 3.3.1 to 3.3.6 (rules P1 to I2), 3.4 (rules L1 to L4), 4.4 (conformance testing) and 7 (mirroring)
  2. BidiCharacterTest-16.0.0.txt, Unicode Character Database, the conformance test lines
  3. BidiBrackets-16.0.0.txt, Unicode Character Database, the Bidi_Paired_Bracket and Bidi_Paired_Bracket_Type properties
  4. DerivedBidiClass-16.0.0.txt, Unicode Character Database, the Bidi_Class property, with the default values of unassigned code points

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example