xref: /netbsd-src/usr.bin/col/col.c (revision de1dfb1250df962f1ff3a011772cf58e605aed11)
1 /*	$NetBSD: col.c,v 1.13 2003/10/16 06:45:22 itojun Exp $	*/
2 
3 /*-
4  * Copyright (c) 1990, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Michael Rendell of the Memorial University of Newfoundland.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 #ifndef lint
37 __COPYRIGHT("@(#) Copyright (c) 1990, 1993, 1994\n\
38 	The Regents of the University of California.  All rights reserved.\n");
39 #endif /* not lint */
40 
41 #ifndef lint
42 #if 0
43 static char sccsid[] = "@(#)col.c	8.5 (Berkeley) 5/4/95";
44 #endif
45 __RCSID("$NetBSD: col.c,v 1.13 2003/10/16 06:45:22 itojun Exp $");
46 #endif /* not lint */
47 
48 #include <ctype.h>
49 #include <err.h>
50 #include <string.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <unistd.h>
54 
55 #define	BS	'\b'		/* backspace */
56 #define	TAB	'\t'		/* tab */
57 #define	SPACE	' '		/* space */
58 #define	NL	'\n'		/* newline */
59 #define	CR	'\r'		/* carriage return */
60 #define	ESC	'\033'		/* escape */
61 #define	SI	'\017'		/* shift in to normal character set */
62 #define	SO	'\016'		/* shift out to alternate character set */
63 #define	VT	'\013'		/* vertical tab (aka reverse line feed) */
64 #define	RLF	'\007'		/* ESC-07 reverse line feed */
65 #define	RHLF	'\010'		/* ESC-010 reverse half-line feed */
66 #define	FHLF	'\011'		/* ESC-011 forward half-line feed */
67 
68 /* build up at least this many lines before flushing them out */
69 #define	BUFFER_MARGIN		32
70 
71 typedef char CSET;
72 
73 typedef struct char_str {
74 #define	CS_NORMAL	1
75 #define	CS_ALTERNATE	2
76 	short		c_column;	/* column character is in */
77 	CSET		c_set;		/* character set (currently only 2) */
78 	char		c_char;		/* character in question */
79 } CHAR;
80 
81 typedef struct line_str LINE;
82 struct line_str {
83 	CHAR	*l_line;		/* characters on the line */
84 	LINE	*l_prev;		/* previous line */
85 	LINE	*l_next;		/* next line */
86 	int	l_lsize;		/* allocated sizeof l_line */
87 	int	l_line_len;		/* strlen(l_line) */
88 	int	l_needs_sort;		/* set if chars went in out of order */
89 	int	l_max_col;		/* max column in the line */
90 };
91 
92 LINE   *alloc_line __P((void));
93 void	dowarn __P((int));
94 void	flush_line __P((LINE *));
95 void	flush_lines __P((int));
96 void	flush_blanks __P((void));
97 void	free_line __P((LINE *));
98 int	main __P((int, char **));
99 void	usage __P((void));
100 void	wrerr __P((void));
101 void   *xmalloc __P((void *, size_t));
102 
103 CSET	last_set;		/* char_set of last char printed */
104 LINE   *lines;
105 int	compress_spaces;	/* if doing space -> tab conversion */
106 int	fine;			/* if `fine' resolution (half lines) */
107 int	max_bufd_lines;		/* max # lines to keep in memory */
108 int	nblank_lines;		/* # blanks after last flushed line */
109 int	no_backspaces;		/* if not to output any backspaces */
110 int	pass_unknown_seqs;	/* whether to pass unknown control sequences */
111 
112 #define	PUTC(ch) \
113 	if (putchar(ch) == EOF) \
114 		wrerr();
115 
116 int
117 main(argc, argv)
118 	int argc;
119 	char **argv;
120 {
121 	int ch;
122 	CHAR *c;
123 	CSET cur_set;			/* current character set */
124 	LINE *l;			/* current line */
125 	int extra_lines;		/* # of lines above first line */
126 	int cur_col;			/* current column */
127 	int cur_line;			/* line number of current position */
128 	int max_line;			/* max value of cur_line */
129 	int this_line;			/* line l points to */
130 	int nflushd_lines;		/* number of lines that were flushed */
131 	int adjust, opt, warned;
132 
133 	max_bufd_lines = 128;
134 	compress_spaces = 1;		/* compress spaces into tabs */
135 	pass_unknown_seqs = 0;		/* remove unknown escape sequences */
136 	while ((opt = getopt(argc, argv, "bfhl:px")) != -1)
137 		switch (opt) {
138 		case 'b':		/* do not output backspaces */
139 			no_backspaces = 1;
140 			break;
141 		case 'f':		/* allow half forward line feeds */
142 			fine = 1;
143 			break;
144 		case 'h':		/* compress spaces into tabs */
145 			compress_spaces = 1;
146 			break;
147 		case 'l':		/* buffered line count */
148 			if ((max_bufd_lines = atoi(optarg)) <= 0) {
149 				(void)fprintf(stderr,
150 				    "col: bad -l argument %s.\n", optarg);
151 				exit(EXIT_FAILURE);
152 			}
153 			break;
154 		case 'p':		/* pass unknown control sequences */
155 			pass_unknown_seqs = 1;
156 			break;
157 		case 'x':		/* do not compress spaces into tabs */
158 			compress_spaces = 0;
159 			break;
160 		case '?':
161 		default:
162 			usage();
163 		}
164 
165 	if (optind != argc)
166 		usage();
167 
168 	/* this value is in half lines */
169 	max_bufd_lines *= 2;
170 
171 	adjust = cur_col = extra_lines = warned = 0;
172 	cur_line = max_line = nflushd_lines = this_line = 0;
173 	cur_set = last_set = CS_NORMAL;
174 	lines = l = alloc_line();
175 
176 	while ((ch = getchar()) != EOF) {
177 		if (!isgraph(ch)) {
178 			switch (ch) {
179 			case BS:		/* can't go back further */
180 				if (cur_col == 0)
181 					continue;
182 				--cur_col;
183 				continue;
184 			case CR:
185 				cur_col = 0;
186 				continue;
187 			case ESC:		/* just ignore EOF */
188 				switch(getchar()) {
189 				case RLF:
190 					cur_line -= 2;
191 					break;
192 				case RHLF:
193 					cur_line--;
194 					break;
195 				case FHLF:
196 					cur_line++;
197 					if (cur_line > max_line)
198 						max_line = cur_line;
199 				}
200 				continue;
201 			case NL:
202 				cur_line += 2;
203 				if (cur_line > max_line)
204 					max_line = cur_line;
205 				cur_col = 0;
206 				continue;
207 			case SPACE:
208 				++cur_col;
209 				continue;
210 			case SI:
211 				cur_set = CS_NORMAL;
212 				continue;
213 			case SO:
214 				cur_set = CS_ALTERNATE;
215 				continue;
216 			case TAB:		/* adjust column */
217 				cur_col |= 7;
218 				++cur_col;
219 				continue;
220 			case VT:
221 				cur_line -= 2;
222 				continue;
223 			}
224 			if (!pass_unknown_seqs)
225 				continue;
226 		}
227 
228 		/* Must stuff ch in a line - are we at the right one? */
229 		if (cur_line != this_line - adjust) {
230 			LINE *lnew;
231 			int nmove;
232 
233 			adjust = 0;
234 			nmove = cur_line - this_line;
235 			if (!fine) {
236 				/* round up to next line */
237 				if (cur_line & 1) {
238 					adjust = 1;
239 					nmove++;
240 				}
241 			}
242 			if (nmove < 0) {
243 				for (; nmove < 0 && l->l_prev; nmove++)
244 					l = l->l_prev;
245 				if (nmove) {
246 					if (nflushd_lines == 0) {
247 						/*
248 						 * Allow backup past first
249 						 * line if nothing has been
250 						 * flushed yet.
251 						 */
252 						for (; nmove < 0; nmove++) {
253 							lnew = alloc_line();
254 							l->l_prev = lnew;
255 							lnew->l_next = l;
256 							l = lines = lnew;
257 							extra_lines++;
258 						}
259 					} else {
260 						if (!warned++)
261 							dowarn(cur_line);
262 						cur_line -= nmove;
263 					}
264 				}
265 			} else {
266 				/* may need to allocate here */
267 				for (; nmove > 0 && l->l_next; nmove--)
268 					l = l->l_next;
269 				for (; nmove > 0; nmove--) {
270 					lnew = alloc_line();
271 					lnew->l_prev = l;
272 					l->l_next = lnew;
273 					l = lnew;
274 				}
275 			}
276 			this_line = cur_line + adjust;
277 			nmove = this_line - nflushd_lines;
278 			if (nmove >= max_bufd_lines + BUFFER_MARGIN) {
279 				nflushd_lines += nmove - max_bufd_lines;
280 				flush_lines(nmove - max_bufd_lines);
281 			}
282 		}
283 		/* grow line's buffer? */
284 		if (l->l_line_len + 1 >= l->l_lsize) {
285 			int need;
286 
287 			need = l->l_lsize ? l->l_lsize * 2 : 90;
288 			l->l_line = (CHAR *)xmalloc((void *) l->l_line,
289 			    (unsigned) need * sizeof(CHAR));
290 			l->l_lsize = need;
291 		}
292 		c = &l->l_line[l->l_line_len++];
293 		c->c_char = ch;
294 		c->c_set = cur_set;
295 		c->c_column = cur_col;
296 		/*
297 		 * If things are put in out of order, they will need sorting
298 		 * when it is flushed.
299 		 */
300 		if (cur_col < l->l_max_col)
301 			l->l_needs_sort = 1;
302 		else
303 			l->l_max_col = cur_col;
304 		cur_col++;
305 	}
306 	if (max_line == 0)
307 		exit(EXIT_SUCCESS);	/* no lines, so just exit */
308 
309 	/* goto the last line that had a character on it */
310 	for (; l->l_next; l = l->l_next)
311 		this_line++;
312 	flush_lines(this_line - nflushd_lines + extra_lines + 1);
313 
314 	/* make sure we leave things in a sane state */
315 	if (last_set != CS_NORMAL)
316 		PUTC('\017');
317 
318 	/* flush out the last few blank lines */
319 	nblank_lines = max_line - this_line;
320 	if (max_line & 1)
321 		nblank_lines++;
322 	else if (!nblank_lines)
323 		/* missing a \n on the last line? */
324 		nblank_lines = 2;
325 	flush_blanks();
326 	exit(EXIT_SUCCESS);
327 	/* NOTREACHED */
328 }
329 
330 void
331 flush_lines(nflush)
332 	int nflush;
333 {
334 	LINE *l;
335 
336 	while (--nflush >= 0) {
337 		l = lines;
338 		lines = l->l_next;
339 		if (l->l_line) {
340 			flush_blanks();
341 			flush_line(l);
342 		}
343 		nblank_lines++;
344 		if (l->l_line)
345 			(void)free((void *)l->l_line);
346 		free_line(l);
347 	}
348 	if (lines)
349 		lines->l_prev = NULL;
350 }
351 
352 /*
353  * Print a number of newline/half newlines.  If fine flag is set, nblank_lines
354  * is the number of half line feeds, otherwise it is the number of whole line
355  * feeds.
356  */
357 void
358 flush_blanks()
359 {
360 	int half, i, nb;
361 
362 	half = 0;
363 	nb = nblank_lines;
364 	if (nb & 1) {
365 		if (fine)
366 			half = 1;
367 		else
368 			nb++;
369 	}
370 	nb /= 2;
371 	for (i = nb; --i >= 0;)
372 		PUTC('\n');
373 	if (half) {
374 		PUTC('\033');
375 		PUTC('9');
376 		if (!nb)
377 			PUTC('\r');
378 	}
379 	nblank_lines = 0;
380 }
381 
382 /*
383  * Write a line to stdout taking care of space to tab conversion (-h flag)
384  * and character set shifts.
385  */
386 void
387 flush_line(l)
388 	LINE *l;
389 {
390 	CHAR *c, *endc;
391 	int nchars, last_col, this_col;
392 
393 	last_col = 0;
394 	nchars = l->l_line_len;
395 
396 	if (l->l_needs_sort) {
397 		static CHAR *sorted;
398 		static int count_size, *count, i, save, sorted_size, tot;
399 
400 		/*
401 		 * Do an O(n) sort on l->l_line by column being careful to
402 		 * preserve the order of characters in the same column.
403 		 */
404 		if (l->l_lsize > sorted_size) {
405 			sorted_size = l->l_lsize;
406 			sorted = (CHAR *)xmalloc((void *)sorted,
407 			    (unsigned)sizeof(CHAR) * sorted_size);
408 		}
409 		if (l->l_max_col >= count_size) {
410 			count_size = l->l_max_col + 1;
411 			count = (int *)xmalloc((void *)count,
412 			    (unsigned)sizeof(int) * count_size);
413 		}
414 		(void)memset(count, 0, sizeof(int) * l->l_max_col + 1);
415 		for (i = nchars, c = l->l_line; --i >= 0; c++)
416 			count[c->c_column]++;
417 
418 		/*
419 		 * calculate running total (shifted down by 1) to use as
420 		 * indices into new line.
421 		 */
422 		for (tot = 0, i = 0; i <= l->l_max_col; i++) {
423 			save = count[i];
424 			count[i] = tot;
425 			tot += save;
426 		}
427 
428 		for (i = nchars, c = l->l_line; --i >= 0; c++)
429 			sorted[count[c->c_column]++] = *c;
430 		c = sorted;
431 	} else
432 		c = l->l_line;
433 	while (nchars > 0) {
434 		this_col = c->c_column;
435 		endc = c;
436 		do {
437 			++endc;
438 		} while (--nchars > 0 && this_col == endc->c_column);
439 
440 		/* if -b only print last character */
441 		if (no_backspaces)
442 			c = endc - 1;
443 
444 		if (this_col > last_col) {
445 			int nspace = this_col - last_col;
446 
447 			if (compress_spaces && nspace > 1) {
448 				int ntabs;
449 
450 				ntabs = ((last_col % 8) + nspace) / 8;
451 				if (ntabs) {
452 					nspace -= (ntabs * 8) - (last_col % 8);
453 					while (--ntabs >= 0)
454 						PUTC('\t');
455 				}
456 			}
457 			while (--nspace >= 0)
458 				PUTC(' ');
459 			last_col = this_col;
460 		}
461 		last_col++;
462 
463 		for (;;) {
464 			if (c->c_set != last_set) {
465 				switch (c->c_set) {
466 				case CS_NORMAL:
467 					PUTC('\017');
468 					break;
469 				case CS_ALTERNATE:
470 					PUTC('\016');
471 				}
472 				last_set = c->c_set;
473 			}
474 			PUTC(c->c_char);
475 			if (++c >= endc)
476 				break;
477 			PUTC('\b');
478 		}
479 	}
480 }
481 
482 #define	NALLOC 64
483 
484 static LINE *line_freelist;
485 
486 LINE *
487 alloc_line()
488 {
489 	LINE *l;
490 	int i;
491 
492 	if (!line_freelist) {
493 		l = (LINE *)xmalloc((void *)NULL, sizeof(LINE) * NALLOC);
494 		line_freelist = l;
495 		for (i = 1; i < NALLOC; i++, l++)
496 			l->l_next = l + 1;
497 		l->l_next = NULL;
498 	}
499 	l = line_freelist;
500 	line_freelist = l->l_next;
501 
502 	(void)memset(l, 0, sizeof(LINE));
503 	return (l);
504 }
505 
506 void
507 free_line(l)
508 	LINE *l;
509 {
510 
511 	l->l_next = line_freelist;
512 	line_freelist = l;
513 }
514 
515 void *
516 xmalloc(p, size)
517 	void *p;
518 	size_t size;
519 {
520 	void *q;
521 
522 	if (!(q = (void *)realloc(p, size)))
523 		err(EXIT_FAILURE, "realloc");
524 	p = q;
525 	return (p);
526 }
527 
528 void
529 usage()
530 {
531 
532 	(void)fprintf(stderr, "usage: col [-bfpx] [-l nline]\n");
533 	exit(EXIT_FAILURE);
534 }
535 
536 void
537 wrerr()
538 {
539 
540 	(void)fprintf(stderr, "col: write error.\n");
541 	exit(EXIT_FAILURE);
542 }
543 
544 void
545 dowarn(line)
546 	int line;
547 {
548 
549 	warnx("warning: can't back up %s",
550 		line < 0 ? "past first line" : "-- line already flushed");
551 }
552