Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,16 @@ Bracket pair detection for N0 is handled by `_find_bracket_pairs`, using `OPEN_B

### Verbose mode

Every phase function (and `_apply_i1`/`_apply_i2`) accepts `verbose=True`; the per-rule W, N and L helpers do not, and their phase function prints on their behalf. When enabled, `print_table` (in `verbose_table.py`, together with the helpers below) prints a before/after table for each rule application, with rows for character index, code point, the character itself, the type (or level, or position) before and after the rule, and embedding level. `print_table` decides "(no changes)" by comparing only the Before/After rows, so Phase X prints two tables: "X1-X8 (levels)" (Before is the paragraph level from X1) and "X1-X9 (types)" (overrides, FSI resolution, X9's BN). Without the levels table, an isolate or embedding with no override would show as "(no changes)". After phase X, `apply_bidi_algorithm` calls `print_isolating_run_sequences` (also in `verbose_table.py`), which prints the X10 sequences one line each (level, character indices as ranges, `sos`/`eos`), then the indices of the characters removed by X9. Columns are always in logical order, including the L2 and L4 tables, where Before/After give each character's position before and after reordering.
Every phase function (and `_apply_i1`/`_apply_i2`) accepts `verbose=True`; the per-rule W, N and L helpers do not, and their phase function prints on their behalf. When enabled, `print_table` (in `verbose_table.py`, together with the helpers below) prints a before/after table for each rule application, with rows for character index, code point, the character itself, the type (or level, or position) before and after the rule, and embedding level. `print_table` decides "(no changes)" by comparing only the Before/After rows, so Phase X prints two tables: "X1-X8 (levels)" (Before is the paragraph level from X1) and "X1-X9 (types)" (overrides, FSI resolution, X9's BN). Without the levels table, an isolate or embedding with no override would show as "(no changes)". After phase X, `apply_bidi_algorithm` calls `print_isolating_run_sequences` (also in `verbose_table.py`), which prints the X10 sequences one line each (level, character indices as ranges, `sos`/`eos`), then the indices of the characters removed by X9. Columns are always in logical order, including the L2 and L4 tables, where Before/After give each character's position before and after reordering. From I1 on (the I1, I2, L1, L2 and L4 tables), a character removed by X9 shows `x` as its level, in the Level row and in the I1/I2/L1 Before/After rows, and `x` as its L2 position. `print_table` does this when passed `after_x9=True`, through `format_level_for_table`. The P and X tables keep the numbers the X rules assigned, and the W and N tables never contain removed characters.

Characters in table cells go through `format_char_for_table`: controls and whitespace are left blank, combining marks are shown on a dotted circle, and each R/AL character is followed by an invisible LEFT-TO-RIGHT MARK so that bidi-aware viewers (Markdown previews, GitHub) don't reverse runs of the row. Cells are sized and centered by `display_width`/`center_in_column`, not `len()`, because those marks take no column on screen. The tracing example in README.md is copied from real output (LRMs included); update it whenever the table format changes.

### Return value

`apply_bidi_algorithm` returns `(logical_levels, reordered_text, paragraph_level, visual_order)`:
- `logical_levels` — embedding levels captured after L1 resets (before L2–L4 reordering)
- `reordered_text` — visually reordered string after all L rules, including L4 mirroring
- `logical_levels` — embedding levels captured after L1 resets (before L2–L4 reordering); one per input character, with `None` for each character removed by X9 (the demo prints it as `x`, like the conformance files; the runners compare the list directly with the file's levels, parsed with `None` for `x`)
- `reordered_text` — visually reordered string after all L rules, including L4 mirroring; characters removed by X9 are left out
- `paragraph_level` — resolved paragraph embedding level (0 = LTR, 1 = RTL)
- `visual_order` — logical index of the character at each visual position (`reordered_text[k]` comes from `text[visual_order[k]]`); the conformance runners compare this, not characters, so mirroring and duplicate characters don't affect the order check
- `visual_order` — logical index of the character at each visual position (`reordered_text[k]` comes from `text[visual_order[k]]`); characters removed by X9 are left out, as in the conformance files' expected order. The conformance runners compare this, not characters, so mirroring and duplicate characters don't affect the order check

`apply_reorder_rules` does the X9 filtering when it builds both results; `_apply_l2` leaves removed characters in their old slots of `chars`, and the verbose L2 table shows `x` as their position after reordering.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ levels, reordered, para_level, visual_order = apply_bidi_algorithm("Hello שלו
| `para_level` | The paragraph embedding level: `0` = left-to-right, `1` = right-to-left |
| `visual_order` | For each visual position, the index of the input character shown there |

The characters removed by rule X9 (the embedding and override controls LRE, RLE, LRO, RLO and PDF, and type BN) have no level: their entry in `levels` is `None` (the demo prints it as `x`), so that `levels` still lines up with the input. They are left out of `reordered` and `visual_order`.

By default the paragraph direction is detected from the first strong character (rules P2–P3). Pass `paragraph_embedding_level=0` or `1` to force it.

`apply_bidi_algorithm` handles one paragraph. If your text may contain several (for example, several lines), split it first with `split_into_paragraphs` (rule P1) and run each part; each paragraph then gets its own direction:
Expand All @@ -70,7 +72,7 @@ for paragraph in split_into_paragraphs("שלום\nHello"):

## Tracing the algorithm

Pass `verbose=True` to see every rule as it runs. Rules that change nothing print a single line; rules that do change something print a table showing each character's index, its code point, the character itself, its type (or level) before and after the rule, and its embedding level. Changed cells are highlighted in the terminal. Phase X prints two tables, one for the levels it assigns and one for the types it changes, so that an embedding or isolate shows up even when no type changes. Rule X10 then lists the isolating run sequences, one line each, with their level, characters and `sos`/`eos`, followed by the characters removed by X9, which belong to no sequence.
Pass `verbose=True` to see every rule as it runs. Rules that change nothing print a single line; rules that do change something print a table showing each character's index, its code point, the character itself, its type (or level) before and after the rule, and its embedding level. Changed cells are highlighted in the terminal. Phase X prints two tables, one for the levels it assigns and one for the types it changes, so that an embedding or isolate shows up even when no type changes. Rule X10 then lists the isolating run sequences, one line each, with their level, characters and `sos`/`eos`, followed by the characters removed by X9, which belong to no sequence. From rule I1 on, the tables show `x` as the level of those removed characters.

```python
apply_bidi_algorithm("שלום 123 Hi", verbose=True)
Expand Down
80 changes: 54 additions & 26 deletions bidi.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@
from typing import NamedTuple

