Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

unicode-display_width

Package Overview
Dependencies
Maintainers
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

unicode-display_width

  • 3.1.2
  • Rubygems
  • Socket score

Version published
Maintainers
1
Created
Source

Unicode::DisplayWidth [version]

Determines the monospace display width of a string in Ruby, which is useful for all kinds of terminal-based applications. The implementation is based on EastAsianWidth.txt, the Emoji specfication and other data, 100% in Ruby. It does not rely on the OS vendor (wcwidth()) to provide an up-to-date method for measuring string width in terminals.

Unicode version: 16.0.0 (September 2024)

Gem Version 3 — Improved Emoji Support

Emoji support is now enabled by default. See below for description and configuration possibilities.

Unicode::DisplayWidth.of now takes keyword arguments: { ambiguous:, emoji:, overwrite: }

See CHANGELOG for details.

Gem Version 2.4.2 — Performance Updates

If you use this gem, you should really upgrade to 2.4.2 or newer. It's often 100x faster, sometimes even 1000x and more!

This is possible because the gem now detects if you use very basic (and common) characters, like ASCII characters. Furthermore, the character width lookup code has been optimized, so even when the string involves full-width or ambiguous characters, the gem is much faster now.

Introduction to Character Widths

Guessing the correct space a character will consume on terminals is not easy. There is no single standard. Most implementations combine data from East Asian Width, some General Categories, and hand-picked adjustments.

How this Library Handles Widths

Further at the top means higher precedence. Please expect changes to this algorithm with every MINOR version update (the X in 1.X.0)!

WidthCharactersComment
?(user defined)Overwrites any other values
?EmojiSee "How this Library Handles Emoji Width" below
-1"\b"Backspace (total width never below 0)
0"\0", "\x05", "\a", "\n", "\v", "\f", "\r", "\x0E", "\x0F"C0 control codes which do not change horizontal width
1"\u{00AD}"SOFT HYPHEN
2"\u{2E3A}"TWO-EM DASH
3"\u{2E3B}"THREE-EM DASH
0General Categories: Mn, Me, Zl, Zp, Cf (non-arabic)Excludes ARABIC format characters
0Derived Property: Default_Ignorable_Code_PointIgnorable ranges
0"\u{1160}".."\u{11FF}", "\u{D7B0}".."\u{D7FF}"HANGUL JUNGSEONG
2East Asian Width: F, WFull-width characters
2"\u{3400}".."\u{4DBF}", "\u{4E00}".."\u{9FFF}", "\u{F900}".."\u{FAFF}", "\u{20000}".."\u{2FFFD}", "\u{30000}".."\u{3FFFD}"Full-width ranges
1 or 2East Asian Width: AAmbiguous characters, user defined, default: 1
1All other codepoints-

Install

Install the gem with:

$ gem install unicode-display_width

Or add to your Gemfile:

gem 'unicode-display_width'

Usage

require 'unicode/display_width'

Unicode::DisplayWidth.of("⚀") # => 1
Unicode::DisplayWidth.of("一") # => 2

Ambiguous Characters

The second parameter defines the value returned by characters defined as ambiguous:

Unicode::DisplayWidth.of("·", 1) # => 1
Unicode::DisplayWidth.of("·", 2) # => 2

Custom Overwrites

You can overwrite how to handle specific code points by passing a hash (or even a proc) as overwrite: parameter:

Unicode::DisplayWidth.of("a\tb", 1, overwrite: { "\t".ord => 10 })) # => TAB counted as 10, result is 12

Please note that using overwrites disables some perfomance optimizations of this gem.

Emoji

If your terminal supports it, the gem detects Emoji and Emoji sequences and adjusts the width of the measured string. This can be disabled by passing emoji: false as an argument:

Unicode::DisplayWidth.of "🤾🏽‍♀️", emoji: :all # => 2
Unicode::DisplayWidth.of "🤾🏽‍♀️", emoji: false # => 5
How this Library Handles Emoji Width

There are many Emoji which get constructed by combining other Emoji in a sequence. This makes measuring the width complicated, since terminals might either display the combined Emoji or the separate parts of the Emoji individually.

Another aspect where terminals disagree is whether Emoji characters which have a text presentation by default (width 1) should be turned into full-width (width 2) when combined with Variation Selector 16 (U+FEOF).

