*** empty log message ***
[coreutils.git] / src / nl.c
blob75ecbb7e23da68dca1dfe11c29ad3f1701fca8c0
1 /* nl -- number lines of files
2 Copyright (C) 89, 92, 1995-1999 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
7 any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Written by Scott Bartram (nancy!scott@uunet.uu.net)
19 Revised by David MacKenzie (djm@gnu.ai.mit.edu) */
21 #include <config.h>
23 #include <stdio.h>
24 #include <sys/types.h>
25 #include <getopt.h>
27 #include "system.h"
29 #include <regex.h>
31 #include "error.h"
32 #include "linebuffer.h"
33 #include "xstrtol.h"
35 /* The official name of this program (e.g., no `g' prefix). */
36 #define PROGRAM_NAME "nl"
38 #define AUTHORS "Scott Bartram and David MacKenzie"
40 #ifndef TRUE
41 # define TRUE 1
42 # define FALSE 0
43 #endif
45 /* Line-number formats. */
46 enum number_format
48 FORMAT_RIGHT_NOLZ, /* Right justified, no leading zeroes. */
49 FORMAT_RIGHT_LZ, /* Right justified, leading zeroes. */
50 FORMAT_LEFT /* Left justified, no leading zeroes. */
53 /* Default section delimiter characters. */
54 #define DEFAULT_SECTION_DELIMITERS "\\:"
56 /* Types of input lines: either one of the section delimiters,
57 or text to output. */
58 enum section
60 Header, Body, Footer, Text
63 /* The name this program was run with. */
64 char *program_name;
66 /* Format of body lines (-b). */
67 static char *body_type = "t";
69 /* Format of header lines (-h). */
70 static char *header_type = "n";
72 /* Format of footer lines (-f). */
73 static char *footer_type = "n";
75 /* Format currently being used (body, header, or footer). */
76 static char *current_type;
78 /* Regex for body lines to number (-bp). */
79 static struct re_pattern_buffer body_regex;
81 /* Regex for header lines to number (-hp). */
82 static struct re_pattern_buffer header_regex;
84 /* Regex for footer lines to number (-fp). */
85 static struct re_pattern_buffer footer_regex;
87 /* Pointer to current regex, if any. */
88 static struct re_pattern_buffer *current_regex = NULL;
90 /* Separator string to print after line number (-s). */
91 static char *separator_str = "\t";
93 /* Input section delimiter string (-d). */
94 static char *section_del = DEFAULT_SECTION_DELIMITERS;
96 /* Header delimiter string. */
97 static char *header_del = NULL;
99 /* Header section delimiter length. */
100 static size_t header_del_len;
102 /* Body delimiter string. */
103 static char *body_del = NULL;
105 /* Body section delimiter length. */
106 static size_t body_del_len;
108 /* Footer delimiter string. */
109 static char *footer_del = NULL;
111 /* Footer section delimiter length. */
112 static size_t footer_del_len;
114 /* Input buffer. */
115 static struct linebuffer line_buf;
117 /* printf format string for line number. */
118 static char *print_fmt;
120 /* printf format string for unnumbered lines. */
121 static char *print_no_line_fmt = NULL;
123 /* Starting line number on each page (-v). */
124 static int starting_line_number = 1;
126 /* Line number increment (-i). */
127 static int page_incr = 1;
129 /* If TRUE, reset line number at start of each page (-p). */
130 static int reset_numbers = TRUE;
132 /* Number of blank lines to consider to be one line for numbering (-l). */
133 static int blank_join = 1;
135 /* Width of line numbers (-w). */
136 static int lineno_width = 6;
138 /* Line number format (-n). */
139 static enum number_format lineno_format = FORMAT_RIGHT_NOLZ;
141 /* Current print line number. */
142 static int line_no;
144 /* Nonzero if we have ever read standard input. */
145 static int have_read_stdin;
147 static struct option const longopts[] =
149 {"header-numbering", required_argument, NULL, 'h'},
150 {"body-numbering", required_argument, NULL, 'b'},
151 {"footer-numbering", required_argument, NULL, 'f'},
152 {"starting-line-number", required_argument, NULL, 'v'},
153 {"page-increment", required_argument, NULL, 'i'},
154 {"no-renumber", no_argument, NULL, 'p'},
155 {"join-blank-lines", required_argument, NULL, 'l'},
156 {"number-separator", required_argument, NULL, 's'},
157 {"number-width", required_argument, NULL, 'w'},
158 {"number-format", required_argument, NULL, 'n'},
159 {"section-delimiter", required_argument, NULL, 'd'},
160 {GETOPT_HELP_OPTION_DECL},
161 {GETOPT_VERSION_OPTION_DECL},
162 {NULL, 0, NULL, 0}
165 /* Print a usage message and quit. */
167 void
168 usage (int status)
170 if (status != 0)
171 fprintf (stderr, _("Try `%s --help' for more information.\n"),
172 program_name);
173 else
175 printf (_("\
176 Usage: %s [OPTION]... [FILE]...\n\
178 program_name);
179 printf (_("\
180 Write each FILE to standard output, with line numbers added.\n\
181 With no FILE, or when FILE is -, read standard input.\n\
183 -b, --body-numbering=STYLE use STYLE for numbering body lines\n\
184 -d, --section-delimiter=CC use CC for separating logical pages\n\
185 -f, --footer-numbering=STYLE use STYLE for numbering footer lines\n\
186 -h, --header-numbering=STYLE use STYLE for numbering header lines\n\
187 -i, --page-increment=NUMBER line number increment at each line\n\
188 -l, --join-blank-lines=NUMBER group of NUMBER empty lines counted as one\n\
189 -n, --number-format=FORMAT insert line numbers according to FORMAT\n\
190 -p, --no-renumber do not reset line numbers at logical pages\n\
191 -s, --number-separator=STRING add STRING after (possible) line number\n\
192 -v, --first-page=NUMBER first line number on each logical page\n\
193 -w, --number-width=NUMBER use NUMBER columns for line numbers\n\
194 --help display this help and exit\n\
195 --version output version information and exit\n\
197 By default, selects -v1 -i1 -l1 -sTAB -w6 -nrn -hn -bt -fn. CC are\n\
198 two delimiter characters for separating logical pages, a missing\n\
199 second character implies :. Type \\\\ for \\. STYLE is one of:\n\
201 a number all lines\n\
202 t number only nonempty lines\n\
203 n number no lines\n\
204 pREGEXP number only lines that contain a match for REGEXP\n\
206 FORMAT is one of:\n\
208 ln left justified, no leading zeros\n\
209 rn right justified, no leading zeros\n\
210 rz right justified, leading zeros\n\
212 "));
213 puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
215 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
218 /* Build the printf format string, based on `lineno_format'. */
220 static void
221 build_print_fmt (void)
223 /* 12 = 10 chars for lineno_width, 1 for %, 1 for \0. */
224 print_fmt = xmalloc (strlen (separator_str) + 12);
225 switch (lineno_format)
227 case FORMAT_RIGHT_NOLZ:
228 sprintf (print_fmt, "%%%dd%s", lineno_width, separator_str);
229 break;
230 case FORMAT_RIGHT_LZ:
231 sprintf (print_fmt, "%%0%dd%s", lineno_width, separator_str);
232 break;
233 case FORMAT_LEFT:
234 sprintf (print_fmt, "%%-%dd%s", lineno_width, separator_str);
235 break;
239 /* Set the command line flag TYPEP and possibly the regex pointer REGEXP,
240 according to `optarg'. */
242 static int
243 build_type_arg (char **typep, struct re_pattern_buffer *regexp)
245 const char *errmsg;
246 int rval = TRUE;
247 int optlen;
249 switch (*optarg)
251 case 'a':
252 case 't':
253 case 'n':
254 *typep = optarg;
255 break;
256 case 'p':
257 *typep = optarg++;
258 optlen = strlen (optarg);
259 regexp->allocated = optlen * 2;
260 regexp->buffer = (unsigned char *) xmalloc (regexp->allocated);
261 regexp->translate = NULL;
262 regexp->fastmap = xmalloc (256);
263 regexp->fastmap_accurate = 0;
264 errmsg = re_compile_pattern (optarg, optlen, regexp);
265 if (errmsg)
266 error (EXIT_FAILURE, 0, "%s", errmsg);
267 break;
268 default:
269 rval = FALSE;
270 break;
272 return rval;
275 /* Print and increment the line number. */
277 static void
278 print_lineno (void)
280 printf (print_fmt, line_no);
281 line_no += page_incr;
284 /* Switch to a header section. */
286 static void
287 proc_header (void)
289 current_type = header_type;
290 current_regex = &header_regex;
291 if (reset_numbers)
292 line_no = starting_line_number;
293 putchar ('\n');
296 /* Switch to a body section. */
298 static void
299 proc_body (void)
301 current_type = body_type;
302 current_regex = &body_regex;
303 putchar ('\n');
306 /* Switch to a footer section. */
308 static void
309 proc_footer (void)
311 current_type = footer_type;
312 current_regex = &footer_regex;
313 putchar ('\n');
316 /* Process a regular text line in `line_buf'. */
318 static void
319 proc_text (void)
321 static int blank_lines = 0; /* Consecutive blank lines so far. */
323 switch (*current_type)
325 case 'a':
326 if (blank_join > 1)
328 if (1 < line_buf.length || ++blank_lines == blank_join)
330 print_lineno ();
331 blank_lines = 0;
333 else
334 printf (print_no_line_fmt);
336 else
337 print_lineno ();
338 break;
339 case 't':
340 if (1 < line_buf.length)
341 print_lineno ();
342 else
343 printf (print_no_line_fmt);
344 break;
345 case 'n':
346 printf (print_no_line_fmt);
347 break;
348 case 'p':
349 if (re_search (current_regex, line_buf.buffer, line_buf.length - 1,
350 0, line_buf.length - 1, (struct re_registers *) 0) < 0)
351 printf (print_no_line_fmt);
352 else
353 print_lineno ();
354 break;
356 fwrite (line_buf.buffer, sizeof (char), line_buf.length, stdout);
359 /* Return the type of line in `line_buf'. */
361 static enum section
362 check_section (void)
364 size_t len = line_buf.length - 1;
366 if (len < 2 || memcmp (line_buf.buffer, section_del, 2))
367 return Text;
368 if (len == header_del_len
369 && !memcmp (line_buf.buffer, header_del, header_del_len))
370 return Header;
371 if (len == body_del_len
372 && !memcmp (line_buf.buffer, body_del, body_del_len))
373 return Body;
374 if (len == footer_del_len
375 && !memcmp (line_buf.buffer, footer_del, footer_del_len))
376 return Footer;
377 return Text;
380 /* Read and process the file pointed to by FP. */
382 static void
383 process_file (FILE *fp)
385 while (readline (&line_buf, fp))
387 switch ((int) check_section ())
389 case Header:
390 proc_header ();
391 break;
392 case Body:
393 proc_body ();
394 break;
395 case Footer:
396 proc_footer ();
397 break;
398 case Text:
399 proc_text ();
400 break;
405 /* Process file FILE to standard output.
406 Return 0 if successful, 1 if not. */
408 static int
409 nl_file (const char *file)
411 FILE *stream;
413 if (STREQ (file, "-"))
415 have_read_stdin = 1;
416 stream = stdin;
418 else
420 stream = fopen (file, "r");
421 if (stream == NULL)
423 error (0, errno, "%s", file);
424 return 1;
428 process_file (stream);
430 if (ferror (stream))
432 error (0, errno, "%s", file);
433 return 1;
435 if (STREQ (file, "-"))
436 clearerr (stream); /* Also clear EOF. */
437 else if (fclose (stream) == EOF)
439 error (0, errno, "%s", file);
440 return 1;
442 return 0;
446 main (int argc, char **argv)
448 int c, exit_status = 0;
449 size_t len;
451 program_name = argv[0];
452 setlocale (LC_ALL, "");
453 bindtextdomain (PACKAGE, LOCALEDIR);
454 textdomain (PACKAGE);
456 have_read_stdin = 0;
458 while ((c = getopt_long (argc, argv, "h:b:f:v:i:pl:s:w:n:d:", longopts,
459 NULL)) != -1)
461 switch (c)
463 case 0:
464 break;
466 case 'h':
467 if (build_type_arg (&header_type, &header_regex) != TRUE)
468 usage (2);
469 break;
470 case 'b':
471 if (build_type_arg (&body_type, &body_regex) != TRUE)
472 usage (2);
473 break;
474 case 'f':
475 if (build_type_arg (&footer_type, &footer_regex) != TRUE)
476 usage (2);
477 break;
478 case 'v':
480 long int tmp_long;
481 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
482 /* Allow it to be negative. */
483 || tmp_long > INT_MAX)
484 error (EXIT_FAILURE, 0, _("invalid starting line number: `%s'"),
485 optarg);
486 starting_line_number = (int) tmp_long;
488 break;
489 case 'i':
491 long int tmp_long;
492 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
493 || tmp_long <= 0 || tmp_long > INT_MAX)
494 error (EXIT_FAILURE, 0, _("invalid line number increment: `%s'"),
495 optarg);
496 page_incr = (int) tmp_long;
498 break;
499 case 'p':
500 reset_numbers = FALSE;
501 break;
502 case 'l':
504 long int tmp_long;
505 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
506 || tmp_long <= 0 || tmp_long > INT_MAX)
507 error (EXIT_FAILURE, 0, _("invalid number of blank lines: `%s'"),
508 optarg);
509 blank_join = (int) tmp_long;
511 break;
512 case 's':
513 separator_str = optarg;
514 break;
515 case 'w':
517 long int tmp_long;
518 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
519 || tmp_long <= 0 || tmp_long > INT_MAX)
520 error (EXIT_FAILURE, 0,
521 _("invalid line number field width: `%s'"),
522 optarg);
523 lineno_width = (int) tmp_long;
525 break;
526 case 'n':
527 switch (*optarg)
529 case 'l':
530 if (optarg[1] == 'n')
531 lineno_format = FORMAT_LEFT;
532 else
533 usage (2);
534 break;
535 case 'r':
536 switch (optarg[1])
538 case 'n':
539 lineno_format = FORMAT_RIGHT_NOLZ;
540 break;
541 case 'z':
542 lineno_format = FORMAT_RIGHT_LZ;
543 break;
544 default:
545 usage (2);
546 break;
548 break;
549 default:
550 usage (2);
551 break;
553 break;
554 case 'd':
555 section_del = optarg;
556 break;
557 case_GETOPT_HELP_CHAR;
558 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
559 default:
560 usage (2);
561 break;
565 /* Initialize the section delimiters. */
566 len = strlen (section_del);
568 header_del_len = len * 3;
569 header_del = xmalloc (header_del_len + 1);
570 strcat (strcat (strcpy (header_del, section_del), section_del), section_del);
572 body_del_len = len * 2;
573 body_del = xmalloc (body_del_len + 1);
574 strcat (strcpy (body_del, section_del), section_del);
576 footer_del_len = len;
577 footer_del = xmalloc (footer_del_len + 1);
578 strcpy (footer_del, section_del);
580 /* Initialize the input buffer. */
581 initbuffer (&line_buf);
583 /* Initialize the printf format for unnumbered lines. */
584 len = strlen (separator_str);
585 print_no_line_fmt = xmalloc (lineno_width + len + 1);
586 memset (print_no_line_fmt, ' ', lineno_width + len);
587 print_no_line_fmt[lineno_width + len] = '\0';
589 line_no = starting_line_number;
590 current_type = body_type;
591 current_regex = &body_regex;
592 build_print_fmt ();
594 /* Main processing. */
596 if (optind == argc)
597 exit_status |= nl_file ("-");
598 else
599 for (; optind < argc; optind++)
600 exit_status |= nl_file (argv[optind]);
602 if (have_read_stdin && fclose (stdin) == EOF)
604 error (0, errno, "-");
605 exit_status = 1;
607 if (ferror (stdout) || fclose (stdout) == EOF)
608 error (EXIT_FAILURE, errno, _("write error"));
610 exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);