.
[coreutils.git] / src / nl.c
blobc596ce7d1f814c1748e9e013d194323adb99b601
1 /* nl -- number lines of files
2 Copyright (C) 1989, 1992, 1995 Free Software Foundation, Inc.
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.
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.
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. */
18 /* Written by Scott Bartram (nancy!scott@uunet.uu.net)
19 Revised by David MacKenzie (djm@gnu.ai.mit.edu) */
21 #include <config.h>
23 #include <stdio.h>
24 #include <sys/types.h>
25 #include <getopt.h>
26 #include <regex.h>
27 #include "linebuffer.h"
28 #include "system.h"
29 #include "version.h"
30 #include "error.h"
32 #ifndef TRUE
33 #define TRUE 1
34 #define FALSE 0
35 #endif
37 /* Line-number formats. */
38 enum number_format
40 FORMAT_RIGHT_NOLZ, /* Right justified, no leading zeroes. */
41 FORMAT_RIGHT_LZ, /* Right justified, leading zeroes. */
42 FORMAT_LEFT /* Left justified, no leading zeroes. */
45 /* Default section delimiter characters. */
46 #define DEFAULT_SECTION_DELIMITERS "\\:"
48 /* Types of input lines: either one of the section delimiters,
49 or text to output. */
50 enum section
52 Header, Body, Footer, Text
55 char *xmalloc ();
56 char *xrealloc ();
58 /* The name this program was run with. */
59 char *program_name;
61 /* Format of body lines (-b). */
62 static char *body_type = "t";
64 /* Format of header lines (-h). */
65 static char *header_type = "n";
67 /* Format of footer lines (-f). */
68 static char *footer_type = "n";
70 /* Format currently being used (body, header, or footer). */
71 static char *current_type;
73 /* Regex for body lines to number (-bp). */
74 static struct re_pattern_buffer body_regex;
76 /* Regex for header lines to number (-hp). */
77 static struct re_pattern_buffer header_regex;
79 /* Regex for footer lines to number (-fp). */
80 static struct re_pattern_buffer footer_regex;
82 /* Pointer to current regex, if any. */
83 static struct re_pattern_buffer *current_regex = NULL;
85 /* Separator string to print after line number (-s). */
86 static char *separator_str = "\t";
88 /* Input section delimiter string (-d). */
89 static char *section_del = DEFAULT_SECTION_DELIMITERS;
91 /* Header delimiter string. */
92 static char *header_del = NULL;
94 /* Header section delimiter length. */
95 static int header_del_len;
97 /* Body delimiter string. */
98 static char *body_del = NULL;
100 /* Body section delimiter length. */
101 static int body_del_len;
103 /* Footer delimiter string. */
104 static char *footer_del = NULL;
106 /* Footer section delimiter length. */
107 static int footer_del_len;
109 /* Input buffer. */
110 static struct linebuffer line_buf;
112 /* printf format string for line number. */
113 static char *print_fmt;
115 /* printf format string for unnumbered lines. */
116 static char *print_no_line_fmt = NULL;
118 /* Starting line number on each page (-v). */
119 static int page_start = 1;
121 /* Line number increment (-i). */
122 static int page_incr = 1;
124 /* If TRUE, reset line number at start of each page (-p). */
125 static int reset_numbers = TRUE;
127 /* Number of blank lines to consider to be one line for numbering (-l). */
128 static int blank_join = 1;
130 /* Width of line numbers (-w). */
131 static int lineno_width = 6;
133 /* Line number format (-n). */
134 static enum number_format lineno_format = FORMAT_RIGHT_NOLZ;
136 /* Current print line number. */
137 static int line_no;
139 /* Nonzero if we have ever read standard input. */
140 static int have_read_stdin;
142 /* If nonzero, display usage information and exit. */
143 static int show_help;
145 /* If nonzero, print the version on standard output then exit. */
146 static int show_version;
148 static struct option const longopts[] =
150 {"header-numbering", required_argument, NULL, 'h'},
151 {"body-numbering", required_argument, NULL, 'b'},
152 {"footer-numbering", required_argument, NULL, 'f'},
153 {"first-page", 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 {"help", no_argument, &show_help, 1},
162 {"version", no_argument, &show_version, 1},
163 {NULL, 0, NULL, 0}
166 /* Print a usage message and quit. */
168 static void
169 usage (int status)
171 if (status != 0)
172 fprintf (stderr, _("Try `%s --help' for more information.\n"),
173 program_name);
174 else
176 printf (_("\
177 Usage: %s [OPTION]... [FILE]...\n\
179 program_name);
180 printf (_("\
181 Write each FILE to standard output, with line numbers added.\n\
182 With no FILE, or when FILE is -, read standard input.\n\
184 -b, --body-numbering=STYLE use STYLE for numbering body lines\n\
185 -d, --section-delimiter=CC use CC for separating logical pages\n\
186 -f, --footer-numbering=STYLE use STYLE for numbering footer lines\n\
187 -h, --header-numbering=STYLE use STYLE for numbering header lines\n\
188 -i, --page-increment=NUMBER line number increment at each line\n\
189 -l, --join-blank-lines=NUMBER group of NUMBER empty lines counted as one\n\
190 -n, --number-format=FORMAT insert line numbers according to FORMAT\n\
191 -p, --no-renumber do not reset line numbers at logical pages\n\
192 -s, --number-separator=STRING add STRING after (possible) line number\n\
193 -v, --first-page=NUMBER first line number on each logical page\n\
194 -w, --number-width=NUMBER use NUMBER columns for line numbers\n\
195 --help display this help and exit\n\
196 --version output version information and exit\n\
198 By default, selects -v1 -i1 -l1 -sTAB -w6 -nrn -hn -bt -fn. CC are\n\
199 two delimiter characters for separating logical pages, a missing\n\
200 second character implies :. Type \\\\ for \\. STYLE is one of:\n\
202 a number all lines\n\
203 t number only nonempty lines\n\
204 n number no lines\n\
205 pREGEXP number only lines that contain a match for REGEXP\n\
207 FORMAT is one of:\n\
209 ln left justified, no leading zeros\n\
210 rn right justified, no leading zeros\n\
211 rz right justified, leading zeros\n\
213 "));
215 exit (status);
218 /* Build the printf format string, based on `lineno_format'. */
220 static void
221 build_print_fmt (void)
223 /* 12 = 10 chars for lineno_width, 1 for %, 1 for \0. */
224 print_fmt = xmalloc (strlen (separator_str) + 12);
225 switch (lineno_format)
227 case FORMAT_RIGHT_NOLZ:
228 sprintf (print_fmt, "%%%dd%s", lineno_width, separator_str);
229 break;
230 case FORMAT_RIGHT_LZ:
231 sprintf (print_fmt, "%%0%dd%s", lineno_width, separator_str);
232 break;
233 case FORMAT_LEFT:
234 sprintf (print_fmt, "%%-%dd%s", lineno_width, separator_str);
235 break;
239 /* Set the command line flag TYPEP and possibly the regex pointer REGEXP,
240 according to `optarg'. */
242 static int
243 build_type_arg (char **typep, struct re_pattern_buffer *regexp)
245 const char *errmsg;
246 int rval = TRUE;
247 int optlen;
249 switch (*optarg)
251 case 'a':
252 case 't':
253 case 'n':
254 *typep = optarg;
255 break;
256 case 'p':
257 *typep = optarg++;
258 optlen = strlen (optarg);
259 regexp->allocated = optlen * 2;
260 regexp->buffer = (unsigned char *) xmalloc (regexp->allocated);
261 regexp->translate = NULL;
262 regexp->fastmap = xmalloc (256);
263 regexp->fastmap_accurate = 0;
264 errmsg = re_compile_pattern (optarg, optlen, regexp);
265 if (errmsg)
266 error (1, 0, "%s", errmsg);
267 break;
268 default:
269 rval = FALSE;
270 break;
272 return rval;
275 /* Print and increment the line number. */
277 static void
278 print_lineno (void)
280 printf (print_fmt, line_no);
281 line_no += page_incr;
284 /* Switch to a header section. */
286 static void
287 proc_header (void)
289 current_type = header_type;
290 current_regex = &header_regex;
291 if (reset_numbers)
292 line_no = page_start;
293 putchar ('\n');
296 /* Switch to a body section. */
298 static void
299 proc_body (void)
301 current_type = body_type;
302 current_regex = &body_regex;
303 putchar ('\n');
306 /* Switch to a footer section. */
308 static void
309 proc_footer (void)
311 current_type = footer_type;
312 current_regex = &footer_regex;
313 putchar ('\n');
316 /* Process a regular text line in `line_buf'. */
318 static void
319 proc_text (void)
321 static int blank_lines = 0; /* Consecutive blank lines so far. */
323 switch (*current_type)
325 case 'a':
326 if (blank_join > 1)
328 if (line_buf.length || ++blank_lines == blank_join)
330 print_lineno ();
331 blank_lines = 0;
333 else
334 printf (print_no_line_fmt);
336 else
337 print_lineno ();
338 break;
339 case 't':
340 if (line_buf.length)
341 print_lineno ();
342 else
343 printf (print_no_line_fmt);
344 break;
345 case 'n':
346 printf (print_no_line_fmt);
347 break;
348 case 'p':
349 if (re_search (current_regex, line_buf.buffer, line_buf.length,
350 0, line_buf.length, (struct re_registers *) 0) < 0)
351 printf (print_no_line_fmt);
352 else
353 print_lineno ();
354 break;
356 fwrite (line_buf.buffer, sizeof (char), line_buf.length, stdout);
357 putchar ('\n');
360 /* Return the type of line in `line_buf'. */
362 static enum section
363 check_section (void)
365 if (line_buf.length < 2 || memcmp (line_buf.buffer, section_del, 2))
366 return Text;
367 if (line_buf.length == header_del_len
368 && !memcmp (line_buf.buffer, header_del, header_del_len))
369 return Header;
370 if (line_buf.length == body_del_len
371 && !memcmp (line_buf.buffer, body_del, body_del_len))
372 return Body;
373 if (line_buf.length == footer_del_len
374 && !memcmp (line_buf.buffer, footer_del, footer_del_len))
375 return Footer;
376 return Text;
379 /* Read and process the file pointed to by FP. */
381 static void
382 process_file (FILE *fp)
384 while (readline (&line_buf, fp))
386 switch ((int) check_section ())
388 case Header:
389 proc_header ();
390 break;
391 case Body:
392 proc_body ();
393 break;
394 case Footer:
395 proc_footer ();
396 break;
397 case Text:
398 proc_text ();
399 break;
404 /* Process file FILE to standard output.
405 Return 0 if successful, 1 if not. */
407 static int
408 nl_file (const char *file)
410 FILE *stream;
412 if (!strcmp (file, "-"))
414 have_read_stdin = 1;
415 stream = stdin;
417 else
419 stream = fopen (file, "r");
420 if (stream == NULL)
422 error (0, errno, "%s", file);
423 return 1;
427 process_file (stream);
429 if (ferror (stream))
431 error (0, errno, "%s", file);
432 return 1;
434 if (!strcmp (file, "-"))
435 clearerr (stream); /* Also clear EOF. */
436 else if (fclose (stream) == EOF)
438 error (0, errno, "%s", file);
439 return 1;
441 return 0;
444 void
445 main (int argc, char **argv)
447 int c, exit_status = 0;
449 program_name = argv[0];
450 have_read_stdin = 0;
452 while ((c = getopt_long (argc, argv, "h:b:f:v:i:pl:s:w:n:d:", longopts,
453 (int *) 0)) != EOF)
455 switch (c)
457 case 0:
458 break;
460 case 'h':
461 if (build_type_arg (&header_type, &header_regex) != TRUE)
462 usage (2);
463 break;
464 case 'b':
465 if (build_type_arg (&body_type, &body_regex) != TRUE)
466 usage (2);
467 break;
468 case 'f':
469 if (build_type_arg (&footer_type, &footer_regex) != TRUE)
470 usage (2);
471 break;
472 case 'v':
473 page_start = atoi (optarg);
474 break;
475 case 'i':
476 page_incr = atoi (optarg);
477 if (page_incr < 1)
478 page_incr = 1;
479 break;
480 case 'p':
481 reset_numbers = FALSE;
482 break;
483 case 'l':
484 blank_join = atoi (optarg);
485 break;
486 case 's':
487 separator_str = optarg;
488 break;
489 case 'w':
490 lineno_width = atoi (optarg);
491 if (lineno_width < 1)
492 lineno_width = 1;
493 break;
494 case 'n':
495 switch (*optarg)
497 case 'l':
498 if (optarg[1] == 'n')
499 lineno_format = FORMAT_LEFT;
500 else
501 usage (2);
502 break;
503 case 'r':
504 switch (optarg[1])
506 case 'n':
507 lineno_format = FORMAT_RIGHT_NOLZ;
508 break;
509 case 'z':
510 lineno_format = FORMAT_RIGHT_LZ;
511 break;
512 default:
513 usage (2);
514 break;
516 break;
517 default:
518 usage (2);
519 break;
521 break;
522 case 'd':
523 section_del = optarg;
524 break;
525 default:
526 usage (2);
527 break;
531 if (show_version)
533 printf ("nl - %s\n", version_string);
534 exit (0);
537 if (show_help)
538 usage (0);
540 /* Initialize the section delimiters. */
541 c = strlen (section_del);
543 header_del_len = c * 3;
544 header_del = xmalloc (header_del_len + 1);
545 strcat (strcat (strcpy (header_del, section_del), section_del), section_del);
547 body_del_len = c * 2;
548 body_del = xmalloc (body_del_len + 1);
549 strcat (strcpy (body_del, section_del), section_del);
551 footer_del_len = c;
552 footer_del = xmalloc (footer_del_len + 1);
553 strcpy (footer_del, section_del);
555 /* Initialize the input buffer. */
556 initbuffer (&line_buf);
558 /* Initialize the printf format for unnumbered lines. */
559 c = strlen (separator_str);
560 print_no_line_fmt = xmalloc (lineno_width + c + 1);
561 memset (print_no_line_fmt, ' ', lineno_width + c);
562 print_no_line_fmt[lineno_width + c] = '\0';
564 line_no = page_start;
565 current_type = body_type;
566 current_regex = &body_regex;
567 build_print_fmt ();
569 /* Main processing. */
571 if (optind == argc)
572 exit_status |= nl_file ("-");
573 else
574 for (; optind < argc; optind++)
575 exit_status |= nl_file (argv[optind]);
577 if (have_read_stdin && fclose (stdin) == EOF)
579 error (0, errno, "-");
580 exit_status = 1;
582 if (ferror (stdout) || fclose (stdout) == EOF)
583 error (1, errno, _("write error"));
585 exit (exit_status);