nu_command/platform/
clear.rs1use 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 screen."
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 search_terms(&self) -> Vec<&str> {
28 vec!["cls"]
29 }
30
31 fn signature(&self) -> Signature {
32 Signature::build("clear")
33 .category(Category::Platform)
34 .input_output_types(vec![(Type::Nothing, Type::Nothing)])
35 .switch(
36 "keep-scrollback",
37 "Do not clear the scrollback history.",
38 Some('k'),
39 )
40 }
41
42 fn run(
43 &self,
44 engine_state: &EngineState,
45 stack: &mut Stack,
46 call: &Call,
47 _input: PipelineData,
48 ) -> Result<PipelineData, ShellError> {
49 let from_io_error = IoError::factory(call.head, None);
50 match call.has_flag(engine_state, stack, "keep-scrollback")? {
51 true => {
52 std::io::stdout()
53 .queue(MoveTo(0, 0))
54 .map_err(&from_io_error)?
55 .queue(ClearCommand(ClearType::All))
56 .map_err(&from_io_error)?
57 .flush()
58 .map_err(&from_io_error)?;
59 }
60 _ => {
61 std::io::stdout()
62 .queue(MoveTo(0, 0))
63 .map_err(&from_io_error)?
64 .queue(ClearCommand(ClearType::All))
65 .map_err(&from_io_error)?
66 .queue(ClearCommand(ClearType::Purge))
67 .map_err(&from_io_error)?
68 .flush()
69 .map_err(&from_io_error)?;
70 }
71 };
72
73 Ok(PipelineData::empty())
74 }
75
76 fn examples(&self) -> Vec<Example<'_>> {
77 vec![
78 Example {
79 description: "Clear the terminal.",
80 example: "clear",
81 result: None,
82 },
83 Example {
84 description: "Clear the terminal but not its scrollback history.",
85 example: "clear --keep-scrollback",
86 result: None,
87 },
88 ]
89 }
90}