Alternate Screen
The alternate screen is a separate buffer that some terminals provide, distinct from the main screen. When activated, the terminal will display the alternate screen, hiding the current content of the main screen. Applications can write to this screen as if it were the regular terminal display, but when the application exits, the terminal will switch back to the main screen, and the contents of the alternate screen will be cleared. This is useful for applications like text editors or terminal games that want to use the full terminal window without disrupting the command line or other terminal content.
This creates a seamless transition between the application and the regular terminal session, as the content displayed before launching the application will reappear after the application exits.
Take this “hello world” program below. If we run it with and without the
std::io::stderr().execute(EnterAlternateScreen)?
(and the corresponding LeaveAlternateScreen
),
you can see how the program behaves differently.
Try running this code on your own and experiment with EnterAlternateScreen
and
LeaveAlternateScreen
.
Note that not all terminal emulators support the alternate screen, and even those that do may handle it differently. As a result, the behavior may vary depending on the backend being used. Always consult the specific backend’s documentation to understand how it implements the alternate screen.