xref: /freebsd/usr.bin/nl/nl.c (revision 640235e2c2ba32947f7c59d168437ffa1280f1e6)
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  *
17  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
21  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27  * POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 #ifndef lint
32 __COPYRIGHT(
33 "@(#) Copyright (c) 1999\
34  The NetBSD Foundation, Inc.  All rights reserved.");
35 __RCSID("$FreeBSD$");
36 #endif
37 
38 #include <sys/types.h>
39 
40 #include <err.h>
41 #include <errno.h>
42 #include <limits.h>
43 #include <locale.h>
44 #include <regex.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <unistd.h>
49 #include <wchar.h>
50 
51 typedef enum {
52 	number_all,		/* number all lines */
53 	number_nonempty,	/* number non-empty lines */
54 	number_none,		/* no line numbering */
55 	number_regex		/* number lines matching regular expression */
56 } numbering_type;
57 
58 struct numbering_property {
59 	const char * const	name;		/* for diagnostics */
60 	numbering_type		type;		/* numbering type */
61 	regex_t			expr;		/* for type == number_regex */
62 };
63 
64 /* line numbering formats */
65 #define FORMAT_LN	"%-*d"	/* left justified, leading zeros suppressed */
66 #define FORMAT_RN	"%*d"	/* right justified, leading zeros suppressed */
67 #define FORMAT_RZ	"%0*d"	/* right justified, leading zeros kept */
68 
69 #define FOOTER		0
70 #define BODY		1
71 #define HEADER		2
72 #define NP_LAST		HEADER
73 
74 static struct numbering_property numbering_properties[NP_LAST + 1] = {
75 	{ .name = "footer", .type = number_none },
76 	{ .name = "body", .type = number_nonempty },
77 	{ .name = "header", .type = number_none }
78 };
79 
80 #define max(a, b)	((a) > (b) ? (a) : (b))
81 
82 /*
83  * Maximum number of characters required for a decimal representation of a
84  * (signed) int; courtesy of tzcode.
85  */
86 #define INT_STRLEN_MAXIMUM \
87 	((sizeof (int) * CHAR_BIT - 1) * 302 / 1000 + 2)
88 
89 static void	filter(void);
90 static void	parse_numbering(const char *, int);
91 static void	usage(void);
92 
93 /*
94  * Dynamically allocated buffer suitable for string representation of ints.
95  */
96 static char *intbuffer;
97 
98 /* delimiter characters that indicate the start of a logical page section */
99 static char delim[2 * MB_LEN_MAX];
100 static int delimlen;
101 
102 /*
103  * Configurable parameters.
104  */
105 
106 /* line numbering format */
107 static const char *format = FORMAT_RN;
108 
109 /* increment value used to number logical page lines */
110 static int incr = 1;
111 
112 /* number of adjacent blank lines to be considered (and numbered) as one */
113 static unsigned int nblank = 1;
114 
115 /* whether to restart numbering at logical page delimiters */
116 static int restart = 1;
117 
118 /* characters used in separating the line number and the corrsp. text line */
119 static const char *sep = "\t";
120 
121 /* initial value used to number logical page lines */
122 static int startnum = 1;
123 
124 /* number of characters to be used for the line number */
125 /* should be unsigned but required signed by `*' precision conversion */
126 static int width = 6;
127 
128 
129 int
130 main(int argc, char *argv[])
131 {
132 	int c;
133 	long val;
134 	unsigned long uval;
135 	char *ep;
136 	size_t intbuffersize, clen;
137 	char delim1[MB_LEN_MAX] = { '\\' }, delim2[MB_LEN_MAX] = { ':' };
138 	size_t delim1len = 1, delim2len = 1;
139 
140 	(void)setlocale(LC_ALL, "");
141 
142 	while ((c = getopt(argc, argv, "pb:d:f:h:i:l:n:s:v:w:")) != -1) {
143 		switch (c) {
144 		case 'p':
145 			restart = 0;
146 			break;
147 		case 'b':
148 			parse_numbering(optarg, BODY);
149 			break;
150 		case 'd':
151 			clen = mbrlen(optarg, MB_CUR_MAX, NULL);
152 			if (clen == (size_t)-1 || clen == (size_t)-2)
153 				errc(EXIT_FAILURE, EILSEQ, NULL);
154 			if (clen != 0) {
155 				memcpy(delim1, optarg, delim1len = clen);
156 				clen = mbrlen(optarg + delim1len,
157 				    MB_CUR_MAX, NULL);
158 				if (clen == (size_t)-1 ||
159 				    clen == (size_t)-2)
160 					errc(EXIT_FAILURE, EILSEQ, NULL);
161 				if (clen != 0) {
162 					memcpy(delim2, optarg + delim1len,
163 					    delim2len = clen);
164 				if (optarg[delim1len + clen] != '\0')
165 					errx(EXIT_FAILURE,
166 					    "invalid delim argument -- %s",
167 					    optarg);
168 				}
169 			}
170 			break;
171 		case 'f':
172 			parse_numbering(optarg, FOOTER);
173 			break;
174 		case 'h':
175 			parse_numbering(optarg, HEADER);
176 			break;
177 		case 'i':
178 			errno = 0;
179 			val = strtol(optarg, &ep, 10);
180 			if ((ep != NULL && *ep != '\0') ||
181 			 ((val == LONG_MIN || val == LONG_MAX) && errno != 0))
182 				errx(EXIT_FAILURE,
183 				    "invalid incr argument -- %s", optarg);
184 			incr = (int)val;
185 			break;
186 		case 'l':
187 			errno = 0;
188 			uval = strtoul(optarg, &ep, 10);
189 			if ((ep != NULL && *ep != '\0') ||
190 			    (uval == ULONG_MAX && errno != 0))
191 				errx(EXIT_FAILURE,
192 				    "invalid num argument -- %s", optarg);
193 			nblank = (unsigned int)uval;
194 			break;
195 		case 'n':
196 			if (strcmp(optarg, "ln") == 0) {
197 				format = FORMAT_LN;
198 			} else if (strcmp(optarg, "rn") == 0) {
199 				format = FORMAT_RN;
200 			} else if (strcmp(optarg, "rz") == 0) {
201 				format = FORMAT_RZ;
202 			} else
203 				errx(EXIT_FAILURE,
204 				    "illegal format -- %s", optarg);
205 			break;
206 		case 's':
207 			sep = optarg;
208 			break;
209 		case 'v':
210 			errno = 0;
211 			val = strtol(optarg, &ep, 10);
212 			if ((ep != NULL && *ep != '\0') ||
213 			 ((val == LONG_MIN || val == LONG_MAX) && errno != 0))
214 				errx(EXIT_FAILURE,
215 				    "invalid startnum value -- %s", optarg);
216 			startnum = (int)val;
217 			break;
218 		case 'w':
219 			errno = 0;
220 			val = strtol(optarg, &ep, 10);
221 			if ((ep != NULL && *ep != '\0') ||
222 			 ((val == LONG_MIN || val == LONG_MAX) && errno != 0))
223 				errx(EXIT_FAILURE,
224 				    "invalid width value -- %s", optarg);
225 			width = (int)val;
226 			if (!(width > 0))
227 				errx(EXIT_FAILURE,
228 				    "width argument must be > 0 -- %d",
229 				    width);
230 			break;
231 		case '?':
232 		default:
233 			usage();
234 			/* NOTREACHED */
235 		}
236 	}
237 	argc -= optind;
238 	argv += optind;
239 
240 	switch (argc) {
241 	case 0:
242 		break;
243 	case 1:
244 		if (strcmp(argv[0], "-") != 0 &&
245 		    freopen(argv[0], "r", stdin) == NULL)
246 			err(EXIT_FAILURE, "%s", argv[0]);
247 		break;
248 	default:
249 		usage();
250 		/* NOTREACHED */
251 	}
252 
253 	/* Generate the delimiter sequence */
254 	memcpy(delim, delim1, delim1len);
255 	memcpy(delim + delim1len, delim2, delim2len);
256 	delimlen = delim1len + delim2len;
257 
258 	/* Allocate a buffer suitable for preformatting line number. */
259 	intbuffersize = max((int)INT_STRLEN_MAXIMUM, width) + 1; /* NUL */
260 	if ((intbuffer = malloc(intbuffersize)) == NULL)
261 		err(EXIT_FAILURE, "cannot allocate preformatting buffer");
262 
263 	/* Do the work. */
264 	filter();
265 
266 	exit(EXIT_SUCCESS);
267 	/* NOTREACHED */
268 }
269 
270 static void
271 filter(void)
272 {
273 	char *buffer;
274 	size_t buffersize;
275 	ssize_t linelen;
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 = 0, idx;
281 
282 	adjblank = 0;
283 	line = startnum;
284 	section = BODY;
285 
286 	buffer = NULL;
287 	buffersize = 0;
288 	while ((linelen = getline(&buffer, &buffersize, stdin)) > 0) {
289 		for (idx = FOOTER; idx <= NP_LAST; idx++) {
290 			/* Does it look like a delimiter? */
291 			if (delimlen * (idx + 1) > linelen)
292 				break;
293 			if (memcmp(buffer + delimlen * idx, delim,
294 			    delimlen) != 0)
295 				break;
296 			/* Was this the whole line? */
297 			if (buffer[delimlen * (idx + 1)] == '\n') {
298 				section = idx;
299 				adjblank = 0;
300 				if (restart)
301 					line = startnum;
302 				goto nextline;
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 			/* Note: sprintf() is safe here. */
333 			consumed = sprintf(intbuffer, format, 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)fputs(sep, stdout);
341 		(void)fwrite(buffer, linelen, 1, stdout);
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 	free(buffer);
353 }
354 
355 /*
356  * Various support functions.
357  */
358 
359 static void
360 parse_numbering(const char *argstr, 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(void)
403 {
404 
405 	(void)fprintf(stderr,
406 "usage: nl [-p] [-b type] [-d delim] [-f type] [-h type] [-i incr] [-l num]\n"
407 "          [-n format] [-s sep] [-v startnum] [-w width] [file]\n");
408 	exit(EXIT_FAILURE);
409 }
410