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