Advice on how to create colored strings from a vector of elements containing characters and their colors?

Hello everyone :wave:

currently I have a Vec of structs that look like this :

#[derive(Copy, Clone)]
pub struct CharacterCell {
    pub ch: char,
    pub fg: u8,
    pub bg: u8,
    pub attrs: Attr,
}

And I would like to transform it into a string that when printed, would be rendered in colors. Any advice ?

You may want to check out the termcolor crate. It's designed to work on both Windows and *nix, which adding ANSI escape codes to your string wouldn't do.

From there it's just a case of iterating over the items and setting the foreground/background colour based on whatever that u8 means before printing the character.

Yeah but I need the color info to be directly encoded in the string, so it can later be reused (and some other technical reasons). Can termcolor do that as well ?

You could just surround the string with the appropriate control codes.

The Colored crate seems to do it.
I have no idea what it's doing but seems the formatted output actually goes into a 'String', and printing it retains the color

use colored::*;

fn main() {
    let my_string: String = format!("{}", "hellow world".red());
    println!("{}", my_string);
}

I looked at that crate, and apparently you can only color entire strings, not individual chars

No, and that's by design. Because supporting the old Windows console APIs is incompatible with control codes embedded in the string.

If you don't care about supporting users who can only get color in their terminals via the Windows console APIs (older versions of Windows 10 IIRC along with anything older than Windows 10), then there are a number of crates in the ecosystem that only use ANSI escape sequences for color to choose from.

I think I'll roll with my own algorithm to add escape codes

And my program already doesnt support windows, as it uses the nix crate

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.