Remove unused "case 0".
[platform/upstream/coreutils.git] / src / nl.c
1 /* nl -- number lines of files
2    Copyright (C) 89, 92, 1995-2004 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 "quote.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 #define AUTHORS "Scott Bartram", "David MacKenzie"
40
41 /* Line-number formats.  They are given an int width, an intmax_t
42    value, and a string separator.  */
43
44 /* Right justified, no leading zeroes.  */
45 static char const FORMAT_RIGHT_NOLZ[] = "%*" PRIdMAX "%s";
46
47 /* Right justified, leading zeroes.  */
48 static char const FORMAT_RIGHT_LZ[] = "%0*" PRIdMAX "%s";
49
50 /* Left justified, no leading zeroes.  */
51 static char const FORMAT_LEFT[] = "%-*" PRIdMAX "%s";
52
53 /* Default section delimiter characters.  */
54 static char const DEFAULT_SECTION_DELIMITERS[] = "\\:";
55
56 /* Types of input lines: either one of the section delimiters,
57    or text to output. */
58 enum section
59 {
60   Header, Body, Footer, Text
61 };
62
63 /* The name this program was run with. */
64 char *program_name;
65
66 /* Format of body lines (-b).  */
67 static char *body_type = "t";
68
69 /* Format of header lines (-h).  */
70 static char *header_type = "n";
71
72 /* Format of footer lines (-f).  */
73 static char *footer_type = "n";
74
75 /* Format currently being used (body, header, or footer).  */
76 static char *current_type;
77
78 /* Regex for body lines to number (-bp).  */
79 static struct re_pattern_buffer body_regex;
80
81 /* Regex for header lines to number (-hp).  */
82 static struct re_pattern_buffer header_regex;
83
84 /* Regex for footer lines to number (-fp).  */
85 static struct re_pattern_buffer footer_regex;
86
87 /* Pointer to current regex, if any.  */
88 static struct re_pattern_buffer *current_regex = NULL;
89
90 /* Separator string to print after line number (-s).  */
91 static char *separator_str = "\t";
92
93 /* Input section delimiter string (-d).  */
94 static char const *section_del = DEFAULT_SECTION_DELIMITERS;
95
96 /* Header delimiter string.  */
97 static char *header_del = NULL;
98
99 /* Header section delimiter length.  */
100 static size_t header_del_len;
101
102 /* Body delimiter string.  */
103 static char *body_del = NULL;
104
105 /* Body section delimiter length.  */
106 static size_t body_del_len;
107
108 /* Footer delimiter string.  */
109 static char *footer_del = NULL;
110
111 /* Footer section delimiter length.  */
112 static size_t footer_del_len;
113
114 /* Input buffer.  */
115 static struct linebuffer line_buf;
116
117 /* printf format string for unnumbered lines.  */
118 static char *print_no_line_fmt = NULL;
119
120 /* Starting line number on each page (-v).  */
121 static intmax_t starting_line_number = 1;
122
123 /* Line number increment (-i).  */
124 static intmax_t page_incr = 1;
125
126 /* If true, reset line number at start of each page (-p).  */
127 static bool reset_numbers = true;
128
129 /* Number of blank lines to consider to be one line for numbering (-l).  */
130 static intmax_t blank_join = 1;
131
132 /* Width of line numbers (-w).  */
133 static int lineno_width = 6;
134
135 /* Line number format (-n).  */
136 static char const *lineno_format = FORMAT_RIGHT_NOLZ;
137
138 /* Current print line number.  */
139 static intmax_t line_no;
140
141 /* True if we have ever read standard input.  */
142 static bool have_read_stdin;
143
144 static struct option const longopts[] =
145 {
146   {"header-numbering", required_argument, NULL, 'h'},
147   {"body-numbering", required_argument, NULL, 'b'},
148   {"footer-numbering", required_argument, NULL, 'f'},
149   {"starting-line-number", required_argument, NULL, 'v'},
150   {"page-increment", required_argument, NULL, 'i'},
151   {"no-renumber", no_argument, NULL, 'p'},
152   {"join-blank-lines", required_argument, NULL, 'l'},
153   {"number-separator", required_argument, NULL, 's'},
154   {"number-width", required_argument, NULL, 'w'},
155   {"number-format", required_argument, NULL, 'n'},
156   {"section-delimiter", required_argument, NULL, 'd'},
157   {GETOPT_HELP_OPTION_DECL},
158   {GETOPT_VERSION_OPTION_DECL},
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 != EXIT_SUCCESS)
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       fputs (_("\
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 "), stdout);
181       fputs (_("\
182 Mandatory arguments to long options are mandatory for short options too.\n\
183 "), stdout);
184       fputs (_("\
185   -b, --body-numbering=STYLE      use STYLE for numbering body lines\n\
186   -d, --section-delimiter=CC      use CC for separating logical pages\n\
187   -f, --footer-numbering=STYLE    use STYLE for numbering footer lines\n\
188 "), stdout);
189       fputs (_("\
190   -h, --header-numbering=STYLE    use STYLE for numbering header lines\n\
191   -i, --page-increment=NUMBER     line number increment at each line\n\
192   -l, --join-blank-lines=NUMBER   group of NUMBER empty lines counted as one\n\
193   -n, --number-format=FORMAT      insert line numbers according to FORMAT\n\
194   -p, --no-renumber               do not reset line numbers at logical pages\n\
195   -s, --number-separator=STRING   add STRING after (possible) line number\n\
196 "), stdout);
197       fputs (_("\
198   -v, --first-page=NUMBER         first line number on each logical page\n\
199   -w, --number-width=NUMBER       use NUMBER columns for line numbers\n\
200 "), stdout);
201       fputs (HELP_OPTION_DESCRIPTION, stdout);
202       fputs (VERSION_OPTION_DESCRIPTION, stdout);
203       fputs (_("\
204 \n\
205 By default, selects -v1 -i1 -l1 -sTAB -w6 -nrn -hn -bt -fn.  CC are\n\
206 two delimiter characters for separating logical pages, a missing\n\
207 second character implies :.  Type \\\\ for \\.  STYLE is one of:\n\
208 "), stdout);
209       fputs (_("\
210 \n\
211   a         number all lines\n\
212   t         number only nonempty lines\n\
213   n         number no lines\n\
214   pBRE      number only lines that contain a match for the basic regular\n\
215               expression, BRE\n\
216 \n\
217 FORMAT is one of:\n\
218 \n\
219   ln   left justified, no leading zeros\n\
220   rn   right justified, no leading zeros\n\
221   rz   right justified, leading zeros\n\
222 \n\
223 "), stdout);
224       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
225     }
226   exit (status);
227 }
228
229 /* Set the command line flag TYPEP and possibly the regex pointer REGEXP,
230    according to `optarg'.  */
231
232 static bool
233 build_type_arg (char **typep, struct re_pattern_buffer *regexp)
234 {
235   const char *errmsg;
236   bool rval = true;
237   size_t optlen;
238
239   switch (*optarg)
240     {
241     case 'a':
242     case 't':
243     case 'n':
244       *typep = optarg;
245       break;
246     case 'p':
247       *typep = optarg++;
248       optlen = strlen (optarg);
249       regexp->allocated = optlen * 2;
250       regexp->buffer = xmalloc (regexp->allocated);
251       regexp->translate = NULL;
252       regexp->fastmap = xmalloc (256);
253       regexp->fastmap_accurate = 0;
254       errmsg = re_compile_pattern (optarg, optlen, regexp);
255       if (errmsg)
256         error (EXIT_FAILURE, 0, "%s", errmsg);
257       break;
258     default:
259       rval = false;
260       break;
261     }
262   return rval;
263 }
264
265 /* Print the line number and separator; increment the line number. */
266
267 static void
268 print_lineno (void)
269 {
270   intmax_t next_line_no;
271
272   printf (lineno_format, lineno_width, line_no, separator_str);
273   
274   next_line_no = line_no + page_incr;
275   if (next_line_no < line_no)
276     error (EXIT_FAILURE, 0, _("line number overflow"));
277   line_no = next_line_no;
278 }
279
280 /* Switch to a header section. */
281
282 static void
283 proc_header (void)
284 {
285   current_type = header_type;
286   current_regex = &header_regex;
287   if (reset_numbers)
288     line_no = starting_line_number;
289   putchar ('\n');
290 }
291
292 /* Switch to a body section. */
293
294 static void
295 proc_body (void)
296 {
297   current_type = body_type;
298   current_regex = &body_regex;
299   putchar ('\n');
300 }
301
302 /* Switch to a footer section. */
303
304 static void
305 proc_footer (void)
306 {
307   current_type = footer_type;
308   current_regex = &footer_regex;
309   putchar ('\n');
310 }
311
312 /* Process a regular text line in `line_buf'. */
313
314 static void
315 proc_text (void)
316 {
317   static intmax_t blank_lines = 0;      /* Consecutive blank lines so far. */
318
319   switch (*current_type)
320     {
321     case 'a':
322       if (blank_join > 1)
323         {
324           if (1 < line_buf.length || ++blank_lines == blank_join)
325             {
326               print_lineno ();
327               blank_lines = 0;
328             }
329           else
330             fputs (print_no_line_fmt, stdout);
331         }
332       else
333         print_lineno ();
334       break;
335     case 't':
336       if (1 < line_buf.length)
337         print_lineno ();
338       else
339         fputs (print_no_line_fmt, stdout);
340       break;
341     case 'n':
342       fputs (print_no_line_fmt, stdout);
343       break;
344     case 'p':
345       if (re_search (current_regex, line_buf.buffer, line_buf.length - 1,
346                      0, line_buf.length - 1, (struct re_registers *) 0) < 0)
347         fputs (print_no_line_fmt, stdout);
348       else
349         print_lineno ();
350       break;
351     }
352   fwrite (line_buf.buffer, sizeof (char), line_buf.length, stdout);
353 }
354
355 /* Return the type of line in `line_buf'. */
356
357 static enum section
358 check_section (void)
359 {
360   size_t len = line_buf.length - 1;
361
362   if (len < 2 || memcmp (line_buf.buffer, section_del, 2))
363     return Text;
364   if (len == header_del_len
365       && !memcmp (line_buf.buffer, header_del, header_del_len))
366     return Header;
367   if (len == body_del_len
368       && !memcmp (line_buf.buffer, body_del, body_del_len))
369     return Body;
370   if (len == 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 (readlinebuffer (&line_buf, fp))
382     {
383       switch (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 true if successful.  */
403
404 static bool
405 nl_file (const char *file)
406 {
407   FILE *stream;
408
409   if (STREQ (file, "-"))
410     {
411       have_read_stdin = true;
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 false;
421         }
422     }
423
424   process_file (stream);
425
426   if (ferror (stream))
427     {
428       error (0, errno, "%s", file);
429       return false;
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 false;
437     }
438   return true;
439 }
440
441 int
442 main (int argc, char **argv)
443 {
444   int c;
445   size_t len;
446   bool ok = true;
447
448   initialize_main (&argc, &argv);
449   program_name = argv[0];
450   setlocale (LC_ALL, "");
451   bindtextdomain (PACKAGE, LOCALEDIR);
452   textdomain (PACKAGE);
453
454   atexit (close_stdout);
455
456   have_read_stdin = false;
457
458   while ((c = getopt_long (argc, argv, "h:b:f:v:i:pl:s:w:n:d:", longopts,
459                            NULL)) != -1)
460     {
461       switch (c)
462         {
463         case 'h':
464           if (! build_type_arg (&header_type, &header_regex))
465             {
466               error (0, 0, _("invalid header numbering style: %s"),
467                      quote (optarg));
468               ok = false;
469             }
470           break;
471         case 'b':
472           if (! build_type_arg (&body_type, &body_regex))
473             {
474               error (0, 0, _("invalid body numbering style: %s"),
475                      quote (optarg));
476               ok = false;
477             }
478           break;
479         case 'f':
480           if (! build_type_arg (&footer_type, &footer_regex))
481             {
482               error (0, 0, _("invalid footer numbering style: %s"),
483                      quote (optarg));
484               ok = false;
485             }
486           break;
487         case 'v':
488           if (xstrtoimax (optarg, NULL, 10, &starting_line_number, "")
489               != LONGINT_OK)
490             {
491               error (0, 0, _("invalid starting line number: %s"),
492                      quote (optarg));
493               ok = false;
494             }
495           break;
496         case 'i':
497           if (! (xstrtoimax (optarg, NULL, 10, &page_incr, "") == LONGINT_OK
498                  && 0 < page_incr))
499             {
500               error (0, 0, _("invalid line number increment: %s"),
501                      quote (optarg));
502               ok = false;
503             }
504           break;
505         case 'p':
506           reset_numbers = false;
507           break;
508         case 'l':
509           if (! (xstrtoimax (optarg, NULL, 10, &blank_join, "") == LONGINT_OK
510                  && 0 < blank_join))
511             {
512               error (0, 0, _("invalid number of blank lines: %s"),
513                      quote (optarg));
514               ok = false;
515             }
516           break;
517         case 's':
518           separator_str = optarg;
519           break;
520         case 'w':
521           {
522             long int tmp_long;
523             if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
524                 || tmp_long <= 0 || tmp_long > INT_MAX)
525               {
526                 error (0, 0, _("invalid line number field width: %s"),
527                        quote (optarg));
528                 ok = false;
529               }
530             else
531               {
532                 lineno_width = tmp_long;
533               }
534           }
535           break;
536         case 'n':
537           if (STREQ (optarg, "ln"))
538             lineno_format = FORMAT_LEFT;
539           else if (STREQ (optarg, "rn"))
540             lineno_format = FORMAT_RIGHT_NOLZ;
541           else if (STREQ (optarg, "rz"))
542             lineno_format = FORMAT_RIGHT_LZ;
543           else
544             {
545               error (0, 0, _("invalid line numbering format: %s"),
546                      quote (optarg));
547               ok = false;
548             }
549           break;
550         case 'd':
551           section_del = optarg;
552           break;
553         case_GETOPT_HELP_CHAR;
554         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
555         default:
556           ok = false;
557           break;
558         }
559     }
560
561   if (!ok)
562     usage (EXIT_FAILURE);
563
564   /* Initialize the section delimiters.  */
565   len = strlen (section_del);
566
567   header_del_len = len * 3;
568   header_del = xmalloc (header_del_len + 1);
569   strcat (strcat (strcpy (header_del, section_del), section_del), section_del);
570
571   body_del_len = len * 2;
572   body_del = xmalloc (body_del_len + 1);
573   strcat (strcpy (body_del, section_del), section_del);
574
575   footer_del_len = len;
576   footer_del = xmalloc (footer_del_len + 1);
577   strcpy (footer_del, section_del);
578
579   /* Initialize the input buffer.  */
580   initbuffer (&line_buf);
581
582   /* Initialize the printf format for unnumbered lines. */
583   len = strlen (separator_str);
584   print_no_line_fmt = xmalloc (lineno_width + len + 1);
585   memset (print_no_line_fmt, ' ', lineno_width + len);
586   print_no_line_fmt[lineno_width + len] = '\0';
587
588   line_no = starting_line_number;
589   current_type = body_type;
590   current_regex = &body_regex;
591
592   /* Main processing. */
593
594   if (optind == argc)
595     ok = nl_file ("-");
596   else
597     for (; optind < argc; optind++)
598       ok &= nl_file (argv[optind]);
599
600   if (have_read_stdin && fclose (stdin) == EOF)
601     error (EXIT_FAILURE, errno, "-");
602
603   exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
604 }