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