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