Emoji TypeWidth / Comment
Basic/Single Emoji character without Variation SelectorNo special handling
Basic/Single Emoji character with VS15 (Text)No special handling
Basic/Single Emoji character with VS16 (Emoji)2 or East Asian Width (see table below)
Emoji Sequence2 if Emoji belongs to configured Emoji set (see table below)
Emoji Modes

The emoji: option can be used to configure which type of Emoji should be considered to have a width of 2 and if VS16-Emoji should be widened. Other sequences are treated as non-combined Emoji, so the widths of all partial Emoji add up (e.g. width of one basic Emoji + one skin tone modifier + another basic Emoji). The following Emoji settings can be used:

emoji: OptionVS16-Emoji WidthEmoji Sequences Width / CommentExample Terminals
true or :auto-Automatically use recommended Emoji setting for your terminal-
:all22 for all ZWJ/modifier/keycap sequences, even if they are not well-formed Emoji sequencesiTerm, foot
:all_no_vs16EAW (1 or 2)2 for all ZWJ/modifier/keycap sequences, even if they are not well-formed Emoji sequencesWezTerm
:possible22 for all possible/well-formed Emoji sequences?
:rgi22 for all RGI Emoji sequences?
:rgi_atEAW (1 or 2)1 or 2: Like :rgi, but Emoji sequences starting with a default-text Emoji have EAWApple Terminal
:vs1622 * number of partial Emoji (sequences never considered to represent a combined Emoji)kitty?
false or :noneEAW (1 or 2)No Emoji adjustmentsgnome-terminal, many older terminals
  • EAW: East Asian Width
  • RGI Emoji: Emoji Recommended for General Interchange
  • ZWJ: Zero-width Joiner: Codepoint U+200D,used in many Emoji sequences
Emoji Support in Terminals

Unfortunately, the level of Emoji support varies a lot between terminals. While some of them are able to display (almost) all Emoji sequences correctly, others fall back to displaying sequences of basic Emoji. When emoji: true or emoji: :auto is used, the gem will attempt to set the best fitting Emoji setting for you (e.g. :rgi_at on "Apple_Terminal" or false on Gnome's terminal widget).

Please note that Emoji display and number of terminal columns used might differs a lot. For example, it might be the case that a terminal does not understand which Emoji to display, but still manages to calculate the proper amount of terminal cells. The automatic Emoji support level per terminal only considers the latter (cursor position), not the actual Emoji image(s) displayed. Please open an issue if you notice your terminal application could use a better default value. Also see the ucs-detect project, which is a great resource that compares various terminal's Unicode/Emoji capabilities.

To terminal implementors reading this: Although the practice of giving all Emoji/ZWJ sequences a width of 2 (:all mode described above) has some advantages, it does not lead to a particularly good developer experience. Since there is always the possibility of well-formed Emoji that are currently not supported (non-RGI / future Unicode) appearing, those sequences will take more cells. Instead of overflowing, cutting off sequences or displaying placeholder-Emoji, could it be worthwile to implement the :rgi option (only known Emoji get width 2) and give those unknown Emoji the space they need? This would support the idea that the meaning of an unknown Emoji sequence can still be conveyed (without messing up the terminal at the same time). Just a thought…

Usage with String Extension

require 'unicode/display_width/string_ext'

"⚀".display_width # => 1
'一'.display_width # => 2

Usage with Config Object

You can use a config object that allows you to save your configuration for later-reuse. This requires an extra line of code, but has the advantage that you'll need to define your string-width options only once:

require 'unicode/display_width'

display_width = Unicode::DisplayWidth.new(
  # ambiguous: 1,
  overwrite: { "A".ord => 100 },
  emoji: :all,
)

display_width.of "⚀" # => 1
display_width.of "🤠‍🤢" # => 2
display_width.of "A" # => 100

Usage from the Command-Line

Use this one-liner to print out display widths for strings from the command-line:

$ gem install unicode-display_width
$ ruby -r unicode/display_width -e 'puts Unicode::DisplayWidth.of $*[0]' -- "一"

Replace "一" with the actual string to measure

Other Implementations & Discussion

See unicode-x for more Unicode related micro libraries.

FAQs

Package last updated on 20 Nov 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc