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