xref: /freebsd/usr.bin/column/column.c (revision 42249ef2)
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 __FBSDID("$FreeBSD$");
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 
63 static void	c_columnate(void);
64 static void	input(FILE *);
65 static void	maketbl(void);
66 static void	print(void);
67 static void	r_columnate(void);
68 static void	usage(void);
69 static int	width(const wchar_t *);
70 
71 static int	termwidth = 80;		/* default terminal width */
72 
73 static int	entries;		/* number of records */
74 static int	eval;			/* exit value */
75 static int	maxlength;		/* longest record */
76 static wchar_t	**list;			/* array of pointers to records */
77 static const wchar_t *separator = L"\t "; /* field separator for table option */
78 
79 int
80 main(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 
154 static void
155 c_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 
183 static void
184 r_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 
210 static void
211 print(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 
220 typedef struct _tbl {
221 	wchar_t **list;
222 	int cols, *len;
223 } TBL;
224 #define	DEFCOLS	25
225 
226 static void
227 maketbl(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 		free(t->list);
274 		free(t->len);
275 	}
276 	free(lens);
277 	free(cols);
278 	free(tbl);
279 }
280 
281 #define	DEFNUM		1000
282 #define	MAXLINELEN	(LINE_MAX + 1)
283 
284 static void
285 input(FILE *fp)
286 {
287 	static int maxentry;
288 	int len;
289 	wchar_t *p, buf[MAXLINELEN];
290 
291 	if (!list)
292 		if ((list = calloc((maxentry = DEFNUM), sizeof(*list))) ==
293 		    NULL)
294 			err(1, NULL);
295 	while (fgetws(buf, MAXLINELEN, fp)) {
296 		for (p = buf; *p && iswspace(*p); ++p);
297 		if (!*p)
298 			continue;
299 		if (!(p = wcschr(p, L'\n'))) {
300 			warnx("line too long");
301 			eval = 1;
302 			continue;
303 		}
304 		*p = L'\0';
305 		len = width(buf);
306 		if (maxlength < len)
307 			maxlength = len;
308 		if (entries == maxentry) {
309 			maxentry += DEFNUM;
310 			if (!(list = realloc(list,
311 			    (u_int)maxentry * sizeof(*list))))
312 				err(1, NULL);
313 		}
314 		list[entries] = malloc((wcslen(buf) + 1) * sizeof(wchar_t));
315 		if (list[entries] == NULL)
316 			err(1, NULL);
317 		wcscpy(list[entries], buf);
318 		entries++;
319 	}
320 }
321 
322 /* Like wcswidth(), but ignores non-printing characters. */
323 static int
324 width(const wchar_t *wcs)
325 {
326 	int w, cw;
327 
328 	for (w = 0; *wcs != L'\0'; wcs++)
329 		if ((cw = wcwidth(*wcs)) > 0)
330 			w += cw;
331 	return (w);
332 }
333 
334 static void
335 usage(void)
336 {
337 
338 	(void)fprintf(stderr,
339 	    "usage: column [-tx] [-c columns] [-s sep] [file ...]\n");
340 	exit(1);
341 }
342