📜 ⬆️ ⬇️

256 colors in the terminal ⇒ nightmare level



I'm building a bike here with a long debugging output in stdout and I was worried about the serious color of the log. Modern xterm terminals are able and fond of 256 colors, but the people who came up with escape sequences for this palette, strapped by backward compatibility and latent propensity for cryptographic empirics, made everything so that it took me several hours to figure it all out. The Internet, too, is not replete with detailed explanations of how it is arranged there.
In short, the text in the x-ray terminal can now display the curly. I have sketched some kind of service , such as a view to generate escape sequences. Chose colors, font style - get a set of stitches. Those who are interested in offal - I ask under the cat.

Colors in xterm


In order for the terminal to understand that it can show 256 colors, it needs to say about it:
  case "$TERM" in 'xterm') TERM=xterm-256color;; 'screen') TERM=screen-256color;; 'Eterm') TERM=Eterm-256color;; esac 

The color itself is encoded in a completely breathtaking way. The escape sequence, which traditionally begins with " \e[ " and ends with " m ", consists of flags, background color and text color. Flags for bold , oblique , underlined and inverse ( fg⇐⇒bg ): 01, 03, 04, 07, respectively (is there a flag for the flashing one, but what if children read me?). Flags of the cancellation of these styles: 22, 23, 24, 27. Flags can be written one after another through a semicolon, before the final “m” there is no semicolon.
The text color has a signature (sorry) 38; 05; COLOUR; . Background color - 48; 05; COLOUR; . COLOR here is ∀ integer ∈ [1, 255]. The first sixteen are well familiar to us old terminal colors, the last 24 are grayscale, the rest are well the rest.
Something like that (thanks to Fedor for the picture):


It is easy to see that the sequence " \e[01;04;38;05;196;48;05;232m " will \e[01;04;38;05;196;48;05;232m mode of bold underlined red against a black background.
')

How to get color?


The colors, it turns out, are encoded into the remaining 256 - 16 - 24 = 216 variants by a simple and understandable algorithm: the rgb gradations are calibrated for six and the figure is obtained as RGB in the hexadecimal number system, with "zero in sixteen" (for #ff9900 this will give 16 + 5 * 6² + 3 * 6 + 0 = 214 ). There are exceptions, as without them. Those are the "standard" 16 colors and grayscale. Yeah.

Why is this all?


Well, first, I was curious. Secondly, three hours is not money. Thirdly, I now have my log file so overflowed that it became even harder to get something out of sight. Well, PS1 , of course, rewritten from scratch.

In general, if you need an escape sequence for a particular color, here’s WYSIWYG . If someone needs offline for some reason - @github .

Thanks for attention.

Upd: frexx.de/xterm-256-notes - a good link on the topic. Thank you, yermulnik .

Source: https://habr.com/ru/post/161999/


All Articles