xref: /original-bsd/usr.bin/unexpand/unexpand.c (revision 04ace372)
1 /*
2  * Copyright (c) 1980 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms are permitted
6  * provided that the above copyright notice and this paragraph are
7  * duplicated in all such forms and that any documentation,
8  * advertising materials, and other materials related to such
9  * distribution and use acknowledge that the software was developed
10  * by the University of California, Berkeley.  The name of the
11  * University may not be used to endorse or promote products derived
12  * from this software without specific prior written permission.
13  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16  */
17 
18 #ifndef lint
19 char copyright[] =
20 "@(#) Copyright (c) 1980 The Regents of the University of California.\n\
21  All rights reserved.\n";
22 #endif /* not lint */
23 
24 #ifndef lint
25 static char sccsid[] = "@(#)unexpand.c	5.2 (Berkeley) 10/26/88";
26 #endif /* not lint */
27 
28 /*
29  * unexpand - put tabs into a file replacing blanks
30  */
31 #include <stdio.h>
32 
33 char	genbuf[BUFSIZ];
34 char	linebuf[BUFSIZ];
35 int	all;
36 
37 main(argc, argv)
38 	int argc;
39 	char *argv[];
40 {
41 	register char *cp;
42 
43 	argc--, argv++;
44 	if (argc > 0 && argv[0][0] == '-') {
45 		if (strcmp(argv[0], "-a") != 0) {
46 			fprintf(stderr, "usage: unexpand [ -a ] file ...\n");
47 			exit(1);
48 		}
49 		all++;
50 		argc--, argv++;
51 	}
52 	do {
53 		if (argc > 0) {
54 			if (freopen(argv[0], "r", stdin) == NULL) {
55 				perror(argv[0]);
56 				exit(1);
57 			}
58 			argc--, argv++;
59 		}
60 		while (fgets(genbuf, BUFSIZ, stdin) != NULL) {
61 			for (cp = linebuf; *cp; cp++)
62 				continue;
63 			if (cp > linebuf)
64 				cp[-1] = 0;
65 			tabify(all);
66 			printf("%s", linebuf);
67 		}
68 	} while (argc > 0);
69 	exit(0);
70 }
71 
72 tabify(c)
73 	char c;
74 {
75 	register char *cp, *dp;
76 	register int dcol;
77 	int ocol;
78 
79 	ocol = 0;
80 	dcol = 0;
81 	cp = genbuf, dp = linebuf;
82 	for (;;) {
83 		switch (*cp) {
84 
85 		case ' ':
86 			dcol++;
87 			break;
88 
89 		case '\t':
90 			dcol += 8;
91 			dcol &= ~07;
92 			break;
93 
94 		default:
95 			while (((ocol + 8) &~ 07) <= dcol) {
96 				if (ocol + 1 == dcol)
97 					break;
98 				*dp++ = '\t';
99 				ocol += 8;
100 				ocol &= ~07;
101 			}
102 			while (ocol < dcol) {
103 				*dp++ = ' ';
104 				ocol++;
105 			}
106 			if (*cp == 0 || c == 0) {
107 				strcpy(dp, cp);
108 				return;
109 			}
110 			*dp++ = *cp;
111 			ocol++, dcol++;
112 		}
113 		cp++;
114 	}
115 }
116