1 /** \file color.c Functions for printing colored messages. */
4 * Mostly taken from the git source tree, version 1.6.1.76, January 2009.
10 static int parse_color(const char *name
, int len
)
12 static const char * const color_names
[] = {
13 "normal", "black", "red", "green", "yellow",
14 "blue", "magenta", "cyan", "white"
18 for (i
= 0; i
< ARRAY_SIZE(color_names
); i
++) {
19 const char *str
= color_names
[i
];
20 if (!strncasecmp(name
, str
, len
) && !str
[len
])
23 i
= strtol(name
, &end
, 10);
24 if (end
- name
== len
&& i
>= -1 && i
<= 255)
29 static int parse_attr(const char *name
, int len
)
31 static const int attr_values
[] = { 1, 2, 4, 5, 7 };
32 static const char * const attr_names
[] = {
33 "bold", "dim", "ul", "blink", "reverse"
36 for (i
= 0; i
< ARRAY_SIZE(attr_names
); i
++) {
37 const char *str
= attr_names
[i
];
38 if (!strncasecmp(name
, str
, len
) && !str
[len
])
39 return attr_values
[i
];
45 * Create an escape sequence for colored output.
47 * \param value Human-readable color spec.
48 * \param dst Result pointer for the escape sequence.
50 * \return -1 on errors, 1 on success.
52 * Format of \a value: [fg [bg]] [attr].
54 int color_parse(const char *value
, char *dst
)
56 const char *ptr
= value
;
61 if (!strcasecmp(value
, "reset")) {
62 strcpy(dst
, COLOR_RESET
);
66 /* [fg [bg]] [attr] */
68 const char *word
= ptr
;
71 while (word
[len
] && !para_isspace(word
[len
]))
75 while (*ptr
&& para_isspace(*ptr
))
78 val
= parse_color(word
, len
);
90 val
= parse_attr(word
, len
);
91 if (val
< 0 || attr
!= -1)
96 if (attr
>= 0 || fg
>= 0 || bg
>= 0) {
112 dst
+= sprintf(dst
, "38;5;%d", fg
);
122 dst
+= sprintf(dst
, "48;5;%d", bg
);
130 PARA_ERROR_LOG("bad color value '%s'\n", value
);