PR c++/79653
[official-gcc.git] / gcc / diagnostic-color.c
blob8353fe016b77149d5c1164de5bba68a329213e76
1 /* Output colorization.
2 Copyright (C) 2011-2017 Free Software Foundation, Inc.
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.
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.
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. */
19 #include "config.h"
20 #include "system.h"
21 #include "diagnostic-color.h"
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.
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.
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("")
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
154 const char *name;
155 const char *val;
156 unsigned char name_len;
157 bool free_val;
160 /* For GCC_COLORS. */
161 static struct color_cap color_dict[] =
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 { "fixit-insert", SGR_SEQ (COLOR_FG_GREEN), 12, false },
172 { "fixit-delete", SGR_SEQ (COLOR_FG_RED), 12, false },
173 { "diff-filename", SGR_SEQ (COLOR_BOLD), 13, false },
174 { "diff-hunk", SGR_SEQ (COLOR_FG_CYAN), 9, false },
175 { "diff-delete", SGR_SEQ (COLOR_FG_RED), 11, false },
176 { "diff-insert", SGR_SEQ (COLOR_FG_GREEN), 11, false },
177 { NULL, NULL, 0, false }
180 const char *
181 colorize_start (bool show_color, const char *name, size_t name_len)
183 struct color_cap const *cap;
185 if (!show_color)
186 return "";
188 for (cap = color_dict; cap->name; cap++)
189 if (cap->name_len == name_len
190 && memcmp (cap->name, name, name_len) == 0)
191 break;
192 if (cap->name == NULL)
193 return "";
195 return cap->val;
198 const char *
199 colorize_stop (bool show_color)
201 return show_color ? SGR_RESET : "";
204 /* Parse GCC_COLORS. The default would look like:
205 GCC_COLORS='error=01;31:warning=01;35:note=01;36:\
206 range1=32:range2=34:locus=01:quote=01:\
207 fixit-insert=32:fixit-delete=31'\
208 diff-filename=01:diff-hunk=32:diff-delete=31:diff-insert=32'
209 No character escaping is needed or supported. */
210 static bool
211 parse_gcc_colors (void)
213 const char *p, *q, *name, *val;
214 char *b;
215 size_t name_len = 0, val_len = 0;
217 p = getenv ("GCC_COLORS"); /* Plural! */
218 if (p == NULL)
219 return true;
220 if (*p == '\0')
221 return false;
223 name = q = p;
224 val = NULL;
225 /* From now on, be well-formed or you're gone. */
226 for (;;)
227 if (*q == ':' || *q == '\0')
229 struct color_cap *cap;
231 if (val)
232 val_len = q - val;
233 else
234 name_len = q - name;
235 /* Empty name without val (empty cap)
236 won't match and will be ignored. */
237 for (cap = color_dict; cap->name; cap++)
238 if (cap->name_len == name_len
239 && memcmp (cap->name, name, name_len) == 0)
240 break;
241 /* If name unknown, go on for forward compatibility. */
242 if (cap->val && val)
244 if (cap->free_val)
245 free (CONST_CAST (char *, cap->val));
246 b = XNEWVEC (char, val_len + sizeof (SGR_SEQ ("")));
247 memcpy (b, SGR_START, strlen (SGR_START));
248 memcpy (b + strlen (SGR_START), val, val_len);
249 memcpy (b + strlen (SGR_START) + val_len, SGR_END,
250 sizeof (SGR_END));
251 cap->val = (const char *) b;
252 cap->free_val = true;
254 if (*q == '\0')
255 return true;
256 name = ++q;
257 val = NULL;
259 else if (*q == '=')
261 if (q == name || val)
262 return true;
264 name_len = q - name;
265 val = ++q; /* Can be the empty string. */
267 else if (val == NULL)
268 q++; /* Accumulate name. */
269 else if (*q == ';' || (*q >= '0' && *q <= '9'))
270 q++; /* Accumulate val. Protect the terminal from being sent
271 garbage. */
272 else
273 return true;
276 #if defined(_WIN32)
277 bool
278 colorize_init (diagnostic_color_rule_t)
280 return false;
282 #else
284 /* Return true if we should use color when in auto mode, false otherwise. */
285 static bool
286 should_colorize (void)
288 char const *t = getenv ("TERM");
289 return t && strcmp (t, "dumb") != 0 && isatty (STDERR_FILENO);
293 bool
294 colorize_init (diagnostic_color_rule_t rule)
296 switch (rule)
298 case DIAGNOSTICS_COLOR_NO:
299 return false;
300 case DIAGNOSTICS_COLOR_YES:
301 return parse_gcc_colors ();
302 case DIAGNOSTICS_COLOR_AUTO:
303 if (should_colorize ())
304 return parse_gcc_colors ();
305 else
306 return false;
307 default:
308 gcc_unreachable ();
311 #endif