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.


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



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

ColorFont codeBackground code
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
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

Terminal manipulation

Switch to the terminal's secondary context\x1b[?1049h
Switch back to the terminal's primary context\x1b[?1049l