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