Usually when using the third-party NPM library development, I often see the terminal printing different colors of the prompt message, feel beautiful, at the same time, have you thought about the principle?

experience

First, you can try the following commands in your bash shell

Echo -e "\033[31m front End \033[0m"Copy the code

Or use Node to execute js files

// test.js
console.log('\033[31m Front end pour tea soldier \033[0m')
Copy the code

The result of both commands is the same, both output red font on the terminal, although a little pink 😂



Why use\033[31mWhat about this weird character wrapping text around a special color? That’s when you needANSI escape sequenceCome on stage.

ANSI escape sequence

This is a standard developed by the American National Standards Institute in the 1970s, and has been widely used in computer equipment since the 1980s. At present, DOS and UNIx-type terminal emulators almost all support ASNI escape sequences.

According to Wikipedia, this is an escape sequence standard with in-signal for controlling cursor position, color, and other options on video text terminals. Inserts certain sequences of bytes into the text, mostly beginning with the ESC escape character and the “[” character, which the terminal interprets as corresponding instructions rather than ordinary character encodings.

The common control type is ASCII

The following table lists the 0-31 non-printable ASCII codes used for control

The name of the ASCII octal hexadecimal C type escape character Ctrl key describe
BEL 7 007 0x07 \a ^G Terminal bell
BS 8 010 0x08 \b ^H The fallback
HT 9 011 0x09 \t ^I Horizontal Tab
LF 10 012 0x0A \n ^J A newline
VT 11 013 0x0B \v ^K Vertical Tab
FF 12 014 0x0C \f ^L Change the page
CR 13 015 0x0D \r ^M enter
ESC 27 033 0x1B \e ^ [ Escape character

In the example given at the beginning of this article, 033 is the octal representation of the escape character ESC, which corresponds to 0x1b or 0x1b in hexadecimal notation. The escape character in C is \e, and the escape character in ASCII is 27.

The previous example can also be written in hexadecimal or \e. The following three commands have the same effect.

Echo - E "\x1b[31m front end pour tea soldier \x1b[0m" echo -e "\x1b[31m front end pour tea soldier \x1b[0m" echo -e "\e[0m front end pour tea soldier \x1b[0m" echo -e "\e[0m"Copy the code

Note: It is best not to use \e as an escape character, as not all languages and compilers support it, such as Python. Hexadecimal notation can sometimes be problematic, such as the reset state described below. The hexadecimal representation of the escape sequence of the reset state is \x1bc, which is a valid hexadecimal number, so the terminal parses it as a whole and does not reset \033c.

The following text will use ESC for \033 or \x1b.

ESC is combined with the @a-z [\]^_ range of characters (the C1 control character), which we call an escape sequence.

Part of ANSI escape sequence

The sequence C1 Control character The name of the describe
ESCN 0x8e SS2 – Single Shift Two The next character selects a character from the G2 printable character set
ESCO 0x8f SS3 – Single Shift Three The next character selects a character from the G3 printable character set
ESCP 0x90 DCS – Device Control String Control equipment
ESC[ 0x9b CSI – Control Sequence Introducer Most useful sequences
ESC\ 0x9c ST – String Terminator Terminates strings in other controls (APC, DCS, OSC, PM, and SOS)
ESC] 0x9d OSC – Operating system Commands () The control string used to start the operating system
ESCX 0x98 SOS – Start of string () Arguments that reference a string of text terminated by ST
ESC^ 0x9e PM – Private messages ()
ESC_ 0x9f APC – Application Commands ()
ESCc RIS – Reset to Initial State Reformat graphics, clear tabs, reset to default fonts, etc

The escape sequence for the reset state is represented as \033c in octal and \x1bc in hexadecimal, but \x1bc is a legal hexadecimal number, so it doesn’t look like

CSI sequence

The combination of ESC and [is called CSI, and sequences that begin with CSI are called CSI sequences, also known as ANSI control sequences.

ESC[CSI]

CSI + 0 or N parameter bytes + 0 or N intermediate bytes + 1 final byte form the CSI sequence. The character range for the second half of the CSI sequence

Part of the Range of characters ASCII
Parameter bytes 0x30-0x3F 0-9:; The < = >?
In the middle of bytes 0x20-0x2F Spaces,!" # $% & '() *, +, -, /
In the end byte 0x40-0x7E @A-Z[\]^_a-z{

The CSI sequence ignores characters beyond 0x20 — 0x7E.

Different combinations of the latter half of the CSI sequence represent different functions, and here are some examples.

Cursor control

CSI sequence describe
CSIH Cursor moves to position (0, 0)
CSInA Move the cursor up n lines
CSInB Move the cursor down n lines
CSInC Move the cursor n columns to the right
CSInD Move the cursor n columns to the left
CSInE Move the cursor down n lines to the beginning of the next line
CSInF The cursor moves to the top of the line and up n lines
CSInG Cursor moves to column n
CSIn; mH

CSIn; mf
Cursor moves to n rows and m columns
CSIs Save cursor position, non-standard, recommendedESC7
CSIu Restore cursor position saved last time, non-standard, recommendedESC8

erasure

CSI sequence describe
CSIJ Clear the screen
CSI0J Clear the cursor to the end of the screen
CSI1J Clear the cursor to the beginning of the screen
CSI2J Clear the entire screen
CSIK Clear current line
CSI0K Clears the cursor to the end of the line
CSI1K Clears the cursor to the beginning of the line
CSI2K Removal of the entire line

Screen mode

CSI sequence describe
CSI=0h 40 x 25 Black and White (text)
CSI=1h 40 x 25 Colour (text)
CSI=2h 80 x 25 Black and White (text)
CSI=3h 80 x 25 Colour (text)
CSI=4h 320 x 200 4 colours (image)
CSI=5h 320 x 200 Black and White (image)
CSI=6h 640 x 200 black and White (image)
CSI=7h Allow a newline
CSI=13h 320 x 200 Color (image)
CSI=14h 640 x 200 Colour (16-colour image)
CSI=15h 640 x 350 Black and White (2-color image)
CSI=16h 640 x 350 Color (16-color image)
CSI=17h 640 x 480 Black and White (2-color image)
CSI=18h 640 x 480 Color (16-color image)
CSI=19h 320 x 200 color (256 color image)
CSI={value}h Change the screen width or type to the mode corresponding to value
CSI={value}l The final character is lowercase L, resets the mode for value, and disallows line breaks if value is 7

Keyboard string

The mode of ESC[{code};{string};{…}p redefines a key to a specified string. See Resources for details.

As you can see from the above, when the final character is A-H, the cursor moves. When the final character is J or K, it indicates erasure. Screen mode is indicated when the final character is h and the parameter byte is =.

When the final character is m, there are no arguments or arguments; The separated CSI sequence is the SGR that we are going to focus on.

SGR

Select Graphic Rendition. You can set terminal text styles, including color, thickness, italic, and underscore.

Common Style Settings

The following table lists CSI sequences in common styles other than colors

CSI sequence The reset sequence describe
CSI0m Reset all style modes
CSI1m CSI21m The bold
CSI2m CSI22m weakening
CSI3m CSI23m italics
CSI4m CSI24m The underline
CSI5m CSI25m Slow flashing
CSI6m CSI26m Rapid flashing
CSI7m CSI27m Reverse display, foreground background color exchange
CSI8m CSI28m hidden
CSI9m CSI29m delete

8/16 color

color Foreground code Background color code
black 30 40
red 31 41
green 32 42
huang 33 43
blue 34 44
magenta 35 45
green 36 46
white 37 47
The default 39 49
reset 0 0

30-37 is the standard 8 standard foreground colors, 40-47 is the corresponding background color, 39 or 49 can be reset color. The unmentioned 38 and 48 are used to set 256 colors and RGB colors, as described later.

For terminals that support the AIXTerm specification, there are eight additional high-intensity colors.

color Foreground code Background color code
Bright black 90 100
Bright red 91 101
Bright green 92 102
Bright yellow 93 103
Bright blue 94 104
Bright magenta 95 105
Bright green 96 106
Bright white 97 107

If you want bold text with a red foreground and a white background, write this

\033[1;31;47m
Copy the code

The same color code may display different colors on different terminals.

256 colors

CSI sequence describe
CSI38; 5{ID}m Set the foreground
CSI48; 5{ID}m Set the background color

5 indicates 256 colors. ID is a value from 0 to 255, which can be understood as the serial number of colors.

256 color calculation method

ID Corresponding relations between
0 to 7 Corresponds to standard colors 30-37 in 8/16
8-15 Corresponding to 8/16 color high intensity colors 90-97
16-231. 16 + 36 × R + 6 × G + B (0 ≤ R, G, B ≤ 5)
232-255. 24 grayscale color

RGB color

CSI sequence describe
CSI38; 2; {R}; {G}; {B}m Set the foreground
CSI48; 2; {R}; {G}; {B}m Set the background color

2 indicates that RGB color is used. Only terminals that support true color (24-bit RGB) can use this color. R, G, and B range from 0 to 255.

\033[0m

Recall from the example at the beginning of this article that we used \033[0m, just to reset all styles. It is more concise to write \033[m, because no arguments default to 0.

Of course, if only the color is set or you want to reset the color, you can use \033[39m or \033[49m to reset the color.

Is it ok not to reset the style? B: Sure. However, if the style is not reset and the new style is not set, subsequent output will inherit the previous style. For example, Node runs the following code

// test.js
console.log('\033[31m Front End Pour tea soldier ');
console.log('Front Tea Sommelier');
Copy the code

The second sentence will also have color, which may not be what we want.

chalk

Chalk is a well-known nodeJS library that displays colors on terminals. How does it do this?

Debugging revealed that it encapsulates a library called anSI-styles, which also follows the escape sequence specification, depending on the code. However, it uses Unicode \u001B to represent ESC.

conclusion

  1. Escape characterESCThere are several ways to express it:\ 033.\x1b.\x1B.\eand\u001B;
  2. ESCCombined with certain characters to form an Escape Sequence,ESCand[compositionCSI(Control sequence importer);
  3. CSI sequences can control terminal behavior when the final character ism, used for intermediate parameters;In SGR mode, you can set the color, thickness and other styles of terminal text\033[{parameter 1};{parameter 2};{... parameter n}mThis format;
  4. Different terminals have different levels of support for CSI sequences. The styles mentioned above may not work, and the color display may also be different.


Finally, the last rendering



Isn’t that cool?

The resources

  1. What does the printf (” \ “033 c) scheme: stackoverflow.com/questions/4…
  2. The ANSI Escape Sequences: gist.github.com/fnky/458719…
  3. The ANSI escape sequences: zh.wikipedia.org/wiki/ANSI%E…
  4. Aixterm specification: sites. The ualberta. Ca/dept/chemen…
  5. C1 Control characters: zh.wikipedia.org/wiki/C0%E4%…
  6. Asni – styles: github.com/chalk/ansi-…