Outputting Inverse Text

Early computer terminals were text-only output devices. Sure, some got fancy and could do color text, perhaps even underline. Many of the early terminals, as well as the first handful of microcomputers (ancestors of the modern desktop), generated only text with perhaps some inverse text to spice things up.

The key to generating inverse text is ANSI, an acronym for the American National Standards Institute. ANSI defines various standards, including a set of terminal control escape sequences. Providing that the terminal, or your early microcomputer, supported ANSI (and inverse text), you could also output fancy text.

An ANSI escape sequence is named after the first character in the sequence, escape, ASCII code 27, hex 0x1b, and octal 033 (also Ctrl+[). A slew of such escape sequences are available, with the one to set inverse text looking like this:

\0x1b[7m

The escape character is followed by a left bracket, the number 7, and lowercase M.

Going inverse is keen, but annoying if you don’t change it back. To do so, this ANSI escape sequence is used:

\0x1b[m

These escape sequences are used in the following code to generate inverse text:

#include <stdio.h>

int main()
{
    printf("This is \x1b[7minverse\x1b[m text\n");

    return(0);
}

Many old school nerds, where I’ve recently learned that the term “neck beard” applies, prefer to use octal in their ANSI escape sequences. So it’s perfectly okey-doke to use this variation of the printf() statement:

printf("This is \033[7minverse\033[m text\n");

Anyhoo, here’s the output:

This is inverse text

If you don’t see this output, and instead see something like this: This is ?[7minverse?[m text, your terminal doesn’t support ANSI. Currently, the CMD window in Windows 10 doesn’t understand ANSI — which is odd because DOS definitely did.

ANSI can do more beyond inverse text: You can change text color, size, cursor position, clear parts of the screen, and more. All you need to know are the proper ANSI codes, which can be found on this website.

When coding ANSI escape sequences, be aware that not all terminals support the full range of ANSI codes. From what I’ve read, Microsoft is working on restoring ANSI features to the CMD and PowerShell terminal windows. Even so, don’t rely heavily on using the codes unless you’re certain of their output effects.

3 thoughts on “Outputting Inverse Text

  1. Faffing about with stuff like \0x1b[7m and \0x1b[m is a pain so on the thankfully rare occasions I need to do this I #define them with meaningful names, for example:

    #define RED “\x1B[31m”
    #define GRN “\x1B[32m”
    #define RESET “\x1B[0m”

    You could actually stick the whole lot in a .h file and never have to think about it again.

  2. I like the notion of defining the colors in a header file. Very neck beard. 😀

Leave a Reply