xref: /freebsd/usr.bin/column/column.c (revision 6780ab54325a71e7e70112b11657973edde8655e)
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 <ctype.h>
53 #include <err.h>
54 #include <limits.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <unistd.h>
59 
60 #define	TAB	8
61 
62 void  c_columnate(void);
63 void  input(FILE *);
64 void  maketbl(void);
65 void  print(void);
66 void  r_columnate(void);
67 void  usage(void);
68 
69 int termwidth = 80;		/* default terminal width */
70 
71 int entries;			/* number of records */
72 int eval;			/* exit value */
73 int maxlength;			/* longest record */
74 char **list;			/* array of pointers to records */
75 const char *separator = "\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 
85 	if (ioctl(1, TIOCGWINSZ, &win) == -1 || !win.ws_col) {
86 		if ((p = getenv("COLUMNS")))
87 			termwidth = atoi(p);
88 	} else
89 		termwidth = win.ws_col;
90 
91 	tflag = xflag = 0;
92 	while ((ch = getopt(argc, argv, "c:s:tx")) != -1)
93 		switch(ch) {
94 		case 'c':
95 			termwidth = atoi(optarg);
96 			break;
97 		case 's':
98 			separator = optarg;
99 			break;
100 		case 't':
101 			tflag = 1;
102 			break;
103 		case 'x':
104 			xflag = 1;
105 			break;
106 		case '?':
107 		default:
108 			usage();
109 		}
110 	argc -= optind;
111 	argv += optind;
112 
113 	if (!*argv)
114 		input(stdin);
115 	else for (; *argv; ++argv)
116 		if ((fp = fopen(*argv, "r"))) {
117 			input(fp);
118 			(void)fclose(fp);
119 		} else {
120 			warn("%s", *argv);
121 			eval = 1;
122 		}
123 
124 	if (!entries)
125 		exit(eval);
126 
127 	maxlength = (maxlength + TAB) & ~(TAB - 1);
128 	if (tflag)
129 		maketbl();
130 	else if (maxlength >= termwidth)
131 		print();
132 	else if (xflag)
133 		c_columnate();
134 	else
135 		r_columnate();
136 	exit(eval);
137 }
138 
139 void
140 c_columnate(void)
141 {
142 	int chcnt, col, cnt, endcol, numcols;
143 	char **lp;
144 
145 	numcols = termwidth / maxlength;
146 	endcol = maxlength;
147 	for (chcnt = col = 0, lp = list;; ++lp) {
148 		chcnt += printf("%s", *lp);
149 		if (!--entries)
150 			break;
151 		if (++col == numcols) {
152 			chcnt = col = 0;
153 			endcol = maxlength;
154 			putchar('\n');
155 		} else {
156 			while ((cnt = ((chcnt + TAB) & ~(TAB - 1))) <= endcol) {
157 				(void)putchar('\t');
158 				chcnt = cnt;
159 			}
160 			endcol += maxlength;
161 		}
162 	}
163 	if (chcnt)
164 		putchar('\n');
165 }
166 
167 void
168 r_columnate(void)
169 {
170 	int base, chcnt, cnt, col, endcol, numcols, numrows, row;
171 
172 	numcols = termwidth / maxlength;
173 	numrows = entries / numcols;
174 	if (entries % numcols)
175 		++numrows;
176 
177 	for (row = 0; row < numrows; ++row) {
178 		endcol = maxlength;
179 		for (base = row, chcnt = col = 0; col < numcols; ++col) {
180 			chcnt += printf("%s", list[base]);
181 			if ((base += numrows) >= entries)
182 				break;
183 			while ((cnt = ((chcnt + TAB) & ~(TAB - 1))) <= endcol) {
184 				(void)putchar('\t');
185 				chcnt = cnt;
186 			}
187 			endcol += maxlength;
188 		}
189 		putchar('\n');
190 	}
191 }
192 
193 void
194 print(void)
195 {
196 	int cnt;
197 	char **lp;
198 
199 	for (cnt = entries, lp = list; cnt--; ++lp)
200 		(void)printf("%s\n", *lp);
201 }
202 
203 typedef struct _tbl {
204 	char **list;
205 	int cols, *len;
206 } TBL;
207 #define	DEFCOLS	25
208 
209 void
210 maketbl(void)
211 {
212 	TBL *t;
213 	int coloff, cnt;
214 	char *p, **lp;
215 	int *lens, maxcols;
216 	TBL *tbl;
217 	char **cols;
218 
219 	if ((t = tbl = calloc(entries, sizeof(TBL))) == NULL)
220 		err(1, (char *)NULL);
221 	if ((cols = calloc((maxcols = DEFCOLS), sizeof(char *))) == NULL)
222 		err(1, (char *)NULL);
223 	if ((lens = calloc(maxcols, sizeof(int))) == NULL)
224 		err(1, (char *)NULL);
225 	for (cnt = 0, lp = list; cnt < entries; ++cnt, ++lp, ++t) {
226 		for (coloff = 0, p = *lp; (cols[coloff] = strtok(p, separator));
227 		    p = NULL)
228 			if (++coloff == maxcols) {
229 				if (!(cols = realloc(cols, (u_int)maxcols +
230 				    DEFCOLS * sizeof(char *))) ||
231 				    !(lens = realloc(lens,
232 				    (u_int)maxcols + DEFCOLS * sizeof(int))))
233 					err(1, NULL);
234 				memset((char *)lens + maxcols * sizeof(int),
235 				    0, DEFCOLS * sizeof(int));
236 				maxcols += DEFCOLS;
237 			}
238 		if ((t->list = calloc(coloff, sizeof(char *))) == NULL)
239 			err(1, (char *)NULL);
240 		if ((t->len = calloc(coloff, sizeof(int))) == NULL)
241 			err(1, (char *)NULL);
242 		for (t->cols = coloff; --coloff >= 0;) {
243 			t->list[coloff] = cols[coloff];
244 			t->len[coloff] = strlen(cols[coloff]);
245 			if (t->len[coloff] > lens[coloff])
246 				lens[coloff] = t->len[coloff];
247 		}
248 	}
249 	for (cnt = 0, t = tbl; cnt < entries; ++cnt, ++t) {
250 		for (coloff = 0; coloff < t->cols  - 1; ++coloff)
251 			(void)printf("%s%*s", t->list[coloff],
252 			    lens[coloff] - t->len[coloff] + 2, " ");
253 		(void)printf("%s\n", t->list[coloff]);
254 	}
255 }
256 
257 #define	DEFNUM		1000
258 #define	MAXLINELEN	(LINE_MAX + 1)
259 
260 void
261 input(FILE *fp)
262 {
263 	static int maxentry;
264 	int len;
265 	char *p, buf[MAXLINELEN];
266 
267 	if (!list)
268 		if ((list = calloc((maxentry = DEFNUM), sizeof(char *))) ==
269 		    NULL)
270 			err(1, (char *)NULL);
271 	while (fgets(buf, MAXLINELEN, fp)) {
272 		for (p = buf; *p && isspace(*p); ++p);
273 		if (!*p)
274 			continue;
275 		if (!(p = strchr(p, '\n'))) {
276 			warnx("line too long");
277 			eval = 1;
278 			continue;
279 		}
280 		*p = '\0';
281 		len = p - buf;
282 		if (maxlength < len)
283 			maxlength = len;
284 		if (entries == maxentry) {
285 			maxentry += DEFNUM;
286 			if (!(list = realloc(list,
287 			    (u_int)maxentry * sizeof(char *))))
288 				err(1, NULL);
289 		}
290 		list[entries++] = strdup(buf);
291 	}
292 }
293 
294 void
295 usage(void)
296 {
297 
298 	(void)fprintf(stderr,
299 	    "usage: column [-tx] [-c columns] [-s sep] [file ...]\n");
300 	exit(1);
301 }
302