nu_command/platform/
clear.rs

1use crossterm::{
2    QueueableCommand,
3    cursor::MoveTo,
4    terminal::{Clear as ClearCommand, ClearType},
5};
6use nu_engine::command_prelude::*;
7use nu_protocol::shell_error::io::IoError;
8
9use std::io::Write;
10
11#[derive(Clone)]
12pub struct Clear;
13
14impl Command for Clear {
15    fn name(&self) -> &str {
16        "clear"
17    }
18
19    fn description(&self) -> &str {
20        "Clear the terminal."
21    }
22
23    fn extra_description(&self) -> &str {
24        "By default clears the current screen and the off-screen scrollback buffer."
25    }
26
27    fn signature(&self) -> Signature {
28        Signature::build("clear")
29            .category(Category::Platform)
30            .input_output_types(vec![(Type::Nothing, Type::Nothing)])
31            .switch(
32                "keep-scrollback",
33                "Do not clear the scrollback history",
34                Some('k'),
35            )
36    }
37
38    fn run(
39        &self,
40        engine_state: &EngineState,
41        stack: &mut Stack,
42        call: &Call,
43        _input: PipelineData,
44    ) -> Result<PipelineData, ShellError> {
45        let from_io_error = IoError::factory(call.head, None);
46        match call.has_flag(engine_state, stack, "keep-scrollback")? {
47            true => {
48                std::io::stdout()
49                    .queue(MoveTo(0, 0))
50                    .map_err(&from_io_error)?
51                    .queue(ClearCommand(ClearType::All))
52                    .map_err(&from_io_error)?
53                    .flush()
54                    .map_err(&from_io_error)?;
55            }
56            _ => {
57                std::io::stdout()
58                    .queue(MoveTo(0, 0))
59                    .map_err(&from_io_error)?
60                    .queue(ClearCommand(ClearType::All))
61                    .map_err(&from_io_error)?
62                    .queue(ClearCommand(ClearType::Purge))
63                    .map_err(&from_io_error)?
64                    .flush()
65                    .map_err(&from_io_error)?;
66            }
67        };
68
69        Ok(PipelineData::Empty)
70    }
71
72    fn examples(&self) -> Vec<Example> {
73        vec![
74            Example {
75                description: "Clear the terminal",
76                example: "clear",
77                result: None,
78            },
79            Example {
80                description: "Clear the terminal but not its scrollback history",
81                example: "clear --keep-scrollback",
82                result: None,
83            },
84        ]
85    }
86}