What mechanism allows ViM to temporarily overwrite the entire console?

When you enter vim , it "clears" the screen. After exiting, it restores the original contents.

I understand that you can use \x1b[2J to clear the console and reset the cursor position, but this will overwrite the contents of the terminal.

I assume that Vim uses ncurses under the hood, in which case I believe the best question is how ncurses does it, but how is it done?

+7
vim tty ncurses
source share
2 answers

Most terminal emulators can save and restore screen contents.

The terminfo codes for this are: smcup to enter full screen mode and rmcup to leave it. (Higher termcap ti and te codes.)

If these features are included in the terminfo database, any program using ncurses will print the smcup line when writing and the rmcup line when exiting.

On the system I'm currently using, the lines (with \E representing the escape character):

 smcup: \E7\E[?1;47h rmcup: \E[2J\E[?1;47l\E8 

This restores the previous screen contents as well as the cursor position.

The specific sequence values ​​(for xterm) are described here :

  • smcup:
    • \E7 Save cursor
    • \E[?1;47h Application cursor keys; Using an alternate screen buffer
  • rmcup:
    • \E[2J Erase screen
    • \E[?1;47l Application cursor keys; Use regular screen buffer
    • \E8 Restore cursor

(This assumes that I am using the semicolon correctly, I am not 100% sure.)

+7
source share

Regarding @Keith Thompson's answer - not exactly:

  • vim does not use ncurses screen optimization, which automatically sends smcup and rmcup . Rather, it is a termcap application . This follows the convention used by most (not all) termcap applications. There are some versions of vi that are not used (for example, on IRIX64).
  • as for "most terminals"; in fact, xterm look-alikes is a small part of the database (even counting variations, less than 10%). Rephrase this to something like "the most common terminal emulators on Linux."
  • the terminal does not save or restore the contents of the screen. Instead, it switches between the two screens (in the xterm documentation "normal" and "alternate"). For example, in xterm you can always switch between them using a menu entry. Xterm FAQ Why doesn't the screen appear when vi starts up? gives more detailed information.
  • for a better context, note that smcup is an (obscure) abbreviation for setting cursor mode or cursor positioning to positional mode. (also cursor addressing). r in rmcup means "reset" (and m means "mode"). set / reset have different connotations from saving / restoring; with the latter, the user is convinced that the values ​​can be added.
+8
source share

All Articles