nl.c revision 102084
11558Srgrimes/*-
250476Speter * Copyright (c) 1999 The NetBSD Foundation, Inc.
31558Srgrimes * All rights reserved.
412481Speter *
51558Srgrimes * This code is derived from software contributed to The NetBSD Foundation
641061Sbde * by Klaus Klein.
774448Ssos *
841061Sbde * Redistribution and use in source and binary forms, with or without
939271Sphk * modification, are permitted provided that the following conditions
1039255Sgibbs * are met:
1138653Sgpalmer * 1. Redistributions of source code must retain the above copyright
1238653Sgpalmer *    notice, this list of conditions and the following disclaimer.
1355980Speter * 2. Redistributions in binary form must reproduce the above copyright
1485380Sjlemon *    notice, this list of conditions and the following disclaimer in the
1543859Sobrien *    documentation and/or other materials provided with the distribution.
1638653Sgpalmer * 3. All advertising materials mentioning features or use of this software
1738653Sgpalmer *    must display the following acknowledgement:
1838653Sgpalmer *        This product includes software developed by the NetBSD
1938653Sgpalmer *        Foundation, Inc. and its contributors.
2038653Sgpalmer * 4. Neither the name of The NetBSD Foundation nor the names of its
2169800Stomsoft *    contributors may be used to endorse or promote products derived
2238653Sgpalmer *    from this software without specific prior written permission.
2379458Sobrien *
2479457Sobrien * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
2538653Sgpalmer * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
2638653Sgpalmer * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
2769800Stomsoft * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
2838653Sgpalmer * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
2938653Sgpalmer * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
3056815Sshin * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
3138653Sgpalmer * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
3278978Sroam * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
3338653Sgpalmer * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
3438653Sgpalmer * POSSIBILITY OF SUCH DAMAGE.
3538653Sgpalmer */
3638843Sjb
3738653Sgpalmer#include <sys/cdefs.h>
3870450Sphk#ifndef lint
3978448Sdd__COPYRIGHT(
4038653Sgpalmer"@(#) Copyright (c) 1999\
4138653Sgpalmer The NetBSD Foundation, Inc.  All rights reserved.");
4238653Sgpalmer__RCSID("$FreeBSD: head/usr.bin/nl/nl.c 102084 2002-08-19 03:07:56Z jmallett $");
4338653Sgpalmer#endif
4477577Sru
4538653Sgpalmer#include <sys/types.h>
4643557Ssemenu
4777042Sru#include <err.h>
4877042Sru#include <errno.h>
4938653Sgpalmer#include <limits.h>
5094658Sscottl#include <locale.h>
5177042Sru#include <regex.h>
5277042Sru#include <stdio.h>
5338653Sgpalmer#include <stdlib.h>
5444690Sbrian#include <string.h>
5538653Sgpalmer#include <unistd.h>
5638653Sgpalmer
5738653Sgpalmertypedef enum {
5838653Sgpalmer	number_all,		/* number all lines */
5938653Sgpalmer	number_nonempty,	/* number non-empty lines */
6038653Sgpalmer	number_none,		/* no line numbering */
6155163Sshin	number_regex		/* number lines matching regular expression */
6238653Sgpalmer} numbering_type;
6398187Sgordon
6438653Sgpalmerstruct numbering_property {
6538653Sgpalmer	const char * const	name;		/* for diagnostics */
6638653Sgpalmer	numbering_type		type;		/* numbering type */
6738653Sgpalmer	regex_t			expr;		/* for type == number_regex */
6855163Sshin};
6993651Smarcel
7038653Sgpalmer/* line numbering formats */
7138653Sgpalmer#define FORMAT_LN	"%-*d"	/* left justified, leading zeros suppressed */
7241061Sbde#define FORMAT_RN	"%*d"	/* right justified, leading zeros suppressed */
7338653Sgpalmer#define FORMAT_RZ	"%0*d"	/* right justified, leading zeros kept */
7485469Sru
7546878Sobrien#define FOOTER		0
7638653Sgpalmer#define BODY		1
7742117Ssos#define HEADER		2
7842117Ssos#define NP_LAST		HEADER
7910855Sjoerg
8092868Srustatic struct numbering_property numbering_properties[NP_LAST + 1] = {
8192868Sru	{ "footer",	number_none	},
8292868Sru	{ "body",	number_nonempty	},
8392868Sru	{ "header",	number_none	}
8492868Sru};
8592868Sru
8692868Sru#define max(a, b)	((a) > (b) ? (a) : (b))
8792868Sru
8885954Speter/*
8985954Speter * Maximum number of characters required for a decimal representation of a
9085954Speter * (signed) int; courtesy of tzcode.
9197951Sgordon */
9286032Speter#define INT_STRLEN_MAXIMUM \
9386032Speter	((sizeof (int) * CHAR_BIT - 1) * 302 / 1000 + 2)
9486032Speter
9586032Speterstatic void	filter(void);
9644317Sjkhstatic void	parse_numbering(const char *, int);
9786032Speterstatic void	usage(void);
9844317Sjkh
9985954Speter/*
10085954Speter * Pointer to dynamically allocated input line buffer, and its size.
10138458Sjb */
10238458Sjbstatic char *buffer;
1031558Srgrimesstatic size_t buffersize;
104
105/*
106 * Dynamically allocated buffer suitable for string representation of ints.
107 */
108static char *intbuffer;
109
110/*
111 * Configurable parameters.
112 */
113/* delimiter characters that indicate the start of a logical page section */
114static char delim[2] = { '\\', ':' };
115
116/* line numbering format */
117static const char *format = FORMAT_RN;
118
119/* increment value used to number logical page lines */
120static int incr = 1;
121
122/* number of adjacent blank lines to be considered (and numbered) as one */
123static unsigned int nblank = 1;
124
125/* whether to restart numbering at logical page delimiters */
126static int restart = 1;
127
128/* characters used in separating the line number and the corrsp. text line */
129static const char *sep = "\t";
130
131/* initial value used to number logical page lines */
132static int startnum = 1;
133
134/* number of characters to be used for the line number */
135/* should be unsigned but required signed by `*' precision conversion */
136static int width = 6;
137
138
139int
140main(argc, argv)
141	int argc;
142	char *argv[];
143{
144	int c;
145	long val;
146	unsigned long uval;
147	char *ep;
148	size_t intbuffersize;
149
150	(void)setlocale(LC_ALL, "");
151
152	while ((c = getopt(argc, argv, "pb:d:f:h:i:l:n:s:v:w:")) != -1) {
153		switch (c) {
154		case 'p':
155			restart = 0;
156			break;
157		case 'b':
158			parse_numbering(optarg, BODY);
159			break;
160		case 'd':
161			if (optarg[0] != '\0')
162				delim[0] = optarg[0];
163			if (optarg[1] != '\0')
164				delim[1] = optarg[1];
165			/* at most two delimiter characters */
166			if (optarg[2] != '\0') {
167				errx(EXIT_FAILURE,
168				    "invalid delim argument -- %s",
169				    optarg);
170				/* NOTREACHED */
171			}
172			break;
173		case 'f':
174			parse_numbering(optarg, FOOTER);
175			break;
176		case 'h':
177			parse_numbering(optarg, HEADER);
178			break;
179		case 'i':
180			errno = 0;
181			val = strtol(optarg, &ep, 10);
182			if ((ep != NULL && *ep != '\0') ||
183			 ((val == LONG_MIN || val == LONG_MAX) && errno != 0))
184				errx(EXIT_FAILURE,
185				    "invalid incr argument -- %s", optarg);
186			incr = (int)val;
187			break;
188		case 'l':
189			errno = 0;
190			uval = strtoul(optarg, &ep, 10);
191			if ((ep != NULL && *ep != '\0') ||
192			    (uval == ULONG_MAX && errno != 0))
193				errx(EXIT_FAILURE,
194				    "invalid num argument -- %s", optarg);
195			nblank = (unsigned int)uval;
196			break;
197		case 'n':
198			if (strcmp(optarg, "ln") == 0) {
199				format = FORMAT_LN;
200			} else if (strcmp(optarg, "rn") == 0) {
201				format = FORMAT_RN;
202			} else if (strcmp(optarg, "rz") == 0) {
203				format = FORMAT_RZ;
204			} else
205				errx(EXIT_FAILURE,
206				    "illegal format -- %s", optarg);
207			break;
208		case 's':
209			sep = optarg;
210			break;
211		case 'v':
212			errno = 0;
213			val = strtol(optarg, &ep, 10);
214			if ((ep != NULL && *ep != '\0') ||
215			 ((val == LONG_MIN || val == LONG_MAX) && errno != 0))
216				errx(EXIT_FAILURE,
217				    "invalid startnum value -- %s", optarg);
218			startnum = (int)val;
219			break;
220		case 'w':
221			errno = 0;
222			val = strtol(optarg, &ep, 10);
223			if ((ep != NULL && *ep != '\0') ||
224			 ((val == LONG_MIN || val == LONG_MAX) && errno != 0))
225				errx(EXIT_FAILURE,
226				    "invalid width value -- %s", optarg);
227			width = (int)val;
228			if (!(width > 0))
229				errx(EXIT_FAILURE,
230				    "width argument must be > 0 -- %d",
231				    width);
232			break;
233		case '?':
234		default:
235			usage();
236			/* NOTREACHED */
237		}
238	}
239	argc -= optind;
240	argv += optind;
241
242	switch (argc) {
243	case 0:
244		break;
245	case 1:
246		if (freopen(argv[0], "r", stdin) == NULL)
247			err(EXIT_FAILURE, "%s", argv[0]);
248		break;
249	default:
250		usage();
251		/* NOTREACHED */
252	}
253
254	/* Determine the maximum input line length to operate on. */
255	if ((val = sysconf(_SC_LINE_MAX)) == -1) /* ignore errno */
256		val = LINE_MAX;
257	/* Allocate sufficient buffer space (including the terminating NUL). */
258	buffersize = (size_t)val + 1;
259	if ((buffer = malloc(buffersize)) == NULL)
260		err(EXIT_FAILURE, "cannot allocate input line buffer");
261
262	/* Allocate a buffer suitable for preformatting line number. */
263	intbuffersize = max(INT_STRLEN_MAXIMUM, width) + 1;	/* NUL */
264	if ((intbuffer = malloc(intbuffersize)) == NULL)
265		err(EXIT_FAILURE, "cannot allocate preformatting buffer");
266
267	/* Do the work. */
268	filter();
269
270	exit(EXIT_SUCCESS);
271	/* NOTREACHED */
272}
273
274static void
275filter()
276{
277	int line;		/* logical line number */
278	int section;		/* logical page section */
279	unsigned int adjblank;	/* adjacent blank lines */
280	int consumed;		/* intbuffer measurement */
281	int donumber, idx;
282
283	adjblank = 0;
284	line = startnum;
285	section = BODY;
286#ifdef __GNUC__
287	(void)&donumber;	/* avoid bogus `uninitialized' warning */
288#endif
289
290	while (fgets(buffer, (int)buffersize, stdin) != NULL) {
291		for (idx = FOOTER; idx <= NP_LAST; idx++) {
292			/* Does it look like a delimiter? */
293			if (buffer[2 * idx + 0] == delim[0] &&
294			    buffer[2 * idx + 1] == delim[1]) {
295				/* Was this the whole line? */
296				if (buffer[2 * idx + 2] == '\n') {
297					section = idx;
298					adjblank = 0;
299					if (restart)
300						line = startnum;
301					goto nextline;
302				}
303			} else {
304				break;
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)printf("%s%s", sep, buffer);
343
344		if (ferror(stdout))
345			err(EXIT_FAILURE, "output error");
346nextline:
347		;
348	}
349
350	if (ferror(stdin))
351		err(EXIT_FAILURE, "input error");
352}
353
354/*
355 * Various support functions.
356 */
357
358static void
359parse_numbering(argstr, section)
360	const char *argstr;
361	int section;
362{
363	int error;
364	char errorbuf[NL_TEXTMAX];
365
366	switch (argstr[0]) {
367	case 'a':
368		numbering_properties[section].type = number_all;
369		break;
370	case 'n':
371		numbering_properties[section].type = number_none;
372		break;
373	case 't':
374		numbering_properties[section].type = number_nonempty;
375		break;
376	case 'p':
377		/* If there was a previous expression, throw it away. */
378		if (numbering_properties[section].type == number_regex)
379			regfree(&numbering_properties[section].expr);
380		else
381			numbering_properties[section].type = number_regex;
382
383		/* Compile/validate the supplied regular expression. */
384		if ((error = regcomp(&numbering_properties[section].expr,
385		    &argstr[1], REG_NEWLINE|REG_NOSUB)) != 0) {
386			(void)regerror(error,
387			    &numbering_properties[section].expr,
388			    errorbuf, sizeof (errorbuf));
389			errx(EXIT_FAILURE,
390			    "%s expr: %s -- %s",
391			    numbering_properties[section].name, errorbuf,
392			    &argstr[1]);
393		}
394		break;
395	default:
396		errx(EXIT_FAILURE,
397		    "illegal %s line numbering type -- %s",
398		    numbering_properties[section].name, argstr);
399	}
400}
401
402static void
403usage()
404{
405
406	(void)fprintf(stderr, "usage: nl [-p] [-b type] [-d delim] [-f type] \
407[-h type] [-i incr] [-l num]\n\t[-n format] [-s sep] [-v startnum] [-w width] \
408[file]\n");
409	exit(EXIT_FAILURE);
410}
411