Safekipedia

ANSI escape code

Discoverer · ages 10+Adapted from Wikipedia
A DEC VT100 computer terminal on display at the Living Computer Museum, where it was connected to a historic DEC PDP-11/70 computer.

ANSI escape sequences are a standard for controlling what appears on video text terminals and terminal emulators. These are the screens and programs that show text on computers. The standard lets a computer control the position of the cursor, the color of text, font styling, and other options. It works through in-band signaling, meaning the control instructions are sent along with the text itself.

Special sequences of bytes are placed inside ordinary text. Most of them begin with an ASCII escape character followed by a bracket character. The terminal reads these sequences as commands rather than as words to show on the screen. Because of this, ANSI codes can change the color of text and move the cursor so that text can be drawn anywhere on the screen.

ANSI sequences were introduced in the 1970s to replace sequences that were specific to each computer maker. By the early 1980s they had become widespread in the computer equipment market.

Hardware text terminals have become increasingly rare in the 21st century. However, the ANSI standard is still important. A great majority of terminal emulators and command consoles understand at least part of the ANSI standard.

The name ANSI stands for "American National Standards Institute".

History

Most makers of video terminals added their own special codes for tasks such as placing the cursor at a spot on the screen. The VT52 terminal, for example, used the ESC character, a Y character, and two more characters that stood for the x,y location. The Hazeltine 1500 had a similar feature, but it used different codes. Because each terminal needed different codes, people created tools such as termcap ("terminal capabilities") and tput so that programs could use the same API with any terminal. Many terminals also needed numbers sent as the binary values of characters, which was hard for some programming languages and for systems that did not use ASCII.

The DEC VT100 video display terminal

The ANSI standard tried to fix these problems with one command set that all terminals would use, and with all numbers sent as ASCII numbers. Its first version, ECMA-48, was adopted in 1976. It continued a series of character coding standards that began with ECMA-6 in 1965, from which ISO 646 comes. The name "ANSI escape sequence" dates from 1979, when ANSI adopted ANSI X3.64. The two standards were later merged into ISO 6429, and in 1994 ANSI withdrew its standard in favor of the international one.

The first popular video terminal to support these sequences was the Digital VT100, introduced in 1978, and its success led to many clones, such as the affordable Zenith Z-19 in 1979, the Qume QVT-108, the Televideo TVI-970, and the Wyse WY-99GT. Over time, software such as bulletin board systems and online services relied on the escape sequences working, so almost all new terminals and emulator programs supported them. In 1981, FIPS publication 86 adopted ANSI X3.64 for use in the US government, but it was later withdrawn when the government stopped duplicating industry standards. ECMA-48 has been updated several times and is currently in its 5th edition from 1991. It is also adopted by IEC as ISO/IEC 6429, and a version is adopted as a Japanese Industrial Standard, JIS X 0211. Related standards include ITU T.61, the Teletex standard, and ISO/IEC 8613, the Open Document Architecture standard, which share many escape codes with the ANSI system.

Platform support

The Xterm terminal emulator

In the early 1980s, a lot of software used these codes to update what appeared on the screen. This included everything on VMS, most software made to run on CP/M home computers, and much Unix-style software, because it was easier to use than other methods. Terminal emulators that connect to other computers almost always support these codes, and xterm on Unix can also work with software on the same machine. Computers later gained built-in displays that supported the codes, and people tried to extend them to printers and to the Open Document Architecture.

The IBM PC, introduced in 1981, did not support these codes. It only understood a few control characters, such as BEL, CR, LF, and BS. Later, DOS 2.0 included an optional device driver called ANSI.SYS, but it was slow and was not installed by default, so software rarely used it. The Windows Console did not support these codes at all, and programs such as TCC and ConEmu were created to add support. In 2016, Microsoft released a Windows 10 update, version 1511, which unexpectedly added support for these codes. Today, Windows Terminal supports them by default.

C0 control codes

Almost all users expect some single-byte characters to have certain functions. These codes were first defined as part of ASCII. Today, the default C0 control code set is defined in ISO 6429 (ECMA-48), which is part of the same standard as the C1 set used by ANSI escape sequences. ISO 2022 allows the C0 set to be used without the C1 set, and the other way around, as long as 0x1B is always ESC. These codes are used to shorten the amount of data sent or to do some jobs that escape sequences cannot do:

Escape sequences vary in length. Their general format is set by ANSI X3.41. They use only bytes from 0x20 to 0x7F, which are all the non-control ASCII characters, so they can be read without looking ahead. What happens if a control character or other invalid byte appears before the sequence ends is undefined.

