xref: /freebsd/usr.bin/column/column.c (revision 734e82fe33aa764367791a7d603b383996c6b40b)
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  * 3. 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
33 static 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
40 static char sccsid[] = "@(#)column.c	8.4 (Berkeley) 5/4/95";
41 #endif
42 #endif
43 
44 #include <sys/cdefs.h>
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, NULL);
237 	if ((cols = calloc((maxcols = DEFCOLS), sizeof(*cols))) == NULL)
238 		err(1, NULL);
239 	if ((lens = calloc(maxcols, sizeof(int))) == NULL)
240 		err(1, 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(wchar_t *))) ||
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, NULL);
257 		if ((t->len = calloc(coloff, sizeof(int))) == NULL)
258 			err(1, 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 		free(t->list);
272 		free(t->len);
273 	}
274 	free(lens);
275 	free(cols);
276 	free(tbl);
277 }
278 
279 #define	DEFNUM		1000
280 #define	MAXLINELEN	(LINE_MAX + 1)
281 
282 static void
283 input(FILE *fp)
284 {
285 	static int maxentry;
286 	int len;
287 	wchar_t *p, buf[MAXLINELEN];
288 
289 	if (!list)
290 		if ((list = calloc((maxentry = DEFNUM), sizeof(*list))) ==
291 		    NULL)
292 			err(1, NULL);
293 	while (fgetws(buf, MAXLINELEN, fp)) {
294 		for (p = buf; *p && iswspace(*p); ++p);
295 		if (!*p)
296 			continue;
297 		if (!(p = wcschr(p, L'\n'))) {
298 			warnx("line too long");
299 			eval = 1;
300 			continue;
301 		}
302 		*p = L'\0';
303 		len = width(buf);
304 		if (maxlength < len)
305 			maxlength = len;
306 		if (entries == maxentry) {
307 			maxentry += DEFNUM;
308 			if (!(list = realloc(list,
309 			    (u_int)maxentry * sizeof(*list))))
310 				err(1, NULL);
311 		}
312 		list[entries] = malloc((wcslen(buf) + 1) * sizeof(wchar_t));
313 		if (list[entries] == NULL)
314 			err(1, NULL);
315 		wcscpy(list[entries], buf);
316 		entries++;
317 	}
318 }
319 
320 /* Like wcswidth(), but ignores non-printing characters. */
321 static int
322 width(const wchar_t *wcs)
323 {
324 	int w, cw;
325 
326 	for (w = 0; *wcs != L'\0'; wcs++)
327 		if ((cw = wcwidth(*wcs)) > 0)
328 			w += cw;
329 	return (w);
330 }
331 
332 static void
333 usage(void)
334 {
335 
336 	(void)fprintf(stderr,
337 	    "usage: column [-tx] [-c columns] [-s sep] [file ...]\n");
338 	exit(1);
339 }
340