xref: /dragonfly/usr.bin/nl/nl.c (revision f746689a)
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.3 2003/10/04 20:36:49 hmp 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 	{ .name = "footer",	.type = number_none	},
80 	{ .name = "body",	.type = number_nonempty	},
81 	{ .name = "header",	.type = 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 	((int)(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(int argc, char **argv)
140 {
141 	int c;
142 	long val;
143 	unsigned long uval;
144 	char *ep;
145 	size_t intbuffersize;
146 
147 	(void)setlocale(LC_ALL, "");
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 (freopen(argv[0], "r", stdin) == NULL)
244 			err(EXIT_FAILURE, "%s", argv[0]);
245 		break;
246 	default:
247 		usage();
248 		/* NOTREACHED */
249 	}
250 
251 	/* Determine the maximum input line length to operate on. */
252 	if ((val = sysconf(_SC_LINE_MAX)) == -1) /* ignore errno */
253 		val = LINE_MAX;
254 	/* Allocate sufficient buffer space (including the terminating NUL). */
255 	buffersize = (size_t)val + 1;
256 	if ((buffer = malloc(buffersize)) == NULL)
257 		err(EXIT_FAILURE, "cannot allocate input line buffer");
258 
259 	/* Allocate a buffer suitable for preformatting line number. */
260 	intbuffersize = max(INT_STRLEN_MAXIMUM, width) + 1;	/* NUL */
261 	if ((intbuffer = malloc(intbuffersize)) == NULL)
262 		err(EXIT_FAILURE, "cannot allocate preformatting buffer");
263 
264 	/* Do the work. */
265 	filter();
266 
267 	exit(EXIT_SUCCESS);
268 	/* NOTREACHED */
269 }
270 
271 static void
272 filter(void)
273 {
274 	int line;		/* logical line number */
275 	int section;		/* logical page section */
276 	unsigned int adjblank;	/* adjacent blank lines */
277 	int consumed;		/* intbuffer measurement */
278 	int donumber, idx;
279 
280 	adjblank = donumber = 0;
281 	line = startnum;
282 	section = BODY;
283 
284 	while (fgets(buffer, (int)buffersize, stdin) != NULL) {
285 		for (idx = FOOTER; idx <= NP_LAST; idx++) {
286 			/* Does it look like a delimiter? */
287 			if (buffer[2 * idx + 0] == delim[0] &&
288 			    buffer[2 * idx + 1] == delim[1]) {
289 				/* Was this the whole line? */
290 				if (buffer[2 * idx + 2] == '\n') {
291 					section = idx;
292 					adjblank = 0;
293 					if (restart)
294 						line = startnum;
295 					goto nextline;
296 				}
297 			} else {
298 				break;
299 			}
300 		}
301 
302 		switch (numbering_properties[section].type) {
303 		case number_all:
304 			/*
305 			 * Doing this for number_all only is disputable, but
306 			 * the standard expresses an explicit dependency on
307 			 * `-b a' etc.
308 			 */
309 			if (buffer[0] == '\n' && ++adjblank < nblank)
310 				donumber = 0;
311 			else
312 				donumber = 1, adjblank = 0;
313 			break;
314 		case number_nonempty:
315 			donumber = (buffer[0] != '\n');
316 			break;
317 		case number_none:
318 			donumber = 0;
319 			break;
320 		case number_regex:
321 			donumber =
322 			    (regexec(&numbering_properties[section].expr,
323 			    buffer, 0, NULL, 0) == 0);
324 			break;
325 		}
326 
327 		if (donumber) {
328 			/* Note: sprintf() is safe here. */
329 			consumed = sprintf(intbuffer, format, width, line);
330 			(void)printf("%s",
331 			    intbuffer + max(0, consumed - width));
332 			line += incr;
333 		} else {
334 			(void)printf("%*s", width, "");
335 		}
336 		(void)printf("%s%s", sep, buffer);
337 
338 		if (ferror(stdout))
339 			err(EXIT_FAILURE, "output error");
340 nextline:
341 		;
342 	}
343 
344 	if (ferror(stdin))
345 		err(EXIT_FAILURE, "input error");
346 }
347 
348 /*
349  * Various support functions.
350  */
351 
352 static void
353 parse_numbering(const char *argstr, int section)
354 {
355 	int error;
356 	char errorbuf[NL_TEXTMAX];
357 
358 	switch (argstr[0]) {
359 	case 'a':
360 		numbering_properties[section].type = number_all;
361 		break;
362 	case 'n':
363 		numbering_properties[section].type = number_none;
364 		break;
365 	case 't':
366 		numbering_properties[section].type = number_nonempty;
367 		break;
368 	case 'p':
369 		/* If there was a previous expression, throw it away. */
370 		if (numbering_properties[section].type == number_regex)
371 			regfree(&numbering_properties[section].expr);
372 		else
373 			numbering_properties[section].type = number_regex;
374 
375 		/* Compile/validate the supplied regular expression. */
376 		if ((error = regcomp(&numbering_properties[section].expr,
377 		    &argstr[1], REG_NEWLINE|REG_NOSUB)) != 0) {
378 			(void)regerror(error,
379 			    &numbering_properties[section].expr,
380 			    errorbuf, sizeof (errorbuf));
381 			errx(EXIT_FAILURE,
382 			    "%s expr: %s -- %s",
383 			    numbering_properties[section].name, errorbuf,
384 			    &argstr[1]);
385 		}
386 		break;
387 	default:
388 		errx(EXIT_FAILURE,
389 		    "illegal %s line numbering type -- %s",
390 		    numbering_properties[section].name, argstr);
391 	}
392 }
393 
394 static void
395 usage(void)
396 {
397 
398 	(void)fprintf(stderr, "usage: nl [-p] [-b type] [-d delim] [-f type] \
399 [-h type] [-i incr] [-l num]\n\t[-n format] [-s sep] [-v startnum] [-w width] \
400 [file]\n");
401 	exit(EXIT_FAILURE);
402 }
403