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