nl.c revision 1.2 1 /* $NetBSD: nl.c,v 1.2 1999/02/16 17:31:25 kleink Exp $ */
2
3 /*-
4 * Copyright (c) 1999 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Klaus Klein.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the NetBSD
21 * Foundation, Inc. and its contributors.
22 * 4. Neither the name of The NetBSD Foundation nor the names of its
23 * contributors may be used to endorse or promote products derived
24 * from this software without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
37 */
38
39 #include <sys/cdefs.h>
40 #ifndef lint
41 __COPYRIGHT(
42 "@(#) Copyright (c) 1999\
43 The NetBSD Foundation, Inc. All rights reserved.");
44 __RCSID("$NetBSD: nl.c,v 1.2 1999/02/16 17:31:25 kleink Exp $");
45 #endif
46
47 #include <errno.h>
48 #include <limits.h>
49 #include <locale.h>
50 #include <regex.h>
51 #include <stdio.h>
52 #include <stdlib.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 __P((void));
94 int main __P((int, char *[]));
95 static void parse_numbering __P((const char *, int));
96 static void usage __P((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, uval;
145 char *ep;
146 size_t intbuffersize;
147
148 (void)setlocale(LC_ALL, "");
149
150 /*
151 * Note: this implementation strictly conforms to the XBD Utility
152 * Syntax Guidelines and does not permit the optional `file' operand
153 * to be intermingled with the options, which is defined in the
154 * XCU specification (Issue 5) but declared an obsolescent feature that
155 * will be removed from a future issue. It shouldn't matter, though.
156 */
157 while ((c = getopt(argc, argv, "pb:d:f:h:i:l:n:s:v:w:")) != -1) {
158 switch (c) {
159 case 'p':
160 restart = 0;
161 break;
162 case 'b':
163 parse_numbering(optarg, BODY);
164 break;
165 case 'd':
166 if (optarg[0] != '\0')
167 delim[0] = optarg[0];
168 if (optarg[1] != '\0')
169 delim[1] = optarg[1];
170 /* at most two delimiter characters */
171 if (optarg[2] != '\0') {
172 (void)fprintf(stderr,
173 "nl: invalid delim argument -- %s\n",
174 optarg);
175 exit(EXIT_FAILURE);
176 /* NOTREACHED */
177 }
178 break;
179 case 'f':
180 parse_numbering(optarg, FOOTER);
181 break;
182 case 'h':
183 parse_numbering(optarg, HEADER);
184 break;
185 case 'i':
186 errno = 0;
187 val = strtol(optarg, &ep, 10);
188 if ((ep != NULL && *ep != '\0') ||
189 ((val == LONG_MIN || val == LONG_MAX) && errno != 0)) {
190 (void)fprintf(stderr,
191 "invalid incr argument -- %s\n", optarg);
192 exit(EXIT_FAILURE);
193 }
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 (void)fprintf(stderr,
202 "invalid num argument -- %s\n", optarg);
203 exit(EXIT_FAILURE);
204 }
205 nblank = (unsigned int)uval;
206 break;
207 case 'n':
208 if (strcmp(optarg, "ln") == 0) {
209 format = FORMAT_LN;
210 } else if (strcmp(optarg, "rn") == 0) {
211 format = FORMAT_RN;
212 } else if (strcmp(optarg, "rz") == 0) {
213 format = FORMAT_RZ;
214 } else {
215 (void)fprintf(stderr,
216 "nl: illegal format -- %s\n", optarg);
217 exit(EXIT_FAILURE);
218 }
219 break;
220 case 's':
221 sep = optarg;
222 break;
223 case 'v':
224 errno = 0;
225 val = strtol(optarg, &ep, 10);
226 if ((ep != NULL && *ep != '\0') ||
227 ((val == LONG_MIN || val == LONG_MAX) && errno != 0)) {
228 (void)fprintf(stderr,
229 "invalid startnum value -- %s\n", optarg);
230 exit(EXIT_FAILURE);
231 }
232 startnum = (int)val;
233 break;
234 case 'w':
235 errno = 0;
236 val = strtol(optarg, &ep, 10);
237 if ((ep != NULL && *ep != '\0') ||
238 ((val == LONG_MIN || val == LONG_MAX) && errno != 0)) {
239 (void)fprintf(stderr,
240 "invalid width value -- %s\n", optarg);
241 exit(EXIT_FAILURE);
242 }
243 width = (int)val;
244 if (!(width > 0)) {
245 (void)fprintf(stderr,
246 "nl: width argument must be > 0 -- %d\n",
247 width);
248 exit(EXIT_FAILURE);
249 }
250 break;
251 case '?':
252 default:
253 usage();
254 /* NOTREACHED */
255 }
256 }
257 argc -= optind;
258 argv += optind;
259
260 switch (argc) {
261 case 0:
262 break;
263 case 1:
264 if (freopen(argv[0], "r", stdin) == NULL) {
265 perror(argv[0]);
266 exit(EXIT_FAILURE);
267 }
268 break;
269 default:
270 usage();
271 /* NOTREACHED */
272 }
273
274 /* Determine the maximum input line length to operate on. */
275 if ((val = sysconf(_SC_LINE_MAX)) == -1) /* ignore errno */
276 val = LINE_MAX;
277 /* Allocate sufficient buffer space (including the terminating NUL). */
278 buffersize = (size_t)val + 1;
279 if ((buffer = malloc(buffersize)) == NULL) {
280 perror("cannot allocate input line buffer");
281 exit(EXIT_FAILURE);
282 }
283
284 /* Allocate a buffer suitable for preformatting line number. */
285 intbuffersize = max(INT_STRLEN_MAXIMUM, width) + 1; /* NUL */
286 if ((intbuffer = malloc(intbuffersize)) == NULL) {
287 perror("cannot allocate preformatting buffer");
288 exit(EXIT_FAILURE);
289 }
290
291 /* Do the work. */
292 filter();
293
294 exit(EXIT_SUCCESS);
295 /* NOTREACHED */
296 }
297
298 static void
299 filter()
300 {
301 int line; /* logical line number */
302 int section; /* logical page section */
303 unsigned int adjblank; /* adjacent blank lines */
304 int consumed; /* intbuffer measurement */
305 int donumber, idx;
306
307 adjblank = 0;
308 line = startnum;
309 section = BODY;
310 #ifdef __GNUC__
311 (void)&donumber; /* avoid bogus `uninitialized' warning */
312 #endif
313
314 while (fgets(buffer, (int)buffersize, stdin) != NULL) {
315 for (idx = FOOTER; idx <= NP_LAST; idx++) {
316 /* Does it look like a delimiter? */
317 if (buffer[2 * idx + 0] == delim[0] &&
318 buffer[2 * idx + 1] == delim[1]) {
319 /* Was this the whole line? */
320 if (buffer[2 * idx + 2] == '\n') {
321 section = idx;
322 adjblank = 0;
323 if (restart)
324 line = startnum;
325 goto nextline;
326 }
327 } else {
328 break;
329 }
330 }
331
332 switch (numbering_properties[section].type) {
333 case number_all:
334 /*
335 * Doing this for number_all only is disputable, but
336 * the standard expresses an explicit dependency on
337 * `-b a' etc.
338 */
339 if (buffer[0] == '\n' && ++adjblank < nblank)
340 donumber = 0;
341 else
342 donumber = 1, adjblank = 0;
343 break;
344 case number_nonempty:
345 donumber = (buffer[0] != '\n');
346 break;
347 case number_none:
348 donumber = 0;
349 break;
350 case number_regex:
351 donumber =
352 (regexec(&numbering_properties[section].expr,
353 buffer, 0, NULL, 0) == 0);
354 break;
355 }
356
357 if (donumber) {
358 /* Note: sprintf() is safe here. */
359 consumed = sprintf(intbuffer, format, width, line);
360 (void)printf("%s",
361 intbuffer + max(0, consumed - width));
362 line += incr;
363 } else {
364 (void)printf("%*s", width, "");
365 }
366 (void)printf("%s%s", sep, buffer);
367
368 if (ferror(stdout)) {
369 perror("output error");
370 exit(EXIT_FAILURE);
371 }
372 nextline:
373 ;
374 }
375
376 if (ferror(stdin)) {
377 perror("input error");
378 exit(EXIT_FAILURE);
379 }
380 }
381
382 /*
383 * Various support functions.
384 */
385
386 static void
387 parse_numbering(argstr, section)
388 const char *argstr;
389 int section;
390 {
391 int error;
392 char errorbuf[LINE_MAX]; /* should be sufficient in any case */
393
394 switch (argstr[0]) {
395 case 'a':
396 numbering_properties[section].type = number_all;
397 break;
398 case 'n':
399 numbering_properties[section].type = number_none;
400 break;
401 case 't':
402 numbering_properties[section].type = number_nonempty;
403 break;
404 case 'p':
405 /* If there was a previous expression, throw it away. */
406 if (numbering_properties[section].type == number_regex)
407 regfree(&numbering_properties[section].expr);
408 else
409 numbering_properties[section].type = number_regex;
410
411 /* Compile/validate the supplied regular expression. */
412 if ((error = regcomp(&numbering_properties[section].expr,
413 &argstr[1], REG_NEWLINE|REG_NOSUB)) != 0) {
414 (void)regerror(error,
415 &numbering_properties[section].expr,
416 errorbuf, sizeof (errorbuf));
417 (void)fprintf(stderr,
418 "nl: %s expr: %s -- %s\n",
419 numbering_properties[section].name, errorbuf,
420 &argstr[1]);
421 exit(EXIT_FAILURE);
422 }
423 break;
424 default:
425 (void)fprintf(stderr,
426 "nl: illegal %s line numbering type -- %s\n",
427 numbering_properties[section].name, argstr);
428 exit(EXIT_FAILURE);
429 }
430 }
431
432 static void
433 usage()
434 {
435
436 (void)fprintf(stderr, "usage: nl [-p] [-b type] [-d delim] [-f type] \
437 [-h type] [-i incr] [-l num]\n\t[-n format] [-s sep] [-v startnum] [-w width] \
438 [file]\n");
439 exit(EXIT_FAILURE);
440 }
441