unicode_width.cr v1.0.0
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
-
Add the dependency to your
shard.yml:dependencies: unicode_width: github: wyhaines/unicode_width.cr -
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
| Method | Description |
|---|---|
UnicodeWidth.width(char : Char) : Int32 |
Display width of a single character (0, 1, or 2) |
UnicodeWidth.width(str : String) : Int32 |
Total display width of a string |
UnicodeWidth.truncate(str, max_width) : String |
Truncate to fit within max_width columns |
UnicodeWidth.pad(str, target_width) : String |
Right-pad with spaces to target_width columns |
Contributing
- Fork it (https://github.com/wyhaines/unicode_width.cr/fork)
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create a new Pull Request
Contributors
- Kirk Haines - creator and maintainer
unicode_width.cr
- 0
- 0
- 0
- 1
- 1
- 13 days ago
- January 29, 2026
Apache License 2.0
Tue, 10 Feb 2026 11:44:59 GMT