xref: /freebsd/usr.bin/col/col.c (revision d0b2dbfa0ecf2bbc9709efc5e20baf8e4b44bbbf)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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 #ifndef lint
36 static const char copyright[] =
37 "@(#) Copyright (c) 1990, 1993, 1994\n\
38 	The Regents of the University of California.  All rights reserved.\n";
39 #endif
40 
41 #if 0
42 #ifndef lint
43 static char sccsid[] = "@(#)col.c	8.5 (Berkeley) 5/4/95";
44 #endif
45 #endif
46 
47 #include <sys/cdefs.h>
48 #include <sys/capsicum.h>
49 
50 #include <capsicum_helpers.h>
51 #include <err.h>
52 #include <errno.h>
53 #include <locale.h>
54 #include <stdio.h>
55 #include <stdlib.h>
56 #include <string.h>
57 #include <termios.h>
58 #include <unistd.h>
59 #include <wchar.h>
60 #include <wctype.h>
61 
62 #define	BS	'\b'		/* backspace */
63 #define	TAB	'\t'		/* tab */
64 #define	SPACE	' '		/* space */
65 #define	NL	'\n'		/* newline */
66 #define	CR	'\r'		/* carriage return */
67 #define	ESC	'\033'		/* escape */
68 #define	SI	'\017'		/* shift in to normal character set */
69 #define	SO	'\016'		/* shift out to alternate character set */
70 #define	VT	'\013'		/* vertical tab (aka reverse line feed) */
71 #define	RLF	'7'		/* ESC-7 reverse line feed */
72 #define	RHLF	'8'		/* ESC-8 reverse half-line feed */
73 #define	FHLF	'9'		/* ESC-9 forward half-line feed */
74 
75 /* build up at least this many lines before flushing them out */
76 #define	BUFFER_MARGIN		32
77 
78 typedef char CSET;
79 
80 typedef struct char_str {
81 #define	CS_NORMAL	1
82 #define	CS_ALTERNATE	2
83 	short		c_column;	/* column character is in */
84 	CSET		c_set;		/* character set (currently only 2) */
85 	wchar_t		c_char;		/* character in question */
86 	int		c_width;	/* character width */
87 } CHAR;
88 
89 typedef struct line_str LINE;
90 struct line_str {
91 	CHAR	*l_line;		/* characters on the line */
92 	LINE	*l_prev;		/* previous line */
93 	LINE	*l_next;		/* next line */
94 	int	l_lsize;		/* allocated sizeof l_line */
95 	int	l_line_len;		/* strlen(l_line) */
96 	int	l_needs_sort;		/* set if chars went in out of order */
97 	int	l_max_col;		/* max column in the line */
98 };
99 
100 static void	addto_lineno(int *, int);
101 static LINE	*alloc_line(void);
102 static void	dowarn(int);
103 static void	flush_line(LINE *);
104 static void	flush_lines(int);
105 static void	flush_blanks(void);
106 static void	free_line(LINE *);
107 static void	usage(void);
108 
109 static CSET	last_set;		/* char_set of last char printed */
110 static LINE	*lines;
111 static int	compress_spaces;	/* if doing space -> tab conversion */
112 static int	fine;			/* if `fine' resolution (half lines) */
113 static int	max_bufd_lines;		/* max # of half lines to keep in memory */
114 static int	nblank_lines;		/* # blanks after last flushed line */
115 static int	no_backspaces;		/* if not to output any backspaces */
116 static int	pass_unknown_seqs;	/* pass unknown control sequences */
117 
118 #define	PUTC(ch) \
119 	do {					\
120 		if (putwchar(ch) == WEOF)	\
121 			errx(1, "write error");	\
122 	} while (0)
123 
124 int
125 main(int argc, char **argv)
126 {
127 	wint_t ch;
128 	CHAR *c;
129 	CSET cur_set;			/* current character set */
130 	LINE *l;			/* current line */
131 	int extra_lines;		/* # of lines above first line */
132 	int cur_col;			/* current column */
133 	int cur_line;			/* line number of current position */
134 	int max_line;			/* max value of cur_line */
135 	int this_line;			/* line l points to */
136 	int nflushd_lines;		/* number of lines that were flushed */
137 	int adjust, opt, warned, width;
138 	const char *errstr;
139 
140 	(void)setlocale(LC_CTYPE, "");
141 
142 	if (caph_limit_stdio() == -1)
143 		err(1, "unable to limit stdio");
144 
145 	if (caph_enter() < 0)
146 		err(1, "unable to enter capability mode");
147 
148 	max_bufd_lines = 256;
149 	compress_spaces = 1;		/* compress spaces into tabs */
150 	while ((opt = getopt(argc, argv, "bfhl:px")) != -1)
151 		switch (opt) {
152 		case 'b':		/* do not output backspaces */
153 			no_backspaces = 1;
154 			break;
155 		case 'f':		/* allow half forward line feeds */
156 			fine = 1;
157 			break;
158 		case 'h':		/* compress spaces into tabs */
159 			compress_spaces = 1;
160 			break;
161 		case 'l':		/* buffered line count */
162 			max_bufd_lines = strtonum(optarg, 1,
163 			    (INT_MAX - BUFFER_MARGIN) / 2, &errstr) * 2;
164 			if (errstr != NULL)
165 				errx(1, "bad -l argument, %s: %s", errstr,
166 					optarg);
167 			break;
168 		case 'p':		/* pass unknown control sequences */
169 			pass_unknown_seqs = 1;
170 			break;
171 		case 'x':		/* do not compress spaces into tabs */
172 			compress_spaces = 0;
173 			break;
174 		case '?':
175 		default:
176 			usage();
177 		}
178 
179 	if (optind != argc)
180 		usage();
181 
182 	adjust = cur_col = extra_lines = warned = 0;
183 	cur_line = max_line = nflushd_lines = this_line = 0;
184 	cur_set = last_set = CS_NORMAL;
185 	lines = l = alloc_line();
186 
187 	while ((ch = getwchar()) != WEOF) {
188 		if (!iswgraph(ch)) {
189 			switch (ch) {
190 			case BS:		/* can't go back further */
191 				if (cur_col == 0)
192 					continue;
193 				--cur_col;
194 				continue;
195 			case CR:
196 				cur_col = 0;
197 				continue;
198 			case ESC:		/* just ignore EOF */
199 				switch(getwchar()) {
200 				/*
201 				 * In the input stream, accept both the
202 				 * XPG5 sequences ESC-digit and the
203 				 * traditional BSD sequences ESC-ctrl.
204 				 */
205 				case '\007':
206 					/* FALLTHROUGH */
207 				case RLF:
208 					addto_lineno(&cur_line, -2);
209 					break;
210 				case '\010':
211 					/* FALLTHROUGH */
212 				case RHLF:
213 					addto_lineno(&cur_line, -1);
214 					break;
215 				case '\011':
216 					/* FALLTHROUGH */
217 				case FHLF:
218 					addto_lineno(&cur_line, 1);
219 					if (cur_line > max_line)
220 						max_line = cur_line;
221 				}
222 				continue;
223 			case NL:
224 				addto_lineno(&cur_line, 2);
225 				if (cur_line > max_line)
226 					max_line = cur_line;
227 				cur_col = 0;
228 				continue;
229 			case SPACE:
230 				++cur_col;
231 				continue;
232 			case SI:
233 				cur_set = CS_NORMAL;
234 				continue;
235 			case SO:
236 				cur_set = CS_ALTERNATE;
237 				continue;
238 			case TAB:		/* adjust column */
239 				cur_col |= 7;
240 				++cur_col;
241 				continue;
242 			case VT:
243 				addto_lineno(&cur_line, -2);
244 				continue;
245 			}
246 			if (iswspace(ch)) {
247 				if ((width = wcwidth(ch)) > 0)
248 					cur_col += width;
249 				continue;
250 			}
251 			if (!pass_unknown_seqs)
252 				continue;
253 		}
254 
255 		/* Must stuff ch in a line - are we at the right one? */
256 		if (cur_line + adjust != this_line) {
257 			LINE *lnew;
258 
259 			/* round up to next line */
260 			adjust = !fine && (cur_line & 1);
261 
262 			if (cur_line + adjust < this_line) {
263 				while (cur_line + adjust < this_line &&
264 				    l->l_prev != NULL) {
265 					l = l->l_prev;
266 					this_line--;
267 				}
268 				if (cur_line + adjust < this_line) {
269 					if (nflushd_lines == 0) {
270 						/*
271 						 * Allow backup past first
272 						 * line if nothing has been
273 						 * flushed yet.
274 						 */
275 						while (cur_line + adjust
276 						    < this_line) {
277 							lnew = alloc_line();
278 							l->l_prev = lnew;
279 							lnew->l_next = l;
280 							l = lines = lnew;
281 							extra_lines++;
282 							this_line--;
283 						}
284 					} else {
285 						if (!warned++)
286 							dowarn(cur_line);
287 						cur_line = this_line - adjust;
288 					}
289 				}
290 			} else {
291 				/* may need to allocate here */
292 				while (cur_line + adjust > this_line) {
293 					if (l->l_next == NULL) {
294 						l->l_next = alloc_line();
295 						l->l_next->l_prev = l;
296 					}
297 					l = l->l_next;
298 					this_line++;
299 				}
300 			}
301 			if (this_line > nflushd_lines &&
302 			    this_line - nflushd_lines >=
303 			    max_bufd_lines + BUFFER_MARGIN) {
304 				if (extra_lines) {
305 					flush_lines(extra_lines);
306 					extra_lines = 0;
307 				}
308 				flush_lines(this_line - nflushd_lines -
309 				    max_bufd_lines);
310 				nflushd_lines = this_line - max_bufd_lines;
311 			}
312 		}
313 		/* grow line's buffer? */
314 		if (l->l_line_len + 1 >= l->l_lsize) {
315 			int need;
316 
317 			need = l->l_lsize ? l->l_lsize * 2 : 90;
318 			if ((l->l_line = realloc(l->l_line,
319 			    (unsigned)need * sizeof(CHAR))) == NULL)
320 				err(1, NULL);
321 			l->l_lsize = need;
322 		}
323 		c = &l->l_line[l->l_line_len++];
324 		c->c_char = ch;
325 		c->c_set = cur_set;
326 		c->c_column = cur_col;
327 		c->c_width = wcwidth(ch);
328 		/*
329 		 * If things are put in out of order, they will need sorting
330 		 * when it is flushed.
331 		 */
332 		if (cur_col < l->l_max_col)
333 			l->l_needs_sort = 1;
334 		else
335 			l->l_max_col = cur_col;
336 		if (c->c_width > 0)
337 			cur_col += c->c_width;
338 	}
339 	if (ferror(stdin))
340 		err(1, NULL);
341 	if (extra_lines) {
342 		/*
343 		 * Extra lines only exist if no lines have been flushed
344 		 * yet. This means that 'lines' must point to line zero
345 		 * after we flush the extra lines.
346 		 */
347 		flush_lines(extra_lines);
348 		l = lines;
349 		this_line = 0;
350 	}
351 
352 	/* goto the last line that had a character on it */
353 	for (; l->l_next; l = l->l_next)
354 		this_line++;
355 	flush_lines(this_line - nflushd_lines + 1);
356 
357 	/* make sure we leave things in a sane state */
358 	if (last_set != CS_NORMAL)
359 		PUTC(SI);
360 
361 	/* flush out the last few blank lines */
362 	if (max_line >= this_line)
363 		nblank_lines = max_line - this_line + (max_line & 1);
364 	if (nblank_lines == 0)
365 		/* end with a newline even if the source doesn't */
366 		nblank_lines = 2;
367 	flush_blanks();
368 	exit(0);
369 }
370 
371 /*
372  * Prints the first 'nflush' lines. Printed lines are freed.
373  * After this function returns, 'lines' points to the first
374  * of the remaining lines, and 'nblank_lines' will have the
375  * number of half line feeds between the final flushed line
376  * and the first remaining line.
377  */
378 static void
379 flush_lines(int nflush)
380 {
381 	LINE *l;
382 
383 	while (--nflush >= 0) {
384 		l = lines;
385 		lines = l->l_next;
386 		if (l->l_line) {
387 			flush_blanks();
388 			flush_line(l);
389 			free(l->l_line);
390 		}
391 		if (l->l_next)
392 			nblank_lines++;
393 		free_line(l);
394 	}
395 	if (lines)
396 		lines->l_prev = NULL;
397 }
398 
399 /*
400  * Print a number of newline/half newlines.
401  * nblank_lines is the number of half line feeds.
402  */
403 static void
404 flush_blanks(void)
405 {
406 	int half, i, nb;
407 
408 	half = 0;
409 	nb = nblank_lines;
410 	if (nb & 1) {
411 		if (fine)
412 			half = 1;
413 		else
414 			nb++;
415 	}
416 	nb /= 2;
417 	for (i = nb; --i >= 0;)
418 		PUTC('\n');
419 	if (half) {
420 		PUTC(ESC);
421 		PUTC(FHLF);
422 		if (!nb)
423 			PUTC('\r');
424 	}
425 	nblank_lines = 0;
426 }
427 
428 /*
429  * Write a line to stdout taking care of space to tab conversion (-h flag)
430  * and character set shifts.
431  */
432 static void
433 flush_line(LINE *l)
434 {
435 	CHAR *c, *endc;
436 	int i, j, nchars, last_col, save, this_col, tot;
437 
438 	last_col = 0;
439 	nchars = l->l_line_len;
440 
441 	if (l->l_needs_sort) {
442 		static CHAR *sorted;
443 		static int count_size, *count, sorted_size;
444 
445 		/*
446 		 * Do an O(n) sort on l->l_line by column being careful to
447 		 * preserve the order of characters in the same column.
448 		 */
449 		if (l->l_lsize > sorted_size) {
450 			sorted_size = l->l_lsize;
451 			if ((sorted = realloc(sorted,
452 			    (unsigned)sizeof(CHAR) * sorted_size)) == NULL)
453 				err(1, NULL);
454 		}
455 		if (l->l_max_col >= count_size) {
456 			count_size = l->l_max_col + 1;
457 			if ((count = realloc(count,
458 			    (unsigned)sizeof(int) * count_size)) == NULL)
459 				err(1, NULL);
460 		}
461 		memset(count, 0, sizeof(int) * l->l_max_col + 1);
462 		for (i = nchars, c = l->l_line; --i >= 0; c++)
463 			count[c->c_column]++;
464 
465 		/*
466 		 * calculate running total (shifted down by 1) to use as
467 		 * indices into new line.
468 		 */
469 		for (tot = 0, i = 0; i <= l->l_max_col; i++) {
470 			save = count[i];
471 			count[i] = tot;
472 			tot += save;
473 		}
474 
475 		for (i = nchars, c = l->l_line; --i >= 0; c++)
476 			sorted[count[c->c_column]++] = *c;
477 		c = sorted;
478 	} else
479 		c = l->l_line;
480 	while (nchars > 0) {
481 		this_col = c->c_column;
482 		endc = c;
483 		do {
484 			++endc;
485 		} while (--nchars > 0 && this_col == endc->c_column);
486 
487 		/* if -b only print last character */
488 		if (no_backspaces) {
489 			c = endc - 1;
490 			if (nchars > 0 &&
491 			    this_col + c->c_width > endc->c_column)
492 				continue;
493 		}
494 
495 		if (this_col > last_col) {
496 			int nspace = this_col - last_col;
497 
498 			if (compress_spaces && nspace > 1) {
499 				while (1) {
500 					int tab_col, tab_size;
501 
502 					tab_col = (last_col + 8) & ~7;
503 					if (tab_col > this_col)
504 						break;
505 					tab_size = tab_col - last_col;
506 					if (tab_size == 1)
507 						PUTC(' ');
508 					else
509 						PUTC('\t');
510 					nspace -= tab_size;
511 					last_col = tab_col;
512 				}
513 			}
514 			while (--nspace >= 0)
515 				PUTC(' ');
516 			last_col = this_col;
517 		}
518 
519 		for (;;) {
520 			if (c->c_set != last_set) {
521 				switch (c->c_set) {
522 				case CS_NORMAL:
523 					PUTC(SI);
524 					break;
525 				case CS_ALTERNATE:
526 					PUTC(SO);
527 				}
528 				last_set = c->c_set;
529 			}
530 			PUTC(c->c_char);
531 			if ((c + 1) < endc)
532 				for (j = 0; j < c->c_width; j++)
533 					PUTC('\b');
534 			if (++c >= endc)
535 				break;
536 		}
537 		last_col += (c - 1)->c_width;
538 	}
539 }
540 
541 /*
542  * Increment or decrement a line number, checking for overflow.
543  * Stop one below INT_MAX such that the adjust variable is safe.
544  */
545 void
546 addto_lineno(int *lno, int offset)
547 {
548 	if (offset > 0) {
549 		if (*lno >= INT_MAX - offset)
550 			errx(1, "too many lines");
551 	} else {
552 		if (*lno < INT_MIN - offset)
553 			errx(1, "too many reverse line feeds");
554 	}
555 	*lno += offset;
556 }
557 
558 #define	NALLOC 64
559 
560 static LINE *line_freelist;
561 
562 static LINE *
563 alloc_line(void)
564 {
565 	LINE *l;
566 	int i;
567 
568 	if (!line_freelist) {
569 		if ((l = realloc(NULL, sizeof(LINE) * NALLOC)) == NULL)
570 			err(1, NULL);
571 		line_freelist = l;
572 		for (i = 1; i < NALLOC; i++, l++)
573 			l->l_next = l + 1;
574 		l->l_next = NULL;
575 	}
576 	l = line_freelist;
577 	line_freelist = l->l_next;
578 
579 	memset(l, 0, sizeof(LINE));
580 	return (l);
581 }
582 
583 static void
584 free_line(LINE *l)
585 {
586 
587 	l->l_next = line_freelist;
588 	line_freelist = l;
589 }
590 
591 static void
592 usage(void)
593 {
594 
595 	(void)fprintf(stderr, "usage: col [-bfhpx] [-l nline]\n");
596 	exit(1);
597 }
598 
599 static void
600 dowarn(int line)
601 {
602 
603 	warnx("warning: can't back up %s",
604 		line < 0 ? "past first line" : "-- line already flushed");
605 }
606