string_width

Types

pub type Option {
  HandleGraphemeClusters
  CountAnsiEscapeCodes
  AmbiguousAsWide
}

Constructors

  • HandleGraphemeClusters

    Many terminal emulators do not handle grapheme clusters well and will instead show their decomposition. To make sure a given string always fits even on those terminals, the functions in this package will copy this behaviour as well.

    If you pass this option, the returned numbers will more accurately represent the width of a string on a website or in an editor, and will match the behaviour of the Javascript string-width package.

    See also Grapheme Clusters and Terminal Emulators for a better explanation on how terminals behave.

  • CountAnsiEscapeCodes

    Do not ignore ansi escape sequences.

  • AmbiguousAsWide

    Some characters are marked by Unicode as “ambiguous”, meaning they may occupy 1 or 2 cells, depending on the context, current language, selected font, surrounding text, and more.

    Unicode recommends treating these characters as narrow by default, but you can change this behaviour using this option.

Functions

pub fn codepoint(chr: UtfCodepoint, options: List(Option)) -> Int

Estimate the required width for a single unicode code point.

Note: that the exact width is context-dependent, so this value may not exactly match what you might expect!

If you encounter a mismatch that is consistent across multiple terminal emulators, please open an issue or ping me on Discord!

pub fn dimensions(
  str: String,
  options: List(Option),
) -> #(Int, Int)

The required number of rows and columns to display the given text.

The number of rows is equal to the number of lines, while the number of columns represents the maximum line width.

Examples

dimensions("안녕하세요", [])
// --> #(1, 10)

dimensions("hello,\n안녕하세요", [])
// --> #(2, 10)
pub fn grapheme_cluster(
  grapheme: String,
  options: List(Option),
) -> Int

Estimate the required width for a single grapheme cluster.

Note: that the exact width is context-dependent, so this value may not exactly match what you might expect!

If you encounter a mismatch that is consistent across multiple terminal emulators, please open an issue or ping me on Discord!

pub fn int_codepoint(cp: Int, options: List(Option)) -> Int
pub fn line(str: String, options: List(Option)) -> Int

Get the width of a line, when printed using a monospace font.

Line breaks are ignored. If the given string contains newlines, the result is undefined.

Examples

line("äöüè", [])
// --> 4

line("안녕하세요", [])
// --> 10

line("👩‍👩‍👦‍👦", [])
// --> 8

line("👩‍👩‍👦‍👦", [HandleGraphemeClusters])
// --> 2

line("\u{1B}[31mhello\u{1B}[39m", [])
// --> 5
Search Document