#[non_exhaustive]
pub enum ClearScreen {
Show 16 variants Terminfo, TerminfoScreen, TerminfoScrollback, TerminfoReset, XtermClear, XtermReset, TputClear, TputReset, Cls, WindowsVt, WindowsVtClear, WindowsCooked, VtRis, VtLeaveAlt, VtCooked, VtWellDone,
}
Expand description

Ways to clear the screen.

There isn’t a single way to clear the (terminal/console) screen. Not only are there several techniques to achieve the outcome, there are differences in the way terminal emulators intepret some of these techniques, as well as platform particularities.

In addition, there are other conditions a screen can be in that might be beneficial to reset, such as when a TUI application crashes and leaves the terminal in a less than useful state.

Finally, a terminal may have scrollback, and this can be kept as-is or cleared as well.

Your application may need one particular clearing method, or it might offer several options to the user, such as “hard” and “soft” clearing. This library makes no assumption and no judgement on what is considered hard, soft, or something else: that is your responsibility to determine in your context.

For most cases, you should use ClearScreen::default() to select the most appropriate method.

In any event, once a way is selected, call clear() to apply it.

Example

ClearScreen::default().clear().expect("failed to clear the screen");

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Terminfo

Does both TerminfoScreen and TerminfoScrollback, in this order, but skips the scrollback reset if the capability isn’t available.

This is essentially what the clear command on unix does. clear: https://invisible-island.net/ncurses/man/clear.1.html

§

TerminfoScreen

Looks up the clear capability in the terminfo (from the TERM env var), and applies it.

A non-hashed terminfo database is required (this is a terminfo crate limitation), such as the one provided with ncurses.

§

TerminfoScrollback

Looks up the E3 (Erase Scrollback) capability in the terminfo (from the TERM env var), and applies it.

The same terminfo limitation applies as for TerminfoScreen.

§

TerminfoReset

Performs a terminfo-driven terminal reset sequence.

This prints whichever are available of the rs1, rs2, rs3, and rf sequences. If none of these are available, it prints whichever are available of the is1, is2, is3, and if sequences. If none are available, an error is returned.

This generally issues at least an ESC c sequence, which resets all terminal state to default values, and then may issue more sequences to reset other things or enforce a particular kind of state. See XtermReset for a description of what XTerm does, as an example.

Note that this is not analogous to what tput reset does: to emulate that, issuing first one of VtCooked/VtWellDone/WindowsCooked followed by this variant will come close.

The same terminfo limitation applies as for TerminfoScreen.

§

XtermClear

Prints clear screen and scrollback sequence as if TERM=xterm.

This does not look up the correct sequence in the terminfo database, but rather prints:

  • CSI H (Cursor Position 0,0), which sets the cursor position to 0,0.
  • CSI 2J (Erase Screen), which erases the whole screen.
  • CSI 3J (Erase Scrollback), which erases the scrollback (xterm extension).
§

XtermReset

Prints the terminal reset sequence as if TERM=xterm.

This does not look up the correct sequence in the terminfo database, but rather prints:

  • ESC c (Reset to Initial State), which nominally resets all terminal state to initial values, but see the documentation for VtRis.
  • CSI !p (Soft Terminal Reset), which nominally does the same thing as RIS, but without disconnecting the terminal data lines… which matters when you’re living in 1970.
  • CSI ?3l (Reset to 80 Columns), which resets the terminal width to 80 columns, or more accurately, resets the option that selects 132 column mode, to its default value of no. I don’t know, man.
  • CSI ?4l (Reset to Jump Scrolling), which sets the scrolling mode to jump. This is naught to do with what we think of as “scrolling,” but rather it’s about the speed at which the terminal will add lines to the screen. Jump mode means “give it to me as fast as it comes” and Smooth mode means to do some buffering and output lines “at a moderate, smooth rate.”
  • CSI 4l (Reset to Replace Mode), which sets the cursor writing mode to Replace, i.e. overwriting characters at cursor position, instead of Insert, which pushes characters under the cursor to the right.
  • ESC > (Set Key Pad to Normal), which sets the keyboard’s numeric keypad to send “what’s printed on the keys” i.e. numbers and the arithmetic symbols.
  • CSI ?69l (Reset Left and Right Margins to the page), which sets the horizontal margins to coincide with the page’s margins: nowadays, no margins.
§

TputClear

Calls the command tput clear.

That command most likely does what Terminfo does internally, but may work better in some cases, such as when the terminfo database on the system is hashed or in a non-standard location that the terminfo crate does not find.

However, it relies on the tput command being available, and on being able to run commands.

§

TputReset

Calls the command tput reset.

