Start the 2.48 cycle
[git/gitster.git] / color.c
blob227a5ab2f42ef99e578c837f59b2b40986a3c9e3
1 #include "git-compat-util.h"
2 #include "config.h"
3 #include "color.h"
4 #include "editor.h"
5 #include "gettext.h"
6 #include "hex-ll.h"
7 #include "pager.h"
8 #include "strbuf.h"
10 static int git_use_color_default = GIT_COLOR_AUTO;
11 int color_stdout_is_tty = -1;
14 * The list of available column colors.
16 const char *column_colors_ansi[] = {
17 GIT_COLOR_RED,
18 GIT_COLOR_GREEN,
19 GIT_COLOR_YELLOW,
20 GIT_COLOR_BLUE,
21 GIT_COLOR_MAGENTA,
22 GIT_COLOR_CYAN,
23 GIT_COLOR_BOLD_RED,
24 GIT_COLOR_BOLD_GREEN,
25 GIT_COLOR_BOLD_YELLOW,
26 GIT_COLOR_BOLD_BLUE,
27 GIT_COLOR_BOLD_MAGENTA,
28 GIT_COLOR_BOLD_CYAN,
29 GIT_COLOR_RESET,
32 enum {
33 COLOR_BACKGROUND_OFFSET = 10,
34 COLOR_FOREGROUND_ANSI = 30,
35 COLOR_FOREGROUND_RGB = 38,
36 COLOR_FOREGROUND_256 = 38,
37 COLOR_FOREGROUND_BRIGHT_ANSI = 90,
40 /* Ignore the RESET at the end when giving the size */
41 const int column_colors_ansi_max = ARRAY_SIZE(column_colors_ansi) - 1;
43 /* An individual foreground or background color. */
44 struct color {
45 enum {
46 COLOR_UNSPECIFIED = 0,
47 COLOR_NORMAL,
48 COLOR_ANSI, /* basic 0-7 ANSI colors + "default" (value = 9) */
49 COLOR_256,
50 COLOR_RGB
51 } type;
52 /* The numeric value for ANSI and 256-color modes */
53 unsigned char value;
54 /* 24-bit RGB color values */
55 unsigned char red, green, blue;
59 * "word" is a buffer of length "len"; does it match the NUL-terminated
60 * "match" exactly?
62 static int match_word(const char *word, int len, const char *match)
64 return !strncasecmp(word, match, len) && !match[len];
67 static int get_hex_color(const char **inp, int width, unsigned char *out)
69 const char *in = *inp;
70 unsigned int val;
72 assert(width == 1 || width == 2);
73 val = (hexval(in[0]) << 4) | hexval(in[width - 1]);
74 if (val & ~0xff)
75 return -1;
76 *inp += width;
77 *out = val;
78 return 0;
82 * If an ANSI color is recognized in "name", fill "out" and return 0.
83 * Otherwise, leave out unchanged and return -1.
85 static int parse_ansi_color(struct color *out, const char *name, int len)
87 /* Positions in array must match ANSI color codes */
88 static const char * const color_names[] = {
89 "black", "red", "green", "yellow",
90 "blue", "magenta", "cyan", "white"
92 int i;
93 int color_offset = COLOR_FOREGROUND_ANSI;
95 if (match_word(name, len, "default")) {
97 * Restores to the terminal's default color, which may not be
98 * the same as explicitly setting "white" or "black".
100 * ECMA-48 - Control Functions \
101 * for Coded Character Sets, 5th edition (June 1991):
102 * > 39 default display colour (implementation-defined)
103 * > 49 default background colour (implementation-defined)
105 * Although not supported /everywhere/--according to terminfo,
106 * some terminals define "op" (original pair) as a blunt
107 * "set to white on black", or even "send full SGR reset"--
108 * it's standard and well-supported enough that if a user
109 * asks for it in their config this will do the right thing.
111 out->type = COLOR_ANSI;
112 out->value = 9 + color_offset;
113 return 0;
116 if (strncasecmp(name, "bright", 6) == 0) {
117 color_offset = COLOR_FOREGROUND_BRIGHT_ANSI;
118 name += 6;
119 len -= 6;
121 for (i = 0; i < ARRAY_SIZE(color_names); i++) {
122 if (match_word(name, len, color_names[i])) {
123 out->type = COLOR_ANSI;
124 out->value = i + color_offset;
125 return 0;
128 return -1;
131 static int parse_color(struct color *out, const char *name, int len)
133 char *end;
134 long val;
136 /* First try the special word "normal"... */
137 if (match_word(name, len, "normal")) {
138 out->type = COLOR_NORMAL;
139 return 0;
142 /* Try a 24- or 12-bit RGB value prefixed with '#' */
143 if ((len == 7 || len == 4) && name[0] == '#') {
144 int width_per_color = (len == 7) ? 2 : 1;
145 const char *color = name + 1;
147 if (!get_hex_color(&color, width_per_color, &out->red) &&
148 !get_hex_color(&color, width_per_color, &out->green) &&
149 !get_hex_color(&color, width_per_color, &out->blue)) {
150 out->type = COLOR_RGB;
151 return 0;
155 /* Then pick from our human-readable color names... */
156 if (parse_ansi_color(out, name, len) == 0) {
157 return 0;
160 /* And finally try a literal 256-color-mode number */
161 val = strtol(name, &end, 10);
162 if (end - name == len) {
164 * Allow "-1" as an alias for "normal", but other negative
165 * numbers are bogus.
167 if (val < -1)
168 ; /* fall through to error */
169 else if (val < 0) {
170 out->type = COLOR_NORMAL;
171 return 0;
172 /* Rewrite 0-7 as more-portable standard colors. */
173 } else if (val < 8) {
174 out->type = COLOR_ANSI;
175 out->value = val + COLOR_FOREGROUND_ANSI;
176 return 0;
177 /* Rewrite 8-15 as more-portable aixterm colors. */
178 } else if (val < 16) {
179 out->type = COLOR_ANSI;
180 out->value = val - 8 + COLOR_FOREGROUND_BRIGHT_ANSI;
181 return 0;
182 } else if (val < 256) {
183 out->type = COLOR_256;
184 out->value = val;
185 return 0;
189 return -1;
192 static int parse_attr(const char *name, size_t len)
194 static const struct {
195 const char *name;
196 size_t len;
197 int val, neg;
198 } attrs[] = {
199 #define ATTR(x, val, neg) { (x), sizeof(x)-1, (val), (neg) }
200 ATTR("bold", 1, 22),
201 ATTR("dim", 2, 22),
202 ATTR("italic", 3, 23),
203 ATTR("ul", 4, 24),
204 ATTR("blink", 5, 25),
205 ATTR("reverse", 7, 27),
206 ATTR("strike", 9, 29)
207 #undef ATTR
209 int negate = 0;
210 int i;
212 if (skip_prefix_mem(name, len, "no", &name, &len)) {
213 skip_prefix_mem(name, len, "-", &name, &len);
214 negate = 1;
217 for (i = 0; i < ARRAY_SIZE(attrs); i++) {
218 if (attrs[i].len == len && !memcmp(attrs[i].name, name, len))
219 return negate ? attrs[i].neg : attrs[i].val;
221 return -1;
224 int color_parse(const char *value, char *dst)
226 return color_parse_mem(value, strlen(value), dst);
230 * Write the ANSI color codes for "c" to "out"; the string should
231 * already have the ANSI escape code in it. "out" should have enough
232 * space in it to fit any color.
234 static char *color_output(char *out, int len, const struct color *c, int background)
236 int offset = 0;
238 if (background)
239 offset = COLOR_BACKGROUND_OFFSET;
240 switch (c->type) {
241 case COLOR_UNSPECIFIED:
242 case COLOR_NORMAL:
243 break;
244 case COLOR_ANSI:
245 out += xsnprintf(out, len, "%d", c->value + offset);
246 break;
247 case COLOR_256:
248 out += xsnprintf(out, len, "%d;5;%d", COLOR_FOREGROUND_256 + offset,
249 c->value);
250 break;
251 case COLOR_RGB:
252 out += xsnprintf(out, len, "%d;2;%d;%d;%d",
253 COLOR_FOREGROUND_RGB + offset,
254 c->red, c->green, c->blue);
255 break;
257 return out;
260 static int color_empty(const struct color *c)
262 return c->type <= COLOR_NORMAL;
265 int color_parse_mem(const char *value, int value_len, char *dst)
267 const char *ptr = value;
268 int len = value_len;
269 char *end = dst + COLOR_MAXLEN;
270 unsigned int has_reset = 0;
271 unsigned int attr = 0;
272 struct color fg = { COLOR_UNSPECIFIED };
273 struct color bg = { COLOR_UNSPECIFIED };
275 while (len > 0 && isspace(*ptr)) {
276 ptr++;
277 len--;
280 if (!len) {
281 dst[0] = '\0';
282 return 0;
285 /* [reset] [fg [bg]] [attr]... */
286 while (len > 0) {
287 const char *word = ptr;
288 struct color c = { COLOR_UNSPECIFIED };
289 int val, wordlen = 0;
291 while (len > 0 && !isspace(word[wordlen])) {
292 wordlen++;
293 len--;
296 ptr = word + wordlen;
297 while (len > 0 && isspace(*ptr)) {
298 ptr++;
299 len--;
302 if (match_word(word, wordlen, "reset")) {
303 has_reset = 1;
304 continue;
307 if (!parse_color(&c, word, wordlen)) {
308 if (fg.type == COLOR_UNSPECIFIED) {
309 fg = c;
310 continue;
312 if (bg.type == COLOR_UNSPECIFIED) {
313 bg = c;
314 continue;
316 goto bad;
318 val = parse_attr(word, wordlen);
319 if (0 <= val)
320 attr |= (1 << val);
321 else
322 goto bad;
325 #undef OUT
326 #define OUT(x) do { \
327 if (dst == end) \
328 BUG("color parsing ran out of space"); \
329 *dst++ = (x); \
330 } while(0)
332 if (has_reset || attr || !color_empty(&fg) || !color_empty(&bg)) {
333 int sep = 0;
334 int i;
336 OUT('\033');
337 OUT('[');
339 if (has_reset)
340 sep++;
342 for (i = 0; attr; i++) {
343 unsigned bit = (1 << i);
344 if (!(attr & bit))
345 continue;
346 attr &= ~bit;
347 if (sep++)
348 OUT(';');
349 dst += xsnprintf(dst, end - dst, "%d", i);
351 if (!color_empty(&fg)) {
352 if (sep++)
353 OUT(';');
354 dst = color_output(dst, end - dst, &fg, 0);
356 if (!color_empty(&bg)) {
357 if (sep++)
358 OUT(';');
359 dst = color_output(dst, end - dst, &bg, 1);
361 OUT('m');
363 OUT(0);
364 return 0;
365 bad:
366 return error(_("invalid color value: %.*s"), value_len, value);
367 #undef OUT
370 int git_config_colorbool(const char *var, const char *value)
372 if (value) {
373 if (!strcasecmp(value, "never"))
374 return 0;
375 if (!strcasecmp(value, "always"))
376 return 1;
377 if (!strcasecmp(value, "auto"))
378 return GIT_COLOR_AUTO;
381 if (!var)
382 return -1;
384 /* Missing or explicit false to turn off colorization */
385 if (!git_config_bool(var, value))
386 return 0;
388 /* any normal truth value defaults to 'auto' */
389 return GIT_COLOR_AUTO;
392 static int check_auto_color(int fd)
394 static int color_stderr_is_tty = -1;
395 int *is_tty_p = fd == 1 ? &color_stdout_is_tty : &color_stderr_is_tty;
396 if (*is_tty_p < 0)
397 *is_tty_p = isatty(fd);
398 if (*is_tty_p || (fd == 1 && pager_in_use() && pager_use_color)) {
399 if (!is_terminal_dumb())
400 return 1;
402 return 0;
405 int want_color_fd(int fd, int var)
408 * NEEDSWORK: This function is sometimes used from multiple threads, and
409 * we end up using want_auto racily. That "should not matter" since
410 * we always write the same value, but it's still wrong. This function
411 * is listed in .tsan-suppressions for the time being.
414 static int want_auto[3] = { -1, -1, -1 };
416 if (fd < 1 || fd >= ARRAY_SIZE(want_auto))
417 BUG("file descriptor out of range: %d", fd);
419 if (var < 0)
420 var = git_use_color_default;
422 if (var == GIT_COLOR_AUTO) {
423 if (want_auto[fd] < 0)
424 want_auto[fd] = check_auto_color(fd);
425 return want_auto[fd];
427 return var;
430 int git_color_config(const char *var, const char *value, void *cb UNUSED)
432 if (!strcmp(var, "color.ui")) {
433 git_use_color_default = git_config_colorbool(var, value);
434 return 0;
437 return 0;
440 void color_print_strbuf(FILE *fp, const char *color, const struct strbuf *sb)
442 if (*color)
443 fprintf(fp, "%s", color);
444 fprintf(fp, "%s", sb->buf);
445 if (*color)
446 fprintf(fp, "%s", GIT_COLOR_RESET);
449 static int color_vfprintf(FILE *fp, const char *color, const char *fmt,
450 va_list args, const char *trail)
452 int r = 0;
454 if (*color)
455 r += fprintf(fp, "%s", color);
456 r += vfprintf(fp, fmt, args);
457 if (*color)
458 r += fprintf(fp, "%s", GIT_COLOR_RESET);
459 if (trail)
460 r += fprintf(fp, "%s", trail);
461 return r;
464 int color_fprintf(FILE *fp, const char *color, const char *fmt, ...)
466 va_list args;
467 int r;
468 va_start(args, fmt);
469 r = color_vfprintf(fp, color, fmt, args, NULL);
470 va_end(args);
471 return r;
474 int color_fprintf_ln(FILE *fp, const char *color, const char *fmt, ...)
476 va_list args;
477 int r;
478 va_start(args, fmt);
479 r = color_vfprintf(fp, color, fmt, args, "\n");
480 va_end(args);
481 return r;
484 int color_is_nil(const char *c)
486 return !strcmp(c, "NIL");