From 75e37afda6e96a3edf64ce581542ed5376ad6615 Mon Sep 17 00:00:00 2001 From: isgav <51133755+isaranga@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:01:05 +0200 Subject: [PATCH] Implement rule P1 in bidi.py as split_into_paragraphs Move the paragraph splitter from demo.py into the P rules section of bidi.py, where it sits next to P2-P3. apply_bidi_algorithm still handles one paragraph. The demo now splits built-in examples as well as user text, and a new example shows two paragraphs getting different directions. README.md and CLAUDE.md are updated to match. --- CLAUDE.md | 8 ++++--- README.md | 17 +++++++++---- bidi.py | 47 ++++++++++++++++++++++++++++++------ demo.py | 71 +++++++++++++++++++++++-------------------------------- 4 files changed, 87 insertions(+), 56 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index c2e6e41..e976989 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -37,13 +37,13 @@ python tests/run_bidi_type_tests.py [--max-failures N] [--lines START-END] [--fa **Run the demo** (`demo.py`, reached through `bidi.py`): ```bash -python bidi.py # list the six built-in examples and usage hints +python bidi.py # list the seven 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. +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. `run_text` splits every text (user text and built-in examples alike) with `split_into_paragraphs` from `bidi.py` (rule P1) and runs each paragraph separately through `run_paragraph`. 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 @@ -61,11 +61,13 @@ levels, reordered, para_level, visual_order = apply_bidi_algorithm("Hello שלו ### Algorithm phases +Rule P1 is `split_into_paragraphs`, which works on the raw string and runs before everything else: it splits after each type-B character (CR LF counts as one), keeping the separator at the end of its paragraph. `apply_bidi_algorithm` handles **one paragraph** (a B may only be its last character); callers with longer text call it once per paragraph. The conformance files contain no B except at the end, so P1 is not covered by them. + `apply_bidi_algorithm` orchestrates six phases in order, each corresponding to a section of UAX #9: | Phase | Function | UAX #9 rules | |-------|----------|--------------| -| P | `determine_paragraph_embedding_level` | P2–P3 | +| P | `determine_paragraph_embedding_level` | P2–P3 (P1 is applied beforehand) | | X | `apply_explicit_levels` | X1–X9 | | W | `apply_weak_rules` | W1–W7 | | N | `apply_neutral_rules` | N0–N2 | diff --git a/README.md b/README.md index a8eb3e6..f3a7be0 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ cd UnicodeBidiAlgorithm python bidi.py ``` -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: +This lists the built-in examples (pure LTR, pure RTL, mixed text with digits, explicit embeddings, isolates, brackets, and two paragraphs) and shows how to run them: ```bash python bidi.py --example 3 # run one example, printing a table for every rule @@ -38,7 +38,7 @@ Bidi control characters are invisible and hard to type, so your text can name th 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. +Text with several paragraphs (for example, several lines in a file) is split into paragraphs by rule P1 and 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 @@ -59,6 +59,15 @@ levels, reordered, para_level, visual_order = apply_bidi_algorithm("Hello שלו 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: + +```python +from bidi import apply_bidi_algorithm, split_into_paragraphs + +for paragraph in split_into_paragraphs("שלום\nHello"): + levels, reordered, para_level, visual_order = apply_bidi_algorithm(paragraph) +``` + ## 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. @@ -92,7 +101,7 @@ Here N1 turns the space between the Hebrew word and the digits into `R`, because ## How the code is organised -`apply_bidi_algorithm` runs six phases in order. Each matches a section of UAX #9: +Rule P1 comes first: `split_into_paragraphs` cuts the text into paragraphs after each paragraph separator. `apply_bidi_algorithm` then runs six phases in order on one paragraph. Each matches a section of UAX #9: | Phase | Function | UAX #9 rules | What it does | |-------|----------|--------------|--------------| @@ -113,7 +122,7 @@ Some things to know when reading the code: ## Scope and caveats -- `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. +- `apply_bidi_algorithm` treats its input as a single paragraph. Split longer text with `split_into_paragraphs` (rule P1) first, as the command-line demo does. The official conformance files contain no paragraph separator except at the end of a test, so they do not check P1. - 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 efecebf..7e0b90c 100644 --- a/bidi.py +++ b/bidi.py @@ -9,9 +9,14 @@ which reflects the Unicode version bundled with your Python build. Usage: - from bidi import apply_bidi_algorithm + from bidi import apply_bidi_algorithm, split_into_paragraphs levels, reordered, para_level, visual_order = apply_bidi_algorithm("Hello עולם", verbose=False) + apply_bidi_algorithm handles one paragraph. For text that may hold several + (for example, several lines), split it first with rule P1: + for paragraph in split_into_paragraphs(text): + levels, reordered, para_level, visual_order = apply_bidi_algorithm(paragraph) + Demo: python bidi.py Lists the built-in examples and shows how to run one of them, all of @@ -216,11 +221,35 @@ def last_non_bn_type(run_indices): # SECTION: P rules # ============================================================ # -# Rule P1 (split the text into paragraphs at each paragraph separator, -# type B) is not implemented. The input is assumed to be a single -# paragraph, so the whole text goes through the rest of the algorithm -# as one unit. To handle text with several paragraphs, split it at its -# paragraph separators first and call apply_bidi_algorithm on each part. +# Rule P1 works on the raw text and is applied before everything else: +# split_into_paragraphs cuts the text into paragraphs, and each paragraph +# then goes through apply_bidi_algorithm (rules P2 to L4) on its own. + +def split_into_paragraphs(text: str) -> list[str]: + """ + P1: Split the text into paragraphs. + + A paragraph ends after each paragraph separator (bidi type B, such as a + newline or U+2029 PARAGRAPH SEPARATOR). The separator is kept at the end + of the paragraph it closes, as P1 says. CR LF counts as a single + separator, so it is not split in two. Text after the last separator, + if any, forms the final paragraph. + """ + 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 + def determine_paragraph_embedding_level(chars: list[CharacterInfo], verbose: bool = False) -> int: """ @@ -1170,7 +1199,11 @@ def apply_bidi_algorithm( paragraph_embedding_level: int | None = None, ) -> tuple[list[int], str, int, list[int]]: """ - Apply the Unicode Bidirectional Algorithm (UAX #9) to text. + Apply the Unicode Bidirectional Algorithm (UAX #9) to one paragraph. + + The text must be a single paragraph: a paragraph separator (type B) may + only appear as its last character. Split longer text with + split_into_paragraphs (rule P1) and call this function on each part. Args: paragraph_embedding_level: If provided (0 or 1), use this as the paragraph diff --git a/demo.py b/demo.py index c80b584..d8b0894 100644 --- a/demo.py +++ b/demo.py @@ -19,9 +19,8 @@ import argparse import re import sys -import unicodedata -from bidi import apply_bidi_algorithm +from bidi import apply_bidi_algorithm, split_into_paragraphs # ============================================================ @@ -65,6 +64,12 @@ "N0 makes both parentheses R, because they hold Hebrew text that follows Hebrew; " "L4 then mirrors them in the reordered text.", ), + ( + "שלום\nHello", + "Two paragraphs (P1)", + "P1 splits the text after the newline; P2 then finds R in paragraph 1 (level 1) " + "and L in paragraph 2 (level 0), so each paragraph gets its own direction.", + ), ] @@ -132,34 +137,6 @@ def show_controls_as_tags(text: str) -> str: 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 # ============================================================ @@ -168,6 +145,24 @@ def split_into_paragraphs(text: str) -> list[str]: def run_text(text: str, title: str, note: str | None, direction: str, brief: bool) -> None: + """Split the text into paragraphs (rule P1) and run each one.""" + paragraphs = split_into_paragraphs(text) + if len(paragraphs) == 1: + run_paragraph(text, title, note, direction, brief) + return + + print("=" * 60) + print(title) + print(f"Input: {show_controls_as_tags(text)}") + if note: + print(f"Watch for: {note}") + print(f"P1 splits the text into {len(paragraphs)} paragraphs; each is run separately.") + print() + for number, paragraph in enumerate(paragraphs, start=1): + run_paragraph(paragraph, f"{title}, paragraph {number}", None, direction, brief) + + +def run_paragraph(text: str, title: str, note: str | None, direction: str, brief: bool) -> None: print("=" * 60) print(title) print(f"Input: {show_controls_as_tags(text)}") @@ -214,7 +209,8 @@ def build_parser() -> argparse.ArgumentParser: "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." + "Text with several paragraphs (for example, several lines) is split by rule P1 " + "and run one paragraph at a time." ), ) source = parser.add_mutually_exclusive_group() @@ -271,18 +267,9 @@ def main(argv: list[str] | None = None) -> None: return user_text = expand_escapes_and_tags(user_text) - paragraphs = split_into_paragraphs(user_text) - if not paragraphs: + if not user_text: 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) + run_text(user_text, "Your text", None, args.direction, args.brief) if __name__ == '__main__':