a/
util.rs

1use bat::PrettyPrinter;
2use bat::Syntax;
3use copypasta_ext::prelude::*;
4use copypasta_ext::x11_fork::ClipboardContext;
5use std::error::Error;
6
7fn lang_exists(lang: &str, langs: &Vec<Syntax>) -> bool {
8    for l in langs {
9        if l.name.to_lowercase() == lang.to_lowercase() {
10            return true;
11        }
12        for e in &l.file_extensions {
13            if e == &lang.to_lowercase() {
14                return true;
15            }
16        }
17    }
18    false
19}
20
21pub fn pretty_print(str: &str, lang: &str) {
22    let mut lang = lang.to_owned();
23    let mut pp = PrettyPrinter::new();
24
25    let langs: Vec<_> = pp.syntaxes().collect();
26    if !lang_exists(&lang, &langs) {
27        lang = "txt".to_owned();
28    }
29
30    pp.input_from_bytes(str.as_bytes())
31        .language(&lang)
32        .print()
33        .unwrap();
34}
35
36pub fn copy_to_clipboard(str: &str) -> Result<(), Box<dyn Error>> {
37    let mut ctx = match ClipboardContext::new() {
38        Ok(c) => c,
39        Err(e) => {
40            return Err(format!(
41                "Cannot initialize clipboard context: {e}\nConsider recompiling with the \"clipboard\" feature disabled\n"
42            ).into())
43        }
44    };
45
46    match ctx.set_contents(str.to_owned()) {
47        Ok(_) => Ok(()),
48        Err(e) => Err(format!(
49            "Cannot initialize clipboard context: {e}\nConsider recompiling with the \"clipboard\" feature disabled\n"
50        ).into()),
51    }
52}