xref: /freebsd/contrib/tcsh/tw.color.c (revision aa0a1e58)
1 /* $Header: /p/tcsh/cvsroot/tcsh/tw.color.c,v 1.25 2008/10/17 19:57:33 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.25 2008/10/17 19:57:33 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 };
90 
91 enum FileType {
92     VDir, VSym, VOrph, VPipe, VSock, VDoor, VBlock, VChr, VExe,
93     VFile, VNormal, VMiss, VLeft, VRight, VEnd
94 };
95 
96 #define nvariables (sizeof(variables)/sizeof(variables[0]))
97 
98 typedef struct {
99     Str	    extension;	/* file extension */
100     Str	    color;	/* color string */
101 } Extension;
102 
103 static Extension *extensions = NULL;
104 static size_t nextensions = 0;
105 
106 static char *colors = NULL;
107 int	     color_context_ls = FALSE;	/* do colored ls */
108 static int  color_context_lsmF = FALSE; /* do colored ls-F */
109 
110 static int getstring (char **, const Char **, Str *, int);
111 static void put_color (const Str *);
112 static void print_color (const Char *, size_t, Char);
113 
114 /* set_color_context():
115  */
116 void
117 set_color_context(void)
118 {
119     struct varent *vp = adrof(STRcolor);
120 
121     if (vp == NULL || vp->vec == NULL) {
122 	color_context_ls = FALSE;
123 	color_context_lsmF = FALSE;
124     } else if (!vp->vec[0] || vp->vec[0][0] == '\0') {
125 	color_context_ls = TRUE;
126 	color_context_lsmF = TRUE;
127     } else {
128 	size_t i;
129 
130 	color_context_ls = FALSE;
131 	color_context_lsmF = FALSE;
132 	for (i = 0; vp->vec[i]; i++)
133 	    if (Strcmp(vp->vec[i], STRls) == 0)
134 		color_context_ls = TRUE;
135 	    else if (Strcmp(vp->vec[i], STRlsmF) == 0)
136 		color_context_lsmF = TRUE;
137     }
138 }
139 
140 
141 /* getstring():
142  */
143 static	int
144 getstring(char **dp, const Char **sp, Str *pd, int f)
145 {
146     const Char *s = *sp;
147     char *d = *dp;
148     eChar sc;
149 
150     while (*s && (*s & CHAR) != (Char)f && (*s & CHAR) != ':') {
151 	if ((*s & CHAR) == '\\' || (*s & CHAR) == '^') {
152 	    if ((sc = parseescape(&s)) == CHAR_ERR)
153 		return 0;
154 	}
155 	else
156 	    sc = *s++ & CHAR;
157 	d += one_wctomb(d, sc);
158     }
159 
160     pd->s = *dp;
161     pd->len = d - *dp;
162     *sp = s;
163     *dp = d;
164     return *s == (Char)f;
165 }
166 
167 
168 /* parseLS_COLORS():
169  *	Parse the LS_COLORS environment variable
170  */
171 void
172 parseLS_COLORS(const Char *value)
173 {
174     size_t  i, len;
175     const Char	 *v;		/* pointer in value */
176     char   *c;			/* pointer in colors */
177     Extension *volatile e;	/* pointer in extensions */
178     jmp_buf_t osetexit;
179     size_t omark;
180 
181     (void) &e;
182 
183     /* init */
184     xfree(extensions);
185     for (i = 0; i < nvariables; i++)
186 	variables[i].color = variables[i].defaultcolor;
187     colors = NULL;
188     extensions = NULL;
189     nextensions = 0;
190 
191     if (value == NULL)
192 	return;
193 
194     len = Strlen(value);
195     /* allocate memory */
196     i = 1;
197     for (v = value; *v; v++)
198 	if ((*v & CHAR) == ':')
199 	    i++;
200     extensions = xmalloc(len + i * sizeof(Extension));
201     colors = i * sizeof(Extension) + (char *)extensions;
202     nextensions = 0;
203 
204     /* init pointers */
205     v = value;
206     c = colors;
207     e = &extensions[0];
208 
209     /* Prevent from crashing if unknown parameters are given. */
210 
211     omark = cleanup_push_mark();
212     getexit(osetexit);
213 
214     if (setexit() == 0) {
215 
216     /* parse */
217     while (*v) {
218 	switch (*v & CHAR) {
219 	case ':':
220 	    v++;
221 	    continue;
222 
223 	case '*':		/* :*ext=color: */
224 	    v++;
225 	    if (getstring(&c, &v, &e->extension, '=') &&
226 		0 < e->extension.len) {
227 		v++;
228 		getstring(&c, &v, &e->color, ':');
229 		e++;
230 		continue;
231 	    }
232 	    break;
233 
234 	default:		/* :vl=color: */
235 	    if (v[0] && v[1] && (v[2] & CHAR) == '=') {
236 		for (i = 0; i < nvariables; i++)
237 		    if ((Char)variables[i].variable[0] == (v[0] & CHAR) &&
238 			(Char)variables[i].variable[1] == (v[1] & CHAR))
239 			break;
240 		if (i < nvariables) {
241 		    v += 3;
242 		    getstring(&c, &v, &variables[i].color, ':');
243 		    continue;
244 		}
245 		else
246 		    stderror(ERR_BADCOLORVAR, v[0], v[1]);
247 	    }
248 	    break;
249 	}
250 	while (*v && (*v & CHAR) != ':')
251 	    v++;
252     }
253     }
254 
255     cleanup_pop_mark(omark);
256     resexit(osetexit);
257 
258     nextensions = e - extensions;
259 }
260 
261 /* put_color():
262  */
263 static void
264 put_color(const Str *color)
265 {
266     size_t  i;
267     const char	 *c = color->s;
268     int	   original_output_raw = output_raw;
269 
270     output_raw = TRUE;
271     cleanup_push(&original_output_raw, output_raw_restore);
272     for (i = color->len; 0 < i; i--)
273 	xputchar(*c++);
274     cleanup_until(&original_output_raw);
275 }
276 
277 
278 /* print_color():
279  */
280 static void
281 print_color(const Char *fname, size_t len, Char suffix)
282 {
283     size_t  i;
284     char   *filename = short2str(fname);
285     char   *last = filename + len;
286     Str	   *color = &variables[VFile].color;
287 
288     switch (suffix) {
289     case '>':			/* File is a symbolic link pointing to
290 				 * a directory */
291 	color = &variables[VDir].color;
292 	break;
293     case '+':			/* File is a hidden directory [aix] or
294 				 * context dependent [hpux] */
295     case ':':			/* File is network special [hpux] */
296 	break;
297     default:
298 	for (i = 0; i < nvariables; i++)
299 	    if (variables[i].suffix != NOS &&
300 		(Char)variables[i].suffix == suffix) {
301 		color = &variables[i].color;
302 		break;
303 	    }
304 	if (i == nvariables) {
305 	    for (i = 0; i < nextensions; i++)
306 		if (len >= extensions[i].extension.len
307 		    && strncmp(last - extensions[i].extension.len,
308 			       extensions[i].extension.s,
309 			       extensions[i].extension.len) == 0) {
310 		  color = &extensions[i].color;
311 		break;
312 	    }
313 	}
314 	break;
315     }
316 
317     put_color(&variables[VLeft].color);
318     put_color(color);
319     put_color(&variables[VRight].color);
320 }
321 
322 
323 /* print_with_color():
324  */
325 void
326 print_with_color(const Char *filename, size_t len, Char suffix)
327 {
328     if (color_context_lsmF &&
329 	(haderr ? (didfds ? is2atty : isdiagatty) :
330 	 (didfds ? is1atty : isoutatty))) {
331 	print_color(filename, len, suffix);
332 	xprintf("%S", filename);
333 	if (0 < variables[VEnd].color.len)
334 	    put_color(&variables[VEnd].color);
335 	else {
336 	    put_color(&variables[VLeft].color);
337 	    put_color(&variables[VNormal].color);
338 	    put_color(&variables[VRight].color);
339 	}
340     }
341     else
342 	xprintf("%S", filename);
343     xputwchar(suffix);
344 }
345 
346 
347 #endif /* COLOR_LS_F */
348