C和ncurses中的ANSI颜色

我知道我可以使用我选择的颜色来进行attronattroff ,但是,我想知道是否可以使用ncurses中的ANSI颜色转义码来实现它:

 #include  #include  int main() { initscr(); char *s2 = NULL; const char *s1 = "World"; int n = 10; // What would be a good way to colour %d? // seems it is not safe to us the ANSI color escape in here... s2 = malloc (snprintf (NULL, 0, "Hello %s \033[22;31m%d", s1, n) + 2); sprintf (s2, "Hello %s \033[22;31m%d", s1, n); printw("%s", s2); refresh(); getch(); endwin(); return 0; } 

-lncurses链接

一个普通的printf("\033[22;31mHello, World!\n"); 在非ncurses程序中工作。

是。 这完全取决于正在监听程序输出的软件或固件类型。 对于V3.3 MSDOS,不,除非加载设备驱动程序ansi.sys,否则它将无法工作。

现代终端窗口往往具有ANSI x3.64语义,因此这些转义序列通常会起作用。 但是不要期望太多:众所周知,额外广泛和超高的角色支持得很差。

我想你可能正在那里陷入危险的境地。 Curses几乎肯定会根据输出字符跟踪字符位置,因为它提供了自己的颜色处理,所以它可能也不会检测ANSI转义序列。

可能有用(你试过吗?)但它也可能完全填满窗口管理。


并且,既然你在评论中说它不起作用那么我猜答案是“不”:-)

如果您正在寻找允许字符串中的ANSI转义序列的可能方法,那么一种方法(尽管它是kludge)将截取字符串并对其进行修改。 有一个像myPrintW()这样的辅助函数,它接受一个字符串并将其分解,类似于(伪代码):

 def myPrintW(s): while s not end of string: s2 = position of color-change-sequence in s if s2 == NULL exit while printw characters from s (inclusive) to s2 (exclusive) decode color-change-sequence at s2 and issue relevant attron/off s = s2 + length of color-change-sequence endwhile enddef 

这基本上会将字符串分解为正常的字符序列和颜色变化序列,并且您将分别处理每个字符串。 它需要一个查找表才能将序列转换成所需的attron/off调用。 不漂亮,但有时候实用主义是最好的。

ncurses上集成ANSI不会太安全。 您想使用attron/off调用,也可能将字符串拆分为%s%d 。 对于> 2次转换,您需要实现自己的printw

2008邮件列表主题讨论这个: https : //lists.gnu.org/archive/html/bug-ncurses/2008-11/msg00026.html

提出的可能性是:

  • 为ANSI转义码创建解析器(源代码中为WONTFIX)。 Mutt和Screen实现了这个: https : //lists.gnu.org/archive/html/bug-ncurses/2008-11/msg00028.html

  • 创建一个terminfo条目: https : //lists.gnu.org/archive/html/bug-ncurses/2008-11/msg00029.html