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