63beb57ead1eae0d30daf7929251c73399b8f769
[platform/upstream/coreutils.git] / src / nl.c
1 /* nl -- number lines of files
2    Copyright (C) 89, 92, 1995-2003 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 WRITTEN_BY _("Written by 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       fputs (_("\
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 "), stdout);
185       fputs (_("\
186 Mandatory arguments to long options are mandatory for short options too.\n\
187 "), stdout);
188       fputs (_("\
189   -b, --body-numbering=STYLE      use STYLE for numbering body lines\n\
190   -d, --section-delimiter=CC      use CC for separating logical pages\n\
191   -f, --footer-numbering=STYLE    use STYLE for numbering footer lines\n\
192 "), stdout);
193       fputs (_("\
194   -h, --header-numbering=STYLE    use STYLE for numbering header lines\n\
195   -i, --page-increment=NUMBER     line number increment at each line\n\
196   -l, --join-blank-lines=NUMBER   group of NUMBER empty lines counted as one\n\
197   -n, --number-format=FORMAT      insert line numbers according to FORMAT\n\
198   -p, --no-renumber               do not reset line numbers at logical pages\n\
199   -s, --number-separator=STRING   add STRING after (possible) line number\n\
200 "), stdout);
201       fputs (_("\
202   -v, --first-page=NUMBER         first line number on each logical page\n\
203   -w, --number-width=NUMBER       use NUMBER columns for line numbers\n\
204 "), stdout);
205       fputs (HELP_OPTION_DESCRIPTION, stdout);
206       fputs (VERSION_OPTION_DESCRIPTION, stdout);
207       fputs (_("\
208 \n\
209 By default, selects -v1 -i1 -l1 -sTAB -w6 -nrn -hn -bt -fn.  CC are\n\
210 two delimiter characters for separating logical pages, a missing\n\
211 second character implies :.  Type \\\\ for \\.  STYLE is one of:\n\
212 "), stdout);
213       fputs (_("\
214 \n\
215   a         number all lines\n\
216   t         number only nonempty lines\n\
217   n         number no lines\n\
218   pREGEXP   number only lines that contain a match for REGEXP\n\
219 \n\
220 FORMAT is one of:\n\
221 \n\
222   ln   left justified, no leading zeros\n\
223   rn   right justified, no leading zeros\n\
224   rz   right justified, leading zeros\n\
225 \n\
226 "), stdout);
227       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
228     }
229   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
230 }
231
232 /* Build the printf format string, based on `lineno_format'. */
233
234 static void
235 build_print_fmt (void)
236 {
237   print_fmt = xmalloc (  1 /* for `%' */
238                        + 1 /* for `-' or `0' */
239                        + INT_STRLEN_BOUND (lineno_width)
240                        + 1 /* for `d' */
241                        + 1 /* for trailing NUL byte */ );
242   switch (lineno_format)
243     {
244     case FORMAT_RIGHT_NOLZ:
245       sprintf (print_fmt, "%%%dd", lineno_width);
246       break;
247     case FORMAT_RIGHT_LZ:
248       sprintf (print_fmt, "%%0%dd", lineno_width);
249       break;
250     case FORMAT_LEFT:
251       sprintf (print_fmt, "%%-%dd", lineno_width);
252       break;
253     }
254 }
255
256 /* Set the command line flag TYPEP and possibly the regex pointer REGEXP,
257    according to `optarg'.  */
258
259 static int
260 build_type_arg (char **typep, struct re_pattern_buffer *regexp)
261 {
262   const char *errmsg;
263   int rval = TRUE;
264   int optlen;
265
266   switch (*optarg)
267     {
268     case 'a':
269     case 't':
270     case 'n':
271       *typep = optarg;
272       break;
273     case 'p':
274       *typep = optarg++;
275       optlen = strlen (optarg);
276       regexp->allocated = optlen * 2;
277       regexp->buffer = xmalloc (regexp->allocated);
278       regexp->translate = NULL;
279       regexp->fastmap = xmalloc (256);
280       regexp->fastmap_accurate = 0;
281       errmsg = re_compile_pattern (optarg, optlen, regexp);
282       if (errmsg)
283         error (EXIT_FAILURE, 0, "%s", errmsg);
284       break;
285     default:
286       rval = FALSE;
287       break;
288     }
289   return rval;
290 }
291
292 /* Print the line number and separator; increment the line number. */
293
294 static void
295 print_lineno (void)
296 {
297   printf (print_fmt, line_no);
298   fputs (separator_str, stdout);
299   line_no += page_incr;
300 }
301
302 /* Switch to a header section. */
303
304 static void
305 proc_header (void)
306 {
307   current_type = header_type;
308   current_regex = &header_regex;
309   if (reset_numbers)
310     line_no = starting_line_number;
311   putchar ('\n');
312 }
313
314 /* Switch to a body section. */
315
316 static void
317 proc_body (void)
318 {
319   current_type = body_type;
320   current_regex = &body_regex;
321   putchar ('\n');
322 }
323
324 /* Switch to a footer section. */
325
326 static void
327 proc_footer (void)
328 {
329   current_type = footer_type;
330   current_regex = &footer_regex;
331   putchar ('\n');
332 }
333
334 /* Process a regular text line in `line_buf'. */
335
336 static void
337 proc_text (void)
338 {
339   static int blank_lines = 0;   /* Consecutive blank lines so far. */
340
341   switch (*current_type)
342     {
343     case 'a':
344       if (blank_join > 1)
345         {
346           if (1 < line_buf.length || ++blank_lines == blank_join)
347             {
348               print_lineno ();
349               blank_lines = 0;
350             }
351           else
352             fputs (print_no_line_fmt, stdout);
353         }
354       else
355         print_lineno ();
356       break;
357     case 't':
358       if (1 < line_buf.length)
359         print_lineno ();
360       else
361         fputs (print_no_line_fmt, stdout);
362       break;
363     case 'n':
364       fputs (print_no_line_fmt, stdout);
365       break;
366     case 'p':
367       if (re_search (current_regex, line_buf.buffer, line_buf.length - 1,
368                      0, line_buf.length - 1, (struct re_registers *) 0) < 0)
369         fputs (print_no_line_fmt, stdout);
370       else
371         print_lineno ();
372       break;
373     }
374   fwrite (line_buf.buffer, sizeof (char), line_buf.length, stdout);
375 }
376
377 /* Return the type of line in `line_buf'. */
378
379 static enum section
380 check_section (void)
381 {
382   size_t len = line_buf.length - 1;
383
384   if (len < 2 || memcmp (line_buf.buffer, section_del, 2))
385     return Text;
386   if (len == header_del_len
387       && !memcmp (line_buf.buffer, header_del, header_del_len))
388     return Header;
389   if (len == body_del_len
390       && !memcmp (line_buf.buffer, body_del, body_del_len))
391     return Body;
392   if (len == footer_del_len
393       && !memcmp (line_buf.buffer, footer_del, footer_del_len))
394     return Footer;
395   return Text;
396 }
397
398 /* Read and process the file pointed to by FP. */
399
400 static void
401 process_file (FILE *fp)
402 {
403   while (readlinebuffer (&line_buf, fp))
404     {
405       switch ((int) check_section ())
406         {
407         case Header:
408           proc_header ();
409           break;
410         case Body:
411           proc_body ();
412           break;
413         case Footer:
414           proc_footer ();
415           break;
416         case Text:
417           proc_text ();
418           break;
419         }
420     }
421 }
422
423 /* Process file FILE to standard output.
424    Return 0 if successful, 1 if not. */
425
426 static int
427 nl_file (const char *file)
428 {
429   FILE *stream;
430
431   if (STREQ (file, "-"))
432     {
433       have_read_stdin = 1;
434       stream = stdin;
435     }
436   else
437     {
438       stream = fopen (file, "r");
439       if (stream == NULL)
440         {
441           error (0, errno, "%s", file);
442           return 1;
443         }
444     }
445
446   process_file (stream);
447
448   if (ferror (stream))
449     {
450       error (0, errno, "%s", file);
451       return 1;
452     }
453   if (STREQ (file, "-"))
454     clearerr (stream);          /* Also clear EOF. */
455   else if (fclose (stream) == EOF)
456     {
457       error (0, errno, "%s", file);
458       return 1;
459     }
460   return 0;
461 }
462
463 int
464 main (int argc, char **argv)
465 {
466   int c, exit_status = 0;
467   size_t len;
468   int fail = 0;
469
470   initialize_main (&argc, &argv);
471   program_name = argv[0];
472   setlocale (LC_ALL, "");
473   bindtextdomain (PACKAGE, LOCALEDIR);
474   textdomain (PACKAGE);
475
476   atexit (close_stdout);
477
478   have_read_stdin = 0;
479
480   while ((c = getopt_long (argc, argv, "h:b:f:v:i:pl:s:w:n:d:", longopts,
481                            NULL)) != -1)
482     {
483       switch (c)
484         {
485         case 0:
486           break;
487
488         case 'h':
489           if (build_type_arg (&header_type, &header_regex) != TRUE)
490             {
491               error (0, 0, _("invalid header numbering style: %s"),
492                      quote (optarg));
493               fail = 1;
494             }
495           break;
496         case 'b':
497           if (build_type_arg (&body_type, &body_regex) != TRUE)
498             {
499               error (0, 0, _("invalid body numbering style: %s"),
500                      quote (optarg));
501               fail = 1;
502             }
503           break;
504         case 'f':
505           if (build_type_arg (&footer_type, &footer_regex) != TRUE)
506             {
507               error (0, 0, _("invalid footer numbering style: %s"),
508                      quote (optarg));
509               fail = 1;
510             }
511           break;
512         case 'v':
513           {
514             long int tmp_long;
515             if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
516                 /* Allow it to be negative.  */
517                 || tmp_long > INT_MAX)
518               {
519                 error (0, 0, _("invalid starting line number: %s"),
520                        quote (optarg));
521                 fail = 1;
522               }
523             else
524               {
525                 starting_line_number = (int) tmp_long;
526               }
527           }
528           break;
529         case 'i':
530           {
531             long int tmp_long;
532             if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
533                 || tmp_long <= 0 || tmp_long > INT_MAX)
534               {
535                 error (0, 0, _("invalid line number increment: %s"),
536                        quote (optarg));
537                 fail = 1;
538               }
539             else
540               {
541                 page_incr = (int) tmp_long;
542               }
543           }
544           break;
545         case 'p':
546           reset_numbers = FALSE;
547           break;
548         case 'l':
549           {
550             long int tmp_long;
551             if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
552                 || tmp_long <= 0 || tmp_long > INT_MAX)
553               {
554                 error (0, 0, _("invalid number of blank lines: %s"),
555                        quote (optarg));
556                 fail = 1;
557               }
558             else
559               {
560                 blank_join = (int) tmp_long;
561               }
562           }
563           break;
564         case 's':
565           separator_str = optarg;
566           break;
567         case 'w':
568           {
569             long int tmp_long;
570             if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
571                 || tmp_long <= 0 || tmp_long > INT_MAX)
572               {
573                 error (0, 0, _("invalid line number field width: %s"),
574                        quote (optarg));
575                 fail = 1;
576               }
577             else
578               {
579                 lineno_width = (int) tmp_long;
580               }
581           }
582           break;
583         case 'n':
584           if (STREQ (optarg, "ln"))
585             lineno_format = FORMAT_LEFT;
586           else if (STREQ (optarg, "rn"))
587             lineno_format = FORMAT_RIGHT_NOLZ;
588           else if (STREQ (optarg, "rz"))
589             lineno_format = FORMAT_RIGHT_LZ;
590           else
591             {
592               error (0, 0, _("invalid line numbering format: %s"),
593                      quote (optarg));
594               fail = 1;
595             }
596           break;
597         case 'd':
598           section_del = optarg;
599           break;
600         case_GETOPT_HELP_CHAR;
601         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, WRITTEN_BY);
602         default:
603           fail = 1;
604           break;
605         }
606     }
607
608   if (fail)
609     usage (2);
610
611   /* Initialize the section delimiters.  */
612   len = strlen (section_del);
613
614   header_del_len = len * 3;
615   header_del = xmalloc (header_del_len + 1);
616   strcat (strcat (strcpy (header_del, section_del), section_del), section_del);
617
618   body_del_len = len * 2;
619   body_del = xmalloc (body_del_len + 1);
620   strcat (strcpy (body_del, section_del), section_del);
621
622   footer_del_len = len;
623   footer_del = xmalloc (footer_del_len + 1);
624   strcpy (footer_del, section_del);
625
626   /* Initialize the input buffer.  */
627   initbuffer (&line_buf);
628
629   /* Initialize the printf format for unnumbered lines. */
630   len = strlen (separator_str);
631   print_no_line_fmt = xmalloc (lineno_width + len + 1);
632   memset (print_no_line_fmt, ' ', lineno_width + len);
633   print_no_line_fmt[lineno_width + len] = '\0';
634
635   line_no = starting_line_number;
636   current_type = body_type;
637   current_regex = &body_regex;
638   build_print_fmt ();
639
640   /* Main processing. */
641
642   if (optind == argc)
643     exit_status |= nl_file ("-");
644   else
645     for (; optind < argc; optind++)
646       exit_status |= nl_file (argv[optind]);
647
648   if (have_read_stdin && fclose (stdin) == EOF)
649     {
650       error (0, errno, "-");
651       exit_status = 1;
652     }
653
654   exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
655 }