I have developed couleurs
NPM package which can be set to append rgb
method to String.prototype
:
> console.log("Hello World!".rgb(255, 0, 0)) // "Hello World!" in red
Hello World!
undefined
> "Hello World!".rgb(255, 0, 0)
'\u001b[38;5;196mHello World!\u001b[0m'
This works fine. What's the proper way to get the ANSI color/style of character at index i
?
Probably this can be hacked with some regular expressions, but I'm not sure if that's really good (however, if a correct implementation is available I'm not against it)... I'd prefer a native way to get the color/style by accessing the character interpreted by tty.
> function getStyle (input, i) { /* get style at index `i` */ return style; }
> getStyle("Hello World!".rgb(255, 0, 0), 0); // Get style of the first char
{
start: "\u001b[38;5;196m",
end: "\u001b[0m",
char: "H"
}
> getStyle("Hello " + "World!".rgb(255, 0, 0), 0); // Get style of the first char
{
start: "",
end: "",
char: "H"
}
Things get complicated when we have multiple combined styles:
> console.log("Green and Italic".rgb(0, 255, 0).italic())
Green and Italic
undefined
> getStyle("Green and Italic".rgb(0, 255, 0).italic(), 0);
{
start: "\u001b[3m\u001b[38;5;46m",
end: "\u001b[0m\u001b[23m",
char: "G"
}
> getStyle(("Bold & Red".bold() + " but this one is only red").rgb(255, 0, 0), 0);
{
start: "\u001b[38;5;196m\u001b[1m",
end: "\u001b[22m\u001b[0m",
char: "B"
}
> getStyle(("Bold & Red".bold() + " but this one is only red").rgb(255, 0, 0), 11);
{
start: "\u001b[38;5;196m",
end: "\u001b[0m",
char: "u"
}
> ("Bold & Red".bold() + " but this one is only red").rgb(255, 0, 0)
'\u001b[38;5;196m\u001b[1mBold & Red\u001b[22m but this one is only red\u001b[0m'
Like I said, I'm looking for a native way (maybe using a child process).
So, how to get the complete ANSI style for character at index i
?
There are a couple of ways to 'add' formatting to text, and this is one of them. The problem is you are mixing text and styling into the same object -- a text string. It's similar to RTF
but different from, say, the native format of Word .DOC files, which works with text runs:
-- the number at the left is the count of characters with a certain formatting.
The latter format is what you are looking for, since you want to index characters in the plain text. Subtracting the formatting lengths will show which one you are interested in. Depending on how many times you expect to ask for a formatting, you can do one-time runs only, or cache the formatted text somewhere.
A one-time run needs to inspect each element of the encoded string, incrementing the "text" index when not inside a color string, and updating the 'last seen' color string if it is. I added a compatible
getCharAt
function for debugging purposes.The returned
color
is still in its original escaped encoding. You can make it return a constant of some kind by adding these into your originalmap
array.