Control Codes

Another important terminal concept is control sequences, also called ANSI escape sequences, EMCA-48, or VT100 codes. An application can write certain sequences of characters to a terminal output, which the terminal recognizes as a control sequence. The control sequence causes the terminal to change some aspect of its state without being printed to the terminal output; this is called in-band signaling, because the signal is carried in normal output. There are a great many control sequences, which are used to do things like change text decoration and cursor position, clear the screen, reset the terminal, change character encodings, and so on.

Two control codes that are used by a variety of terminal-based applications are smcup and rmcup which mean “save memory cursor position”, and “restore memory cursor position”. These are used by terminal emulators to switch between two different screen buffers, known as the “alternate screen” and the “normal screen”. The normal screen acts like a stream of paper and allows the user to scroll back through previous output, while the alternate screen acts more like a fixed grid of display characters and doesn’t support scrollback. The normal screen is usually used by the command-line interface and other programs that produce streams of output, while the alternate screen is used by applications that want to draw an interface of some sort to the screen, such as text editors.

The state of the normal and alternate screens are saved and restored when switching to and fro, allowing an application to draw to the alternate screen without overwriting the contents of the scrollback buffer. When the application is exited, it switches back to the normal screen during cleanup. You will see these effects, for example, when using the vim text editor, or when reading man pages with man.