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