xref: /netbsd-src/usr.bin/fold/fold.c (revision ce0bb6e8d2e560ecacbe865a848624f94498063b)
1 /*-
2  * Copyright (c) 1990 The Regents of the University of California.
3  * 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 
37 #ifndef lint
38 char copyright[] =
39 "@(#) Copyright (c) 1990 The Regents of the University of California.\n\
40  All rights reserved.\n";
41 #endif /* not lint */
42 
43 #ifndef lint
44 /*static char sccsid[] = "from: @(#)fold.c	5.5 (Berkeley) 6/1/90";*/
45 static char rcsid[] = "$Id: fold.c,v 1.5 1993/10/13 18:34:13 jtc Exp $";
46 #endif /* not lint */
47 
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <unistd.h>
52 #include <err.h>
53 
54 #define	DEFLINEWIDTH	80
55 
56 static void fold ();
57 static int new_column_position ();
58 int count_bytes = 0;
59 int split_words = 0;
60 
61 int
62 main(argc, argv)
63 	int argc;
64 	char **argv;
65 {
66 	register int ch;
67 	int width;
68 	char *p;
69 
70 	width = -1;
71 	while ((ch = getopt(argc, argv, "0123456789bsw:")) != -1)
72 		switch (ch) {
73 		case 'b':
74 			count_bytes = 1;
75 			break;
76 		case 's':
77 			split_words = 1;
78 			break;
79 		case 'w':
80 			if ((width = atoi(optarg)) <= 0) {
81 				(void)fprintf(stderr,
82 				    "fold: illegal width value.\n");
83 				exit(1);
84 			}
85 			break;
86 		case '0': case '1': case '2': case '3': case '4':
87 		case '5': case '6': case '7': case '8': case '9':
88 			if (width == -1) {
89 				p = argv[optind - 1];
90 				if (p[0] == '-' && p[1] == ch && !p[2])
91 					width = atoi(++p);
92 				else
93 					width = atoi(argv[optind] + 1);
94 			}
95 			break;
96 		default:
97 			(void)fprintf(stderr,
98 			    "usage: fold [-bs] [-w width] [file ...]\n");
99 			exit(1);
100 		}
101 	argv += optind;
102 	argc -= optind;
103 
104 	if (width == -1)
105 		width = DEFLINEWIDTH;
106 
107 	if (!*argv)
108 		fold(width);
109 	else for (; *argv; ++argv)
110 		if (!freopen(*argv, "r", stdin)) {
111 			err (1, "%s", *argv);
112 			/* NOTREACHED */
113 		} else
114 			fold(width);
115 	exit(0);
116 }
117 
118 /*
119  * Fold the contents of standard input to fit within WIDTH columns
120  * (or bytes) and write to standard output.
121  *
122  * If split_words is set, split the line at the last space character
123  * on the line.  This flag necessitates storing the line in a buffer
124  * until the current column > width, or a newline or EOF is read.
125  *
126  * The buffer can grow larger than WIDTH due to backspaces and carriage
127  * returns embedded in the input stream.
128  */
129 static void
130 fold(width)
131 	register int width;
132 {
133 	static char *buf = NULL;
134 	static int   buf_max = 0;
135 	register int ch, col;
136 	register int indx;
137 
138 	col = indx = 0;
139 	while ((ch = getchar()) != EOF) {
140 		if (ch == '\n') {
141 			if (indx != 0)
142 				fwrite (buf, 1, indx, stdout);
143 			putchar('\n');
144 			col = indx = 0;
145 			continue;
146 		}
147 
148 		col = new_column_position (col, ch);
149 		if (col > width) {
150 			int i, last_space;
151 
152 			if (split_words) {
153 				for (i = 0, last_space = -1; i < indx; i++)
154 					if(buf[i] == ' ') last_space = i;
155 			}
156 
157 			if (split_words && last_space != -1) {
158 				last_space++;
159 
160 				fwrite (buf, 1, last_space, stdout);
161 				memmove (buf, buf+last_space, indx-last_space);
162 
163 				indx -= last_space;
164 				col = 0;
165 				for (i = 0; i < indx; i++) {
166 					col = new_column_position (col, ch);
167 				}
168 			} else {
169 				fwrite (buf, 1, indx, stdout);
170 				col = indx = 0;
171 			}
172 			putchar('\n');
173 
174 			/* calculate the column position for the next line. */
175 			col = new_column_position (col, ch);
176 		}
177 
178 		if (indx + 1 > buf_max) {
179 			/* Allocate buffer in LINE_MAX increments */
180 			buf_max += 2048;
181 			if((buf = realloc (buf, buf_max)) == NULL) {
182 				err (1, NULL);
183 				/* NOTREACHED */
184 			}
185 		}
186 		buf[indx++] = ch;
187 	}
188 
189 	if (indx != 0)
190 		fwrite (buf, 1, indx, stdout);
191 }
192 
193 /*
194  * calculate the column position
195  */
196 static int
197 new_column_position (col, ch)
198 	int col;
199 	int ch;
200 {
201 	if (!count_bytes) {
202 		switch (ch) {
203 		case '\b':
204 			if (col > 0)
205 				--col;
206 			break;
207 		case '\r':
208 			col = 0;
209 			break;
210 		case '\t':
211 			col = (col + 8) & ~7;
212 			break;
213 		default:
214 			++col;
215 			break;
216 		}
217 	} else {
218 		++col;
219 	}
220 
221 	return col;
222 }
223