I want to add colors to the stack trace I am working on and also the previous error messages. But I am creating a separate mr for it.
You can use this header file to print colored output to the terminal.
If the -cti-no-color flag is set these macros just return the input string without color.
You can not only change the stoke color and background color of the text but also text style like bold or italic, the font, and even make the text blink.
To always enable colors somewhere you can also add #define CTI_NO_COLOR 0
before your #include "color.h"
.
In the ANSI terminal color standard colors work by printing a certain special character sequence that indicates to the terminal that the colors should change.
An ANSI color code is generally structured as follows:
ESC [ <parameters> m
- ESC is the escape character, ASCII code 27 (hex 0x1B), written in strings as \033 or \x1B.
- [ is the Control Sequence Introducer (CSI).
- is a semicolon-separated list of numbers.
- m is the final byte indicating that this is a SGR (Select Graphic Rendition) command.
Exampe: \033[31mHello\033[0m will print the word Hello in red. 31 is the parameter for red and 0 is the reset all parameter.
Using this header file you can write the above as RED("Hello")
which will be turned into "\033[31m""Hello""\033[0m"
.
All macros in this file prepend your string with a color code and append a reset color code. But importantly only if global.cti_no_color is true!
If global.cti_no_color is false, RED("Hello") is just turned into just "Hello". This is because actually RED("Hello") is turned into:
(global.cti_no_color ? "Hello": "\033[31m""Hello""\033[0m")
Here is an example to print a the Dutch flag:
printf("%s\n%s\n%s\n", RED("#####"), WHITE("#####"), BLUE("#####"));
Here is an example to print a blinking Dutch flag:
printf("%s\n%s\n%s\n", RED_BLINK("#####"),WHITE_BLINK("#####"),BLUE_BLINK("#####"));
Here is an example to print a rainbow.
printf("%s%s%s%s%s%s%s", RED("R"),YELLOW("A"),GREEN("I"),AQUA("N"),BLUE("B"),PURPLE("O"),CYAN("W"));