dd: clarify meaning of multiplication factors; put xM in order
[platform/upstream/coreutils.git] / src / pr.c
1 /* pr -- convert text files for printing.
2    Copyright (C) 88, 91, 1995-2008 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 3 of the License, or
7    (at your option) 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, see <http://www.gnu.org/licenses/>.  */
16
17 /*  By Pete TerMaat, with considerable refinement by Roland Huebner.  */
18 \f
19 /* Things to watch: Sys V screws up on ...
20    pr -n -3 -s: /usr/dict/words
21    pr -m -o10 -n /usr/dict/words{,,,}
22    pr -6 -a -n -o5 /usr/dict/words
23
24    Ideas:
25
26    Keep a things_to_do list of functions to call when we know we have
27    something to print.  Cleaner than current series of checks.
28
29    Improve the printing of control prefixes.
30
31    Expand the file name in the centered header line to a full file name.
32
33
34    Concept:
35
36    If the input_tab_char differs from the default value TAB
37    (`-e[CHAR[...]]' is used), any input text tab is expanded to the
38    default width of 8 spaces (compare char_to_clump). - Same as SunOS
39    does.
40
41    The treatment of the number_separator (compare add_line_number):
42    The default value TAB of the number_separator (`-n[SEP[...]]') doesn't
43    be thought to be an input character. An optional `-e'-input has no
44    effect.
45    -  With single column output
46       only one POSIX requirement has to be met:
47    The default n-separator should be a TAB. The consequence is a
48    different width between the number and the text if the output position
49    of the separator changes, i.e. it depends upon the left margin used.
50    That's not nice but easy-to-use together with the defaults of other
51    utilities, e.g. sort or cut. - Same as SunOS does.
52    -  With multicolumn output
53       two conflicting POSIX requirements exist:
54    First `default n-separator is TAB', second `output text columns shall
55    be of equal width'. Moreover POSIX specifies the number+separator a
56    part of the column, together with `-COLUMN' and `-a -COLUMN'.
57    (With -m output the number shall occupy each line only once. Exactly
58    the same situation as single column output exists.)
59       GNU pr gives priority to the 2nd requirement and observes POSIX
60    column definition. The n-separator TAB is expanded to the same number
61    of spaces in each column using the default value 8. Tabification is
62    only performed if it is compatible with the output position.
63    Consequence: The output text columns are of equal width. The layout
64    of a page does not change if the left margin varies. - Looks better
65    than the SunOS approach.
66       SunOS pr gives priority to the 1st requirement. n-separator TAB
67    width varies with each column. Only the width of text part of the
68    column is fixed.
69    Consequence: The output text columns don't have equal width. The
70    widths and the layout of the whole page varies with the left margin.
71    An overflow of the line length (without margin) over the input value
72    PAGE_WIDTH may occur.
73
74    The interference of the POSIX-compliant small letter options -w and -s:
75    (`interference' means `setting a _separator_ with -s switches off the
76    column sturctur and the default - not generally - page_width,
77    acts on -w option')
78        options:       text form  / separator:     equivalent new options:
79        -w l   -s[x]
80     --------------------------------------------------------------------
81     1.  --     --     columns    / space          --
82                       trunc. to page_width = 72
83     2.  --    -s[:]   full lines / TAB[:]         -J  --sep-string[="<TAB>"|:]
84                       no truncation
85     3.  -w l   --     columns    / space          -W l
86                       trunc. to page_width = l
87     4.  -w l  -s[:]   columns    / no sep.[:]     -W l  --sep-string[=:]
88                       trunc. to page_width = l
89     --------------------------------------------------------------------
90
91
92    Options:
93
94    Including version 1.22i:
95    Some SMALL LETTER options has been redefined with the object of a
96    better POSIX compliance. The output of some further cases has been
97    adapted to other UNIXes. A violation of downward compatibility has to
98    be accepted.
99    Some NEW CAPITAL LETTER options ( -J, -S, -W) has been introduced to
100    turn off unexpected interferences of small letter options (-s and -w
101    together with the three column options).
102    -N option and the second argument LAST_PAGE of +FIRST_PAGE offer more
103    flexibility; The detailed handling of form feeds set in the input
104    files requires -T option.
105
106    Capital letter options dominate small letter ones.
107
108    Some of the option-arguments cannot be specified as separate arguments
109    from the preceding option letter (already stated in POSIX specification).
110
111    Form feeds in the input cause page breaks in the output. Multiple
112    form feeds produce empty pages.
113
114    +FIRST_PAGE[:LAST_PAGE], --pages=FIRST_PAGE[:LAST_PAGE]
115                 begin [stop] printing with page FIRST_[LAST_]PAGE
116
117    -COLUMN, --columns=COLUMN
118                 Produce output that is COLUMN columns wide and
119                 print columns down, unless -a is used. Balance number of
120                 lines in the columns on each page.
121
122    -a, --across         Print columns across rather than down, used
123                 together with -COLUMN. The input
124                 one
125                 two
126                 three
127                 four
128                 will be printed with `-a -3' as
129                 one     two     three
130                 four
131
132    -b           Balance columns on the last page.
133                 -b is no longer an independent option. It's always used
134                 together with -COLUMN (unless -a is used) to get a
135                 consistent formulation with "FF set by hand" in input
136                 files. Each formfeed found terminates the number of lines
137                 to be read with the actual page. The situation for
138                 printing columns down is equivalent to that on the last
139                 page. So we need a balancing.
140
141                 Keeping -b as an underground option guarantees some
142                 downward compatibility. Utilities using pr with -b
143                 (a most frequently used form) still work as usual.
144
145    -c, --show-control-chars
146                 Print unprintable characters as control prefixes.
147                 Control-g is printed as ^G (use hat notation) and
148                 octal backslash notation.
149
150    -d, --double-space   Double space the output.
151
152    -D FORMAT, --date-format=FORMAT  Use FORMAT for the header date.
153
154    -e[CHAR[WIDTH]], --expand-tabs[=CHAR[WIDTH]]
155                 Expand tabs to spaces on input.  Optional argument CHAR
156                 is the input TAB character. (Default is TAB).  Optional
157                 argument WIDTH is the input TAB character's width.
158                 (Default is 8.)
159
160    -F, -f, --form-feed  Use formfeeds instead of newlines to separate
161                 pages. A three line HEADER is used, no TRAILER with -F,
162                 without -F both HEADER and TRAILER are made of five lines.
163
164    -h HEADER, --header=HEADER
165                 Replace the filename in the header with the string HEADER.
166                 A centered header is used.
167
168    -i[CHAR[WIDTH]], --output-tabs[=CHAR[WIDTH]]
169                 Replace spaces with tabs on output.  Optional argument
170                 CHAR is the output TAB character. (Default is TAB).
171                 Optional argument WIDTH is the output TAB character's
172                 width. (Default is 8)
173
174    -J, --join-lines     Merge lines of full length, turns off -W/-w
175                 line truncation, no column alignment, --sep-string[=STRING]
176                 sets separators, works with all column options
177                 (-COLUMN | -a -COLUMN | -m).
178                 -J has been introduced (together with -W and --sep-string) to
179                 disentangle the old (POSIX compliant) options -w, -s
180                 along with the 3 column options.
181
182    -l PAGE_LENGTH, --length=PAGE_LENGTH
183                 Set the page length to PAGE_LENGTH lines. Default is 66,
184                 including 5 lines of HEADER and 5 lines of TRAILER
185                 without -F, but only 3 lines of HEADER and no TRAILER
186                 with -F (i.e the number of text lines defaults to 56 or
187                 63 respectively).
188
189    -m, --merge          Print files in parallel; pad_across_to align
190                 columns; truncate lines and print separator strings;
191                 Do it also with empty columns to get a continuous line
192                 numbering and column marking by separators throughout
193                 the whole merged file.
194
195                 Empty pages in some input files produce empty columns
196                 [marked by separators] in the merged pages. Completely
197                 empty merged pages show no column separators at all.
198
199                 The layout of a merged page is ruled by the largest form
200                 feed distance of the single pages at that page. Shorter
201                 columns will be filled up with empty lines.
202
203                 Together with -J option join lines of full length and
204                 set separators when -S option is used.
205
206    -n[SEP[DIGITS]], --number-lines[=SEP[DIGITS]]
207                 Provide DIGITS digit line numbering (default for DIGITS
208                 is 5). With multicolumn output the number occupies the
209                 first DIGITS column positions of each text column or only
210                 each line of -m output.
211                 With single column output the number precedes each line
212                 just as -m output.
213                 Optional argument SEP is the character appended to the
214                 line number to separate it from the text followed.
215                 The default separator is a TAB. In a strict sense a TAB
216                 is always printed with single column output only. The
217                 TAB-width varies with the TAB-position, e.g. with the
218                 left margin specified by -o option.
219                 With multicolumn output priority is given to `equal width
220                 of output columns' (a POSIX specification). The TAB-width
221                 is fixed to the value of the 1st column and does not
222                 change with different values of left margin. That means a
223                 fixed number of spaces is always printed in the place of
224                 a TAB. The tabification depends upon the output
225                 position.
226
227                 Default counting of the line numbers starts with 1st
228                 line of the input file (not the 1st line printed,
229                 compare the --page option and -N option).
230
231    -N NUMBER, --first-line-number=NUMBER
232                 Start line counting with the number NUMBER at the 1st
233                 line of first page printed (mostly not the 1st line of
234                 the input file).
235
236    -o MARGIN, --indent=MARGIN
237                 Offset each line with a margin MARGIN spaces wide.
238                 Total page width is the size of the margin plus the
239                 PAGE_WIDTH set with -W/-w option.
240
241    -r, --no-file-warnings
242                 Omit warning when a file cannot be opened.
243
244    -s[CHAR], --separator[=CHAR]
245                 Separate columns by a single character CHAR, default for
246                 CHAR is the TAB character without -w and 'no char' with -w.
247                 Without `-s' default separator `space' is set.
248                 -s[CHAR] turns off line truncation of all 3 column options
249                 (-COLUMN|-a -COLUMN|-m) except -w is set. That is a POSIX
250                 compliant formulation. The source code translates -s into
251                 the new options -S and -J, also -W if required.
252
253    -S STRING, --sep-string[=STRING]
254                 Separate columns by any string STRING. The -S option
255                 doesn't react upon the -W/-w option (unlike -s option
256                 does). It defines a separator nothing else.
257                 Without -S: Default separator TAB is used with -J and
258                 `space' otherwise (same as -S" ").
259                 With -S "": No separator is used.
260                 Quotes should be used with blanks and some shell active
261                 characters.
262                 -S is problematic because in its obsolete form you
263                 cannot use -S "STRING", but in its standard form you
264                 must use -S "STRING" if STRING is empty.  Use
265                 --sep-string to avoid the ambiguity.
266
267    -t, --omit-header    Do not print headers or footers but retain form
268                 feeds set in the input files.
269
270    -T, --omit-pagination
271                 Do not print headers or footers, eliminate any pagination
272                 by form feeds set in the input files.
273
274    -v, --show-nonprinting
275                 Print unprintable characters as escape sequences. Use
276                 octal backslash notation. Control-G becomes \007.
277
278    -w PAGE_WIDTH, --width=PAGE_WIDTH
279                 Set page width to PAGE_WIDTH characters for multiple
280                 text-column output only (default for PAGE_WIDTH is 72).
281                 -s[CHAR] turns off the default page width and any line
282                 truncation. Lines of full length will be merged,
283                 regardless of the column options set. A POSIX compliant
284                 formulation.
285
286    -W PAGE_WIDTH, --page-width=PAGE_WIDTH
287                 Set the page width to PAGE_WIDTH characters. That's valid
288                 with and without a column option. Text lines will be
289                 truncated, unless -J is used. Together with one of the
290                 column options (-COLUMN| -a -COLUMN| -m) column alignment
291                 is always used.
292                 Default is 72 characters.
293                 Without -W PAGE_WIDTH
294                 - but with one of the column options default truncation of
295                   72 characters is used (to keep downward compatibility
296                   and to simplify most frequently met column tasks).
297                   Column alignment and column separators are used.
298                 - and without any of the column options NO line truncation
299                   is used (to keep downward compatibility and to meet most
300                   frequent tasks). That's equivalent to  -W 72 -J .
301
302                 With/without  -W PAGE_WIDTH  the header line is always
303                 truncated to avoid line overflow.
304
305                 (In pr versions newer than 1.14 -S option does no longer
306                 affect -W option.)
307
308 */
309 \f
310
311 #include <config.h>
312
313 #include <getopt.h>
314 #include <sys/types.h>
315 #include "system.h"
316 #include "error.h"
317 #include "hard-locale.h"
318 #include "mbswidth.h"
319 #include "quote.h"
320 #include "stat-time.h"
321 #include "stdio--.h"
322 #include "strftime.h"
323 #include "xstrtol.h"
324
325 /* The official name of this program (e.g., no `g' prefix).  */
326 #define PROGRAM_NAME "pr"
327
328 #define AUTHORS \
329   proper_name ("Pete TerMaat"), \
330   proper_name ("Roland Huebner")
331
332 /* Used with start_position in the struct COLUMN described below.
333    If start_position == ANYWHERE, we aren't truncating columns and
334    can begin printing a column anywhere.  Otherwise we must pad to
335    the horizontal position start_position. */
336 #define ANYWHERE        0
337
338 /* Each column has one of these structures allocated for it.
339    If we're only dealing with one file, fp is the same for all
340    columns.
341
342    The general strategy is to spend time setting up these column
343    structures (storing columns if necessary), after which printing
344    is a matter of flitting from column to column and calling
345    print_func.
346
347    Parallel files, single files printing across in multiple
348    columns, and single files printing down in multiple columns all
349    fit the same printing loop.
350
351    print_func           Function used to print lines in this column.
352                         If we're storing this column it will be
353                         print_stored(), Otherwise it will be read_line().
354
355    char_func            Function used to process characters in this column.
356                         If we're storing this column it will be store_char(),
357                         otherwise it will be print_char().
358
359    current_line         Index of the current entry in line_vector, which
360                         contains the index of the first character of the
361                         current line in buff[].
362
363    lines_stored         Number of lines in this column which are stored in
364                         buff.
365
366    lines_to_print       If we're storing this column, lines_to_print is
367                         the number of stored_lines which remain to be
368                         printed.  Otherwise it is the number of lines
369                         we can print without exceeding lines_per_body.
370
371    start_position       The horizontal position we want to be in before we
372                         print the first character in this column.
373
374    numbered             True means precede this column with a line number. */
375
376 /* FIXME: There are many unchecked integer overflows in this file,
377    that will cause this command to misbehave given large inputs or
378    options.  Many of the "int" values below should be "size_t" or
379    something else like that.  */
380
381 struct COLUMN;
382 struct COLUMN
383   {
384     FILE *fp;                   /* Input stream for this column. */
385     char const *name;           /* File name. */
386     enum
387       {
388         OPEN,
389         FF_FOUND,               /* used with -b option, set with \f, changed
390                                    to ON_HOLD after print_header */
391         ON_HOLD,                /* Hit a form feed. */
392         CLOSED
393       }
394     status;                     /* Status of the file pointer. */
395
396     /* Func to print lines in this col. */
397     bool (*print_func) (struct COLUMN *);
398
399     /* Func to print/store chars in this col. */
400     void (*char_func) (char);
401
402     int current_line;           /* Index of current place in line_vector. */
403     int lines_stored;           /* Number of lines stored in buff. */
404     int lines_to_print;         /* No. lines stored or space left on page. */
405     int start_position;         /* Horizontal position of first char. */
406     bool numbered;
407     bool full_page_printed;     /* True means printed without a FF found. */
408
409     /* p->full_page_printed  controls a special case of "FF set by hand":
410        True means a full page has been printed without FF found. To avoid an
411        additional empty page we have to ignore a FF immediately following in
412        the next line. */
413   };
414
415 typedef struct COLUMN COLUMN;
416
417 #define NULLCOL (COLUMN *)0
418
419 static int char_to_clump (char c);
420 static bool read_line (COLUMN *p);
421 static bool print_page (void);
422 static bool print_stored (COLUMN *p);
423 static bool open_file (char *name, COLUMN *p);
424 static bool skip_to_page (uintmax_t page);
425 static void print_header (void);
426 static void pad_across_to (int position);
427 static void add_line_number (COLUMN *p);
428 static void getoptarg (char *arg, char switch_char, char *character,
429                        int *number);
430 void usage (int status);
431 static void print_files (int number_of_files, char **av);
432 static void init_parameters (int number_of_files);
433 static void init_header (char const *filename, int desc);
434 static bool init_fps (int number_of_files, char **av);
435 static void init_funcs (void);
436 static void init_store_cols (void);
437 static void store_columns (void);
438 static void balance (int total_stored);
439 static void store_char (char c);
440 static void pad_down (int lines);
441 static void read_rest_of_line (COLUMN *p);
442 static void skip_read (COLUMN *p, int column_number);
443 static void print_char (char c);
444 static void cleanup (void);
445 static void print_sep_string (void);
446 static void separator_string (const char *optarg_S);
447
448 /* All of the columns to print.  */
449 static COLUMN *column_vector;
450
451 /* When printing a single file in multiple downward columns,
452    we store the leftmost columns contiguously in buff.
453    To print a line from buff, get the index of the first character
454    from line_vector[i], and print up to line_vector[i + 1]. */
455 static char *buff;
456
457 /* Index of the position in buff where the next character
458    will be stored. */
459 static int buff_current;
460
461 /* The number of characters in buff.
462    Used for allocation of buff and to detect overflow of buff. */
463 static size_t buff_allocated;
464
465 /* Array of indices into buff.
466    Each entry is an index of the first character of a line.
467    This is used when storing lines to facilitate shuffling when
468    we do column balancing on the last page. */
469 static int *line_vector;
470
471 /* Array of horizonal positions.
472    For each line in line_vector, end_vector[line] is the horizontal
473    position we are in after printing that line.  We keep track of this
474    so that we know how much we need to pad to prepare for the next
475    column. */
476 static int *end_vector;
477
478 /* (-m) True means we're printing multiple files in parallel. */
479 static bool parallel_files = false;
480
481 /* (-m) True means a line starts with some empty columns (some files
482    already CLOSED or ON_HOLD) which we have to align. */
483 static bool align_empty_cols;
484
485 /* (-m) True means we have not yet found any printable column in a line.
486    align_empty_cols = true  has to be maintained. */
487 static bool empty_line;
488
489 /* (-m) False means printable column output precedes a form feed found.
490    Column alignment is done only once. No additional action with that form
491    feed.
492    True means we found only a form feed in a column. Maybe we have to do
493    some column alignment with that form feed. */
494 static bool FF_only;
495
496 /* (-[0-9]+) True means we're given an option explicitly specifying
497    number of columns.  Used to detect when this option is used with -m
498    and when translating old options to new/long options. */
499 static bool explicit_columns = false;
500
501 /* (-t|-T) False means we aren't printing headers and footers. */
502 static bool extremities = true;
503
504 /* (-t) True means we retain all FF set by hand in input files.
505    False is set with -T option. */
506 static bool keep_FF = false;
507 static bool print_a_FF = false;
508
509 /* True means we need to print a header as soon as we know we've got input
510    to print after it. */
511 static bool print_a_header;
512
513 /* (-f) True means use formfeeds instead of newlines to separate pages. */
514 static bool use_form_feed = false;
515
516 /* True means we have read the standard input. */
517 static bool have_read_stdin = false;
518
519 /* True means the -a flag has been given. */
520 static bool print_across_flag = false;
521
522 /* True means we're printing one file in multiple (>1) downward columns. */
523 static bool storing_columns = true;
524
525 /* (-b) True means balance columns on the last page as Sys V does. */
526 /* That's no longer an independent option. With storing_columns = true
527    balance_columns = true is used too (s. function init_parameters).
528    We get a consistent formulation with "FF set by hand" in input files. */
529 static bool balance_columns = false;
530
531 /* (-l) Number of lines on a page, including header and footer lines. */
532 static int lines_per_page = 66;
533
534 /* Number of lines in the header and footer can be reset to 0 using
535    the -t flag. */
536 enum { lines_per_header = 5 };
537 static int lines_per_body;
538 enum { lines_per_footer = 5 };
539
540 /* (-w|-W) Width in characters of the page.  Does not include the width of
541    the margin. */
542 static int chars_per_line = 72;
543
544 /* (-w|W) True means we truncate lines longer than chars_per_column. */
545 static bool truncate_lines = false;
546
547 /* (-J) True means we join lines without any line truncation. -J
548    dominates -w option. */
549 static bool join_lines = false;
550
551 /* Number of characters in a column.  Based on col_sep_length and
552    page width. */
553 static int chars_per_column;
554
555 /* (-e) True means convert tabs to spaces on input. */
556 static bool untabify_input = false;
557
558 /* (-e) The input tab character. */
559 static char input_tab_char = '\t';
560
561 /* (-e) Tabstops are at chars_per_tab, 2*chars_per_tab, 3*chars_per_tab, ...
562    where the leftmost column is 1. */
563 static int chars_per_input_tab = 8;
564
565 /* (-i) True means convert spaces to tabs on output. */
566 static bool tabify_output = false;
567
568 /* (-i) The output tab character. */
569 static char output_tab_char = '\t';
570
571 /* (-i) The width of the output tab. */
572 static int chars_per_output_tab = 8;
573
574 /* Keeps track of pending white space.  When we hit a nonspace
575    character after some whitespace, we print whitespace, tabbing
576    if necessary to get to output_position + spaces_not_printed. */
577 static int spaces_not_printed;
578
579 /* (-o) Number of spaces in the left margin (tabs used when possible). */
580 static int chars_per_margin = 0;
581
582 /* Position where the next character will fall.
583    Leftmost position is 0 + chars_per_margin.
584    Rightmost position is chars_per_margin + chars_per_line - 1.
585    This is important for converting spaces to tabs on output. */
586 static int output_position;
587
588 /* Horizontal position relative to the current file.
589    (output_position depends on where we are on the page;
590    input_position depends on where we are in the file.)
591    Important for converting tabs to spaces on input. */
592 static int input_position;
593
594 /* True if there were any failed opens so we can exit with nonzero
595    status.  */
596 static bool failed_opens = false;
597
598 /* The number of spaces taken up if we print a tab character with width
599    c_ from position h_. */
600 #define TAB_WIDTH(c_, h_) ((c_) - ((h_) % (c_)))
601
602 /* The horizontal position we'll be at after printing a tab character
603    of width c_ from the position h_. */
604 #define POS_AFTER_TAB(c_, h_) ((h_) + TAB_WIDTH (c_, h_))
605
606 /* (-NNN) Number of columns of text to print. */
607 static int columns = 1;
608
609 /* (+NNN:MMM) Page numbers on which to begin and stop printing.
610    first_page_number = 0  will be used to check input only. */
611 static uintmax_t first_page_number = 0;
612 static uintmax_t last_page_number = UINTMAX_MAX;
613
614 /* Number of files open (not closed, not on hold). */
615 static int files_ready_to_read = 0;
616
617 /* Current page number.  Displayed in header. */
618 static uintmax_t page_number;
619
620 /* Current line number.  Displayed when -n flag is specified.
621
622    When printing files in parallel (-m flag), line numbering is as follows:
623    1    foo     goo     moo
624    2    hoo     too     zoo
625
626    When printing files across (-a flag), ...
627    1    foo     2       moo     3       goo
628    4    hoo     5       too     6       zoo
629
630    Otherwise, line numbering is as follows:
631    1    foo     3       goo     5       too
632    2    moo     4       hoo     6       zoo */
633 static int line_number;
634
635 /* With line_number overflow, we use power_10 to cut off the higher-order
636    digits of the line_number */
637 static int power_10;
638
639 /* (-n) True means lines should be preceded by numbers. */
640 static bool numbered_lines = false;
641
642 /* (-n) Character which follows each line number. */
643 static char number_separator = '\t';
644
645 /* (-n) line counting starts with 1st line of input file (not with 1st
646    line of 1st page printed). */
647 static int line_count = 1;
648
649 /* (-n) True means counting of skipped lines starts with 1st line of
650    input file. False means -N option is used in addition, counting of
651    skipped lines not required. */
652 static bool skip_count = true;
653
654 /* (-N) Counting starts with start_line_number = NUMBER at 1st line of
655    first page printed, usually not 1st page of input file. */
656 static int start_line_num = 1;
657
658 /* (-n) Width in characters of a line number. */
659 static int chars_per_number = 5;
660
661 /* Used when widening the first column to accommodate numbers -- only
662    needed when printing files in parallel.  Includes width of both the
663    number and the number_separator. */
664 static int number_width;
665
666 /* Buffer sprintf uses to format a line number. */
667 static char *number_buff;
668
669 /* (-v) True means unprintable characters are printed as escape sequences.
670    control-g becomes \007. */
671 static bool use_esc_sequence = false;
672
673 /* (-c) True means unprintable characters are printed as control prefixes.
674    control-g becomes ^G. */
675 static bool use_cntrl_prefix = false;
676
677 /* (-d) True means output is double spaced. */
678 static bool double_space = false;
679
680 /* Number of files opened initially in init_files.  Should be 1
681    unless we're printing multiple files in parallel. */
682 static int total_files = 0;
683
684 /* (-r) True means don't complain if we can't open a file. */
685 static bool ignore_failed_opens = false;
686
687 /* (-S) True means we separate columns with a specified string.
688    -S option does not affect line truncation nor column alignment. */
689 static bool use_col_separator = false;
690
691 /* String used to separate columns if the -S option has been specified.
692    Default without -S but together with one of the column options
693    -a|COLUMN|-m is a `space' and with the -J option a `tab'. */
694 static char *col_sep_string = "";
695 static int col_sep_length = 0;
696 static char *column_separator = " ";
697 static char *line_separator = "\t";
698
699 /* Number of separator characters waiting to be printed as soon as we
700    know that we have any input remaining to be printed. */
701 static int separators_not_printed;
702
703 /* Position we need to pad to, as soon as we know that we have input
704    remaining to be printed. */
705 static int padding_not_printed;
706
707 /* True means we should pad the end of the page.  Remains false until we
708    know we have a page to print. */
709 static bool pad_vertically;
710
711 /* (-h) String of characters used in place of the filename in the header. */
712 static char *custom_header;
713
714 /* (-D) Date format for the header.  */
715 static char const *date_format;
716
717 /* Date and file name for the header.  */
718 static char *date_text;
719 static char const *file_text;
720
721 /* Output columns available, not counting the date and file name.  */
722 static int header_width_available;
723
724 static char *clump_buff;
725
726 /* True means we read the line no. lines_per_body in skip_read
727    called by skip_to_page. That variable controls the coincidence of a
728    "FF set by hand" and "full_page_printed", see above the definition of
729    structure COLUMN. */
730 static bool last_line = false;
731
732 /* For long options that have no equivalent short option, use a
733    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
734 enum
735 {
736   COLUMNS_OPTION = CHAR_MAX + 1,
737   PAGES_OPTION
738 };
739
740 static char const short_options[] =
741   "-0123456789D:FJN:S::TW:abcde::fh:i::l:mn::o:rs::tvw:";
742
743 static struct option const long_options[] =
744 {
745   {"pages", required_argument, NULL, PAGES_OPTION},
746   {"columns", required_argument, NULL, COLUMNS_OPTION},
747   {"across", no_argument, NULL, 'a'},
748   {"show-control-chars", no_argument, NULL, 'c'},
749   {"double-space", no_argument, NULL, 'd'},
750   {"date-format", required_argument, NULL, 'D'},
751   {"expand-tabs", optional_argument, NULL, 'e'},
752   {"form-feed", no_argument, NULL, 'f'},
753   {"header", required_argument, NULL, 'h'},
754   {"output-tabs", optional_argument, NULL, 'i'},
755   {"join-lines", no_argument, NULL, 'J'},
756   {"length", required_argument, NULL, 'l'},
757   {"merge", no_argument, NULL, 'm'},
758   {"number-lines", optional_argument, NULL, 'n'},
759   {"first-line-number", required_argument, NULL, 'N'},
760   {"indent", required_argument, NULL, 'o'},
761   {"no-file-warnings", no_argument, NULL, 'r'},
762   {"separator", optional_argument, NULL, 's'},
763   {"sep-string", optional_argument, NULL, 'S'},
764   {"omit-header", no_argument, NULL, 't'},
765   {"omit-pagination", no_argument, NULL, 'T'},
766   {"show-nonprinting", no_argument, NULL, 'v'},
767   {"width", required_argument, NULL, 'w'},
768   {"page-width", required_argument, NULL, 'W'},
769   {GETOPT_HELP_OPTION_DECL},
770   {GETOPT_VERSION_OPTION_DECL},
771   {NULL, 0, NULL, 0}
772 };
773
774 /* Return the number of columns that have either an open file or
775    stored lines. */
776
777 static int
778 cols_ready_to_print (void)
779 {
780   COLUMN *q;
781   int i;
782   int n;
783
784   n = 0;
785   for (q = column_vector, i = 0; i < columns; ++q, ++i)
786     if (q->status == OPEN ||
787         q->status == FF_FOUND ||        /* With -b: To print a header only */
788         (storing_columns && q->lines_stored > 0 && q->lines_to_print > 0))
789       ++n;
790   return n;
791 }
792
793 /* Estimate first_ / last_page_number
794    using option +FIRST_PAGE:LAST_PAGE */
795
796 static bool
797 first_last_page (int oi, char c, char const *pages)
798 {
799   char *p;
800   uintmax_t first;
801   uintmax_t last = UINTMAX_MAX;
802   strtol_error err = xstrtoumax (pages, &p, 10, &first, "");
803   if (err != LONGINT_OK && err != LONGINT_INVALID_SUFFIX_CHAR)
804     xstrtol_fatal (err, oi, c, long_options, pages);
805
806   if (p == pages || !first)
807     return false;
808
809   if (*p == ':')
810     {
811       char const *p1 = p + 1;
812       err = xstrtoumax (p1, &p, 10, &last, "");
813       if (err != LONGINT_OK)
814         xstrtol_fatal (err, oi, c, long_options, pages);
815       if (p1 == p || last < first)
816         return false;
817     }
818
819   if (*p)
820     return false;
821
822   first_page_number = first;
823   last_page_number = last;
824   return true;
825 }
826
827 /* Parse column count string S, and if it's valid (1 or larger and
828    within range of the type of `columns') set the global variables
829    columns and explicit_columns and return true.
830    Otherwise, exit with a diagnostic.  */
831 static void
832 parse_column_count (char const *s)
833 {
834   long int tmp_long;
835   if (xstrtol (s, NULL, 10, &tmp_long, "") != LONGINT_OK
836       || !(1 <= tmp_long && tmp_long <= INT_MAX))
837     error (EXIT_FAILURE, 0,
838            _("invalid number of columns: %s"), quote (s));
839
840   columns = tmp_long;
841   explicit_columns = true;
842 }
843
844 /* Estimate length of col_sep_string with option -S.  */
845
846 static void
847 separator_string (const char *optarg_S)
848 {
849   col_sep_length = (int) strlen (optarg_S);
850   col_sep_string = xmalloc (col_sep_length + 1);
851   strcpy (col_sep_string, optarg_S);
852 }
853
854 int
855 main (int argc, char **argv)
856 {
857   int n_files;
858   bool old_options = false;
859   bool old_w = false;
860   bool old_s = false;
861   char **file_names;
862
863   /* Accumulate the digits of old-style options like -99.  */
864   char *column_count_string = NULL;
865   size_t n_digits = 0;
866   size_t n_alloc = 0;
867
868   initialize_main (&argc, &argv);
869   set_program_name (argv[0]);
870   setlocale (LC_ALL, "");
871   bindtextdomain (PACKAGE, LOCALEDIR);
872   textdomain (PACKAGE);
873
874   atexit (close_stdout);
875
876   n_files = 0;
877   file_names = (argc > 1
878                 ? xmalloc ((argc - 1) * sizeof (char *))
879                 : NULL);
880
881   for (;;)
882     {
883       int oi = -1;
884       int c = getopt_long (argc, argv, short_options, long_options, &oi);
885       if (c == -1)
886         break;
887
888       if (ISDIGIT (c))
889         {
890           /* Accumulate column-count digits specified via old-style options. */
891           if (n_digits + 1 >= n_alloc)
892             column_count_string
893               = X2REALLOC (column_count_string, &n_alloc);
894           column_count_string[n_digits++] = c;
895           column_count_string[n_digits] = '\0';
896           continue;
897         }
898
899       n_digits = 0;
900
901       switch (c)
902         {
903         case 1:                 /* Non-option argument. */
904           /* long option --page dominates old `+FIRST_PAGE ...'.  */
905           if (! (first_page_number == 0
906                  && *optarg == '+' && first_last_page (-2, '+', optarg + 1)))
907             file_names[n_files++] = optarg;
908           break;
909
910         case PAGES_OPTION:      /* --pages=FIRST_PAGE[:LAST_PAGE] */
911           {                     /* dominates old opt +... */
912             if (! optarg)
913               error (EXIT_FAILURE, 0,
914                      _("`--pages=FIRST_PAGE[:LAST_PAGE]' missing argument"));
915             else if (! first_last_page (oi, 0, optarg))
916               error (EXIT_FAILURE, 0, _("invalid page range %s"),
917                      quote (optarg));
918             break;
919           }
920
921         case COLUMNS_OPTION:    /* --columns=COLUMN */
922           {
923             parse_column_count (optarg);
924
925             /* If there was a prior column count specified via the
926                short-named option syntax, e.g., -9, ensure that this
927                long-name-specified value overrides it.  */
928             free (column_count_string);
929             column_count_string = NULL;
930             n_alloc = 0;
931             break;
932           }
933
934         case 'a':
935           print_across_flag = true;
936           storing_columns = false;
937           break;
938         case 'b':
939           balance_columns = true;
940           break;
941         case 'c':
942           use_cntrl_prefix = true;
943           break;
944         case 'd':
945           double_space = true;
946           break;
947         case 'D':
948           date_format = optarg;
949           break;
950         case 'e':
951           if (optarg)
952             getoptarg (optarg, 'e', &input_tab_char,
953                        &chars_per_input_tab);
954           /* Could check tab width > 0. */
955           untabify_input = true;
956           break;
957         case 'f':
958         case 'F':
959           use_form_feed = true;
960           break;
961         case 'h':
962           custom_header = optarg;
963           break;
964         case 'i':
965           if (optarg)
966             getoptarg (optarg, 'i', &output_tab_char,
967                        &chars_per_output_tab);
968           /* Could check tab width > 0. */
969           tabify_output = true;
970           break;
971         case 'J':
972           join_lines = true;
973           break;
974         case 'l':
975           {
976             long int tmp_long;
977             if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
978                 || tmp_long <= 0 || tmp_long > INT_MAX)
979               {
980                 error (EXIT_FAILURE, 0,
981                        _("`-l PAGE_LENGTH' invalid number of lines: %s"),
982                        quote (optarg));
983               }
984             lines_per_page = tmp_long;
985             break;
986           }
987         case 'm':
988           parallel_files = true;
989           storing_columns = false;
990           break;
991         case 'n':
992           numbered_lines = true;
993           if (optarg)
994             getoptarg (optarg, 'n', &number_separator,
995                        &chars_per_number);
996           break;
997         case 'N':
998           skip_count = false;
999           {
1000             long int tmp_long;
1001             if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
1002                 || tmp_long > INT_MAX)
1003               {
1004                 error (EXIT_FAILURE, 0,
1005                        _("`-N NUMBER' invalid starting line number: %s"),
1006                        quote (optarg));
1007               }
1008             start_line_num = tmp_long;
1009             break;
1010           }
1011         case 'o':
1012           {
1013             long int tmp_long;
1014             if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
1015                 || tmp_long < 0 || tmp_long > INT_MAX)
1016               error (EXIT_FAILURE, 0,
1017                      _("`-o MARGIN' invalid line offset: %s"), quote (optarg));
1018             chars_per_margin = tmp_long;
1019             break;
1020           }
1021         case 'r':
1022           ignore_failed_opens = true;
1023           break;
1024         case 's':
1025           old_options = true;
1026           old_s = true;
1027           if (!use_col_separator && optarg)
1028             separator_string (optarg);
1029           break;
1030         case 'S':
1031           old_s = false;
1032           /* Reset an additional input of -s, -S dominates -s */
1033           col_sep_string = "";
1034           col_sep_length = 0;
1035           use_col_separator = true;
1036           if (optarg)
1037             separator_string (optarg);
1038           break;
1039         case 't':
1040           extremities = false;
1041           keep_FF = true;
1042           break;
1043         case 'T':
1044           extremities = false;
1045           keep_FF = false;
1046           break;
1047         case 'v':
1048           use_esc_sequence = true;
1049           break;
1050         case 'w':
1051           old_options = true;
1052           old_w = true;
1053           {
1054             long int tmp_long;
1055             if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
1056                 || tmp_long <= 0 || tmp_long > INT_MAX)
1057               error (EXIT_FAILURE, 0,
1058                      _("`-w PAGE_WIDTH' invalid number of characters: %s"),
1059                      quote (optarg));
1060             if (!truncate_lines)
1061               chars_per_line = tmp_long;
1062             break;
1063           }
1064         case 'W':
1065           old_w = false;                        /* dominates -w */
1066           truncate_lines = true;
1067           {
1068             long int tmp_long;
1069             if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
1070                 || tmp_long <= 0 || tmp_long > INT_MAX)
1071               error (EXIT_FAILURE, 0,
1072                      _("`-W PAGE_WIDTH' invalid number of characters: %s"),
1073                      quote (optarg));
1074             chars_per_line = tmp_long;
1075             break;
1076           }
1077         case_GETOPT_HELP_CHAR;
1078         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1079         default:
1080           usage (EXIT_FAILURE);
1081           break;
1082         }
1083     }
1084
1085   if (column_count_string)
1086     {
1087       parse_column_count (column_count_string);
1088       free (column_count_string);
1089     }
1090
1091   if (! date_format)
1092     date_format = (getenv ("POSIXLY_CORRECT") && !hard_locale (LC_TIME)
1093                    ? "%b %e %H:%M %Y"
1094                    : "%Y-%m-%d %H:%M");
1095
1096   /* Now we can set a reasonable initial value: */
1097   if (first_page_number == 0)
1098     first_page_number = 1;
1099
1100   if (parallel_files & explicit_columns)
1101     error (EXIT_FAILURE, 0,
1102          _("cannot specify number of columns when printing in parallel"));
1103
1104   if (parallel_files & print_across_flag)
1105     error (EXIT_FAILURE, 0,
1106        _("cannot specify both printing across and printing in parallel"));
1107
1108 /* Translate some old short options to new/long options.
1109    To meet downward compatibility with other UNIX pr utilities
1110    and some POSIX specifications. */
1111
1112   if (old_options)
1113     {
1114       if (old_w)
1115         {
1116           if (parallel_files | explicit_columns)
1117             {
1118               /* activate -W */
1119               truncate_lines = true;
1120               if (old_s)
1121                 /* adapt HP-UX and SunOS: -s = no separator;
1122                    activate -S */
1123                 use_col_separator = true;
1124             }
1125           else
1126             /* old -w sets width with columns only
1127                activate -J */
1128             join_lines = true;
1129         }
1130       else if (!use_col_separator)
1131         {
1132           /* No -S option read */
1133           if (old_s & (parallel_files | explicit_columns))
1134             {
1135               if (!truncate_lines)
1136                 {
1137                   /* old -s (without -w and -W) annuls column alignment,
1138                   uses fields, activate -J */
1139                   join_lines = true;
1140                   if (col_sep_length > 0)
1141                     /* activate -S */
1142                     use_col_separator = true;
1143                 }
1144               else
1145                 /* with -W */
1146                 /* adapt HP-UX and SunOS: -s = no separator;
1147                    activate -S */
1148                 use_col_separator = true;
1149             }
1150         }
1151     }
1152
1153   for (; optind < argc; optind++)
1154     {
1155       file_names[n_files++] = argv[optind];
1156     }
1157
1158   if (n_files == 0)
1159     {
1160       /* No file arguments specified;  read from standard input.  */
1161       print_files (0, NULL);
1162     }
1163   else
1164     {
1165       if (parallel_files)
1166         print_files (n_files, file_names);
1167       else
1168         {
1169           int i;
1170           for (i = 0; i < n_files; i++)
1171             print_files (1, &file_names[i]);
1172         }
1173     }
1174
1175   cleanup ();
1176
1177   if (have_read_stdin && fclose (stdin) == EOF)
1178     error (EXIT_FAILURE, errno, _("standard input"));
1179   if (failed_opens)
1180     exit (EXIT_FAILURE);
1181   exit (EXIT_SUCCESS);
1182 }
1183
1184 /* Parse options of the form -scNNN.
1185
1186    Example: -nck, where 'n' is the option, c is the optional number
1187    separator, and k is the optional width of the field used when printing
1188    a number. */
1189
1190 static void
1191 getoptarg (char *arg, char switch_char, char *character, int *number)
1192 {
1193   if (!ISDIGIT (*arg))
1194     *character = *arg++;
1195   if (*arg)
1196     {
1197       long int tmp_long;
1198       if (xstrtol (arg, NULL, 10, &tmp_long, "") != LONGINT_OK
1199           || tmp_long <= 0 || tmp_long > INT_MAX)
1200         {
1201           error (0, 0,
1202              _("`-%c' extra characters or invalid number in the argument: %s"),
1203                  switch_char, quote (arg));
1204           usage (EXIT_FAILURE);
1205         }
1206       *number = tmp_long;
1207     }
1208 }
1209 \f
1210 /* Set parameters related to formatting. */
1211
1212 static void
1213 init_parameters (int number_of_files)
1214 {
1215   int chars_used_by_number = 0;
1216
1217   lines_per_body = lines_per_page - lines_per_header - lines_per_footer;
1218   if (lines_per_body <= 0)
1219     {
1220       extremities = false;
1221       keep_FF = true;
1222     }
1223   if (extremities == false)
1224     lines_per_body = lines_per_page;
1225
1226   if (double_space)
1227     lines_per_body = lines_per_body / 2;
1228
1229   /* If input is stdin, cannot print parallel files.  BSD dumps core
1230      on this. */
1231   if (number_of_files == 0)
1232     parallel_files = false;
1233
1234   if (parallel_files)
1235     columns = number_of_files;
1236
1237   /* One file, multi columns down: -b option is set to get a consistent
1238      formulation with "FF set by hand" in input files. */
1239   if (storing_columns)
1240     balance_columns = true;
1241
1242   /* Tabification is assumed for multiple columns. */
1243   if (columns > 1)
1244     {
1245       if (!use_col_separator)
1246         {
1247           /* Use default separator */
1248           if (join_lines)
1249             col_sep_string = line_separator;
1250           else
1251             col_sep_string = column_separator;
1252
1253           col_sep_length = 1;
1254           use_col_separator = true;
1255         }
1256       /* It's rather pointless to define a TAB separator with column
1257          alignment */
1258       else if (!join_lines && *col_sep_string == '\t')
1259         col_sep_string = column_separator;
1260
1261       truncate_lines = true;
1262       tabify_output = true;
1263     }
1264   else
1265     storing_columns = false;
1266
1267   /* -J dominates -w in any case */
1268   if (join_lines)
1269     truncate_lines = false;
1270
1271   if (numbered_lines)
1272     {
1273       int tmp_i;
1274       int chars_per_default_tab = 8;
1275
1276       line_count = start_line_num;
1277
1278       /* To allow input tab-expansion (-e sensitive) use:
1279          if (number_separator == input_tab_char)
1280            number_width = chars_per_number +
1281              TAB_WIDTH (chars_per_input_tab, chars_per_number);   */
1282
1283       /* Estimate chars_per_text without any margin and keep it constant. */
1284       if (number_separator == '\t')
1285         number_width = chars_per_number +
1286           TAB_WIDTH (chars_per_default_tab, chars_per_number);
1287       else
1288         number_width = chars_per_number + 1;
1289
1290       /* The number is part of the column width unless we are
1291          printing files in parallel. */
1292       if (parallel_files)
1293         chars_used_by_number = number_width;
1294
1295       /* We use power_10 to cut off the higher-order digits of the
1296          line_number in function add_line_number */
1297       tmp_i = chars_per_number;
1298       for (power_10 = 1; tmp_i > 0; --tmp_i)
1299         power_10 = 10 * power_10;
1300     }
1301
1302   chars_per_column = (chars_per_line - chars_used_by_number -
1303                      (columns - 1) * col_sep_length) / columns;
1304
1305   if (chars_per_column < 1)
1306     error (EXIT_FAILURE, 0, _("page width too narrow"));
1307
1308   if (numbered_lines)
1309     {
1310       free (number_buff);
1311       number_buff = xmalloc (2 * chars_per_number);
1312     }
1313
1314   /* Pick the maximum between the tab width and the width of an
1315      escape sequence.
1316      The width of an escape sequence (4) isn't the lower limit any longer.
1317      We've to use 8 as the lower limit, if we use chars_per_default_tab = 8
1318      to expand a tab which is not an input_tab-char. */
1319   free (clump_buff);
1320   clump_buff = xmalloc (MAX (8, chars_per_input_tab));
1321 }
1322 \f
1323 /* Open the necessary files,
1324    maintaining a COLUMN structure for each column.
1325
1326    With multiple files, each column p has a different p->fp.
1327    With single files, each column p has the same p->fp.
1328    Return false if (number_of_files > 0) and no files can be opened,
1329    true otherwise.
1330
1331    With each column/file p, p->full_page_printed is initialized,
1332    see also open_file.  */
1333
1334 static bool
1335 init_fps (int number_of_files, char **av)
1336 {
1337   int i, files_left;
1338   COLUMN *p;
1339   FILE *firstfp;
1340   char const *firstname;
1341
1342   total_files = 0;
1343
1344   free (column_vector);
1345   column_vector = xnmalloc (columns, sizeof (COLUMN));
1346
1347   if (parallel_files)
1348     {
1349       files_left = number_of_files;
1350       for (p = column_vector; files_left--; ++p, ++av)
1351         {
1352           if (! open_file (*av, p))
1353             {
1354               --p;
1355               --columns;
1356             }
1357         }
1358       if (columns == 0)
1359         return false;
1360       init_header ("", -1);
1361     }
1362   else
1363     {
1364       p = column_vector;
1365       if (number_of_files > 0)
1366         {
1367           if (! open_file (*av, p))
1368             return false;
1369           init_header (*av, fileno (p->fp));
1370           p->lines_stored = 0;
1371         }
1372       else
1373         {
1374           p->name = _("standard input");
1375           p->fp = stdin;
1376           have_read_stdin = true;
1377           p->status = OPEN;
1378           p->full_page_printed = false;
1379           ++total_files;
1380           init_header ("", -1);
1381           p->lines_stored = 0;
1382         }
1383
1384       firstname = p->name;
1385       firstfp = p->fp;
1386       for (i = columns - 1, ++p; i; --i, ++p)
1387         {
1388           p->name = firstname;
1389           p->fp = firstfp;
1390           p->status = OPEN;
1391           p->full_page_printed = false;
1392           p->lines_stored = 0;
1393         }
1394     }
1395   files_ready_to_read = total_files;
1396   return true;
1397 }
1398 \f
1399 /* Determine print_func and char_func, the functions
1400    used by each column for printing and/or storing.
1401
1402    Determine the horizontal position desired when we begin
1403    printing a column (p->start_position). */
1404
1405 static void
1406 init_funcs (void)
1407 {
1408   int i, h, h_next;
1409   COLUMN *p;
1410
1411   h = chars_per_margin;
1412
1413   if (!truncate_lines)
1414     h_next = ANYWHERE;
1415   else
1416     {
1417       /* When numbering lines of parallel files, we enlarge the
1418          first column to accomodate the number.  Looks better than
1419          the Sys V approach. */
1420       if (parallel_files & numbered_lines)
1421         h_next = h + chars_per_column + number_width;
1422       else
1423         h_next = h + chars_per_column;
1424     }
1425
1426   /* Enlarge p->start_position of first column to use the same form of
1427      padding_not_printed with all columns. */
1428   h = h + col_sep_length;
1429
1430   /* This loop takes care of all but the rightmost column. */
1431
1432   for (p = column_vector, i = 1; i < columns; ++p, ++i)
1433     {
1434       if (storing_columns)      /* One file, multi columns down. */
1435         {
1436           p->char_func = store_char;
1437           p->print_func = print_stored;
1438         }
1439       else
1440         /* One file, multi columns across; or parallel files.  */
1441         {
1442           p->char_func = print_char;
1443           p->print_func = read_line;
1444         }
1445
1446       /* Number only the first column when printing files in
1447          parallel. */
1448       p->numbered = numbered_lines && (!parallel_files || i == 1);
1449       p->start_position = h;
1450
1451       /* If we don't truncate lines, all start_positions are
1452          ANYWHERE, except the first column's start_position when
1453          using a margin. */
1454
1455       if (!truncate_lines)
1456         {
1457           h = ANYWHERE;
1458           h_next = ANYWHERE;
1459         }
1460       else
1461         {
1462           h = h_next + col_sep_length;
1463           h_next = h + chars_per_column;
1464         }
1465     }
1466
1467   /* The rightmost column.
1468
1469      Doesn't need to be stored unless we intend to balance
1470      columns on the last page. */
1471   if (storing_columns & balance_columns)
1472     {
1473       p->char_func = store_char;
1474       p->print_func = print_stored;
1475     }
1476   else
1477     {
1478       p->char_func = print_char;
1479       p->print_func = read_line;
1480     }
1481
1482   p->numbered = numbered_lines && (!parallel_files || i == 1);
1483   p->start_position = h;
1484 }
1485 \f
1486 /* Open a file.  Return true if successful.
1487
1488    With each file p, p->full_page_printed is initialized,
1489    see also init_fps. */
1490
1491 static bool
1492 open_file (char *name, COLUMN *p)
1493 {
1494   if (STREQ (name, "-"))
1495     {
1496       p->name = _("standard input");
1497       p->fp = stdin;
1498       have_read_stdin = true;
1499     }
1500   else
1501     {
1502       p->name = name;
1503       p->fp = fopen (name, "r");
1504     }
1505   if (p->fp == NULL)
1506     {
1507       failed_opens = true;
1508       if (!ignore_failed_opens)
1509         error (0, errno, "%s", name);
1510       return false;
1511     }
1512   p->status = OPEN;
1513   p->full_page_printed = false;
1514   ++total_files;
1515   return true;
1516 }
1517
1518 /* Close the file in P.
1519
1520    If we aren't dealing with multiple files in parallel, we change
1521    the status of all columns in the column list to reflect the close. */
1522
1523 static void
1524 close_file (COLUMN *p)
1525 {
1526   COLUMN *q;
1527   int i;
1528
1529   if (p->status == CLOSED)
1530     return;
1531   if (ferror (p->fp))
1532     error (EXIT_FAILURE, errno, "%s", p->name);
1533   if (fileno (p->fp) != STDIN_FILENO && fclose (p->fp) != 0)
1534     error (EXIT_FAILURE, errno, "%s", p->name);
1535
1536   if (!parallel_files)
1537     {
1538       for (q = column_vector, i = columns; i; ++q, --i)
1539         {
1540           q->status = CLOSED;
1541           if (q->lines_stored == 0)
1542             {
1543               q->lines_to_print = 0;
1544             }
1545         }
1546     }
1547   else
1548     {
1549       p->status = CLOSED;
1550       p->lines_to_print = 0;
1551     }
1552
1553   --files_ready_to_read;
1554 }
1555
1556 /* Put a file on hold until we start a new page,
1557    since we've hit a form feed.
1558
1559    If we aren't dealing with parallel files, we must change the
1560    status of all columns in the column list. */
1561
1562 static void
1563 hold_file (COLUMN *p)
1564 {
1565   COLUMN *q;
1566   int i;
1567
1568   if (!parallel_files)
1569     for (q = column_vector, i = columns; i; ++q, --i)
1570       {
1571         if (storing_columns)
1572           q->status = FF_FOUND;
1573         else
1574           q->status = ON_HOLD;
1575       }
1576   else
1577     p->status = ON_HOLD;
1578
1579   p->lines_to_print = 0;
1580   --files_ready_to_read;
1581 }
1582
1583 /* Undo hold_file -- go through the column list and change any
1584    ON_HOLD columns to OPEN.  Used at the end of each page. */
1585
1586 static void
1587 reset_status (void)
1588 {
1589   int i = columns;
1590   COLUMN *p;
1591
1592   for (p = column_vector; i; --i, ++p)
1593     if (p->status == ON_HOLD)
1594       {
1595         p->status = OPEN;
1596         files_ready_to_read++;
1597       }
1598
1599   if (storing_columns)
1600     {
1601       if (column_vector->status == CLOSED)
1602         /* We use the info to output an error message in  skip_to_page. */
1603         files_ready_to_read = 0;
1604       else
1605         files_ready_to_read = 1;
1606     }
1607 }
1608 \f
1609 /* Print a single file, or multiple files in parallel.
1610
1611    Set up the list of columns, opening the necessary files.
1612    Allocate space for storing columns, if necessary.
1613    Skip to first_page_number, if user has asked to skip leading pages.
1614    Determine which functions are appropriate to store/print lines
1615    in each column.
1616    Print the file(s). */
1617
1618 static void
1619 print_files (int number_of_files, char **av)
1620 {
1621   init_parameters (number_of_files);
1622   if (! init_fps (number_of_files, av))
1623     return;
1624   if (storing_columns)
1625     init_store_cols ();
1626
1627   if (first_page_number > 1)
1628     {
1629       if (!skip_to_page (first_page_number))
1630         return;
1631       else
1632         page_number = first_page_number;
1633     }
1634   else
1635     page_number = 1;
1636
1637   init_funcs ();
1638
1639   line_number = line_count;
1640   while (print_page ())
1641     ;
1642 }
1643 \f
1644 /* Initialize header information.
1645    If DESC is non-negative, it is a file descriptor open to
1646    FILENAME for reading.  */
1647
1648 static void
1649 init_header (char const *filename, int desc)
1650 {
1651   char *buf = NULL;
1652   struct stat st;
1653   struct timespec t;
1654   int ns;
1655   struct tm *tm;
1656
1657   /* If parallel files or standard input, use current date. */
1658   if (STREQ (filename, "-"))
1659     desc = -1;
1660   if (0 <= desc && fstat (desc, &st) == 0)
1661     t = get_stat_mtime (&st);
1662   else
1663     {
1664       static struct timespec timespec;
1665       if (! timespec.tv_sec)
1666         gettime (&timespec);
1667       t = timespec;
1668     }
1669
1670   ns = t.tv_nsec;
1671   tm = localtime (&t.tv_sec);
1672   if (tm == NULL)
1673     {
1674       buf = xmalloc (INT_BUFSIZE_BOUND (long int)
1675                      + MAX (10, INT_BUFSIZE_BOUND (int)));
1676       sprintf (buf, "%ld.%09d", (long int) t.tv_sec, ns);
1677     }
1678   else
1679     {
1680       size_t bufsize = nstrftime (NULL, SIZE_MAX, date_format, tm, 0, ns) + 1;
1681       buf = xmalloc (bufsize);
1682       nstrftime (buf, bufsize, date_format, tm, 0, ns);
1683     }
1684
1685   free (date_text);
1686   date_text = buf;
1687   file_text = custom_header ? custom_header : desc < 0 ? "" : filename;
1688   header_width_available = (chars_per_line
1689                             - mbswidth (date_text, 0)
1690                             - mbswidth (file_text, 0));
1691 }
1692 \f
1693 /* Set things up for printing a page
1694
1695    Scan through the columns ...
1696    Determine which are ready to print
1697    (i.e., which have lines stored or open files)
1698    Set p->lines_to_print appropriately
1699    (to p->lines_stored if we're storing, or lines_per_body
1700    if we're reading straight from the file)
1701    Keep track of this total so we know when to stop printing */
1702
1703 static void
1704 init_page (void)
1705 {
1706   int j;
1707   COLUMN *p;
1708
1709   if (storing_columns)
1710     {
1711       store_columns ();
1712       for (j = columns - 1, p = column_vector; j; --j, ++p)
1713         {
1714           p->lines_to_print = p->lines_stored;
1715         }
1716
1717       /* Last column. */
1718       if (balance_columns)
1719         {
1720           p->lines_to_print = p->lines_stored;
1721         }
1722       /* Since we're not balancing columns, we don't need to store
1723          the rightmost column.   Read it straight from the file. */
1724       else
1725         {
1726           if (p->status == OPEN)
1727             {
1728               p->lines_to_print = lines_per_body;
1729             }
1730           else
1731             p->lines_to_print = 0;
1732         }
1733     }
1734   else
1735     for (j = columns, p = column_vector; j; --j, ++p)
1736       if (p->status == OPEN)
1737         {
1738           p->lines_to_print = lines_per_body;
1739         }
1740       else
1741         p->lines_to_print = 0;
1742 }
1743
1744 /* Align empty columns and print separators.
1745    Empty columns will be formed by files with status ON_HOLD or CLOSED
1746    when printing multiple files in parallel. */
1747
1748 static void
1749 align_column (COLUMN *p)
1750 {
1751   padding_not_printed = p->start_position;
1752   if (padding_not_printed - col_sep_length > 0)
1753     {
1754       pad_across_to (padding_not_printed - col_sep_length);
1755       padding_not_printed = ANYWHERE;
1756     }
1757
1758   if (use_col_separator)
1759     print_sep_string ();
1760
1761   if (p->numbered)
1762     add_line_number (p);
1763 }
1764
1765 /* Print one page.
1766
1767    As long as there are lines left on the page and columns ready to print,
1768    Scan across the column list
1769    if the column has stored lines or the file is open
1770    pad to the appropriate spot
1771    print the column
1772    pad the remainder of the page with \n or \f as requested
1773    reset the status of all files -- any files which where on hold because
1774    of formfeeds are now put back into the lineup. */
1775
1776 static bool
1777 print_page (void)
1778 {
1779   int j;
1780   int lines_left_on_page;
1781   COLUMN *p;
1782
1783   /* Used as an accumulator (with | operator) of successive values of
1784      pad_vertically.  The trick is to set pad_vertically
1785      to false before each run through the inner loop, then after that
1786      loop, it tells us whether a line was actually printed (whether a
1787      newline needs to be output -- or two for double spacing).  But those
1788      values have to be accumulated (in pv) so we can invoke pad_down
1789      properly after the outer loop completes. */
1790   bool pv;
1791
1792   init_page ();
1793
1794   if (cols_ready_to_print () == 0)
1795     return false;
1796
1797   if (extremities)
1798     print_a_header = true;
1799
1800   /* Don't pad unless we know a page was printed. */
1801   pad_vertically = false;
1802   pv = false;
1803
1804   lines_left_on_page = lines_per_body;
1805   if (double_space)
1806     lines_left_on_page *= 2;
1807
1808   while (lines_left_on_page > 0 && cols_ready_to_print () > 0)
1809     {
1810       output_position = 0;
1811       spaces_not_printed = 0;
1812       separators_not_printed = 0;
1813       pad_vertically = false;
1814       align_empty_cols = false;
1815       empty_line = true;
1816
1817       for (j = 1, p = column_vector; j <= columns; ++j, ++p)
1818         {
1819           input_position = 0;
1820           if (p->lines_to_print > 0 || p->status == FF_FOUND)
1821             {
1822               FF_only = false;
1823               padding_not_printed = p->start_position;
1824               if (!(p->print_func) (p))
1825                 read_rest_of_line (p);
1826               pv |= pad_vertically;
1827
1828               --p->lines_to_print;
1829               if (p->lines_to_print <= 0)
1830                 {
1831                   if (cols_ready_to_print () <= 0)
1832                     break;
1833                 }
1834
1835               /* File p changed its status to ON_HOLD or CLOSED */
1836               if (parallel_files && p->status != OPEN)
1837                 {
1838                   if (empty_line)
1839                     align_empty_cols = true;
1840                   else if (p->status == CLOSED ||
1841                            (p->status == ON_HOLD && FF_only))
1842                     align_column (p);
1843                 }
1844             }
1845           else if (parallel_files)
1846             {
1847               /* File status ON_HOLD or CLOSED */
1848               if (empty_line)
1849                 align_empty_cols = true;
1850               else
1851                 align_column (p);
1852             }
1853
1854           /* We need it also with an empty column */
1855           if (use_col_separator)
1856             ++separators_not_printed;
1857         }
1858
1859       if (pad_vertically)
1860         {
1861           putchar ('\n');
1862           --lines_left_on_page;
1863         }
1864
1865       if (cols_ready_to_print () <= 0 && !extremities)
1866         break;
1867
1868       if (double_space & pv)
1869         {
1870           putchar ('\n');
1871           --lines_left_on_page;
1872         }
1873     }
1874
1875   if (lines_left_on_page == 0)
1876     for (j = 1, p = column_vector; j <= columns; ++j, ++p)
1877       if (p->status == OPEN)
1878         p->full_page_printed = true;
1879
1880   pad_vertically = pv;
1881
1882   if (pad_vertically & extremities)
1883     pad_down (lines_left_on_page + lines_per_footer);
1884   else if (keep_FF & print_a_FF)
1885     {
1886       putchar ('\f');
1887       print_a_FF = false;
1888     }
1889
1890   if (last_page_number < page_number)
1891     return false;               /* Stop printing with LAST_PAGE */
1892
1893   reset_status ();              /* Change ON_HOLD to OPEN. */
1894
1895   return true;                  /* More pages to go. */
1896 }
1897 \f
1898 /* Allocate space for storing columns.
1899
1900    This is necessary when printing multiple columns from a single file.
1901    Lines are stored consecutively in buff, separated by '\0'.
1902
1903    The following doesn't apply any longer - any tuning possible?
1904    (We can't use a fixed offset since with the '-s' flag lines aren't
1905    truncated.)
1906
1907    We maintain a list (line_vector) of pointers to the beginnings
1908    of lines in buff.  We allocate one more than the number of lines
1909    because the last entry tells us the index of the last character,
1910    which we need to know in order to print the last line in buff. */
1911
1912 static void
1913 init_store_cols (void)
1914 {
1915   int total_lines = lines_per_body * columns;
1916   int chars_if_truncate = total_lines * (chars_per_column + 1);
1917
1918   free (line_vector);
1919   /* FIXME: here's where it was allocated.  */
1920   line_vector = xmalloc ((total_lines + 1) * sizeof (int *));
1921
1922   free (end_vector);
1923   end_vector = xmalloc (total_lines * sizeof (int *));
1924
1925   free (buff);
1926   buff_allocated = (use_col_separator
1927                     ? 2 * chars_if_truncate
1928                     : chars_if_truncate);       /* Tune this. */
1929   buff = xmalloc (buff_allocated);
1930 }
1931
1932 /* Store all but the rightmost column.
1933    (Used when printing a single file in multiple downward columns)
1934
1935    For each column
1936    set p->current_line to be the index in line_vector of the
1937    first line in the column
1938    For each line in the column
1939    store the line in buff
1940    add to line_vector the index of the line's first char
1941    buff_start is the index in buff of the first character in the
1942    current line. */
1943
1944 static void
1945 store_columns (void)
1946 {
1947   int i, j;
1948   int line = 0;
1949   int buff_start;
1950   int last_col;         /* The rightmost column which will be saved in buff */
1951   COLUMN *p;
1952
1953   buff_current = 0;
1954   buff_start = 0;
1955
1956   if (balance_columns)
1957     last_col = columns;
1958   else
1959     last_col = columns - 1;
1960
1961   for (i = 1, p = column_vector; i <= last_col; ++i, ++p)
1962     p->lines_stored = 0;
1963
1964   for (i = 1, p = column_vector; i <= last_col && files_ready_to_read;
1965        ++i, ++p)
1966     {
1967       p->current_line = line;
1968       for (j = lines_per_body; j && files_ready_to_read; --j)
1969
1970         if (p->status == OPEN)  /* Redundant.  Clean up. */
1971           {
1972             input_position = 0;
1973
1974             if (!read_line (p))
1975               read_rest_of_line (p);
1976
1977             if (p->status == OPEN
1978                 || buff_start != buff_current)
1979               {
1980                 ++p->lines_stored;
1981                 line_vector[line] = buff_start;
1982                 end_vector[line++] = input_position;
1983                 buff_start = buff_current;
1984               }
1985           }
1986     }
1987
1988   /* Keep track of the location of the last char in buff. */
1989   line_vector[line] = buff_start;
1990
1991   if (balance_columns)
1992     balance (line);
1993 }
1994
1995 static void
1996 balance (int total_stored)
1997 {
1998   COLUMN *p;
1999   int i, lines;
2000   int first_line = 0;
2001
2002   for (i = 1, p = column_vector; i <= columns; ++i, ++p)
2003     {
2004       lines = total_stored / columns;
2005       if (i <= total_stored % columns)
2006         ++lines;
2007
2008       p->lines_stored = lines;
2009       p->current_line = first_line;
2010
2011       first_line += lines;
2012     }
2013 }
2014
2015 /* Store a character in the buffer. */
2016
2017 static void
2018 store_char (char c)
2019 {
2020   if (buff_current >= buff_allocated)
2021     {
2022       /* May be too generous. */
2023       buff = X2REALLOC (buff, &buff_allocated);
2024     }
2025   buff[buff_current++] = c;
2026 }
2027
2028 static void
2029 add_line_number (COLUMN *p)
2030 {
2031   int i;
2032   char *s;
2033   int left_cut;
2034
2035   /* Cutting off the higher-order digits is more informative than
2036      lower-order cut off*/
2037   if (line_number < power_10)
2038     sprintf (number_buff, "%*d", chars_per_number, line_number);
2039   else
2040     {
2041       left_cut = line_number % power_10;
2042       sprintf (number_buff, "%0*d", chars_per_number, left_cut);
2043     }
2044   line_number++;
2045   s = number_buff;
2046   for (i = chars_per_number; i > 0; i--)
2047     (p->char_func) (*s++);
2048
2049   if (columns > 1)
2050     {
2051       /* Tabification is assumed for multiple columns, also for n-separators,
2052          but `default n-separator = TAB' hasn't been given priority over
2053          equal column_width also specified by POSIX. */
2054       if (number_separator == '\t')
2055         {
2056           i = number_width - chars_per_number;
2057           while (i-- > 0)
2058             (p->char_func) (' ');
2059         }
2060       else
2061         (p->char_func) (number_separator);
2062     }
2063   else
2064     /* To comply with POSIX, we avoid any expansion of default TAB
2065        separator with a single column output. No column_width requirement
2066        has to be considered. */
2067     {
2068       (p->char_func) (number_separator);
2069       if (number_separator == '\t')
2070         output_position = POS_AFTER_TAB (chars_per_output_tab,
2071                           output_position);
2072     }
2073
2074   if (truncate_lines & !parallel_files)
2075     input_position += number_width;
2076 }
2077 \f
2078 /* Print (or store) padding until the current horizontal position
2079    is position. */
2080
2081 static void
2082 pad_across_to (int position)
2083 {
2084   int h = output_position;
2085
2086   if (tabify_output)
2087     spaces_not_printed = position - output_position;
2088   else
2089     {
2090       while (++h <= position)
2091         putchar (' ');
2092       output_position = position;
2093     }
2094 }
2095
2096 /* Pad to the bottom of the page.
2097
2098    If the user has requested a formfeed, use one.
2099    Otherwise, use newlines. */
2100
2101 static void
2102 pad_down (int lines)
2103 {
2104   int i;
2105
2106   if (use_form_feed)
2107     putchar ('\f');
2108   else
2109     for (i = lines; i; --i)
2110       putchar ('\n');
2111 }
2112
2113 /* Read the rest of the line.
2114
2115    Read from the current column's file until an end of line is
2116    hit.  Used when we've truncated a line and we no longer need
2117    to print or store its characters. */
2118
2119 static void
2120 read_rest_of_line (COLUMN *p)
2121 {
2122   int c;
2123   FILE *f = p->fp;
2124
2125   while ((c = getc (f)) != '\n')
2126     {
2127       if (c == '\f')
2128         {
2129           if ((c = getc (f)) != '\n')
2130             ungetc (c, f);
2131           if (keep_FF)
2132             print_a_FF = true;
2133           hold_file (p);
2134           break;
2135         }
2136       else if (c == EOF)
2137         {
2138           close_file (p);
2139           break;
2140         }
2141     }
2142 }
2143
2144 /* Read a line with skip_to_page.
2145
2146    Read from the current column's file until an end of line is
2147    hit.  Used when we read full lines to skip pages.
2148    With skip_to_page we have to check for FF-coincidence which is done
2149    in function read_line otherwise.
2150    Count lines of skipped pages to find the line number of 1st page
2151    printed relative to 1st line of input file (start_line_num). */
2152
2153 static void
2154 skip_read (COLUMN *p, int column_number)
2155 {
2156   int c;
2157   FILE *f = p->fp;
2158   int i;
2159   bool single_ff = false;
2160   COLUMN *q;
2161
2162   /* Read 1st character in a line or any character succeeding a FF */
2163   if ((c = getc (f)) == '\f' && p->full_page_printed)
2164     /* A FF-coincidence with a previous full_page_printed.
2165        To avoid an additional empty page, eliminate the FF */
2166     if ((c = getc (f)) == '\n')
2167       c = getc (f);
2168
2169   p->full_page_printed = false;
2170
2171   /* 1st character a FF means a single FF without any printable
2172      characters. Don't count it as a line with -n option. */
2173   if (c == '\f')
2174     single_ff = true;
2175
2176   /* Preparing for a FF-coincidence: Maybe we finish that page
2177      without a FF found */
2178   if (last_line)
2179     p->full_page_printed = true;
2180
2181   while (c != '\n')
2182     {
2183       if (c == '\f')
2184         {
2185           /* No FF-coincidence possible,
2186              no catching up of a FF-coincidence with next page */
2187           if (last_line)
2188             {
2189               if (!parallel_files)
2190                 for (q = column_vector, i = columns; i; ++q, --i)
2191                   q->full_page_printed = false;
2192               else
2193                 p->full_page_printed = false;
2194             }
2195
2196           if ((c = getc (f)) != '\n')
2197             ungetc (c, f);
2198           hold_file (p);
2199           break;
2200         }
2201       else if (c == EOF)
2202         {
2203           close_file (p);
2204           break;
2205         }
2206       c = getc (f);
2207     }
2208
2209   if (skip_count)
2210     if ((!parallel_files || column_number == 1) && !single_ff)
2211       ++line_count;
2212 }
2213 \f
2214 /* If we're tabifying output,
2215
2216    When print_char encounters white space it keeps track
2217    of our desired horizontal position and delays printing
2218    until this function is called. */
2219
2220 static void
2221 print_white_space (void)
2222 {
2223   int h_new;
2224   int h_old = output_position;
2225   int goal = h_old + spaces_not_printed;
2226
2227   while (goal - h_old > 1
2228          && (h_new = POS_AFTER_TAB (chars_per_output_tab, h_old)) <= goal)
2229     {
2230       putchar (output_tab_char);
2231       h_old = h_new;
2232     }
2233   while (++h_old <= goal)
2234     putchar (' ');
2235
2236   output_position = goal;
2237   spaces_not_printed = 0;
2238 }
2239
2240 /* Print column separators.
2241
2242    We keep a count until we know that we'll be printing a line,
2243    then print_sep_string() is called. */
2244
2245 static void
2246 print_sep_string (void)
2247 {
2248   char *s;
2249   int l = col_sep_length;
2250
2251   s = col_sep_string;
2252
2253   if (separators_not_printed <= 0)
2254     {
2255       /* We'll be starting a line with chars_per_margin, anything else? */
2256       if (spaces_not_printed > 0)
2257         print_white_space ();
2258     }
2259   else
2260     {
2261       for (; separators_not_printed > 0; --separators_not_printed)
2262         {
2263           while (l-- > 0)
2264             {
2265               /* 3 types of sep_strings: spaces only, spaces and chars,
2266               chars only */
2267               if (*s == ' ')
2268                 {
2269                   /* We're tabifying output; consecutive spaces in
2270                   sep_string may have to be converted to tabs */
2271                   s++;
2272                   ++spaces_not_printed;
2273                 }
2274               else
2275                 {
2276                   if (spaces_not_printed > 0)
2277                     print_white_space ();
2278                   putchar (*s++);
2279                   ++output_position;
2280                 }
2281             }
2282           /* sep_string ends with some spaces */
2283           if (spaces_not_printed > 0)
2284             print_white_space ();
2285         }
2286     }
2287 }
2288
2289 /* Print (or store, depending on p->char_func) a clump of N
2290    characters. */
2291
2292 static void
2293 print_clump (COLUMN *p, int n, char *clump)
2294 {
2295   while (n--)
2296     (p->char_func) (*clump++);
2297 }
2298
2299 /* Print a character.
2300
2301    Update the following comment: process-char hasn't been used any
2302    longer.
2303    If we're tabifying, all tabs have been converted to spaces by
2304    process_char().  Keep a count of consecutive spaces, and when
2305    a nonspace is encountered, call print_white_space() to print the
2306    required number of tabs and spaces. */
2307
2308 static void
2309 print_char (char c)
2310 {
2311   if (tabify_output)
2312     {
2313       if (c == ' ')
2314         {
2315           ++spaces_not_printed;
2316           return;
2317         }
2318       else if (spaces_not_printed > 0)
2319         print_white_space ();
2320
2321       /* Nonprintables are assumed to have width 0, except '\b'. */
2322       if (! isprint (to_uchar (c)))
2323         {
2324           if (c == '\b')
2325             --output_position;
2326         }
2327       else
2328         ++output_position;
2329     }
2330   putchar (c);
2331 }
2332
2333 /* Skip to page PAGE before printing.
2334    PAGE may be larger than total number of pages. */
2335
2336 static bool
2337 skip_to_page (uintmax_t page)
2338 {
2339   uintmax_t n;
2340   int i;
2341   int j;
2342   COLUMN *p;
2343
2344   for (n = 1; n < page; ++n)
2345     {
2346       for (i = 1; i < lines_per_body; ++i)
2347         {
2348           for (j = 1, p = column_vector; j <= columns; ++j, ++p)
2349             if (p->status == OPEN)
2350               skip_read (p, j);
2351         }
2352       last_line = true;
2353       for (j = 1, p = column_vector; j <= columns; ++j, ++p)
2354         if (p->status == OPEN)
2355           skip_read (p, j);
2356
2357       if (storing_columns)      /* change FF_FOUND to ON_HOLD */
2358         for (j = 1, p = column_vector; j <= columns; ++j, ++p)
2359           if (p->status != CLOSED)
2360             p->status = ON_HOLD;
2361
2362       reset_status ();
2363       last_line = false;
2364
2365       if (files_ready_to_read < 1)
2366         {
2367           /* It's very helpful, normally the total number of pages is
2368              not known in advance.  */
2369           error (0, 0,
2370                  _("starting page number %"PRIuMAX
2371                    " exceeds page count %"PRIuMAX),
2372                  page, n);
2373           break;
2374         }
2375     }
2376   return files_ready_to_read > 0;
2377 }
2378
2379 /* Print a header.
2380
2381    Formfeeds are assumed to use up two lines at the beginning of
2382    the page. */
2383
2384 static void
2385 print_header (void)
2386 {
2387   char page_text[256 + INT_STRLEN_BOUND (page_number)];
2388   int available_width;
2389   int lhs_spaces;
2390   int rhs_spaces;
2391
2392   output_position = 0;
2393   pad_across_to (chars_per_margin);
2394   print_white_space ();
2395
2396   if (page_number == 0)
2397     error (EXIT_FAILURE, 0, _("page number overflow"));
2398
2399   /* The translator must ensure that formatting the translation of
2400      "Page %"PRIuMAX does not generate more than (sizeof page_text - 1)
2401      bytes.  */
2402   sprintf (page_text, _("Page %"PRIuMAX), page_number++);
2403   available_width = header_width_available - mbswidth (page_text, 0);
2404   available_width = MAX (0, available_width);
2405   lhs_spaces = available_width >> 1;
2406   rhs_spaces = available_width - lhs_spaces;
2407
2408   printf ("\n\n%s%*s%s%*s%s\n\n\n",
2409           date_text, lhs_spaces, " ", file_text, rhs_spaces, " ", page_text);
2410
2411   print_a_header = false;
2412   output_position = 0;
2413 }
2414
2415 /* Print (or store, if p->char_func is store_char()) a line.
2416
2417    Read a character to determine whether we have a line or not.
2418    (We may hit EOF, \n, or \f)
2419
2420    Once we know we have a line,
2421    set pad_vertically = true, meaning it's safe
2422    to pad down at the end of the page, since we do have a page.
2423    print a header if needed.
2424    pad across to padding_not_printed if needed.
2425    print any separators which need to be printed.
2426    print a line number if it needs to be printed.
2427
2428    Print the clump which corresponds to the first character.
2429
2430    Enter a loop and keep printing until an end of line condition
2431    exists, or until we exceed chars_per_column.
2432
2433    Return false if we exceed chars_per_column before reading
2434    an end of line character, true otherwise. */
2435
2436 static bool
2437 read_line (COLUMN *p)
2438 {
2439   int c;
2440   int chars IF_LINT (= 0);
2441   int last_input_position;
2442   int j, k;
2443   COLUMN *q;
2444
2445   /* read 1st character in each line or any character succeeding a FF: */
2446   c = getc (p->fp);
2447
2448   last_input_position = input_position;
2449
2450   if (c == '\f' && p->full_page_printed)
2451     if ((c = getc (p->fp)) == '\n')
2452       c = getc (p->fp);
2453   p->full_page_printed = false;
2454
2455   switch (c)
2456     {
2457     case '\f':
2458       if ((c = getc (p->fp)) != '\n')
2459         ungetc (c, p->fp);
2460       FF_only = true;
2461       if (print_a_header & !storing_columns)
2462         {
2463           pad_vertically = true;
2464           print_header ();
2465         }
2466       else if (keep_FF)
2467         print_a_FF = true;
2468       hold_file (p);
2469       return true;
2470     case EOF:
2471       close_file (p);
2472       return true;
2473     case '\n':
2474       break;
2475     default:
2476       chars = char_to_clump (c);
2477     }
2478
2479   if (truncate_lines && input_position > chars_per_column)
2480     {
2481       input_position = last_input_position;
2482       return false;
2483     }
2484
2485   if (p->char_func != store_char)
2486     {
2487       pad_vertically = true;
2488
2489       if (print_a_header & !storing_columns)
2490         print_header ();
2491
2492       if (parallel_files & align_empty_cols)
2493         {
2494           /* We have to align empty columns at the beginning of a line. */
2495           k = separators_not_printed;
2496           separators_not_printed = 0;
2497           for (j = 1, q = column_vector; j <= k; ++j, ++q)
2498             {
2499               align_column (q);
2500               separators_not_printed += 1;
2501             }
2502           padding_not_printed = p->start_position;
2503           if (truncate_lines)
2504             spaces_not_printed = chars_per_column;
2505           else
2506             spaces_not_printed = 0;
2507           align_empty_cols = false;
2508         }
2509
2510       if (padding_not_printed - col_sep_length > 0)
2511         {
2512           pad_across_to (padding_not_printed - col_sep_length);
2513           padding_not_printed = ANYWHERE;
2514         }
2515
2516       if (use_col_separator)
2517         print_sep_string ();
2518     }
2519
2520   if (p->numbered)
2521     add_line_number (p);
2522
2523   empty_line = false;
2524   if (c == '\n')
2525     return true;
2526
2527   print_clump (p, chars, clump_buff);
2528
2529   for (;;)
2530     {
2531       c = getc (p->fp);
2532
2533       switch (c)
2534         {
2535         case '\n':
2536           return true;
2537         case '\f':
2538           if ((c = getc (p->fp)) != '\n')
2539             ungetc (c, p->fp);
2540           if (keep_FF)
2541             print_a_FF = true;
2542           hold_file (p);
2543           return true;
2544         case EOF:
2545           close_file (p);
2546           return true;
2547         }
2548
2549       last_input_position = input_position;
2550       chars = char_to_clump (c);
2551       if (truncate_lines && input_position > chars_per_column)
2552         {
2553           input_position = last_input_position;
2554           return false;
2555         }
2556
2557       print_clump (p, chars, clump_buff);
2558     }
2559 }
2560
2561 /* Print a line from buff.
2562
2563    If this function has been called, we know we have "something to
2564    print". But it remains to be seen whether we have a real text page
2565    or an empty page (a single form feed) with/without a header only.
2566    Therefore first we set pad_vertically to true and print a header
2567    if necessary.
2568    If FF_FOUND and we are using -t|-T option we omit any newline by
2569    setting pad_vertically to false (see print_page).
2570    Otherwise we pad across if necessary, print separators if necessary
2571    and text of COLUMN *p.
2572
2573    Return true, meaning there is no need to call read_rest_of_line. */
2574
2575 static bool
2576 print_stored (COLUMN *p)
2577 {
2578   COLUMN *q;
2579   int i;
2580
2581   int line = p->current_line++;
2582   char *first = &buff[line_vector[line]];
2583   /* FIXME
2584      UMR: Uninitialized memory read:
2585      * This is occurring while in:
2586      print_stored   [pr.c:2239]
2587      * Reading 4 bytes from 0x5148c in the heap.
2588      * Address 0x5148c is 4 bytes into a malloc'd block at 0x51488 of 676 bytes
2589      * This block was allocated from:
2590      malloc         [rtlib.o]
2591      xmalloc        [xmalloc.c:94]
2592      init_store_cols [pr.c:1648]
2593      */
2594   char *last = &buff[line_vector[line + 1]];
2595
2596   pad_vertically = true;
2597
2598   if (print_a_header)
2599     print_header ();
2600
2601   if (p->status == FF_FOUND)
2602     {
2603       for (i = 1, q = column_vector; i <= columns; ++i, ++q)
2604         q->status = ON_HOLD;
2605       if (column_vector->lines_to_print <= 0)
2606         {
2607           if (!extremities)
2608             pad_vertically = false;
2609           return true;          /* print a header only */
2610         }
2611     }
2612
2613   if (padding_not_printed - col_sep_length > 0)
2614     {
2615       pad_across_to (padding_not_printed - col_sep_length);
2616       padding_not_printed = ANYWHERE;
2617     }
2618
2619   if (use_col_separator)
2620     print_sep_string ();
2621
2622   while (first != last)
2623     print_char (*first++);
2624
2625   if (spaces_not_printed == 0)
2626     {
2627       output_position = p->start_position + end_vector[line];
2628       if (p->start_position - col_sep_length == chars_per_margin)
2629         output_position -= col_sep_length;
2630     }
2631
2632   return true;
2633 }
2634
2635 /* Convert a character to the proper format and return the number of
2636    characters in the resulting clump.  Increment input_position by
2637    the width of the clump.
2638
2639    Tabs are converted to clumps of spaces.
2640    Nonprintable characters may be converted to clumps of escape
2641    sequences or control prefixes.
2642
2643    Note: the width of a clump is not necessarily equal to the number of
2644    characters in clump_buff.  (e.g, the width of '\b' is -1, while the
2645    number of characters is 1.) */
2646
2647 static int
2648 char_to_clump (char c)
2649 {
2650   unsigned char uc = c;
2651   char *s = clump_buff;
2652   int i;
2653   char esc_buff[4];
2654   int width;
2655   int chars;
2656   int chars_per_c = 8;
2657
2658   if (c == input_tab_char)
2659     chars_per_c = chars_per_input_tab;
2660
2661   if (c == input_tab_char || c == '\t')
2662     {
2663       width = TAB_WIDTH (chars_per_c, input_position);
2664
2665       if (untabify_input)
2666         {
2667           for (i = width; i; --i)
2668             *s++ = ' ';
2669           chars = width;
2670         }
2671       else
2672         {
2673           *s = c;
2674           chars = 1;
2675         }
2676
2677     }
2678   else if (! isprint (uc))
2679     {
2680       if (use_esc_sequence)
2681         {
2682           width = 4;
2683           chars = 4;
2684           *s++ = '\\';
2685           sprintf (esc_buff, "%03o", uc);
2686           for (i = 0; i <= 2; ++i)
2687             *s++ = esc_buff[i];
2688         }
2689       else if (use_cntrl_prefix)
2690         {
2691           if (uc < 0200)
2692             {
2693               width = 2;
2694               chars = 2;
2695               *s++ = '^';
2696               *s++ = c ^ 0100;
2697             }
2698           else
2699             {
2700               width = 4;
2701               chars = 4;
2702               *s++ = '\\';
2703               sprintf (esc_buff, "%03o", uc);
2704               for (i = 0; i <= 2; ++i)
2705                 *s++ = esc_buff[i];
2706             }
2707         }
2708       else if (c == '\b')
2709         {
2710           width = -1;
2711           chars = 1;
2712           *s = c;
2713         }
2714       else
2715         {
2716           width = 0;
2717           chars = 1;
2718           *s = c;
2719         }
2720     }
2721   else
2722     {
2723       width = 1;
2724       chars = 1;
2725       *s = c;
2726     }
2727
2728   /* Too many backspaces must put us in position 0 -- never negative.  */
2729   if (width < 0 && input_position == 0)
2730     {
2731       chars = 0;
2732       input_position = 0;
2733     }
2734   else if (width < 0 && input_position <= -width)
2735     input_position = 0;
2736   else
2737     input_position += width;
2738
2739   return chars;
2740 }
2741
2742 /* We've just printed some files and need to clean up things before
2743    looking for more options and printing the next batch of files.
2744
2745    Free everything we've xmalloc'ed, except `header'. */
2746
2747 static void
2748 cleanup (void)
2749 {
2750   free (number_buff);
2751   free (clump_buff);
2752   free (column_vector);
2753   free (line_vector);
2754   free (end_vector);
2755   free (buff);
2756 }
2757 \f
2758 /* Complain, print a usage message, and die. */
2759
2760 void
2761 usage (int status)
2762 {
2763   if (status != EXIT_SUCCESS)
2764     fprintf (stderr, _("Try `%s --help' for more information.\n"),
2765              program_name);
2766   else
2767     {
2768       printf (_("\
2769 Usage: %s [OPTION]... [FILE]...\n\
2770 "),
2771               program_name);
2772
2773       fputs (_("\
2774 Paginate or columnate FILE(s) for printing.\n\
2775 \n\
2776 "), stdout);
2777       fputs (_("\
2778 Mandatory arguments to long options are mandatory for short options too.\n\
2779 "), stdout);
2780       fputs (_("\
2781   +FIRST_PAGE[:LAST_PAGE], --pages=FIRST_PAGE[:LAST_PAGE]\n\
2782                     begin [stop] printing with page FIRST_[LAST_]PAGE\n\
2783   -COLUMN, --columns=COLUMN\n\
2784                     output COLUMN columns and print columns down,\n\
2785                     unless -a is used. Balance number of lines in the\n\
2786                     columns on each page.\n\
2787 "), stdout);
2788       fputs (_("\
2789   -a, --across      print columns across rather than down, used together\n\
2790                     with -COLUMN\n\
2791   -c, --show-control-chars\n\
2792                     use hat notation (^G) and octal backslash notation\n\
2793   -d, --double-space\n\
2794                     double space the output\n\
2795 "), stdout);
2796       fputs (_("\
2797   -D, --date-format=FORMAT\n\
2798                     use FORMAT for the header date\n\
2799   -e[CHAR[WIDTH]], --expand-tabs[=CHAR[WIDTH]]\n\
2800                     expand input CHARs (TABs) to tab WIDTH (8)\n\
2801   -F, -f, --form-feed\n\
2802                     use form feeds instead of newlines to separate pages\n\
2803                     (by a 3-line page header with -F or a 5-line header\n\
2804                     and trailer without -F)\n\
2805 "), stdout);
2806       fputs (_("\
2807   -h HEADER, --header=HEADER\n\
2808                     use a centered HEADER instead of filename in page header,\n\
2809                     -h \"\" prints a blank line, don't use -h\"\"\n\
2810   -i[CHAR[WIDTH]], --output-tabs[=CHAR[WIDTH]]\n\
2811                     replace spaces with CHARs (TABs) to tab WIDTH (8)\n\
2812   -J, --join-lines  merge full lines, turns off -W line truncation, no column\n\
2813                     alignment, --sep-string[=STRING] sets separators\n\
2814 "), stdout);
2815       fputs (_("\
2816   -l PAGE_LENGTH, --length=PAGE_LENGTH\n\
2817                     set the page length to PAGE_LENGTH (66) lines\n\
2818                     (default number of lines of text 56, and with -F 63)\n\
2819   -m, --merge       print all files in parallel, one in each column,\n\
2820                     truncate lines, but join lines of full length with -J\n\
2821 "), stdout);
2822       fputs (_("\
2823   -n[SEP[DIGITS]], --number-lines[=SEP[DIGITS]]\n\
2824                     number lines, use DIGITS (5) digits, then SEP (TAB),\n\
2825                     default counting starts with 1st line of input file\n\
2826   -N NUMBER, --first-line-number=NUMBER\n\
2827                     start counting with NUMBER at 1st line of first\n\
2828                     page printed (see +FIRST_PAGE)\n\
2829 "), stdout);
2830       fputs (_("\
2831   -o MARGIN, --indent=MARGIN\n\
2832                     offset each line with MARGIN (zero) spaces, do not\n\
2833                     affect -w or -W, MARGIN will be added to PAGE_WIDTH\n\
2834   -r, --no-file-warnings\n\
2835                     omit warning when a file cannot be opened\n\
2836 "), stdout);
2837       fputs (_("\
2838   -s[CHAR],--separator[=CHAR]\n\
2839                     separate columns by a single character, default for CHAR\n\
2840                     is the <TAB> character without -w and \'no char\' with -w\n\
2841                     -s[CHAR] turns off line truncation of all 3 column\n\
2842                     options (-COLUMN|-a -COLUMN|-m) except -w is set\n\
2843 "), stdout);
2844       fputs (_("\
2845   -SSTRING, --sep-string[=STRING]\n\
2846 "), stdout);
2847       fputs (_("\
2848                     separate columns by STRING,\n\
2849                     without -S: Default separator <TAB> with -J and <space>\n\
2850                     otherwise (same as -S\" \"), no effect on column options\n\
2851   -t, --omit-header  omit page headers and trailers\n\
2852 "), stdout);
2853       fputs (_("\
2854   -T, --omit-pagination\n\
2855                     omit page headers and trailers, eliminate any pagination\n\
2856                     by form feeds set in input files\n\
2857   -v, --show-nonprinting\n\
2858                     use octal backslash notation\n\
2859   -w PAGE_WIDTH, --width=PAGE_WIDTH\n\
2860                     set page width to PAGE_WIDTH (72) characters for\n\
2861                     multiple text-column output only, -s[char] turns off (72)\n\
2862 "), stdout);
2863       fputs (_("\
2864   -W PAGE_WIDTH, --page-width=PAGE_WIDTH\n\
2865                     set page width to PAGE_WIDTH (72) characters always,\n\
2866                     truncate lines, except -J option is set, no interference\n\
2867                     with -S or -s\n\
2868 "), stdout);
2869       fputs (HELP_OPTION_DESCRIPTION, stdout);
2870       fputs (VERSION_OPTION_DESCRIPTION, stdout);
2871       fputs (_("\
2872 \n\
2873 -t is implied if PAGE_LENGTH <= 10.  With no FILE, or when\n\
2874 FILE is -, read standard input.\n\
2875 "), stdout);
2876       emit_bug_reporting_address ();
2877     }
2878   exit (status);
2879 }