ANSI escape code


ANSI escape sequences are a standard for in-band signaling to control the cursor location, color, and other options on video text terminals and terminal emulators. Certain sequences of bytes, most starting with Esc and 'bracket|character codes.
ANSI sequences were introduced in the 1970s to replace vendor-specific sequences and became widespread in the computer equipment market by the early 1980s. They were used in development, scientific and commercial applications and later by the nascent [bulletin board systems">character encoding">character codes.
ANSI sequences were introduced in the 1970s to replace vendor-specific sequences and became widespread in the computer equipment market by the early 1980s. They were used in development, scientific and commercial applications and later by the nascent [bulletin board systems to offer improved displays compared to earlier systems lacking cursor movement, a primary reason they became a standard adopted by all manufacturers.
Although hardware text terminals have become increasingly rare in the 21st century, the relevance of the ANSI standard persists because most terminal emulators interpret at least some of the ANSI escape sequences in output text. A notable exception was DOS and older versions of the Win32 console of Microsoft Windows.

History

Almost all manufacturers of video terminals added vendor-specific escape sequences to perform operations such as placing the cursor at arbitrary positions on the screen. One example is the VT52 terminal, which allowed the cursor to be placed at an x,y location on the screen by sending the character, a character, and then two characters representing with numerical values equal to the x,y location plus 32. The Hazeltine 1500 had a similar feature, invoked using, and then the X and Y positions separated with a comma. While the two terminals had identical functionality in this regard, different control sequences had to be used to invoke them.
As these sequences were different for different terminals, elaborate libraries such as termcap and utilities such as tput had to be created so programs could use the same API to work with any terminal. In addition, many of these terminals required sending numbers as the binary values of the characters; for some programming languages, and for systems that did not use ASCII internally, it was often difficult to turn a number into the correct character.
The ANSI standard attempted to address these problems by making a command set that all terminals would use and requiring all numeric information to be transmitted as ASCII numbers. The first standard in the series was ECMA-48, adopted in 1976. It was a continuation of a series of character coding standards, the first one being ECMA-6 from 1965, a 7-bit standard from which ISO 646 originates. The name "ANSI escape sequence" dates from 1979 when ANSI adopted ANSI X3.64. The ANSI X3L2 committee collaborated with the ECMA committee TC 1 to produce nearly identical standards. These two standards were merged into an international standard, ISO 6429. In 1994, ANSI withdrew its standard in favor of the international standard.
The first popular video terminal to support these sequences was the Digital VT100, introduced in 1978. This model was very successful in the market, which sparked a variety of VT100 clones, among the earliest and most popular of which was the much more affordable Zenith Z-19 in 1979. Others included the Qume QVT-108, Televideo TVI-970, Wyse WY-99GT as well as optional "VT100" or "VT103" or "ANSI" modes with varying degrees of compatibility on many other brands. The popularity of these gradually led to more and more software assuming the escape sequences worked, leading to almost all new terminals and emulator programs supporting them.
In 1981, ANSI X3.64 was adopted for use in the US government by FIPS publication 86. Later, the US government stopped duplicating industry standards, so FIPS pub. 86 was withdrawn.
ECMA-48 has been updated several times and is currently at its 5th edition, from 1991. It is also adopted by ISO and IEC as standard ISO/IEC 6429.
Related standards include ITU T.61, the Teletex standard, and the ISO/IEC 8613, the Open Document Architecture standard. The two systems share many escape codes with the ANSI system, with extensions that are not necessarily meaningful to computer terminals. Both systems quickly fell into disuse, but ECMA-48 does mark the extensions used in them as reserved.

Platform support

Unix-like systems

Although termcap/terminfo-style libraries were primarily developed on and for Unix, since about 1984 programs running on Unix-like operating systems could almost always assume they were using a terminal or emulator that supported ANSI sequences; this led to widespread use of ANSI by programs running on those platforms. For instance, many games and shell scripts, and utilities such as color directory listings, directly write the ANSI sequences and thus cannot be used on a terminal that does not interpret them. Many programs, including text editors such as vi and GNU Emacs, use termcap or terminfo, or use libraries such as curses that use termcap or terminfo, and thus in theory support non-ANSI terminals, but this is so rarely tested nowadays that they are unlikely to work with those terminals. Terminal emulators for communicating with local programs as well as remote machines and the text system console almost always support ANSI escape codes.

DOS and Windows

MS-DOS 1.x did not support the ANSI or any other escape sequences. Only a few control characters were interpreted by the underlying BIOS, making it almost impossible to do any kind of full-screen application. Any display effects had to be done with BIOS calls, which were notoriously slow, or by directly manipulating the IBM PC hardware.
DOS 2.0 introduced the ability to add a device driver for the ANSI escape sequences – the de facto standard being, but others like, and are used as well. Slowness and the fact that it was not installed by default made software rarely take advantage of it; instead, applications continued to directly manipulate the hardware to get the text display needed. ANSI.SYS and similar drivers continued to work in Windows 9x up to Windows Me, and in NT-derived systems for 16-bit legacy programs executing under the NTVDM.
Many emulators of DOS were able to interpret the sequences. PTS-DOS as well as Concurrent DOS, Multiuser DOS and REAL/32 have built-in support and do not require a separate ANSI driver to be loaded. OS/2 had an command that enabled the sequences.
The Windows Console did not support ANSI escape sequences, nor did Microsoft provide any method to enable them. Some replacements or additions for the console window such as JP Software's TCC, Michael J. Mefford's ANSI.COM, Jason Hood's
and Maximus5's ConEmu interpreted ANSI escape sequences printed by programs. A Python package internally interpreted ANSI escape sequences in text being printed, translating them to calls to manipulate the color and cursor position, to make it easier to port Python code using ANSI to Windows. Cygwin performs similar translation to all output written to the console using Cygwin file descriptors, the filtering is done by the output functions of cygwin1.dll, to allow porting of POSIX C code to Windows.
In 2016, Microsoft released the Windows 10 Version 1511 update which unexpectedly implemented support for ANSI escape sequences. The change was designed to complement the Windows Subsystem for Linux, adding to the Windows Console Host used by Command Prompt support for character escape codes used by terminal-based software for Unix-like systems. This is not the default behavior and must be enabled programmatically with the Win32 API via. This was enabled by CMD.EXE but not initially by PowerShell; however, Windows PowerShell 5.1 now enables this by default. The ability to make a string constant containing ESC was added in PowerShell 6 with ; for PowerShell 5 you had to use.
Windows Terminal, introduced in 2019, supports the sequences by default, and it appears Microsoft intends to merge or replace Windows Console with it.

Atari ST

The Atari ST used the command system adapted from the VT52 with some expansions for color support, rather than supporting ANSI escape codes.

AmigaOS

not only interprets ANSI code sequences for text output to the screen, the AmigaOS printer driver also interprets them and translates them into the codes required for the particular printer that is actually attached.

Escape sequences

Escape sequences vary in length. The general format for an ANSI-compliant escape sequence is defined by ANSI X3.41. The is followed by zero or more intermediate "" bytes between hex 0x20 and 0x2F inclusive, followed by a final "" byte between 0x30 and 0x7E inclusive.
Additionally, some control functions take additional parameter data following the ESC sequence itself, i.e. after the byte of the ESC sequence. Specifically, the ESC sequence for is itself followed by a sequence of parameter and intermediate bytes, followed by a final byte between 0x40 and 0x7E; the entire sequence including both the ESC sequence for CSI and the subsequent parameter and identifier bytes is dubbed a "control sequence" by ECMA-48. Additionally, the ESC sequences for,,, and are followed by a variable-length sequence of parameter data terminated by ; this is known as a "control string".
ANSI X3.41 / ECMA-35 divides escape sequences into several broad categories:
The standard says that, in 8-bit environments, the control functions corresponding to type escape sequences can be represented as single bytes in the 0x80–0x9F range. However, on modern devices those codes are often used for other purposes, such as parts of UTF-8 or for CP-1252 characters, so only the 2-byte sequence is typically used.
Other C0 codes besides ESC — commonly BEL, BS, CR, LF, FF, TAB, VT, SO, and SI — produce similar or identical effects to some control sequences when output.
SequenceEscape typeC1ShortNameEffect
ESC N 0x8ESS2Single Shift TwoSelect a single character from one of the alternative character sets. SS2 selects the G2 character set, and SS3 selects the G3 character set. In a 7-bit environment, this is followed by one or more GL bytes specifying a character from that set. In an 8-bit environment, these may instead be GR bytes.
ESC O 0x8FSS3Single Shift ThreeSelect a single character from one of the alternative character sets. SS2 selects the G2 character set, and SS3 selects the G3 character set. In a 7-bit environment, this is followed by one or more GL bytes specifying a character from that set. In an 8-bit environment, these may instead be GR bytes.
ESC P 0x90DCSDevice Control StringTerminated by ST. Xterm's uses of this sequence include defining User-Defined Keys, and requesting or setting Termcap/Terminfo data.
ESC 0x9DOSCOperating System CommandStarts a control string for the operating system to use, terminated by ST. In xterm, they may also be terminated by BEL. For example, xterm allows the window title to be set by.
A non-xterm extension is the hyperlink, OSC 8 from 2017, used by VTE and iTerm2.
ESC X 0x98SOSStart of StringTakes an argument of a string of text, terminated by ST. The uses for these string control sequences are defined by the application or privacy discipline. These functions are rarely implemented and the arguments are ignored by xterm.
ESC ^ 0x9EPMPrivacy MessageTakes an argument of a string of text, terminated by ST. The uses for these string control sequences are defined by the application or privacy discipline. These functions are rarely implemented and the arguments are ignored by xterm.
ESC _ 0x9FAPCTakes an argument of a string of text, terminated by ST. The uses for these string control sequences are defined by the application or privacy discipline. These functions are rarely implemented and the arguments are ignored by xterm.

SequenceEscape typeShortNameEffect
ESC SP F ACS6, S7C1TAnnounce Code Structure 6 / Send 7-bit C1 Control Character to the HostDefined in ECMA-35 as announcing representation of C1 functions as 7-bit escape sequences in the following data. Terminals, in practice, implement this sequence as an instruction to change the format used in sequences generated by the terminal itself to 7-bit escape format.
ESC SP G ACS7, S8C1TAnnounce Code Structure 7 / Send 8-bit C1 Control Character to the HostDefined in ECMA-35 as announcing representation of C1 functions as 8-bit single bytes in the following data. Terminals, in practice, implement this sequence as an instruction to change the format used in sequences generated by the terminal itself to 8-bit single byte format.

Pressing special keys on the keyboard, as well as outputting many xterm CSI, DCS, or OSC sequences, often produces a CSI, DCS, or OSC sequence, sent from the terminal to the computer as though the user typed it.

CSI sequences

For CSI, or "Control Sequence Introducer" commands, the is followed by any number of "parameter bytes" in the range 0x30–0x3F, then by any number of "intermediate bytes" in the range 0x20–0x2F, then finally by a single "final byte" in the range 0x40–0x7E.
All common sequences just use the parameters as a series of semicolon-separated numbers such as. Missing numbers are treated as . Some sequences treat as in order to make missing parameters useful. Bytes other than digits and semicolon seem to not be used.
An example of a CSI sequence that cleans up the entire line:
A subset of arrangements was declared "private" so that terminal manufacturers could insert their own sequences without conflicting with the standard. Sequences containing the parameter bytes <=>? or the final bytes 0x70–0x7E are private.
The behavior of the terminal is undefined in the case where a CSI sequence contains any character outside of the range 0x20–0x7E. These illegal characters are either C0 control characters, DEL, or bytes with the high bit set. Possible responses are to ignore the byte, to process it immediately, and furthermore whether to continue with the CSI sequence, to abort it immediately, or to ignore the rest of it.

Terminal output sequences

CodeShortNameEffect
CSI ACUUCursor UpMoves the cursor cells in the given direction. If the cursor is already at the edge of the screen, this has no effect.
CSI BCUDCursor DownMoves the cursor cells in the given direction. If the cursor is already at the edge of the screen, this has no effect.
CSI CCUFCursor ForwardMoves the cursor cells in the given direction. If the cursor is already at the edge of the screen, this has no effect.
CSI DCUBCursor BackMoves the cursor cells in the given direction. If the cursor is already at the edge of the screen, this has no effect.
CSI ECNLCursor Next LineMoves cursor to beginning of the line lines down.
CSI FCPLCursor Previous LineMoves cursor to beginning of the line lines up.
CSI GCHAMoves the cursor to column .
CSI ; HCUPCursor PositionMoves the cursor to row, column. The values are 1-based, and default to if omitted. A sequence such as is a synonym for as well as is the same as and
CSI JEDErase in DisplayClears part of the screen. If is , clear from cursor to end of screen. If is, clear from cursor to beginning of the screen. If is, clear entire screen. If is, clear entire screen and delete all lines saved in the scrollback buffer.
CSI KELErase in LineErases part of the line. If is , clear from cursor to the end of the line. If is, clear from cursor to beginning of the line. If is, clear entire line. Cursor position does not change.
CSI SSUScroll UpScroll whole page up by lines. New lines are added at the bottom.
CSI TSDScroll DownScroll whole page down by lines. New lines are added at the top.
CSI ; fHVPSame as CUP, but counts as a format effector function rather than an editor function. This can lead to different handling in certain terminal modes.
CSI mSGRSelect Graphic RenditionSets the appearance of the following characters, see [|SGR parameters] below.
CSI 5iAUX Port OnEnable aux serial port usually for local serial printer
CSI 4iAUX Port OffDisable aux serial port usually for local serial printer
CSI 6nDSRDevice Status ReportReports the cursor position to the application as

CodeEffect
CSI sSCP/SCOSC: Save Current Cursor Position. Saves the cursor position/state in SCO console mode. In vertical split screen mode, instead used to set or reset left and right margins.
CSI uRCP/SCORC: Restore Saved Cursor Position. Restores the cursor position/state in SCO console mode.
CSI ? 25 hDECTCEM Shows the cursor, from the VT320.
CSI ? 25 lDECTCEM Hides the cursor.
CSI ? 1049 hEnable alternative screen buffer
CSI ? 1049 lDisable alternative screen buffer
CSI ? 2004 hTurn on bracketed paste mode. Text pasted into the terminal will be surrounded by and, and characters in it should not be treated as commands. From Unix terminal emulators.
CSI ? 2004 lTurn off bracketed paste mode.

SGR parameters

SGR sets display attributes. Several attributes can be set in the same sequence, separated by semicolons. Each display attribute remains in effect until a following occurrence of SGR resets it. If no codes are given, is treated as .
In ECMA-48 SGR is called "Select Graphic Rendition". In Linux manual pages the term "Set Graphics Rendition" is used.
CodeEffectNote
0Reset / NormalAll attributes off
1Bold or increased intensityAs with faint, the color change is a PC invention.
2Faint or decreased intensityaka Dim. May be implemented as a light font weight like bold.
3ItalicNot widely supported. Sometimes treated as inverse or blink.
4UnderlineStyle extensions exist for Kitty, VTE, mintty and iTerm2.
5Slow Blinkless than 150 per minute
6Rapid BlinkMS-DOS ANSI.SYS, 150+ per minute; not widely supported
7Reverse videoswap foreground and background colors, aka invert; inconsistent emulation
8Concealaka Hide, not widely supported.
9Crossed-outaka Strike, characters legible but marked as if for deletion.
10Primary font
11–19Alternative fontSelect alternative font
20FrakturRarely supported
21Doubly underline or Bold offDouble-underline per ECMA-48. See
22Normal color or intensityNeither bold nor faint
23Not italic, not Fraktur
24Underline offNot singly or doubly underlined
25Blink off
26Proportional spacingITU T.61 and T.416, not known to be used on terminals
27Reverse/invert off
28Revealconceal off
29Not crossed out
30–37Set foreground colorSee color table below
38Set foreground colorNext arguments are or, see below
39Default foreground colorimplementation defined
40–47Set background colorSee color table below
48Set background colorNext arguments are or, see below
49Default background colorimplementation defined
50Disable proportional spacingT.61 and T.416
51Framed
52EncircledImplemented as "emoji variation selector" in mintty.
53OverlinedImplemented as "emoji variation selector" in mintty.
54Not framed or encircled
55Not overlined
58Set underline colorKitty, VTE, mintty, and iTerm2.
Next arguments are or, see below
59Default underline colorKitty, VTE, mintty, and iTerm2.
60ideogram underline or right side lineRarely supported
61ideogram double underline or
double line on the right side
Rarely supported
62ideogram overline or left side lineRarely supported
63ideogram double overline or
double line on the left side
Rarely supported
64ideogram stress markingRarely supported
65ideogram attributes offreset the effects of all of –
73superscriptmintty
74subscriptmintty
90–97Set bright foreground coloraixterm
Set bright background coloraixterm

Colors

3/4 bit

The original specification only had 8 colors, and just gave them names. The SGR parameters 30-37 selected the foreground color, while 40-47 selected the background. Quite a few terminals implemented "bold" as a brighter color rather than a different font, thus providing 8 additional foreground colors. Usually you could not get these as background colors, though sometimes inverse video would allow that. Examples: to get black letters on white background use, to get red use, to get bright red use. To reset colors to their defaults, use , or reset all attributes with. Later terminals added the ability to directly specify the "bright" colors with 90-97 and 100-107.
When hardware started using 8-bit digital-to-analog converters several pieces of software assigned 24-bit color numbers to these names. The chart below shows values sent to the DAC for some common hardware and software.

8-bit

As 256-color lookup tables became common on graphic cards, escape sequences were added to select from a pre-defined set of 256 colors:
ESC 38;5; m Select foreground color
ESC[ 48;5; m Select background color
0- 7: standard colors
8- 15: high intensity colors
16-231: 6 × 6 × 6 cube : 16 + 36 × r + 6 × g + b
232-255: grayscale from black to white in 24 steps
The ITU's T.416 [Information technology
- Open Document Architecture and interchange format: Character content architectures uses ':' as separator characters instead:
ESC 38:5: m Select foreground color
ESC[ 48:5: m Select background color

24-bit

As "true color" graphic cards with 16 to 24 bits [of color
became common, Xterm, KDE's Konsole, iTerm, as well as all libvte based terminals support 24-bit foreground and background color setting.
ESC 38;2;;; m Select RGB foreground color
ESC[ 48;2;;; m Select RGB background color
The ITU's T.416 Information technology - Open Document Architecture and interchange format: Character content architectures which was adopted as ISO/IEC International Standard 8613-6 gives an alternative version that seems to be less supported. The parameters after the '2', i.e. even the r,g,b are optional. Note that this is not just the above sequence with semicolon replaced by colon, there is a leading "colorspace ID". The definition of the colorspace ID is not included in that document so it may be blank to represent the unspecified default. As well as the '2' value to specify a Red-Green-Blue format there are alternatives of '0' for implementation defined and '1' for transparent - neither of what have any further parameters; '3' specifies colors using a Cyan-Magenta-Yellow scheme, and '4' for a Cyan-Magenta-Yellow-Black one, the latter using the position marked as "unused" for the Black component:
ESC[ 38:2:::::::; m Select RGB foreground color
ESC[ 48:2:::::::; m Select RGB background color

Examples

— This clears the screen and, on some devices, locates the cursor to the y,x position 1,1.
— This makes text green. The green may be a dark, dull green, so you may wish to enable Bold with the sequence which would make it bright green, or combined as. Some implementations use the Bold state to make the character Bright.
— This reassigns the key F10 to send to the [keyboard buffer
the string "DIR" and ENTER, which in the DOS command line would display the contents of the current directory. This was sometimes used for ANSI bombs. This is a private-use code, using a non-standard extension to include a string-valued parameter. Following the letter of the standard would consider the sequence to end at the letter D.
— This saves the cursor position. Using the sequence will restore it to the position. Say the current cursor position is 7 and 10. The sequence will save those two numbers. Now you can move to a different cursor position, such as 20 and 3, using the sequence or. Now if you use the sequence CSI u the cursor position will return to 7 and 10. Some terminals require the DEC sequences / instead which is more widely supported.

Example of use in shell scripting

ANSI escape codes are often used in UNIX and UNIX-like terminals to provide syntax highlighting. For example, on compatible terminals, the following list command color-codes file and directory names by type.
Users can employ escape codes in their scripts by including them as part of standard output or standard error. For example, the following GNU sed command embellishes the output of the make command by displaying lines containing words starting with "WARN" in reverse video and words starting with "ERR" in bright yellow on a dark red background. The representations of the codes are highlighted.
make 2>&1 | sed -e 's/.*\bWARN.*/\x1bBash function flashes the terminal until the user presses a key.
flasher
This can be used to alert a programmer when a lengthy command terminates, such as with  .
printf \\033c
This will reset the console, similar to the command on modern Linux systems; however it should work even on older Linux systems and on other UNIX variants.

Example of use in C


  1. include
int main

Terminal input sequences

When typing input on a terminal keypresses outside the normal main alphanumeric keyboard area can be sent to the host as ANSI sequences. For keys that have an equivalent output function, such as the cursor keys, these often mirror the output sequences. However, for most keypresses there isn't an equivalent output sequence to use.
There are several encoding schemes, and unfortunately most terminals mix sequences from different schemes, so host software has to be able to deal with input sequences using any scheme.
To complicate the matter, the VT terminals themselves have two schemes of input, normal mode and application mode that can be switched by the application.

-> char
-> esc
-> esc
-> Alt-keypress or keycode sequence
'[' -> Alt-[
'[' '~' -> keycode sequence, defaults to 1

If the terminating character is '~', the first number must be present and is a
keycode number, the second number is an optional modifier value. If the terminating
character is a letter, the letter is the keycode value, and the optional number is
the modifier value.
The modifier value defaults to 1, and after subtracting 1 is a bitmap of modifier
keys being pressed: Meta-Ctrl-Alt-Shift. So, for example, <esc>[4;2~ is
Shift-End, <esc>[20~ is function key 9, <esc>[5C is Ctrl-Right.

vt sequences:
[1~ - Home [16~ - [31~ - F17
[2~ - Insert [17~ - F6 [32~ - F18
[3~ - Delete [18~ - F7 [33~ - F19
[4~ - End [19~ - F8 [34~ - F20
[5~ - PgUp [20~ - F9 [35~ -
[6~ - PgDn [21~ - F10
[7~ - Home [22~ -
[8~ - End [23~ - F11
[9~ - [24~ - F12
[10~ - F0 [25~ - F13
[11~ - F1 [26~ - F14
[12~ - F2 [27~ -
[13~ - F3 [28~ - F15
[14~ - F4 [29~ - F16
[15~ - F5 [30~ -
xterm sequences:
[A - Up [K - [U -
[B - Down [L - [V -
[C - Right [M - [W -
[D - Left [N - [X -
[E - [O - [Y -
[F - End [1P - F1 [Z -
[G - Keypad 5 [1Q - F2
[H - Home [1R - F3
[I - [1S - F4
[J - [T -

<esc>[A to <esc>[D are the same as the ANSI output sequences. The <num> is normally
omitted if no modifier keys are pressed, but most implementations always emit the
<num> for F1-F4.
Xterm has a comprehensive documentation page on the various function-key and mouse input sequence schemes from DEC's VT terminals and various other terminals it emulates. Thomas Dickey has added a lot of support to it over time; he also maintains a list of default keys used by other terminal emulators for comparison.

Invalid and ambiguous sequences in use

  • The Linux console uses to change the palette, which, if hard-coded into an application, may hang other terminals. However, appending will be ignored by Linux and form a proper, ignorable sequence for other terminals.
  • On the Linux console, certain function keys generate sequences of the form CSI ^_, which would form C1 codes.
  • Konsole generates SS3 modifiers char when F1–F4 are pressed with modifiers.