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)
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) */
24 #include <sys/types.h>
32 #include "linebuffer.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"
45 /* Line-number formats. */
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,
60 Header, Body, Footer, Text
63 /* The name this program was run with. */
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;
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. */
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},
165 /* Print a usage message and quit. */
171 fprintf (stderr, _("Try `%s --help' for more information.\n"),
176 Usage: %s [OPTION]... [FILE]...\n\
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\
204 pREGEXP number only lines that contain a match for REGEXP\n\
208 ln left justified, no leading zeros\n\
209 rn right justified, no leading zeros\n\
210 rz right justified, leading zeros\n\
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'. */
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);
230 case FORMAT_RIGHT_LZ:
231 sprintf (print_fmt, "%%0%dd%s", lineno_width, separator_str);
234 sprintf (print_fmt, "%%-%dd%s", lineno_width, separator_str);
239 /* Set the command line flag TYPEP and possibly the regex pointer REGEXP,
240 according to `optarg'. */
243 build_type_arg (char **typep, struct re_pattern_buffer *regexp)
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);
266 error (EXIT_FAILURE, 0, "%s", errmsg);
275 /* Print and increment the line number. */
280 printf (print_fmt, line_no);
281 line_no += page_incr;
284 /* Switch to a header section. */
289 current_type = header_type;
290 current_regex = &header_regex;
292 line_no = starting_line_number;
296 /* Switch to a body section. */
301 current_type = body_type;
302 current_regex = &body_regex;
306 /* Switch to a footer section. */
311 current_type = footer_type;
312 current_regex = &footer_regex;
316 /* Process a regular text line in `line_buf'. */
321 static int blank_lines = 0; /* Consecutive blank lines so far. */
323 switch (*current_type)
328 if (1 < line_buf.length || ++blank_lines == blank_join)
334 printf (print_no_line_fmt);
340 if (1 < line_buf.length)
343 printf (print_no_line_fmt);
346 printf (print_no_line_fmt);
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);
356 fwrite (line_buf.buffer, sizeof (char), line_buf.length, stdout);
359 /* Return the type of line in `line_buf'. */
364 size_t len = line_buf.length - 1;
366 if (len < 2 || memcmp (line_buf.buffer, section_del, 2))
368 if (len == header_del_len
369 && !memcmp (line_buf.buffer, header_del, header_del_len))
371 if (len == body_del_len
372 && !memcmp (line_buf.buffer, body_del, body_del_len))
374 if (len == footer_del_len
375 && !memcmp (line_buf.buffer, footer_del, footer_del_len))
380 /* Read and process the file pointed to by FP. */
383 process_file (FILE *fp)
385 while (readline (&line_buf, fp))
387 switch ((int) check_section ())
405 /* Process file FILE to standard output.
406 Return 0 if successful, 1 if not. */
409 nl_file (const char *file)
413 if (STREQ (file, "-"))
420 stream = fopen (file, "r");
423 error (0, errno, "%s", file);
428 process_file (stream);
432 error (0, errno, "%s", file);
435 if (STREQ (file, "-"))
436 clearerr (stream); /* Also clear EOF. */
437 else if (fclose (stream) == EOF)
439 error (0, errno, "%s", file);
446 main (int argc, char **argv)
448 int c, exit_status = 0;
451 program_name = argv[0];
452 setlocale (LC_ALL, "");
453 bindtextdomain (PACKAGE, LOCALEDIR);
454 textdomain (PACKAGE);
458 while ((c = getopt_long (argc, argv, "h:b:f:v:i:pl:s:w:n:d:", longopts,
467 if (build_type_arg (&header_type, &header_regex) != TRUE)
471 if (build_type_arg (&body_type, &body_regex) != TRUE)
475 if (build_type_arg (&footer_type, &footer_regex) != TRUE)
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'"),
486 starting_line_number = (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'"),
496 page_incr = (int) tmp_long;
500 reset_numbers = FALSE;
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'"),
509 blank_join = (int) tmp_long;
513 separator_str = optarg;
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'"),
523 lineno_width = (int) tmp_long;
530 if (optarg[1] == 'n')
531 lineno_format = FORMAT_LEFT;
539 lineno_format = FORMAT_RIGHT_NOLZ;
542 lineno_format = FORMAT_RIGHT_LZ;
555 section_del = optarg;
557 case_GETOPT_HELP_CHAR;
558 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
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;
594 /* Main processing. */
597 exit_status |= nl_file ("-");
599 for (; optind < argc; optind++)
600 exit_status |= nl_file (argv[optind]);
602 if (have_read_stdin && fclose (stdin) == EOF)
604 error (0, errno, "-");
607 if (ferror (stdout) || fclose (stdout) == EOF)
608 error (EXIT_FAILURE, errno, _("write error"));
610 exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);