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>
68 * pr: a printing and pagination filter. If multiple input files
69 * are specified, each is read, formatted, and written to standard
70 * output. By default, input is separated into 66-line pages, each
71 * with a header that includes the page number, date, time and the
74 * Complies with posix P1003.2/D11
80 int pgnm; /* starting page number */
81 int clcnt; /* number of columns */
82 int colwd; /* column data width - multiple columns */
83 int across; /* mult col flag; write across page */
84 int dspace; /* double space flag */
85 char inchar; /* expand input char */
86 int ingap; /* expand input gap */
87 int formfeed; /* use formfeed as trailer */
88 char *header; /* header name instead of file name */
89 char ochar; /* contract output char */
90 int ogap; /* contract output gap */
91 int lines; /* number of lines per page */
92 int merge; /* merge multiple files in output */
93 char nmchar; /* line numbering append char */
94 int nmwd; /* width of line number field */
95 int offst; /* number of page offset spaces */
96 int nodiag; /* do not report file open errors */
97 char schar; /* text column separation character */
98 int sflag; /* -s option for multiple columns */
99 int nohead; /* do not write head and trailer */
100 int pgwd; /* page width with multiple col output */
101 char *timefrmt; /* time conversion string */
106 FILE *err; /* error message file pointer */
107 int addone; /* page length is odd with double space */
108 int errcnt; /* error count on file processing */
109 char digs[] = "0123456789"; /* page number translation map */
118 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
119 (void)signal(SIGINT, terminate);
120 ret_val = setup(argc, argv);
123 * select the output format based on options
126 ret_val = mulfile(argc, argv);
128 ret_val = onecol(argc, argv);
130 ret_val = horzcol(argc, argv);
132 ret_val = vertcol(argc, argv);
136 if (errcnt || ret_val)
142 * onecol: print files with only one column of output.
143 * Line length is unlimited.
150 register int cnt = -1;
153 register int linecnt;
176 * allocate line buffer
178 if ((obuf = malloc((unsigned)(LBUF + off)*sizeof(char))) == NULL) {
183 * allocate header buffer
185 if ((hbuf = malloc((unsigned)(HDBUF + offst)*sizeof(char))) == NULL) {
190 ohbuf = hbuf + offst;
194 nbuf[--num] = nmchar;
196 (void)memset(obuf, (int)' ', offst);
197 (void)memset(hbuf, (int)' ', offst);
203 while ((inf = nxtfile(argc, argv, &fname, ohbuf, 0)) != NULL) {
206 * skip to specified page
208 if (inskip(inf, pgnm, lines))
228 while (linecnt < lines) {
232 if ((cnt = inln(inf,lbuf,LBUF,&cps,0,&mor)) < 0)
234 if (!linecnt && !nohead &&
235 prhead(hbuf, fname, pagecnt))
243 addnum(nbuf, num, ++lncnt);
244 if (otln(obuf,cnt+off, &ips, &ops, mor))
246 } else if (otln(lbuf, cnt, &ips, &ops, mor))
250 * if line bigger than buffer, get more
258 * whole line rcvd. reset tab proc. state
267 * fill to end of page
269 if (linecnt && prtail(lines-linecnt-lrgln, lrgln))
273 * On EOF go to next file
288 * vertcol: print files with more than one column of output down a page
296 register char **lstdat;
299 register int cnt = -1;
308 int mxlen = pgwd + offst + 1;
309 int mclcnt = clcnt - 1;
326 * allocate page buffer
328 if ((buf = malloc((unsigned)lines*mxlen*sizeof(char))) == NULL) {
334 * allocate page header
336 if ((hbuf = malloc((unsigned)(HDBUF + offst)*sizeof(char))) == NULL) {
340 ohbuf = hbuf + offst;
342 (void)memset(hbuf, (int)' ', offst);
345 * col pointers when no headers
349 (struct vcol *)malloc((unsigned)mvc*sizeof(struct vcol))) == NULL) {
355 * pointer into page where last data per line is located
357 if ((lstdat = (char **)malloc((unsigned)lines*sizeof(char *))) == NULL){
363 * fast index lookups to locate start of lines
365 if ((indy = (int *)malloc((unsigned)lines*sizeof(int))) == NULL) {
369 if ((lindy = (int *)malloc((unsigned)lines*sizeof(int))) == NULL) {
380 * initialize buffer lookup indexes and offset area
382 for (j = 0; j < lines; ++j) {
383 lindy[j] = j * mxlen;
384 indy[j] = lindy[j] + offst;
386 ptbf = buf + lindy[j];
387 (void)memset(ptbf, (int)' ', offst);
390 ptbf = buf + indy[j];
397 while ((inf = nxtfile(argc, argv, &fname, ohbuf, 0)) != NULL) {
400 * skip to requested page
402 if (inskip(inf, pgnm, lines))
417 for (i = 0; i < clcnt; ++i) {
420 * if last column, do not pad
431 * is this first column
434 ptbf = buf + indy[j];
444 addnum(ptbf, nmwd, ++lncnt);
452 cnt = inln(inf,ptbf,colwd,&cps,1,&mor);
459 * pad all but last column on page
463 * pad to end of column
467 else if ((pln = col-cnt) > 0) {
474 * remember last char in line
485 * when -t (no header) is specified the spec requires
486 * the min number of lines. The last page may not have
487 * balanced length columns. To fix this we must reorder
488 * the columns. This is a very slow technique so it is
489 * only used under limited conditions. Without -t, the
490 * balancing of text columns is unspecified. To NOT
491 * balance the last page, add the global variable
492 * nohead to the if statement below e.g.
494 * if ((cnt < 0) && nohead && cvc ......
499 * check to see if last page needs to be reordered
501 if ((cnt < 0) && cvc && ((mvc-cvc) >= clcnt)){
509 if (!nohead && prhead(hbuf, fname, pagecnt))
511 for (i = 0; i < pln; ++i) {
514 if (offst&& otln(buf,offst,&ips,&ops,1))
518 for (j = 0; j < clcnt; ++j) {
520 * determine column length
533 cnt = vc[tvc].cnt + 1;
538 if (otln(vc[tvc].pt, cnt, &ips,
548 if (otln(buf, 0, &ips, &ops, 0))
554 if (prtail((lines - pln), 0))
557 * done with output, go to next file
563 * determine how many lines to output
573 if (pln && !nohead && prhead(hbuf, fname, pagecnt))
579 for (i = 0; i < pln; ++i) {
580 ptbf = buf + lindy[i];
581 if ((j = lstdat[i] - ptbf) <= offst)
583 if (otln(ptbf, j, &ips, &ops, 0))
590 if (pln && prtail((lines - pln), 0))
594 * if EOF go to next file
609 * horzcol: print files with more than one column of output across a page
618 register int cnt = -1;
619 register char *lstdat;
620 register int col = colwd + 1;
635 if ((buf = malloc((unsigned)(pgwd+offst+1)*sizeof(char))) == NULL) {
643 if ((hbuf = malloc((unsigned)(HDBUF + offst)*sizeof(char))) == NULL) {
647 ohbuf = hbuf + offst;
649 (void)memset(buf, (int)' ', offst);
650 (void)memset(hbuf, (int)' ', offst);
656 while ((inf = nxtfile(argc, argv, &fname, ohbuf, 0)) != NULL) {
658 if (inskip(inf, pgnm, lines))
672 for (i = 0; i < lines; ++i) {
682 * add number to column
684 addnum(ptbf, nmwd, ++lncnt);
691 if ((cnt = inln(inf,ptbf,colwd,&cps,1,
698 * if last line skip padding
704 * pad to end of column
708 else if ((pln = col - cnt) > 0) {
709 (void)memset(ptbf,(int)' ',pln);
715 * determine line length
717 if ((j = lstdat - buf) <= offst)
720 prhead(hbuf, fname, pagecnt))
725 if (otln(buf, j, &ips, &ops, 0))
732 if (i && prtail(lines-i, 0))
736 * if EOF go to next file
751 * mulfile: print files with more than one column of output and
752 * more than one file concurrently
763 register char *lstdat;
781 * array of FILE *, one for each operand
783 if ((fbuf = (FILE **)malloc((unsigned)clcnt*sizeof(FILE *))) == NULL) {
791 if ((hbuf = malloc((unsigned)(HDBUF + offst)*sizeof(char))) == NULL) {
795 ohbuf = hbuf + offst;
798 * do not know how many columns yet. The number of operands provide an
799 * upper bound on the number of columns. We use the number of files
800 * we can open successfully to set the number of columns. The operation
801 * of the merge operation (-m) in relation to unsuccesful file opens
802 * is unspecified by posix.
806 if ((fbuf[j] = nxtfile(argc, argv, &fname, ohbuf, 1)) == NULL)
808 if (pgnm && (inskip(fbuf[j], pgnm, lines)))
820 * calculate page boundries based on open file count
824 colwd = (pgwd - clcnt - nmwd)/clcnt;
825 pgwd = ((colwd + 1) * clcnt) - nmwd - 2;
827 colwd = (pgwd + 1 - clcnt)/clcnt;
828 pgwd = ((colwd + 1) * clcnt) - 1;
832 "pr: page width too small for %d columns\n", clcnt);
841 if ((buf = malloc((unsigned)(pgwd+offst+1)*sizeof(char))) == NULL) {
846 (void)memset(buf, (int)' ', offst);
847 (void)memset(hbuf, (int)' ', offst);
856 * continue to loop while any file still has data
862 for (i = 0; i < lines; ++i) {
867 * add line number to line
869 addnum(ptbf, nmwd, ++lncnt);
879 for (j = 0; j < clcnt; ++j) {
880 if (fbuf[j] == NULL) {
885 } else if ((cnt = inln(fbuf[j], ptbf, colwd,
886 &cps, 1, &mor)) < 0) {
890 if (fbuf[j] != stdin)
891 (void)fclose(fbuf[j]);
905 * if last ACTIVE column, done with line
911 * pad to end of column
915 } else if ((pln = col - cnt) > 0) {
916 (void)memset(ptbf, (int)' ', pln);
922 * calculate data in line
924 if ((j = lstdat - buf) <= offst)
927 if (!i && !nohead && prhead(hbuf, fname, pagecnt))
933 if (otln(buf, j, &ips, &ops, 0))
937 * if no more active files, done
948 if (i && prtail(lines-i, 0))
958 * inln(): input a line of data (unlimited length lines supported)
959 * Input is optionally expanded to spaces
964 * cps: column positon 1st char in buffer (large line support)
965 * trnc: throw away data more than lim up to \n
966 * mor: set if more data in line (not truncated)
969 inln(inf, buf, lim, cps, trnc, mor)
978 register int gap = ingap;
979 register int ch = EOF;
980 register char *ptbuf;
981 register int chk = (int)inchar;
987 * expanding input option
989 while ((--lim >= 0) && ((ch = getc(inf)) != EOF)) {
991 * is this the input "tab" char
995 * expand to number of spaces
997 col = (ptbuf - buf) + *cps;
998 col = gap - (col % gap);
1001 * if more than this line, push back
1003 if ((col > lim) && (ungetc(ch, inf) == EOF))
1009 while ((--col >= 0) && (--lim >= 0))
1021 while ((--lim >= 0) && ((ch = getc(inf)) != EOF)) {
1037 * entire line processed
1045 * line was larger than limit
1049 * throw away rest of line
1051 while ((ch = getc(inf)) != EOF) {
1059 * save column offset if not truncated
1069 * otln(): output a line of data. (Supports unlimited length lines)
1070 * output is optionally contracted to tabs
1072 * buf: output buffer with data
1073 * cnt: number of chars of valid data in buf
1074 * svips: buffer input column position (for large lines)
1075 * svops: buffer output column position (for large lines)
1076 * mor: output line not complete in this buf; more data to come.
1077 * 1 is more, 0 is complete, -1 is no \n's
1080 otln(buf, cnt, svips, svops, mor)
1087 register int ops; /* last col output */
1088 register int ips; /* last col in buf examined */
1089 register int gap = ogap;
1091 register char *endbuf;
1095 * contracting on output
1100 while (buf < endbuf) {
1102 * count number of spaces and ochar in buffer
1111 * simulate ochar processing
1113 if (*buf == ochar) {
1114 ips += gap - (ips % gap);
1120 * got a non space char; contract out spaces
1124 * use as many ochar as will fit
1126 if ((tbps = ops + gap - (ops % gap)) > ips)
1128 if (putchar(ochar) == EOF) {
1137 * finish off with spaces
1139 if (putchar(' ') == EOF) {
1147 * output non space char
1149 if (putchar(*buf++) == EOF) {
1159 * if incomplete line, save position counts
1169 * use as many ochar as will fit
1171 if ((tbps = ops + gap - (ops % gap)) > ips)
1173 if (putchar(ochar) == EOF) {
1181 * finish off with spaces
1183 if (putchar(' ') == EOF) {
1193 * output is not contracted
1195 if (cnt && (fwrite(buf, sizeof(char), cnt, stdout) <= 0)) {
1204 * process line end and double space as required
1206 if ((putchar('\n') == EOF) || (dspace && (putchar('\n') == EOF))) {
1214 * inskip(): skip over pgcnt pages with lncnt lines per page
1215 * file is closed at EOF (if not stdin).
1217 * inf FILE * to read from
1218 * pgcnt number of pages to skip
1219 * lncnt number of lines per page
1222 inskip(inf, pgcnt, lncnt)
1230 while(--pgcnt > 0) {
1232 while ((c = getc(inf)) != EOF) {
1233 if ((c == '\n') && (--cnt == 0))
1246 * nxtfile: returns a FILE * to next file in arg list and sets the
1247 * time field for this file (or current date).
1249 * buf array to store proper date for the header.
1250 * dt if set skips the date processing (used with -m)
1253 nxtfile(argc, argv, fname, buf, dt)
1264 struct tm *timeptr = NULL;
1265 struct stat statbuf;
1266 static int twice = -1;
1269 if (eoptind >= argc) {
1271 * no file listed; default, use standard input
1283 if (gettimeofday(&tv, &tz) < 0) {
1285 (void)fprintf(err, "pr: cannot get time of day, %s\n",
1291 timeptr = localtime(&tv_sec);
1293 for (; eoptind < argc; ++eoptind) {
1294 if (strcmp(argv[eoptind], "-") == 0) {
1296 * process a "-" for filename
1305 if (nohead || (dt && twice))
1307 if (gettimeofday(&tv, &tz) < 0) {
1310 "pr: cannot get time of day, %s\n",
1315 timeptr = localtime(&tv_sec);
1318 * normal file processing
1320 if ((inf = fopen(argv[eoptind], "r")) == NULL) {
1324 (void)fprintf(err, "pr: Cannot open %s, %s\n",
1325 argv[eoptind], strerror(errno));
1333 *fname = argv[eoptind];
1335 if (nohead || (dt && twice))
1339 if (gettimeofday(&tv, &tz) < 0) {
1342 "pr: cannot get time of day, %s\n",
1347 timeptr = localtime(&tv_sec);
1349 if (fstat(fileno(inf), &statbuf) < 0) {
1353 "pr: Cannot stat %s, %s\n",
1354 argv[eoptind], strerror(errno));
1357 timeptr = localtime(&(statbuf.st_mtime));
1366 * set up time field used in header
1368 if (strftime(buf, HDBUF, timefrmt, timeptr) <= 0) {
1372 (void)fputs("pr: time conversion failed\n", err);
1379 * addnum(): adds the line number to the column
1380 * Truncates from the front or pads with spaces as required.
1381 * Numbers are right justified.
1383 * buf buffer to store the number
1384 * wdth width of buffer to fill
1387 * NOTE: numbers occupy part of the column. The posix
1388 * spec does not specify if -i processing should or should not
1389 * occur on number padding. The spec does say it occupies
1390 * part of the column. The usage of addnum currently treats
1391 * numbers as part of the column so spaces may be replaced.
1394 addnum(buf, wdth, line)
1399 register char *pt = buf + wdth;
1402 *--pt = digs[line % 10];
1404 } while (line && (pt > buf));
1407 * pad with space as required
1414 * prhead(): prints the top of page header
1416 * buf buffer with time field (and offset)
1417 * cnt number of chars in buf
1418 * fname fname field for header
1419 * pagcnt page number
1422 prhead(buf, fname, pagcnt)
1430 if ((putchar('\n') == EOF) || (putchar('\n') == EOF)) {
1435 * posix is not clear if the header is subject to line length
1436 * restrictions. The specification for header line format
1437 * in the spec clearly does not limit length. No pr currently
1438 * restricts header length. However if we need to truncate in
1439 * an reasonable way, adjust the length of the printf by
1440 * changing HDFMT to allow a length max as an arguement printf.
1441 * buf (which contains the offset spaces and time field could
1444 * note only the offset (if any) is processed for tab expansion
1446 if (offst && otln(buf, offst, &ips, &ops, -1))
1448 (void)printf(HDFMT,buf+offst, fname, pagcnt);
1453 * prtail(): pad page with empty lines (if required) and print page trailer
1456 * cnt number of lines of padding needed
1457 * incomp was a '\n' missing from last line output
1466 * only pad with no headers when incomplete last line
1469 ((dspace && (putchar('\n') == EOF)) ||
1470 (putchar('\n') == EOF))) {
1475 * but honor the formfeed request
1478 if (putchar('\f') == EOF) {
1486 * if double space output two \n
1492 * if an odd number of lines per page, add an extra \n
1501 if ((incomp && (putchar('\n') == EOF)) ||
1502 (putchar('\f') == EOF)) {
1509 while (--cnt >= 0) {
1510 if (putchar('\n') == EOF) {
1519 * terminate(): when a SIGINT is recvd
1522 terminate(which_sig)
1531 * flsh_errs(): output saved up diagnostic messages after all normal
1532 * processing has completed
1539 (void)fflush(stdout);
1544 while (fgets(buf, BUFSIZ, err) != NULL)
1545 (void)fputs(buf, stderr);
1551 (void)fputs("pr: memory allocation failed\n", err);
1557 (void)fprintf(err, "pr: write failure, %s\n", strerror(errno));
1564 "usage: pr [+page] [-col] [-adFmrt] [-e[ch][gap]] [-h header]\n",err);
1566 " [-i[ch][gap]] [-l line] [-n[ch][width]] [-o offset]\n",err);
1568 " [-L locale] [-s[ch]] [-w width] [-] [file ...]\n", err);
1572 * setup: Validate command args, initialize and perform sanity
1578 register char **argv;
1588 if (isatty(fileno(stdout))) {
1590 * defer diagnostics until processing is done
1592 if ((err = tmpfile()) == NULL) {
1593 (void)fputs("Cannot defer diagnostic messages\n",stderr);
1598 while ((c = egetopt(argc, argv, "#adFmrte?h:i?L:l:n?o:s?w:")) != -1) {
1601 if ((pgnm = atoi(eoptarg)) < 1) {
1602 (void)fputs("pr: +page number must be 1 or more\n",
1608 if ((clcnt = atoi(eoptarg)) < 1) {
1609 (void)fputs("pr: -columns must be 1 or more\n",err);
1623 if ((eoptarg != NULL) && !isdigit((unsigned char)*eoptarg))
1624 inchar = *eoptarg++;
1627 if ((eoptarg != NULL) && isdigit((unsigned char)*eoptarg)) {
1628 if ((ingap = atoi(eoptarg)) < 0) {
1630 "pr: -e gap must be 0 or more\n", err);
1635 } else if ((eoptarg != NULL) && (*eoptarg != '\0')) {
1637 "pr: invalid value for -e %s\n", eoptarg);
1650 if ((eoptarg != NULL) && !isdigit((unsigned char)*eoptarg))
1654 if ((eoptarg != NULL) && isdigit((unsigned char)*eoptarg)) {
1655 if ((ogap = atoi(eoptarg)) < 0) {
1657 "pr: -i gap must be 0 or more\n", err);
1662 } else if ((eoptarg != NULL) && (*eoptarg != '\0')) {
1664 "pr: invalid value for -i %s\n", eoptarg);
1673 if (!isdigit((unsigned char)*eoptarg) || ((lines=atoi(eoptarg)) < 1)) {
1675 "pr: Number of lines must be 1 or more\n",err);
1683 if ((eoptarg != NULL) && !isdigit((unsigned char)*eoptarg))
1684 nmchar = *eoptarg++;
1687 if ((eoptarg != NULL) && isdigit((unsigned char)*eoptarg)) {
1688 if ((nmwd = atoi(eoptarg)) < 1) {
1690 "pr: -n width must be 1 or more\n",err);
1693 } else if ((eoptarg != NULL) && (*eoptarg != '\0')) {
1695 "pr: invalid value for -n %s\n", eoptarg);
1701 if (!isdigit((unsigned char)*eoptarg) || ((offst = atoi(eoptarg))< 1)){
1702 (void)fputs("pr: -o offset must be 1 or more\n",
1712 if (eoptarg == NULL)
1716 if (*eoptarg != '\0') {
1718 "pr: invalid value for -s %s\n",
1729 if (!isdigit((unsigned char)*eoptarg) || ((pgwd = atoi(eoptarg)) < 1)){
1731 "pr: -w width must be 1 or more \n",err);
1742 * default and sanity checks
1746 if ((clcnt = argc - eoptind) <= 1) {
1755 (void)fputs("pr: -a flag requires multiple columns\n",
1760 (void)fputs("pr: -m cannot be used with -a\n", err);
1770 if (cflag || merge) {
1783 "pr: -m cannot be used with multiple columns\n", err);
1787 colwd = (pgwd + 1 - (clcnt * (nmwd + 2)))/clcnt;
1788 pgwd = ((colwd + nmwd + 2) * clcnt) - 1;
1790 colwd = (pgwd + 1 - clcnt)/clcnt;
1791 pgwd = ((colwd + 1) * clcnt) - 1;
1795 "pr: page width is too small for %d columns\n",clcnt);
1803 * make sure long enough for headers. if not disable
1805 if (lines <= HEADLEN + TAILLEN)
1808 lines -= HEADLEN + TAILLEN;
1811 * adjust for double space on odd length pages
1823 (void) setlocale(LC_TIME, (Lflag != NULL) ? Lflag : "");
1825 d_first = (*nl_langinfo(D_MD_ORDER) == 'd');
1826 timefrmt = d_first ? TIMEFMTD : TIMEFMTM;