Skip to main content

nu_command/platform/clip/
copy.rs

1use super::clipboard::provider::{Clipboard, create_clipboard};
2use crate::viewers::render_value_as_plain_table_text;
3use nu_engine::command_prelude::*;
4
5#[derive(Clone)]
6pub struct ClipCopy;
7
8impl ClipCopy {
9    fn copy_text(
10        engine_state: &EngineState,
11        stack: &mut Stack,
12        input: &Value,
13        span: Span,
14        config: &nu_protocol::Config,
15    ) -> Result<(), ShellError> {
16        let text = match input {
17            Value::String { val, .. } => val.to_owned(),
18            _ => render_value_as_plain_table_text(engine_state, stack, input.clone(), span)?,
19        };
20
21        create_clipboard(config, engine_state, stack).copy_text(&text)
22    }
23}
24
25impl Command for ClipCopy {
26    fn name(&self) -> &str {
27        "clip copy"
28    }
29
30    fn signature(&self) -> Signature {
31        Signature::build(self.name())
32            .input_output_types(vec![(Type::Any, Type::Any)])
33            .switch("show", "Display copied value in the output.", Some('s'))
34            .category(Category::System)
35    }
36
37    fn description(&self) -> &str {
38        "Copy the input into the clipboard."
39    }
40
41    fn run(
42        &self,
43        engine_state: &EngineState,
44        stack: &mut Stack,
45        call: &Call,
46        input: PipelineData,
47    ) -> Result<PipelineData, ShellError> {
48        let value = input.into_value(call.head)?;
49        let config = stack.get_config(engine_state);
50
51        Self::copy_text(engine_state, stack, &value, call.head, &config)?;
52
53        if call.has_flag(engine_state, stack, "show")? {
54            Ok(value.into_pipeline_data())
55        } else {
56            Ok(Value::nothing(call.head).into_pipeline_data())
57        }
58    }
59
60    fn examples(&self) -> Vec<Example<'_>> {
61        vec![
62            Example {
63                example: "'hello' | clip copy",
64                description: "Copy a string to the clipboard.",
65                result: None,
66            },
67            Example {
68                example: "$env | clip copy --show",
69                description: "Copy a structured value and pass it through.",
70                result: None,
71            },
72            Example {
73                example: "ls | clip copy",
74                description: "Copy structured values as plain table text without ANSI escape sequences.",
75                result: None,
76            },
77        ]
78    }
79}