I wrote an ANSI interpreter

Just for fun, I wrote an ANSI interpreter. It was surprisingly easy.

ANSI was hugely popular in the late 80s and then the 90s when BBSes were popular. They were an encoding system that allowed text to be displayed in different colors. ANSI escape codes generally take the form of ESC[{params}{char} where ESC is the escape character, \x1B, {params} is an optional list of numbers, delimited by semi-colons, and being the last part of the sequence, {char} dictates what formatting to apply, such as changing text color, enabling bold, or even moving the cursor around the screen.

Writing the interpreter was simple. I just needed to create a state machine whose state changes whenever a new character is read in from the ANSI file. The interpreter reads in characters and prints them out as it goes along. However, when it encounters an escape character, 0x1B, it goes into a state where it’s looking for ‘[‘, and if that succeeds, it goes into a “looking for parameters” state, and finally a “looking for the {char}” state. Once it gets that last char, it tells “executes” the command.

Go ahead and take a look at the source on bitbucket. It’s called Pansi. 😉

Here’s a video demonstrating it in action. I’ve hooked it up to a simple text renderer engine. However, my text renderer is using a free 8×8 bitmap font that does not have support for extended ASCII characters, and so I’ve had to cheat and just treat all those high-bit ASCII characters as 8×8 blocks. Hence, the artwork doesn’t look quite right. If you like the artwork in the demo and want to see them in full, download them at ACiD’s site.