Merge branch 'jt/mailinfo-fold-in-body-headers' into maint
[git] / color.c
1 #include "cache.h"
2 #include "color.h"
3
4 static int git_use_color_default = GIT_COLOR_AUTO;
5 int color_stdout_is_tty = -1;
6
7 /*
8  * The list of available column colors.
9  */
10 const char *column_colors_ansi[] = {
11         GIT_COLOR_RED,
12         GIT_COLOR_GREEN,
13         GIT_COLOR_YELLOW,
14         GIT_COLOR_BLUE,
15         GIT_COLOR_MAGENTA,
16         GIT_COLOR_CYAN,
17         GIT_COLOR_BOLD_RED,
18         GIT_COLOR_BOLD_GREEN,
19         GIT_COLOR_BOLD_YELLOW,
20         GIT_COLOR_BOLD_BLUE,
21         GIT_COLOR_BOLD_MAGENTA,
22         GIT_COLOR_BOLD_CYAN,
23         GIT_COLOR_RESET,
24 };
25
26 /* Ignore the RESET at the end when giving the size */
27 const int column_colors_ansi_max = ARRAY_SIZE(column_colors_ansi) - 1;
28
29 /* An individual foreground or background color. */
30 struct color {
31         enum {
32                 COLOR_UNSPECIFIED = 0,
33                 COLOR_NORMAL,
34                 COLOR_ANSI, /* basic 0-7 ANSI colors */
35                 COLOR_256,
36                 COLOR_RGB
37         } type;
38         /* The numeric value for ANSI and 256-color modes */
39         unsigned char value;
40         /* 24-bit RGB color values */
41         unsigned char red, green, blue;
42 };
43
44 /*
45  * "word" is a buffer of length "len"; does it match the NUL-terminated
46  * "match" exactly?
47  */
48 static int match_word(const char *word, int len, const char *match)
49 {
50         return !strncasecmp(word, match, len) && !match[len];
51 }
52
53 static int get_hex_color(const char *in, unsigned char *out)
54 {
55         unsigned int val;
56         val = (hexval(in[0]) << 4) | hexval(in[1]);
57         if (val & ~0xff)
58                 return -1;
59         *out = val;
60         return 0;
61 }
62
63 static int parse_color(struct color *out, const char *name, int len)
64 {
65         /* Positions in array must match ANSI color codes */
66         static const char * const color_names[] = {
67                 "black", "red", "green", "yellow",
68                 "blue", "magenta", "cyan", "white"
69         };
70         char *end;
71         int i;
72         long val;
73
74         /* First try the special word "normal"... */
75         if (match_word(name, len, "normal")) {
76                 out->type = COLOR_NORMAL;
77                 return 0;
78         }
79
80         /* Try a 24-bit RGB value */
81         if (len == 7 && name[0] == '#') {
82                 if (!get_hex_color(name + 1, &out->red) &&
83                     !get_hex_color(name + 3, &out->green) &&
84                     !get_hex_color(name + 5, &out->blue)) {
85                         out->type = COLOR_RGB;
86                         return 0;
87                 }
88         }
89
90         /* Then pick from our human-readable color names... */
91         for (i = 0; i < ARRAY_SIZE(color_names); i++) {
92                 if (match_word(name, len, color_names[i])) {
93                         out->type = COLOR_ANSI;
94                         out->value = i;
95                         return 0;
96                 }
97         }
98
99         /* And finally try a literal 256-color-mode number */
100         val = strtol(name, &end, 10);
101         if (end - name == len) {
102                 /*
103                  * Allow "-1" as an alias for "normal", but other negative
104                  * numbers are bogus.
105                  */
106                 if (val < -1)
107                         ; /* fall through to error */
108                 else if (val < 0) {
109                         out->type = COLOR_NORMAL;
110                         return 0;
111                 /* Rewrite low numbers as more-portable standard colors. */
112                 } else if (val < 8) {
113                         out->type = COLOR_ANSI;
114                         out->value = val;
115                         return 0;
116                 } else if (val < 256) {
117                         out->type = COLOR_256;
118                         out->value = val;
119                         return 0;
120                 }
121         }
122
123         return -1;
124 }
125
126 static int parse_attr(const char *name, size_t len)
127 {
128         static const struct {
129                 const char *name;
130                 size_t len;
131                 int val, neg;
132         } attrs[] = {
133 #define ATTR(x, val, neg) { (x), sizeof(x)-1, (val), (neg) }
134                 ATTR("bold",      1, 22),
135                 ATTR("dim",       2, 22),
136                 ATTR("italic",    3, 23),
137                 ATTR("ul",        4, 24),
138                 ATTR("blink",     5, 25),
139                 ATTR("reverse",   7, 27),
140                 ATTR("strike",    9, 29)
141 #undef ATTR
142         };
143         int negate = 0;
144         int i;
145
146         if (skip_prefix_mem(name, len, "no", &name, &len)) {
147                 skip_prefix_mem(name, len, "-", &name, &len);
148                 negate = 1;
149         }
150
151         for (i = 0; i < ARRAY_SIZE(attrs); i++) {
152                 if (attrs[i].len == len && !memcmp(attrs[i].name, name, len))
153                         return negate ? attrs[i].neg : attrs[i].val;
154         }
155         return -1;
156 }
157
158 int color_parse(const char *value, char *dst)
159 {
160         return color_parse_mem(value, strlen(value), dst);
161 }
162
163 void color_set(char *dst, const char *color_bytes)
164 {
165         xsnprintf(dst, COLOR_MAXLEN, "%s", color_bytes);
166 }
167
168 /*
169  * Write the ANSI color codes for "c" to "out"; the string should
170  * already have the ANSI escape code in it. "out" should have enough
171  * space in it to fit any color.
172  */
173 static char *color_output(char *out, int len, const struct color *c, char type)
174 {
175         switch (c->type) {
176         case COLOR_UNSPECIFIED:
177         case COLOR_NORMAL:
178                 break;
179         case COLOR_ANSI:
180                 if (len < 2)
181                         die("BUG: color parsing ran out of space");
182                 *out++ = type;
183                 *out++ = '0' + c->value;
184                 break;
185         case COLOR_256:
186                 out += xsnprintf(out, len, "%c8;5;%d", type, c->value);
187                 break;
188         case COLOR_RGB:
189                 out += xsnprintf(out, len, "%c8;2;%d;%d;%d", type,
190                                  c->red, c->green, c->blue);
191                 break;
192         }
193         return out;
194 }
195
196 static int color_empty(const struct color *c)
197 {
198         return c->type <= COLOR_NORMAL;
199 }
200
201 int color_parse_mem(const char *value, int value_len, char *dst)
202 {
203         const char *ptr = value;
204         int len = value_len;
205         char *end = dst + COLOR_MAXLEN;
206         unsigned int attr = 0;
207         struct color fg = { COLOR_UNSPECIFIED };
208         struct color bg = { COLOR_UNSPECIFIED };
209
210         if (!strncasecmp(value, "reset", len)) {
211                 xsnprintf(dst, end - dst, GIT_COLOR_RESET);
212                 return 0;
213         }
214
215         /* [fg [bg]] [attr]... */
216         while (len > 0) {
217                 const char *word = ptr;
218                 struct color c = { COLOR_UNSPECIFIED };
219                 int val, wordlen = 0;
220
221                 while (len > 0 && !isspace(word[wordlen])) {
222                         wordlen++;
223                         len--;
224                 }
225
226                 ptr = word + wordlen;
227                 while (len > 0 && isspace(*ptr)) {
228                         ptr++;
229                         len--;
230                 }
231
232                 if (!parse_color(&c, word, wordlen)) {
233                         if (fg.type == COLOR_UNSPECIFIED) {
234                                 fg = c;
235                                 continue;
236                         }
237                         if (bg.type == COLOR_UNSPECIFIED) {
238                                 bg = c;
239                                 continue;
240                         }
241                         goto bad;
242                 }
243                 val = parse_attr(word, wordlen);
244                 if (0 <= val)
245                         attr |= (1 << val);
246                 else
247                         goto bad;
248         }
249
250 #undef OUT
251 #define OUT(x) do { \
252         if (dst == end) \
253                 die("BUG: color parsing ran out of space"); \
254         *dst++ = (x); \
255 } while(0)
256
257         if (attr || !color_empty(&fg) || !color_empty(&bg)) {
258                 int sep = 0;
259                 int i;
260
261                 OUT('\033');
262                 OUT('[');
263
264                 for (i = 0; attr; i++) {
265                         unsigned bit = (1 << i);
266                         if (!(attr & bit))
267                                 continue;
268                         attr &= ~bit;
269                         if (sep++)
270                                 OUT(';');
271                         dst += xsnprintf(dst, end - dst, "%d", i);
272                 }
273                 if (!color_empty(&fg)) {
274                         if (sep++)
275                                 OUT(';');
276                         /* foreground colors are all in the 3x range */
277                         dst = color_output(dst, end - dst, &fg, '3');
278                 }
279                 if (!color_empty(&bg)) {
280                         if (sep++)
281                                 OUT(';');
282                         /* background colors are all in the 4x range */
283                         dst = color_output(dst, end - dst, &bg, '4');
284                 }
285                 OUT('m');
286         }
287         OUT(0);
288         return 0;
289 bad:
290         return error(_("invalid color value: %.*s"), value_len, value);
291 #undef OUT
292 }
293
294 int git_config_colorbool(const char *var, const char *value)
295 {
296         if (value) {
297                 if (!strcasecmp(value, "never"))
298                         return 0;
299                 if (!strcasecmp(value, "always"))
300                         return 1;
301                 if (!strcasecmp(value, "auto"))
302                         return GIT_COLOR_AUTO;
303         }
304
305         if (!var)
306                 return -1;
307
308         /* Missing or explicit false to turn off colorization */
309         if (!git_config_bool(var, value))
310                 return 0;
311
312         /* any normal truth value defaults to 'auto' */
313         return GIT_COLOR_AUTO;
314 }
315
316 static int check_auto_color(void)
317 {
318         if (color_stdout_is_tty < 0)
319                 color_stdout_is_tty = isatty(1);
320         if (color_stdout_is_tty || (pager_in_use() && pager_use_color)) {
321                 char *term = getenv("TERM");
322                 if (term && strcmp(term, "dumb"))
323                         return 1;
324         }
325         return 0;
326 }
327
328 int want_color(int var)
329 {
330         static int want_auto = -1;
331
332         if (var < 0)
333                 var = git_use_color_default;
334
335         if (var == GIT_COLOR_AUTO) {
336                 if (want_auto < 0)
337                         want_auto = check_auto_color();
338                 return want_auto;
339         }
340         return var;
341 }
342
343 int git_color_config(const char *var, const char *value, void *cb)
344 {
345         if (!strcmp(var, "color.ui")) {
346                 git_use_color_default = git_config_colorbool(var, value);
347                 return 0;
348         }
349
350         return 0;
351 }
352
353 int git_color_default_config(const char *var, const char *value, void *cb)
354 {
355         if (git_color_config(var, value, cb) < 0)
356                 return -1;
357
358         return git_default_config(var, value, cb);
359 }
360
361 void color_print_strbuf(FILE *fp, const char *color, const struct strbuf *sb)
362 {
363         if (*color)
364                 fprintf(fp, "%s", color);
365         fprintf(fp, "%s", sb->buf);
366         if (*color)
367                 fprintf(fp, "%s", GIT_COLOR_RESET);
368 }
369
370 static int color_vfprintf(FILE *fp, const char *color, const char *fmt,
371                 va_list args, const char *trail)
372 {
373         int r = 0;
374
375         if (*color)
376                 r += fprintf(fp, "%s", color);
377         r += vfprintf(fp, fmt, args);
378         if (*color)
379                 r += fprintf(fp, "%s", GIT_COLOR_RESET);
380         if (trail)
381                 r += fprintf(fp, "%s", trail);
382         return r;
383 }
384
385
386
387 int color_fprintf(FILE *fp, const char *color, const char *fmt, ...)
388 {
389         va_list args;
390         int r;
391         va_start(args, fmt);
392         r = color_vfprintf(fp, color, fmt, args, NULL);
393         va_end(args);
394         return r;
395 }
396
397 int color_fprintf_ln(FILE *fp, const char *color, const char *fmt, ...)
398 {
399         va_list args;
400         int r;
401         va_start(args, fmt);
402         r = color_vfprintf(fp, color, fmt, args, "\n");
403         va_end(args);
404         return r;
405 }
406
407 int color_is_nil(const char *c)
408 {
409         return !strcmp(c, "NIL");
410 }