'How to reset the console output? Clearing just shifts the output back

My console application needs to clear the screen. How do I truly clear the screen, like the reset command in Linux?

I tried using methods I found on Google, like:

print!("{}[2J", 27 as char); // First attempt
print!("{}", termion::clear::All); // 'termion' crate, version 1.5.3

They all just scroll down, leaving the previous output behind. I thought of executing the reset command through Rust, but there must be some other way, right?



Solution 1:[1]

Since no one is writing an answer, I'll do.

As @mcarton mentioned, you need to use an alternate screen that will auto reset everything after going out of scope.

Basically this will create a virtual screen over your current terminal screen that will be positioned just on the old one at the same coordinates with the same height and width. Its like a copy, for short.

During your program you will write and delete to the alternate screen without harming your terminal screen.

An example working code from docs is:

use termion::screen::AlternateScreen;
use std::io::{Write, stdout};

fn main() {
    {
        let mut screen = AlternateScreen::from(stdout());
        write!(screen, "Writing to alternate screen!").unwrap();
        screen.flush().unwrap();
    }
    println!("Writing to main screen.");
}

You can also use termion to print to the mutable alternate screen.

        write!(
            screen,
            "{}{}{}",
            termion::cursor::Goto(1, 10),
            "some text on coordinates (y=10, x=1)",
            termion::cursor::Hide,
        )
        .unwrap();
//
// to refresh the screen you need to flush it, i.e 
// to write all the changes from the buffer to the screen
// just like flushing to toilet, 
// but flushing the buffer where the text was placed
// which is a matrix
        self.screen.flush().unwrap();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 alexzander