I started to write a terminal text editor, something like the first text editors for UNIX, such as vi. My only goal is to have a good time, but I want to be able to show text in color, so I can have syntax highlighting for editing source code.
How can I achieve this? Is there some special POSIX API for this, or do I have to 开发者_JAVA技巧use ncurses? (I'd rather not)
Any advice? Maybe some textbooks on the UNIX API?
This is a little C program that illustrates how you could use color codes:
#include <stdio.h>
#define KNRM "\x1B[0m"
#define KRED "\x1B[31m"
#define KGRN "\x1B[32m"
#define KYEL "\x1B[33m"
#define KBLU "\x1B[34m"
#define KMAG "\x1B[35m"
#define KCYN "\x1B[36m"
#define KWHT "\x1B[37m"
int main()
{
printf("%sred\n", KRED);
printf("%sgreen\n", KGRN);
printf("%syellow\n", KYEL);
printf("%sblue\n", KBLU);
printf("%smagenta\n", KMAG);
printf("%scyan\n", KCYN);
printf("%swhite\n", KWHT);
printf("%snormal\n", KNRM);
return 0;
}
Different solution that I find more elegant
Here's another way to do it. Some people will prefer this as the code is a bit cleaner. There are no %s
and a RESET
color to end the coloration.
#include <stdio.h>
#define RED "\x1B[31m"
#define GRN "\x1B[32m"
#define YEL "\x1B[33m"
#define BLU "\x1B[34m"
#define MAG "\x1B[35m"
#define CYN "\x1B[36m"
#define WHT "\x1B[37m"
#define RESET "\x1B[0m"
int main() {
printf(RED "red\n" RESET);
printf(GRN "green\n" RESET);
printf(YEL "yellow\n" RESET);
printf(BLU "blue\n" RESET);
printf(MAG "magenta\n" RESET);
printf(CYN "cyan\n" RESET);
printf(WHT "white\n" RESET);
return 0;
}
This program gives the following output:
Simple example with multiple colors
This way, it's easy to do something like:
printf("This is " RED "red" RESET " and this is " BLU "blue" RESET "\n");
This line produces the following output:
You probably want ANSI color codes. Most *nix terminals support them.
Use ANSI escape sequences. This article goes into some detail about them. You can use them with printf
as well.
精彩评论