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