diagnostic-color.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. /* Output colorization.
  2. Copyright (C) 2011-2015 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 3, or (at your option)
  6. any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software
  13. Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
  14. 02110-1301, USA. */
  15. #include "config.h"
  16. #include "system.h"
  17. #include "diagnostic-color.h"
  18. /* Select Graphic Rendition (SGR, "\33[...m") strings. */
  19. /* Also Erase in Line (EL) to Right ("\33[K") by default. */
  20. /* Why have EL to Right after SGR?
  21. -- The behavior of line-wrapping when at the bottom of the
  22. terminal screen and at the end of the current line is often
  23. such that a new line is introduced, entirely cleared with
  24. the current background color which may be different from the
  25. default one (see the boolean back_color_erase terminfo(5)
  26. capability), thus scrolling the display by one line.
  27. The end of this new line will stay in this background color
  28. even after reverting to the default background color with
  29. "\33[m', unless it is explicitly cleared again with "\33[K"
  30. (which is the behavior the user would instinctively expect
  31. from the whole thing). There may be some unavoidable
  32. background-color flicker at the end of this new line because
  33. of this (when timing with the monitor's redraw is just right).
  34. -- The behavior of HT (tab, "\t") is usually the same as that of
  35. Cursor Forward Tabulation (CHT) with a default parameter
  36. of 1 ("\33[I"), i.e., it performs pure movement to the next
  37. tab stop, without any clearing of either content or screen
  38. attributes (including background color); try
  39. printf 'asdfqwerzxcv\rASDF\tZXCV\n'
  40. in a bash(1) shell to demonstrate this. This is not what the
  41. user would instinctively expect of HT (but is ok for CHT).
  42. The instinctive behavior would include clearing the terminal
  43. cells that are skipped over by HT with blank cells in the
  44. current screen attributes, including background color;
  45. the boolean dest_tabs_magic_smso terminfo(5) capability
  46. indicates this saner behavior for HT, but only some rare
  47. terminals have it (although it also indicates a special
  48. glitch with standout mode in the Teleray terminal for which
  49. it was initially introduced). The remedy is to add "\33K"
  50. after each SGR sequence, be it START (to fix the behavior
  51. of any HT after that before another SGR) or END (to fix the
  52. behavior of an HT in default background color that would
  53. follow a line-wrapping at the bottom of the screen in another
  54. background color, and to complement doing it after START).
  55. Piping GCC's output through a pager such as less(1) avoids
  56. any HT problems since the pager performs tab expansion.
  57. Generic disadvantages of this remedy are:
  58. -- Some very rare terminals might support SGR but not EL (nobody
  59. will use "gcc -fdiagnostics-color" on a terminal that does not
  60. support SGR in the first place).
  61. -- Having these extra control sequences might somewhat complicate
  62. the task of any program trying to parse "gcc -fdiagnostics-color"
  63. output in order to extract structuring information from it.
  64. A specific disadvantage to doing it after SGR START is:
  65. -- Even more possible background color flicker (when timing
  66. with the monitor's redraw is just right), even when not at the
  67. bottom of the screen.
  68. There are no additional disadvantages specific to doing it after
  69. SGR END.
  70. It would be impractical for GCC to become a full-fledged
  71. terminal program linked against ncurses or the like, so it will
  72. not detect terminfo(5) capabilities. */
  73. #define COLOR_SEPARATOR ";"
  74. #define COLOR_NONE "00"
  75. #define COLOR_BOLD "01"
  76. #define COLOR_UNDERSCORE "04"
  77. #define COLOR_BLINK "05"
  78. #define COLOR_REVERSE "07"
  79. #define COLOR_FG_BLACK "30"
  80. #define COLOR_FG_RED "31"
  81. #define COLOR_FG_GREEN "32"
  82. #define COLOR_FG_YELLOW "33"
  83. #define COLOR_FG_BLUE "34"
  84. #define COLOR_FG_MAGENTA "35"
  85. #define COLOR_FG_CYAN "36"
  86. #define COLOR_FG_WHITE "37"
  87. #define COLOR_BG_BLACK "40"
  88. #define COLOR_BG_RED "41"
  89. #define COLOR_BG_GREEN "42"
  90. #define COLOR_BG_YELLOW "43"
  91. #define COLOR_BG_BLUE "44"
  92. #define COLOR_BG_MAGENTA "45"
  93. #define COLOR_BG_CYAN "46"
  94. #define COLOR_BG_WHITE "47"
  95. #define SGR_START "\33["
  96. #define SGR_END "m\33[K"
  97. #define SGR_SEQ(str) SGR_START str SGR_END
  98. #define SGR_RESET SGR_SEQ("")
  99. /* The context and logic for choosing default --color screen attributes
  100. (foreground and background colors, etc.) are the following.
  101. -- There are eight basic colors available, each with its own
  102. nominal luminosity to the human eye and foreground/background
  103. codes (black [0 %, 30/40], blue [11 %, 34/44], red [30 %, 31/41],
  104. magenta [41 %, 35/45], green [59 %, 32/42], cyan [70 %, 36/46],
  105. yellow [89 %, 33/43], and white [100 %, 37/47]).
  106. -- Sometimes, white as a background is actually implemented using
  107. a shade of light gray, so that a foreground white can be visible
  108. on top of it (but most often not).
  109. -- Sometimes, black as a foreground is actually implemented using
  110. a shade of dark gray, so that it can be visible on top of a
  111. background black (but most often not).
  112. -- Sometimes, more colors are available, as extensions.
  113. -- Other attributes can be selected/deselected (bold [1/22],
  114. underline [4/24], standout/inverse [7/27], blink [5/25], and
  115. invisible/hidden [8/28]). They are sometimes implemented by
  116. using colors instead of what their names imply; e.g., bold is
  117. often achieved by using brighter colors. In practice, only bold
  118. is really available to us, underline sometimes being mapped by
  119. the terminal to some strange color choice, and standout best
  120. being left for use by downstream programs such as less(1).
  121. -- We cannot assume that any of the extensions or special features
  122. are available for the purpose of choosing defaults for everyone.
  123. -- The most prevalent default terminal backgrounds are pure black
  124. and pure white, and are not necessarily the same shades of
  125. those as if they were selected explicitly with SGR sequences.
  126. Some terminals use dark or light pictures as default background,
  127. but those are covered over by an explicit selection of background
  128. color with an SGR sequence; their users will appreciate their
  129. background pictures not be covered like this, if possible.
  130. -- Some uses of colors attributes is to make some output items
  131. more understated (e.g., context lines); this cannot be achieved
  132. by changing the background color.
  133. -- For these reasons, the GCC color defaults should strive not
  134. to change the background color from its default, unless it's
  135. for a short item that should be highlighted, not understated.
  136. -- The GCC foreground color defaults (without an explicitly set
  137. background) should provide enough contrast to be readable on any
  138. terminal with either a black (dark) or white (light) background.
  139. This only leaves red, magenta, green, and cyan (and their bold
  140. counterparts) and possibly bold blue. */
  141. /* Default colors. The user can overwrite them using environment
  142. variable GCC_COLORS. */
  143. struct color_cap
  144. {
  145. const char *name;
  146. const char *val;
  147. unsigned char name_len;
  148. bool free_val;
  149. };
  150. /* For GCC_COLORS. */
  151. static struct color_cap color_dict[] =
  152. {
  153. { "error", SGR_SEQ (COLOR_BOLD COLOR_SEPARATOR COLOR_FG_RED), 5, false },
  154. { "warning", SGR_SEQ (COLOR_BOLD COLOR_SEPARATOR COLOR_FG_MAGENTA),
  155. 7, false },
  156. { "note", SGR_SEQ (COLOR_BOLD COLOR_SEPARATOR COLOR_FG_CYAN), 4, false },
  157. { "caret", SGR_SEQ (COLOR_BOLD COLOR_SEPARATOR COLOR_FG_GREEN), 5, false },
  158. { "locus", SGR_SEQ (COLOR_BOLD), 5, false },
  159. { "quote", SGR_SEQ (COLOR_BOLD), 5, false },
  160. { NULL, NULL, 0, false }
  161. };
  162. const char *
  163. colorize_start (bool show_color, const char *name, size_t name_len)
  164. {
  165. struct color_cap const *cap;
  166. if (!show_color)
  167. return "";
  168. for (cap = color_dict; cap->name; cap++)
  169. if (cap->name_len == name_len
  170. && memcmp (cap->name, name, name_len) == 0)
  171. break;
  172. if (cap->name == NULL)
  173. return "";
  174. return cap->val;
  175. }
  176. const char *
  177. colorize_stop (bool show_color)
  178. {
  179. return show_color ? SGR_RESET : "";
  180. }
  181. /* Parse GCC_COLORS. The default would look like:
  182. GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'
  183. No character escaping is needed or supported. */
  184. static bool
  185. parse_gcc_colors (void)
  186. {
  187. const char *p, *q, *name, *val;
  188. char *b;
  189. size_t name_len = 0, val_len = 0;
  190. p = getenv ("GCC_COLORS"); /* Plural! */
  191. if (p == NULL)
  192. return true;
  193. if (*p == '\0')
  194. return false;
  195. name = q = p;
  196. val = NULL;
  197. /* From now on, be well-formed or you're gone. */
  198. for (;;)
  199. if (*q == ':' || *q == '\0')
  200. {
  201. struct color_cap *cap;
  202. if (val)
  203. val_len = q - val;
  204. else
  205. name_len = q - name;
  206. /* Empty name without val (empty cap)
  207. won't match and will be ignored. */
  208. for (cap = color_dict; cap->name; cap++)
  209. if (cap->name_len == name_len
  210. && memcmp (cap->name, name, name_len) == 0)
  211. break;
  212. /* If name unknown, go on for forward compatibility. */
  213. if (cap->val && val)
  214. {
  215. if (cap->free_val)
  216. free (CONST_CAST (char *, cap->val));
  217. b = XNEWVEC (char, val_len + sizeof (SGR_SEQ ("")));
  218. memcpy (b, SGR_START, strlen (SGR_START));
  219. memcpy (b + strlen (SGR_START), val, val_len);
  220. memcpy (b + strlen (SGR_START) + val_len, SGR_END,
  221. sizeof (SGR_END));
  222. cap->val = (const char *) b;
  223. cap->free_val = true;
  224. }
  225. if (*q == '\0')
  226. return true;
  227. name = ++q;
  228. val = NULL;
  229. }
  230. else if (*q == '=')
  231. {
  232. if (q == name || val)
  233. return true;
  234. name_len = q - name;
  235. val = ++q; /* Can be the empty string. */
  236. }
  237. else if (val == NULL)
  238. q++; /* Accumulate name. */
  239. else if (*q == ';' || (*q >= '0' && *q <= '9'))
  240. q++; /* Accumulate val. Protect the terminal from being sent
  241. garbage. */
  242. else
  243. return true;
  244. }
  245. #if defined(_WIN32)
  246. bool
  247. colorize_init (diagnostic_color_rule_t)
  248. {
  249. return false;
  250. }
  251. #else
  252. /* Return true if we should use color when in auto mode, false otherwise. */
  253. static bool
  254. should_colorize (void)
  255. {
  256. char const *t = getenv ("TERM");
  257. return t && strcmp (t, "dumb") != 0 && isatty (STDERR_FILENO);
  258. }
  259. bool
  260. colorize_init (diagnostic_color_rule_t rule)
  261. {
  262. switch (rule)
  263. {
  264. case DIAGNOSTICS_COLOR_NO:
  265. return false;
  266. case DIAGNOSTICS_COLOR_YES:
  267. return parse_gcc_colors ();
  268. case DIAGNOSTICS_COLOR_AUTO:
  269. if (should_colorize ())
  270. return parse_gcc_colors ();
  271. else
  272. return false;
  273. default:
  274. gcc_unreachable ();
  275. }
  276. }
  277. #endif