Henrique Alves
Henrique Alves@healves82

Dec 12, 2016

Colors in terminal

Update 13/12/16 — I’ve added more context. Also more information on text styles and resource links at the bottom.

I built a little CLI tool that-color to name a color from a given hex. It also gives a nice color scale from hello-color. I use this tool often when I’m writing styleguide or mocking up components. I don’t have to think about color names, values or open the browser.

that-color

I started this project using the modules colors, terminal-kit and ansy-styles. The first time I used ansi-styles I got undefined trying to ouput the style.color. I looked into the code and from there I started a quick research around this subject.

Before write this library I didn’t bother to understand how colors works in terminal. Just because this 👇 didn’t look friendly.

printf "\u001b[38;2;230;90;180mhello world\u001b[0m"

It turned out to be more simple than I thought.

  • \u001B unicode ANSI escape code. By the way \u001B, \x1b and \e are different ways to write the same thing.
  • [ part of ANSI sequence escape.
  • 38;is the xterm-256 foreground color code. Use 48 to change the background color instead.
  • 2; is the color format code for 24-bit RGB Truecolor ANSI support.
  • m end of the sequence.
  • \u001b[0m reset all changes for the next escape sequence.

Translating it to JavaScript make it easier to read and parse in my head:

`\u001B[${fg|bg};2;${r};${g};${b}m${msg}`

Text style

The first parameter after [ determines the style of the text. This value is off by default. Some of the attributes are: 0 for off, 1 for bold, 2 for underscore and 3 for blink.

Now the code looks like:

`\u001B[${style};${fg|bg};2;${r};${g};${b}m${msg}`

Not bad right!? You can use supports-color to detect terminal color support. Now you’re all set to build your own colors.js module or just use ansy-styles.

Self note

Doing a bit of homework and trying to understand how things works under the hood is always self-rewarding.

Resources