# Formatting of the verbose-mode tables; not part of the algorithm itself.
from verbose_table import print_table, print_isolating_run_sequences, format_char_for_table
from verbose_table import (print_table, print_isolating_run_sequences,
format_char_for_table, format_level_for_table)

# Three lookup tables are read, at import time, from the Unicode Character
# Database (UCD) files kept unchanged in the ucd/ folder (see ucd_data.py for how):
Expand Down Expand Up @@ -948,7 +949,7 @@ def apply_neutral_rules(chars: list[CharacterInfo], sequences: list[dict],
def _apply_i1(chars: list[CharacterInfo], verbose: bool = False) -> None:
"""I1: For characters at an even (L) level — R goes up one, AN and EN go up two."""
if verbose:
before = [ci.embedding_level for ci in chars]
before = [format_level_for_table(ci) for ci in chars]
for ci in chars:
if ci.character_type == 'BN':
continue
Expand All @@ -958,23 +959,23 @@ def _apply_i1(chars: list[CharacterInfo], verbose: bool = False) -> None:
elif ci.character_type in ('AN', 'EN'):
ci.embedding_level += 2
if verbose:
after = [ci.embedding_level for ci in chars]
print_table("I1", chars, [str(l) for l in before], [str(l) for l in after])
after = [format_level_for_table(ci) for ci in chars]
print_table("I1", chars, before, after, after_x9=True)


def _apply_i2(chars: list[CharacterInfo], verbose: bool = False) -> None:
"""I2: For characters at an odd (R) level — L, EN, and AN go up one."""
if verbose:
before = [ci.embedding_level for ci in chars]
before = [format_level_for_table(ci) for ci in chars]
for ci in chars:
if ci.character_type == 'BN':
continue
if ci.embedding_level % 2 == 1: # odd
if ci.character_type in ('L', 'EN', 'AN'):
ci.embedding_level += 1
if verbose:
after = [ci.embedding_level for ci in chars]
print_table("I2", chars, [str(l) for l in before], [str(l) for l in after])
after = [format_level_for_table(ci) for ci in chars]
print_table("I2", chars, before, after, after_x9=True)


def apply_implicit_rules(chars: list[CharacterInfo], verbose: bool = False) -> None:
Expand Down Expand Up @@ -1035,12 +1036,11 @@ def _apply_l2(chars: list[CharacterInfo]) -> None:
L2: From highest to lowest odd level, reverse each maximal contiguous
sequence of chars at that level or higher.

BN characters (removed by rule X9) are transparent to this algorithm:
they are excluded from run detection so they do not split runs of
visible characters at higher embedding levels. After reordering the
visible characters, BN characters are left in their original relative
positions within the chars list (they will be filtered out by the
caller when building the final visual string).
Characters removed by rule X9 are left out of run detection, so they
do not split runs of visible characters at higher embedding levels.
After reordering the visible characters, the removed characters are
left in their original slots in the chars list; apply_reorder_rules
leaves them out of the visual order and the reordered text.
"""
if not chars:
return
Expand Down Expand Up @@ -1124,6 +1124,9 @@ def apply_reorder_rules(
"""
L2-L4: Apply visual reordering (L1 must be applied before calling).

Characters removed by rule X9 (RLE, LRE, RLO, LRO, PDF, BN) have no
place in the visual order, so they are left out of both results.

Returns:
(reordered_text, visual_order)
reordered_text: the characters in visual order, with L4 mirroring applied
Expand All @@ -1139,16 +1142,24 @@ def apply_reorder_rules(
if verbose:
# For each character, report its position before L2 (its logical
# index) and its position after L2 (where it is displayed).
# Characters removed by X9 are not displayed, so they get 'x'.
visual_position_of = {}
for position, ci in enumerate(chars):
visual_position_of[ci.index] = position
position = 0
for ci in chars:
if ci.original_type not in X9_REMOVE_TYPES:
visual_position_of[ci.index] = position
position += 1
before_positions = []
after_positions = []
for ci in logical_chars:
before_positions.append(str(ci.index))
after_positions.append(str(visual_position_of[ci.index]))
if ci.index in visual_position_of:
after_positions.append(str(visual_position_of[ci.index]))
else:
after_positions.append('x')
print("=== After L2: Visual Reorder ===")
print_table("L2", logical_chars, before_positions, after_positions)
print_table("L2", logical_chars, before_positions, after_positions,
after_x9=True)

_apply_l3(chars)

Expand All @@ -1160,13 +1171,21 @@ def apply_reorder_rules(
after_chars = [format_char_for_table(ci.character)
for ci in logical_chars]
print("=== After L4: Mirror ===")
print_table("L4", logical_chars, before_chars, after_chars)
print_table("L4", logical_chars, before_chars, after_chars,
after_x9=True)

# The list is now in visual order. Each CharacterInfo still remembers
# its logical position in ci.index, so we can report both the displayed
# text (including mirrored glyphs) and where each character came from.
reordered_text = ''.join(ci.character for ci in chars)
visual_order = [ci.index for ci in chars]
# Rule X9 removed the embedding and override controls (and BN), so they
# are not part of the displayed text.
reordered_text = ''
visual_order = []
for ci in chars:
if ci.original_type in X9_REMOVE_TYPES:
continue
reordered_text += ci.character
visual_order.append(ci.index)

return reordered_text, visual_order

Expand All @@ -1179,7 +1198,7 @@ def apply_bidi_algorithm(
text: str,
verbose: bool = False,
paragraph_embedding_level: int | None = None,
) -> tuple[list[int], str, int, list[int]]:
) -> tuple[list[int | None], str, int, list[int]]:
"""
Apply the Unicode Bidirectional Algorithm (UAX #9) to one paragraph.

Expand All @@ -1194,10 +1213,13 @@ def apply_bidi_algorithm(
Returns:
(logical_levels, reordered_text, paragraph_level, visual_order)
logical_levels: resolved embedding levels in logical (input) order, after L1 resets
(one per input character; None for each character removed by X9)
reordered_text: visually reordered string, with L4 mirroring applied
(without the characters removed by X9)
paragraph_level: resolved paragraph embedding level (0=LTR, 1=RTL)
visual_order: for each visual position, the logical index of the
character shown there (so reordered_text[k] comes from text[visual_order[k]])
character shown there (so reordered_text[k] comes from text[visual_order[k]]);
the characters removed by X9 have no visual position
"""
if not text:
if paragraph_embedding_level is not None:
Expand Down Expand Up @@ -1257,13 +1279,19 @@ def apply_bidi_algorithm(
# reset levels are part of the "resolved" levels that conformance tests
# check. Apply L1 now, capture levels, then run L2-L4 for reordering.
if verbose:
before_levels = [str(ci.embedding_level) for ci in chars]
before_levels = [format_level_for_table(ci) for ci in chars]
_apply_l1(chars, paragraph_level)
if verbose:
after_levels = [str(ci.embedding_level) for ci in chars]
after_levels = [format_level_for_table(ci) for ci in chars]
print("=== After L1: Level Reset ===")
print_table("L1", chars, before_levels, after_levels)
logical_levels = [ci.embedding_level for ci in chars]
print_table("L1", chars, before_levels, after_levels, after_x9=True)
# Characters removed by X9 have no level in the result: None.
logical_levels = []
for ci in chars:
if ci.original_type in X9_REMOVE_TYPES:
logical_levels.append(None)
else:
logical_levels.append(ci.embedding_level)

reordered_text, visual_order = apply_reorder_rules(chars, verbose=verbose)

Expand Down
15 changes: 12 additions & 3 deletions demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,9 @@
"LRE/PDF explicit embedding",
"The X1-X8 (levels) table puts the text between LRE and PDF at level 2, so the Hebrew word "
"ends up at level 3 after I1; the X1-X9 (types) table shows X9 turning LRE and PDF into BN. "
"X9 removes them, so X10 leaves them out of every isolating run sequence, and the W and N "
"tables show only characters 1-10.",
"X9 removes them, so X10 leaves them out of every isolating run sequence, the W and N "
"tables show only characters 1-10, and from I1 on their level is x. The L2 table gives "
"them no visual position (x), so they are missing from the visual order and the reordered text.",
),
(
"הוא אמר: ״[LRI]Car is מכונית in Hebrew[PDI]״.[RLM]",
Expand Down Expand Up @@ -197,7 +198,15 @@ def run_paragraph(text: str, title: str, note: str | None, direction: str, brief
if not brief:
print()
print(f"Paragraph level: {para_level}")
print(f"Embedding levels: {levels}")
# Characters removed by rule X9 have no level (None); show them as x,
# as the Unicode conformance files do.
level_texts = []
for level in levels:
if level is None:
level_texts.append('x')
else:
level_texts.append(str(level))
print(f"Embedding levels: [{', '.join(level_texts)}]")
print(f"Visual order: {visual_order}")
print(f"Reordered text: {show_controls_as_tags(reordered)}")
print()
Expand Down
Loading
Loading