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