fixed col's entab algorithm which was losing spaces
[unix-history] / usr.bin / col / col.c
CommitLineData
15637ed4
RG
1/*-
2 * Copyright (c) 1990 The Regents of the University of California.
3 * 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
38char copyright[] =
39"@(#) Copyright (c) 1990 The Regents of the University of California.\n\
40 All rights reserved.\n";
41#endif /* not lint */
42
43#ifndef lint
44static char sccsid[] = "@(#)col.c 5.3 (Berkeley) 2/2/91";
45#endif /* not lint */
46
47#include <errno.h>
48#include <ctype.h>
49#include <string.h>
50#include <stdio.h>
51
52#define BS '\b' /* backspace */
53#define TAB '\t' /* tab */
54#define SPACE ' ' /* space */
55#define NL '\n' /* newline */
56#define CR '\r' /* carriage return */
57#define ESC '\033' /* escape */
58#define SI '\017' /* shift in to normal character set */
59#define SO '\016' /* shift out to alternate character set */
60#define VT '\013' /* vertical tab (aka reverse line feed) */
61#define RLF '\007' /* ESC-07 reverse line feed */
62#define RHLF '\010' /* ESC-010 reverse half-line feed */
63#define FHLF '\011' /* ESC-011 forward half-line feed */
64
65/* build up at least this many lines before flushing them out */
66#define BUFFER_MARGIN 32
67
68typedef char CSET;
69
70typedef struct char_str {
71#define CS_NORMAL 1
72#define CS_ALTERNATE 2
73 short c_column; /* column character is in */
74 CSET c_set; /* character set (currently only 2) */
75 char c_char; /* character in question */
76} CHAR;
77
78typedef struct line_str LINE;
79struct line_str {
80 CHAR *l_line; /* characters on the line */
81 LINE *l_prev; /* previous line */
82 LINE *l_next; /* next line */
83 int l_lsize; /* allocated sizeof l_line */
84 int l_line_len; /* strlen(l_line) */
85 int l_needs_sort; /* set if chars went in out of order */
86 int l_max_col; /* max column in the line */
87};
88
89LINE *alloc_line();
90void *xmalloc();
91
92CSET last_set; /* char_set of last char printed */
93LINE *lines;
94int compress_spaces; /* if doing space -> tab conversion */
95int fine; /* if `fine' resolution (half lines) */
96int max_bufd_lines; /* max # lines to keep in memory */
97int nblank_lines; /* # blanks after last flushed line */
98int no_backspaces; /* if not to output any backspaces */
99
100#define PUTC(ch) \
101 if (putchar(ch) == EOF) \
102 wrerr();
103
c4ed8671
AM
104/* next tabstop after col */
105#define TABSTOP(col,ts) ((col) + (ts) - (col) % (ts))
106
15637ed4
RG
107main(argc, argv)
108 int argc;
109 char **argv;
110{
111 extern int optind;
112 extern char *optarg;
113 register int ch;
114 CHAR *c;
115 CSET cur_set; /* current character set */
116 LINE *l; /* current line */
117 int extra_lines; /* # of lines above first line */
118 int cur_col; /* current column */
119 int cur_line; /* line number of current position */
120 int max_line; /* max value of cur_line */
121 int this_line; /* line l points to */
122 int nflushd_lines; /* number of lines that were flushed */
123 int adjust, opt, warned;
124
125 max_bufd_lines = 128;
126 compress_spaces = 1; /* compress spaces into tabs */
127 while ((opt = getopt(argc, argv, "bfhl:x")) != EOF)
128 switch (opt) {
129 case 'b': /* do not output backspaces */
130 no_backspaces = 1;
131 break;
132 case 'f': /* allow half forward line feeds */
133 fine = 1;
134 break;
135 case 'h': /* compress spaces into tabs */
136 compress_spaces = 1;
137 break;
138 case 'l': /* buffered line count */
139 if ((max_bufd_lines = atoi(optarg)) <= 0) {
140 (void)fprintf(stderr,
141 "col: bad -l argument %s.\n", optarg);
142 exit(1);
143 }
144 break;
145 case 'x': /* do not compress spaces into tabs */
146 compress_spaces = 0;
147 break;
148 case '?':
149 default:
150 usage();
151 }
152
153 if (optind != argc)
154 usage();
155
156 /* this value is in half lines */
157 max_bufd_lines *= 2;
158
159 adjust = cur_col = extra_lines = warned = 0;
160 cur_line = max_line = nflushd_lines = this_line = 0;
161 cur_set = last_set = CS_NORMAL;
162 lines = l = alloc_line();
163
164 while ((ch = getchar()) != EOF) {
165 if (!isgraph(ch)) {
166 switch (ch) {
167 case BS: /* can't go back further */
168 if (cur_col == 0)
169 continue;
170 --cur_col;
171 continue;
172 case CR:
173 cur_col = 0;
174 continue;
175 case ESC: /* just ignore EOF */
176 switch(getchar()) {
177 case RLF:
178 cur_line -= 2;
179 break;
180 case RHLF:
181 cur_line--;
182 break;
183 case FHLF:
184 cur_line++;
185 if (cur_line > max_line)
186 max_line = cur_line;
187 }
188 continue;
189 case NL:
190 cur_line += 2;
191 if (cur_line > max_line)
192 max_line = cur_line;
193 cur_col = 0;
194 continue;
195 case SPACE:
196 ++cur_col;
197 continue;
198 case SI:
199 cur_set = CS_NORMAL;
200 continue;
201 case SO:
202 cur_set = CS_ALTERNATE;
203 continue;
204 case TAB: /* adjust column */
205 cur_col |= 7;
206 ++cur_col;
207 continue;
208 case VT:
209 cur_line -= 2;
210 continue;
211 }
212 continue;
213 }
214
215 /* Must stuff ch in a line - are we at the right one? */
216 if (cur_line != this_line - adjust) {
217 LINE *lnew;
218 int nmove;
219
220 adjust = 0;
221 nmove = cur_line - this_line;
222 if (!fine) {
223 /* round up to next line */
224 if (cur_line & 1) {
225 adjust = 1;
226 nmove++;
227 }
228 }
229 if (nmove < 0) {
230 for (; nmove < 0 && l->l_prev; nmove++)
231 l = l->l_prev;
232 if (nmove) {
233 if (nflushd_lines == 0) {
234 /*
235 * Allow backup past first
236 * line if nothing has been
237 * flushed yet.
238 */
239 for (; nmove < 0; nmove++) {
240 lnew = alloc_line();
241 l->l_prev = lnew;
242 lnew->l_next = l;
243 l = lines = lnew;
244 extra_lines++;
245 }
246 } else {
247 if (!warned++)
248 warn(cur_line);
249 cur_line -= nmove;
250 }
251 }
252 } else {
253 /* may need to allocate here */
254 for (; nmove > 0 && l->l_next; nmove--)
255 l = l->l_next;
256 for (; nmove > 0; nmove--) {
257 lnew = alloc_line();
258 lnew->l_prev = l;
259 l->l_next = lnew;
260 l = lnew;
261 }
262 }
263 this_line = cur_line + adjust;
264 nmove = this_line - nflushd_lines;
265 if (nmove >= max_bufd_lines + BUFFER_MARGIN) {
266 nflushd_lines += nmove - max_bufd_lines;
267 flush_lines(nmove - max_bufd_lines);
268 }
269 }
270 /* grow line's buffer? */
271 if (l->l_line_len + 1 >= l->l_lsize) {
272 int need;
273
274 need = l->l_lsize ? l->l_lsize * 2 : 90;
275 l->l_line = (CHAR *)xmalloc((void *) l->l_line,
276 (unsigned) need * sizeof(CHAR));
277 l->l_lsize = need;
278 }
279 c = &l->l_line[l->l_line_len++];
280 c->c_char = ch;
281 c->c_set = cur_set;
282 c->c_column = cur_col;
283 /*
284 * If things are put in out of order, they will need sorting
285 * when it is flushed.
286 */
287 if (cur_col < l->l_max_col)
288 l->l_needs_sort = 1;
289 else
290 l->l_max_col = cur_col;
291 cur_col++;
292 }
293 /* goto the last line that had a character on it */
294 for (; l->l_next; l = l->l_next)
295 this_line++;
296 flush_lines(this_line - nflushd_lines + extra_lines + 1);
297
298 /* make sure we leave things in a sane state */
299 if (last_set != CS_NORMAL)
300 PUTC('\017');
301
302 /* flush out the last few blank lines */
303 nblank_lines = max_line - this_line;
304 if (max_line & 1)
305 nblank_lines++;
306 else if (!nblank_lines)
307 /* missing a \n on the last line? */
308 nblank_lines = 2;
309 flush_blanks();
310 exit(0);
311}
312
313flush_lines(nflush)
314 int nflush;
315{
316 LINE *l;
317
318 while (--nflush >= 0) {
319 l = lines;
320 lines = l->l_next;
321 if (l->l_line) {
322 flush_blanks();
323 flush_line(l);
324 }
325 nblank_lines++;
326 if (l->l_line)
327 (void)free((void *)l->l_line);
328 free_line(l);
329 }
330 if (lines)
331 lines->l_prev = NULL;
332}
333
334/*
335 * Print a number of newline/half newlines. If fine flag is set, nblank_lines
336 * is the number of half line feeds, otherwise it is the number of whole line
337 * feeds.
338 */
339flush_blanks()
340{
341 int half, i, nb;
342
343 half = 0;
344 nb = nblank_lines;
345 if (nb & 1) {
346 if (fine)
347 half = 1;
348 else
349 nb++;
350 }
351 nb /= 2;
352 for (i = nb; --i >= 0;)
353 PUTC('\n');
354 if (half) {
355 PUTC('\033');
356 PUTC('9');
357 if (!nb)
358 PUTC('\r');
359 }
360 nblank_lines = 0;
361}
362
363/*
364 * Write a line to stdout taking care of space to tab conversion (-h flag)
365 * and character set shifts.
366 */
367flush_line(l)
368 LINE *l;
369{
370 CHAR *c, *endc;
371 int nchars, last_col, this_col;
372
373 last_col = 0;
374 nchars = l->l_line_len;
375
376 if (l->l_needs_sort) {
377 static CHAR *sorted;
378 static int count_size, *count, i, save, sorted_size, tot;
379
380 /*
381 * Do an O(n) sort on l->l_line by column being careful to
382 * preserve the order of characters in the same column.
383 */
384 if (l->l_lsize > sorted_size) {
385 sorted_size = l->l_lsize;
386 sorted = (CHAR *)xmalloc((void *)sorted,
387 (unsigned)sizeof(CHAR) * sorted_size);
388 }
389 if (l->l_max_col >= count_size) {
390 count_size = l->l_max_col + 1;
391 count = (int *)xmalloc((void *)count,
392 (unsigned)sizeof(int) * count_size);
393 }
394 bzero((char *)count, sizeof(int) * l->l_max_col + 1);
395 for (i = nchars, c = l->l_line; --i >= 0; c++)
396 count[c->c_column]++;
397
398 /*
399 * calculate running total (shifted down by 1) to use as
400 * indices into new line.
401 */
402 for (tot = 0, i = 0; i <= l->l_max_col; i++) {
403 save = count[i];
404 count[i] = tot;
405 tot += save;
406 }
407
408 for (i = nchars, c = l->l_line; --i >= 0; c++)
409 sorted[count[c->c_column]++] = *c;
410 c = sorted;
411 } else
412 c = l->l_line;
413 while (nchars > 0) {
414 this_col = c->c_column;
415 endc = c;
416 do {
417 ++endc;
418 } while (--nchars > 0 && this_col == endc->c_column);
419
420 /* if -b only print last character */
421 if (no_backspaces)
422 c = endc - 1;
423
424 if (this_col > last_col) {
425 int nspace = this_col - last_col;
426
427 if (compress_spaces && nspace > 1) {
428 int ntabs;
429
c4ed8671
AM
430 while ((ntabs = TABSTOP(last_col, 8)) <= this_col) {
431 PUTC('\t');
432 last_col = ntabs;
433 }
434 nspace = this_col - last_col;
435/*
15637ed4
RG
436 ntabs = this_col / 8 - last_col / 8;
437 nspace -= ntabs * 8;
438 while (--ntabs >= 0)
439 PUTC('\t');
c4ed8671 440*/
15637ed4
RG
441 }
442 while (--nspace >= 0)
443 PUTC(' ');
444 last_col = this_col;
445 }
446 last_col++;
447
448 for (;;) {
449 if (c->c_set != last_set) {
450 switch (c->c_set) {
451 case CS_NORMAL:
452 PUTC('\017');
453 break;
454 case CS_ALTERNATE:
455 PUTC('\016');
456 }
457 last_set = c->c_set;
458 }
459 PUTC(c->c_char);
460 if (++c >= endc)
461 break;
462 PUTC('\b');
463 }
464 }
465}
466
467#define NALLOC 64
468
469static LINE *line_freelist;
470
471LINE *
472alloc_line()
473{
474 LINE *l;
475 int i;
476
477 if (!line_freelist) {
478 l = (LINE *)xmalloc((void *)NULL, sizeof(LINE) * NALLOC);
479 line_freelist = l;
480 for (i = 1; i < NALLOC; i++, l++)
481 l->l_next = l + 1;
482 l->l_next = NULL;
483 }
484 l = line_freelist;
485 line_freelist = l->l_next;
486
487 bzero(l, sizeof(LINE));
488 return(l);
489}
490
491free_line(l)
492 LINE *l;
493{
494 l->l_next = line_freelist;
495 line_freelist = l;
496}
497
498void *
499xmalloc(p, size)
500 void *p;
501 size_t size;
502{
503 if (!(p = (void *)realloc(p, size))) {
504 (void)fprintf(stderr, "col: %s.\n", strerror(ENOMEM));
505 exit(1);
506 }
507 return(p);
508}
509
510usage()
511{
512 (void)fprintf(stderr, "usage: col [-bfx] [-l nline]\n");
513 exit(1);
514}
515
516wrerr()
517{
518 (void)fprintf(stderr, "col: write error.\n");
519 exit(1);
520}
521
522warn(line)
523 int line;
524{
525 (void)fprintf(stderr,
526 "col: warning: can't back up %s.\n", line < 0 ?
527 "past first line" : "-- line already flushed");
528}