xref: /dragonfly/usr.bin/fold/fold.c (revision 1de703da)
1 /*-
2  * Copyright (c) 1990, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Kevin Ruddy.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  * @(#) Copyright (c) 1990, 1993 The Regents of the University of California.  All rights reserved.
37  * @(#)fold.c	8.1 (Berkeley) 6/6/93
38  * $FreeBSD: src/usr.bin/fold/fold.c,v 1.4.2.3 2002/07/11 01:01:44 tjr Exp $
39  * $DragonFly: src/usr.bin/fold/fold.c,v 1.2 2003/06/17 04:29:26 dillon Exp $
40  */
41 
42 #include <ctype.h>
43 #include <err.h>
44 #include <limits.h>
45 #include <locale.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <unistd.h>
50 
51 #define	DEFLINEWIDTH	80
52 
53 void fold(int);
54 static int newpos(int, int);
55 static void usage(void);
56 
57 int bflag;			/* Count bytes, not columns */
58 int sflag;			/* Split on word boundaries */
59 
60 int
61 main(argc, argv)
62 	int argc;
63 	char **argv;
64 {
65 	register int ch;
66 	int rval, width;
67 	char *p;
68 
69 	(void) setlocale(LC_CTYPE, "");
70 
71 	width = -1;
72 	while ((ch = getopt(argc, argv, "0123456789bsw:")) != -1)
73 		switch (ch) {
74 		case 'b':
75 			bflag = 1;
76 			break;
77 		case 's':
78 			sflag = 1;
79 			break;
80 		case 'w':
81 			if ((width = atoi(optarg)) <= 0) {
82 				errx(1, "illegal width value");
83 			}
84 			break;
85 		case '0': case '1': case '2': case '3': case '4':
86 		case '5': case '6': case '7': case '8': case '9':
87 			if (width == -1) {
88 				p = argv[optind - 1];
89 				if (p[0] == '-' && p[1] == ch && !p[2])
90 					width = atoi(++p);
91 				else
92 					width = atoi(argv[optind] + 1);
93 			}
94 			break;
95 		default:
96 			usage();
97 		}
98 	argv += optind;
99 	argc -= optind;
100 
101 	if (width == -1)
102 		width = DEFLINEWIDTH;
103 	rval = 0;
104 	if (!*argv)
105 		fold(width);
106 	else for (; *argv; ++argv)
107 		if (!freopen(*argv, "r", stdin)) {
108 			warn("%s", *argv);
109 			rval = 1;
110 		} else
111 			fold(width);
112 	exit(rval);
113 }
114 
115 static void
116 usage()
117 {
118 	(void)fprintf(stderr, "usage: fold [-bs] [-w width] [file ...]\n");
119 	exit(1);
120 }
121 
122 /*
123  * Fold the contents of standard input to fit within WIDTH columns (or bytes)
124  * and write to standard output.
125  *
126  * If sflag is set, split the line at the last space character on the line.
127  * This flag necessitates storing the line in a buffer until the current
128  * column > width, or a newline or EOF is read.
129  *
130  * The buffer can grow larger than WIDTH due to backspaces and carriage
131  * returns embedded in the input stream.
132  */
133 void
134 fold(width)
135 	register int width;
136 {
137 	static char *buf;
138 	static int buf_max;
139 	int ch, col, i, indx, space;
140 
141 	col = indx = 0;
142 	while ((ch = getchar()) != EOF) {
143 		if (ch == '\n') {
144 			if (indx != 0)
145 				fwrite(buf, 1, indx, stdout);
146 			putchar('\n');
147 			col = indx = 0;
148 			continue;
149 		}
150 		if ((col = newpos(col, ch)) > width) {
151 			if (sflag) {
152 				i = indx;
153 				while (--i >= 0 && !isblank((unsigned char)buf[i]))
154 					;
155 				space = i;
156 			}
157 			if (sflag && space != -1) {
158 				space++;
159 				fwrite(buf, 1, space, stdout);
160 				memmove(buf, buf + space, indx - space);
161 				indx -= space;
162 				col = 0;
163 				for (i = 0; i < indx; i++)
164 					col = newpos(col,
165 					    (unsigned char)buf[i]);
166 			} else {
167 				fwrite(buf, 1, indx, stdout);
168 				col = indx = 0;
169 			}
170 			putchar('\n');
171 			col = newpos(col, ch);
172 		}
173 		if (indx + 1 > buf_max) {
174 			buf_max += LINE_MAX;
175 			if ((buf = realloc(buf, buf_max)) == NULL)
176 				err(1, "realloc()");
177 		}
178 		buf[indx++] = ch;
179 	}
180 
181 	if (indx != 0)
182 		fwrite(buf, 1, indx, stdout);
183 }
184 
185 /*
186  * Update the current column position for a character.
187  */
188 static int
189 newpos(col, ch)
190 	int col, ch;
191 {
192 
193 	if (bflag)
194 		++col;
195 	else
196 		switch (ch) {
197 		case '\b':
198 			if (col > 0)
199 				--col;
200 			break;
201 		case '\r':
202 			col = 0;
203 			break;
204 		case '\t':
205 			col = (col + 8) & ~7;
206 			break;
207 		default:
208 			if (isprint(ch))
209 				++col;
210 			break;
211 		}
212 
213 	return (col);
214 }
215