fold.c revision 200462
1106686Stjr/*-
2128005Stjr * Copyright (c) 1990, 1993
3106686Stjr *	The Regents of the University of California.  All rights reserved.
4106686Stjr *
5106686Stjr * This code is derived from software contributed to Berkeley by
6106686Stjr * Kevin Ruddy.
7106686Stjr *
8106686Stjr * Redistribution and use in source and binary forms, with or without
9106686Stjr * modification, are permitted provided that the following conditions
10106686Stjr * are met:
11106686Stjr * 1. Redistributions of source code must retain the above copyright
12106686Stjr *    notice, this list of conditions and the following disclaimer.
13106686Stjr * 2. Redistributions in binary form must reproduce the above copyright
14106686Stjr *    notice, this list of conditions and the following disclaimer in the
15106686Stjr *    documentation and/or other materials provided with the distribution.
16106686Stjr * 3. All advertising materials mentioning features or use of this software
17106686Stjr *    must display the following acknowledgement:
18106686Stjr *	This product includes software developed by the University of
19106686Stjr *	California, Berkeley and its contributors.
20106686Stjr * 4. Neither the name of the University nor the names of its contributors
21106686Stjr *    may be used to endorse or promote products derived from this software
22106686Stjr *    without specific prior written permission.
23106686Stjr *
24106686Stjr * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25106686Stjr * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26106686Stjr * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27106686Stjr * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28106686Stjr * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29106686Stjr * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30106686Stjr * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31106686Stjr * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32106686Stjr * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33106686Stjr * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34106686Stjr * SUCH DAMAGE.
35106686Stjr */
36106686Stjr
37106686Stjr#ifndef lint
38106686Stjrstatic const char copyright[] =
39106686Stjr"@(#) Copyright (c) 1990, 1993\n\
40106686Stjr	The Regents of the University of California.  All rights reserved.\n";
41106686Stjr#endif /* not lint */
42106686Stjr
43106686Stjr#ifndef lint
44106686Stjr#if 0
45106686Stjrstatic char sccsid[] = "@(#)fold.c	8.1 (Berkeley) 6/6/93";
46106686Stjr#endif
47106686Stjr#endif /* not lint */
48106686Stjr
49106686Stjr#include <sys/cdefs.h>
50106686Stjr__FBSDID("$FreeBSD: head/usr.bin/fold/fold.c 200462 2009-12-13 03:14:06Z delphij $");
51106686Stjr
52106686Stjr#include <err.h>
53106686Stjr#include <limits.h>
54106686Stjr#include <locale.h>
55106686Stjr#include <stdio.h>
56137587Snik#include <stdlib.h>
57137587Snik#include <string.h>
58106686Stjr#include <unistd.h>
59106686Stjr#include <wchar.h>
60106686Stjr#include <wctype.h>
61106686Stjr
62106686Stjr#define	DEFLINEWIDTH	80
63106686Stjr
64106686Stjrvoid fold(int);
65106686Stjrstatic int newpos(int, wint_t);
66106686Stjrstatic void usage(void);
67106686Stjr
68106686Stjrint bflag;			/* Count bytes, not columns */
69106686Stjrint sflag;			/* Split on word boundaries */
70106686Stjr
71106686Stjrint
72106686Stjrmain(int argc, char **argv)
73106686Stjr{
74106686Stjr	int ch;
75106686Stjr	int rval, width;
76106686Stjr	char *p;
77106686Stjr
78106686Stjr	(void) setlocale(LC_CTYPE, "");
79128005Stjr
80106686Stjr	width = -1;
81106686Stjr	while ((ch = getopt(argc, argv, "0123456789bsw:")) != -1)
82106686Stjr		switch (ch) {
83106686Stjr		case 'b':
84106686Stjr			bflag = 1;
85106686Stjr			break;
86106686Stjr		case 's':
87106686Stjr			sflag = 1;
88106686Stjr			break;
89106686Stjr		case 'w':
90106686Stjr			if ((width = atoi(optarg)) <= 0) {
91106686Stjr				errx(1, "illegal width value");
92106686Stjr			}
93106686Stjr			break;
94106686Stjr		case '0': case '1': case '2': case '3': case '4':
95106686Stjr		case '5': case '6': case '7': case '8': case '9':
96106686Stjr			if (width == -1) {
97106686Stjr				p = argv[optind - 1];
98106686Stjr				if (p[0] == '-' && p[1] == ch && !p[2])
99106686Stjr					width = atoi(++p);
100106686Stjr				else
101106686Stjr					width = atoi(argv[optind] + 1);
102106686Stjr			}
103106686Stjr			break;
104106686Stjr		default:
105128005Stjr			usage();
106106686Stjr		}
107106686Stjr	argv += optind;
108106686Stjr	argc -= optind;
109106686Stjr
110106686Stjr	if (width == -1)
111106686Stjr		width = DEFLINEWIDTH;
112106686Stjr	rval = 0;
113106686Stjr	if (!*argv)
114128005Stjr		fold(width);
115106686Stjr	else for (; *argv; ++argv)
116106686Stjr		if (!freopen(*argv, "r", stdin)) {
117106686Stjr			warn("%s", *argv);
118106686Stjr			rval = 1;
119106686Stjr		} else
120106686Stjr			fold(width);
121137587Snik	exit(rval);
122106686Stjr}
123106686Stjr
124106686Stjrstatic void
125usage(void)
126{
127	(void)fprintf(stderr, "usage: fold [-bs] [-w width] [file ...]\n");
128	exit(1);
129}
130
131/*
132 * Fold the contents of standard input to fit within WIDTH columns (or bytes)
133 * and write to standard output.
134 *
135 * If sflag is set, split the line at the last space character on the line.
136 * This flag necessitates storing the line in a buffer until the current
137 * column > width, or a newline or EOF is read.
138 *
139 * The buffer can grow larger than WIDTH due to backspaces and carriage
140 * returns embedded in the input stream.
141 */
142void
143fold(int width)
144{
145	static wchar_t *buf;
146	static int buf_max;
147	int col, i, indx, space;
148	wint_t ch;
149
150	col = indx = 0;
151	while ((ch = getwchar()) != WEOF) {
152		if (ch == '\n') {
153			wprintf(L"%.*ls\n", indx, buf);
154			col = indx = 0;
155			continue;
156		}
157		if ((col = newpos(col, ch)) > width) {
158			if (sflag) {
159				i = indx;
160				while (--i >= 0 && !iswblank(buf[i]))
161					;
162				space = i;
163			}
164			if (sflag && space != -1) {
165				space++;
166				wprintf(L"%.*ls\n", space, buf);
167				wmemmove(buf, buf + space, indx - space);
168				indx -= space;
169				col = 0;
170				for (i = 0; i < indx; i++)
171					col = newpos(col, buf[i]);
172			} else {
173				wprintf(L"%.*ls\n", indx, buf);
174				col = indx = 0;
175			}
176			col = newpos(col, ch);
177		}
178		if (indx + 1 > buf_max) {
179			buf_max += LINE_MAX;
180			buf = realloc(buf, sizeof(*buf) * buf_max);
181			if (buf == NULL)
182				err(1, "realloc()");
183		}
184		buf[indx++] = ch;
185	}
186
187	if (indx != 0)
188		wprintf(L"%.*ls", indx, buf);
189}
190
191/*
192 * Update the current column position for a character.
193 */
194static int
195newpos(int col, wint_t ch)
196{
197	char buf[MB_LEN_MAX];
198	size_t len;
199	int w;
200
201	if (bflag) {
202		len = wcrtomb(buf, ch, NULL);
203		col += len;
204	} else
205		switch (ch) {
206		case '\b':
207			if (col > 0)
208				--col;
209			break;
210		case '\r':
211			col = 0;
212			break;
213		case '\t':
214			col = (col + 8) & ~7;
215			break;
216		default:
217			if ((w = wcwidth(ch)) > 0)
218				col += w;
219			break;
220		}
221
222	return (col);
223}
224