tw.color.c revision 131962
1/* $Header: /src/pub/tcsh/tw.color.c,v 1.12 2004/01/23 16:21: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
35RCSID("$Id: tw.color.c,v 1.12 2004/01/23 16:21:33 christos Exp $")
36
37#include "tw.h"
38#include "ed.h"
39#include "tc.h"
40
41#ifdef COLOR_LS_F
42
43typedef struct {
44    char   *s;
45    int     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
56typedef struct {
57    const char suffix;
58    const char *variable;
59    Str     color;
60    Str     defaultcolor;
61} Variable;
62
63static 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};
84
85enum FileType {
86    VDir, VSym, VOrph, VPipe, VSock, VDoor, VBlock, VChr, VExe,
87    VFile, VNormal, VMiss, VLeft, VRight, VEnd
88};
89
90#define nvariables (sizeof(variables)/sizeof(variables[0]))
91
92typedef struct {
93    Str     extension;	/* file extension */
94    Str     color;	/* color string */
95} Extension;
96
97static Extension *extensions = NULL;
98static int nextensions = 0;
99
100static char *colors = NULL;
101bool	     color_context_ls = FALSE;	/* do colored ls */
102static bool  color_context_lsmF = FALSE;	/* do colored ls-F */
103
104static bool getstring __P((char **, const Char **, Str *, int));
105static void put_color __P((Str *));
106static void print_color __P((Char *, size_t, int));
107
108/* set_color_context():
109 */
110void
111set_color_context()
112{
113    struct varent *vp = adrof(STRcolor);
114
115    if (vp == NULL || vp->vec == NULL) {
116	color_context_ls = FALSE;
117	color_context_lsmF = FALSE;
118    } else if (!vp->vec[0] || vp->vec[0][0] == '\0') {
119	color_context_ls = TRUE;
120	color_context_lsmF = TRUE;
121    } else {
122	size_t i;
123
124	color_context_ls = FALSE;
125	color_context_lsmF = FALSE;
126	for (i = 0; vp->vec[i]; i++)
127	    if (Strcmp(vp->vec[i], STRls) == 0)
128		color_context_ls = TRUE;
129	    else if (Strcmp(vp->vec[i], STRlsmF) == 0)
130		color_context_lsmF = TRUE;
131    }
132}
133
134
135/* getstring():
136 */
137static  bool
138getstring(dp, sp, pd, f)
139    char        **dp;		/* dest buffer */
140    const Char  **sp;		/* source buffer */
141    Str          *pd;		/* pointer to dest buffer */
142    int           f;		/* final character */
143{
144    const Char *s = *sp;
145    char *d = *dp;
146    int sc;
147
148    while (*s && (*s & CHAR) != f && (*s & CHAR) != ':') {
149	if ((*s & CHAR) == '\\' || (*s & CHAR) == '^') {
150	    if ((sc = parseescape(&s)) == -1)
151		return 0;
152	    else
153		*d++ = (char) sc;
154	}
155	else
156	    *d++ = *s++ & CHAR;
157    }
158
159    pd->s = *dp;
160    pd->len = (int) (d - *dp);
161    *sp = s;
162    *dp = d;
163    return *s == f;
164}
165
166
167/* parseLS_COLORS():
168 *	Parse the LS_COLORS environment variable
169 */
170void
171parseLS_COLORS(value)
172    Char   *value;		/* LS_COLOR variable's value */
173{
174    int     i;
175    size_t  len;
176    const Char   *v;		/* pointer in value */
177    char   *c;			/* pointer in colors */
178    Extension *e;		/* pointer in extensions */
179    jmp_buf_t osetexit;
180
181    (void) &e;
182
183    /* init */
184    if (extensions)
185        xfree((ptr_t) extensions);
186    for (i = 0; i < nvariables; i++)
187	variables[i].color = variables[i].defaultcolor;
188    colors = NULL;
189    extensions = NULL;
190    nextensions = 0;
191
192    if (value == NULL)
193	return;
194
195    len = Strlen(value);
196    /* allocate memory */
197    i = 1;
198    for (v = value; *v; v++)
199	if ((*v & CHAR) == ':')
200	    i++;
201    extensions = (Extension *) xmalloc((size_t) (len + i * sizeof(Extension)));
202    colors = i * sizeof(Extension) + (char *)extensions;
203    nextensions = 0;
204
205    /* init pointers */
206    v = value;
207    c = colors;
208    e = &extensions[0];
209
210    /* Prevent from crashing if unknown parameters are given. */
211
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 (variables[i].variable[0] == (v[0] & CHAR) &&
238			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    resexit(osetexit);
256
257    nextensions = (int) (e - extensions);
258}
259
260
261/* put_color():
262 */
263static void
264put_color(color)
265    Str    *color;
266{
267    extern bool output_raw;	/* PWP: in sh.print.c */
268    size_t  i;
269    char   *c = color->s;
270    bool    original_output_raw = output_raw;
271
272    output_raw = TRUE;
273    for (i = color->len; 0 < i; i--)
274	xputchar(*c++);
275    output_raw = original_output_raw;
276}
277
278
279/* print_color():
280 */
281static void
282print_color(fname, len, suffix)
283    Char   *fname;
284    size_t  len;
285    int     suffix;
286{
287    int     i;
288    char   *filename = short2str(fname);
289    char   *last = filename + len;
290    Str    *color = &variables[VFile].color;
291
292    switch (suffix) {
293    case '>':			/* File is a symbolic link pointing to
294				 * a directory */
295        color = &variables[VDir].color;
296	    break;
297    case '+':			/* File is a hidden directory [aix] or
298				 * context dependent [hpux] */
299    case ':':			/* File is network special [hpux] */
300        break;
301    default:
302	for (i = 0; i < nvariables; i++)
303	    if (variables[i].suffix != NOS &&
304		variables[i].suffix == suffix) {
305		color = &variables[i].color;
306		break;
307	    }
308	if (i == nvariables) {
309	    for (i = 0; i < nextensions; i++)
310	        if (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 */
328void
329print_with_color(filename, len, suffix)
330    Char   *filename;
331    size_t  len;
332    int    suffix;
333{
334    if (color_context_lsmF &&
335	(haderr ? (didfds ? is2atty : isdiagatty) :
336	 (didfds ? is1atty : isoutatty))) {
337	print_color(filename, len, suffix);
338	xprintf("%S", filename);
339	if (0 < variables[VEnd].color.len)
340	    put_color(&variables[VEnd].color);
341	else {
342	    put_color(&variables[VLeft].color);
343	    put_color(&variables[VNormal].color);
344	    put_color(&variables[VRight].color);
345	}
346	xputchar(suffix);
347    }
348    else
349	xprintf("\045S%c", filename, suffix);
350}
351
352
353#endif /* COLOR_LS_F */
354