aboutsummaryrefslogtreecommitdiffstats
path: root/text_cmds/tr/tr.c
blob: 7bd2ca74405e0d96e96cd89475b87b381e15381d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
/*
 * Copyright (c) 1988, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/cdefs.h>

__FBSDID("$FreeBSD: src/usr.bin/tr/tr.c,v 1.24 2005/04/09 14:31:41 stefanf Exp $");

#ifndef lint
static const char copyright[] =
"@(#) Copyright (c) 1988, 1993\n\
	The Regents of the University of California.  All rights reserved.\n";
#endif

#ifndef lint
static const char sccsid[] = "@(#)tr.c	8.2 (Berkeley) 5/4/95";
#endif

#include <sys/types.h>

#include <ctype.h>
#include <err.h>
#include <limits.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <wchar.h>
#include <wctype.h>

#include "cmap.h"
#include "cset.h"
#include "extern.h"

STR s1 = { STRING1, NORMAL, 0, OOBCH, 0, { 0, OOBCH }, NULL, NULL };
STR s2 = { STRING2, NORMAL, 0, OOBCH, 0, { 0, OOBCH }, NULL, NULL };

static struct cset *setup(char *, STR *, int, int);
static void usage(void);

int
main(int argc, char **argv)
{
	static int carray[NCHARS_SB];
	struct cmap *map;
	struct cset *delete, *squeeze;
	int n, *p;
	int Cflag, cflag, dflag, sflag, isstring2;
	wint_t ch, cnt, lastch;

	(void)setlocale(LC_ALL, "");

	Cflag = cflag = dflag = sflag = 0;
	while ((ch = getopt(argc, argv, "Ccdsu")) != -1)
		switch((char)ch) {
		case 'C':
			Cflag = 1;
			cflag = 0;
			break;
		case 'c':
			cflag = 1;
			Cflag = 0;
			break;
		case 'd':
			dflag = 1;
			break;
		case 's':
			sflag = 1;
			break;
		case 'u':
			setbuf(stdout, (char *)NULL);
			break;
		case '?':
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	switch(argc) {
	case 0:
	default:
		usage();
		/* NOTREACHED */
	case 1:
		isstring2 = 0;
		if(!argv[0]) usage();
		break;
	case 2:
		isstring2 = 1;
		if(!argv[0] || !argv[1]) usage();
		break;
	}

	/*
	 * tr -ds [-Cc] string1 string2
	 * Delete all characters (or complemented characters) in string1.
	 * Squeeze all characters in string2.
	 */
	if (dflag && sflag) {
		if (!isstring2)
			usage();

		delete = setup(argv[0], &s1, cflag, Cflag);
		squeeze = setup(argv[1], &s2, 0, 0);

		for (lastch = OOBCH; (ch = getwchar()) != WEOF;)
			if (!cset_in(delete, ch) &&
			    (lastch != ch || !cset_in(squeeze, ch))) {
				lastch = ch;
				(void)putwchar(ch);
			}
		if (ferror(stdin))
			err(1, NULL);
		exit(0);
	}

	/*
	 * tr -d [-Cc] string1
	 * Delete all characters (or complemented characters) in string1.
	 */
	if (dflag) {
		if (isstring2)
			usage();

		delete = setup(argv[0], &s1, cflag, Cflag);

		while ((ch = getwchar()) != WEOF)
			if (!cset_in(delete, ch))
				(void)putwchar(ch);
		if (ferror(stdin))
			err(1, NULL);
		exit(0);
	}

	/*
	 * tr -s [-Cc] string1
	 * Squeeze all characters (or complemented characters) in string1.
	 */
	if (sflag && !isstring2) {
		squeeze = setup(argv[0], &s1, cflag, Cflag);

		for (lastch = OOBCH; (ch = getwchar()) != WEOF;)
			if (lastch != ch || !cset_in(squeeze, ch)) {
				lastch = ch;
				(void)putwchar(ch);
			}
		if (ferror(stdin))
			err(1, NULL);
		exit(0);
	}

	/*
	 * tr [-Ccs] string1 string2
	 * Replace all characters (or complemented characters) in string1 with
	 * the character in the same position in string2.  If the -s option is
	 * specified, squeeze all the characters in string2.
	 */
	if (!isstring2)
		usage();

	map = cmap_alloc();
	if (map == NULL)
		err(1, NULL);
	squeeze = cset_alloc();
	if (squeeze == NULL)
		err(1, NULL);

	s1.str = argv[0];

	if (Cflag || cflag) {
		cmap_default(map, OOBCH);
		if ((s2.str = strdup(argv[1])) == NULL)
			errx(1, "strdup(argv[1])");
	} else
		s2.str = argv[1];

	if (!next(&s2))
		errx(1, "empty string2");

	/*
	 * For -s result will contain only those characters defined
	 * as the second characters in each of the toupper or tolower
	 * pairs.
	 */

	/* If string2 runs out of characters, use the last one specified. */
	while (next(&s1)) {
	again:
		if (s1.state == CCLASS_LOWER &&
		    s2.state == CCLASS_UPPER &&
		    s1.cnt == 1 && s2.cnt == 1) {
			do {
				ch = towupper(s1.lastch);
				cmap_add(map, s1.lastch, ch);
				if (sflag && iswupper(ch))
					cset_add(squeeze, ch);
				if (!next(&s1))
					goto endloop;
			} while (s1.state == CCLASS_LOWER && s1.cnt > 1);
			/* skip upper set */
			do {
				if (!next(&s2))
					break;
			} while (s2.state == CCLASS_UPPER && s2.cnt > 1);
			goto again;
		} else if (s1.state == CCLASS_UPPER &&
			   s2.state == CCLASS_LOWER &&
			   s1.cnt == 1 && s2.cnt == 1) {
			do {
				ch = towlower(s1.lastch);
				cmap_add(map, s1.lastch, ch);
				if (sflag && iswlower(ch))
					cset_add(squeeze, ch);
				if (!next(&s1))
					goto endloop;
			} while (s1.state == CCLASS_UPPER && s1.cnt > 1);
			/* skip lower set */
			do {
				if (!next(&s2))
					break;
			} while (s2.state == CCLASS_LOWER && s2.cnt > 1);
			goto again;
		} else {
			cmap_add(map, s1.lastch, s2.lastch);
			if (sflag)
				cset_add(squeeze, s2.lastch);
		}
		(void)next(&s2);
	}
