Wednesday, October 11, 2017

ANSI escape sequences - colors

ANSI escape sequences for color manipulation consists not only on text color codes, but also, on convenient combinations with text attributes codes. Some ANSI codes related to them are:
 
Text attributes
0  All attributes OFF
1  Bold
2  Dimmed             (odd with magenta)
4  Underscore         (monochrome displays only)
7  Reversed           (foreground/background)
8  Hidden             (concealed)
9  Stroke-through
Text Colors
        Foreground Background
Black           30         40
Red             31         41
Green           32         42
Yellow          33         43
Blue            34         44
Magenta         35         45
Cyan            36         46
White           37         47
The escape sequence, as a whole, begins by the escape character, which is the ASCII 27 (0x1B) character, followed by the [ character, followed by a semicolon-separated ANSI codes list as per the above tables, finally ending on a lowercase m. That is:
Esc[<code-1>;...;<code-n>m
But depending on where it's used, the initial escape character (Esc) or the sequence itself is indicated in particular ways. For instance, even in various components of BASH it varies as follows:

  \[\e[ANSI-codes-list\] - In PS1 and PS2 prompts definition
    \e[ANSI-codes-list   - In .inputrc definitions
    ^[[ANSI-codes-list   - On scripts (^V+Esc in VIM generates ^[)

As a real example, see the following excerpt from a PS1 definition:
(an expanded example is found at Shell initialization files)

  O='\[\e[0m\]'        # all off
  B='\[\e[0;1m\]'      # bright / bold
  Y='\[\e[0;33m\]'     # yellow / orange
 

  PS1="$O\n"
  PS1="$PS1"$([[ "$LOGNAME" != root ]] && echo "$Y\u$B@")
  PS1="$PS1$Y\h$B:$O\w\n$B\\\$$O

  export PS1

It will produce something similar to:
                                              
user1@host:/tmp                               
$ _                                           

Many interesting things can be done with ANSI escape sequences.
There's also some more advanced features such as:
  • Cursor positioning
  • Clearing the screen, the line and so on...