[!WITH_REGEX]: Include rx.h.
[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 #if WITH_REGEX
27 # include <regex.h>
28 #else
29 # include <rx.h>
30 #endif
31 #include "linebuffer.h"
32 #include "system.h"
33 #include "version.h"
34 #include "error.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 char *xmalloc ();
60 char *xrealloc ();
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 page_start = 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   {"first-page", 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     }
219   exit (status);
220 }
221
222 /* Build the printf format string, based on `lineno_format'. */
223
224 static void
225 build_print_fmt (void)
226 {
227   /* 12 = 10 chars for lineno_width, 1 for %, 1 for \0.  */
228   print_fmt = xmalloc (strlen (separator_str) + 12);
229   switch (lineno_format)
230     {
231     case FORMAT_RIGHT_NOLZ:
232       sprintf (print_fmt, "%%%dd%s", lineno_width, separator_str);
233       break;
234     case FORMAT_RIGHT_LZ:
235       sprintf (print_fmt, "%%0%dd%s", lineno_width, separator_str);
236       break;
237     case FORMAT_LEFT:
238       sprintf (print_fmt, "%%-%dd%s", lineno_width, separator_str);
239       break;
240     }
241 }
242
243 /* Set the command line flag TYPEP and possibly the regex pointer REGEXP,
244    according to `optarg'.  */
245
246 static int
247 build_type_arg (char **typep, struct re_pattern_buffer *regexp)
248 {
249   const char *errmsg;
250   int rval = TRUE;
251   int optlen;
252
253   switch (*optarg)
254     {
255     case 'a':
256     case 't':
257     case 'n':
258       *typep = optarg;
259       break;
260     case 'p':
261       *typep = optarg++;
262       optlen = strlen (optarg);
263       regexp->allocated = optlen * 2;
264       regexp->buffer = (unsigned char *) xmalloc (regexp->allocated);
265       regexp->translate = NULL;
266       regexp->fastmap = xmalloc (256);
267       regexp->fastmap_accurate = 0;
268       errmsg = re_compile_pattern (optarg, optlen, regexp);
269       if (errmsg)
270         error (1, 0, "%s", errmsg);
271       break;
272     default:
273       rval = FALSE;
274       break;
275     }
276   return rval;
277 }
278
279 /* Print and increment the line number. */
280
281 static void
282 print_lineno (void)
283 {
284   printf (print_fmt, line_no);
285   line_no += page_incr;
286 }
287
288 /* Switch to a header section. */
289
290 static void
291 proc_header (void)
292 {
293   current_type = header_type;
294   current_regex = &header_regex;
295   if (reset_numbers)
296     line_no = page_start;
297   putchar ('\n');
298 }
299
300 /* Switch to a body section. */
301
302 static void
303 proc_body (void)
304 {
305   current_type = body_type;
306   current_regex = &body_regex;
307   putchar ('\n');
308 }
309
310 /* Switch to a footer section. */
311
312 static void
313 proc_footer (void)
314 {
315   current_type = footer_type;
316   current_regex = &footer_regex;
317   putchar ('\n');
318 }
319
320 /* Process a regular text line in `line_buf'. */
321
322 static void
323 proc_text (void)
324 {
325   static int blank_lines = 0;   /* Consecutive blank lines so far. */
326
327   switch (*current_type)
328     {
329     case 'a':
330       if (blank_join > 1)
331         {
332           if (line_buf.length || ++blank_lines == blank_join)
333             {
334               print_lineno ();
335               blank_lines = 0;
336             }
337           else
338             printf (print_no_line_fmt);
339         }
340       else
341         print_lineno ();
342       break;
343     case 't':
344       if (line_buf.length)
345         print_lineno ();
346       else
347         printf (print_no_line_fmt);
348       break;
349     case 'n':
350       printf (print_no_line_fmt);
351       break;
352     case 'p':
353       if (re_search (current_regex, line_buf.buffer, line_buf.length,
354                      0, line_buf.length, (struct re_registers *) 0) < 0)
355         printf (print_no_line_fmt);
356       else
357         print_lineno ();
358       break;
359     }
360   fwrite (line_buf.buffer, sizeof (char), line_buf.length, stdout);
361   putchar ('\n');
362 }
363
364 /* Return the type of line in `line_buf'. */
365
366 static enum section
367 check_section (void)
368 {
369   if (line_buf.length < 2 || memcmp (line_buf.buffer, section_del, 2))
370     return Text;
371   if (line_buf.length == header_del_len
372       && !memcmp (line_buf.buffer, header_del, header_del_len))
373     return Header;
374   if (line_buf.length == body_del_len
375       && !memcmp (line_buf.buffer, body_del, body_del_len))
376     return Body;
377   if (line_buf.length == footer_del_len
378       && !memcmp (line_buf.buffer, footer_del, footer_del_len))
379     return Footer;
380   return Text;
381 }
382
383 /* Read and process the file pointed to by FP. */
384
385 static void
386 process_file (FILE *fp)
387 {
388   while (readline (&line_buf, fp))
389     {
390       switch ((int) check_section ())
391         {
392         case Header:
393           proc_header ();
394           break;
395         case Body:
396           proc_body ();
397           break;
398         case Footer:
399           proc_footer ();
400           break;
401         case Text:
402           proc_text ();
403           break;
404         }
405     }
406 }
407
408 /* Process file FILE to standard output.
409    Return 0 if successful, 1 if not. */
410
411 static int
412 nl_file (const char *file)
413 {
414   FILE *stream;
415
416   if (!strcmp (file, "-"))
417     {
418       have_read_stdin = 1;
419       stream = stdin;
420     }
421   else
422     {
423       stream = fopen (file, "r");
424       if (stream == NULL)
425         {
426           error (0, errno, "%s", file);
427           return 1;
428         }
429     }
430
431   process_file (stream);
432
433   if (ferror (stream))
434     {
435       error (0, errno, "%s", file);
436       return 1;
437     }
438   if (!strcmp (file, "-"))
439     clearerr (stream);          /* Also clear EOF. */
440   else if (fclose (stream) == EOF)
441     {
442       error (0, errno, "%s", file);
443       return 1;
444     }
445   return 0;
446 }
447
448 void
449 main (int argc, char **argv)
450 {
451   int c, exit_status = 0;
452
453   program_name = argv[0];
454   have_read_stdin = 0;
455
456   while ((c = getopt_long (argc, argv, "h:b:f:v:i:pl:s:w:n:d:", longopts,
457                            (int *) 0)) != EOF)
458     {
459       switch (c)
460         {
461         case 0:
462           break;
463
464         case 'h':
465           if (build_type_arg (&header_type, &header_regex) != TRUE)
466             usage (2);
467           break;
468         case 'b':
469           if (build_type_arg (&body_type, &body_regex) != TRUE)
470             usage (2);
471           break;
472         case 'f':
473           if (build_type_arg (&footer_type, &footer_regex) != TRUE)
474             usage (2);
475           break;
476         case 'v':
477           page_start = atoi (optarg);
478           break;
479         case 'i':
480           page_incr = atoi (optarg);
481           if (page_incr < 1)
482             page_incr = 1;
483           break;
484         case 'p':
485           reset_numbers = FALSE;
486           break;
487         case 'l':
488           blank_join = atoi (optarg);
489           break;
490         case 's':
491           separator_str = optarg;
492           break;
493         case 'w':
494           lineno_width = atoi (optarg);
495           if (lineno_width < 1)
496             lineno_width = 1;
497           break;
498         case 'n':
499           switch (*optarg)
500             {
501             case 'l':
502               if (optarg[1] == 'n')
503                 lineno_format = FORMAT_LEFT;
504               else
505                 usage (2);
506               break;
507             case 'r':
508               switch (optarg[1])
509                 {
510                 case 'n':
511                   lineno_format = FORMAT_RIGHT_NOLZ;
512                   break;
513                 case 'z':
514                   lineno_format = FORMAT_RIGHT_LZ;
515                   break;
516                 default:
517                   usage (2);
518                   break;
519                 }
520               break;
521             default:
522               usage (2);
523               break;
524             }
525           break;
526         case 'd':
527           section_del = optarg;
528           break;
529         default:
530           usage (2);
531           break;
532         }
533     }
534
535   if (show_version)
536     {
537       printf ("nl - %s\n", version_string);
538       exit (0);
539     }
540
541   if (show_help)
542     usage (0);
543
544   /* Initialize the section delimiters.  */
545   c = strlen (section_del);
546
547   header_del_len = c * 3;
548   header_del = xmalloc (header_del_len + 1);
549   strcat (strcat (strcpy (header_del, section_del), section_del), section_del);
550
551   body_del_len = c * 2;
552   body_del = xmalloc (body_del_len + 1);
553   strcat (strcpy (body_del, section_del), section_del);
554
555   footer_del_len = c;
556   footer_del = xmalloc (footer_del_len + 1);
557   strcpy (footer_del, section_del);
558
559   /* Initialize the input buffer.  */
560   initbuffer (&line_buf);
561
562   /* Initialize the printf format for unnumbered lines. */
563   c = strlen (separator_str);
564   print_no_line_fmt = xmalloc (lineno_width + c + 1);
565   memset (print_no_line_fmt, ' ', lineno_width + c);
566   print_no_line_fmt[lineno_width + c] = '\0';
567
568   line_no = page_start;
569   current_type = body_type;
570   current_regex = &body_regex;
571   build_print_fmt ();
572
573   /* Main processing. */
574
575   if (optind == argc)
576     exit_status |= nl_file ("-");
577   else
578     for (; optind < argc; optind++)
579       exit_status |= nl_file (argv[optind]);
580
581   if (have_read_stdin && fclose (stdin) == EOF)
582     {
583       error (0, errno, "-");
584       exit_status = 1;
585     }
586   if (ferror (stdout) || fclose (stdout) == EOF)
587     error (1, errno, _("write error"));
588
589   exit (exit_status);
590 }