BSD 3 development
[unix-history] / usr / src / cmd / expand.c
CommitLineData
45964d3d
BJ
1#include <stdio.h>
2/*
3 * expand - expand tabs to equivalent spaces
4 */
5char obuf[BUFSIZ];
6int nstops;
7int tabstops[100];
8
9main(argc, argv)
10 int argc;
11 char *argv[];
12{
13 register int c, column;
14 register int n;
15
16 setbuf(stdout, obuf);
17 argc--, argv++;
18 do {
19 while (argc > 0 && argv[0][0] == '-') {
20 getstops(argv[0]);
21 argc--, argv++;
22 }
23 if (argc > 0) {
24 if (freopen(argv[0], "r", stdin) == NULL) {
25 perror(argv[0]);
26 exit(1);
27 }
28 argc--, argv++;
29 }
30 column = 0;
31 for (;;) {
32 c = getc(stdin);
33 if (c == -1)
34 break;
35 switch (c) {
36
37 case '\t':
38 if (nstops == 0) {
39 do {
40 putchar(' ');
41 column++;
42 } while (column & 07);
43 continue;
44 }
45 if (nstops == 1) {
46 do {
47 putchar(' ');
48 column++;
49 } while (((column - 1) % tabstops[0]) != (tabstops[0] - 1));
50 continue;
51 }
52 for (n = 0; n < nstops; n++)
53 if (tabstops[n] > column)
54 break;
55 if (n == nstops) {
56 putchar(' ');
57 column++;
58 continue;
59 }
60 while (column < tabstops[n]) {
61 putchar(' ');
62 column++;
63 }
64 continue;
65
66 case '\b':
67 if (column)
68 column--;
69 putchar('\b');
70 continue;
71
72 default:
73 putchar(c);
74 column++;
75 continue;
76
77 case '\n':
78 putchar(c);
79 column = 0;
80 continue;
81 }
82 }
83 } while (argc > 0);
84 exit(0);
85}
86
87getstops(cp)
88 register char *cp;
89{
90 register int i;
91
92 nstops = 0;
93 cp++;
94 for (;;) {
95 i = 0;
96 while (*cp >= '0' && *cp <= '9')
97 i = i * 10 + *cp++ - '0';
98 if (i <= 0 || i > 256) {
99bad:
100 fprintf(stderr, "Bad tab stop spec\n");
101 exit(1);
102 }
103 if (nstops > 0 && i <= tabstops[nstops])
104 goto bad;
105 tabstops[nstops++] = i;
106 if (*cp == 0)
107 break;
108 if (*cp++ != ',')
109 goto bad;
110 }
111}