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