nl.c revision 97338
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 37#include <sys/cdefs.h> 38#ifndef lint 39__COPYRIGHT( 40"@(#) Copyright (c) 1999\ 41 The NetBSD Foundation, Inc. All rights reserved."); 42__RCSID("$FreeBSD: head/usr.bin/nl/nl.c 97338 2002-05-27 06:46:29Z tjr $"); 43#endif 44 45#include <sys/types.h> 46 47#include <err.h> 48#include <errno.h> 49#include <limits.h> 50#include <locale.h> 51#include <regex.h> 52#include <stdio.h> 53#include <stdlib.h> 54#include <string.h> 55#include <unistd.h> 56 57typedef enum { 58 number_all, /* number all lines */ 59 number_nonempty, /* number non-empty lines */ 60 number_none, /* no line numbering */ 61 number_regex /* number lines matching regular expression */ 62} numbering_type; 63 64struct numbering_property { 65 const char * const name; /* for diagnostics */ 66 numbering_type type; /* numbering type */ 67 regex_t expr; /* for type == number_regex */ 68}; 69 70/* line numbering formats */ 71#define FORMAT_LN "%-*d" /* left justified, leading zeros suppressed */ 72#define FORMAT_RN "%*d" /* right justified, leading zeros suppressed */ 73#define FORMAT_RZ "%0*d" /* right justified, leading zeros kept */ 74 75#define FOOTER 0 76#define BODY 1 77#define HEADER 2 78#define NP_LAST HEADER 79 80static struct numbering_property numbering_properties[NP_LAST + 1] = { 81 { "footer", number_none }, 82 { "body", number_nonempty }, 83 { "header", number_none } 84}; 85 86#define max(a, b) ((a) > (b) ? (a) : (b)) 87 88/* 89 * Maximum number of characters required for a decimal representation of a 90 * (signed) int; courtesy of tzcode. 91 */ 92#define INT_STRLEN_MAXIMUM \ 93 ((sizeof (int) * CHAR_BIT - 1) * 302 / 1000 + 2) 94 95static void filter(void); 96int main(int, char *[]); 97static void parse_numbering(const char *, int); 98static void usage(void); 99 100/* 101 * Pointer to dynamically allocated input line buffer, and its size. 102 */ 103static char *buffer; 104static size_t buffersize; 105 106/* 107 * Dynamically allocated buffer suitable for string representation of ints. 108 */ 109static char *intbuffer; 110 111/* 112 * Configurable parameters. 113 */ 114/* delimiter characters that indicate the start of a logical page section */ 115static char delim[2] = { '\\', ':' }; 116 117/* line numbering format */ 118static const char *format = FORMAT_RN; 119 120/* increment value used to number logical page lines */ 121static int incr = 1; 122 123/* number of adjacent blank lines to be considered (and numbered) as one */ 124static unsigned int nblank = 1; 125 126/* whether to restart numbering at logical page delimiters */ 127static int restart = 1; 128 129/* characters used in separating the line number and the corrsp. text line */ 130static const char *sep = "\t"; 131 132/* initial value used to number logical page lines */ 133static int startnum = 1; 134 135/* number of characters to be used for the line number */ 136/* should be unsigned but required signed by `*' precision conversion */ 137static int width = 6; 138 139 140int 141main(argc, argv) 142 int argc; 143 char *argv[]; 144{ 145 int c; 146 long val; 147 unsigned long uval; 148 char *ep; 149 size_t intbuffersize; 150 151 (void)setlocale(LC_ALL, ""); 152 153 /* 154 * Note: this implementation strictly conforms to the XBD Utility 155 * Syntax Guidelines and does not permit the optional `file' operand 156 * to be intermingled with the options, which is defined in the 157 * XCU specification (Issue 5) but declared an obsolescent feature that 158 * will be removed from a future issue. It shouldn't matter, though. 159 */ 160 while ((c = getopt(argc, argv, "pb:d:f:h:i:l:n:s:v:w:")) != -1) { 161 switch (c) { 162 case 'p': 163 restart = 0; 164 break; 165 case 'b': 166 parse_numbering(optarg, BODY); 167 break; 168 case 'd': 169 if (optarg[0] != '\0') 170 delim[0] = optarg[0]; 171 if (optarg[1] != '\0') 172 delim[1] = optarg[1]; 173 /* at most two delimiter characters */ 174 if (optarg[2] != '\0') { 175 errx(EXIT_FAILURE, 176 "invalid delim argument -- %s", 177 optarg); 178 /* NOTREACHED */ 179 } 180 break; 181 case 'f': 182 parse_numbering(optarg, FOOTER); 183 break; 184 case 'h': 185 parse_numbering(optarg, HEADER); 186 break; 187 case 'i': 188 errno = 0; 189 val = strtol(optarg, &ep, 10); 190 if ((ep != NULL && *ep != '\0') || 191 ((val == LONG_MIN || val == LONG_MAX) && errno != 0)) 192 errx(EXIT_FAILURE, 193 "invalid incr argument -- %s", optarg); 194 incr = (int)val; 195 break; 196 case 'l': 197 errno = 0; 198 uval = strtoul(optarg, &ep, 10); 199 if ((ep != NULL && *ep != '\0') || 200 (uval == ULONG_MAX && errno != 0)) 201 errx(EXIT_FAILURE, 202 "invalid num argument -- %s", optarg); 203 nblank = (unsigned int)uval; 204 break; 205 case 'n': 206 if (strcmp(optarg, "ln") == 0) { 207 format = FORMAT_LN; 208 } else if (strcmp(optarg, "rn") == 0) { 209 format = FORMAT_RN; 210 } else if (strcmp(optarg, "rz") == 0) { 211 format = FORMAT_RZ; 212 } else 213 errx(EXIT_FAILURE, 214 "illegal format -- %s", optarg); 215 break; 216 case 's': 217 sep = optarg; 218 break; 219 case 'v': 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 startnum value -- %s", optarg); 226 startnum = (int)val; 227 break; 228 case 'w': 229 errno = 0; 230 val = strtol(optarg, &ep, 10); 231 if ((ep != NULL && *ep != '\0') || 232 ((val == LONG_MIN || val == LONG_MAX) && errno != 0)) 233 errx(EXIT_FAILURE, 234 "invalid width value -- %s", optarg); 235 width = (int)val; 236 if (!(width > 0)) 237 errx(EXIT_FAILURE, 238 "width argument must be > 0 -- %d", 239 width); 240 break; 241 case '?': 242 default: 243 usage(); 244 /* NOTREACHED */ 245 } 246 } 247 argc -= optind; 248 argv += optind; 249 250 switch (argc) { 251 case 0: 252 break; 253 case 1: 254 if (freopen(argv[0], "r", stdin) == NULL) 255 err(EXIT_FAILURE, "%s", argv[0]); 256 break; 257 default: 258 usage(); 259 /* NOTREACHED */ 260 } 261 262 /* Determine the maximum input line length to operate on. */ 263 if ((val = sysconf(_SC_LINE_MAX)) == -1) /* ignore errno */ 264 val = LINE_MAX; 265 /* Allocate sufficient buffer space (including the terminating NUL). */ 266 buffersize = (size_t)val + 1; 267 if ((buffer = malloc(buffersize)) == NULL) 268 err(EXIT_FAILURE, "cannot allocate input line buffer"); 269 270 /* Allocate a buffer suitable for preformatting line number. */ 271 intbuffersize = max(INT_STRLEN_MAXIMUM, width) + 1; /* NUL */ 272 if ((intbuffer = malloc(intbuffersize)) == NULL) 273 err(EXIT_FAILURE, "cannot allocate preformatting buffer"); 274 275 /* Do the work. */ 276 filter(); 277 278 exit(EXIT_SUCCESS); 279 /* NOTREACHED */ 280} 281 282static void 283filter() 284{ 285 int line; /* logical line number */ 286 int section; /* logical page section */ 287 unsigned int adjblank; /* adjacent blank lines */ 288 int consumed; /* intbuffer measurement */ 289 int donumber, idx; 290 291 adjblank = 0; 292 line = startnum; 293 section = BODY; 294#ifdef __GNUC__ 295 (void)&donumber; /* avoid bogus `uninitialized' warning */ 296#endif 297 298 while (fgets(buffer, (int)buffersize, stdin) != NULL) { 299 for (idx = FOOTER; idx <= NP_LAST; idx++) { 300 /* Does it look like a delimiter? */ 301 if (buffer[2 * idx + 0] == delim[0] && 302 buffer[2 * idx + 1] == delim[1]) { 303 /* Was this the whole line? */ 304 if (buffer[2 * idx + 2] == '\n') { 305 section = idx; 306 adjblank = 0; 307 if (restart) 308 line = startnum; 309 goto nextline; 310 } 311 } else { 312 break; 313 } 314 } 315 316 switch (numbering_properties[section].type) { 317 case number_all: 318 /* 319 * Doing this for number_all only is disputable, but 320 * the standard expresses an explicit dependency on 321 * `-b a' etc. 322 */ 323 if (buffer[0] == '\n' && ++adjblank < nblank) 324 donumber = 0; 325 else 326 donumber = 1, adjblank = 0; 327 break; 328 case number_nonempty: 329 donumber = (buffer[0] != '\n'); 330 break; 331 case number_none: 332 donumber = 0; 333 break; 334 case number_regex: 335 donumber = 336 (regexec(&numbering_properties[section].expr, 337 buffer, 0, NULL, 0) == 0); 338 break; 339 } 340 341 if (donumber) { 342 /* Note: sprintf() is safe here. */ 343 consumed = sprintf(intbuffer, format, width, line); 344 (void)printf("%s", 345 intbuffer + max(0, consumed - width)); 346 line += incr; 347 } else { 348 (void)printf("%*s", width, ""); 349 } 350 (void)printf("%s%s", sep, buffer); 351 352 if (ferror(stdout)) 353 err(EXIT_FAILURE, "output error"); 354nextline: 355 ; 356 } 357 358 if (ferror(stdin)) 359 err(EXIT_FAILURE, "input error"); 360} 361 362/* 363 * Various support functions. 364 */ 365 366static void 367parse_numbering(argstr, section) 368 const char *argstr; 369 int section; 370{ 371 int error; 372 char errorbuf[NL_TEXTMAX]; 373 374 switch (argstr[0]) { 375 case 'a': 376 numbering_properties[section].type = number_all; 377 break; 378 case 'n': 379 numbering_properties[section].type = number_none; 380 break; 381 case 't': 382 numbering_properties[section].type = number_nonempty; 383 break; 384 case 'p': 385 /* If there was a previous expression, throw it away. */ 386 if (numbering_properties[section].type == number_regex) 387 regfree(&numbering_properties[section].expr); 388 else 389 numbering_properties[section].type = number_regex; 390 391 /* Compile/validate the supplied regular expression. */ 392 if ((error = regcomp(&numbering_properties[section].expr, 393 &argstr[1], REG_NEWLINE|REG_NOSUB)) != 0) { 394 (void)regerror(error, 395 &numbering_properties[section].expr, 396 errorbuf, sizeof (errorbuf)); 397 errx(EXIT_FAILURE, 398 "%s expr: %s -- %s", 399 numbering_properties[section].name, errorbuf, 400 &argstr[1]); 401 } 402 break; 403 default: 404 errx(EXIT_FAILURE, 405 "illegal %s line numbering type -- %s", 406 numbering_properties[section].name, argstr); 407 } 408} 409 410static void 411usage() 412{ 413 414 (void)fprintf(stderr, "usage: nl [-p] [-b type] [-d delim] [-f type] \ 415[-h type] [-i incr] [-l num]\n\t[-n format] [-s sep] [-v startnum] [-w width] \ 416[file]\n"); 417 exit(EXIT_FAILURE); 418} 419