xref: /freebsd/usr.bin/column/column.c (revision c8191bc69e371d47c087ae124ff863de342a479b)
1 /*
2  * Copyright (c) 1989, 1993, 1994
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #ifndef lint
31 static const char copyright[] =
32 "@(#) Copyright (c) 1989, 1993, 1994\n\
33 	The Regents of the University of California.  All rights reserved.\n";
34 #endif
35 
36 #if 0
37 #ifndef lint
38 static char sccsid[] = "@(#)column.c	8.4 (Berkeley) 5/4/95";
39 #endif
40 #endif
41 
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44 
45 #include <sys/types.h>
46 #include <sys/ioctl.h>
47 #include <sys/param.h>
48 
49 #include <err.h>
50 #include <limits.h>
51 #include <locale.h>
52 #include <stdio.h>
53 #include <stdlib.h>
54 #include <string.h>
55 #include <unistd.h>
56 #include <wchar.h>
57 #include <wctype.h>
58 
59 #define	TAB	8
60 
61 static void	c_columnate(void);
62 static void	input(FILE *);
63 static void	maketbl(void);
64 static void	print(void);
65 static void	r_columnate(void);
66 static void	usage(void);
67 static int	width(const wchar_t *);
68 
69 static int	termwidth = 80;		/* default terminal width */
70 
71 static int	entries;		/* number of records */
72 static int	eval;			/* exit value */
73 static int	maxlength;		/* longest record */
74 static wchar_t	**list;			/* array of pointers to records */
75 static const wchar_t *separator = L"\t "; /* field separator for table option */
76 
77 int
78 main(int argc, char **argv)
79 {
80 	struct winsize win;
81 	FILE *fp;
82 	int ch, tflag, xflag;
83 	char *p;
84 	const char *src;
85 	wchar_t *newsep;
86 	size_t seplen;
87 
88 	setlocale(LC_ALL, "");
89 
90 	if (ioctl(1, TIOCGWINSZ, &win) == -1 || !win.ws_col) {
91 		if ((p = getenv("COLUMNS")))
92 			termwidth = atoi(p);
93 	} else
94 		termwidth = win.ws_col;
95 
96 	tflag = xflag = 0;
97 	while ((ch = getopt(argc, argv, "c:s:tx")) != -1)
98 		switch(ch) {
99 		case 'c':
100 			termwidth = atoi(optarg);
101 			break;
102 		case 's':
103 			src = optarg;
104 			seplen = mbsrtowcs(NULL, &src, 0, NULL);
105 			if (seplen == (size_t)-1)
106 				err(1, "bad separator");
107 			newsep = malloc((seplen + 1) * sizeof(wchar_t));
108 			if (newsep == NULL)
109 				err(1, NULL);
110 			mbsrtowcs(newsep, &src, seplen + 1, NULL);
111 			separator = newsep;
112 			break;
113 		case 't':
114 			tflag = 1;
115 			break;
116 		case 'x':
117 			xflag = 1;
118 			break;
119 		case '?':
120 		default:
121 			usage();
122 		}
123 	argc -= optind;
124 	argv += optind;
125 
126 	if (!*argv)
127 		input(stdin);
128 	else for (; *argv; ++argv)
129 		if ((fp = fopen(*argv, "r"))) {
130 			input(fp);
131 			(void)fclose(fp);
132 		} else {
133 			warn("%s", *argv);
134 			eval = 1;
135 		}
136 
137 	if (!entries)
138 		exit(eval);
139 
140 	maxlength = roundup(maxlength + 1, TAB);
141 	if (tflag)
142 		maketbl();
143 	else if (maxlength >= termwidth)
144 		print();
145 	else if (xflag)
146 		c_columnate();
147 	else
148 		r_columnate();
149 	exit(eval);
150 }
151 
152 static void
153 c_columnate(void)
154 {
155 	int chcnt, col, cnt, endcol, numcols;
156 	wchar_t **lp;
157 
158 	numcols = termwidth / maxlength;
159 	endcol = maxlength;
160 	for (chcnt = col = 0, lp = list;; ++lp) {
161 		wprintf(L"%ls", *lp);
162 		chcnt += width(*lp);
163 		if (!--entries)
164 			break;
165 		if (++col == numcols) {
166 			chcnt = col = 0;
167 			endcol = maxlength;
168 			putwchar('\n');
169 		} else {
170 			while ((cnt = roundup(chcnt + 1, TAB)) <= endcol) {
171 				(void)putwchar('\t');
172 				chcnt = cnt;
173 			}
174 			endcol += maxlength;
175 		}
176 	}
177 	if (chcnt)
178 		putwchar('\n');
179 }
180 
181 static void
182 r_columnate(void)
183 {
184 	int base, chcnt, cnt, col, endcol, numcols, numrows, row;
185 
186 	numcols = termwidth / maxlength;
187 	numrows = entries / numcols;
188 	if (entries % numcols)
189 		++numrows;
190 
191 	for (row = 0; row < numrows; ++row) {
192 		endcol = maxlength;
193 		for (base = row, chcnt = col = 0; col < numcols; ++col) {
194 			wprintf(L"%ls", list[base]);
195 			chcnt += width(list[base]);
196 			if ((base += numrows) >= entries)
197 				break;
198 			while ((cnt = roundup(chcnt + 1, TAB)) <= endcol) {
199 				(void)putwchar('\t');
200 				chcnt = cnt;
201 			}
202 			endcol += maxlength;
203 		}
204 		putwchar('\n');
205 	}
206 }
207 
208 static void
209 print(void)
210 {
211 	int cnt;
212 	wchar_t **lp;
213 
214 	for (cnt = entries, lp = list; cnt--; ++lp)
215 		(void)wprintf(L"%ls\n", *lp);
216 }
217 
218 typedef struct _tbl {
219 	wchar_t **list;
220 	int cols, *len;
221 } TBL;
222 #define	DEFCOLS	25
223 
224 static void
225 maketbl(void)
226 {
227 	TBL *t;
228 	int coloff, cnt;
229 	wchar_t *p, **lp;
230 	int *lens, maxcols;
231 	TBL *tbl;
232 	wchar_t **cols;
233 	wchar_t *last;
234 
235 	if ((t = tbl = calloc(entries, sizeof(TBL))) == NULL)
236 		err(1, (char *)NULL);
237 	if ((cols = calloc((maxcols = DEFCOLS), sizeof(*cols))) == NULL)
238 		err(1, (char *)NULL);
239 	if ((lens = calloc(maxcols, sizeof(int))) == NULL)
240 		err(1, (char *)NULL);
241 	for (cnt = 0, lp = list; cnt < entries; ++cnt, ++lp, ++t) {
242 		for (coloff = 0, p = *lp;
243 		    (cols[coloff] = wcstok(p, separator, &last));
244 		    p = NULL)
245 			if (++coloff == maxcols) {
246 				if (!(cols = realloc(cols, ((u_int)maxcols +
247 				    DEFCOLS) * sizeof(char *))) ||
248 				    !(lens = realloc(lens,
249 				    ((u_int)maxcols + DEFCOLS) * sizeof(int))))
250 					err(1, NULL);
251 				memset((char *)lens + maxcols * sizeof(int),
252 				    0, DEFCOLS * sizeof(int));
253 				maxcols += DEFCOLS;
254 			}
255 		if ((t->list = calloc(coloff, sizeof(*t->list))) == NULL)
256 			err(1, (char *)NULL);
257 		if ((t->len = calloc(coloff, sizeof(int))) == NULL)
258 			err(1, (char *)NULL);
259 		for (t->cols = coloff; --coloff >= 0;) {
260 			t->list[coloff] = cols[coloff];
261 			t->len[coloff] = width(cols[coloff]);
262 			if (t->len[coloff] > lens[coloff])
263 				lens[coloff] = t->len[coloff];
264 		}
265 	}
266 	for (cnt = 0, t = tbl; cnt < entries; ++cnt, ++t) {
267 		for (coloff = 0; coloff < t->cols  - 1; ++coloff)
268 			(void)wprintf(L"%ls%*ls", t->list[coloff],
269 			    lens[coloff] - t->len[coloff] + 2, L" ");
270 		(void)wprintf(L"%ls\n", t->list[coloff]);
271 	}
272 }
273 
274 #define	DEFNUM		1000
275 #define	MAXLINELEN	(LINE_MAX + 1)
276 
277 static void
278 input(FILE *fp)
279 {
280 	static int maxentry;
281 	int len;
282 	wchar_t *p, buf[MAXLINELEN];
283 
284 	if (!list)
285 		if ((list = calloc((maxentry = DEFNUM), sizeof(*list))) ==
286 		    NULL)
287 			err(1, (char *)NULL);
288 	while (fgetws(buf, MAXLINELEN, fp)) {
289 		for (p = buf; *p && iswspace(*p); ++p);
290 		if (!*p)
291 			continue;
292 		if (!(p = wcschr(p, L'\n'))) {
293 			warnx("line too long");
294 			eval = 1;
295 			continue;
296 		}
297 		*p = L'\0';
298 		len = width(buf);
299 		if (maxlength < len)
300 			maxlength = len;
301 		if (entries == maxentry) {
302 			maxentry += DEFNUM;
303 			if (!(list = realloc(list,
304 			    (u_int)maxentry * sizeof(*list))))
305 				err(1, NULL);
306 		}
307 		list[entries] = malloc((wcslen(buf) + 1) * sizeof(wchar_t));
308 		if (list[entries] == NULL)
309 			err(1, NULL);
310 		wcscpy(list[entries], buf);
311 		entries++;
312 	}
313 }
314 
315 /* Like wcswidth(), but ignores non-printing characters. */
316 static int
317 width(const wchar_t *wcs)
318 {
319 	int w, cw;
320 
321 	for (w = 0; *wcs != L'\0'; wcs++)
322 		if ((cw = wcwidth(*wcs)) > 0)
323 			w += cw;
324 	return (w);
325 }
326 
327 static void
328 usage(void)
329 {
330 
331 	(void)fprintf(stderr,
332 	    "usage: column [-tx] [-c columns] [-s sep] [file ...]\n");
333 	exit(1);
334 }
335