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