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