package

github.com/wyhaines/unicode_width.cr

1.0.0 / published Jan 29, 2026 / repository

Unicode East Asian Width (UAX#11) implementation for Crystal - character and string display width calculation

CI GitHub release Crystal License

unicode_width

A Crystal implementation of Unicode Standard Annex #11 (UAX #11) — East Asian Width — for calculating the display width of characters and strings in a terminal. Built from Unicode 17.0.0 character data.

Overview

Terminal emulators render most characters in a single column, but CJK (Chinese, Japanese, Korean) ideographs, fullwidth forms, and certain other characters occupy two columns. Combining marks and control characters occupy zero columns. This shard provides fast, correct width lookups using binary search over precomputed Unicode range tables.

Installation

  1. Add the dependency to your shard.yml:

    dependencies:
      unicode_width:
        github: wyhaines/unicode_width.cr
  2. Run shards install

Usage

require "unicode_width"

Character width

UnicodeWidth.width('a')      # => 1  (ASCII)
UnicodeWidth.width('中')     # => 2  (CJK ideograph)
UnicodeWidth.width('\u{0300}') # => 0  (combining mark)

String width

UnicodeWidth.width("hello")  # => 5
UnicodeWidth.width("中文")   # => 4  (two wide characters)
UnicodeWidth.width("a中b")   # => 4  (1 + 2 + 1)

Truncate to a display width

Truncates at character boundaries without splitting wide characters:

UnicodeWidth.truncate("中文字", 4) # => "中文"
UnicodeWidth.truncate("中文字", 3) # => "中"   (won't split a 2-wide char)

Pad to a display width

Appends spaces to reach the target column width:

UnicodeWidth.pad("中", 4)    # => "中  "  (2-wide char + 2 spaces)
UnicodeWidth.pad("hello", 5) # => "hello" (already at target)

API

MethodDescription
UnicodeWidth.width(char : Char) : Int32Display width of a single character (0, 1, or 2)
UnicodeWidth.width(str : String) : Int32Total display width of a string
UnicodeWidth.truncate(str, max_width) : StringTruncate to fit within max_width columns
UnicodeWidth.pad(str, target_width) : StringRight-pad with spaces to target_width columns

Contributing

  1. Fork it (https://github.com/wyhaines/unicode_width.cr/fork)
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Contributors

API