Standard library · Text

bidi

The Unicode bidirectional algorithm: the right display order when right to left and left to right text are mixed.

import bidi

Text is stored in memory in the order it was typed, but when right to left and left to right scripts are mixed, the order seen on screen is not that order. Browsers and editors do the rearranging with the Unicode bidirectional algorithm.

If you are drawing text yourself somewhere that does not do this for you, onto an image, in a terminal or on a simple display, the bidi package runs the same algorithm and tells you where every character goes.

Each function takes a paragraph direction: DirAuto infers it from the first strong character in the text, and the other two set it in advance. The "level" of each character is a number: even means left to right and odd means right to left.

Constants and variables

DirAuto

const DirAuto: i32 = 0
Take the paragraph direction from the first strong character in the text: right to left when it is an Arabic-script letter, left to right when it is a Latin one.
bidi-Reorder.salam
import bidi

func main:
    s := "abc سلام"
    println bidi.ParagraphLevel(s, bidi.DirAuto), bidi.ParagraphLevel("سلام abc", bidi.DirAuto)
    println bidi.ParagraphLevel(s, bidi.DirRTL), bidi.ParagraphLevel("سلام", bidi.DirLTR)
    println bidi.Levels(s, bidi.DirLTR)
    println bidi.VisualOrder(s, bidi.DirLTR)
    println bidi.Reorder(s, bidi.DirLTR)
end
Output0 1 1 0 [0, 0, 0, 0, 1, 1, 1, 1] [0, 1, 2, 3, 7, 6, 5, 4] abc مالس

DirLTR

const DirLTR: i32 = 1
The paragraph is left to right, as on an English page.

The example for this item is shown with the ones above: bidi-Reorder.salam

DirRTL

const DirRTL: i32 = 2
The paragraph is right to left, as on a Persian page.

The example for this item is shown with the ones above: bidi-Reorder.salam

Functions

ParagraphLevel

func ParagraphLevel(s: str, dir: int): int
Returns the base level of the paragraph: zero for left to right and one for right to left.

The example for this item is shown with the ones above: bidi-Reorder.salam

Levels

func Levels(s: str, dir: int): Vector<int>
Returns the level of every character in a vector; odd levels are displayed right to left.

The example for this item is shown with the ones above: bidi-Reorder.salam

VisualOrder

func VisualOrder(s: str, dir: int): Vector<int>
Says which characters are seen, in which order, reading the screen from left to right. Element i is the index of the character that appears in position i.

The example for this item is shown with the ones above: bidi-Reorder.salam

Reorder

func Reorder(s: str, dir: int): str
Rearranges the text into the order it should be drawn in from left to right: the same string, in display order.

The example for this item is shown with the ones above: bidi-Reorder.salam