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