我知道我可以做的attron,并attroff与我选择的颜色,但是,我想知道是否有可能与ncurses的内ANSI颜色转义符来做到这一点:
#include <stdio.h>
#include <ncurses.h>
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;
}
Run Code Online (Sandbox Code Playgroud)
与...联系 -lncurses
printf("\033[22;31mHello, World!\n");在非ncurses计划中定期工作.
我认为你可能误入了危险的领域。Curses 几乎肯定会根据输出字符跟踪字符位置,并且由于它提供自己的颜色处理,因此它可能也不会检测 ANSI 转义序列。
如果您正在寻求一种允许字符串中使用 ANSI 转义序列的可能方法,那么一种方法(尽管是拼凑)就是截取字符串并修改它。有一个辅助函数myPrintW(),它接受一个字符串并将其分解,类似于(伪代码):
def myPrintW(s as copy):
while s not empty:
p = position of first ansi-sequence in s
if p == NULL exit while
printw first p characters of s
remove the first p characters from s
decode ansi-sequence at start of s
issue relevant attron/off for that ansi-sequence
remove ansi-sequence from start of s
endwhile
output s though it may be empty
enddef
Run Code Online (Sandbox Code Playgroud)
这基本上会将字符串分解为正常的字符序列和反序列化序列,并且您将单独处理每个序列。
它需要一个查找表(如果您需要处理具有任意参数的 ANSI 序列,则需要一个查找表)才能将序列转换为所需的attron/off调用。