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
11 changes: 8 additions & 3 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`).

Expand Down Expand Up @@ -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
Expand Down
26 changes: 23 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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

Expand Down Expand Up @@ -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.
Expand Down
28 changes: 7 additions & 21 deletions bidi.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Loading
Loading