How does vi restore terminal content after quitting it?

How does a program like vi or man or any other program replace the terminal content with the program's own contents then after quitting those programs they bring back the old terminal content?


Solution 1:

Vi flips to the alternate screen buffer, supported by terminals. This is achieved using escape sequences. See this link for full details.

The termcap entry for these are 'ti' to enter, and 'te' to exit full-screen mode.

As @Celada points out below, hardcoding xterm escape sequences is not a Good Idea™, because the sequences vary according to $TERM, for example:

xterm-color
  ti: <Esc> 7 <Esc> [ ? 47 h
  te: <Esc> [ 2 J <Esc> [ ? 4 7 l <Esc> 8

xterm-256color
  ti: <Esc> [ ? 1 0 4 9 h
  te: <Esc> [ ? 1 0 4 9 l

On the other hand, xterm support is very broad these days among non-xterm terminals. Supporting only xterm is unlikely to cause problems, except for users with exotic or obsolete $TERM settings. Source: I support products that do this.

Solution 2:

By sending control sequences to the terminal (xterm, vt-220) or using ncurses (like mc).

A ANSI Escape Sequence starts with ESC (\033 octal) [. ; separates Numbers.

C Example that clears the Screen and moves the cursor to 1,1.

#include <stdio.h>

int main()
{
    // clear the terminal
    printf("\033[2J\033[1;1H");
    printf("hello");

}

Example of switchting to alternate Buffer and back (xterm).

#include <stdio.h>
#include <unistd.h>

int main()
{
    printf("\033[?1049h\033[H");
    printf("hello\n");
    sleep(1);
    printf("bye");
    sleep(1);
    printf("\033[?1049l");
}