xref: /freebsd/contrib/tcsh/tw.color.c (revision 38f0b757fd84d17d0fc24739a7cda160c4516d81)
1 /* $Header: /p/tcsh/cvsroot/tcsh/tw.color.c,v 1.27 2010/08/19 05:52:19 christos Exp $ */
2 /*
3  * tw.color.c: builtin color ls-F
4  */
5 /*-
6  * Copyright (c) 1998 The Regents of the University of California.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 #include "sh.h"
34 
35 RCSID("$tcsh: tw.color.c,v 1.27 2010/08/19 05:52:19 christos Exp $")
36 
37 #include "tw.h"
38 #include "ed.h"
39 #include "tc.h"
40 
41 #ifdef COLOR_LS_F
42 
43 typedef struct {
44     const char	 *s;
45     size_t len;
46 } Str;
47 
48 
49 #define VAR(suffix,variable,defaultcolor) \
50 { \
51     suffix, variable, { defaultcolor, sizeof(defaultcolor) - 1 }, \
52       { defaultcolor, sizeof(defaultcolor) - 1 } \
53 }
54 #define NOS '\0' /* no suffix */
55 
56 typedef struct {
57     const char suffix;
58     const char *variable;
59     Str	    color;
60     Str	    defaultcolor;
61 } Variable;
62 
63 static Variable variables[] = {
64     VAR('/', "di", "01;34"),	/* Directory */
65     VAR('@', "ln", "01;36"),	/* Symbolic link */
66     VAR('&', "or", ""),		/* Orphanned symbolic link (defaults to ln) */
67     VAR('|', "pi", "33"),	/* Named pipe (FIFO) */
68     VAR('=', "so", "01;35"),	/* Socket */
69     VAR('>', "do", "01;35"),	/* Door (solaris fast ipc mechanism)  */
70     VAR('#', "bd", "01;33"),	/* Block device */
71     VAR('%', "cd", "01;33"),	/* Character device */
72     VAR('*', "ex", "01;32"),	/* Executable file */
73     VAR(NOS, "fi", "0"),	/* Regular file */
74     VAR(NOS, "no", "0"),	/* Normal (non-filename) text */
75     VAR(NOS, "mi", ""),		/* Missing file (defaults to fi) */
76 #ifdef IS_ASCII
77     VAR(NOS, "lc", "\033["),	/* Left code (ASCII) */
78 #else
79     VAR(NOS, "lc", "\x27["),	/* Left code (EBCDIC)*/
80 #endif
81     VAR(NOS, "rc", "m"),	/* Right code */
82     VAR(NOS, "ec", ""),		/* End code (replaces lc+no+rc) */
83     VAR(NOS, "su", ""),		/* Setuid file (u+s) */
84     VAR(NOS, "sg", ""),		/* Setgid file (g+s) */
85     VAR(NOS, "tw", ""),		/* Sticky and other writable dir (+t,o+w) */
86     VAR(NOS, "ow", ""),		/* Other writable dir (o+w) but not sticky */
87     VAR(NOS, "st", ""),		/* Sticky dir (+t) but not other writable */
88     VAR(NOS, "rs", "0"),	/* Reset to normal color */
89     VAR(NOS, "hl", "44;37"),    /* Reg file extra hard links, obsolete? */
90     VAR(NOS, "mh", "44;37"),    /* Reg file extra hard links */
91     VAR(NOS, "ca", "30;41"),    /* File with capability */
92 };
93 
94 enum FileType {
95     VDir, VSym, VOrph, VPipe, VSock, VDoor, VBlock, VChr, VExe,
96     VFile, VNormal, VMiss, VLeft, VRight, VEnd
97 };
98 
99 #define nvariables (sizeof(variables)/sizeof(variables[0]))
100 
101 typedef struct {
102     Str	    extension;	/* file extension */
103     Str	    color;	/* color string */
104 } Extension;
105 
106 static Extension *extensions = NULL;
107 static size_t nextensions = 0;
108 
109 static char *colors = NULL;
110 int	     color_context_ls = FALSE;	/* do colored ls */
111 static int  color_context_lsmF = FALSE; /* do colored ls-F */
112 
113 static int getstring (char **, const Char **, Str *, int);
114 static void put_color (const Str *);
115 static void print_color (const Char *, size_t, Char);
116 
117 /* set_color_context():
118  */
119 void
120 set_color_context(void)
121 {
122     struct varent *vp = adrof(STRcolor);
123 
124     if (vp == NULL || vp->vec == NULL) {
125 	color_context_ls = FALSE;
126 	color_context_lsmF = FALSE;
127     } else if (!vp->vec[0] || vp->vec[0][0] == '\0') {
128 	color_context_ls = TRUE;
129 	color_context_lsmF = TRUE;
130     } else {
131 	size_t i;
132 
133 	color_context_ls = FALSE;
134 	color_context_lsmF = FALSE;
135 	for (i = 0; vp->vec[i]; i++)
136 	    if (Strcmp(vp->vec[i], STRls) == 0)
137 		color_context_ls = TRUE;
138 	    else if (Strcmp(vp->vec[i], STRlsmF) == 0)
139 		color_context_lsmF = TRUE;
140     }
141 }
142 
143 
144 /* getstring():
145  */
146 static	int
147 getstring(char **dp, const Char **sp, Str *pd, int f)
148 {
149     const Char *s = *sp;
150     char *d = *dp;
151     eChar sc;
152 
153     while (*s && (*s & CHAR) != (Char)f && (*s & CHAR) != ':') {
154 	if ((*s & CHAR) == '\\' || (*s & CHAR) == '^') {
155 	    if ((sc = parseescape(&s)) == CHAR_ERR)
156 		return 0;
157 	}
158 	else
159 	    sc = *s++ & CHAR;
160 	d += one_wctomb(d, sc);
161     }
162 
163     pd->s = *dp;
164     pd->len = d - *dp;
165     *sp = s;
166     *dp = d;
167     return *s == (Char)f;
168 }
169 
170 
171 /* parseLS_COLORS():
172  *	Parse the LS_COLORS environment variable
173  */
174 void
175 parseLS_COLORS(const Char *value)
176 {
177     size_t  i, len;
178     const Char	 *v;		/* pointer in value */
179     char   *c;			/* pointer in colors */
180     Extension *volatile e;	/* pointer in extensions */
181     jmp_buf_t osetexit;
182     size_t omark;
183 
184     (void) &e;
185 
186     /* init */
187     xfree(extensions);
188     for (i = 0; i < nvariables; i++)
189 	variables[i].color = variables[i].defaultcolor;
190     colors = NULL;
191     extensions = NULL;
192     nextensions = 0;
193 
194     if (value == NULL)
195 	return;
196 
197     len = Strlen(value);
198     /* allocate memory */
199     i = 1;
200     for (v = value; *v; v++)
201 	if ((*v & CHAR) == ':')
202 	    i++;
203     extensions = xmalloc(len + i * sizeof(Extension));
204     colors = i * sizeof(Extension) + (char *)extensions;
205     nextensions = 0;
206 
207     /* init pointers */
208     v = value;
209     c = colors;
210     e = &extensions[0];
211 
212     /* Prevent from crashing if unknown parameters are given. */
213 
214     omark = cleanup_push_mark();
215     getexit(osetexit);
216 
217     if (setexit() == 0) {
218 
219     /* parse */
220     while (*v) {
221 	switch (*v & CHAR) {
222 	case ':':
223 	    v++;
224 	    continue;
225 
226 	case '*':		/* :*ext=color: */
227 	    v++;
228 	    if (getstring(&c, &v, &e->extension, '=') &&
229 		0 < e->extension.len) {
230 		v++;
231 		getstring(&c, &v, &e->color, ':');
232 		e++;
233 		continue;
234 	    }
235 	    break;
236 
237 	default:		/* :vl=color: */
238 	    if (v[0] && v[1] && (v[2] & CHAR) == '=') {
239 		for (i = 0; i < nvariables; i++)
240 		    if ((Char)variables[i].variable[0] == (v[0] & CHAR) &&
241 			(Char)variables[i].variable[1] == (v[1] & CHAR))
242 			break;
243 		if (i < nvariables) {
244 		    v += 3;
245 		    getstring(&c, &v, &variables[i].color, ':');
246 		    continue;
247 		}
248 		else
249 		    stderror(ERR_BADCOLORVAR, v[0], v[1]);
250 	    }
251 	    break;
252 	}
253 	while (*v && (*v & CHAR) != ':')
254 	    v++;
255     }
256     }
257 
258     cleanup_pop_mark(omark);
259     resexit(osetexit);
260 
261     nextensions = e - extensions;
262 }
263 
264 /* put_color():
265  */
266 static void
267 put_color(const Str *color)
268 {
269     size_t  i;
270     const char	 *c = color->s;
271     int	   original_output_raw = output_raw;
272 
273     output_raw = TRUE;
274     cleanup_push(&original_output_raw, output_raw_restore);
275     for (i = color->len; 0 < i; i--)
276 	xputchar(*c++);
277     cleanup_until(&original_output_raw);
278 }
279 
280 
281 /* print_color():
282  */
283 static void
284 print_color(const Char *fname, size_t len, Char suffix)
285 {
286     size_t  i;
287     char   *filename = short2str(fname);
288     char   *last = filename + len;
289     Str	   *color = &variables[VFile].color;
290 
291     switch (suffix) {
292     case '>':			/* File is a symbolic link pointing to
293 				 * a directory */
294 	color = &variables[VDir].color;
295 	break;
296     case '+':			/* File is a hidden directory [aix] or
297 				 * context dependent [hpux] */
298     case ':':			/* File is network special [hpux] */
299 	break;
300     default:
301 	for (i = 0; i < nvariables; i++)
302 	    if (variables[i].suffix != NOS &&
303 		(Char)variables[i].suffix == suffix) {
304 		color = &variables[i].color;
305 		break;
306 	    }
307 	if (i == nvariables) {
308 	    for (i = 0; i < nextensions; i++)
309 		if (len >= extensions[i].extension.len
310 		    && strncmp(last - extensions[i].extension.len,
311 			       extensions[i].extension.s,
312 			       extensions[i].extension.len) == 0) {
313 		  color = &extensions[i].color;
314 		break;
315 	    }
316 	}
317 	break;
318     }
319 
320     put_color(&variables[VLeft].color);
321     put_color(color);
322     put_color(&variables[VRight].color);
323 }
324 
325 
326 /* print_with_color():
327  */
328 void
329 print_with_color(const Char *filename, size_t len, Char suffix)
330 {
331     if (color_context_lsmF &&
332 	(haderr ? (didfds ? is2atty : isdiagatty) :
333 	 (didfds ? is1atty : isoutatty))) {
334 	print_color(filename, len, suffix);
335 	xprintf("%S", filename);
336 	if (0 < variables[VEnd].color.len)
337 	    put_color(&variables[VEnd].color);
338 	else {
339 	    put_color(&variables[VLeft].color);
340 	    put_color(&variables[VNormal].color);
341 	    put_color(&variables[VRight].color);
342 	}
343     }
344     else
345 	xprintf("%S", filename);
346     xputwchar(suffix);
347 }
348 
349 
350 #endif /* COLOR_LS_F */
351