sharkdp / bat

A cat(1) clone with wings.
Apache License 2.0
49.87k stars 1.26k forks source link

Add From impls for PrettyPrinter #3069

Open NickLarsenNZ opened 3 months ago

NickLarsenNZ commented 3 months ago

I'm trying to print syntax highlighted code inside a comfy-table cell. So instead of .print() I would like to be able to use .into() to get a String (ultimately I need a &str, but I can use as_str()).

let x: String = PrettyPrinter::new()
    .input_from_bytes(input)
    .language(language)
    .into();

Would you be open to allowing some additional impls, or at least a impl From<String> for PrettyPrinter?

I would be happy to contribute.

kojix2 commented 3 months ago

I created a pull request (#3070) because I wanted to get a string. I'm new to Rust, so I'm not sure about the best practices for API design. At first, I tried to add std::fmt::Write as an argument to the print() function with a default value, but I learned that Rust doesn't support default arguments. So, I added a new function called print_with_writer, although ChatGPT suggested print_to might be a better name. I noticed in your code that there's a method called into().

If your approach fits Rust's conventions better than my pull request, I would be grateful if you could suggest an API and submit a pull request.

Thank you!

kojix2 commented 1 week ago

Finally, #3070 has been merged, and the following code now works.

use bat::PrettyPrinter;

fn main() {
    let mut output_str = String::new();

        PrettyPrinter::new()
        .input_from_bytes(b"<span style=\"color: #ff00cc\">Hello world!</span>\n")
        .language("html")
        .print_with_writer(Some(&mut output_str))
        .unwrap();

    println!("{}", output_str);
}

image