See the documentation above on TputClear for more details, save that the equivalent is TerminfoReset.

§

Cls

Calls the command cls.

This is the Windows command to clear the screen. It has the same caveats as TputClear does, but its internal mechanism is not known. Prefer [WindowsClear][ClearScreen::WindowsClear] instead to avoid relying on an external command.

This will always attempt to run the command, regardless of compile target, which may have unintended effects if the cls executable does something different on the platform.

§

WindowsVt

Sets the Windows Console to support VT escapes.

This sets the ENABLE_VIRTUAL_TERMINAL_PROCESSING bit in the console mode, which enables support for the terminal escape sequences every other terminal uses. This is supported since Windows 10, from the Threshold 2 Update in November 2015.

Does nothing on non-Windows targets.

§

WindowsVtClear

Sets the Windows Console to support VT escapes and prints the clear sequence.

This runs WindowsVt and XtermClear, in this order. This is described here: https://docs.microsoft.com/en-us/windows/console/clearing-the-screen#example-1 as the recommended clearing method for all new development, although we also reset the cursor position.

While WindowsVt will do nothing on non-Windows targets, XtermClear will still run.

§

WindowsCooked

Uses Windows Console function to disable raw mode.

Does nothing on non-Windows targets.

§

VtRis

Prints the RIS VT100 escape code: Reset to Initial State.

This is the ESC c or 1b 63 escape, which by spec is defined to reset the terminal state to all initial values, which may be a range of things, for example as described in the VT510 manual: https://vt100.net/docs/vt510-rm/RIS

However, the exact behaviour is highly dependent on the terminal emulator, and some modern terminal emulators do not always clear scrollback, for example Tmux and GNOME VTE.

§

VtLeaveAlt

Prints the CSI sequence to leave the Alternate Screen mode.

If the screen is in alternate screen mode, like how vim or a pager or another such rich TUI application would do, this sequence will clear the alternate screen buffer, then revert the terminal to normal mode, and restore the position of the cursor to what it was before Alternate Screen mode was entered, assuming the proper sequence was used.

It will not clear the normal mode buffer.

This is useful when recovering from a TUI application which crashed without resetting state.

§

VtCooked

Sets the terminal to cooked mode.

This attempts to switch the terminal to “cooked” mode, which can be thought of as the opposite of “raw” mode, where the terminal does not respond to line discipline (which makes carriage return, line feed, and general typing display out to screen, and translates Ctrl-C to sending the SIGINT signal, etc) but instead passes all input to the controlling program and only displays what it outputs explicitly.

There’s also an intermediate “cbreak” or “rare” mode which behaves like “cooked” but sends each character one at a time immediately rather buffering and sending lines.

TUI applications such as editors and pagers often set raw mode to gain precise control of the terminal state. If such a program crashes, it may not reset the terminal mode back to the mode it found it in, which can leave the terminal behaving oddly or rendering it completely unusable.

In truth, these terminal modes are a set of configuration bits that are given to the termios(3) libc API, and control a variety of terminal modes. “Cooked” mode sets:

  • Input BRKINT set: on BREAK, flush i/o queues and send a SIGINT to any running process.
  • Input ICRNL set: translate Carriage Returns to New Lines on input.
  • Input IGNPAR set: ignore framing and parity errors.
  • Input ISTRIP set: strip off eigth bit.
  • Input IXON set: enable XON/XOFF flow control on output.
  • Output OPOST set: enable output processing.
  • Local ICANON set: enable canonical mode (see below).
  • Local ISIG set: when Ctrl-C, Ctrl-Q, etc are received, send the appropriate signal.

Canonical mode is really the core of “cooked” mode and enables:

  • line buffering, so input is only sent to the underlying program when a line delimiter character is entered (usually a newline);
  • line editing, so ERASE (backspace) and KILL (remove entire line) control characters edit the line before it is sent to the program;
  • a maximum line length of 4096 characters (bytes).

When canonical mode is unset (when the bit is cleared), all input processing is disabled.

Due to how the underlying tcsetattr function is defined in POSIX, this may complete without error if any part of the configuration is applied, not just when all of it is set.

Note that you generally want VtWellDone instead.

Does nothing on non-Unix targets.

§

VtWellDone

Sets the terminal to “well done” mode.

This is similar to VtCooked, but with a different, broader, mode configuration which approximates a terminal’s initial state, such as is expected by a shell, and clears many bits that should probably never be set (like the translation/mapping modes).

“Well done” mode is an invention of this library, inspired by several other sources such as Golang’s goterm, the termios(3) and tput(1) manual pages, but not identical to any.

