1160383Snetchild/*
2160383Snetchild * Copyright (c) 1989, 1993, 1994
3160383Snetchild *	The Regents of the University of California.  All rights reserved.
4160383Snetchild *
5160383Snetchild * Redistribution and use in source and binary forms, with or without
6160383Snetchild * modification, are permitted provided that the following conditions
7160383Snetchild * are met:
8160383Snetchild * 1. Redistributions of source code must retain the above copyright
9160383Snetchild *    notice, this list of conditions and the following disclaimer.
10160383Snetchild * 2. Redistributions in binary form must reproduce the above copyright
11160383Snetchild *    notice, this list of conditions and the following disclaimer in the
12160383Snetchild *    documentation and/or other materials provided with the distribution.
13160383Snetchild * 4. Neither the name of the University nor the names of its contributors
14160383Snetchild *    may be used to endorse or promote products derived from this software
15160383Snetchild *    without specific prior written permission.
16160383Snetchild *
17160383Snetchild * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18160383Snetchild * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19160383Snetchild * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20160383Snetchild * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21160383Snetchild * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22160383Snetchild * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23160383Snetchild * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24160383Snetchild * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25160383Snetchild * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26160383Snetchild * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27160383Snetchild * SUCH DAMAGE.
28160383Snetchild */
29160383Snetchild
30160383Snetchild#ifndef lint
31160383Snetchildstatic const char copyright[] =
32160383Snetchild"@(#) Copyright (c) 1989, 1993, 1994\n\
33160383Snetchild	The Regents of the University of California.  All rights reserved.\n";
34160383Snetchild#endif
35160383Snetchild
36160383Snetchild#if 0
37160383Snetchild#ifndef lint
38160383Snetchildstatic char sccsid[] = "@(#)column.c	8.4 (Berkeley) 5/4/95";
39160383Snetchild#endif
40160383Snetchild#endif
41172150Sariff
42172150Sariff#include <sys/cdefs.h>
43165833Snetchild__FBSDID("$FreeBSD$");
44161054Snetchild
45161054Snetchild#include <sys/types.h>
46161054Snetchild#include <sys/ioctl.h>
47160383Snetchild#include <sys/param.h>
48160383Snetchild
49160383Snetchild#include <err.h>
50160383Snetchild#include <limits.h>
51160383Snetchild#include <locale.h>
52172150Sariff#include <stdio.h>
53172150Sariff#include <stdlib.h>
54160383Snetchild#include <string.h>
55229981Spfg#include <unistd.h>
56229981Spfg#include <wchar.h>
57229981Spfg#include <wctype.h>
58229981Spfg
59229981Spfg#define	TAB	8
60229981Spfg
61229981Spfgstatic void	c_columnate(void);
62229981Spfgstatic void	input(FILE *);
63160383Snetchildstatic void	maketbl(void);
64160383Snetchildstatic void	print(void);
65160383Snetchildstatic void	r_columnate(void);
66160383Snetchildstatic void	usage(void);
67160383Snetchildstatic int	width(const wchar_t *);
68165833Snetchild
69165833Snetchildstatic int	termwidth = 80;		/* default terminal width */
70160383Snetchild
71160383Snetchildstatic int	entries;		/* number of records */
72160383Snetchildstatic int	eval;			/* exit value */
73160383Snetchildstatic int	maxlength;		/* longest record */
74160383Snetchildstatic wchar_t	**list;			/* array of pointers to records */
75160383Snetchildstatic const wchar_t *separator = L"\t "; /* field separator for table option */
76160383Snetchild
77160383Snetchildint
78160383Snetchildmain(int argc, char **argv)
79160383Snetchild{
80160383Snetchild	struct winsize win;
81160383Snetchild	FILE *fp;
82160383Snetchild	int ch, tflag, xflag;
83160383Snetchild	char *p;
84160383Snetchild	const char *src;
85160383Snetchild	wchar_t *newsep;
86160383Snetchild	size_t seplen;
87160383Snetchild
88160383Snetchild	setlocale(LC_ALL, "");
89160383Snetchild
90160383Snetchild	if (ioctl(1, TIOCGWINSZ, &win) == -1 || !win.ws_col) {
91160383Snetchild		if ((p = getenv("COLUMNS")))
92160383Snetchild			termwidth = atoi(p);
93160383Snetchild	} else
94160383Snetchild		termwidth = win.ws_col;
95160383Snetchild
96160383Snetchild	tflag = xflag = 0;
97160383Snetchild	while ((ch = getopt(argc, argv, "c:s:tx")) != -1)
98160383Snetchild		switch(ch) {
99160383Snetchild		case 'c':
100160383Snetchild			termwidth = atoi(optarg);
101160383Snetchild			break;
102160383Snetchild		case 's':
103160383Snetchild			src = optarg;
104160383Snetchild			seplen = mbsrtowcs(NULL, &src, 0, NULL);
105160383Snetchild			if (seplen == (size_t)-1)
106160383Snetchild				err(1, "bad separator");
107160383Snetchild			newsep = malloc((seplen + 1) * sizeof(wchar_t));
108160383Snetchild			if (newsep == NULL)
109160383Snetchild				err(1, NULL);
110160383Snetchild			mbsrtowcs(newsep, &src, seplen + 1, NULL);
111160383Snetchild			separator = newsep;
112160383Snetchild			break;
113160383Snetchild		case 't':
114160383Snetchild			tflag = 1;
115160383Snetchild			break;
116160383Snetchild		case 'x':
117160383Snetchild			xflag = 1;
118160383Snetchild			break;
119160383Snetchild		case '?':
120160383Snetchild		default:
121160383Snetchild			usage();
122160383Snetchild		}
123160383Snetchild	argc -= optind;
124160383Snetchild	argv += optind;
125160383Snetchild
126160383Snetchild	if (!*argv)
127160383Snetchild		input(stdin);
128160383Snetchild	else for (; *argv; ++argv)
129160383Snetchild		if ((fp = fopen(*argv, "r"))) {
130160383Snetchild			input(fp);
131160383Snetchild			(void)fclose(fp);
132160383Snetchild		} else {
133160383Snetchild			warn("%s", *argv);
134160383Snetchild			eval = 1;
135160383Snetchild		}
136160383Snetchild
137160383Snetchild	if (!entries)
138160383Snetchild		exit(eval);
139160383Snetchild
140160383Snetchild	maxlength = roundup(maxlength + 1, TAB);
141160383Snetchild	if (tflag)
142160383Snetchild		maketbl();
143160383Snetchild	else if (maxlength >= termwidth)
144160383Snetchild		print();
145160383Snetchild	else if (xflag)
146160383Snetchild		c_columnate();
147160383Snetchild	else
148160383Snetchild		r_columnate();
149160383Snetchild	exit(eval);
150160383Snetchild}
151160383Snetchild
152160383Snetchildstatic void
153160383Snetchildc_columnate(void)
154160383Snetchild{
155160383Snetchild	int chcnt, col, cnt, endcol, numcols;
156160383Snetchild	wchar_t **lp;
157160383Snetchild
158160383Snetchild	numcols = termwidth / maxlength;
159160383Snetchild	endcol = maxlength;
160160383Snetchild	for (chcnt = col = 0, lp = list;; ++lp) {
161160383Snetchild		wprintf(L"%ls", *lp);
162160383Snetchild		chcnt += width(*lp);
163160383Snetchild		if (!--entries)
164160383Snetchild			break;
165160383Snetchild		if (++col == numcols) {
166160383Snetchild			chcnt = col = 0;
167160383Snetchild			endcol = maxlength;
168160383Snetchild			putwchar('\n');
169160383Snetchild		} else {
170160383Snetchild			while ((cnt = roundup(chcnt + 1, TAB)) <= endcol) {
171160383Snetchild				(void)putwchar('\t');
172160383Snetchild				chcnt = cnt;
173160383Snetchild			}
174160383Snetchild			endcol += maxlength;
175160383Snetchild		}
176160383Snetchild	}
177160383Snetchild	if (chcnt)
178160383Snetchild		putwchar('\n');
179160383Snetchild}
180160383Snetchild
181160383Snetchildstatic void
182160383Snetchildr_columnate(void)
183160383Snetchild{
184160383Snetchild	int base, chcnt, cnt, col, endcol, numcols, numrows, row;
185160383Snetchild
186160383Snetchild	numcols = termwidth / maxlength;
187160383Snetchild	numrows = entries / numcols;
188160383Snetchild	if (entries % numcols)
189160383Snetchild		++numrows;
190160383Snetchild
191160383Snetchild	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
208static void
209print(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
218typedef struct _tbl {
219	wchar_t **list;
220	int cols, *len;
221} TBL;
222#define	DEFCOLS	25
223
224static void
225maketbl(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
277static void
278input(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. */
316static int
317width(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
327static void
328usage(void)
329{
330
331	(void)fprintf(stderr,
332	    "usage: column [-tx] [-c columns] [-s sep] [file ...]\n");
333	exit(1);
334}
335