ANSI Escape Codes

This post is basically a cheatsheet to use ANSI escape codes to make beautiful terminal apps.

Table of contents

Ansi escape codes

ANSI escape codes allow you to do plenty of beautiful things in the terminal. You can change the color of the font, the color of the background, you can change the style of the font (bold, italic, underlined, etc...), and you can also move the cursor to overwrite previous text, to make text change dynamically.

This page is a cheatsheet for ANSI escape codes, because I often forget them and I struggle to find the information.

The special character

I don't understand really how it works, but many characters can work:

  • \033 which is the first one I used (good ol'times)
  • \e which fixed a few bugs for me
  • \x1B which seems to be the most portable one

Style codes

Building codes

Basically, the codes are built like this:

  • they start with \x1B[ (or any of the codes specified above + [)
  • then, the contain an arbitrary number of integers separated by ;
  • and they end with m

The code containing only 0 (being \x1B[0m) will reset any style property of the font.

Most of the time, you will print a code changing the style of your terminal, then print a certain string, and then, the reset code.

Styles

Here are the codes that allow you to change the font style.

StyleCode
Bold \x1B[1m
Faint \x1B[2m
Italic \x1B[3m
Underlined \x1B[4m
Inverse \x1B[7m
Strikethrough \x1B[9m

Colors

Here are the codes that you can use to change the color of the font, or the color of the background.

Color Font code Background code
Black \x1B[30m \x1B[40m
Red \x1B[31m \x1B[41m
Green \x1B[32m \x1B[42m
Yellow \x1B[33m \x1B[43m
Blue \x1B[34m \x1B[44m
Magenta\x1B[35m \x1B[45m
Cyan \x1B[36m \x1B[46m
White \x1B[37m \x1B[47m
Any palette color (with V in [0-255]) \x1B[38;5;Vm \x1B[48;5;Vm
Any RGB color (with values in [0-255]) \x1B[38;2;R;G;Bm \x1B[48;2;R;G;Bm

Cursor manipulation

Here are some useful codes to move the cursor around. Please note that they just move the cursor, so they don't really change anything to what's displayed. If you want to change what's displayed, you will have to move the cursor and print things. For example, if you want to delete the last character, you will have to:

  • move the cursor one character back
  • print a space (to delete the current character)
  • move the cursor one character back again, so your cursor is at the new end of the text
Effect Code
Goes back one character \b
Moves one line up \x1B[A
Moves n lines up (replace N by the number of lines) \x1B[NA
Goes back to the begining of the line \r
Goes back to the begining of the previous line \x1B[F
Goes back to the begining of the n-th previous line (replace N by the number of lines) \x1B[NF
Erases the whole line \x1B[2K