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
39 static char copyright[] =
40 "@(#) Copyright (c) 1993\n\
41 The Regents of the University of California. All rights reserved.\n";
45 static char sccsid[] = "@(#)pr.c 8.2 (Berkeley) 4/16/94";
48 #include <sys/types.h>
64 * pr: a printing and pagination filter. If multiple input files
65 * are specified, each is read, formatted, and written to standard
66 * output. By default, input is seperated into 66-line pages, each
67 * with a header that includes the page number, date, time and the
70 * Complies with posix P1003.2/D11
76 int pgnm; /* starting page number */
77 int clcnt; /* number of columns */
78 int colwd; /* column data width - multiple columns */
79 int across; /* mult col flag; write across page */
80 int dspace; /* double space flag */
81 char inchar; /* expand input char */
82 int ingap; /* expand input gap */
83 int formfeed; /* use formfeed as trailer */
84 char *header; /* header name instead of file name */
85 char ochar; /* contract output char */
86 int ogap; /* contract output gap */
87 int lines; /* number of lines per page */
88 int merge; /* merge multiple files in output */
89 char nmchar; /* line numbering append char */
90 int nmwd; /* width of line number field */
91 int offst; /* number of page offset spaces */
92 int nodiag; /* do not report file open errors */
93 char schar; /* text column separation character */
94 int sflag; /* -s option for multiple columns */
95 int nohead; /* do not write head and trailer */
96 int pgwd; /* page width with multiple col output */
97 char *timefrmt; /* time conversion string */
102 FILE *err; /* error message file pointer */
103 int addone; /* page length is odd with double space */
104 int errcnt; /* error count on file processing */
105 char digs[] = "0123456789"; /* page number translation map */
114 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
115 (void)signal(SIGINT, terminate);
116 ret_val = setup(argc, argv);
119 * select the output format based on options
122 ret_val = mulfile(argc, argv);
124 ret_val = onecol(argc, argv);
126 ret_val = horzcol(argc, argv);
128 ret_val = vertcol(argc, argv);
132 if (errcnt || ret_val)
138 * onecol: print files with only one column of output.
139 * Line length is unlimited.
146 register int cnt = -1;
149 register int linecnt;
172 * allocate line buffer
174 if ((obuf = malloc((unsigned)(LBUF + off)*sizeof(char))) == NULL) {
179 * allocate header buffer
181 if ((hbuf = malloc((unsigned)(HDBUF + offst)*sizeof(char))) == NULL) {
186 ohbuf = hbuf + offst;
190 nbuf[--num] = nmchar;
192 (void)memset(obuf, (int)' ', offst);
193 (void)memset(hbuf, (int)' ', offst);
199 while ((inf = nxtfile(argc, argv, &fname, ohbuf, 0)) != NULL) {
202 * skip to specified page
204 if (inskip(inf, pgnm, lines))
224 while (linecnt < lines) {
228 if ((cnt = inln(inf,lbuf,LBUF,&cps,0,&mor)) < 0)
230 if (!linecnt && !nohead &&
231 prhead(hbuf, fname, pagecnt))
239 addnum(nbuf, num, ++lncnt);
240 if (otln(obuf,cnt+off, &ips, &ops, mor))
242 } else if (otln(lbuf, cnt, &ips, &ops, mor))
246 * if line bigger than buffer, get more
254 * whole line rcvd. reset tab proc. state
263 * fill to end of page
265 if (linecnt && prtail(lines-linecnt-lrgln, lrgln))
269 * On EOF go to next file
284 * vertcol: print files with more than one column of output down a page
292 register char **lstdat;
295 register int cnt = -1;
304 int mxlen = pgwd + offst + 1;
305 int mclcnt = clcnt - 1;
322 * allocate page buffer
324 if ((buf = malloc((unsigned)lines*mxlen*sizeof(char))) == NULL) {
330 * allocate page header
332 if ((hbuf = malloc((unsigned)(HDBUF + offst)*sizeof(char))) == NULL) {
336 ohbuf = hbuf + offst;
338 (void)memset(hbuf, (int)' ', offst);
341 * col pointers when no headers
345 (struct vcol *)malloc((unsigned)mvc*sizeof(struct vcol))) == NULL) {
351 * pointer into page where last data per line is located
353 if ((lstdat = (char **)malloc((unsigned)lines*sizeof(char *))) == NULL){
359 * fast index lookups to locate start of lines
361 if ((indy = (int *)malloc((unsigned)lines*sizeof(int))) == NULL) {
365 if ((lindy = (int *)malloc((unsigned)lines*sizeof(int))) == NULL) {
376 * initialize buffer lookup indexes and offset area
378 for (j = 0; j < lines; ++j) {
379 lindy[j] = j * mxlen;
380 indy[j] = lindy[j] + offst;
382 ptbf = buf + lindy[j];
383 (void)memset(ptbf, (int)' ', offst);
386 ptbf = buf + indy[j];
393 while ((inf = nxtfile(argc, argv, &fname, ohbuf, 0)) != NULL) {
396 * skip to requested page
398 if (inskip(inf, pgnm, lines))
413 for (i = 0; i < clcnt; ++i) {
416 * if last column, do not pad
427 * is this first column
430 ptbf = buf + indy[j];
440 addnum(ptbf, nmwd, ++lncnt);
448 cnt = inln(inf,ptbf,colwd,&cps,1,&mor);
455 * pad all but last column on page
459 * pad to end of column
463 else if ((pln = col-cnt) > 0) {
470 * remember last char in line
481 * when -t (no header) is specified the spec requires
482 * the min number of lines. The last page may not have
483 * balanced length columns. To fix this we must reorder
484 * the columns. This is a very slow technique so it is
485 * only used under limited conditions. Without -t, the
486 * balancing of text columns is unspecified. To NOT
487 * balance the last page, add the global variable
488 * nohead to the if statement below e.g.
490 * if ((cnt < 0) && nohead && cvc ......
495 * check to see if last page needs to be reordered
497 if ((cnt < 0) && cvc && ((mvc-cvc) >= clcnt)){
505 if (!nohead && prhead(hbuf, fname, pagecnt))
507 for (i = 0; i < pln; ++i) {
510 if (offst&& otln(buf,offst,&ips,&ops,1))
514 for (j = 0; j < clcnt; ++j) {
516 * determine column length
529 cnt = vc[tvc].cnt + 1;
534 if (otln(vc[tvc].pt, cnt, &ips,
544 if (otln(buf, 0, &ips, &ops, 0))
550 if (prtail((lines - pln), 0))
553 * done with output, go to next file
559 * determine how many lines to output
569 if (pln && !nohead && prhead(hbuf, fname, pagecnt))
575 for (i = 0; i < pln; ++i) {
576 ptbf = buf + lindy[i];
577 if ((j = lstdat[i] - ptbf) <= offst)
579 if (otln(ptbf, j, &ips, &ops, 0))
586 if (pln && prtail((lines - pln), 0))
590 * if EOF go to next file
605 * horzcol: print files with more than one column of output across a page
614 register int cnt = -1;
615 register char *lstdat;
616 register int col = colwd + 1;
631 if ((buf = malloc((unsigned)(pgwd+offst+1)*sizeof(char))) == NULL) {
639 if ((hbuf = malloc((unsigned)(HDBUF + offst)*sizeof(char))) == NULL) {
643 ohbuf = hbuf + offst;
645 (void)memset(buf, (int)' ', offst);
646 (void)memset(hbuf, (int)' ', offst);
652 while ((inf = nxtfile(argc, argv, &fname, ohbuf, 0)) != NULL) {
654 if (inskip(inf, pgnm, lines))
668 for (i = 0; i < lines; ++i) {
678 * add number to column
680 addnum(ptbf, nmwd, ++lncnt);
687 if ((cnt = inln(inf,ptbf,colwd,&cps,1,
694 * if last line skip padding
700 * pad to end of column
704 else if ((pln = col - cnt) > 0) {
705 (void)memset(ptbf,(int)' ',pln);
711 * determine line length
713 if ((j = lstdat - buf) <= offst)
716 prhead(hbuf, fname, pagecnt))
721 if (otln(buf, j, &ips, &ops, 0))
728 if (i && prtail(lines-i, 0))
732 * if EOF go to next file
747 * mulfile: print files with more than one column of output and
748 * more than one file concurrently
759 register char *lstdat;
777 * array of FILE *, one for each operand
779 if ((fbuf = (FILE **)malloc((unsigned)clcnt*sizeof(FILE *))) == NULL) {
787 if ((hbuf = malloc((unsigned)(HDBUF + offst)*sizeof(char))) == NULL) {
791 ohbuf = hbuf + offst;
794 * do not know how many columns yet. The number of operands provide an
795 * upper bound on the number of columns. We use the number of files
796 * we can open successfully to set the number of columns. The operation
797 * of the merge operation (-m) in relation to unsuccesful file opens
798 * is unspecified by posix.
802 if ((fbuf[j] = nxtfile(argc, argv, &fname, ohbuf, 1)) == NULL)
804 if (pgnm && (inskip(fbuf[j], pgnm, lines)))
816 * calculate page boundries based on open file count
820 colwd = (pgwd - clcnt - nmwd)/clcnt;
821 pgwd = ((colwd + 1) * clcnt) - nmwd - 2;
823 colwd = (pgwd + 1 - clcnt)/clcnt;
824 pgwd = ((colwd + 1) * clcnt) - 1;
828 "pr: page width too small for %d columns\n", clcnt);
837 if ((buf = malloc((unsigned)(pgwd+offst+1)*sizeof(char))) == NULL) {
842 (void)memset(buf, (int)' ', offst);
843 (void)memset(hbuf, (int)' ', offst);
852 * continue to loop while any file still has data
858 for (i = 0; i < lines; ++i) {
863 * add line number to line
865 addnum(ptbf, nmwd, ++lncnt);
875 for (j = 0; j < clcnt; ++j) {
876 if (fbuf[j] == NULL) {
881 } else if ((cnt = inln(fbuf[j], ptbf, colwd,
882 &cps, 1, &mor)) < 0) {
886 if (fbuf[j] != stdin)
887 (void)fclose(fbuf[j]);
901 * if last ACTIVE column, done with line
907 * pad to end of column
911 } else if ((pln = col - cnt) > 0) {
912 (void)memset(ptbf, (int)' ', pln);
918 * calculate data in line
920 if ((j = lstdat - buf) <= offst)
923 if (!i && !nohead && prhead(hbuf, fname, pagecnt))
929 if (otln(buf, j, &ips, &ops, 0))
933 * if no more active files, done
944 if (i && prtail(lines-i, 0))
954 * inln(): input a line of data (unlimited length lines supported)
955 * Input is optionally expanded to spaces
960 * cps: column positon 1st char in buffer (large line support)
961 * trnc: throw away data more than lim up to \n
962 * mor: set if more data in line (not truncated)
965 inln(inf, buf, lim, cps, trnc, mor)
974 register int gap = ingap;
975 register int ch = EOF;
976 register char *ptbuf;
977 register int chk = (int)inchar;
983 * expanding input option
985 while ((--lim >= 0) && ((ch = getc(inf)) != EOF)) {
987 * is this the input "tab" char
991 * expand to number of spaces
993 col = (ptbuf - buf) + *cps;
994 col = gap - (col % gap);
997 * if more than this line, push back
999 if ((col > lim) && (ungetc(ch, inf) == EOF))
1005 while ((--col >= 0) && (--lim >= 0))
1017 while ((--lim >= 0) && ((ch = getc(inf)) != EOF)) {
1033 * entire line processed
1041 * line was larger than limit
1045 * throw away rest of line
1047 while ((ch = getc(inf)) != EOF) {
1055 * save column offset if not truncated
1065 * otln(): output a line of data. (Supports unlimited length lines)
1066 * output is optionally contracted to tabs
1068 * buf: output buffer with data
1069 * cnt: number of chars of valid data in buf
1070 * svips: buffer input column position (for large lines)
1071 * svops: buffer output column position (for large lines)
1072 * mor: output line not complete in this buf; more data to come.
1073 * 1 is more, 0 is complete, -1 is no \n's
1076 otln(buf, cnt, svips, svops, mor)
1083 register int ops; /* last col output */
1084 register int ips; /* last col in buf examined */
1085 register int gap = ogap;
1087 register char *endbuf;
1091 * contracting on output
1096 while (buf < endbuf) {
1098 * count number of spaces and ochar in buffer
1107 * simulate ochar processing
1109 if (*buf == ochar) {
1110 ips += gap - (ips % gap);
1116 * got a non space char; contract out spaces
1120 * use as many ochar as will fit
1122 if ((tbps = ops + gap - (ops % gap)) > ips)
1124 if (putchar(ochar) == EOF) {
1133 * finish off with spaces
1135 if (putchar(' ') == EOF) {
1143 * output non space char
1145 if (putchar(*buf++) == EOF) {
1155 * if incomplete line, save position counts
1165 * use as many ochar as will fit
1167 if ((tbps = ops + gap - (ops % gap)) > ips)
1169 if (putchar(ochar) == EOF) {
1177 * finish off with spaces
1179 if (putchar(' ') == EOF) {
1189 * output is not contracted
1191 if (cnt && (fwrite(buf, sizeof(char), cnt, stdout) <= 0)) {
1200 * process line end and double space as required
1202 if ((putchar('\n') == EOF) || (dspace && (putchar('\n') == EOF))) {
1210 * inskip(): skip over pgcnt pages with lncnt lines per page
1211 * file is closed at EOF (if not stdin).
1213 * inf FILE * to read from
1214 * pgcnt number of pages to skip
1215 * lncnt number of lines per page
1218 inskip(inf, pgcnt, lncnt)
1226 while(--pgcnt > 0) {
1228 while ((c = getc(inf)) != EOF) {
1229 if ((c == '\n') && (--cnt == 0))
1242 * nxtfile: returns a FILE * to next file in arg list and sets the
1243 * time field for this file (or current date).
1245 * buf array to store proper date for the header.
1246 * dt if set skips the date processing (used with -m)
1249 nxtfile(argc, argv, fname, buf, dt)
1259 struct tm *timeptr = NULL;
1260 struct stat statbuf;
1261 static int twice = -1;
1264 if (eoptind >= argc) {
1266 * no file listed; default, use standard input
1278 if (gettimeofday(&tv, &tz) < 0) {
1280 (void)fprintf(err, "pr: cannot get time of day, %s\n",
1285 timeptr = localtime(&(tv.tv_sec));
1287 for (; eoptind < argc; ++eoptind) {
1288 if (strcmp(argv[eoptind], "-") == 0) {
1290 * process a "-" for filename
1299 if (nohead || (dt && twice))
1301 if (gettimeofday(&tv, &tz) < 0) {
1304 "pr: cannot get time of day, %s\n",
1308 timeptr = localtime(&(tv.tv_sec));
1311 * normal file processing
1313 if ((inf = fopen(argv[eoptind], "r")) == NULL) {
1317 (void)fprintf(err, "pr: Cannot open %s, %s\n",
1318 argv[eoptind], strerror(errno));
1326 *fname = argv[eoptind];
1328 if (nohead || (dt && twice))
1332 if (gettimeofday(&tv, &tz) < 0) {
1335 "pr: cannot get time of day, %s\n",
1339 timeptr = localtime(&(tv.tv_sec));
1341 if (fstat(fileno(inf), &statbuf) < 0) {
1345 "pr: Cannot stat %s, %s\n",
1346 argv[eoptind], strerror(errno));
1349 timeptr = localtime(&(statbuf.st_mtime));
1358 * set up time field used in header
1360 if (strftime(buf, HDBUF, timefrmt, timeptr) <= 0) {
1364 (void)fputs("pr: time conversion failed\n", err);
1371 * addnum(): adds the line number to the column
1372 * Truncates from the front or pads with spaces as required.
1373 * Numbers are right justified.
1375 * buf buffer to store the number
1376 * wdth width of buffer to fill
1379 * NOTE: numbers occupy part of the column. The posix
1380 * spec does not specify if -i processing should or should not
1381 * occur on number padding. The spec does say it occupies
1382 * part of the column. The usage of addnum currently treats
1383 * numbers as part of the column so spaces may be replaced.
1386 addnum(buf, wdth, line)
1391 register char *pt = buf + wdth;
1394 *--pt = digs[line % 10];
1396 } while (line && (pt > buf));
1399 * pad with space as required
1406 * prhead(): prints the top of page header
1408 * buf buffer with time field (and offset)
1409 * cnt number of chars in buf
1410 * fname fname field for header
1411 * pagcnt page number
1414 prhead(buf, fname, pagcnt)
1422 if ((putchar('\n') == EOF) || (putchar('\n') == EOF)) {
1427 * posix is not clear if the header is subject to line length
1428 * restrictions. The specification for header line format
1429 * in the spec clearly does not limit length. No pr currently
1430 * restricts header length. However if we need to truncate in
1431 * an reasonable way, adjust the length of the printf by
1432 * changing HDFMT to allow a length max as an arguement printf.
1433 * buf (which contains the offset spaces and time field could
1436 * note only the offset (if any) is processed for tab expansion
1438 if (offst && otln(buf, offst, &ips, &ops, -1))
1440 (void)printf(HDFMT,buf+offst, fname, pagcnt);
1445 * prtail(): pad page with empty lines (if required) and print page trailer
1448 * cnt number of lines of padding needed
1449 * incomp was a '\n' missing from last line output
1458 * only pad with no headers when incomplete last line
1462 if ((dspace && (putchar('\n') == EOF)) ||
1463 (putchar('\n') == EOF)) {
1471 * if double space output two \n
1477 * if an odd number of lines per page, add an extra \n
1486 if ((incomp && (putchar('\n') == EOF)) ||
1487 (putchar('\f') == EOF)) {
1494 while (--cnt >= 0) {
1495 if (putchar('\n') == EOF) {
1504 * terminate(): when a SIGINT is recvd
1507 terminate(which_sig)
1516 * flsh_errs(): output saved up diagnostic messages after all normal
1517 * processing has completed
1524 (void)fflush(stdout);
1529 while (fgets(buf, BUFSIZ, err) != NULL)
1530 (void)fputs(buf, stderr);
1536 (void)fputs("pr: memory allocation failed\n", err);
1542 (void)fprintf(err, "pr: write failure, %s\n", strerror(errno));
1549 "usage: pr [+page] [-col] [-adFmrt] [-e[ch][gap]] [-h header]\n",err);
1551 " [-i[ch][gap]] [-l line] [-n[ch][width]] [-o offset]\n",err);
1553 " [-s[ch]] [-w width] [-] [file ...]\n", err);
1557 * setup: Validate command args, initialize and perform sanity
1563 register char **argv;
1571 if (isatty(fileno(stdout))) {
1573 * defer diagnostics until processing is done
1575 if ((err = tmpfile()) == NULL) {
1576 (void)fputs("Cannot defer diagnostic messages\n",stderr);
1581 while ((c = egetopt(argc, argv, "#adFmrte?h:i?l:n?o:s?w:")) != EOF) {
1584 if ((pgnm = atoi(eoptarg)) < 1) {
1585 (void)fputs("pr: +page number must be 1 or more\n",
1591 if ((clcnt = atoi(eoptarg)) < 1) {
1592 (void)fputs("pr: -columns must be 1 or more\n",err);
1606 if ((eoptarg != NULL) && !isdigit(*eoptarg))
1607 inchar = *eoptarg++;
1610 if ((eoptarg != NULL) && isdigit(*eoptarg)) {
1611 if ((ingap = atoi(eoptarg)) < 0) {
1613 "pr: -e gap must be 0 or more\n", err);
1618 } else if ((eoptarg != NULL) && (*eoptarg != '\0')) {
1620 "pr: invalid value for -e %s\n", eoptarg);
1633 if ((eoptarg != NULL) && !isdigit(*eoptarg))
1637 if ((eoptarg != NULL) && isdigit(*eoptarg)) {
1638 if ((ogap = atoi(eoptarg)) < 0) {
1640 "pr: -i gap must be 0 or more\n", err);
1645 } else if ((eoptarg != NULL) && (*eoptarg != '\0')) {
1647 "pr: invalid value for -i %s\n", eoptarg);
1653 if (!isdigit(*eoptarg) || ((lines=atoi(eoptarg)) < 1)) {
1655 "pr: Number of lines must be 1 or more\n",err);
1663 if ((eoptarg != NULL) && !isdigit(*eoptarg))
1664 nmchar = *eoptarg++;
1667 if ((eoptarg != NULL) && isdigit(*eoptarg)) {
1668 if ((nmwd = atoi(eoptarg)) < 1) {
1670 "pr: -n width must be 1 or more\n",err);
1673 } else if ((eoptarg != NULL) && (*eoptarg != '\0')) {
1675 "pr: invalid value for -n %s\n", eoptarg);
1681 if (!isdigit(*eoptarg) || ((offst = atoi(eoptarg))< 1)){
1682 (void)fputs("pr: -o offset must be 1 or more\n",
1692 if (eoptarg == NULL)
1696 if (*eoptarg != '\0') {
1698 "pr: invalid value for -s %s\n", eoptarg);
1707 if (!isdigit(*eoptarg) || ((pgwd = atoi(eoptarg)) < 1)){
1709 "pr: -w width must be 1 or more \n",err);
1720 * default and sanity checks
1724 if ((clcnt = argc - eoptind) <= 1) {
1733 (void)fputs("pr: -a flag requires multiple columns\n",
1738 (void)fputs("pr: -m cannot be used with -a\n", err);
1748 if (cflag || merge) {
1761 "pr: -m cannot be used with multiple columns\n", err);
1765 colwd = (pgwd + 1 - (clcnt * (nmwd + 2)))/clcnt;
1766 pgwd = ((colwd + nmwd + 2) * clcnt) - 1;
1768 colwd = (pgwd + 1 - clcnt)/clcnt;
1769 pgwd = ((colwd + 1) * clcnt) - 1;
1773 "pr: page width is too small for %d columns\n",clcnt);
1781 * make sure long enough for headers. if not disable
1783 if (lines <= HEADLEN + TAILLEN)
1786 lines -= HEADLEN + TAILLEN;
1789 * adjust for double space on odd length pages
1801 if ((timefrmt = getenv("LC_TIME")) == NULL)