获取索引处字符的 ANSI 颜色

Get ANSI color for character at index

本文关键字:ANSI 颜色 字符 索引 获取      更新时间:2023-09-26

我开发了couleurs NPM包,可以设置为将rgb方法附加到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'

这工作正常。在索引i获取字符的ANSI颜色/样式的正确方法是什么?

可能这可以用一些正则表达式破解,但我不确定这是否真的很好(但是,如果有正确的实现,我不反对它)......我更喜欢一种原生的方式来通过访问 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"
}

当我们有多个组合样式时,事情会变得复杂:

> 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'

就像我说的,我正在寻找一种本机方式(也许使用子进程)。

那么,如何在索引i获得字符的完整ANSI样式呢?

有几种方法可以为文本"添加"格式,这是其中之一。问题是您将文本和样式混合到同一个对象中 - 文本字符串。它类似于RTF

Here is some 'b bold'b0 and {'i italic} text'par

但与 Word .DOC 文件的本机格式不同,后者适用于文本运行

(text) Here is some bold and italic text'r
(chp)  13 None
       4  sprmCFBold
       5  None
       6  sprmCFItalic
       6  None

-- 左边的数字是具有特定格式的字符数。

后一种格式是您正在寻找的,因为您希望为纯文本中的字符编制索引。减去格式长度将显示您对哪一个感兴趣。根据您希望请求格式设置的次数,您可以只执行一次性运行,也可以将格式化文本缓存在某处。

一次性运行需要检查编码字符串的每个元素,当不在颜色字符串内时,递增"文本"索引,如果是,则更新"上次看到"的颜色字符串。我添加了一个兼容的getCharAt函数用于调试目的。

var str = ''u001b[38;5;196m'u001b[1mBo'x1B[22mld & Red'u001b[22m but this one is only red'u001b[0m';
const map = {
    bold: ["'x1B[1m", "'x1B[22m" ]
  , italic: ["'x1B[3m", "'x1B[23m" ]
  , underline: ["'x1B[4m", "'x1B[24m" ]
  , inverse: ["'x1B[7m", "'x1B[27m" ]
  , strikethrough: ["'x1B[9m", "'x1B[29m" ]
};
String.prototype.getColorAt = function(index)
{
    var strindex=0, color=[], cmatch, i,j;
    while (strindex < this.length)
    {
        cmatch = this.substr(strindex).match(/^('u001B'[[^m]*m)/);
        if (cmatch)
        {
            // Global reset?
            if (cmatch[0] == ''x1B[0m')
            {
                color = [];
            } else
            {
                // Off code?
                for (i=0; i<map.length; i++)
                {
                    if (map[i][1] == cmatch[0])
                    {
                        // Remove On code?
                        for (j=color.length-1; j>=0; j--)
                        {
                            if (color[j] == map[i][0])
                                color.splice (j,1);
                        }
                        break;
                    }
                }
                if (j==map.length)
                    color.push (cmatch[0]);
            }
            strindex += cmatch[0].length;
        } else
        {
            /* a regular character! */
            if (!index)
                break;
            strindex++;
            index--;
        }
    }
    return color.join('');
}
String.prototype.getCharAt = function(index)
{
    var strindex=0, cmatch;
    while (strindex < this.length)
    {
        cmatch = this.substr(strindex).match(/^('u001B'[[^m]*m)/);
        if (cmatch)
        {
            strindex += cmatch[0].length;
        } else
        {
            /* a regular character! */
            if (!index)
                return this.substr(strindex,1);
            strindex++;
            index--;
        }
    }
    return '';
}
console.log (str);
color = str.getColorAt (1);
text = str.getCharAt (1);
console.log ('color is '+color+color.length+', char is '+text);

返回的color仍采用其原始转义编码。您可以通过将这些添加到原始map数组中来使其返回某种常量。

我无法为您提供完整的解决方案,但这里有一个草图:

  • 维护一个累积当前格式的堆栈
  • 将字符串拆分为块espace sequence | just a character
  • 遍历此块列表
  • 如果只是一个 char,请保存其索引 + 堆栈的当前状态
  • 如果是转义,请将相应的格式推送到堆栈上,或者从中弹出格式

还可以使用此算法将转义字符串转换为 html,并使用 XML 方法遍历结果树。

顺便说一句,后者反过来也会很好,这个怎么样:

console.log("<font color='red'>hi <b>there</b></font>".toANSI())