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