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