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: releng/10.2/usr.bin/nl/nl.c 226362 2011-10-14 07:28:39Z ed $"); 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 52typedef 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 59struct 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 75static 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 90static void filter(void); 91static void parse_numbering(const char *, int); 92static void usage(void); 93 94/* 95 * Dynamically allocated buffer suitable for string representation of ints. 96 */ 97static char *intbuffer; 98 99/* delimiter characters that indicate the start of a logical page section */ 100static char delim[2 * MB_LEN_MAX]; 101static int delimlen; 102 103/* 104 * Configurable parameters. 105 */ 106 107/* line numbering format */ 108static const char *format = FORMAT_RN; 109 110/* increment value used to number logical page lines */ 111static int incr = 1; 112 113/* number of adjacent blank lines to be considered (and numbered) as one */ 114static unsigned int nblank = 1; 115 116/* whether to restart numbering at logical page delimiters */ 117static int restart = 1; 118 119/* characters used in separating the line number and the corrsp. text line */ 120static const char *sep = "\t"; 121 122/* initial value used to number logical page lines */ 123static 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 */ 127static int width = 6; 128 129 130int 131main(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 (freopen(argv[0], "r", stdin) == NULL) 246 err(EXIT_FAILURE, "%s", argv[0]); 247 break; 248 default: 249 usage(); 250 /* NOTREACHED */ 251 } 252 253 /* Generate the delimiter sequence */ 254 memcpy(delim, delim1, delim1len); 255 memcpy(delim + delim1len, delim2, delim2len); 256 delimlen = delim1len + delim2len; 257 258 /* Allocate a buffer suitable for preformatting line number. */ 259 intbuffersize = max((int)INT_STRLEN_MAXIMUM, width) + 1; /* NUL */ 260 if ((intbuffer = malloc(intbuffersize)) == NULL) 261 err(EXIT_FAILURE, "cannot allocate preformatting buffer"); 262 263 /* Do the work. */ 264 filter(); 265 266 exit(EXIT_SUCCESS); 267 /* NOTREACHED */ 268} 269 270static void 271filter(void) 272{ 273 char *buffer; 274 size_t buffersize; 275 ssize_t linelen; 276 int line; /* logical line number */ 277 int section; /* logical page section */ 278 unsigned int adjblank; /* adjacent blank lines */ 279 int consumed; /* intbuffer measurement */ 280 int donumber = 0, idx; 281 282 adjblank = 0; 283 line = startnum; 284 section = BODY; 285 286 buffer = NULL; 287 buffersize = 0; 288 while ((linelen = getline(&buffer, &buffersize, stdin)) > 0) { 289 for (idx = FOOTER; idx <= NP_LAST; idx++) { 290 /* Does it look like a delimiter? */ 291 if (delimlen * (idx + 1) > linelen) 292 break; 293 if (memcmp(buffer + delimlen * idx, delim, 294 delimlen) != 0) 295 break; 296 /* Was this the whole line? */ 297 if (buffer[delimlen * (idx + 1)] == '\n') { 298 section = idx; 299 adjblank = 0; 300 if (restart) 301 line = startnum; 302 goto nextline; 303 } 304 } 305 306 switch (numbering_properties[section].type) { 307 case number_all: 308 /* 309 * Doing this for number_all only is disputable, but 310 * the standard expresses an explicit dependency on 311 * `-b a' etc. 312 */ 313 if (buffer[0] == '\n' && ++adjblank < nblank) 314 donumber = 0; 315 else 316 donumber = 1, adjblank = 0; 317 break; 318 case number_nonempty: 319 donumber = (buffer[0] != '\n'); 320 break; 321 case number_none: 322 donumber = 0; 323 break; 324 case number_regex: 325 donumber = 326 (regexec(&numbering_properties[section].expr, 327 buffer, 0, NULL, 0) == 0); 328 break; 329 } 330 331 if (donumber) { 332 /* Note: sprintf() is safe here. */ 333 consumed = sprintf(intbuffer, format, width, line); 334 (void)printf("%s", 335 intbuffer + max(0, consumed - width)); 336 line += incr; 337 } else { 338 (void)printf("%*s", width, ""); 339 } 340 (void)fputs(sep, stdout); 341 (void)fwrite(buffer, linelen, 1, stdout); 342 343 if (ferror(stdout)) 344 err(EXIT_FAILURE, "output error"); 345nextline: 346 ; 347 } 348 349 if (ferror(stdin)) 350 err(EXIT_FAILURE, "input error"); 351 352 free(buffer); 353} 354 355/* 356 * Various support functions. 357 */ 358 359static void 360parse_numbering(const char *argstr, int section) 361{ 362 int error; 363 char errorbuf[NL_TEXTMAX]; 364 365 switch (argstr[0]) { 366 case 'a': 367 numbering_properties[section].type = number_all; 368 break; 369 case 'n': 370 numbering_properties[section].type = number_none; 371 break; 372 case 't': 373 numbering_properties[section].type = number_nonempty; 374 break; 375 case 'p': 376 /* If there was a previous expression, throw it away. */ 377 if (numbering_properties[section].type == number_regex) 378 regfree(&numbering_properties[section].expr); 379 else 380 numbering_properties[section].type = number_regex; 381 382 /* Compile/validate the supplied regular expression. */ 383 if ((error = regcomp(&numbering_properties[section].expr, 384 &argstr[1], REG_NEWLINE|REG_NOSUB)) != 0) { 385 (void)regerror(error, 386 &numbering_properties[section].expr, 387 errorbuf, sizeof (errorbuf)); 388 errx(EXIT_FAILURE, 389 "%s expr: %s -- %s", 390 numbering_properties[section].name, errorbuf, 391 &argstr[1]); 392 } 393 break; 394 default: 395 errx(EXIT_FAILURE, 396 "illegal %s line numbering type -- %s", 397 numbering_properties[section].name, argstr); 398 } 399} 400 401static void 402usage(void) 403{ 404 405 (void)fprintf(stderr, 406"usage: nl [-p] [-b type] [-d delim] [-f type] [-h type] [-i incr] [-l num]\n" 407" [-n format] [-s sep] [-v startnum] [-w width] [file]\n"); 408 exit(EXIT_FAILURE); 409} 410