256 colors in the terminal ⇒ nightmare level

    I'm building some bike with a long debugging output in stdoutand I was excited about the serious color of the log. Modern terminals xtermcan and love 256 colors, but here are the people who came up with escape sequences for this palette, hobbled by backward compatibility and a latent penchant for cryptographic empiricism, all made it take me several hours to figure it all out. The Internet is also not full of detailed explanations of how it is arranged there.
    In short, the text in the X terminal can now be displayed curly. I sketched some semblance of a service , such as visivig to generate escape sequences. Selected colors, font style - get a set of squiggles. Those who are interested in offal - I ask for a cat.

    Colors in xterm

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

    The color itself is encoded in an absolutely breathtaking manner. An escape sequence, traditionally starting with " \e[" and ending with " m", consists of flags, background colors, and text colors. Flags for bold , oblique , underlined and inverse ( fg⇐⇒bg): 01, 03, 04, 07, respectively (there is still a flag for blinking, but suddenly children read me?). Flags for canceling these styles: 22, 23, 24, 27. Flags can be written one after the other through a semicolon; no semicolon is put before the final “m”.
    The color of the text has a signature (sorry) 38; 05; COLOR; . Background color -  48; 05; COLOR;. COLOR here is ∀ an integer ∈ [1, 255]. The first sixteen are familiar to us old terminal colors, the last 24 are shades of gray, the rest are the rest.
    Something like this (thanks to Fedor for the picture):

    It is easy to see that the sequence “ \e[01;04;38;05;196;48;05;232m” will turn on the mode of bold underlined red on a black background.

    How to get color?

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

    Why is this all?

    Well, firstly, I was curious. Secondly, three hours is not money. Thirdly, now my log file is so poured so that it became even more difficult to grab something with a look. Well PS1, of course, rewritten from scratch.

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

    Thanks for attention.

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

    Also popular now: