tw.color.c revision 83098
1/* $Header: /src/pub/tcsh/tw.color.c,v 1.8 2001/03/18 19:06:32 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. 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
39RCSID("$Id: tw.color.c,v 1.8 2001/03/18 19:06:32 christos Exp $")
40
41#include "tw.h"
42#include "ed.h"
43#include "tc.h"
44
45#ifdef COLOR_LS_F
46
47typedef 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
60typedef struct {
61    const char suffix;
62    const char *variable;
63    Str     color;
64    Str     defaultcolor;
65} Variable;
66
67static 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('>', "do", "01;35"),	/* Door (solaris fast ipc mechanism)  */
74    VAR('#', "bd", "01;33"),	/* Block device */
75    VAR('%', "cd", "01;33"),	/* Character device */
76    VAR('*', "ex", "01;32"),	/* Executable file */
77    VAR(NOS, "fi", "0"),	/* Regular file */
78    VAR(NOS, "no", "0"),	/* Normal (non-filename) text */
79    VAR(NOS, "mi", ""),		/* Missing file (defaults to fi) */
80#ifdef IS_ASCII
81    VAR(NOS, "lc", "\033["),	/* Left code (ASCII) */
82#else
83    VAR(NOS, "lc", "\x27["),	/* Left code (EBCDIC)*/
84#endif
85    VAR(NOS, "rc", "m"),	/* Right code */
86    VAR(NOS, "ec", ""),		/* End code (replaces lc+no+rc) */
87};
88
89enum FileType {
90    VDir, VSym, VOrph, VPipe, VSock, VDoor, VBlock, VChr, VExe,
91    VFile, VNormal, VMiss, VLeft, VRight, VEnd
92};
93
94#define nvariables (sizeof(variables)/sizeof(variables[0]))
95
96typedef struct {
97    Str     extension;	/* file extension */
98    Str     color;	/* color string */
99} Extension;
100
101static Extension *extensions = NULL;
102static int nextensions = 0;
103
104static char *colors = NULL;
105bool	     color_context_ls = FALSE;	/* do colored ls */
106static bool  color_context_lsmF = FALSE;	/* do colored ls-F */
107
108static bool getstring __P((char **, const Char **, Str *, int));
109static void put_color __P((Str *));
110static void print_color __P((Char *, size_t, int));
111
112/* set_color_context():
113 */
114void
115set_color_context()
116{
117    struct varent *vp = adrof(STRcolor);
118
119    if (!vp) {
120	color_context_ls = FALSE;
121	color_context_lsmF = FALSE;
122    }
123    else if (!vp->vec[0] || vp->vec[0][0] == '\0') {
124	color_context_ls = TRUE;
125	color_context_lsmF = TRUE;
126    }
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 */
143static  bool
144getstring(dp, sp, pd, f)
145    char        **dp;		/* dest buffer */
146    const Char  **sp;		/* source buffer */
147    Str          *pd;		/* pointer to dest buffer */
148    int           f;		/* final character */
149{
150    const Char *s = *sp;
151    char *d = *dp;
152    int sc;
153
154    while (*s && (*s & CHAR) != f && (*s & CHAR) != ':') {
155	if ((*s & CHAR) == '\\' || (*s & CHAR) == '^') {
156	    if ((sc = parseescape(&s)) == -1)
157		return 0;
158	    else
159		*d++ = (char) sc;
160	}
161	else
162	    *d++ = *s++ & CHAR;
163    }
164
165    pd->s = *dp;
166    pd->len = (int) (d - *dp);
167    *sp = s;
168    *dp = d;
169    return *s == f;
170}
171
172
173/* parseLS_COLORS():
174 *	Parse the LS_COLORS environment variable
175 */
176void
177parseLS_COLORS(value)
178    Char   *value;		/* LS_COLOR variable's value */
179{
180    int     i;
181    size_t  len;
182    const Char   *v;		/* pointer in value */
183    char   *c;			/* pointer in colors */
184    Extension *e;		/* pointer in extensions */
185    jmp_buf_t osetexit;
186
187    /* init */
188    if (extensions)
189        xfree((ptr_t) extensions);
190    for (i = 0; i < nvariables; i++)
191	variables[i].color = variables[i].defaultcolor;
192    colors = NULL;
193    extensions = NULL;
194    nextensions = 0;
195
196    if (value == NULL)
197	return;
198
199    len = Strlen(value);
200    /* allocate memory */
201    i = 1;
202    for (v = value; *v; v++)
203	if ((*v & CHAR) == ':')
204	    i++;
205    extensions = (Extension *) xmalloc((size_t) (len + i * sizeof(Extension)));
206    colors = i * sizeof(Extension) + (char *)extensions;
207    nextensions = 0;
208
209    /* init pointers */
210    v = value;
211    c = colors;
212    e = &extensions[0];
213
214    /* Prevent from crashing if unknown parameters are given. */
215
216    getexit(osetexit);
217
218    if (setexit() == 0) {
219
220    /* parse */
221    while (*v) {
222	switch (*v & CHAR) {
223	case ':':
224	    v++;
225	    continue;
226
227	case '*':		/* :*ext=color: */
228	    v++;
229	    if (getstring(&c, &v, &e->extension, '=') &&
230		0 < e->extension.len) {
231		v++;
232		getstring(&c, &v, &e->color, ':');
233		e++;
234		continue;
235	    }
236	    break;
237
238	default:		/* :vl=color: */
239	    if (v[0] && v[1] && (v[2] & CHAR) == '=') {
240		for (i = 0; i < nvariables; i++)
241		    if (variables[i].variable[0] == (v[0] & CHAR) &&
242			variables[i].variable[1] == (v[1] & CHAR))
243			break;
244		if (i < nvariables) {
245		    v += 3;
246		    getstring(&c, &v, &variables[i].color, ':');
247		    continue;
248		}
249		else
250		    stderror(ERR_BADCOLORVAR, v[0], v[1]);
251	    }
252	    break;
253	}
254	while (*v && (*v & CHAR) != ':')
255	    v++;
256    }
257    }
258
259    resexit(osetexit);
260
261    nextensions = (int) (e - extensions);
262}
263
264
265/* put_color():
266 */
267static void
268put_color(color)
269    Str    *color;
270{
271    extern bool output_raw;	/* PWP: in sh.print.c */
272    size_t  i;
273    char   *c = color->s;
274    bool    original_output_raw = output_raw;
275
276    output_raw = TRUE;
277    for (i = color->len; 0 < i; i--)
278	xputchar(*c++);
279    output_raw = original_output_raw;
280}
281
282
283/* print_color():
284 */
285static void
286print_color(fname, len, suffix)
287    Char   *fname;
288    size_t  len;
289    int     suffix;
290{
291    int     i;
292    char   *filename = short2str(fname);
293    char   *last = filename + len;
294    Str    *color = &variables[VFile].color;
295
296    switch (suffix) {
297    case '>':			/* File is a symbolic link pointing to
298				 * a directory */
299        color = &variables[VDir].color;
300	    break;
301    case '+':			/* File is a hidden directory [aix] or
302				 * context dependent [hpux] */
303    case ':':			/* File is network special [hpux] */
304        break;
305    default:
306	for (i = 0; i < nvariables; i++)
307	    if (variables[i].suffix != NOS &&
308		variables[i].suffix == suffix) {
309		color = &variables[i].color;
310		break;
311	    }
312	if (i == nvariables) {
313	    for (i = 0; i < nextensions; i++)
314	        if (strncmp(last - extensions[i].extension.len,
315			    extensions[i].extension.s,
316			    extensions[i].extension.len) == 0) {
317		  color = &extensions[i].color;
318		break;
319	    }
320	}
321	break;
322    }
323
324    put_color(&variables[VLeft].color);
325    put_color(color);
326    put_color(&variables[VRight].color);
327}
328
329
330/* print_with_color():
331 */
332void
333print_with_color(filename, len, suffix)
334    Char   *filename;
335    size_t  len;
336    int    suffix;
337{
338    if (color_context_lsmF &&
339	(haderr ? (didfds ? is2atty : isdiagatty) :
340	 (didfds ? is1atty : isoutatty))) {
341	print_color(filename, len, suffix);
342	xprintf("%S", filename);
343	if (0 < variables[VEnd].color.len)
344	    put_color(&variables[VEnd].color);
345	else {
346	    put_color(&variables[VLeft].color);
347	    put_color(&variables[VNormal].color);
348	    put_color(&variables[VRight].color);
349	}
350	xputchar(suffix);
351    }
352    else
353	xprintf("%S%c", filename, suffix);
354}
355
356
357#endif /* COLOR_LS_F */
358