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