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