When you enter vim, it "clears" the screen. Upon exiting, it "restores" the original contents.
I understand one can use \x1b[2J
to clear the console and reset the cursor position, but this will overwrite terminal contents.
I assume Vim uses ncurses under the hood, in which case I suppose the better question is how ncurses does this, but how is it done?
Most terminal emulators are able to save and restore the contents of the screen.
The terminfo codes for this are smcup
to enter full-screen mode and rmcup
to leave it. (The older termcap codes are ti
and te
.)
If these capabilities are enabled in the terminfo
database, any program that uses ncurses
will print the smcup
string on entry, and the rmcup
string on exit.
On the system I'm using at the moment, the strings are (with \E
representing the Escape character):
smcup: \E7\E[?1;47h
rmcup: \E[2J\E[?1;47l\E8
This restores the previous contents of the screen as well as the cursor position.
The specific meanings of the sequences (for xterm) are documented here:
\E7
Save Cursor\E[?1;47h
Application Cursor Keys; Use Alternate Screen Buffer\E[2J
Erase screen\E[?1;47l
Application Cursor Keys; Use Normal Screen Buffer\E8
Restore Cursor(This assumes I'm understanding the use of the semicolon correctly; I'm not 100% sure of that.)
Regarding the answer by @Keith Thompson — not exactly:
smcup
and rmcup
automatically. Rather, it is a termcap application. It follows a convention used by most (not all) termcap applications. There are some implementations of vi
which do not for instance (on IRIX64 perhaps).smcup
is an (obscure) abbreviation for set-mode-cursor-positioning, or start cursor-positioning mode. (also cursor-addressing). The r
in rmcup
means "reset" (and m
means "mode"). set/reset have different connotations from save/restore; with the latter the user is led to believe that the values can be stacked up.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With