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