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