diff --git a/CLAUDE.md b/CLAUDE.md index fdc4f3e..4137018 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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. diff --git a/README.md b/README.md index c93b737..0c7f7e4 100644 --- a/README.md +++ b/README.md @@ -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: @@ -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) diff --git a/bidi.py b/bidi.py index 0ba1537..6c794a0 100644 --- a/bidi.py +++ b/bidi.py @@ -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): @@ -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 @@ -958,14 +959,14 @@ 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 @@ -973,8 +974,8 @@ def _apply_i2(chars: list[CharacterInfo], verbose: bool = False) -> None: 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: @@ -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 @@ -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 @@ -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) @@ -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 @@ -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. @@ -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: @@ -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) diff --git a/demo.py b/demo.py index 788bd1e..79654e5 100644 --- a/demo.py +++ b/demo.py @@ -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]", @@ -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() diff --git a/tests/run_bidi_tests.py b/tests/run_bidi_tests.py index a99b5ca..9816678 100644 --- a/tests/run_bidi_tests.py +++ b/tests/run_bidi_tests.py @@ -38,7 +38,7 @@ def fmt(seq, other): return fmt(a, b), fmt(b, a) # Bidi types removed by rule X9. Characters with these original types are -# excluded from the expected levels and visual order fields in the test file. +# shown as 'x' in the expected levels field and left out of the visual order. X9_TYPES = frozenset({"RLE", "LRE", "RLO", "LRO", "PDF", "BN"}) @@ -107,34 +107,27 @@ def run_test(tc: TestCase) -> tuple[bool, str]: f"FAIL line {tc.line_number} | dir={tc.direction} | " f"logical_levels length {len(logical_levels)} != text length {len(tc.text)}" ) - if len(reordered_text) != len(tc.text): + # Characters removed by X9 are left out of the reordered text and visual order. + kept_count = sum(1 for ch in tc.text if unicodedata.bidirectional(ch) not in X9_TYPES) + if len(reordered_text) != kept_count: return False, ( f"FAIL line {tc.line_number} | dir={tc.direction} | " - f"reordered_text length {len(reordered_text)} != text length {len(tc.text)}" + f"reordered_text length {len(reordered_text)} != non-X9 character count {kept_count}" ) - if len(visual_order) != len(tc.text): + if len(visual_order) != kept_count: return False, ( f"FAIL line {tc.line_number} | dir={tc.direction} | " - f"visual_order length {len(visual_order)} != text length {len(tc.text)}" + f"visual_order length {len(visual_order)} != non-X9 character count {kept_count}" ) - actual_levels = [ - level - for ch, level in zip(tc.text, logical_levels) - if unicodedata.bidirectional(ch) not in X9_TYPES - ] - expected_levels_filtered = [lvl for lvl in tc.expected_levels if lvl is not None] - - levels_ok = actual_levels == expected_levels_filtered + # Both lists use None for the characters removed by X9 ('x' in the file). + levels_ok = logical_levels == tc.expected_levels # --- Compare paragraph level (only meaningful for auto-detect) --- para_level_ok = actual_para_level == tc.para_level # --- Compare visual order (by logical index, so L4 mirroring doesn't matter) --- - actual_order = [ - i for i in visual_order - if unicodedata.bidirectional(tc.text[i]) not in X9_TYPES - ] + actual_order = visual_order order_ok = actual_order == tc.expected_order @@ -146,7 +139,7 @@ def run_test(tc: TestCase) -> tuple[bool, str]: if not para_level_ok: lines.append(f" para_level expected: {tc.para_level} actual: {actual_para_level}") if not levels_ok: - exp_str, act_str = _highlight_diff(expected_levels_filtered, actual_levels) + exp_str, act_str = _highlight_diff(tc.expected_levels, logical_levels) lines.append(f" levels expected: {exp_str}") lines.append(f" actual: {act_str}") if not order_ok: diff --git a/tests/run_bidi_type_tests.py b/tests/run_bidi_type_tests.py index a76608f..a610449 100644 --- a/tests/run_bidi_type_tests.py +++ b/tests/run_bidi_type_tests.py @@ -183,26 +183,27 @@ def run_test(tc: TestCase) -> tuple[bool, str]: f"logical_levels length {len(logical_levels)} != text length {len(text)}\n" f" chars={chars_repr}" ) - if len(reordered_text) != len(text): + # Characters removed by X9 are left out of the reordered text and visual order. + kept_count = sum(1 for tp in tc.types if tp not in X9_TYPES) + if len(reordered_text) != kept_count: return False, ( f"FAIL line {tc.line_number} | dir={_MODE_NAMES[tc.para_mode]} | " - f"reordered_text length {len(reordered_text)} != text length {len(text)}\n" + f"reordered_text length {len(reordered_text)} != non-X9 character count {kept_count}\n" f" chars={chars_repr}" ) - if len(visual_order) != len(text): + if len(visual_order) != kept_count: return False, ( f"FAIL line {tc.line_number} | dir={_MODE_NAMES[tc.para_mode]} | " - f"visual_order length {len(visual_order)} != text length {len(text)}\n" + f"visual_order length {len(visual_order)} != non-X9 character count {kept_count}\n" f" chars={chars_repr}" ) # --- Levels check --- - actual_levels = [lvl for tp, lvl in zip(tc.types, logical_levels) if tp not in X9_TYPES] - expected_levels_filtered = [l for l in tc.expected_levels if l is not None] - levels_ok = actual_levels == expected_levels_filtered + # Both lists use None for the characters removed by X9 ('x' in the file). + levels_ok = logical_levels == tc.expected_levels # --- Reorder check (by logical index, so duplicate or mirrored characters don't matter) --- - actual_reorder = [i for i in visual_order if tc.types[i] not in X9_TYPES] + actual_reorder = visual_order reorder_ok = actual_reorder == tc.expected_reorder if levels_ok and reorder_ok: @@ -213,7 +214,7 @@ def run_test(tc: TestCase) -> tuple[bool, str]: f" chars={chars_repr}", ] if not levels_ok: - exp_str, act_str = _highlight_diff(expected_levels_filtered, actual_levels) + exp_str, act_str = _highlight_diff(tc.expected_levels, logical_levels) lines.append(f" levels expected: {exp_str}") lines.append(f" actual: {act_str}") if not reorder_ok: diff --git a/verbose_table.py b/verbose_table.py index d334946..4b63ac1 100644 --- a/verbose_table.py +++ b/verbose_table.py @@ -37,6 +37,20 @@ def format_char_for_table(ch: str) -> str: return ch +def format_level_for_table(ci) -> str: + """ + Return how a character's embedding level is shown in a verbose table + printed after rule X9. + + Once rule X9 has removed a character (its character_type is then BN), + it has no level, so it is shown as 'x', as in the Unicode conformance + files. + """ + if ci.character_type == 'BN': + return 'x' + return str(ci.embedding_level) + + def display_width(text: str) -> int: """ Return the number of terminal columns text occupies. @@ -115,15 +129,19 @@ def print_isolating_run_sequences(sequences: list[dict], chars: list) -> None: def print_table(rule_name: str, chars: list, types_before: list[str], types_after: list[str], - irs_label: str = '') -> None: + irs_label: str = '', after_x9: bool = False) -> None: """ Print a before/after table showing the effect of a single rule application. chars is a list of bidi.CharacterInfo objects; only their index, - character and embedding_level are read. types_before and types_after are - parallel lists of Bidi type strings, one entry per element of chars. + character, character_type and embedding_level are read. types_before + and types_after are parallel lists of Bidi type strings, one entry per + element of chars. irs_label, when provided, is appended to the header to identify the isolating run sequence (e.g. "IRS level=2"). + after_x9, when True, shows the Level of each character removed by rule + X9 as 'x' (see format_level_for_table). The tables of phases P and X + leave it False, so they show the levels the X rules assigned. Prints nothing beyond the header line when types_before == types_after. Changed cells in the After row are highlighted with BOLD_YELLOW ANSI colour. @@ -149,7 +167,12 @@ def print_table(rule_name: str, chars: list, before_cells = list(types_before) after_cells = list(types_after) after_changed = [b != a for b, a in zip(types_before, types_after)] - level_cells = [str(ci.embedding_level) for ci in chars] + level_cells = [] + for ci in chars: + if after_x9: + level_cells.append(format_level_for_table(ci)) + else: + level_cells.append(str(ci.embedding_level)) # Compute column widths col_widths = []