How does vi restore terminal content after quitting it?

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.

Leave a Comment