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