2 * Copyright (c) 1991 Keith Muller.
4 * The Regents of the University of California. All rights reserved.
6 * This code is derived from software contributed to Berkeley by
7 * Keith Muller of the University of California, San Diego.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by the University of
20 * California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
41 static char copyright[] =
42 "@(#) Copyright (c) 1993\n\
43 The Regents of the University of California. All rights reserved.\n";
47 static char sccsid[] = "@(#)pr.c 8.2 (Berkeley) 4/16/94";
50 #include <sys/types.h>
67 * pr: a printing and pagination filter. If multiple input files
68 * are specified, each is read, formatted, and written to standard
69 * output. By default, input is seperated into 66-line pages, each
70 * with a header that includes the page number, date, time and the
73 * Complies with posix P1003.2/D11
79 int pgnm; /* starting page number */
80 int clcnt; /* number of columns */
81 int colwd; /* column data width - multiple columns */
82 int across; /* mult col flag; write across page */
83 int dspace; /* double space flag */
84 char inchar; /* expand input char */
85 int ingap; /* expand input gap */
86 int formfeed; /* use formfeed as trailer */
87 char *header; /* header name instead of file name */
88 char ochar; /* contract output char */
89 int ogap; /* contract output gap */
90 int lines; /* number of lines per page */
91 int merge; /* merge multiple files in output */
92 char nmchar; /* line numbering append char */
93 int nmwd; /* width of line number field */
94 int offst; /* number of page offset spaces */
95 int nodiag; /* do not report file open errors */
96 char schar; /* text column separation character */
97 int sflag; /* -s option for multiple columns */
98 int nohead; /* do not write head and trailer */
99 int pgwd; /* page width with multiple col output */
100 char *timefrmt; /* time conversion string */
105 FILE *err; /* error message file pointer */
106 int addone; /* page length is odd with double space */
107 int errcnt; /* error count on file processing */
108 char digs[] = "0123456789"; /* page number translation map */
117 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
118 (void)signal(SIGINT, terminate);
119 ret_val = setup(argc, argv);
122 * select the output format based on options
125 ret_val = mulfile(argc, argv);
127 ret_val = onecol(argc, argv);
129 ret_val = horzcol(argc, argv);
131 ret_val = vertcol(argc, argv);
135 if (errcnt || ret_val)
141 * onecol: print files with only one column of output.
142 * Line length is unlimited.
149 register int cnt = -1;
152 register int linecnt;
175 * allocate line buffer
177 if ((obuf = malloc((unsigned)(LBUF + off)*sizeof(char))) == NULL) {
182 * allocate header buffer
184 if ((hbuf = malloc((unsigned)(HDBUF + offst)*sizeof(char))) == NULL) {
189 ohbuf = hbuf + offst;
193 nbuf[--num] = nmchar;
195 (void)memset(obuf, (int)' ', offst);
196 (void)memset(hbuf, (int)' ', offst);
202 while ((inf = nxtfile(argc, argv, &fname, ohbuf, 0)) != NULL) {
205 * skip to specified page
207 if (inskip(inf, pgnm, lines))
227 while (linecnt < lines) {
231 if ((cnt = inln(inf,lbuf,LBUF,&cps,0,&mor)) < 0)
233 if (!linecnt && !nohead &&
234 prhead(hbuf, fname, pagecnt))
242 addnum(nbuf, num, ++lncnt);
243 if (otln(obuf,cnt+off, &ips, &ops, mor))
245 } else if (otln(lbuf, cnt, &ips, &ops, mor))
249 * if line bigger than buffer, get more
257 * whole line rcvd. reset tab proc. state
266 * fill to end of page
268 if (linecnt && prtail(lines-linecnt-lrgln, lrgln))
272 * On EOF go to next file
287 * vertcol: print files with more than one column of output down a page
295 register char **lstdat;
298 register int cnt = -1;
307 int mxlen = pgwd + offst + 1;
308 int mclcnt = clcnt - 1;
325 * allocate page buffer
327 if ((buf = malloc((unsigned)lines*mxlen*sizeof(char))) == NULL) {
333 * allocate page header
335 if ((hbuf = malloc((unsigned)(HDBUF + offst)*sizeof(char))) == NULL) {
339 ohbuf = hbuf + offst;
341 (void)memset(hbuf, (int)' ', offst);
344 * col pointers when no headers
348 (struct vcol *)malloc((unsigned)mvc*sizeof(struct vcol))) == NULL) {
354 * pointer into page where last data per line is located
356 if ((lstdat = (char **)malloc((unsigned)lines*sizeof(char *))) == NULL){
362 * fast index lookups to locate start of lines
364 if ((indy = (int *)malloc((unsigned)lines*sizeof(int))) == NULL) {
368 if ((lindy = (int *)malloc((unsigned)lines*sizeof(int))) == NULL) {
379 * initialize buffer lookup indexes and offset area
381 for (j = 0; j < lines; ++j) {
382 lindy[j] = j * mxlen;
383 indy[j] = lindy[j] + offst;
385 ptbf = buf + lindy[j];
386 (void)memset(ptbf, (int)' ', offst);
389 ptbf = buf + indy[j];
396 while ((inf = nxtfile(argc, argv, &fname, ohbuf, 0)) != NULL) {
399 * skip to requested page
401 if (inskip(inf, pgnm, lines))
416 for (i = 0; i < clcnt; ++i) {
419 * if last column, do not pad
430 * is this first column
433 ptbf = buf + indy[j];
443 addnum(ptbf, nmwd, ++lncnt);
451 cnt = inln(inf,ptbf,colwd,&cps,1,&mor);
458 * pad all but last column on page
462 * pad to end of column
466 else if ((pln = col-cnt) > 0) {
473 * remember last char in line
484 * when -t (no header) is specified the spec requires
485 * the min number of lines. The last page may not have
486 * balanced length columns. To fix this we must reorder
487 * the columns. This is a very slow technique so it is
488 * only used under limited conditions. Without -t, the
489 * balancing of text columns is unspecified. To NOT
490 * balance the last page, add the global variable
491 * nohead to the if statement below e.g.
493 * if ((cnt < 0) && nohead && cvc ......
498 * check to see if last page needs to be reordered
500 if ((cnt < 0) && cvc && ((mvc-cvc) >= clcnt)){
508 if (!nohead && prhead(hbuf, fname, pagecnt))
510 for (i = 0; i < pln; ++i) {
513 if (offst&& otln(buf,offst,&ips,&ops,1))
517 for (j = 0; j < clcnt; ++j) {
519 * determine column length
532 cnt = vc[tvc].cnt + 1;
537 if (otln(vc[tvc].pt, cnt, &ips,
547 if (otln(buf, 0, &ips, &ops, 0))
553 if (prtail((lines - pln), 0))
556 * done with output, go to next file
562 * determine how many lines to output
572 if (pln && !nohead && prhead(hbuf, fname, pagecnt))
578 for (i = 0; i < pln; ++i) {
579 ptbf = buf + lindy[i];
580 if ((j = lstdat[i] - ptbf) <= offst)
582 if (otln(ptbf, j, &ips, &ops, 0))
589 if (pln && prtail((lines - pln), 0))
593 * if EOF go to next file
608 * horzcol: print files with more than one column of output across a page
617 register int cnt = -1;
618 register char *lstdat;
619 register int col = colwd + 1;
634 if ((buf = malloc((unsigned)(pgwd+offst+1)*sizeof(char))) == NULL) {
642 if ((hbuf = malloc((unsigned)(HDBUF + offst)*sizeof(char))) == NULL) {
646 ohbuf = hbuf + offst;
648 (void)memset(buf, (int)' ', offst);
649 (void)memset(hbuf, (int)' ', offst);
655 while ((inf = nxtfile(argc, argv, &fname, ohbuf, 0)) != NULL) {
657 if (inskip(inf, pgnm, lines))
671 for (i = 0; i < lines; ++i) {
681 * add number to column
683 addnum(ptbf, nmwd, ++lncnt);
690 if ((cnt = inln(inf,ptbf,colwd,&cps,1,
697 * if last line skip padding
703 * pad to end of column
707 else if ((pln = col - cnt) > 0) {
708 (void)memset(ptbf,(int)' ',pln);
714 * determine line length
716 if ((j = lstdat - buf) <= offst)
719 prhead(hbuf, fname, pagecnt))
724 if (otln(buf, j, &ips, &ops, 0))
731 if (i && prtail(lines-i, 0))
735 * if EOF go to next file
750 * mulfile: print files with more than one column of output and
751 * more than one file concurrently
762 register char *lstdat;
780 * array of FILE *, one for each operand
782 if ((fbuf = (FILE **)malloc((unsigned)clcnt*sizeof(FILE *))) == NULL) {
790 if ((hbuf = malloc((unsigned)(HDBUF + offst)*sizeof(char))) == NULL) {
794 ohbuf = hbuf + offst;
797 * do not know how many columns yet. The number of operands provide an
798 * upper bound on the number of columns. We use the number of files
799 * we can open successfully to set the number of columns. The operation
800 * of the merge operation (-m) in relation to unsuccesful file opens
801 * is unspecified by posix.
805 if ((fbuf[j] = nxtfile(argc, argv, &fname, ohbuf, 1)) == NULL)
807 if (pgnm && (inskip(fbuf[j], pgnm, lines)))
819 * calculate page boundries based on open file count
823 colwd = (pgwd - clcnt - nmwd)/clcnt;
824 pgwd = ((colwd + 1) * clcnt) - nmwd - 2;
826 colwd = (pgwd + 1 - clcnt)/clcnt;
827 pgwd = ((colwd + 1) * clcnt) - 1;
831 "pr: page width too small for %d columns\n", clcnt);
840 if ((buf = malloc((unsigned)(pgwd+offst+1)*sizeof(char))) == NULL) {
845 (void)memset(buf, (int)' ', offst);
846 (void)memset(hbuf, (int)' ', offst);
855 * continue to loop while any file still has data
861 for (i = 0; i < lines; ++i) {
866 * add line number to line
868 addnum(ptbf, nmwd, ++lncnt);
878 for (j = 0; j < clcnt; ++j) {
879 if (fbuf[j] == NULL) {
884 } else if ((cnt = inln(fbuf[j], ptbf, colwd,
885 &cps, 1, &mor)) < 0) {
889 if (fbuf[j] != stdin)
890 (void)fclose(fbuf[j]);
904 * if last ACTIVE column, done with line
910 * pad to end of column
914 } else if ((pln = col - cnt) > 0) {
915 (void)memset(ptbf, (int)' ', pln);
921 * calculate data in line
923 if ((j = lstdat - buf) <= offst)
926 if (!i && !nohead && prhead(hbuf, fname, pagecnt))
932 if (otln(buf, j, &ips, &ops, 0))
936 * if no more active files, done
947 if (i && prtail(lines-i, 0))
957 * inln(): input a line of data (unlimited length lines supported)
958 * Input is optionally expanded to spaces
963 * cps: column positon 1st char in buffer (large line support)
964 * trnc: throw away data more than lim up to \n
965 * mor: set if more data in line (not truncated)
968 inln(inf, buf, lim, cps, trnc, mor)
977 register int gap = ingap;
978 register int ch = EOF;
979 register char *ptbuf;
980 register int chk = (int)inchar;
986 * expanding input option
988 while ((--lim >= 0) && ((ch = getc(inf)) != EOF)) {
990 * is this the input "tab" char
994 * expand to number of spaces
996 col = (ptbuf - buf) + *cps;
997 col = gap - (col % gap);
1000 * if more than this line, push back
1002 if ((col > lim) && (ungetc(ch, inf) == EOF))
1008 while ((--col >= 0) && (--lim >= 0))
1020 while ((--lim >= 0) && ((ch = getc(inf)) != EOF)) {
1036 * entire line processed
1044 * line was larger than limit
1048 * throw away rest of line
1050 while ((ch = getc(inf)) != EOF) {
1058 * save column offset if not truncated
1068 * otln(): output a line of data. (Supports unlimited length lines)
1069 * output is optionally contracted to tabs
1071 * buf: output buffer with data
1072 * cnt: number of chars of valid data in buf
1073 * svips: buffer input column position (for large lines)
1074 * svops: buffer output column position (for large lines)
1075 * mor: output line not complete in this buf; more data to come.
1076 * 1 is more, 0 is complete, -1 is no \n's
1079 otln(buf, cnt, svips, svops, mor)
1086 register int ops; /* last col output */
1087 register int ips; /* last col in buf examined */
1088 register int gap = ogap;
1090 register char *endbuf;
1094 * contracting on output
1099 while (buf < endbuf) {
1101 * count number of spaces and ochar in buffer
1110 * simulate ochar processing
1112 if (*buf == ochar) {
1113 ips += gap - (ips % gap);
1119 * got a non space char; contract out spaces
1123 * use as many ochar as will fit
1125 if ((tbps = ops + gap - (ops % gap)) > ips)
1127 if (putchar(ochar) == EOF) {
1136 * finish off with spaces
1138 if (putchar(' ') == EOF) {
1146 * output non space char
1148 if (putchar(*buf++) == EOF) {
1158 * if incomplete line, save position counts
1168 * use as many ochar as will fit
1170 if ((tbps = ops + gap - (ops % gap)) > ips)
1172 if (putchar(ochar) == EOF) {
1180 * finish off with spaces
1182 if (putchar(' ') == EOF) {
1192 * output is not contracted
1194 if (cnt && (fwrite(buf, sizeof(char), cnt, stdout) <= 0)) {
1203 * process line end and double space as required
1205 if ((putchar('\n') == EOF) || (dspace && (putchar('\n') == EOF))) {
1213 * inskip(): skip over pgcnt pages with lncnt lines per page
1214 * file is closed at EOF (if not stdin).
1216 * inf FILE * to read from
1217 * pgcnt number of pages to skip
1218 * lncnt number of lines per page
1221 inskip(inf, pgcnt, lncnt)
1229 while(--pgcnt > 0) {
1231 while ((c = getc(inf)) != EOF) {
1232 if ((c == '\n') && (--cnt == 0))
1245 * nxtfile: returns a FILE * to next file in arg list and sets the
1246 * time field for this file (or current date).
1248 * buf array to store proper date for the header.
1249 * dt if set skips the date processing (used with -m)
1252 nxtfile(argc, argv, fname, buf, dt)
1263 struct tm *timeptr = NULL;
1264 struct stat statbuf;
1265 static int twice = -1;
1268 if (eoptind >= argc) {
1270 * no file listed; default, use standard input
1282 if (gettimeofday(&tv, &tz) < 0) {
1284 (void)fprintf(err, "pr: cannot get time of day, %s\n",
1290 timeptr = localtime(&tv_sec);
1292 for (; eoptind < argc; ++eoptind) {
1293 if (strcmp(argv[eoptind], "-") == 0) {
1295 * process a "-" for filename
1304 if (nohead || (dt && twice))
1306 if (gettimeofday(&tv, &tz) < 0) {
1309 "pr: cannot get time of day, %s\n",
1314 timeptr = localtime(&tv_sec);
1317 * normal file processing
1319 if ((inf = fopen(argv[eoptind], "r")) == NULL) {
1323 (void)fprintf(err, "pr: Cannot open %s, %s\n",
1324 argv[eoptind], strerror(errno));
1332 *fname = argv[eoptind];
1334 if (nohead || (dt && twice))
1338 if (gettimeofday(&tv, &tz) < 0) {
1341 "pr: cannot get time of day, %s\n",
1346 timeptr = localtime(&tv_sec);
1348 if (fstat(fileno(inf), &statbuf) < 0) {
1352 "pr: Cannot stat %s, %s\n",
1353 argv[eoptind], strerror(errno));
1356 timeptr = localtime(&(statbuf.st_mtime));
1365 * set up time field used in header
1367 if (strftime(buf, HDBUF, timefrmt, timeptr) <= 0) {
1371 (void)fputs("pr: time conversion failed\n", err);
1378 * addnum(): adds the line number to the column
1379 * Truncates from the front or pads with spaces as required.
1380 * Numbers are right justified.
1382 * buf buffer to store the number
1383 * wdth width of buffer to fill
1386 * NOTE: numbers occupy part of the column. The posix
1387 * spec does not specify if -i processing should or should not
1388 * occur on number padding. The spec does say it occupies
1389 * part of the column. The usage of addnum currently treats
1390 * numbers as part of the column so spaces may be replaced.
1393 addnum(buf, wdth, line)
1398 register char *pt = buf + wdth;
1401 *--pt = digs[line % 10];
1403 } while (line && (pt > buf));
1406 * pad with space as required
1413 * prhead(): prints the top of page header
1415 * buf buffer with time field (and offset)
1416 * cnt number of chars in buf
1417 * fname fname field for header
1418 * pagcnt page number
1421 prhead(buf, fname, pagcnt)
1429 if ((putchar('\n') == EOF) || (putchar('\n') == EOF)) {
1434 * posix is not clear if the header is subject to line length
1435 * restrictions. The specification for header line format
1436 * in the spec clearly does not limit length. No pr currently
1437 * restricts header length. However if we need to truncate in
1438 * an reasonable way, adjust the length of the printf by
1439 * changing HDFMT to allow a length max as an arguement printf.
1440 * buf (which contains the offset spaces and time field could
1443 * note only the offset (if any) is processed for tab expansion
1445 if (offst && otln(buf, offst, &ips, &ops, -1))
1447 (void)printf(HDFMT,buf+offst, fname, pagcnt);
1452 * prtail(): pad page with empty lines (if required) and print page trailer
1455 * cnt number of lines of padding needed
1456 * incomp was a '\n' missing from last line output
1465 * only pad with no headers when incomplete last line
1468 ((dspace && (putchar('\n') == EOF)) ||
1469 (putchar('\n') == EOF))) {
1474 * but honor the formfeed request
1477 if (putchar('\f') == EOF) {
1485 * if double space output two \n
1491 * if an odd number of lines per page, add an extra \n
1500 if ((incomp && (putchar('\n') == EOF)) ||
1501 (putchar('\f') == EOF)) {
1508 while (--cnt >= 0) {
1509 if (putchar('\n') == EOF) {
1518 * terminate(): when a SIGINT is recvd
1521 terminate(which_sig)
1530 * flsh_errs(): output saved up diagnostic messages after all normal
1531 * processing has completed
1538 (void)fflush(stdout);
1543 while (fgets(buf, BUFSIZ, err) != NULL)
1544 (void)fputs(buf, stderr);
1550 (void)fputs("pr: memory allocation failed\n", err);
1556 (void)fprintf(err, "pr: write failure, %s\n", strerror(errno));
1563 "usage: pr [+page] [-col] [-adFmrt] [-e[ch][gap]] [-h header]\n",err);
1565 " [-i[ch][gap]] [-l line] [-n[ch][width]] [-o offset]\n",err);
1567 " [-L locale] [-s[ch]] [-w width] [-] [file ...]\n", err);
1571 * setup: Validate command args, initialize and perform sanity
1577 register char **argv;
1586 if (isatty(fileno(stdout))) {
1588 * defer diagnostics until processing is done
1590 if ((err = tmpfile()) == NULL) {
1591 (void)fputs("Cannot defer diagnostic messages\n",stderr);
1596 while ((c = egetopt(argc, argv, "#adFmrte?h:i?L:l:n?o:s?w:")) != -1) {
1599 if ((pgnm = atoi(eoptarg)) < 1) {
1600 (void)fputs("pr: +page number must be 1 or more\n",
1606 if ((clcnt = atoi(eoptarg)) < 1) {
1607 (void)fputs("pr: -columns must be 1 or more\n",err);
1621 if ((eoptarg != NULL) && !isdigit((unsigned char)*eoptarg))
1622 inchar = *eoptarg++;
1625 if ((eoptarg != NULL) && isdigit((unsigned char)*eoptarg)) {
1626 if ((ingap = atoi(eoptarg)) < 0) {
1628 "pr: -e gap must be 0 or more\n", err);
1633 } else if ((eoptarg != NULL) && (*eoptarg != '\0')) {
1635 "pr: invalid value for -e %s\n", eoptarg);
1648 if ((eoptarg != NULL) && !isdigit((unsigned char)*eoptarg))
1652 if ((eoptarg != NULL) && isdigit((unsigned char)*eoptarg)) {
1653 if ((ogap = atoi(eoptarg)) < 0) {
1655 "pr: -i gap must be 0 or more\n", err);
1660 } else if ((eoptarg != NULL) && (*eoptarg != '\0')) {
1662 "pr: invalid value for -i %s\n", eoptarg);
1671 if (!isdigit((unsigned char)*eoptarg) || ((lines=atoi(eoptarg)) < 1)) {
1673 "pr: Number of lines must be 1 or more\n",err);
1681 if ((eoptarg != NULL) && !isdigit((unsigned char)*eoptarg))
1682 nmchar = *eoptarg++;
1685 if ((eoptarg != NULL) && isdigit((unsigned char)*eoptarg)) {
1686 if ((nmwd = atoi(eoptarg)) < 1) {
1688 "pr: -n width must be 1 or more\n",err);
1691 } else if ((eoptarg != NULL) && (*eoptarg != '\0')) {
1693 "pr: invalid value for -n %s\n", eoptarg);
1699 if (!isdigit((unsigned char)*eoptarg) || ((offst = atoi(eoptarg))< 1)){
1700 (void)fputs("pr: -o offset must be 1 or more\n",
1710 if (eoptarg == NULL)
1714 if (*eoptarg != '\0') {
1716 "pr: invalid value for -s %s\n",
1727 if (!isdigit((unsigned char)*eoptarg) || ((pgwd = atoi(eoptarg)) < 1)){
1729 "pr: -w width must be 1 or more \n",err);
1740 * default and sanity checks
1744 if ((clcnt = argc - eoptind) <= 1) {
1753 (void)fputs("pr: -a flag requires multiple columns\n",
1758 (void)fputs("pr: -m cannot be used with -a\n", err);
1768 if (cflag || merge) {
1781 "pr: -m cannot be used with multiple columns\n", err);
1785 colwd = (pgwd + 1 - (clcnt * (nmwd + 2)))/clcnt;
1786 pgwd = ((colwd + nmwd + 2) * clcnt) - 1;
1788 colwd = (pgwd + 1 - clcnt)/clcnt;
1789 pgwd = ((colwd + 1) * clcnt) - 1;
1793 "pr: page width is too small for %d columns\n",clcnt);
1801 * make sure long enough for headers. if not disable
1803 if (lines <= HEADLEN + TAILLEN)
1806 lines -= HEADLEN + TAILLEN;
1809 * adjust for double space on odd length pages
1822 (void) setlocale(LC_TIME, (Lflag != NULL) ? Lflag : "");