ANSI escape codes are a way to do more than just plain text in the terminal (be it Windows cmd.exe or UNIX xterm). A picture is worth a thousand words so here’s what I was able to do with them:

ANSI escape codes in action.

All of the text appearance manipulation and coloring was done using a tiny library I wrote yesterday and a very intuitive C++ syntax. Here’s the code responsible for the screenshot above:

colors.cpp:

Pretty easy to follow I hope πŸ™‚ The library defines a bunch of stream manipulators that inject the appropriate escape sequences. For example, cout << bold << "BOLD"; will print out, you guessed it, bolded text. color_n picks from the 8 bit color table. color_rgb let’s you define a 24 bit truecolor. The _bg_ version is for selecting the background color. Here’s the complete source code for the library, hope you will find it useful!

P.S. The color_rgb does not appear to work on Mac OS terminal. So far all the codes work only on Linux; haven’t tested on Windows πŸ™‚

ansi_escape_code.hpp:

5 Replies to “ANSI escape codes”

  1. Cool! I get errors like this with gcc5.4:
    ../src/ascii_escape_codes.hpp:13:7: error: ‘ascii_escape_codes::reset’ declared as an ‘inline’ variable
    ENTRY(reset, 0)
    ^
    ../src/ascii_escape_codes.hpp:9:40: note: in definition of macro ‘ENTRY’
    static inline struct name##_opcode {} name; \
    ^

    If I remove the “inline” I now get warnings such as:
    ../src/ascii_escape_codes.hpp:19:7: warning: ‘ascii_escape_codes::rapid_blink’ defined but not used [-Wunused-variable]
    ENTRY(rapid_blink, 6)
    ^
    ../src/ascii_escape_codes.hpp:9:33: note: in definition of macro ‘ENTRY’
    static struct name##_opcode {} name; \
    ^

    It works if I ignore these warnings, but your example makes my terminal super laggy. Do you know how I can get rid of the warnings?

    1. Looks similar enough to what I see on my Mac. What OS did you use?
      Not every terminal (Windows CMD, Linux) supports RGB/24bit colors.
      It’s probably best to use the few colors spelled out by name if one wants to be consistent across many platforms.

      P.S. Thanks for reading my blog πŸ™‚

Leave a Reply