xref: /freebsd/contrib/tcsh/tw.color.c (revision 5521ff5a4d1929056e7ffc982fac3341ca54df7c)
1 /* $Header: /src/pub/tcsh/tw.color.c,v 1.7 2000/06/11 02:14:16 kim 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. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *	This product includes software developed by the University of
20  *	California, Berkeley and its contributors.
21  * 4. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  */
37 #include "sh.h"
38 
39 RCSID("$Id: tw.color.c,v 1.7 2000/06/11 02:14:16 kim Exp $")
40 
41 #include "tw.h"
42 #include "ed.h"
43 #include "tc.h"
44 
45 #ifdef COLOR_LS_F
46 
47 typedef struct {
48     char   *s;
49     int     len;
50 } Str;
51 
52 
53 #define VAR(suffix,variable,defaultcolor) \
54 { \
55     suffix, variable, { defaultcolor, sizeof(defaultcolor) - 1 }, \
56       { defaultcolor, sizeof(defaultcolor) - 1 } \
57 }
58 #define NOS '\0' /* no suffix */
59 
60 typedef struct {
61     const char suffix;
62     const char *variable;
63     Str     color;
64     Str     defaultcolor;
65 } Variable;
66 
67 static Variable variables[] = {
68     VAR('/', "di", "01;34"),	/* Directory */
69     VAR('@', "ln", "01;36"),	/* Symbolic link */
70     VAR('&', "or", ""),		/* Orphanned symbolic link (defaults to ln) */
71     VAR('|', "pi", "33"),	/* Named pipe (FIFO) */
72     VAR('=', "so", "01;35"),	/* Socket */
73     VAR('#', "bd", "01;33"),	/* Block device */
74     VAR('%', "cd", "01;33"),	/* Character device */
75     VAR('*', "ex", "01;32"),	/* Executable file */
76     VAR(NOS, "fi", "0"),	/* Regular file */
77     VAR(NOS, "no", "0"),	/* Normal (non-filename) text */
78     VAR(NOS, "mi", ""),		/* Missing file (defaults to fi) */
79 #ifdef IS_ASCII
80     VAR(NOS, "lc", "\033["),	/* Left code (ASCII) */
81 #else
82     VAR(NOS, "lc", "\x27["),	/* Left code (EBCDIC)*/
83 #endif
84     VAR(NOS, "rc", "m"),	/* Right code */
85     VAR(NOS, "ec", ""),		/* End code (replaces lc+no+rc) */
86 };
87 
88 enum FileType {
89     VDir, VSym, VOrph, VPipe, VSock, VBlock, VChr, VExe,
90     VFile, VNormal, VMiss, VLeft, VRight, VEnd
91 };
92 
93 #define nvariables (sizeof(variables)/sizeof(variables[0]))
94 
95 typedef struct {
96     Str     extension;	/* file extension */
97     Str     color;	/* color string */
98 } Extension;
99 
100 static Extension *extensions = NULL;
101 static int nextensions = 0;
102 
103 static char *colors = NULL;
104 bool	     color_context_ls = FALSE;	/* do colored ls */
105 static bool  color_context_lsmF = FALSE;	/* do colored ls-F */
106 
107 static bool getstring __P((char **, const Char **, Str *, int));
108 static void put_color __P((Str *));
109 static void print_color __P((Char *, size_t, int));
110 
111 /* set_color_context():
112  */
113 void
114 set_color_context()
115 {
116     struct varent *vp = adrof(STRcolor);
117 
118     if (!vp) {
119 	color_context_ls = FALSE;
120 	color_context_lsmF = FALSE;
121     }
122     else if (!vp->vec[0] || vp->vec[0][0] == '\0') {
123 	color_context_ls = TRUE;
124 	color_context_lsmF = TRUE;
125     }
126     else {
127 	size_t i;
128 
129 	color_context_ls = FALSE;
130 	color_context_lsmF = FALSE;
131 	for (i = 0; vp->vec[i]; i++)
132 	    if (Strcmp(vp->vec[i], STRls) == 0)
133 		color_context_ls = TRUE;
134 	    else if (Strcmp(vp->vec[i], STRlsmF) == 0)
135 		color_context_lsmF = TRUE;
136     }
137 }
138 
139 
140 /* getstring():
141  */
142 static  bool
143 getstring(dp, sp, pd, f)
144     char        **dp;		/* dest buffer */
145     const Char  **sp;		/* source buffer */
146     Str          *pd;		/* pointer to dest buffer */
147     int           f;		/* final character */
148 {
149     const Char *s = *sp;
150     char *d = *dp;
151     int sc;
152 
153     while (*s && (*s & CHAR) != f && (*s & CHAR) != ':') {
154 	if ((*s & CHAR) == '\\' || (*s & CHAR) == '^') {
155 	    if ((sc = parseescape(&s)) == -1)
156 		return 0;
157 	    else
158 		*d++ = (char) sc;
159 	}
160 	else
161 	    *d++ = *s++ & CHAR;
162     }
163 
164     pd->s = *dp;
165     pd->len = (int) (d - *dp);
166     *sp = s;
167     *dp = d;
168     return *s == f;
169 }
170 
171 
172 /* parseLS_COLORS():
173  *	Parse the LS_COLORS environment variable
174  */
175 void
176 parseLS_COLORS(value)
177     Char   *value;		/* LS_COLOR variable's value */
178 {
179     int     i;
180     size_t  len;
181     const Char   *v;		/* pointer in value */
182     char   *c;			/* pointer in colors */
183     Extension *e;		/* pointer in extensions */
184     jmp_buf_t osetexit;
185 
186     /* init */
187     if (extensions)
188         xfree((ptr_t) extensions);
189     for (i = 0; i < nvariables; i++)
190 	variables[i].color = variables[i].defaultcolor;
191     colors = NULL;
192     extensions = NULL;
193     nextensions = 0;
194 
195     if (value == NULL)
196 	return;
197 
198     len = Strlen(value);
199     /* allocate memory */
200     i = 1;
201     for (v = value; *v; v++)
202 	if ((*v & CHAR) == ':')
203 	    i++;
204     extensions = (Extension *) xmalloc((size_t) (len + i * sizeof(Extension)));
205     colors = i * sizeof(Extension) + (char *)extensions;
206     nextensions = 0;
207 
208     /* init pointers */
209     v = value;
210     c = colors;
211     e = &extensions[0];
212 
213     /* Prevent from crashing if unknown parameters are given. */
214 
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 (variables[i].variable[0] == (v[0] & CHAR) &&
241 			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     resexit(osetexit);
259 
260     nextensions = (int) (e - extensions);
261 }
262 
263 
264 /* put_color():
265  */
266 static void
267 put_color(color)
268     Str    *color;
269 {
270     extern bool output_raw;	/* PWP: in sh.print.c */
271     size_t  i;
272     char   *c = color->s;
273     bool    original_output_raw = output_raw;
274 
275     output_raw = TRUE;
276     for (i = color->len; 0 < i; i--)
277 	xputchar(*c++);
278     output_raw = original_output_raw;
279 }
280 
281 
282 /* print_color():
283  */
284 static void
285 print_color(fname, len, suffix)
286     Char   *fname;
287     size_t  len;
288     int     suffix;
289 {
290     int     i;
291     char   *filename = short2str(fname);
292     char   *last = filename + len;
293     Str    *color = &variables[VFile].color;
294 
295     switch (suffix) {
296     case '>':			/* File is a symbolic link pointing to
297 				 * a directory */
298         color = &variables[VDir].color;
299 	    break;
300     case '+':			/* File is a hidden directory [aix] or
301 				 * context dependent [hpux] */
302     case ':':			/* File is network special [hpux] */
303         break;
304     default:
305 	for (i = 0; i < nvariables; i++)
306 	    if (variables[i].suffix != NOS &&
307 		variables[i].suffix == suffix) {
308 		color = &variables[i].color;
309 		break;
310 	    }
311 	if (i == nvariables) {
312 	    for (i = 0; i < nextensions; i++)
313 	        if (strncmp(last - extensions[i].extension.len,
314 			    extensions[i].extension.s,
315 			    extensions[i].extension.len) == 0) {
316 		  color = &extensions[i].color;
317 		break;
318 	    }
319 	}
320 	break;
321     }
322 
323     put_color(&variables[VLeft].color);
324     put_color(color);
325     put_color(&variables[VRight].color);
326 }
327 
328 
329 /* print_with_color():
330  */
331 void
332 print_with_color(filename, len, suffix)
333     Char   *filename;
334     size_t  len;
335     int    suffix;
336 {
337     if (color_context_lsmF &&
338 	(haderr ? (didfds ? is2atty : isdiagatty) :
339 	 (didfds ? is1atty : isoutatty))) {
340 	print_color(filename, len, suffix);
341 	xprintf("%S", filename);
342 	if (0 < variables[VEnd].color.len)
343 	    put_color(&variables[VEnd].color);
344 	else {
345 	    put_color(&variables[VLeft].color);
346 	    put_color(&variables[VNormal].color);
347 	    put_color(&variables[VRight].color);
348 	}
349 	xputchar(suffix);
350     }
351     else
352 	xprintf("%S%c", filename, suffix);
353 }
354 
355 
356 #endif /* COLOR_LS_F */
357