Ftfy.Formatting (ftfy v0.1.0)

Copy Markdown View Source

Functions for justifying Unicode text in a monospaced display such as a terminal, based on the display width of characters.

Port of ftfy.formatting. The Python original relies on the wcwidth library; we reimplement the core single-character width lookup from the same Unicode tables. The string-width function here is the simple sum of character widths (it is not grapheme-cluster aware), which matches wcwidth.wcswidth for ordinary text.

Summary

Functions

The display width of a single character in a monospaced terminal: 0, 1, or 2 for printable characters, and -1 for non-printable/control characters.

Center text within a display width of at least width cells.

Left-justify text to a display width of at least width cells, padding with fillchar (which must have display width 1). "Left" means toward the start of the string.

Right-justify text to a display width of at least width cells.

The number of character cells this string is likely to occupy in a monospaced, Unicode-aware terminal. Returns -1 if it contains a non-printable or control character.

Functions

character_width(arg1)

@spec character_width(binary()) :: integer()

The display width of a single character in a monospaced terminal: 0, 1, or 2 for printable characters, and -1 for non-printable/control characters.

iex> Ftfy.Formatting.character_width("車")
2
iex> Ftfy.Formatting.character_width("A")
1
iex> Ftfy.Formatting.character_width("\n")
-1

display_center(text, width, fillchar \\ " ")

@spec display_center(binary(), non_neg_integer(), binary()) :: binary()

Center text within a display width of at least width cells.

display_ljust(text, width, fillchar \\ " ")

@spec display_ljust(binary(), non_neg_integer(), binary()) :: binary()

Left-justify text to a display width of at least width cells, padding with fillchar (which must have display width 1). "Left" means toward the start of the string.

display_rjust(text, width, fillchar \\ " ")

@spec display_rjust(binary(), non_neg_integer(), binary()) :: binary()

Right-justify text to a display width of at least width cells.

monospaced_width(text)

@spec monospaced_width(binary()) :: integer()

The number of character cells this string is likely to occupy in a monospaced, Unicode-aware terminal. Returns -1 if it contains a non-printable or control character.

iex> Ftfy.Formatting.monospaced_width("ちゃぶ台返し")
12
iex> Ftfy.Formatting.monospaced_width("example" <> <<0x80::utf8>>)
-1