Home | History | Annotate | Line # | Download | only in nl
nl.c revision 1.3
      1 /*	$NetBSD: nl.c,v 1.3 1999/04/23 14:43:05 kleink Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Klaus Klein.
      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. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *        This product includes software developed by the NetBSD
     21  *        Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 #ifndef lint
     41 __COPYRIGHT(
     42 "@(#) Copyright (c) 1999\
     43  The NetBSD Foundation, Inc.  All rights reserved.");
     44 __RCSID("$NetBSD: nl.c,v 1.3 1999/04/23 14:43:05 kleink Exp $");
     45 #endif
     46 
     47 #include <errno.h>
     48 #include <limits.h>
     49 #include <locale.h>
     50 #include <regex.h>
     51 #include <stdio.h>
     52 #include <stdlib.h>
     53 #include <unistd.h>
     54 
     55 typedef enum {
     56 	number_all,		/* number all lines */
     57 	number_nonempty,	/* number non-empty lines */
     58 	number_none,		/* no line numbering */
     59 	number_regex		/* number lines matching regular expression */
     60 } numbering_type;
     61 
     62 struct numbering_property {
     63 	const char * const	name;		/* for diagnostics */
     64 	numbering_type		type;		/* numbering type */
     65 	regex_t			expr;		/* for type == number_regex */
     66 };
     67 
     68 /* line numbering formats */
     69 #define FORMAT_LN	"%-*d"	/* left justified, leading zeros suppressed */
     70 #define FORMAT_RN	"%*d"	/* right justified, leading zeros suppressed */
     71 #define FORMAT_RZ	"%0*d"	/* right justified, leading zeros kept */
     72 
     73 #define FOOTER		0
     74 #define BODY		1
     75 #define HEADER		2
     76 #define NP_LAST		HEADER
     77 
     78 static struct numbering_property numbering_properties[NP_LAST + 1] = {
     79 	{ "footer",	number_none	},
     80 	{ "body",	number_nonempty	},
     81 	{ "header",	number_none	}
     82 };
     83 
     84 #define max(a, b)	((a) > (b) ? (a) : (b))
     85 
     86 /*
     87  * Maximum number of characters required for a decimal representation of a
     88  * (signed) int; courtesy of tzcode.
     89  */
     90 #define INT_STRLEN_MAXIMUM \
     91 	((sizeof (int) * CHAR_BIT - 1) * 302 / 1000 + 2)
     92 
     93 static void	filter __P((void));
     94 int		main __P((int, char *[]));
     95 static void	parse_numbering __P((const char *, int));
     96 static void	usage __P((void));
     97 
     98 /*
     99  * Pointer to dynamically allocated input line buffer, and its size.
    100  */
    101 static char *buffer;
    102 static size_t buffersize;
    103 
    104 /*
    105  * Dynamically allocated buffer suitable for string representation of ints.
    106  */
    107 static char *intbuffer;
    108 
    109 /*
    110  * Configurable parameters.
    111  */
    112 /* delimiter characters that indicate the start of a logical page section */
    113 static char delim[2] = { '\\', ':' };
    114 
    115 /* line numbering format */
    116 static const char *format = FORMAT_RN;
    117 
    118 /* increment value used to number logical page lines */
    119 static int incr = 1;
    120 
    121 /* number of adjacent blank lines to be considered (and numbered) as one */
    122 static unsigned int nblank = 1;
    123 
    124 /* whether to restart numbering at logical page delimiters */
    125 static int restart = 1;
    126 
    127 /* characters used in separating the line number and the corrsp. text line */
    128 static const char *sep = "\t";
    129 
    130 /* initial value used to number logical page lines */
    131 static int startnum = 1;
    132 
    133 /* number of characters to be used for the line number */
    134 /* should be unsigned but required signed by `*' precision conversion */
    135 static int width = 6;
    136 
    137 
    138 int
    139 main(argc, argv)
    140 	int argc;
    141 	char *argv[];
    142 {
    143 	int c;
    144 	long val;
    145 	unsigned long uval;
    146 	char *ep;
    147 	size_t intbuffersize;
    148 
    149 	(void)setlocale(LC_ALL, "");
    150 
    151 	/*
    152 	 * Note: this implementation strictly conforms to the XBD Utility
    153 	 * Syntax Guidelines and does not permit the optional `file' operand
    154 	 * to be intermingled with the options, which is defined in the
    155 	 * XCU specification (Issue 5) but declared an obsolescent feature that
    156 	 * will be removed from a future issue.  It shouldn't matter, though.
    157 	 */
    158 	while ((c = getopt(argc, argv, "pb:d:f:h:i:l:n:s:v:w:")) != -1) {
    159 		switch (c) {
    160 		case 'p':
    161 			restart = 0;
    162 			break;
    163 		case 'b':
    164 			parse_numbering(optarg, BODY);
    165 			break;
    166 		case 'd':
    167 			if (optarg[0] != '\0')
    168 				delim[0] = optarg[0];
    169 			if (optarg[1] != '\0')
    170 				delim[1] = optarg[1];
    171 			/* at most two delimiter characters */
    172 			if (optarg[2] != '\0') {
    173 				(void)fprintf(stderr,
    174 				    "nl: invalid delim argument -- %s\n",
    175 				    optarg);
    176 				exit(EXIT_FAILURE);
    177 				/* NOTREACHED */
    178 			}
    179 			break;
    180 		case 'f':
    181 			parse_numbering(optarg, FOOTER);
    182 			break;
    183 		case 'h':
    184 			parse_numbering(optarg, HEADER);
    185 			break;
    186 		case 'i':
    187 			errno = 0;
    188 			val = strtol(optarg, &ep, 10);
    189 			if ((ep != NULL && *ep != '\0') ||
    190 			 ((val == LONG_MIN || val == LONG_MAX) && errno != 0)) {
    191 				(void)fprintf(stderr,
    192 				    "invalid incr argument -- %s\n", optarg);
    193 				exit(EXIT_FAILURE);
    194 			}
    195 			incr = (int)val;
    196 			break;
    197 		case 'l':
    198 			errno = 0;
    199 			uval = strtoul(optarg, &ep, 10);
    200 			if ((ep != NULL && *ep != '\0') ||
    201 			    (uval == ULONG_MAX && errno != 0)) {
    202 				(void)fprintf(stderr,
    203 				    "invalid num argument -- %s\n", optarg);
    204 				exit(EXIT_FAILURE);
    205 			}
    206 			nblank = (unsigned int)uval;
    207 			break;
    208 		case 'n':
    209 			if (strcmp(optarg, "ln") == 0) {
    210 				format = FORMAT_LN;
    211 			} else if (strcmp(optarg, "rn") == 0) {
    212 				format = FORMAT_RN;
    213 			} else if (strcmp(optarg, "rz") == 0) {
    214 				format = FORMAT_RZ;
    215 			} else {
    216 				(void)fprintf(stderr,
    217 				    "nl: illegal format -- %s\n", optarg);
    218 				exit(EXIT_FAILURE);
    219 			}
    220 			break;
    221 		case 's':
    222 			sep = optarg;
    223 			break;
    224 		case 'v':
    225 			errno = 0;
    226 			val = strtol(optarg, &ep, 10);
    227 			if ((ep != NULL && *ep != '\0') ||
    228 			 ((val == LONG_MIN || val == LONG_MAX) && errno != 0)) {
    229 				(void)fprintf(stderr,
    230 				    "invalid startnum value -- %s\n", optarg);
    231 				exit(EXIT_FAILURE);
    232 			}
    233 			startnum = (int)val;
    234 			break;
    235 		case 'w':
    236 			errno = 0;
    237 			val = strtol(optarg, &ep, 10);
    238 			if ((ep != NULL && *ep != '\0') ||
    239 			 ((val == LONG_MIN || val == LONG_MAX) && errno != 0)) {
    240 				(void)fprintf(stderr,
    241 				    "invalid width value -- %s\n", optarg);
    242 				exit(EXIT_FAILURE);
    243 			}
    244 			width = (int)val;
    245 			if (!(width > 0)) {
    246 				(void)fprintf(stderr,
    247 				    "nl: width argument must be > 0 -- %d\n",
    248 				    width);
    249 				 exit(EXIT_FAILURE);
    250 			}
    251 			break;
    252 		case '?':
    253 		default:
    254 			usage();
    255 			/* NOTREACHED */
    256 		}
    257 	}
    258 	argc -= optind;
    259 	argv += optind;
    260 
    261 	switch (argc) {
    262 	case 0:
    263 		break;
    264 	case 1:
    265 		if (freopen(argv[0], "r", stdin) == NULL) {
    266 			perror(argv[0]);
    267 			exit(EXIT_FAILURE);
    268 		}
    269 		break;
    270 	default:
    271 		usage();
    272 		/* NOTREACHED */
    273 	}
    274 
    275 	/* Determine the maximum input line length to operate on. */
    276 	if ((val = sysconf(_SC_LINE_MAX)) == -1) /* ignore errno */
    277 		val = LINE_MAX;
    278 	/* Allocate sufficient buffer space (including the terminating NUL). */
    279 	buffersize = (size_t)val + 1;
    280 	if ((buffer = malloc(buffersize)) == NULL) {
    281 		perror("cannot allocate input line buffer");
    282 		exit(EXIT_FAILURE);
    283 	}
    284 
    285 	/* Allocate a buffer suitable for preformatting line number. */
    286 	intbuffersize = max(INT_STRLEN_MAXIMUM, width) + 1;	/* NUL */
    287 	if ((intbuffer = malloc(intbuffersize)) == NULL) {
    288 		perror("cannot allocate preformatting buffer");
    289 		exit(EXIT_FAILURE);
    290 	}
    291 
    292 	/* Do the work. */
    293 	filter();
    294 
    295 	exit(EXIT_SUCCESS);
    296 	/* NOTREACHED */
    297 }
    298 
    299 static void
    300 filter()
    301 {
    302 	int line;		/* logical line number */
    303 	int section;		/* logical page section */
    304 	unsigned int adjblank;	/* adjacent blank lines */
    305 	int consumed;		/* intbuffer measurement */
    306 	int donumber, idx;
    307 
    308 	adjblank = 0;
    309 	line = startnum;
    310 	section = BODY;
    311 #ifdef __GNUC__
    312 	(void)&donumber;	/* avoid bogus `uninitialized' warning */
    313 #endif
    314 
    315 	while (fgets(buffer, (int)buffersize, stdin) != NULL) {
    316 		for (idx = FOOTER; idx <= NP_LAST; idx++) {
    317 			/* Does it look like a delimiter? */
    318 			if (buffer[2 * idx + 0] == delim[0] &&
    319 			    buffer[2 * idx + 1] == delim[1]) {
    320 				/* Was this the whole line? */
    321 				if (buffer[2 * idx + 2] == '\n') {
    322 					section = idx;
    323 					adjblank = 0;
    324 					if (restart)
    325 						line = startnum;
    326 					goto nextline;
    327 				}
    328 			} else {
    329 				break;
    330 			}
    331 		}
    332 
    333 		switch (numbering_properties[section].type) {
    334 		case number_all:
    335 			/*
    336 			 * Doing this for number_all only is disputable, but
    337 			 * the standard expresses an explicit dependency on
    338 			 * `-b a' etc.
    339 			 */
    340 			if (buffer[0] == '\n' && ++adjblank < nblank)
    341 				donumber = 0;
    342 			else
    343 				donumber = 1, adjblank = 0;
    344 			break;
    345 		case number_nonempty:
    346 			donumber = (buffer[0] != '\n');
    347 			break;
    348 		case number_none:
    349 			donumber = 0;
    350 			break;
    351 		case number_regex:
    352 			donumber =
    353 			    (regexec(&numbering_properties[section].expr,
    354 			    buffer, 0, NULL, 0) == 0);
    355 			break;
    356 		}
    357 
    358 		if (donumber) {
    359 			/* Note: sprintf() is safe here. */
    360 			consumed = sprintf(intbuffer, format, width, line);
    361 			(void)printf("%s",
    362 			    intbuffer + max(0, consumed - width));
    363 			line += incr;
    364 		} else {
    365 			(void)printf("%*s", width, "");
    366 		}
    367 		(void)printf("%s%s", sep, buffer);
    368 
    369 		if (ferror(stdout)) {
    370 			perror("output error");
    371 			exit(EXIT_FAILURE);
    372 		}
    373 nextline:
    374 		;
    375 	}
    376 
    377 	if (ferror(stdin)) {
    378 		perror("input error");
    379 		exit(EXIT_FAILURE);
    380 	}
    381 }
    382 
    383 /*
    384  * Various support functions.
    385  */
    386 
    387 static void
    388 parse_numbering(argstr, section)
    389 	const char *argstr;
    390 	int section;
    391 {
    392 	int error;
    393 	char errorbuf[LINE_MAX];	/* should be sufficient in any case */
    394 
    395 	switch (argstr[0]) {
    396 	case 'a':
    397 		numbering_properties[section].type = number_all;
    398 		break;
    399 	case 'n':
    400 		numbering_properties[section].type = number_none;
    401 		break;
    402 	case 't':
    403 		numbering_properties[section].type = number_nonempty;
    404 		break;
    405 	case 'p':
    406 		/* If there was a previous expression, throw it away. */
    407 		if (numbering_properties[section].type == number_regex)
    408 			regfree(&numbering_properties[section].expr);
    409 		else
    410 			numbering_properties[section].type = number_regex;
    411 
    412 		/* Compile/validate the supplied regular expression. */
    413 		if ((error = regcomp(&numbering_properties[section].expr,
    414 		    &argstr[1], REG_NEWLINE|REG_NOSUB)) != 0) {
    415 			(void)regerror(error,
    416 			    &numbering_properties[section].expr,
    417 			    errorbuf, sizeof (errorbuf));
    418 			(void)fprintf(stderr,
    419 			    "nl: %s expr: %s -- %s\n",
    420 			    numbering_properties[section].name, errorbuf,
    421 			    &argstr[1]);
    422 			exit(EXIT_FAILURE);
    423 		}
    424 		break;
    425 	default:
    426 		(void)fprintf(stderr,
    427 		    "nl: illegal %s line numbering type -- %s\n",
    428 		    numbering_properties[section].name, argstr);
    429 		exit(EXIT_FAILURE);
    430 	}
    431 }
    432 
    433 static void
    434 usage()
    435 {
    436 
    437 	(void)fprintf(stderr, "usage: nl [-p] [-b type] [-d delim] [-f type] \
    438 [-h type] [-i incr] [-l num]\n\t[-n format] [-s sep] [-v startnum] [-w width] \
    439 [file]\n");
    440 	exit(EXIT_FAILURE);
    441 }
    442