endloop:
	if (cflag || (Cflag && MB_CUR_MAX > 1)) {
		/*
		 * This is somewhat tricky: since the character set is
		 * potentially huge, we need to avoid allocating a map
		 * entry for every character. Our strategy is to set the
		 * default mapping to the last character of string #2
		 * (= the one that gets automatically repeated), then to
		 * add back identity mappings for characters that should
		 * remain unchanged. We don't waste space on identity mappings
		 * for non-characters with the -C option; those are simulated
		 * in the I/O loop.
		 */
		s2.str = argv[1];
		s2.state = NORMAL;
		for (cnt = 0; cnt < WCHAR_MAX; cnt++) {
			if (Cflag && !iswrune(cnt))
				continue;
			if (cmap_lookup(map, cnt) == OOBCH) {
				if (next(&s2))
					cmap_add(map, cnt, s2.lastch);
				if (sflag)
					cset_add(squeeze, s2.lastch);
			} else
				cmap_add(map, cnt, cnt);
			if ((s2.state == EOS || s2.state == INFINITE) &&
			    cnt >= cmap_max(map))
				break;
		}
		cmap_default(map, s2.lastch);
	} else if (Cflag) {
		for (p = carray, cnt = 0; cnt < NCHARS_SB; cnt++) {
			if (cmap_lookup(map, cnt) == OOBCH && iswrune(cnt))
				*p++ = cnt;
			else
				cmap_add(map, cnt, cnt);
		}
		n = p - carray;
		if (Cflag && n > 1)
			(void)mergesort(carray, n, sizeof(*carray), charcoll);

		s2.str = argv[1];
		s2.state = NORMAL;
		for (cnt = 0; cnt < n; cnt++) {
			(void)next(&s2);
			cmap_add(map, carray[cnt], s2.lastch);
			/*
			 * Chars taken from s2 can be different this time
			 * due to lack of complex upper/lower processing,
			 * so fill string2 again to not miss some.
			 */
			if (sflag)
				cset_add(squeeze, s2.lastch);
		}
	}

	cset_cache(squeeze);
	cmap_cache(map);

	if (sflag)
		for (lastch = OOBCH; (ch = getwchar()) != WEOF;) {
			if (!Cflag || iswrune(ch))
				ch = cmap_lookup(map, ch);
			if (lastch != ch || !cset_in(squeeze, ch)) {
				lastch = ch;
				(void)putwchar(ch);
			}
		}
	else
		while ((ch = getwchar()) != WEOF) {
			if (!Cflag || iswrune(ch))
				ch = cmap_lookup(map, ch);
			(void)putwchar(ch);
		}
	if (ferror(stdin))
		err(1, NULL);
	exit (0);
}

static struct cset *
setup(char *arg, STR *str, int cflag, int Cflag)
{
	struct cset *cs;

	cs = cset_alloc();
	if (cs == NULL)
		err(1, NULL);
	str->str = arg;
	while (next(str))
		cset_add(cs, str->lastch);
	if (Cflag)
		cset_addclass(cs, wctype("rune"), true);
	if (cflag || Cflag)
		cset_invert(cs);
	cset_cache(cs);
	return (cs);
}

int
charcoll(const void *a, const void *b)
{
	static char sa[2], sb[2];

	sa[0] = *(const int *)a;
	sb[0] = *(const int *)b;
	return (strcoll(sa, sb));
}

static void
usage(void)
{
	(void)fprintf(stderr, "%s\n%s\n%s\n%s\n",
		"usage: tr [-Ccsu] string1 string2",
		"       tr [-Ccu] -d string1",
		"       tr [-Ccu] -s string1",
		"       tr [-Ccu] -ds string1 string2");
	exit(1);
}