1/* Output colorization.
2   Copyright (C) 2011-2015 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.  */
152struct 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.  */
161static 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  { "caret", SGR_SEQ (COLOR_BOLD COLOR_SEPARATOR COLOR_FG_GREEN), 5, false },
168  { "locus", SGR_SEQ (COLOR_BOLD), 5, false },
169  { "quote", SGR_SEQ (COLOR_BOLD), 5, false },
170  { NULL, NULL, 0, false }
171};
172
173const char *
174colorize_start (bool show_color, const char *name, size_t name_len)
175{
176  struct color_cap const *cap;
177
178  if (!show_color)
179    return "";
180
181  for (cap = color_dict; cap->name; cap++)
182    if (cap->name_len == name_len
183	&& memcmp (cap->name, name, name_len) == 0)
184      break;
185  if (cap->name == NULL)
186    return "";
187
188  return cap->val;
189}
190
191const char *
192colorize_stop (bool show_color)
193{
194  return show_color ? SGR_RESET : "";
195}
196
197/* Parse GCC_COLORS.  The default would look like:
198   GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'
199   No character escaping is needed or supported.  */
200static bool
201parse_gcc_colors (void)
202{
203  const char *p, *q, *name, *val;
204  char *b;
205  size_t name_len = 0, val_len = 0;
206
207  p = getenv ("GCC_COLORS"); /* Plural! */
208  if (p == NULL)
209    return true;
210  if (*p == '\0')
211    return false;
212
213  name = q = p;
214  val = NULL;
215  /* From now on, be well-formed or you're gone.  */
216  for (;;)
217    if (*q == ':' || *q == '\0')
218      {
219	struct color_cap *cap;
220
221	if (val)
222	  val_len = q - val;
223	else
224	  name_len = q - name;
225	/* Empty name without val (empty cap)
226	   won't match and will be ignored.  */
227	for (cap = color_dict; cap->name; cap++)
228	  if (cap->name_len == name_len
229	      && memcmp (cap->name, name, name_len) == 0)
230	    break;
231	/* If name unknown, go on for forward compatibility.  */
232	if (cap->val && val)
233	  {
234	    if (cap->free_val)
235	      free (CONST_CAST (char *, cap->val));
236	    b = XNEWVEC (char, val_len + sizeof (SGR_SEQ ("")));
237	    memcpy (b, SGR_START, strlen (SGR_START));
238	    memcpy (b + strlen (SGR_START), val, val_len);
239	    memcpy (b + strlen (SGR_START) + val_len, SGR_END,
240		    sizeof (SGR_END));
241	    cap->val = (const char *) b;
242	    cap->free_val = true;
243	  }
244	if (*q == '\0')
245	  return true;
246	name = ++q;
247	val = NULL;
248      }
249    else if (*q == '=')
250      {
251	if (q == name || val)
252	  return true;
253
254	name_len = q - name;
255	val = ++q; /* Can be the empty string.  */
256      }
257    else if (val == NULL)
258      q++; /* Accumulate name.  */
259    else if (*q == ';' || (*q >= '0' && *q <= '9'))
260      q++; /* Accumulate val.  Protect the terminal from being sent
261	      garbage.  */
262    else
263      return true;
264}
265
266#if defined(_WIN32)
267bool
268colorize_init (diagnostic_color_rule_t)
269{
270  return false;
271}
272#else
273
274/* Return true if we should use color when in auto mode, false otherwise. */
275static bool
276should_colorize (void)
277{
278  char const *t = getenv ("TERM");
279  return t && strcmp (t, "dumb") != 0 && isatty (STDERR_FILENO);
280}
281
282
283bool
284colorize_init (diagnostic_color_rule_t rule)
285{
286  switch (rule)
287    {
288    case DIAGNOSTICS_COLOR_NO:
289      return false;
290    case DIAGNOSTICS_COLOR_YES:
291      return parse_gcc_colors ();
292    case DIAGNOSTICS_COLOR_AUTO:
293      if (should_colorize ())
294	return parse_gcc_colors ();
295      else
296	return false;
297    default:
298      gcc_unreachable ();
299    }
300}
301#endif
302