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