diff --git a/CLAUDE.md b/CLAUDE.md index 4999a5a..c2e6e41 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Overview -A pure-Python implementation of the Unicode Bidirectional Algorithm (UAX #9), targeting Unicode 17.0. The entire algorithm lives in a single file: [bidi.py](bidi.py). The tables printed in verbose mode are formatted by [verbose_table.py](verbose_table.py), which holds no algorithm logic. The algorithm uses lookup tables built from two Unicode Character Database files, kept unchanged in [ucd/](ucd/): `BidiBrackets.txt` and `BidiMirroring.txt` (currently Unicode 17.0.0). They are read by [ucd_data.py](ucd_data.py), which also holds no algorithm logic. To update the data, replace these files; do not hand-copy their contents into code. +A pure-Python implementation of the Unicode Bidirectional Algorithm (UAX #9), targeting Unicode 17.0. The entire algorithm lives in a single file: [bidi.py](bidi.py). The tables printed in verbose mode are formatted by [verbose_table.py](verbose_table.py), which holds no algorithm logic. The algorithm uses lookup tables built from two Unicode Character Database files, kept unchanged in [ucd/](ucd/): `BidiBrackets.txt` and `BidiMirroring.txt` (currently Unicode 17.0.0). They are read by [ucd_data.py](ucd_data.py), which also holds no algorithm logic. The command-line demo lives in [demo.py](demo.py), again with no algorithm logic; the `__main__` block of `bidi.py` only calls `demo.main()`. To update the data, replace these files; do not hand-copy their contents into code. No external dependencies — only Python stdlib (`unicodedata`, `dataclasses`, `pathlib`). @@ -35,10 +35,15 @@ python tests/run_bidi_type_tests.py [--max-failures N] [--lines START-END] [--fa ## Commands -**Run the built-in demo** (six example strings with verbose output): +**Run the demo** (`demo.py`, reached through `bidi.py`): ```bash -python bidi.py +python bidi.py # list the six built-in examples and usage hints +python bidi.py --all # run every example with verbose output +python bidi.py --example N # run one example +python bidi.py "text" # run your own text +python bidi.py --file PATH # run the text in a UTF-8 file ``` +Every mode accepts `--brief` (results only, no tables) and `--direction {auto,ltr,rtl}` (passed as `paragraph_embedding_level`). User text (argument or file) and the built-in `EXAMPLES` may contain `[LRI]`-style tags for the bidi controls and `\uXXXX` / `\UXXXXXXXX` escapes; `expand_escapes_and_tags` turns them into characters before the text is run. Write controls in `EXAMPLES` as tags, not escapes. `show_controls_as_tags` does the reverse for the printed Input and Reordered text lines. Because `bidi.py` does not implement P1, `split_into_paragraphs` splits user text after each type-B character (CR LF counts as one) and runs each paragraph separately. Each built-in example in `EXAMPLES` carries a "Watch for" note; if you change an example, check that its note still matches the verbose output. `main()` calls `sys.stdout.reconfigure(encoding="utf-8")` so Hebrew/Arabic output works in Windows consoles. **Use as a library:** ```python diff --git a/README.md b/README.md index 5eb7033..a8eb3e6 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ A readable, pure-Python implementation of the [Unicode Bidirectional Algorithm ( The bidi algorithm decides how text that mixes left-to-right scripts (Latin, Cyrillic, …) with right-to-left scripts (Hebrew, Arabic, …) is laid out on screen. This project is meant for **learning how that algorithm works**. It favours clarity over speed or brevity: -- The whole algorithm is in one file, [bidi.py](bidi.py), with no dependencies beyond the Python standard library. The two Unicode data files it needs are kept, unchanged, in [ucd/](ucd/), and are read by [ucd_data.py](ucd_data.py). The tables printed in verbose mode are formatted separately, in [verbose_table.py](verbose_table.py). Neither file holds any algorithm logic; they are kept apart so that file reading and formatting code don't clutter the algorithm. +- The whole algorithm is in one file, [bidi.py](bidi.py), with no dependencies beyond the Python standard library. The two Unicode data files it needs are kept, unchanged, in [ucd/](ucd/), and are read by [ucd_data.py](ucd_data.py). The tables printed in verbose mode are formatted separately, in [verbose_table.py](verbose_table.py), and the command-line demo lives in [demo.py](demo.py). None of these files holds any algorithm logic; they are kept apart so that file reading, formatting and command-line code don't clutter the algorithm. - Each UAX #9 rule has its own function, named after the rule (`_apply_w1`, `_apply_n0`, `_apply_l2`, …), so you can read the code next to the spec. - A **verbose mode** prints a before/after table every time a rule is applied, so you can follow a string through the algorithm step by step. @@ -18,7 +18,27 @@ cd UnicodeBidiAlgorithm python bidi.py ``` -This runs a set of example strings (pure LTR, pure RTL, mixed text with digits, explicit embeddings, isolates, and brackets) through the full algorithm with verbose output. +This lists the built-in examples (pure LTR, pure RTL, mixed text with digits, explicit embeddings, isolates, and brackets) and shows how to run them: + +```bash +python bidi.py --example 3 # run one example, printing a table for every rule +python bidi.py --all # run all the examples +python bidi.py "Hello שלום" # run your own text +python bidi.py --file input.txt # run the text in a UTF-8 file +``` + +Each example comes with a note on what to look for in its output. Two options work in every mode: + +- `--brief` prints only the results (levels, visual order, reordered text) without the rule-by-rule tables. +- `--direction ltr` or `--direction rtl` sets the paragraph direction instead of detecting it. Running the same text both ways is a good way to see what the paragraph level changes. + +Bidi control characters are invisible and hard to type, so your text can name them with tags: `[LRE]`, `[RLE]`, `[PDF]`, `[LRO]`, `[RLO]`, `[LRI]`, `[RLI]`, `[FSI]`, `[PDI]`, `[LRM]`, `[RLM]`, `[ALM]`. Any character can also be written as `\uXXXX`. The built-in examples are written the same way, and the demo prints control characters as tags in its input and output lines. For example: + +```bash +python bidi.py "[RLI]Hello[PDI] שלום" +``` + +Text with several paragraphs (for example, several lines in a file) is run one paragraph at a time. The demo itself lives in [demo.py](demo.py), so that `bidi.py` holds only the algorithm. ## Using it as a library @@ -93,7 +113,7 @@ Some things to know when reading the code: ## Scope and caveats -- The input is treated as a single paragraph; the algorithm does not split text at paragraph separators (rule P1). +- `apply_bidi_algorithm` treats its input as a single paragraph; it does not split text at paragraph separators (rule P1). The command-line demo does this splitting before calling it. - Line breaking is not handled: the L rules treat the whole input as one line. - Bidi classes come from Python's `unicodedata` module, so they follow the Unicode version built into your Python, which may be older than 17.0 (for example, Python 3.14 uses Unicode 16.0). Characters added in later Unicode versions may then get the wrong bidi class. - Rule L3 (combining marks) takes no action. The spec leaves this to the renderer. diff --git a/bidi.py b/bidi.py index 7e7f0b2..efecebf 100644 --- a/bidi.py +++ b/bidi.py @@ -14,7 +14,8 @@ Demo: python bidi.py - Runs built-in example strings through the full algorithm with verbose output. + Lists the built-in examples and shows how to run one of them, all of + them, or your own text with verbose output. See demo.py. """ import unicodedata @@ -1244,24 +1245,9 @@ def apply_bidi_algorithm( # SECTION: Demo # ============================================================ +# The command-line demo (built-in examples, your own text, options) lives in +# demo.py, so that this file holds only the algorithm. + if __name__ == '__main__': - examples = [ - ("Hello, World!", "Pure LTR"), - ("שלום", "Pure RTL (Hebrew: shalom)"), - ("שלום 123 Hi", "Mixed RTL+digits+LTR"), - ("\u202AHello שלום\u202C", "LRE/PDF explicit embedding"), - ("הוא אמר: ״\u2066Car is מכונית in Hebrew\u2069״.\u200f", "LRI/FSI isolate"), - ('He said “שלום”', "Neutral brackets + N0"), - ] - - for text, description in examples: - print("=" * 60) - print(f"Example: {description}") - print(f"Input: {repr(text)}") - print() - levels, reordered, para_level, visual_order = apply_bidi_algorithm(text, verbose=True) - print(f"Paragraph level: {para_level}") - print(f"Embedding levels: {levels}") - print(f"Visual order: {visual_order}") - print(f"Reordered text: {repr(reordered)}") - print() + import demo + demo.main() diff --git a/demo.py b/demo.py new file mode 100644 index 0000000..c80b584 --- /dev/null +++ b/demo.py @@ -0,0 +1,289 @@ +""" +Command-line demo for the Unicode Bidirectional Algorithm in bidi.py. + +This file only handles the command line: choosing the input text, reading +escapes and tags in it, and printing the results. It holds no algorithm logic. + +Usage: + python bidi.py List the built-in examples + python bidi.py --all Run every built-in example + python bidi.py --example 3 Run built-in example 3 + python bidi.py "Hello שלום" Run your own text + python bidi.py --file input.txt Run the text in a UTF-8 file + +Options for every mode: + --direction {auto,ltr,rtl} Paragraph direction (default: auto, rules P2-P3) + --brief Print only the results, not the rule-by-rule tables +""" + +import argparse +import re +import sys +import unicodedata + +from bidi import apply_bidi_algorithm + + +# ============================================================ +# Built-in examples +# ============================================================ +# +# Each example is (text, title, what to watch for in the verbose output). +# Bidi control characters are written as tags such as [LRI], the same way +# you can write them in your own text (see expand_escapes_and_tags below). + +EXAMPLES = [ + ( + "Hello, World!", + "Pure LTR", + "Everything stays at level 0, so L2 leaves the order unchanged.", + ), + ( + "שלום", + "Pure RTL (Hebrew: shalom)", + "P2 finds R first, so the paragraph is RTL (level 1); L2 reverses the whole string.", + ), + ( + "שלום 123 Hi", + "Mixed RTL + digits + LTR", + "N1 turns the space before the digits into R; I2 raises the digits and Latin letters to level 2.", + ), + ( + "[LRE]Hello שלום[PDF]", + "LRE/PDF explicit embedding", + "X1-X9 put the text between LRE and PDF at level 2, so the Hebrew word ends up at level 3 after I1.", + ), + ( + "הוא אמר: ״[LRI]Car is מכונית in Hebrew[PDI]״.[RLM]", + "LRI/PDI isolate", + "The text between LRI and PDI forms its own isolating run sequence (level 2), " + "separate from the Hebrew sentence around it (level 1).", + ), + ( + "Hello שלום (עולם)", + "Brackets (N0) and mirroring (L4)", + "N0 makes both parentheses R, because they hold Hebrew text that follows Hebrew; " + "L4 then mirrors them in the reordered text.", + ), +] + + +# ============================================================ +# Writing bidi controls as tags and escapes +# ============================================================ +# +# Bidi control characters are invisible and hard to type on a command line, +# so user text may name them with a tag such as [RLI], or give any character +# as an escape such as ⁧. + +CONTROL_TAGS = { + 'LRE': '‪', # LEFT-TO-RIGHT EMBEDDING + 'RLE': '‫', # RIGHT-TO-LEFT EMBEDDING + 'PDF': '‬', # POP DIRECTIONAL FORMATTING + 'LRO': '‭', # LEFT-TO-RIGHT OVERRIDE + 'RLO': '‮', # RIGHT-TO-LEFT OVERRIDE + 'LRI': '⁦', # LEFT-TO-RIGHT ISOLATE + 'RLI': '⁧', # RIGHT-TO-LEFT ISOLATE + 'FSI': '⁨', # FIRST STRONG ISOLATE + 'PDI': '⁩', # POP DIRECTIONAL ISOLATE + 'LRM': '‎', # LEFT-TO-RIGHT MARK + 'RLM': '‏', # RIGHT-TO-LEFT MARK + 'ALM': '؜', # ARABIC LETTER MARK +} + + +def _replace_tag(match: re.Match) -> str: + name = match.group(1) + if name in CONTROL_TAGS: + return CONTROL_TAGS[name] + # Not a known tag (for example "[x]"): keep the text as written. + return match.group(0) + + +def _replace_escape(match: re.Match) -> str: + hex_digits = match.group(1) or match.group(2) + return chr(int(hex_digits, 16)) + + +def expand_escapes_and_tags(text: str) -> str: + """Replace [TAG] names and \\uXXXX / \\UXXXXXXXX escapes with real characters.""" + text = re.sub(r'\[([A-Z]{3})\]', _replace_tag, text) + text = re.sub(r'\\u([0-9A-Fa-f]{4})|\\U([0-9A-Fa-f]{8})', _replace_escape, text) + return text + + +def show_controls_as_tags(text: str) -> str: + """ + Quote text for printing, showing each bidi control character as its tag. + + This is the reverse of expand_escapes_and_tags for the controls, so the + input and output lines can be read and copied back onto the command line. + """ + shown = '' + for ch in text: + tag = None + for name, control in CONTROL_TAGS.items(): + if ch == control: + tag = name + if tag is not None: + shown += f'[{tag}]' + else: + shown += ch + return repr(shown) + + +# ============================================================ +# Splitting user text into paragraphs +# ============================================================ + +def split_into_paragraphs(text: str) -> list[str]: + """ + Split text after each paragraph separator (bidi type B, such as a newline). + + bidi.py does not implement rule P1 and treats its input as one paragraph, + so the demo does the splitting itself. As P1 says, each separator stays + at the end of the paragraph it closes. CR LF counts as a single separator. + """ + paragraphs = [] + current = '' + for i, ch in enumerate(text): + current += ch + if unicodedata.bidirectional(ch) != 'B': + continue + next_is_lf = i + 1 < len(text) and text[i + 1] == '\n' + if ch == '\r' and next_is_lf: + continue # the LF that follows ends this paragraph + paragraphs.append(current) + current = '' + if current: + paragraphs.append(current) + return paragraphs + + +# ============================================================ +# Running and printing +# ============================================================ + +DIRECTION_TO_LEVEL = {'auto': None, 'ltr': 0, 'rtl': 1} + + +def run_text(text: str, title: str, note: str | None, direction: str, brief: bool) -> None: + print("=" * 60) + print(title) + print(f"Input: {show_controls_as_tags(text)}") + if note: + print(f"Watch for: {note}") + print() + + levels, reordered, para_level, visual_order = apply_bidi_algorithm( + text, + verbose=not brief, + paragraph_embedding_level=DIRECTION_TO_LEVEL[direction], + ) + + if not brief: + print() + print(f"Paragraph level: {para_level}") + print(f"Embedding levels: {levels}") + print(f"Visual order: {visual_order}") + print(f"Reordered text: {show_controls_as_tags(reordered)}") + print() + + +def list_examples() -> None: + print("Built-in examples:") + for number, (text, title, _note) in enumerate(EXAMPLES, start=1): + print(f" {number}. {title:<34} {repr(text)}") + print() + print("Try:") + print(" python bidi.py --example 3 run one example, showing every rule") + print(" python bidi.py --all run all the examples") + print(' python bidi.py "Hello שלום" run your own text') + print(' python bidi.py "[RLI]Hi[PDI] שלום" name control characters with tags (or \\u2067)') + print(" python bidi.py --file input.txt run the text in a UTF-8 file") + print() + print("Add --brief to skip the tables, or --direction ltr/rtl to set the paragraph direction.") + print("Run python bidi.py --help for details.") + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="python bidi.py", + description="Trace the Unicode Bidirectional Algorithm (UAX #9) rule by rule.", + epilog=( + "Bidi control characters can be written as tags: " + + ", ".join(f"[{name}]" for name in CONTROL_TAGS) + + ". Any character can also be written as \\uXXXX or \\UXXXXXXXX. " + "Text with several paragraphs (for example, several lines) is run one paragraph at a time." + ), + ) + source = parser.add_mutually_exclusive_group() + source.add_argument("text", nargs="?", help="your own text to run") + source.add_argument("--all", action="store_true", help="run every built-in example") + source.add_argument("--example", type=int, metavar="N", help="run built-in example N") + source.add_argument("--file", metavar="PATH", help="run the text in a UTF-8 file") + parser.add_argument( + "--direction", + choices=["auto", "ltr", "rtl"], + default="auto", + help="paragraph direction (default: auto, detected by rules P2-P3)", + ) + parser.add_argument( + "--brief", + action="store_true", + help="print only the results, not the rule-by-rule tables", + ) + return parser + + +def main(argv: list[str] | None = None) -> None: + # Windows consoles may not use UTF-8 by default, which makes printing + # Hebrew or Arabic fail. + sys.stdout.reconfigure(encoding="utf-8") + + parser = build_parser() + args = parser.parse_args(argv) + + if args.all: + for number, (text, title, note) in enumerate(EXAMPLES, start=1): + text = expand_escapes_and_tags(text) + run_text(text, f"Example {number}: {title}", note, args.direction, args.brief) + return + + if args.example is not None: + if not 1 <= args.example <= len(EXAMPLES): + parser.error(f"--example must be between 1 and {len(EXAMPLES)}") + text, title, note = EXAMPLES[args.example - 1] + text = expand_escapes_and_tags(text) + run_text(text, f"Example {args.example}: {title}", note, args.direction, args.brief) + return + + if args.file is not None: + try: + with open(args.file, encoding="utf-8") as f: + user_text = f.read() + except (OSError, UnicodeDecodeError) as error: + parser.error(f"cannot read {args.file}: {error}") + elif args.text is not None: + user_text = args.text + else: + list_examples() + return + + user_text = expand_escapes_and_tags(user_text) + paragraphs = split_into_paragraphs(user_text) + if not paragraphs: + parser.error("the text is empty") + + if len(paragraphs) == 1: + run_text(paragraphs[0], "Your text", None, args.direction, args.brief) + return + + print(f"The text has {len(paragraphs)} paragraphs; each is run separately (rule P1).") + print() + for number, paragraph in enumerate(paragraphs, start=1): + run_text(paragraph, f"Paragraph {number}", None, args.direction, args.brief) + + +if __name__ == '__main__': + main()