Mathias Nyman | d7bd2db | 2015-04-28 13:18:21 +0300 | [diff] [blame] | 1 | #include <stdio.h> |
| 2 | #include <stdarg.h> |
| 3 | |
| 4 | #include "color.h" |
| 5 | |
| 6 | enum color { |
| 7 | C_RED, |
| 8 | C_GREEN, |
| 9 | C_YELLOW, |
| 10 | C_BLUE, |
| 11 | C_MAGENTA, |
| 12 | C_CYAN, |
| 13 | C_WHITE, |
| 14 | C_CLEAR |
| 15 | }; |
| 16 | |
| 17 | static const char * const color_codes[] = { |
| 18 | "\e[31m", |
| 19 | "\e[32m", |
| 20 | "\e[33m", |
| 21 | "\e[34m", |
| 22 | "\e[35m", |
| 23 | "\e[36m", |
| 24 | "\e[37m", |
| 25 | "\e[0m", |
| 26 | NULL, |
| 27 | }; |
| 28 | |
| 29 | static enum color attr_colors[] = { |
| 30 | C_CYAN, |
| 31 | C_YELLOW, |
| 32 | C_MAGENTA, |
| 33 | C_BLUE, |
| 34 | C_GREEN, |
| 35 | C_RED |
| 36 | }; |
| 37 | |
| 38 | static int color_is_enabled; |
| 39 | |
| 40 | void enable_color(void) |
| 41 | { |
| 42 | color_is_enabled = 1; |
| 43 | } |
| 44 | |
| 45 | int color_fprintf(FILE *fp, enum color_attr attr, const char *fmt, ...) |
| 46 | { |
| 47 | int ret = 0; |
| 48 | va_list args; |
| 49 | |
| 50 | va_start(args, fmt); |
| 51 | |
| 52 | if (!color_is_enabled) { |
| 53 | ret = vfprintf(fp, fmt, args); |
| 54 | goto end; |
| 55 | } |
| 56 | |
| 57 | ret += fprintf(fp, "%s", color_codes[attr_colors[attr]]); |
| 58 | ret += vfprintf(fp, fmt, args); |
| 59 | ret += fprintf(fp, "%s", color_codes[C_CLEAR]); |
| 60 | |
| 61 | end: |
| 62 | va_end(args); |
| 63 | return ret; |
| 64 | } |