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