Notably most implementations read the terminal configuration bits and only modify that set, whereas this library authoritatively writes the entire configuration from scratch.

It is a strict superset of VtCooked.

  • Input BRKINT set: on BREAK, flush i/o queues and send a SIGINT to any running process.
  • Input ICRNL set: translate Carriage Return to New Line on input.
  • Input IUTF8 set: input is UTF-8 (Linux only, since 2.6.4).
  • Input IGNPAR set: ignore framing and parity errors.
  • Input IMAXBEL set: ring terminal bell when input queue is full (not implemented in Linux).
  • Input ISTRIP set: strip off eigth bit.
  • Input IXON set: enable XON/XOFF flow control on output.
  • Output ONLCR set: do not translate Carriage Return to CR NL.
  • Output OPOST set: enable output processing.
  • Control CREAD set: enable receiver.
  • Local ICANON set: enable canonical mode (see VtCooked).
  • Local ISIG set: when Ctrl-C, Ctrl-Q, etc are received, send the appropriate signal.

Does nothing on non-Unix targets.

Implementations§

source§

impl ClearScreen

source

pub fn clear(self) -> Result<(), Error>

Performs the clearing action, printing to stdout.

Examples found in repository?
examples/clscli.rs (line 34)
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
fn main() -> Result<(), Error> {
	if let Some(variant) = env::args().nth(1) {
		let cs = match variant.as_str() {
			"auto" => ClearScreen::default(),
			"Terminfo" => ClearScreen::Terminfo,
			"TerminfoScreen" => ClearScreen::TerminfoScreen,
			"TerminfoScrollback" => ClearScreen::TerminfoScrollback,
			"TerminfoReset" => ClearScreen::TerminfoReset,
			"XtermClear" => ClearScreen::XtermClear,
			"XtermReset" => ClearScreen::XtermReset,
			"TputClear" => ClearScreen::TputClear,
			"TputReset" => ClearScreen::TputReset,
			"Cls" => ClearScreen::Cls,
			"WindowsVt" => ClearScreen::WindowsVt,
			"WindowsVtClear" => ClearScreen::WindowsVtClear,
			#[cfg(feature = "windows-console")]
			"WindowsConsoleClear" => ClearScreen::WindowsConsoleClear,
			#[cfg(feature = "windows-console")]
			"WindowsConsoleBlank" => ClearScreen::WindowsConsoleBlank,
			"WindowsCooked" => ClearScreen::WindowsCooked,
			"VtRis" => ClearScreen::VtRis,
			"VtLeaveAlt" => ClearScreen::VtLeaveAlt,
			"VtCooked" => ClearScreen::VtCooked,
			"VtWellDone" => ClearScreen::VtWellDone,
			_ => return Err(Error::UnknownVariant(variant)),
		};

		println!("variant = {:?}, sleeping 1 second", cs);
		sleep(Duration::from_secs(1));
		cs.clear()?;

		Ok(())
	} else {
		println!("Usage: cargo run --example cli -- <variant>\nWhere <variant> is one of the ClearScreen enum variants, same casing, or 'auto'.\nI recommend piping into `hexdump -C` to see what’s happening.");
		Ok(())
	}
}
source

pub fn clear_to(self, w: &mut impl Write) -> Result<(), Error>

Performs the clearing action, printing to a given writer.

This allows to capture any escape sequences that might be printed, for example, but note that it will not prevent actions taken via system APIs, such as the Windows, VtCooked, and VtWellDone variants do.

For normal use, prefer clear().

Trait Implementations§

source§

impl Clone for ClearScreen

source§

fn clone(&self) -> ClearScreen

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for ClearScreen

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for ClearScreen

source§

fn default() -> Self

Detects the environment and makes its best guess as how to clear the screen.

This function’s behaviour (but not its type signature) may change without notice, as better techniques appear. However, it will always strive to provide the best method. It will also never have side-effects, and finding any such behaviour should be reported as a bug.

If you wish to make your own, the is_microsoft_terminal() and is_windows_10() functions may be useful.

The ClearScreen variant selected is always in the “clear” behaviour side of things. If you wish to only clear the screen and not the scrollback, or to perform a terminal reset, or apply the other available clearing strategies, you’ll need to select what’s best yourself.

See the TERMINALS.md file in the repo for research on many terminals as well as the current result of this function for each terminal.

source§

impl PartialEq<ClearScreen> for ClearScreen

source§

fn eq(&self, other: &ClearScreen) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl Copy for ClearScreen

source§

impl Eq for ClearScreen

source§

impl StructuralEq for ClearScreen

source§

impl StructuralPartialEq for ClearScreen

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

const: unstable · source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
const: unstable · source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.