Use PROGRAM_NAME in place of string in parse_long_options call.
[platform/upstream/coreutils.git] / src / nl.c
1 /* nl -- number lines of files
2    Copyright (C) 89, 92, 1995-1999 Free Software Foundation, Inc.
3
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.
8
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.
13
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.  */
17 \f
18 /* Written by Scott Bartram (nancy!scott@uunet.uu.net)
19    Revised by David MacKenzie (djm@gnu.ai.mit.edu) */
20
21 #include <config.h>
22
23 #include <stdio.h>
24 #include <sys/types.h>
25 #include <getopt.h>
26
27 #include "system.h"
28
29 #include <regex.h>
30
31 #include "error.h"
32 #include "linebuffer.h"
33 #include "long-options.h"
34 #include "xstrtol.h"
35
36 /* The official name of this program (e.g., no `g' prefix).  */
37 #define PROGRAM_NAME "nl"
38
39 #ifndef TRUE
40 # define TRUE   1
41 # define FALSE  0
42 #endif
43
44 /* Line-number formats. */
45 enum number_format
46 {
47   FORMAT_RIGHT_NOLZ,            /* Right justified, no leading zeroes.  */
48   FORMAT_RIGHT_LZ,              /* Right justified, leading zeroes.  */
49   FORMAT_LEFT                   /* Left justified, no leading zeroes.  */
50 };
51
52 /* Default section delimiter characters.  */
53 #define DEFAULT_SECTION_DELIMITERS  "\\:"
54
55 /* Types of input lines: either one of the section delimiters,
56    or text to output. */
57 enum section
58 {
59   Header, Body, Footer, Text
60 };
61
62 /* The name this program was run with. */
63 char *program_name;
64
65 /* Format of body lines (-b).  */
66 static char *body_type = "t";
67
68 /* Format of header lines (-h).  */
69 static char *header_type = "n";
70
71 /* Format of footer lines (-f).  */
72 static char *footer_type = "n";
73
74 /* Format currently being used (body, header, or footer).  */
75 static char *current_type;
76
77 /* Regex for body lines to number (-bp).  */
78 static struct re_pattern_buffer body_regex;
79
80 /* Regex for header lines to number (-hp).  */
81 static struct re_pattern_buffer header_regex;
82
83 /* Regex for footer lines to number (-fp).  */
84 static struct re_pattern_buffer footer_regex;
85
86 /* Pointer to current regex, if any.  */
87 static struct re_pattern_buffer *current_regex = NULL;
88
89 /* Separator string to print after line number (-s).  */
90 static char *separator_str = "\t";
91
92 /* Input section delimiter string (-d).  */
93 static char *section_del = DEFAULT_SECTION_DELIMITERS;
94
95 /* Header delimiter string.  */
96 static char *header_del = NULL;
97
98 /* Header section delimiter length.  */
99 static int header_del_len;
100
101 /* Body delimiter string.  */
102 static char *body_del = NULL;
103
104 /* Body section delimiter length.  */
105 static int body_del_len;
106
107 /* Footer delimiter string.  */
108 static char *footer_del = NULL;
109
110 /* Footer section delimiter length.  */
111 static int footer_del_len;
112
113 /* Input buffer.  */
114 static struct linebuffer line_buf;
115
116 /* printf format string for line number.  */
117 static char *print_fmt;
118
119 /* printf format string for unnumbered lines.  */
120 static char *print_no_line_fmt = NULL;
121
122 /* Starting line number on each page (-v).  */
123 static int starting_line_number = 1;
124
125 /* Line number increment (-i).  */
126 static int page_incr = 1;
127
128 /* If TRUE, reset line number at start of each page (-p).  */
129 static int reset_numbers = TRUE;
130
131 /* Number of blank lines to consider to be one line for numbering (-l).  */
132 static int blank_join = 1;
133
134 /* Width of line numbers (-w).  */
135 static int lineno_width = 6;
136
137 /* Line number format (-n).  */
138 static enum number_format lineno_format = FORMAT_RIGHT_NOLZ;
139
140 /* Current print line number.  */
141 static int line_no;
142
143 /* Nonzero if we have ever read standard input. */
144 static int have_read_stdin;
145
146 static struct option const longopts[] =
147 {
148   {"header-numbering", required_argument, NULL, 'h'},
149   {"body-numbering", required_argument, NULL, 'b'},
150   {"footer-numbering", required_argument, NULL, 'f'},
151   {"starting-line-number", required_argument, NULL, 'v'},
152   {"page-increment", required_argument, NULL, 'i'},
153   {"no-renumber", no_argument, NULL, 'p'},
154   {"join-blank-lines", required_argument, NULL, 'l'},
155   {"number-separator", required_argument, NULL, 's'},
156   {"number-width", required_argument, NULL, 'w'},
157   {"number-format", required_argument, NULL, 'n'},
158   {"section-delimiter", required_argument, NULL, 'd'},
159   {NULL, 0, NULL, 0}
160 };
161
162 /* Print a usage message and quit. */
163
164 void
165 usage (int status)
166 {
167   if (status != 0)
168     fprintf (stderr, _("Try `%s --help' for more information.\n"),
169              program_name);
170   else
171     {
172       printf (_("\
173 Usage: %s [OPTION]... [FILE]...\n\
174 "),
175               program_name);
176       printf (_("\
177 Write each FILE to standard output, with line numbers added.\n\
178 With no FILE, or when FILE is -, read standard input.\n\
179 \n\
180   -b, --body-numbering=STYLE      use STYLE for numbering body lines\n\
181   -d, --section-delimiter=CC      use CC for separating logical pages\n\
182   -f, --footer-numbering=STYLE    use STYLE for numbering footer lines\n\
183   -h, --header-numbering=STYLE    use STYLE for numbering header lines\n\
184   -i, --page-increment=NUMBER     line number increment at each line\n\
185   -l, --join-blank-lines=NUMBER   group of NUMBER empty lines counted as one\n\
186   -n, --number-format=FORMAT      insert line numbers according to FORMAT\n\
187   -p, --no-renumber               do not reset line numbers at logical pages\n\
188   -s, --number-separator=STRING   add STRING after (possible) line number\n\
189   -v, --first-page=NUMBER         first line number on each logical page\n\
190   -w, --number-width=NUMBER       use NUMBER columns for line numbers\n\
191       --help                      display this help and exit\n\
192       --version                   output version information and exit\n\
193 \n\
194 By default, selects -v1 -i1 -l1 -sTAB -w6 -nrn -hn -bt -fn.  CC are\n\
195 two delimiter characters for separating logical pages, a missing\n\
196 second character implies :.  Type \\\\ for \\.  STYLE is one of:\n\
197 \n\
198   a         number all lines\n\
199   t         number only nonempty lines\n\
200   n         number no lines\n\
201   pREGEXP   number only lines that contain a match for REGEXP\n\
202 \n\
203 FORMAT is one of:\n\
204 \n\
205   ln   left justified, no leading zeros\n\
206   rn   right justified, no leading zeros\n\
207   rz   right justified, leading zeros\n\
208 \n\
209 "));
210       puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
211     }
212   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
213 }
214
215 /* Build the printf format string, based on `lineno_format'. */
216
217 static void
218 build_print_fmt (void)
219 {
220   /* 12 = 10 chars for lineno_width, 1 for %, 1 for \0.  */
221   print_fmt = xmalloc (strlen (separator_str) + 12);
222   switch (lineno_format)
223     {
224     case FORMAT_RIGHT_NOLZ:
225       sprintf (print_fmt, "%%%dd%s", lineno_width, separator_str);
226       break;
227     case FORMAT_RIGHT_LZ:
228       sprintf (print_fmt, "%%0%dd%s", lineno_width, separator_str);
229       break;
230     case FORMAT_LEFT:
231       sprintf (print_fmt, "%%-%dd%s", lineno_width, separator_str);
232       break;
233     }
234 }
235
236 /* Set the command line flag TYPEP and possibly the regex pointer REGEXP,
237    according to `optarg'.  */
238
239 static int
240 build_type_arg (char **typep, struct re_pattern_buffer *regexp)
241 {
242   const char *errmsg;
243   int rval = TRUE;
244   int optlen;
245
246   switch (*optarg)
247     {
248     case 'a':
249     case 't':
250     case 'n':
251       *typep = optarg;
252       break;
253     case 'p':
254       *typep = optarg++;
255       optlen = strlen (optarg);
256       regexp->allocated = optlen * 2;
257       regexp->buffer = (unsigned char *) xmalloc (regexp->allocated);
258       regexp->translate = NULL;
259       regexp->fastmap = xmalloc (256);
260       regexp->fastmap_accurate = 0;
261       errmsg = re_compile_pattern (optarg, optlen, regexp);
262       if (errmsg)
263         error (EXIT_FAILURE, 0, "%s", errmsg);
264       break;
265     default:
266       rval = FALSE;
267       break;
268     }
269   return rval;
270 }
271
272 /* Print and increment the line number. */
273
274 static void
275 print_lineno (void)
276 {
277   printf (print_fmt, line_no);
278   line_no += page_incr;
279 }
280
281 /* Switch to a header section. */
282
283 static void
284 proc_header (void)
285 {
286   current_type = header_type;
287   current_regex = &header_regex;
288   if (reset_numbers)
289     line_no = starting_line_number;
290   putchar ('\n');
291 }
292
293 /* Switch to a body section. */
294
295 static void
296 proc_body (void)
297 {
298   current_type = body_type;
299   current_regex = &body_regex;
300   putchar ('\n');
301 }
302
303 /* Switch to a footer section. */
304
305 static void
306 proc_footer (void)
307 {
308   current_type = footer_type;
309   current_regex = &footer_regex;
310   putchar ('\n');
311 }
312
313 /* Process a regular text line in `line_buf'. */
314
315 static void
316 proc_text (void)
317 {
318   static int blank_lines = 0;   /* Consecutive blank lines so far. */
319
320   switch (*current_type)
321     {
322     case 'a':
323       if (blank_join > 1)
324         {
325           if (line_buf.length || ++blank_lines == blank_join)
326             {
327               print_lineno ();
328               blank_lines = 0;
329             }
330           else
331             printf (print_no_line_fmt);
332         }
333       else
334         print_lineno ();
335       break;
336     case 't':
337       if (line_buf.length)
338         print_lineno ();
339       else
340         printf (print_no_line_fmt);
341       break;
342     case 'n':
343       printf (print_no_line_fmt);
344       break;
345     case 'p':
346       if (re_search (current_regex, line_buf.buffer, line_buf.length,
347                      0, line_buf.length, (struct re_registers *) 0) < 0)
348         printf (print_no_line_fmt);
349       else
350         print_lineno ();
351       break;
352     }
353   fwrite (line_buf.buffer, sizeof (char), line_buf.length, stdout);
354   putchar ('\n');
355 }
356
357 /* Return the type of line in `line_buf'. */
358
359 static enum section
360 check_section (void)
361 {
362   if (line_buf.length < 2 || memcmp (line_buf.buffer, section_del, 2))
363     return Text;
364   if (line_buf.length == header_del_len
365       && !memcmp (line_buf.buffer, header_del, header_del_len))
366     return Header;
367   if (line_buf.length == body_del_len
368       && !memcmp (line_buf.buffer, body_del, body_del_len))
369     return Body;
370   if (line_buf.length == footer_del_len
371       && !memcmp (line_buf.buffer, footer_del, footer_del_len))
372     return Footer;
373   return Text;
374 }
375
376 /* Read and process the file pointed to by FP. */
377
378 static void
379 process_file (FILE *fp)
380 {
381   while (readline (&line_buf, fp))
382     {
383       switch ((int) check_section ())
384         {
385         case Header:
386           proc_header ();
387           break;
388         case Body:
389           proc_body ();
390           break;
391         case Footer:
392           proc_footer ();
393           break;
394         case Text:
395           proc_text ();
396           break;
397         }
398     }
399 }
400
401 /* Process file FILE to standard output.
402    Return 0 if successful, 1 if not. */
403
404 static int
405 nl_file (const char *file)
406 {
407   FILE *stream;
408
409   if (STREQ (file, "-"))
410     {
411       have_read_stdin = 1;
412       stream = stdin;
413     }
414   else
415     {
416       stream = fopen (file, "r");
417       if (stream == NULL)
418         {
419           error (0, errno, "%s", file);
420           return 1;
421         }
422     }
423
424   process_file (stream);
425
426   if (ferror (stream))
427     {
428       error (0, errno, "%s", file);
429       return 1;
430     }
431   if (STREQ (file, "-"))
432     clearerr (stream);          /* Also clear EOF. */
433   else if (fclose (stream) == EOF)
434     {
435       error (0, errno, "%s", file);
436       return 1;
437     }
438   return 0;
439 }
440
441 int
442 main (int argc, char **argv)
443 {
444   int c, exit_status = 0;
445
446   program_name = argv[0];
447   setlocale (LC_ALL, "");
448   bindtextdomain (PACKAGE, LOCALEDIR);
449   textdomain (PACKAGE);
450
451   parse_long_options (argc, argv, PROGRAM_NAME, GNU_PACKAGE, VERSION,
452                       "Scott Bartram and David MacKenzie", usage);
453
454   have_read_stdin = 0;
455
456   while ((c = getopt_long (argc, argv, "h:b:f:v:i:pl:s:w:n:d:", longopts,
457                            NULL)) != -1)
458     {
459       switch (c)
460         {
461         case 0:
462           break;
463
464         case 'h':
465           if (build_type_arg (&header_type, &header_regex) != TRUE)
466             usage (2);
467           break;
468         case 'b':
469           if (build_type_arg (&body_type, &body_regex) != TRUE)
470             usage (2);
471           break;
472         case 'f':
473           if (build_type_arg (&footer_type, &footer_regex) != TRUE)
474             usage (2);
475           break;
476         case 'v':
477           {
478             long int tmp_long;
479             if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
480                 /* Allow it to be negative.  */
481                 || tmp_long > INT_MAX)
482               error (EXIT_FAILURE, 0, _("invalid starting line number: `%s'"),
483                      optarg);
484             starting_line_number = (int) tmp_long;
485           }
486           break;
487         case 'i':
488           {
489             long int tmp_long;
490             if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
491                 || tmp_long <= 0 || tmp_long > INT_MAX)
492               error (EXIT_FAILURE, 0, _("invalid line number increment: `%s'"),
493                      optarg);
494             page_incr = (int) tmp_long;
495           }
496           break;
497         case 'p':
498           reset_numbers = FALSE;
499           break;
500         case 'l':
501           {
502             long int tmp_long;
503             if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
504                 || tmp_long <= 0 || tmp_long > INT_MAX)
505               error (EXIT_FAILURE, 0, _("invalid number of blank lines: `%s'"),
506                      optarg);
507             blank_join = (int) tmp_long;
508           }
509           break;
510         case 's':
511           separator_str = optarg;
512           break;
513         case 'w':
514           {
515             long int tmp_long;
516             if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
517                 || tmp_long <= 0 || tmp_long > INT_MAX)
518               error (EXIT_FAILURE, 0,
519                      _("invalid line number field width: `%s'"),
520                      optarg);
521             lineno_width = (int) tmp_long;
522           }
523           break;
524         case 'n':
525           switch (*optarg)
526             {
527             case 'l':
528               if (optarg[1] == 'n')
529                 lineno_format = FORMAT_LEFT;
530               else
531                 usage (2);
532               break;
533             case 'r':
534               switch (optarg[1])
535                 {
536                 case 'n':
537                   lineno_format = FORMAT_RIGHT_NOLZ;
538                   break;
539                 case 'z':
540                   lineno_format = FORMAT_RIGHT_LZ;
541                   break;
542                 default:
543                   usage (2);
544                   break;
545                 }
546               break;
547             default:
548               usage (2);
549               break;
550             }
551           break;
552         case 'd':
553           section_del = optarg;
554           break;
555         default:
556           usage (2);
557           break;
558         }
559     }
560
561   /* Initialize the section delimiters.  */
562   c = strlen (section_del);
563
564   header_del_len = c * 3;
565   header_del = xmalloc (header_del_len + 1);
566   strcat (strcat (strcpy (header_del, section_del), section_del), section_del);
567
568   body_del_len = c * 2;
569   body_del = xmalloc (body_del_len + 1);
570   strcat (strcpy (body_del, section_del), section_del);
571
572   footer_del_len = c;
573   footer_del = xmalloc (footer_del_len + 1);
574   strcpy (footer_del, section_del);
575
576   /* Initialize the input buffer.  */
577   initbuffer (&line_buf);
578
579   /* Initialize the printf format for unnumbered lines. */
580   c = strlen (separator_str);
581   print_no_line_fmt = xmalloc (lineno_width + c + 1);
582   memset (print_no_line_fmt, ' ', lineno_width + c);
583   print_no_line_fmt[lineno_width + c] = '\0';
584
585   line_no = starting_line_number;
586   current_type = body_type;
587   current_regex = &body_regex;
588   build_print_fmt ();
589
590   /* Main processing. */
591
592   if (optind == argc)
593     exit_status |= nl_file ("-");
594   else
595     for (; optind < argc; optind++)
596       exit_status |= nl_file (argv[optind]);
597
598   if (have_read_stdin && fclose (stdin) == EOF)
599     {
600       error (0, errno, "-");
601       exit_status = 1;
602     }
603   if (ferror (stdout) || fclose (stdout) == EOF)
604     error (EXIT_FAILURE, errno, _("write error"));
605
606   exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
607 }