ANSI to RGBa color conversion crate

I'm looking for crate that provides reverse conversion to RGBa format from ANSI string.

To grab some vector, where color tag wrapped into const with text object appended. Found these crates, but seems there is RGBa -> ANSI conversion, not reverse API. Also found IsTerminal available since Rust 1.70, maybe something already exist from the box for these needs.

That entirely depends on the terminal emulator and its settings.

2 Likes

In fact, I want to wrap vector item collected into GTK TextTag, then render it manually as part of TextView widget using foreground-rgba property.

HEX format is not problem here also, just prefer RGBa if available.

UPD. forgot to append parser keyword in search, so found at least cansi - seems that I want,
just last update about 2 years ago.

I'm afraid I don't have a specific crate to recommend. The rest of the comment is just elaborating on @jendrikw's warning that any conversion comes with caveats to be aware of.

TL;DR: The conversion can be made on a best-effort basis, but will probably be inexact and/or have to support a lot of configuration for customization.


The Wikipedia article is a pretty good summary of the three main ways of coloring terminal text (4, 8, or 24 bit).

The 4 bit codes are the most widely supported, what people usually mean when they say "ANSI color", and also the most problematic to "reverse":

  • The corresponding RGB is variable across terminals and usually configurable to boot
  • The 4 bits may actually be 3 bits + bold

16 colors of the 8 bit codes correspond in a general sense to the 4 bit codes, and thus present similar problems. Customizing the 4 bit codes may or may not customize the 16 colors in the 8 bit mode, depending on the terminal software.

24bit RGB would be the easiest to convert, for obvious reasons, but is also less widely supported and correspondingly more rare.

Then you also have to contend with things like inverted mode and background colors (no matter the number of bits). Some terminals also treat italic as inverted, or allow configuring such. Same with blink and probably other modifiers.

3 Likes

Thanks for explained reply!

I'm working on browser (client) for Gemini protocol, where this feature not officially specified but optionally used to highlight colors in preformatted blocks. Just asked community and got response I should take a look at SGR specification instead.

So by this query, found following crates that correspond for my goals.

1 Like