prettytable-rs icon indicating copy to clipboard operation
prettytable-rs copied to clipboard

output of a table to a string with styles -- is it possible?

Open faried opened this issue 2 years ago • 5 comments

I have a Vec<String> that represents my output lines. I want to append a table to it but I can't seem to do that and preserve cell styles. I've tried


let mut output = Vec::<String>::new();

let mut table = Table::new();
table.add_row(row![Fg => "first", "second"]);

output.push(table.to_string());
// also tried
output.push(format!("{}", table));

I'm new to Rust, so I don't know if there's a way to do this (prettytable-rs 0.8.0).

faried avatar Jun 06 '22 19:06 faried

@faried Did you find the solution to preserve the style?

I just use print in my project, but it doesn't preserve the style.

table.print(&mut output).unwrap()

Saruniks avatar Nov 07 '22 12:11 Saruniks

No, I didn't find a solution. The package's internals need to be modified to support this.

faried avatar Nov 07 '22 12:11 faried

Feel free to send a PR, p.s. it's now 0.10

pinkforest avatar Dec 27 '22 11:12 pinkforest

I was going to experiment with using the print_term to help with this by capturing the terminal output. However, I couldn't get the print_term to work

    let mut my_term = term::stdout().unwrap();
    let _ = table.print_term(&mut my_term);

This throws an error for

^ the trait `Terminal` is not implemented for `Box<dyn Terminal<Output = Stdout> + Send>`

Not 100% sure how to capture the input back from the Terminal either, but getting this to work seems like the first step

krpatter-intc avatar Dec 23 '23 17:12 krpatter-intc

This seems to work for capturing the output in to a string:

    let temp_cursor = Cursor::new(Vec::new());
    let temp_term = term::terminfo::TerminfoTerminal::new(temp_cursor);
    let mut temp_term = temp_term.unwrap();
    let _ = table.print_term(&mut temp_term);
    // now get cursor, then get vector
    let vector = temp_term.get_mut().get_ref();
    let mystr = str::from_utf8(&vector).unwrap();
    println!("{}", mystr);
    println!("----");

krpatter-intc avatar Dec 23 '23 18:12 krpatter-intc