summaryrefslogtreecommitdiff
path: root/src/tr.c
blob: 5dad8234bc78782f4d10522ccad17985818c2ea3 (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

#include <stdio.h>
#include <wchar.h>
#include <wctype.h>
#include <unistd.h>
#include <assert.h>


int index_of(wchar_t c, char *s)
{
	mbstate_t mbst, mbst_init = { };
	int i=0;
	char *z;

	while (*s) {
		if (s[0] == '[' && s[1] == ':') {
			wctype_t type;
			char typename[32];
			z = strchr(s, ':');
			if (!z || z[1] != ']' || z-s >= sizeof typename) {
				ERROR;
			}
			memcpy(typename, s, z-s);
			typename[z-s] = 0;
			type = wctype(typename);
			if (!type)
				ERROR;
			if (iswctype(c, type))
				return i;
		}

		if (mbrtowc(&wc, s, MB_LEN_MAX, &mbst) >= (size_t)-2)
			return ERROR;
	}
}


char *parse_repl(char *s1, char *s2)
{
	struct map *head, *tail;
	int i;
	for (i=j=0; s1[i]; i++) {
		tail->next = malloc(sizeof(struct map));
		tail = tail->next;

		if (!strncmp(s1, "[:upper:]", 9)
		 && !strncmp(s2, "[:lower:]", 9)) {
			tail->from = tail->to = 0;
			s1 += 9; s2 += 9;
		}
		if (!strncmp(s1, "[:lower:]", 9)
		 && !strncmp(s2, "[:upper:]", 9)) {
			tail->from = tail->to = 1;
			s1 += 9; s2 += 9;
		}
	}
}


int main(int argc, char *argv[])
{
	int o;
	int cmpl = 0, del = 0, sqez = 0, repl = 1;
	wchar_t ch, pv = WEOF;
	char b[MB_LEN_MAX];
	int i, j;
	mbstate_t mbst, mbst_init = { };

	setlocale(LC_CTYPE, "");

	while ((o = getopt(argc, argv, "Ccds")) != EOF)
	{
		switch (o)
		{
		case 'C':
		case 'c':
			cmpl = 1;
			break;
		case 'd':
			del = 1;
			break;
		case 's':
			sqez = 1;
			break;
		default:
			return 1;
		}
	}
	string1 = argc-optind >= 1 ? argv[optind] : "";
	string2 = argc-optind >= 2 ? argv[optind+1] : "";
	if (!string2 || del) repl = 0;

	i=0;
	while (b[i] = getchar() != EOF) {
retry:
		switch (mbrtowc(&wc, b+i, 1, &mbst)) {
		case -1:
			if (!i) {
				putchar(b[0]);
				mbst = mbst_init;
				continue;
			}
			for (j=0; j<i; j++)
				putchar(b[j]);
			b[i=0] = b[j];
			mbst = mbst_init;
			goto retry;
		case -2:
			i++;
			continue;
		}
		b[++i] = 0;
	}



	return 0;
}