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