xref: /netbsd-src/usr.bin/fold/fold.c (revision f5d3fbbc6ff4a77159fb268d247bd94cb7d7e332)
1 /*	$NetBSD: fold.c,v 1.7 1997/10/18 15:02:18 lukem 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.7 1997/10/18 15:02:18 lukem 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 			if (split_words) {
159 				for (i = 0, last_space = -1; i < indx; i++)
160 					if(buf[i] == ' ') last_space = i;
161 			}
162 
163 			if (split_words && last_space != -1) {
164 				last_space++;
165 
166 				fwrite (buf, 1, last_space, stdout);
167 				memmove (buf, buf+last_space, indx-last_space);
168 
169 				indx -= last_space;
170 				col = 0;
171 				for (i = 0; i < indx; i++) {
172 					col = new_column_position (col, ch);
173 				}
174 			} else {
175 				fwrite (buf, 1, indx, stdout);
176 				col = indx = 0;
177 			}
178 			putchar('\n');
179 
180 			/* calculate the column position for the next line. */
181 			col = new_column_position (col, ch);
182 		}
183 
184 		if (indx + 1 > buf_max) {
185 			/* Allocate buffer in LINE_MAX increments */
186 			buf_max += 2048;
187 			if((buf = realloc (buf, buf_max)) == NULL) {
188 				err (1, "realloc");
189 				/* NOTREACHED */
190 			}
191 		}
192 		buf[indx++] = ch;
193 	}
194 
195 	if (indx != 0)
196 		fwrite (buf, 1, indx, stdout);
197 }
198 
199 /*
200  * calculate the column position
201  */
202 static int
203 new_column_position (col, ch)
204 	int col;
205 	int ch;
206 {
207 	if (!count_bytes) {
208 		switch (ch) {
209 		case '\b':
210 			if (col > 0)
211 				--col;
212 			break;
213 		case '\r':
214 			col = 0;
215 			break;
216 		case '\t':
217 			col = (col + 8) & ~7;
218 			break;
219 		default:
220 			++col;
221 			break;
222 		}
223 	} else {
224 		++col;
225 	}
226 
227 	return col;
228 }
229