xref: /minix3/usr.bin/nl/nl.c (revision 1e69cb63f46730e77da9d78903bc04fd914ae8a8)
1 /*	$NetBSD: nl.c,v 1.12 2013/09/17 20:00:50 wiz 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.12 2013/09/17 20:00:50 wiz 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 #include <err.h>
48 
49 typedef enum {
50 	number_all,		/* number all lines */
51 	number_nonempty,	/* number non-empty lines */
52 	number_none,		/* no line numbering */
53 	number_regex		/* number lines matching regular expression */
54 } numbering_type;
55 
56 struct numbering_property {
57 	const char * const	name;		/* for diagnostics */
58 	numbering_type		type;		/* numbering type */
59 	regex_t			expr;		/* for type == number_regex */
60 };
61 
62 /* line numbering formats */
63 #define FORMAT_LN	"%-*d"	/* left justified, leading zeros suppressed */
64 #define FORMAT_RN	"%*d"	/* right justified, leading zeros suppressed */
65 #define FORMAT_RZ	"%0*d"	/* right justified, leading zeros kept */
66 
67 #define FOOTER		0
68 #define BODY		1
69 #define HEADER		2
70 #define NP_LAST		HEADER
71 
72 static struct numbering_property numbering_properties[NP_LAST + 1] = {
73 	{ "footer",	number_none,	{ 0, 0, 0, 0 } },
74 	{ "body",	number_nonempty, { 0, 0, 0, 0 } },
75 	{ "header",	number_none,	{ 0, 0, 0, 0 } },
76 };
77 
78 #define max(a, b)	((a) > (b) ? (a) : (b))
79 
80 /*
81  * Maximum number of characters required for a decimal representation of a
82  * (signed) int; courtesy of tzcode.
83  */
84 #define INT_STRLEN_MAXIMUM \
85 	((sizeof (int) * CHAR_BIT - 1) * 302 / 1000 + 2)
86 
87 static void	filter(void);
88 static void	parse_numbering(const char *, int);
89 static void	usage(void) __attribute__((__noreturn__));
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 static size_t intbuffersize;
102 
103 /*
104  * Configurable parameters.
105  */
106 /* delimiter characters that indicate the start of a logical page section */
107 static char delim[2] = { '\\', ':' };
108 
109 /* line numbering format */
110 static const char *format = FORMAT_RN;
111 
112 /* increment value used to number logical page lines */
113 static int incr = 1;
114 
115 /* number of adjacent blank lines to be considered (and numbered) as one */
116 static unsigned int nblank = 1;
117 
118 /* whether to restart numbering at logical page delimiters */
119 static int restart = 1;
120 
121 /* characters used in separating the line number and the corrsp. text line */
122 static const char *sep = "\t";
123 
124 /* initial value used to number logical page lines */
125 static int startnum = 1;
126 
127 /* number of characters to be used for the line number */
128 /* should be unsigned but required signed by `*' precision conversion */
129 static int width = 6;
130 
131 
132 int
main(int argc,char * argv[])133 main(int argc, char *argv[])
134 {
135 	int c;
136 	long val;
137 	unsigned long uval;
138 	char *ep;
139 
140 	(void)setlocale(LC_ALL, "");
141 
142 	/*
143 	 * Note: this implementation strictly conforms to the XBD Utility
144 	 * Syntax Guidelines and does not permit the optional `file' operand
145 	 * to be intermingled with the options, which is defined in the
146 	 * XCU specification (Issue 5) but declared an obsolescent feature that
147 	 * will be removed from a future issue.  It shouldn't matter, though.
148 	 */
149 	while ((c = getopt(argc, argv, "pb:d:f:h:i:l:n:s:v:w:")) != -1) {
150 		switch (c) {
151 		case 'p':
152 			restart = 0;
153 			break;
154 		case 'b':
155 			parse_numbering(optarg, BODY);
156 			break;
157 		case 'd':
158 			if (optarg[0] != '\0')
159 				delim[0] = optarg[0];
160 			if (optarg[1] != '\0')
161 				delim[1] = optarg[1];
162 			/* at most two delimiter characters */
163 			if (optarg[2] != '\0') {
164 				errx(EXIT_FAILURE,
165 				    "invalid delim argument -- %s",
166 				    optarg);
167 				/* NOTREACHED */
168 			}
169 			break;
170 		case 'f':
171 			parse_numbering(optarg, FOOTER);
172 			break;
173 		case 'h':
174 			parse_numbering(optarg, HEADER);
175 			break;
176 		case 'i':
177 			errno = 0;
178 			val = strtol(optarg, &ep, 10);
179 			if ((ep != NULL && *ep != '\0') ||
180 			 ((val == LONG_MIN || val == LONG_MAX) && errno != 0))
181 				errx(EXIT_FAILURE,
182 				    "invalid incr argument -- %s", optarg);
183 			incr = (int)val;
184 			break;
185 		case 'l':
186 			errno = 0;
187 			uval = strtoul(optarg, &ep, 10);
188 			if ((ep != NULL && *ep != '\0') ||
189 			    (uval == ULONG_MAX && errno != 0))
190 				errx(EXIT_FAILURE,
191 				    "invalid num argument -- %s", optarg);
192 			nblank = (unsigned int)uval;
193 			break;
194 		case 'n':
195 			if (strcmp(optarg, "ln") == 0) {
196 				format = FORMAT_LN;
197 			} else if (strcmp(optarg, "rn") == 0) {
198 				format = FORMAT_RN;
199 			} else if (strcmp(optarg, "rz") == 0) {
200 				format = FORMAT_RZ;
201 			} else
202 				errx(EXIT_FAILURE,
203 				    "illegal format -- %s", optarg);
204 			break;
205 		case 's':
206 			sep = optarg;
207 			break;
208 		case 'v':
209 			errno = 0;
210 			val = strtol(optarg, &ep, 10);
211 			if ((ep != NULL && *ep != '\0') ||
212 			 ((val == LONG_MIN || val == LONG_MAX) && errno != 0))
213 				errx(EXIT_FAILURE,
214 				    "invalid startnum value -- %s", optarg);
215 			startnum = (int)val;
216 			break;
217 		case 'w':
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 				errx(EXIT_FAILURE,
223 				    "invalid width value -- %s", optarg);
224 			width = (int)val;
225 			if (!(width > 0))
226 				errx(EXIT_FAILURE,
227 				    "width argument must be > 0 -- %d",
228 				    width);
229 			break;
230 		case '?':
231 		default:
232 			usage();
233 			/* NOTREACHED */
234 		}
235 	}
236 	argc -= optind;
237 	argv += optind;
238 
239 	switch (argc) {
240 	case 0:
241 		break;
242 	case 1:
243 		if (strcmp(argv[0], "-") != 0 &&
244 		    freopen(argv[0], "r", stdin) == NULL)
245 			err(EXIT_FAILURE, "Cannot open `%s'", argv[0]);
246 		break;
247 	default:
248 		usage();
249 		/* NOTREACHED */
250 	}
251 
252 	/* Determine the maximum input line length to operate on. */
253 	if ((val = sysconf(_SC_LINE_MAX)) == -1) /* ignore errno */
254 		val = LINE_MAX;
255 	/* Allocate sufficient buffer space (including the terminating NUL). */
256 	buffersize = (size_t)val + 1;
257 	if ((buffer = malloc(buffersize)) == NULL)
258 		err(EXIT_FAILURE, "Cannot allocate input line buffer");
259 
260 	/* Allocate a buffer suitable for preformatting line number. */
261 	intbuffersize = max((int)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 	return EXIT_SUCCESS;
269 	/* NOTREACHED */
270 }
271 
272 static void
filter(void)273 filter(void)
274 {
275 	int line;		/* logical line number */
276 	int section;		/* logical page section */
277 	unsigned int adjblank;	/* adjacent blank lines */
278 	int consumed;		/* intbuffer measurement */
279 	int donumber, idx;
280 
281 	adjblank = 0;
282 	line = startnum;
283 	section = BODY;
284 #ifdef __GNUC__
285 	donumber = 0;	/* avoid bogus `uninitialized' warning */
286 #endif
287 
288 	while (fgets(buffer, (int)buffersize, stdin) != NULL) {
289 		for (idx = FOOTER; idx <= NP_LAST; idx++) {
290 			/* Does it look like a delimiter? */
291 			if (buffer[2 * idx + 0] == delim[0] &&
292 			    buffer[2 * idx + 1] == delim[1]) {
293 				/* Was this the whole line? */
294 				if (buffer[2 * idx + 2] == '\n') {
295 					section = idx;
296 					adjblank = 0;
297 					if (restart)
298 						line = startnum;
299 					goto nextline;
300 				}
301 			} else {
302 				break;
303 			}
304 		}
305 
306 		switch (numbering_properties[section].type) {
307 		case number_all:
308 			/*
309 			 * Doing this for number_all only is disputable, but
310 			 * the standard expresses an explicit dependency on
311 			 * `-b a' etc.
312 			 */
313 			if (buffer[0] == '\n' && ++adjblank < nblank)
314 				donumber = 0;
315 			else
316 				donumber = 1, adjblank = 0;
317 			break;
318 		case number_nonempty:
319 			donumber = (buffer[0] != '\n');
320 			break;
321 		case number_none:
322 			donumber = 0;
323 			break;
324 		case number_regex:
325 			donumber =
326 			    (regexec(&numbering_properties[section].expr,
327 			    buffer, 0, NULL, 0) == 0);
328 			break;
329 		}
330 
331 		if (donumber) {
332 			consumed = snprintf(intbuffer, intbuffersize, format,
333 			    width, line);
334 			(void)printf("%s",
335 			    intbuffer + max(0, consumed - width));
336 			line += incr;
337 		} else {
338 			(void)printf("%*s", width, "");
339 		}
340 		(void)printf("%s%s", sep, buffer);
341 
342 		if (ferror(stdout))
343 			err(EXIT_FAILURE, "output error");
344 nextline:
345 		;
346 	}
347 
348 	if (ferror(stdin))
349 		err(EXIT_FAILURE, "input error");
350 }
351 
352 /*
353  * Various support functions.
354  */
355 
356 static void
parse_numbering(const char * argstr,int section)357 parse_numbering(const char *argstr, int section)
358 {
359 	int error;
360 	char errorbuf[NL_TEXTMAX];
361 
362 	switch (argstr[0]) {
363 	case 'a':
364 		numbering_properties[section].type = number_all;
365 		break;
366 	case 'n':
367 		numbering_properties[section].type = number_none;
368 		break;
369 	case 't':
370 		numbering_properties[section].type = number_nonempty;
371 		break;
372 	case 'p':
373 		/* If there was a previous expression, throw it away. */
374 		if (numbering_properties[section].type == number_regex)
375 			regfree(&numbering_properties[section].expr);
376 		else
377 			numbering_properties[section].type = number_regex;
378 
379 		/* Compile/validate the supplied regular expression. */
380 		if ((error = regcomp(&numbering_properties[section].expr,
381 		    &argstr[1], REG_NEWLINE|REG_NOSUB)) != 0) {
382 			(void)regerror(error,
383 			    &numbering_properties[section].expr,
384 			    errorbuf, sizeof (errorbuf));
385 			errx(EXIT_FAILURE,
386 			    "%s expr: %s -- %s",
387 			    numbering_properties[section].name, errorbuf,
388 			    &argstr[1]);
389 		}
390 		break;
391 	default:
392 		errx(EXIT_FAILURE,
393 		    "illegal %s line numbering type -- %s",
394 		    numbering_properties[section].name, argstr);
395 		exit(EXIT_FAILURE);
396 	}
397 }
398 
399 static void
usage(void)400 usage(void)
401 {
402 	(void)fprintf(stderr, "Usage: %s [-p] [-b type] [-d delim] [-f type] "
403 	    "[-h type] [-i incr] [-l num]\n\t[-n format] [-s sep] "
404 	    "[-v startnum] [-w width] [file]\n", getprogname());
405 	exit(EXIT_FAILURE);
406 }
407