xref: /dragonfly/usr.bin/nl/nl.c (revision 1de703da)
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  * @(#) Copyright (c) 1999 The NetBSD Foundation, Inc.  All rights reserved.
37  * $FreeBSD: src/usr.bin/nl/nl.c,v 1.2.2.2 2002/07/15 06:18:43 tjr Exp $
38  * $DragonFly: src/usr.bin/nl/nl.c,v 1.2 2003/06/17 04:29:30 dillon Exp $
39  */
40 
41 #include <sys/cdefs.h>
42 
43 #include <sys/types.h>
44 
45 #include <err.h>
46 #include <errno.h>
47 #include <limits.h>
48 #include <locale.h>
49 #include <regex.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <unistd.h>
54 
55 typedef enum {
56 	number_all,		/* number all lines */
57 	number_nonempty,	/* number non-empty lines */
58 	number_none,		/* no line numbering */
59 	number_regex		/* number lines matching regular expression */
60 } numbering_type;
61 
62 struct numbering_property {
63 	const char * const	name;		/* for diagnostics */
64 	numbering_type		type;		/* numbering type */
65 	regex_t			expr;		/* for type == number_regex */
66 };
67 
68 /* line numbering formats */
69 #define FORMAT_LN	"%-*d"	/* left justified, leading zeros suppressed */
70 #define FORMAT_RN	"%*d"	/* right justified, leading zeros suppressed */
71 #define FORMAT_RZ	"%0*d"	/* right justified, leading zeros kept */
72 
73 #define FOOTER		0
74 #define BODY		1
75 #define HEADER		2
76 #define NP_LAST		HEADER
77 
78 static struct numbering_property numbering_properties[NP_LAST + 1] = {
79 	{ "footer",	number_none	},
80 	{ "body",	number_nonempty	},
81 	{ "header",	number_none	}
82 };
83 
84 #define max(a, b)	((a) > (b) ? (a) : (b))
85 
86 /*
87  * Maximum number of characters required for a decimal representation of a
88  * (signed) int; courtesy of tzcode.
89  */
90 #define INT_STRLEN_MAXIMUM \
91 	((sizeof (int) * CHAR_BIT - 1) * 302 / 1000 + 2)
92 
93 static void	filter(void);
94 int		main(int, char *[]);
95 static void	parse_numbering(const char *, int);
96 static void	usage(void);
97 
98 /*
99  * Pointer to dynamically allocated input line buffer, and its size.
100  */
101 static char *buffer;
102 static size_t buffersize;
103 
104 /*
105  * Dynamically allocated buffer suitable for string representation of ints.
106  */
107 static char *intbuffer;
108 
109 /*
110  * Configurable parameters.
111  */
112 /* delimiter characters that indicate the start of a logical page section */
113 static char delim[2] = { '\\', ':' };
114 
115 /* line numbering format */
116 static const char *format = FORMAT_RN;
117 
118 /* increment value used to number logical page lines */
119 static int incr = 1;
120 
121 /* number of adjacent blank lines to be considered (and numbered) as one */
122 static unsigned int nblank = 1;
123 
124 /* whether to restart numbering at logical page delimiters */
125 static int restart = 1;
126 
127 /* characters used in separating the line number and the corrsp. text line */
128 static const char *sep = "\t";
129 
130 /* initial value used to number logical page lines */
131 static int startnum = 1;
132 
133 /* number of characters to be used for the line number */
134 /* should be unsigned but required signed by `*' precision conversion */
135 static int width = 6;
136 
137 
138 int
139 main(argc, argv)
140 	int argc;
141 	char *argv[];
142 {
143 	int c;
144 	long val;
145 	unsigned long uval;
146 	char *ep;
147 	size_t intbuffersize;
148 
149 	(void)setlocale(LC_ALL, "");
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 				errx(EXIT_FAILURE,
167 				    "invalid delim argument -- %s",
168 				    optarg);
169 				/* NOTREACHED */
170 			}
171 			break;
172 		case 'f':
173 			parse_numbering(optarg, FOOTER);
174 			break;
175 		case 'h':
176 			parse_numbering(optarg, HEADER);
177 			break;
178 		case 'i':
179 			errno = 0;
180 			val = strtol(optarg, &ep, 10);
181 			if ((ep != NULL && *ep != '\0') ||
182 			 ((val == LONG_MIN || val == LONG_MAX) && errno != 0))
183 				errx(EXIT_FAILURE,
184 				    "invalid incr argument -- %s", optarg);
185 			incr = (int)val;
186 			break;
187 		case 'l':
188 			errno = 0;
189 			uval = strtoul(optarg, &ep, 10);
190 			if ((ep != NULL && *ep != '\0') ||
191 			    (uval == ULONG_MAX && errno != 0))
192 				errx(EXIT_FAILURE,
193 				    "invalid num argument -- %s", optarg);
194 			nblank = (unsigned int)uval;
195 			break;
196 		case 'n':
197 			if (strcmp(optarg, "ln") == 0) {
198 				format = FORMAT_LN;
199 			} else if (strcmp(optarg, "rn") == 0) {
200 				format = FORMAT_RN;
201 			} else if (strcmp(optarg, "rz") == 0) {
202 				format = FORMAT_RZ;
203 			} else
204 				errx(EXIT_FAILURE,
205 				    "illegal format -- %s", optarg);
206 			break;
207 		case 's':
208 			sep = optarg;
209 			break;
210 		case 'v':
211 			errno = 0;
212 			val = strtol(optarg, &ep, 10);
213 			if ((ep != NULL && *ep != '\0') ||
214 			 ((val == LONG_MIN || val == LONG_MAX) && errno != 0))
215 				errx(EXIT_FAILURE,
216 				    "invalid startnum value -- %s", optarg);
217 			startnum = (int)val;
218 			break;
219 		case 'w':
220 			errno = 0;
221 			val = strtol(optarg, &ep, 10);
222 			if ((ep != NULL && *ep != '\0') ||
223 			 ((val == LONG_MIN || val == LONG_MAX) && errno != 0))
224 				errx(EXIT_FAILURE,
225 				    "invalid width value -- %s", optarg);
226 			width = (int)val;
227 			if (!(width > 0))
228 				errx(EXIT_FAILURE,
229 				    "width argument must be > 0 -- %d",
230 				    width);
231 			break;
232 		case '?':
233 		default:
234 			usage();
235 			/* NOTREACHED */
236 		}
237 	}
238 	argc -= optind;
239 	argv += optind;
240 
241 	switch (argc) {
242 	case 0:
243 		break;
244 	case 1:
245 		if (freopen(argv[0], "r", stdin) == NULL)
246 			err(EXIT_FAILURE, "%s", argv[0]);
247 		break;
248 	default:
249 		usage();
250 		/* NOTREACHED */
251 	}
252 
253 	/* Determine the maximum input line length to operate on. */
254 	if ((val = sysconf(_SC_LINE_MAX)) == -1) /* ignore errno */
255 		val = LINE_MAX;
256 	/* Allocate sufficient buffer space (including the terminating NUL). */
257 	buffersize = (size_t)val + 1;
258 	if ((buffer = malloc(buffersize)) == NULL)
259 		err(EXIT_FAILURE, "cannot allocate input line buffer");
260 
261 	/* Allocate a buffer suitable for preformatting line number. */
262 	intbuffersize = max(INT_STRLEN_MAXIMUM, width) + 1;	/* NUL */
263 	if ((intbuffer = malloc(intbuffersize)) == NULL)
264 		err(EXIT_FAILURE, "cannot allocate preformatting buffer");
265 
266 	/* Do the work. */
267 	filter();
268 
269 	exit(EXIT_SUCCESS);
270 	/* NOTREACHED */
271 }
272 
273 static void
274 filter()
275 {
276 	int line;		/* logical line number */
277 	int section;		/* logical page section */
278 	unsigned int adjblank;	/* adjacent blank lines */
279 	int consumed;		/* intbuffer measurement */
280 	int donumber, idx;
281 
282 	adjblank = 0;
283 	line = startnum;
284 	section = BODY;
285 #ifdef __GNUC__
286 	(void)&donumber;	/* avoid bogus `uninitialized' warning */
287 #endif
288 
289 	while (fgets(buffer, (int)buffersize, stdin) != NULL) {
290 		for (idx = FOOTER; idx <= NP_LAST; idx++) {
291 			/* Does it look like a delimiter? */
292 			if (buffer[2 * idx + 0] == delim[0] &&
293 			    buffer[2 * idx + 1] == delim[1]) {
294 				/* Was this the whole line? */
295 				if (buffer[2 * idx + 2] == '\n') {
296 					section = idx;
297 					adjblank = 0;
298 					if (restart)
299 						line = startnum;
300 					goto nextline;
301 				}
302 			} else {
303 				break;
304 			}
305 		}
306 
307 		switch (numbering_properties[section].type) {
308 		case number_all:
309 			/*
310 			 * Doing this for number_all only is disputable, but
311 			 * the standard expresses an explicit dependency on
312 			 * `-b a' etc.
313 			 */
314 			if (buffer[0] == '\n' && ++adjblank < nblank)
315 				donumber = 0;
316 			else
317 				donumber = 1, adjblank = 0;
318 			break;
319 		case number_nonempty:
320 			donumber = (buffer[0] != '\n');
321 			break;
322 		case number_none:
323 			donumber = 0;
324 			break;
325 		case number_regex:
326 			donumber =
327 			    (regexec(&numbering_properties[section].expr,
328 			    buffer, 0, NULL, 0) == 0);
329 			break;
330 		}
331 
332 		if (donumber) {
333 			/* Note: sprintf() is safe here. */
334 			consumed = sprintf(intbuffer, format, width, line);
335 			(void)printf("%s",
336 			    intbuffer + max(0, consumed - width));
337 			line += incr;
338 		} else {
339 			(void)printf("%*s", width, "");
340 		}
341 		(void)printf("%s%s", sep, buffer);
342 
343 		if (ferror(stdout))
344 			err(EXIT_FAILURE, "output error");
345 nextline:
346 		;
347 	}
348 
349 	if (ferror(stdin))
350 		err(EXIT_FAILURE, "input error");
351 }
352 
353 /*
354  * Various support functions.
355  */
356 
357 static void
358 parse_numbering(argstr, section)
359 	const char *argstr;
360 	int section;
361 {
362 	int error;
363 	char errorbuf[NL_TEXTMAX];
364 
365 	switch (argstr[0]) {
366 	case 'a':
367 		numbering_properties[section].type = number_all;
368 		break;
369 	case 'n':
370 		numbering_properties[section].type = number_none;
371 		break;
372 	case 't':
373 		numbering_properties[section].type = number_nonempty;
374 		break;
375 	case 'p':
376 		/* If there was a previous expression, throw it away. */
377 		if (numbering_properties[section].type == number_regex)
378 			regfree(&numbering_properties[section].expr);
379 		else
380 			numbering_properties[section].type = number_regex;
381 
382 		/* Compile/validate the supplied regular expression. */
383 		if ((error = regcomp(&numbering_properties[section].expr,
384 		    &argstr[1], REG_NEWLINE|REG_NOSUB)) != 0) {
385 			(void)regerror(error,
386 			    &numbering_properties[section].expr,
387 			    errorbuf, sizeof (errorbuf));
388 			errx(EXIT_FAILURE,
389 			    "%s expr: %s -- %s",
390 			    numbering_properties[section].name, errorbuf,
391 			    &argstr[1]);
392 		}
393 		break;
394 	default:
395 		errx(EXIT_FAILURE,
396 		    "illegal %s line numbering type -- %s",
397 		    numbering_properties[section].name, argstr);
398 	}
399 }
400 
401 static void
402 usage()
403 {
404 
405 	(void)fprintf(stderr, "usage: nl [-p] [-b type] [-d delim] [-f type] \
406 [-h type] [-i incr] [-l num]\n\t[-n format] [-s sep] [-v startnum] [-w width] \
407 [file]\n");
408 	exit(EXIT_FAILURE);
409 }
410