Popular C0 control codes
^C0AbbrC escape sequenceNameEffect
^G0x07BEL\aBellMakes an audible noise.
^H0x08BS\bBackspaceMoves the cursor left (but may "backwards wrap" if cursor is at start of line).
^I0x09HT\tTabMoves the cursor right to next tab stop.
^J0x0ALF\nLine FeedMoves to next line, scrolls the display up if at bottom of the screen. Usually does not move horizontally, though programs should not rely on this.
^L0x0CFF\fForm FeedMove a printer to top of next page. Usually does not move horizontally, though programs should not rely on this. Effect on video terminals varies.
^M0x0DCR\rCarriage ReturnMoves the cursor to column zero.
^[0x1BESC\x1B, \033EscapeStarts all the escape sequences

Fe Escape sequences

When the ESC character is followed by a certain code, the sequence is called an Fe type. What it means is decided by the rules for C1 control codes. All escape sequences for those control codes follow this same format.

In 8-bit systems, these control codes can be written as single bytes. This works with character encodings based on the ISO 8859 series. However, modern devices use encodings such as UTF-8 or CP-1252, where those codes are often used for other things. So a two-byte sequence is usually used instead. In UTF-8, a C1 control code is written using the C1 Controls and Latin-1 Supplement block, which gives a different two-byte code, but this does not save any space.

Some type Fe (C1 set element) ANSI escape sequences (not an exhaustive list)
CodeC1AbbrNameEffect
ESC N0x8ESS2Single 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 (0x20–0x7F) specifying a character from that set.: 9.4  In an 8-bit environment, these may instead be GR bytes (0xA0–0xFF).: 8.4 
ESC O0x8FSS3Single Shift Three
ESC P0x90DCSDevice Control StringTerminated by ST.: 5.6  Xterm's uses of this sequence include defining User-Defined Keys, and requesting or setting Termcap/Terminfo data.
ESC [0x9BCSIControl Sequence IntroducerStarts most of the useful sequences, terminated by a byte in the range 0x40 through 0x7E.: 5.4 
ESC \0x9CSTString TerminatorTerminates strings in other controls.: 8.3.143 
ESC ]0x9DOSCOperating System CommandStarts a control string for the operating system to use, terminated by ST.: 8.3.89 
ESC X0x98SOSStart of StringTakes an argument of a string of text, terminated by ST.: 5.6  The uses for these string control sequences are defined by the application: 8.3.2, 8.3.128  or privacy discipline.: 8.3.94  These functions are rarely implemented and the arguments are ignored by xterm. Some Kermit clients allow the server to automatically execute Kermit commands on the client by embedding them in APC sequences; this is a potential security risk if the server is untrusted.
ESC ^0x9EPMPrivacy Message
ESC _0x9FAPCApplication Program Command

Control Sequence Introducer commands

Control Sequence Introducer, or CSI, commands start with the characters ESC [, which some programming languages write as \e[, \x1b[, or \033[. After these come some optional settings, and then one final character that tells the terminal what to do.

Most of these commands use numbers separated by semicolons, such as 1;2;3. If a number is missing, the terminal treats it as 0. Some commands were set aside as "private," so that companies making terminals could add their own commands without clashing with the standard.

Some ANSI control sequences (not an exhaustive list)
CodeAbbrNameEffect
CSI n ACUUCursor UpMoves the cursor n (default 1) cells in the given direction. If the cursor is already at the edge of the screen, this has no effect.
CSI n BCUDCursor Down
CSI n CCUFCursor Forward
CSI n DCUBCursor Back
CSI n ECNLCursor Next LineMoves cursor to beginning of the line n (default 1) lines down. (not ANSI.SYS)
CSI n FCPLCursor Previous LineMoves cursor to beginning of the line n (default 1) lines up. (not ANSI.SYS)
CSI n GCHACursor Horizontal AbsoluteMoves the cursor to column n (default 1). (not ANSI.SYS)
CSI n ; m HCUPCursor PositionMoves the cursor to row n, column m. The values are 1-based, and default to 1 (top left corner) if omitted. A sequence such as CSI ;5H is a synonym for CSI 1;5H as well as CSI 17;H is the same as CSI 17H and CSI 17;1H
CSI n JEDErase in DisplayClears part of the screen. If n is 0 (or missing), clear from cursor to end of screen. If n is 1, clear from cursor to beginning of the screen. If n is 2, clear entire screen (and moves cursor to upper left on DOS ANSI.SYS). If n is 3, clear entire screen and delete all lines saved in the scrollback buffer (this feature was added for xterm and is supported by other terminal applications).
CSI n KELErase in LineErases part of the line. If n is 0 (or missing), clear from cursor to the end of the line. If n is 1, clear from cursor to beginning of the line. If n is 2, clear entire line. Cursor position does not change.
CSI n SSUScroll UpScroll whole page up by n (default 1) lines. New lines are added at the bottom. (not ANSI.SYS)
CSI n TSDScroll DownScroll whole page down by n (default 1) lines. New lines are added at the top. (not ANSI.SYS)
CSI n ; m fHVPHorizontal Vertical PositionSame as CUP, but counts as a format effector function (like CR or LF) rather than an editor function (like CUD or CNL). This can lead to different handling in certain terminal modes.: Annex A 
CSI n mSGRSelect Graphic RenditionSets colors and style of the characters following this code
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 (CPR) by transmitting ESC[n;mR, where n is the row and m is the column.
Some popular private sequences
CodeAbbrNameEffect
CSI sSCP, SCOSCSave Current Cursor PositionSaves the cursor position/state in SCO console mode. In vertical split screen mode, instead used to set (as CSI n ; n s) or reset left and right margins.
CSI uRCP, SCORCRestore Saved Cursor PositionRestores the cursor position/state in SCO console mode.
CSI ? 25 hDECTCEMShows the cursor, from the VT220.
CSI ? 25 lDECTCEMHides the cursor.
CSI ? 1004 hEnable reporting focus. Reports whenever terminal emulator enters or exits focus as ESC [I and ESC [O, respectively.
CSI ? 1004 lDisable reporting focus.
CSI ? 1049 hEnable alternative screen buffer, from xterm
CSI ? 1049 lDisable alternative screen buffer, from xterm
CSI ? 2004 hTurn on bracketed paste mode. In bracketed paste mode, text pasted into the terminal will be surrounded by ESC [200~ and ESC [201~; programs running in the terminal should not treat characters bracketed by those sequences as commands (Vim, for example, does not treat them as commands). From xterm
CSI ? 2004 lTurn off bracketed paste mode.

Select Graphic Rendition parameters

The control sequence CSI n m, called Select Graphic Rendition (SGR), changes how text looks on screen. Several settings can be combined in one sequence by separating them with semicolons, and each setting stays in effect until a later SGR changes it. If no codes are given, CSI m works the same as CSI 0 m, which resets the text to normal.

Colors were added to terminals in stages. The first standard had only 8 named colors, and later terminals added brighter versions of them. As 256-color lookup tables became common on graphics cards, sequences were added to choose from 256 colors, and the 8-bit color codes that make this possible are shown below. Later, as "true color" graphics became common, programs such as Konsole and GNOME Terminal added support for 24-bit colors, which use red, green, and blue values. Because the color lists are not fixed by the standards, the exact colors can look different from one terminal emulator to another.

See also: Web colors § Web-safe colors

nNameNote
0Reset or normalAll attributes become turned off
1Bold or increased intensityAs with faint, the color change is a PC (SCO / CGA) invention.
2Faint, decreased intensity, or dimMay 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, iTerm2 and Konsole.
5Slow blinkSets blinking to less than 150 times per minute
6Rapid blinkMS-DOS ANSI.SYS, 150+ per minute; not widely supported
7Reverse video or invertSwap foreground and background colors.
8Conceal or hideNot widely supported.
9Crossed-out, or strikeCharacters legible but marked as if for deletion. Not supported in Terminal.app.
10Primary (default) font
11–19Alternative fontSelect alternative font n − 10
20Fraktur (Gothic)Rarely supported
21Doubly underlined; or: not boldDouble-underline per ECMA-48,: 8.3.117  but instead disables bold intensity on several terminals, including in the Linux kernel's console before version 4.17.
22Normal intensityNeither bold nor faint; color changes where intensity is implemented as such.
23Neither italic, nor blackletter
24Not underlinedNeither singly nor doubly underlined
25Not blinkingTurn blinking off
26Proportional spacingITU T.61 and T.416, not known to be used on terminals
27Not reversed
28RevealNot concealed
29Not crossed out
30–37Set foreground color
38Set foreground colorNext arguments are 5;n or 2;r;g;b
39Default foreground colorImplementation defined (according to standard)
40–47Set background color
48Set background colorNext arguments are 5;n or 2;r;g;b
49Default background colorImplementation defined (according to standard)
50Disable proportional spacingT.61 and T.416
51FramedImplemented as "emoji variation selector" in mintty.
52Encircled
53OverlinedNot supported in Terminal.app
54Neither framed nor encircled
55Not overlined
58Set underline colorNot in standard; implemented in Kitty, VTE, mintty, and iTerm2. Next arguments are 5;n or 2;r;g;b.
59Default underline colorNot in standard; implemented in Kitty, VTE, mintty, and iTerm2.
60Ideogram underline or right side lineRarely supported
61Ideogram double underline, or double line on the right side
62Ideogram overline or left side line
63Ideogram double overline, or double line on the left side
64Ideogram stress marking
65No ideogram attributesReset the effects of all of 60–64
73SuperscriptImplemented only in mintty
74Subscript
75Neither superscript nor subscript
90–97Set bright foreground colorNot in standard; originally implemented by aixterm
100–107Set bright background color
FGBGNameCGA/EGA/VGAWindows ConsolePowerShell 1.0–6.0VS CodeWindows 10 ConsoleTerminal.appPuTTYmIRCxtermUbuntuEclipse Terminal
3040Black0, 0, 012, 12, 120, 0, 01, 1, 10, 0, 0
3141Red196, 0, 0128, 0, 0205, 49, 49197, 15, 31153, 0, 0187, 0, 0127, 0, 0205, 0, 0222, 56, 43205, 0, 0
3242Green0, 196, 00, 128, 013, 188, 12119, 161, 140, 166, 00, 187, 00, 147, 00, 205, 057, 181, 740, 205, 0
3343Yellow196, 126, 0128, 128, 0238, 237, 240229, 229, 16193, 156, 0153, 153, 0187, 187, 0252, 127, 0205, 205, 0255, 199, 6205, 205, 0
3444Blue0, 0, 1960, 0, 12836, 114, 2000, 55, 2180, 0, 1780, 0, 1870, 0, 1270, 0, 2380, 111, 1840, 0, 238
3545Magenta196, 0, 196128, 0, 1281, 36, 86188, 63, 188136, 23, 152178, 0, 178187, 0, 187156, 0, 156205, 0, 205118, 38, 113205, 0, 205
3646Cyan0, 196, 1960, 128, 12817, 168, 20558, 150, 2210, 166, 1780, 187, 1870, 147, 1470, 205, 20544, 181, 2330, 205, 205
3747White196, 196, 196192, 192, 192229, 229, 229204, 204, 204191, 191, 191187, 187, 187210, 210, 210229, 229, 229204, 204, 204229, 229, 229
90100Bright Black (Gray)78, 78, 78128, 128, 128102, 102, 102118, 118, 118102, 102, 10285, 85, 85127, 127, 127127, 127, 127128, 128, 1280, 0, 0
91101Bright Red220, 78, 78255, 0, 0241, 76, 76231, 72, 86230, 0, 0255, 85, 85255, 0, 0
92102Bright Green78, 220, 780, 255, 035, 209, 13922, 198, 120, 217, 085, 255, 850, 252, 00, 255, 0
93103Bright Yellow243, 243, 78255, 255, 0245, 245, 67249, 241, 165230, 230, 0255, 255, 85255, 255, 0
94104Bright Blue78, 78, 2200, 0, 25559, 142, 23459, 120, 2550, 0, 25585, 85, 2550, 0, 25292, 92, 2550, 0, 25592, 92, 255
95105Bright Magenta243, 78, 243255, 0, 255214, 112, 214180, 0, 158230, 0, 230255, 85, 255255, 0, 255
96106Bright Cyan78, 243, 2430, 255, 25541, 184, 21997, 214, 2140, 230, 23085, 255, 2550, 255, 255
97107Bright White255, 255, 255229, 229, 229242, 242, 242230, 230, 230255, 255, 255

Operating System Command sequences

Most Operating System Command sequences were defined by Xterm, but many other terminal programs also support them. For historical reasons, Xterm can end a command with BEL as well as the standard ending. For example, Xterm lets the icon name and window title be set with a code that ends with BEL. A hyperlink code from 2017 is not part of Xterm, but it is used by VTE, iTerm2, and mintty, among others.

The Linux console uses a code to change its color palette. If this code were built into a program, it might freeze other terminals. Adding an extra ending to the code is ignored by Linux, and other terminals read it as a complete code that they can safely skip.

Fs Escape sequences

When the escape character (ESC) is followed by a code from a certain range of values, the sequence is called an Fs type. This type is used for control functions that are registered one at a time with the ISO-IR registry.

A table of these functions is listed under ISO/IEC 2022.

Fp Escape sequences

When the escape character (ESC) is followed by a byte in the range 0x30 to 0x3F, the sequence is of type Fp. This type is set apart for up to sixteen private-use control functions.

Some type Fp (private-use) escape sequences recognised by the VT100
AbbrNameEffect
ESC 7DECSCDEC Save CursorSaves the cursor position, encoding shift state and formatting attributes.
ESC 8DECRCDEC Restore CursorRestores the cursor position, encoding shift state and formatting attributes from the previous DECSC if any, otherwise resets these all to their defaults.

nF Escape sequences

An escape sequence is of the nF type when the escape character is followed by a code from one range of values. More codes from that range can follow, and then a final code from another range ends the sequence. These sequences are sorted into groups by their first code, and by whether the final code marks private use.

Most nFt sequences change the current character set, and they are listed in ISO/IEC 2022. Some others:

When the first code is '#', the public sequences are reserved for extra registered control functions. No such sequences are registered at present. Type 3Fp sequences, which include those starting with '#', are available for private-use control functions.

Some type 0Ft (announcement) ANSI escape sequences: 15.2 
AbbrNameEffect
ESC SP F
ACS6
S7C1T
Announce Code Structure 6
Send 7-bit C1 Control Character to the Host
Makes the function keys send ESC + letter instead of 8-bit C1 codes.
ESC SP G
ACS7
S8C1T
Announce Code Structure 7
Send 8-bit C1 Control Character to the Host
Makes the function keys send 8-bit C1 codes.
Some type 3Fp (private-use) escape sequences recognised by the VT100
AbbrNameEffect
ESC # 3DECDHLDEC Double-Height Letters, Top HalfMakes the current line use characters twice as tall. This code is for the top half.
ESC # 4DECDHLDEC Double-Height Letters, Bottom HalfMakes the current line use characters twice as tall. This code is for the bottom half.
ESC # 5DECSWLDEC Single-Width LineMakes the current line use single-width characters, per the default behaviour.
ESC # 6DECDWLDEC Double-Width LineMakes the current line use double-width characters, discarding any characters in the second half of the line.

Examples

Some codes control the screen. CSI 2 J clears the screen and, on some devices, moves the cursor to the upper left corner. CSI 32 m makes text green, and adding CSI 1 m makes it brighter. Some codes change what the keyboard sends, such as one that makes the F10 key type "DIR" and ENTER in MS-DOS, which was ANSI bombs sometimes used. The codes CSI s and CSI u save and restore the cursor position.

Output of example program on Gnome Terminal

In shell scripting, these codes are often used in UNIX and UNIX-like terminals for syntax highlighting. For example, the list command can color file and folder names by type. Users can also add codes to standard output or standard error in their scripts. One example uses the sed command to mark lines from make that contain "WARN" in reverse video and lines with "ERR" in bright yellow, ignoring letter case. A Bash function can flash the terminal until a key is pressed. A C program can also display the numbers 0 to 109 in the format of each Select Graphic Rendition code.

Terminal input sequences

When a user presses special keys, such as arrow keys or function keys, the terminal sends a special code to the computer, as if the user had typed it. For some keys, like the cursor keys, the code matches the code the computer uses to move the cursor. Most other keys have no matching code. Terminals use several different code styles and often mix them, so programs must be able to understand all of them. VT terminals also have a normal mode and an application mode, and a program can switch between them.

When a modifier key such as Shift, Alt, or Ctrl is held down, a number is added to the code to show which keys are pressed. For example, 4;2~ means Shift+End, and [20~ means function key F9. Some terminal programs handle these keys differently. Old versions of [Terminator copied a faulty behavior from GNOME Terminal, and Konsole uses its own codes for F1 to F4 when modifiers are used. Some terminals, including iTerm2 and kitty, can also report extra keys using an enhanced mode.

Key pressedNumberComment
1always added, the rest are optional
Shift1
(Left) Alt2
Control4
Meta8

Quiz time!

5 questions about ANSI escape code

Question 1 of 5

What can ANSI escape sequences let a computer control on a terminal screen?

Pictures

A screenshot of htop, a program that shows the processes running on a computer, displayed in a terminal on Ubuntu.

Keep exploring

This article is a child-friendly adaptation of the Wikipedia article on ANSI escape code, available under CC BY-SA 4.0.

Images from Wikimedia Commons. Tap any image to view credits and license.