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