du: --apparent counts only symlinks and regular
[coreutils.git] / src / pr.c
blob28a6952421369818df4379749a94a7f3b97d7cd1
1 /* pr -- convert text files for printing.
2 Copyright (C) 1988-2023 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 /* By Pete TerMaat, with considerable refinement by Roland Huebner. */
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
24 Ideas:
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.
29 Improve the printing of control prefixes.
31 Expand the file name in the centered header line to a full file name.
34 Concept:
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.
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.
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 structure 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 --------------------------------------------------------------------
92 Options:
94 Including version 1.22i:
95 Some SMALL LETTER options have 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.
106 Capital letter options dominate small letter ones.
108 Some of the option-arguments cannot be specified as separate arguments
109 from the preceding option letter (already stated in POSIX specification).
111 Form feeds in the input cause page breaks in the output. Multiple
112 form feeds produce empty pages.
114 +FIRST_PAGE[:LAST_PAGE], --pages=FIRST_PAGE[:LAST_PAGE]
115 begin [stop] printing with page FIRST_[LAST_]PAGE
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.
122 -a, --across Print columns across rather than down, used
123 together with -COLUMN. The input
126 three
127 four
128 will be printed with '-a -3' as
129 one two three
130 four
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.
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.
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.
150 -d, --double-space Double space the output.
152 -D FORMAT, --date-format=FORMAT Use FORMAT for the header date.
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.)
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.
164 -h HEADER, --header=HEADER
165 Replace the filename in the header with the string HEADER.
166 A centered header is used.
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)
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.
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).
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.
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.
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.
203 Together with -J option join lines of full length and
204 set separators when -S option is used.
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.
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).
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).
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.
241 -r, --no-file-warnings
242 Omit warning when a file cannot be opened.
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.
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.
267 -t, --omit-header Do not print headers or footers but retain form
268 feeds set in the input files.
270 -T, --omit-pagination
271 Do not print headers or footers, eliminate any pagination
272 by form feeds set in the input files.
274 -v, --show-nonprinting
275 Print unprintable characters as escape sequences. Use
276 octal backslash notation. Control-G becomes \007.
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.
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 .
302 With/without -W PAGE_WIDTH the header line is always
303 truncated to avoid line overflow.
305 (In pr versions newer than 1.14 -S option does no longer
306 affect -W option.)
310 #include <config.h>
312 #include <getopt.h>
313 #include <sys/types.h>
314 #include "system.h"
315 #include "die.h"
316 #include "error.h"
317 #include "fadvise.h"
318 #include "hard-locale.h"
319 #include "mbswidth.h"
320 #include "quote.h"
321 #include "stat-time.h"
322 #include "stdio--.h"
323 #include "strftime.h"
324 #include "xstrtol.h"
325 #include "xstrtol-error.h"
326 #include "xdectoint.h"
328 /* The official name of this program (e.g., no 'g' prefix). */
329 #define PROGRAM_NAME "pr"
331 #define AUTHORS \
332 proper_name ("Pete TerMaat"), \
333 proper_name ("Roland Huebner")
335 /* Used with start_position in the struct COLUMN described below.
336 If start_position == ANYWHERE, we aren't truncating columns and
337 can begin printing a column anywhere. Otherwise we must pad to
338 the horizontal position start_position. */
339 #define ANYWHERE 0
341 /* Each column has one of these structures allocated for it.
342 If we're only dealing with one file, fp is the same for all
343 columns.
345 The general strategy is to spend time setting up these column
346 structures (storing columns if necessary), after which printing
347 is a matter of flitting from column to column and calling
348 print_func.
350 Parallel files, single files printing across in multiple
351 columns, and single files printing down in multiple columns all
352 fit the same printing loop.
354 print_func Function used to print lines in this column.
355 If we're storing this column it will be
356 print_stored(), Otherwise it will be read_line().
358 char_func Function used to process characters in this column.
359 If we're storing this column it will be store_char(),
360 otherwise it will be print_char().
362 current_line Index of the current entry in line_vector, which
363 contains the index of the first character of the
364 current line in buff[].
366 lines_stored Number of lines in this column which are stored in
367 buff.
369 lines_to_print If we're storing this column, lines_to_print is
370 the number of stored_lines which remain to be
371 printed. Otherwise it is the number of lines
372 we can print without exceeding lines_per_body.
374 start_position The horizontal position we want to be in before we
375 print the first character in this column.
377 numbered True means precede this column with a line number. */
379 /* FIXME: There are many unchecked integer overflows in this file,
380 that will cause this command to misbehave given large inputs or
381 options. Many of the "int" values below should be "size_t" or
382 something else like that. */
384 struct COLUMN;
385 struct COLUMN
387 FILE *fp; /* Input stream for this column. */
388 char const *name; /* File name. */
389 enum
391 OPEN,
392 FF_FOUND, /* used with -b option, set with \f, changed
393 to ON_HOLD after print_header */
394 ON_HOLD, /* Hit a form feed. */
395 CLOSED
397 status; /* Status of the file pointer. */
399 /* Func to print lines in this col. */
400 bool (*print_func) (struct COLUMN *);
402 /* Func to print/store chars in this col. */
403 void (*char_func) (char);
405 int current_line; /* Index of current place in line_vector. */
406 int lines_stored; /* Number of lines stored in buff. */
407 int lines_to_print; /* No. lines stored or space left on page. */
408 int start_position; /* Horizontal position of first char. */
409 bool numbered;
410 bool full_page_printed; /* True means printed without a FF found. */
412 /* p->full_page_printed controls a special case of "FF set by hand":
413 True means a full page has been printed without FF found. To avoid an
414 additional empty page we have to ignore a FF immediately following in
415 the next line. */
418 typedef struct COLUMN COLUMN;
420 static int char_to_clump (char c);
421 static bool read_line (COLUMN *p);
422 static bool print_page (void);
423 static bool print_stored (COLUMN *p);
424 static bool open_file (char *name, COLUMN *p);
425 static bool skip_to_page (uintmax_t page);
426 static void print_header (void);
427 static void pad_across_to (int position);
428 static void add_line_number (COLUMN *p);
429 static void getoptnum (char const *n_str, int min, int *num,
430 char const *errfmt);
431 static void getoptarg (char *arg, char switch_char, char *character,
432 int *number);
433 static void print_files (int number_of_files, char **av);
434 static void init_parameters (int number_of_files);
435 static void init_header (char const *filename, int desc);
436 static bool init_fps (int number_of_files, char **av);
437 static void init_funcs (void);
438 static void init_store_cols (void);
439 static void store_columns (void);
440 static void balance (int total_stored);
441 static void store_char (char c);
442 static void pad_down (unsigned int lines);
443 static void read_rest_of_line (COLUMN *p);
444 static void skip_read (COLUMN *p, int column_number);
445 static void print_char (char c);
446 static void cleanup (void);
447 static void print_sep_string (void);
448 static void separator_string (char const *optarg_S);
450 /* All of the columns to print. */
451 static COLUMN *column_vector;
453 /* When printing a single file in multiple downward columns,
454 we store the leftmost columns contiguously in buff.
455 To print a line from buff, get the index of the first character
456 from line_vector[i], and print up to line_vector[i + 1]. */
457 static char *buff;
459 /* Index of the position in buff where the next character
460 will be stored. */
461 static unsigned int buff_current;
463 /* The number of characters in buff.
464 Used for allocation of buff and to detect overflow of buff. */
465 static size_t buff_allocated;
467 /* Array of indices into buff.
468 Each entry is an index of the first character of a line.
469 This is used when storing lines to facilitate shuffling when
470 we do column balancing on the last page. */
471 static int *line_vector;
473 /* Array of horizontal positions.
474 For each line in line_vector, end_vector[line] is the horizontal
475 position we are in after printing that line. We keep track of this
476 so that we know how much we need to pad to prepare for the next
477 column. */
478 static int *end_vector;
480 /* (-m) True means we're printing multiple files in parallel. */
481 static bool parallel_files = false;
483 /* (-m) True means a line starts with some empty columns (some files
484 already CLOSED or ON_HOLD) which we have to align. */
485 static bool align_empty_cols;
487 /* (-m) True means we have not yet found any printable column in a line.
488 align_empty_cols = true has to be maintained. */
489 static bool empty_line;
491 /* (-m) False means printable column output precedes a form feed found.
492 Column alignment is done only once. No additional action with that form
493 feed.
494 True means we found only a form feed in a column. Maybe we have to do
495 some column alignment with that form feed. */
496 static bool FF_only;
498 /* (-[0-9]+) True means we're given an option explicitly specifying
499 number of columns. Used to detect when this option is used with -m
500 and when translating old options to new/long options. */
501 static bool explicit_columns = false;
503 /* (-t|-T) False means we aren't printing headers and footers. */
504 static bool extremities = true;
506 /* (-t) True means we retain all FF set by hand in input files.
507 False is set with -T option. */
508 static bool keep_FF = false;
509 static bool print_a_FF = false;
511 /* True means we need to print a header as soon as we know we've got input
512 to print after it. */
513 static bool print_a_header;
515 /* (-f) True means use formfeeds instead of newlines to separate pages. */
516 static bool use_form_feed = false;
518 /* True means we have read the standard input. */
519 static bool have_read_stdin = false;
521 /* True means the -a flag has been given. */
522 static bool print_across_flag = false;
524 /* True means we're printing one file in multiple (>1) downward columns. */
525 static bool storing_columns = true;
527 /* (-b) True means balance columns on the last page as Sys V does. */
528 /* That's no longer an independent option. With storing_columns = true
529 balance_columns = true is used too (s. function init_parameters).
530 We get a consistent formulation with "FF set by hand" in input files. */
531 static bool balance_columns = false;
533 /* (-l) Number of lines on a page, including header and footer lines. */
534 static int lines_per_page = 66;
536 /* Number of lines in the header and footer can be reset to 0 using
537 the -t flag. */
538 enum { lines_per_header = 5 };
539 static int lines_per_body;
540 enum { lines_per_footer = 5 };
542 /* (-w|-W) Width in characters of the page. Does not include the width of
543 the margin. */
544 static int chars_per_line = 72;
546 /* (-w|W) True means we truncate lines longer than chars_per_column. */
547 static bool truncate_lines = false;
549 /* (-J) True means we join lines without any line truncation. -J
550 dominates -w option. */
551 static bool join_lines = false;
553 /* Number of characters in a column. Based on col_sep_length and
554 page width. */
555 static int chars_per_column;
557 /* (-e) True means convert tabs to spaces on input. */
558 static bool untabify_input = false;
560 /* (-e) The input tab character. */
561 static char input_tab_char = '\t';
563 /* (-e) Tabstops are at chars_per_tab, 2*chars_per_tab, 3*chars_per_tab, ...
564 where the leftmost column is 1. */
565 static int chars_per_input_tab = 8;
567 /* (-i) True means convert spaces to tabs on output. */
568 static bool tabify_output = false;
570 /* (-i) The output tab character. */
571 static char output_tab_char = '\t';
573 /* (-i) The width of the output tab. */
574 static int chars_per_output_tab = 8;
576 /* Keeps track of pending white space. When we hit a nonspace
577 character after some whitespace, we print whitespace, tabbing
578 if necessary to get to output_position + spaces_not_printed. */
579 static int spaces_not_printed;
581 /* (-o) Number of spaces in the left margin (tabs used when possible). */
582 static int chars_per_margin = 0;
584 /* Position where the next character will fall.
585 Leftmost position is 0 + chars_per_margin.
586 Rightmost position is chars_per_margin + chars_per_line - 1.
587 This is important for converting spaces to tabs on output. */
588 static int output_position;
590 /* Horizontal position relative to the current file.
591 (output_position depends on where we are on the page;
592 input_position depends on where we are in the file.)
593 Important for converting tabs to spaces on input. */
594 static int input_position;
596 /* True if there were any failed opens so we can exit with nonzero
597 status. */
598 static bool failed_opens = false;
600 /* The number of spaces taken up if we print a tab character with width
601 c_ from position h_. */
602 #define TAB_WIDTH(c_, h_) ((c_) - ((h_) % (c_)))
604 /* The horizontal position we'll be at after printing a tab character
605 of width c_ from the position h_. */
606 #define POS_AFTER_TAB(c_, h_) ((h_) + TAB_WIDTH (c_, h_))
608 /* (-NNN) Number of columns of text to print. */
609 static int columns = 1;
611 /* (+NNN:MMM) Page numbers on which to begin and stop printing.
612 first_page_number = 0 will be used to check input only. */
613 static uintmax_t first_page_number = 0;
614 static uintmax_t last_page_number = UINTMAX_MAX;
616 /* Number of files open (not closed, not on hold). */
617 static int files_ready_to_read = 0;
619 /* Current page number. Displayed in header. */
620 static uintmax_t page_number;
622 /* Current line number. Displayed when -n flag is specified.
624 When printing files in parallel (-m flag), line numbering is as follows:
625 1 foo goo moo
626 2 hoo too zoo
628 When printing files across (-a flag), ...
629 1 foo 2 moo 3 goo
630 4 hoo 5 too 6 zoo
632 Otherwise, line numbering is as follows:
633 1 foo 3 goo 5 too
634 2 moo 4 hoo 6 zoo */
635 static int line_number;
637 /* (-n) True means lines should be preceded by numbers. */
638 static bool numbered_lines = false;
640 /* (-n) Character which follows each line number. */
641 static char number_separator = '\t';
643 /* (-n) line counting starts with 1st line of input file (not with 1st
644 line of 1st page printed). */
645 static int line_count = 1;
647 /* (-n) True means counting of skipped lines starts with 1st line of
648 input file. False means -N option is used in addition, counting of
649 skipped lines not required. */
650 static bool skip_count = true;
652 /* (-N) Counting starts with start_line_number = NUMBER at 1st line of
653 first page printed, usually not 1st page of input file. */
654 static int start_line_num = 1;
656 /* (-n) Width in characters of a line number. */
657 static int chars_per_number = 5;
659 /* Used when widening the first column to accommodate numbers -- only
660 needed when printing files in parallel. Includes width of both the
661 number and the number_separator. */
662 static int number_width;
664 /* Buffer sprintf uses to format a line number. */
665 static char *number_buff;
667 /* (-v) True means unprintable characters are printed as escape sequences.
668 control-g becomes \007. */
669 static bool use_esc_sequence = false;
671 /* (-c) True means unprintable characters are printed as control prefixes.
672 control-g becomes ^G. */
673 static bool use_cntrl_prefix = false;
675 /* (-d) True means output is double spaced. */
676 static bool double_space = false;
678 /* Number of files opened initially in init_files. Should be 1
679 unless we're printing multiple files in parallel. */
680 static int total_files = 0;
682 /* (-r) True means don't complain if we can't open a file. */
683 static bool ignore_failed_opens = false;
685 /* (-S) True means we separate columns with a specified string.
686 -S option does not affect line truncation nor column alignment. */
687 static bool use_col_separator = false;
689 /* String used to separate columns if the -S option has been specified.
690 Default without -S but together with one of the column options
691 -a|COLUMN|-m is a 'space' and with the -J option a 'tab'. */
692 static char const *col_sep_string = "";
693 static int col_sep_length = 0;
694 static char *column_separator = (char *) " ";
695 static char *line_separator = (char *) "\t";
697 /* Number of separator characters waiting to be printed as soon as we
698 know that we have any input remaining to be printed. */
699 static int separators_not_printed;
701 /* Position we need to pad to, as soon as we know that we have input
702 remaining to be printed. */
703 static int padding_not_printed;
705 /* True means we should pad the end of the page. Remains false until we
706 know we have a page to print. */
707 static bool pad_vertically;
709 /* (-h) String of characters used in place of the filename in the header. */
710 static char *custom_header;
712 /* (-D) Date format for the header. */
713 static char const *date_format;
715 /* The local time zone rules, as per the TZ environment variable. */
716 static timezone_t localtz;
718 /* Date and file name for the header. */
719 static char *date_text;
720 static char const *file_text;
722 /* Output columns available, not counting the date and file name. */
723 static int header_width_available;
725 static char *clump_buff;
727 /* True means we read the line no. lines_per_body in skip_read
728 called by skip_to_page. That variable controls the coincidence of a
729 "FF set by hand" and "full_page_printed", see above the definition of
730 structure COLUMN. */
731 static bool last_line = false;
733 /* For long options that have no equivalent short option, use a
734 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
735 enum
737 COLUMNS_OPTION = CHAR_MAX + 1,
738 PAGES_OPTION
741 static char const short_options[] =
742 "-0123456789D:FJN:S::TW:abcde::fh:i::l:mn::o:rs::tvw:";
744 static struct option const long_options[] =
746 {"pages", required_argument, NULL, PAGES_OPTION},
747 {"columns", required_argument, NULL, COLUMNS_OPTION},
748 {"across", no_argument, NULL, 'a'},
749 {"show-control-chars", no_argument, NULL, 'c'},
750 {"double-space", no_argument, NULL, 'd'},
751 {"date-format", required_argument, NULL, 'D'},
752 {"expand-tabs", optional_argument, NULL, 'e'},
753 {"form-feed", no_argument, NULL, 'f'},
754 {"header", required_argument, NULL, 'h'},
755 {"output-tabs", optional_argument, NULL, 'i'},
756 {"join-lines", no_argument, NULL, 'J'},
757 {"length", required_argument, NULL, 'l'},
758 {"merge", no_argument, NULL, 'm'},
759 {"number-lines", optional_argument, NULL, 'n'},
760 {"first-line-number", required_argument, NULL, 'N'},
761 {"indent", required_argument, NULL, 'o'},
762 {"no-file-warnings", no_argument, NULL, 'r'},
763 {"separator", optional_argument, NULL, 's'},
764 {"sep-string", optional_argument, NULL, 'S'},
765 {"omit-header", no_argument, NULL, 't'},
766 {"omit-pagination", no_argument, NULL, 'T'},
767 {"show-nonprinting", no_argument, NULL, 'v'},
768 {"width", required_argument, NULL, 'w'},
769 {"page-width", required_argument, NULL, 'W'},
770 {GETOPT_HELP_OPTION_DECL},
771 {GETOPT_VERSION_OPTION_DECL},
772 {NULL, 0, NULL, 0}
775 static void
776 integer_overflow (void)
778 die (EXIT_FAILURE, 0, _("integer overflow"));
781 /* Return the number of columns that have either an open file or
782 stored lines. */
784 ATTRIBUTE_PURE
785 static unsigned int
786 cols_ready_to_print (void)
788 COLUMN *q;
789 unsigned int i;
790 unsigned int n;
792 n = 0;
793 for (q = column_vector, i = 0; i < columns; ++q, ++i)
794 if (q->status == OPEN
795 || q->status == FF_FOUND /* With -b: To print a header only */
796 || (storing_columns && q->lines_stored > 0 && q->lines_to_print > 0))
797 ++n;
798 return n;
801 /* Estimate first_ / last_page_number
802 using option +FIRST_PAGE:LAST_PAGE */
804 static bool
805 first_last_page (int oi, char c, char const *pages)
807 char *p;
808 uintmax_t first;
809 uintmax_t last = UINTMAX_MAX;
810 strtol_error err = xstrtoumax (pages, &p, 10, &first, "");
811 if (err != LONGINT_OK && err != LONGINT_INVALID_SUFFIX_CHAR)
812 xstrtol_fatal (err, oi, c, long_options, pages);
814 if (p == pages || !first)
815 return false;
817 if (*p == ':')
819 char const *p1 = p + 1;
820 err = xstrtoumax (p1, &p, 10, &last, "");
821 if (err != LONGINT_OK)
822 xstrtol_fatal (err, oi, c, long_options, pages);
823 if (p1 == p || last < first)
824 return false;
827 if (*p)
828 return false;
830 first_page_number = first;
831 last_page_number = last;
832 return true;
835 /* Parse column count string S, and if it's valid (1 or larger and
836 within range of the type of 'columns') set the global variables
837 columns and explicit_columns. Otherwise, exit with a diagnostic. */
839 static void
840 parse_column_count (char const *s)
842 getoptnum (s, 1, &columns, _("invalid number of columns"));
843 explicit_columns = true;
846 /* Estimate length of col_sep_string with option -S. */
848 static void
849 separator_string (char const *optarg_S)
851 size_t len = strlen (optarg_S);
852 if (INT_MAX < len)
853 integer_overflow ();
854 col_sep_length = len;
855 col_sep_string = optarg_S;
859 main (int argc, char **argv)
861 unsigned int n_files;
862 bool old_options = false;
863 bool old_w = false;
864 bool old_s = false;
865 char **file_names;
867 /* Accumulate the digits of old-style options like -99. */
868 char *column_count_string = NULL;
869 size_t n_digits = 0;
870 size_t n_alloc = 0;
872 initialize_main (&argc, &argv);
873 set_program_name (argv[0]);
874 setlocale (LC_ALL, "");
875 bindtextdomain (PACKAGE, LOCALEDIR);
876 textdomain (PACKAGE);
878 atexit (close_stdout);
880 n_files = 0;
881 file_names = (argc > 1
882 ? xnmalloc (argc - 1, sizeof (char *))
883 : NULL);
885 while (true)
887 int oi = -1;
888 int c = getopt_long (argc, argv, short_options, long_options, &oi);
889 if (c == -1)
890 break;
892 if (ISDIGIT (c))
894 /* Accumulate column-count digits specified via old-style options. */
895 if (n_digits + 1 >= n_alloc)
896 column_count_string
897 = X2REALLOC (column_count_string, &n_alloc);
898 column_count_string[n_digits++] = c;
899 column_count_string[n_digits] = '\0';
900 continue;
903 n_digits = 0;
905 switch (c)
907 case 1: /* Non-option argument. */
908 /* long option --page dominates old '+FIRST_PAGE ...'. */
909 if (! (first_page_number == 0
910 && *optarg == '+' && first_last_page (-2, '+', optarg + 1)))
911 file_names[n_files++] = optarg;
912 break;
914 case PAGES_OPTION: /* --pages=FIRST_PAGE[:LAST_PAGE] */
915 { /* dominates old opt +... */
916 if (! optarg)
917 die (EXIT_FAILURE, 0,
918 _("'--pages=FIRST_PAGE[:LAST_PAGE]' missing argument"));
919 else if (! first_last_page (oi, 0, optarg))
920 die (EXIT_FAILURE, 0, _("invalid page range %s"),
921 quote (optarg));
922 break;
925 case COLUMNS_OPTION: /* --columns=COLUMN */
927 parse_column_count (optarg);
929 /* If there was a prior column count specified via the
930 short-named option syntax, e.g., -9, ensure that this
931 long-name-specified value overrides it. */
932 free (column_count_string);
933 column_count_string = NULL;
934 n_alloc = 0;
935 break;
938 case 'a':
939 print_across_flag = true;
940 storing_columns = false;
941 break;
942 case 'b':
943 balance_columns = true;
944 break;
945 case 'c':
946 use_cntrl_prefix = true;
947 break;
948 case 'd':
949 double_space = true;
950 break;
951 case 'D':
952 date_format = optarg;
953 break;
954 case 'e':
955 if (optarg)
956 getoptarg (optarg, 'e', &input_tab_char,
957 &chars_per_input_tab);
958 /* Could check tab width > 0. */
959 untabify_input = true;
960 break;
961 case 'f':
962 case 'F':
963 use_form_feed = true;
964 break;
965 case 'h':
966 custom_header = optarg;
967 break;
968 case 'i':
969 if (optarg)
970 getoptarg (optarg, 'i', &output_tab_char,
971 &chars_per_output_tab);
972 /* Could check tab width > 0. */
973 tabify_output = true;
974 break;
975 case 'J':
976 join_lines = true;
977 break;
978 case 'l':
979 getoptnum (optarg, 1, &lines_per_page,
980 _("'-l PAGE_LENGTH' invalid number of lines"));
981 break;
982 case 'm':
983 parallel_files = true;
984 storing_columns = false;
985 break;
986 case 'n':
987 numbered_lines = true;
988 if (optarg)
989 getoptarg (optarg, 'n', &number_separator,
990 &chars_per_number);
991 break;
992 case 'N':
993 skip_count = false;
994 getoptnum (optarg, INT_MIN, &start_line_num,
995 _("'-N NUMBER' invalid starting line number"));
996 break;
997 case 'o':
998 getoptnum (optarg, 0, &chars_per_margin,
999 _("'-o MARGIN' invalid line offset"));
1000 break;
1001 case 'r':
1002 ignore_failed_opens = true;
1003 break;
1004 case 's':
1005 old_options = true;
1006 old_s = true;
1007 if (!use_col_separator && optarg)
1008 separator_string (optarg);
1009 break;
1010 case 'S':
1011 old_s = false;
1012 /* Reset an additional input of -s, -S dominates -s */
1013 col_sep_string = "";
1014 col_sep_length = 0;
1015 use_col_separator = true;
1016 if (optarg)
1017 separator_string (optarg);
1018 break;
1019 case 't':
1020 extremities = false;
1021 keep_FF = true;
1022 break;
1023 case 'T':
1024 extremities = false;
1025 keep_FF = false;
1026 break;
1027 case 'v':
1028 use_esc_sequence = true;
1029 break;
1030 case 'w':
1031 old_options = true;
1032 old_w = true;
1034 int tmp_cpl;
1035 getoptnum (optarg, 1, &tmp_cpl,
1036 _("'-w PAGE_WIDTH' invalid number of characters"));
1037 if (! truncate_lines)
1038 chars_per_line = tmp_cpl;
1040 break;
1041 case 'W':
1042 old_w = false; /* dominates -w */
1043 truncate_lines = true;
1044 getoptnum (optarg, 1, &chars_per_line,
1045 _("'-W PAGE_WIDTH' invalid number of characters"));
1046 break;
1047 case_GETOPT_HELP_CHAR;
1048 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1049 default:
1050 usage (EXIT_FAILURE);
1051 break;
1055 if (column_count_string)
1057 parse_column_count (column_count_string);
1058 free (column_count_string);
1061 if (! date_format)
1062 date_format = (getenv ("POSIXLY_CORRECT") && !hard_locale (LC_TIME)
1063 ? "%b %e %H:%M %Y"
1064 : "%Y-%m-%d %H:%M");
1066 localtz = tzalloc (getenv ("TZ"));
1068 /* Now we can set a reasonable initial value: */
1069 if (first_page_number == 0)
1070 first_page_number = 1;
1072 if (parallel_files && explicit_columns)
1073 die (EXIT_FAILURE, 0,
1074 _("cannot specify number of columns when printing in parallel"));
1076 if (parallel_files && print_across_flag)
1077 die (EXIT_FAILURE, 0,
1078 _("cannot specify both printing across and printing in parallel"));
1080 /* Translate some old short options to new/long options.
1081 To meet downward compatibility with other UNIX pr utilities
1082 and some POSIX specifications. */
1084 if (old_options)
1086 if (old_w)
1088 if (parallel_files || explicit_columns)
1090 /* activate -W */
1091 truncate_lines = true;
1092 if (old_s)
1093 /* adapt HP-UX and SunOS: -s = no separator;
1094 activate -S */
1095 use_col_separator = true;
1097 else
1098 /* old -w sets width with columns only
1099 activate -J */
1100 join_lines = true;
1102 else if (!use_col_separator)
1104 /* No -S option read */
1105 if (old_s && (parallel_files || explicit_columns))
1107 if (!truncate_lines)
1109 /* old -s (without -w and -W) annuls column alignment,
1110 uses fields, activate -J */
1111 join_lines = true;
1112 if (col_sep_length > 0)
1113 /* activate -S */
1114 use_col_separator = true;
1116 else
1117 /* with -W */
1118 /* adapt HP-UX and SunOS: -s = no separator;
1119 activate -S */
1120 use_col_separator = true;
1125 for (; optind < argc; optind++)
1127 file_names[n_files++] = argv[optind];
1130 if (n_files == 0)
1132 /* No file arguments specified; read from standard input. */
1133 print_files (0, NULL);
1135 else
1137 if (parallel_files)
1138 print_files (n_files, file_names);
1139 else
1141 for (unsigned int i = 0; i < n_files; i++)
1142 print_files (1, &file_names[i]);
1146 cleanup ();
1148 if (have_read_stdin && fclose (stdin) == EOF)
1149 die (EXIT_FAILURE, errno, _("standard input"));
1150 main_exit (failed_opens ? EXIT_FAILURE : EXIT_SUCCESS);
1153 /* Parse numeric arguments, ensuring MIN <= number <= INT_MAX. */
1155 static void
1156 getoptnum (char const *n_str, int min, int *num, char const *err)
1158 intmax_t tnum = xdectoimax (n_str, min, INT_MAX, "", err, 0);
1159 *num = tnum;
1162 /* Parse options of the form -scNNN.
1164 Example: -nck, where 'n' is the option, c is the optional number
1165 separator, and k is the optional width of the field used when printing
1166 a number. */
1168 static void
1169 getoptarg (char *arg, char switch_char, char *character, int *number)
1171 if (!ISDIGIT (*arg))
1172 *character = *arg++;
1173 if (*arg)
1175 long int tmp_long;
1176 strtol_error e = xstrtol (arg, NULL, 10, &tmp_long, "");
1177 if (e == LONGINT_OK)
1179 if (tmp_long <= 0)
1180 e = LONGINT_INVALID;
1181 else if (INT_MAX < tmp_long)
1182 e = LONGINT_OVERFLOW;
1184 if (e != LONGINT_OK)
1186 error (0, e & LONGINT_OVERFLOW ? EOVERFLOW : 0,
1187 _("'-%c' extra characters or invalid number in the argument: %s"),
1188 switch_char, quote (arg));
1189 usage (EXIT_FAILURE);
1191 *number = tmp_long;
1195 /* Set parameters related to formatting. */
1197 static void
1198 init_parameters (int number_of_files)
1200 int chars_used_by_number = 0;
1202 lines_per_body = lines_per_page - lines_per_header - lines_per_footer;
1203 if (lines_per_body <= 0)
1205 extremities = false;
1206 keep_FF = true;
1208 if (extremities == false)
1209 lines_per_body = lines_per_page;
1211 if (double_space)
1212 lines_per_body = lines_per_body / 2;
1214 /* If input is stdin, cannot print parallel files. BSD dumps core
1215 on this. */
1216 if (number_of_files == 0)
1217 parallel_files = false;
1219 if (parallel_files)
1220 columns = number_of_files;
1222 /* One file, multi columns down: -b option is set to get a consistent
1223 formulation with "FF set by hand" in input files. */
1224 if (storing_columns)
1225 balance_columns = true;
1227 /* Tabification is assumed for multiple columns. */
1228 if (columns > 1)
1230 if (!use_col_separator)
1232 /* Use default separator */
1233 if (join_lines)
1234 col_sep_string = line_separator;
1235 else
1236 col_sep_string = column_separator;
1238 col_sep_length = 1;
1239 use_col_separator = true;
1241 /* It's rather pointless to define a TAB separator with column
1242 alignment */
1243 else if (!join_lines && col_sep_length == 1 && *col_sep_string == '\t')
1244 col_sep_string = column_separator;
1246 truncate_lines = true;
1247 if (! (col_sep_length == 1 && *col_sep_string == '\t'))
1248 untabify_input = true;
1249 tabify_output = true;
1251 else
1252 storing_columns = false;
1254 /* -J dominates -w in any case */
1255 if (join_lines)
1256 truncate_lines = false;
1258 if (numbered_lines)
1260 int chars_per_default_tab = 8;
1262 line_count = start_line_num;
1264 /* To allow input tab-expansion (-e sensitive) use:
1265 if (number_separator == input_tab_char)
1266 number_width = chars_per_number
1267 + TAB_WIDTH (chars_per_input_tab, chars_per_number); */
1269 /* Estimate chars_per_text without any margin and keep it constant. */
1270 if (number_separator == '\t')
1271 number_width = (chars_per_number
1272 + TAB_WIDTH (chars_per_default_tab, chars_per_number));
1273 else
1274 number_width = chars_per_number + 1;
1276 /* The number is part of the column width unless we are
1277 printing files in parallel. */
1278 if (parallel_files)
1279 chars_used_by_number = number_width;
1282 int sep_chars, useful_chars;
1283 if (INT_MULTIPLY_WRAPV (columns - 1, col_sep_length, &sep_chars))
1284 sep_chars = INT_MAX;
1285 if (INT_SUBTRACT_WRAPV (chars_per_line - chars_used_by_number, sep_chars,
1286 &useful_chars))
1287 useful_chars = 0;
1288 chars_per_column = useful_chars / columns;
1290 if (chars_per_column < 1)
1291 die (EXIT_FAILURE, 0, _("page width too narrow"));
1293 if (numbered_lines)
1295 free (number_buff);
1296 number_buff = xmalloc (MAX (chars_per_number,
1297 INT_STRLEN_BOUND (line_number)) + 1);
1300 /* Pick the maximum between the tab width and the width of an
1301 escape sequence.
1302 The width of an escape sequence (4) isn't the lower limit any longer.
1303 We've to use 8 as the lower limit, if we use chars_per_default_tab = 8
1304 to expand a tab which is not an input_tab-char. */
1305 free (clump_buff);
1306 clump_buff = xmalloc (MAX (8, chars_per_input_tab));
1309 /* Open the necessary files,
1310 maintaining a COLUMN structure for each column.
1312 With multiple files, each column p has a different p->fp.
1313 With single files, each column p has the same p->fp.
1314 Return false if (number_of_files > 0) and no files can be opened,
1315 true otherwise.
1317 With each column/file p, p->full_page_printed is initialized,
1318 see also open_file. */
1320 static bool
1321 init_fps (int number_of_files, char **av)
1323 COLUMN *p;
1325 total_files = 0;
1327 free (column_vector);
1328 column_vector = xnmalloc (columns, sizeof (COLUMN));
1330 if (parallel_files)
1332 int files_left = number_of_files;
1333 for (p = column_vector; files_left--; ++p, ++av)
1335 if (! open_file (*av, p))
1337 --p;
1338 --columns;
1341 if (columns == 0)
1342 return false;
1343 init_header ("", -1);
1345 else
1347 p = column_vector;
1348 if (number_of_files > 0)
1350 if (! open_file (*av, p))
1351 return false;
1352 init_header (*av, fileno (p->fp));
1353 p->lines_stored = 0;
1355 else
1357 p->name = _("standard input");
1358 p->fp = stdin;
1359 have_read_stdin = true;
1360 p->status = OPEN;
1361 p->full_page_printed = false;
1362 ++total_files;
1363 init_header ("", -1);
1364 p->lines_stored = 0;
1367 char const *firstname = p->name;
1368 FILE *firstfp = p->fp;
1369 int i;
1370 for (i = columns - 1, ++p; i; --i, ++p)
1372 p->name = firstname;
1373 p->fp = firstfp;
1374 p->status = OPEN;
1375 p->full_page_printed = false;
1376 p->lines_stored = 0;
1379 files_ready_to_read = total_files;
1380 return true;
1383 /* Determine print_func and char_func, the functions
1384 used by each column for printing and/or storing.
1386 Determine the horizontal position desired when we begin
1387 printing a column (p->start_position). */
1389 static void
1390 init_funcs (void)
1392 int i, h, h_next;
1393 COLUMN *p;
1395 h = chars_per_margin;
1397 if (!truncate_lines)
1398 h_next = ANYWHERE;
1399 else
1401 /* When numbering lines of parallel files, we enlarge the
1402 first column to accommodate the number. Looks better than
1403 the Sys V approach. */
1404 if (parallel_files && numbered_lines)
1405 h_next = h + chars_per_column + number_width;
1406 else
1407 h_next = h + chars_per_column;
1410 /* Enlarge p->start_position of first column to use the same form of
1411 padding_not_printed with all columns. */
1412 h = h + col_sep_length;
1414 /* This loop takes care of all but the rightmost column. */
1416 for (p = column_vector, i = 1; i < columns; ++p, ++i)
1418 if (storing_columns) /* One file, multi columns down. */
1420 p->char_func = store_char;
1421 p->print_func = print_stored;
1423 else
1424 /* One file, multi columns across; or parallel files. */
1426 p->char_func = print_char;
1427 p->print_func = read_line;
1430 /* Number only the first column when printing files in
1431 parallel. */
1432 p->numbered = numbered_lines && (!parallel_files || i == 1);
1433 p->start_position = h;
1435 /* If we don't truncate lines, all start_positions are
1436 ANYWHERE, except the first column's start_position when
1437 using a margin. */
1439 if (!truncate_lines)
1441 h = ANYWHERE;
1442 h_next = ANYWHERE;
1444 else
1446 h = h_next + col_sep_length;
1447 h_next = h + chars_per_column;
1451 /* The rightmost column.
1453 Doesn't need to be stored unless we intend to balance
1454 columns on the last page. */
1455 if (storing_columns && balance_columns)
1457 p->char_func = store_char;
1458 p->print_func = print_stored;
1460 else
1462 p->char_func = print_char;
1463 p->print_func = read_line;
1466 p->numbered = numbered_lines && (!parallel_files || i == 1);
1467 p->start_position = h;
1470 /* Open a file. Return true if successful.
1472 With each file p, p->full_page_printed is initialized,
1473 see also init_fps. */
1475 static bool
1476 open_file (char *name, COLUMN *p)
1478 if (STREQ (name, "-"))
1480 p->name = _("standard input");
1481 p->fp = stdin;
1482 have_read_stdin = true;
1484 else
1486 p->name = name;
1487 p->fp = fopen (name, "r");
1489 if (p->fp == NULL)
1491 failed_opens = true;
1492 if (!ignore_failed_opens)
1493 error (0, errno, "%s", quotef (name));
1494 return false;
1496 fadvise (p->fp, FADVISE_SEQUENTIAL);
1497 p->status = OPEN;
1498 p->full_page_printed = false;
1499 ++total_files;
1500 return true;
1503 /* Close the file in P.
1505 If we aren't dealing with multiple files in parallel, we change
1506 the status of all columns in the column list to reflect the close. */
1508 static void
1509 close_file (COLUMN *p)
1511 COLUMN *q;
1512 int i;
1514 if (p->status == CLOSED)
1515 return;
1517 int err = errno;
1518 if (!ferror (p->fp))
1519 err = 0;
1520 if (fileno (p->fp) == STDIN_FILENO)
1521 clearerr (p->fp);
1522 else if (fclose (p->fp) != 0 && !err)
1523 err = errno;
1524 if (err)
1525 die (EXIT_FAILURE, err, "%s", quotef (p->name));
1527 if (!parallel_files)
1529 for (q = column_vector, i = columns; i; ++q, --i)
1531 q->status = CLOSED;
1532 if (q->lines_stored == 0)
1534 q->lines_to_print = 0;
1538 else
1540 p->status = CLOSED;
1541 p->lines_to_print = 0;
1544 --files_ready_to_read;
1547 /* Put a file on hold until we start a new page,
1548 since we've hit a form feed.
1550 If we aren't dealing with parallel files, we must change the
1551 status of all columns in the column list. */
1553 static void
1554 hold_file (COLUMN *p)
1556 COLUMN *q;
1557 int i;
1559 if (!parallel_files)
1560 for (q = column_vector, i = columns; i; ++q, --i)
1562 if (storing_columns)
1563 q->status = FF_FOUND;
1564 else
1565 q->status = ON_HOLD;
1567 else
1568 p->status = ON_HOLD;
1570 p->lines_to_print = 0;
1571 --files_ready_to_read;
1574 /* Undo hold_file -- go through the column list and change any
1575 ON_HOLD columns to OPEN. Used at the end of each page. */
1577 static void
1578 reset_status (void)
1580 int i = columns;
1581 COLUMN *p;
1583 for (p = column_vector; i; --i, ++p)
1584 if (p->status == ON_HOLD)
1586 p->status = OPEN;
1587 files_ready_to_read++;
1590 if (storing_columns)
1592 if (column_vector->status == CLOSED)
1593 /* We use the info to output an error message in skip_to_page. */
1594 files_ready_to_read = 0;
1595 else
1596 files_ready_to_read = 1;
1600 /* Print a single file, or multiple files in parallel.
1602 Set up the list of columns, opening the necessary files.
1603 Allocate space for storing columns, if necessary.
1604 Skip to first_page_number, if user has asked to skip leading pages.
1605 Determine which functions are appropriate to store/print lines
1606 in each column.
1607 Print the file(s). */
1609 static void
1610 print_files (int number_of_files, char **av)
1612 init_parameters (number_of_files);
1613 if (! init_fps (number_of_files, av))
1614 return;
1615 if (storing_columns)
1616 init_store_cols ();
1618 if (first_page_number > 1)
1620 if (!skip_to_page (first_page_number))
1621 return;
1622 else
1623 page_number = first_page_number;
1625 else
1626 page_number = 1;
1628 init_funcs ();
1630 line_number = line_count;
1631 while (print_page ())
1635 /* Initialize header information.
1636 If DESC is non-negative, it is a file descriptor open to
1637 FILENAME for reading. */
1639 static void
1640 init_header (char const *filename, int desc)
1642 char *buf = NULL;
1643 struct stat st;
1644 struct timespec t;
1645 int ns;
1646 struct tm tm;
1648 /* If parallel files or standard input, use current date. */
1649 if (STREQ (filename, "-"))
1650 desc = -1;
1651 if (0 <= desc && fstat (desc, &st) == 0)
1652 t = get_stat_mtime (&st);
1653 else
1655 static struct timespec timespec;
1656 if (! timespec.tv_sec)
1657 gettime (&timespec);
1658 t = timespec;
1661 ns = t.tv_nsec;
1662 if (localtime_rz (localtz, &t.tv_sec, &tm))
1664 size_t bufsize
1665 = nstrftime (NULL, SIZE_MAX, date_format, &tm, localtz, ns) + 1;
1666 buf = xmalloc (bufsize);
1667 nstrftime (buf, bufsize, date_format, &tm, localtz, ns);
1669 else
1671 char secbuf[INT_BUFSIZE_BOUND (intmax_t)];
1672 buf = xmalloc (sizeof secbuf + MAX (10, INT_BUFSIZE_BOUND (int)));
1673 sprintf (buf, "%s.%09d", timetostr (t.tv_sec, secbuf), ns);
1676 free (date_text);
1677 date_text = buf;
1678 file_text = custom_header ? custom_header : desc < 0 ? "" : filename;
1679 header_width_available = (chars_per_line
1680 - mbswidth (date_text, 0)
1681 - mbswidth (file_text, 0));
1684 /* Set things up for printing a page
1686 Scan through the columns ...
1687 Determine which are ready to print
1688 (i.e., which have lines stored or open files)
1689 Set p->lines_to_print appropriately
1690 (to p->lines_stored if we're storing, or lines_per_body
1691 if we're reading straight from the file)
1692 Keep track of this total so we know when to stop printing */
1694 static void
1695 init_page (void)
1697 int j;
1698 COLUMN *p;
1700 if (storing_columns)
1702 store_columns ();
1703 for (j = columns - 1, p = column_vector; j; --j, ++p)
1705 p->lines_to_print = p->lines_stored;
1708 /* Last column. */
1709 if (balance_columns)
1711 p->lines_to_print = p->lines_stored;
1713 /* Since we're not balancing columns, we don't need to store
1714 the rightmost column. Read it straight from the file. */
1715 else
1717 if (p->status == OPEN)
1719 p->lines_to_print = lines_per_body;
1721 else
1722 p->lines_to_print = 0;
1725 else
1726 for (j = columns, p = column_vector; j; --j, ++p)
1727 if (p->status == OPEN)
1729 p->lines_to_print = lines_per_body;
1731 else
1732 p->lines_to_print = 0;
1735 /* Align empty columns and print separators.
1736 Empty columns will be formed by files with status ON_HOLD or CLOSED
1737 when printing multiple files in parallel. */
1739 static void
1740 align_column (COLUMN *p)
1742 padding_not_printed = p->start_position;
1743 if (col_sep_length < padding_not_printed)
1745 pad_across_to (padding_not_printed - col_sep_length);
1746 padding_not_printed = ANYWHERE;
1749 if (use_col_separator)
1750 print_sep_string ();
1752 if (p->numbered)
1753 add_line_number (p);
1756 /* Print one page.
1758 As long as there are lines left on the page and columns ready to print,
1759 Scan across the column list
1760 if the column has stored lines or the file is open
1761 pad to the appropriate spot
1762 print the column
1763 pad the remainder of the page with \n or \f as requested
1764 reset the status of all files -- any files which where on hold because
1765 of formfeeds are now put back into the lineup. */
1767 static bool
1768 print_page (void)
1770 int j;
1771 int lines_left_on_page;
1772 COLUMN *p;
1774 /* Used as an accumulator (with | operator) of successive values of
1775 pad_vertically. The trick is to set pad_vertically
1776 to false before each run through the inner loop, then after that
1777 loop, it tells us whether a line was actually printed (whether a
1778 newline needs to be output -- or two for double spacing). But those
1779 values have to be accumulated (in pv) so we can invoke pad_down
1780 properly after the outer loop completes. */
1781 bool pv;
1783 init_page ();
1785 if (cols_ready_to_print () == 0)
1786 return false;
1788 if (extremities)
1789 print_a_header = true;
1791 /* Don't pad unless we know a page was printed. */
1792 pad_vertically = false;
1793 pv = false;
1795 lines_left_on_page = lines_per_body;
1796 if (double_space)
1797 lines_left_on_page *= 2;
1799 while (lines_left_on_page > 0 && cols_ready_to_print () > 0)
1801 output_position = 0;
1802 spaces_not_printed = 0;
1803 separators_not_printed = 0;
1804 pad_vertically = false;
1805 align_empty_cols = false;
1806 empty_line = true;
1808 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
1810 input_position = 0;
1811 if (p->lines_to_print > 0 || p->status == FF_FOUND)
1813 FF_only = false;
1814 padding_not_printed = p->start_position;
1815 if (!(p->print_func) (p))
1816 read_rest_of_line (p);
1817 pv |= pad_vertically;
1819 --p->lines_to_print;
1820 if (p->lines_to_print <= 0)
1822 if (cols_ready_to_print () == 0)
1823 break;
1826 /* File p changed its status to ON_HOLD or CLOSED */
1827 if (parallel_files && p->status != OPEN)
1829 if (empty_line)
1830 align_empty_cols = true;
1831 else if (p->status == CLOSED
1832 || (p->status == ON_HOLD && FF_only))
1833 align_column (p);
1836 else if (parallel_files)
1838 /* File status ON_HOLD or CLOSED */
1839 if (empty_line)
1840 align_empty_cols = true;
1841 else
1842 align_column (p);
1845 /* We need it also with an empty column */
1846 if (use_col_separator)
1847 ++separators_not_printed;
1850 if (pad_vertically)
1852 putchar ('\n');
1853 --lines_left_on_page;
1856 if (cols_ready_to_print () == 0 && !extremities)
1857 break;
1859 if (double_space && pv)
1861 putchar ('\n');
1862 --lines_left_on_page;
1866 if (lines_left_on_page == 0)
1867 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
1868 if (p->status == OPEN)
1869 p->full_page_printed = true;
1871 pad_vertically = pv;
1873 if (pad_vertically && extremities)
1874 pad_down (lines_left_on_page + lines_per_footer);
1875 else if (keep_FF && print_a_FF)
1877 putchar ('\f');
1878 print_a_FF = false;
1881 if (last_page_number < ++page_number)
1882 return false; /* Stop printing with LAST_PAGE */
1884 reset_status (); /* Change ON_HOLD to OPEN. */
1886 return true; /* More pages to go. */
1889 /* Allocate space for storing columns.
1891 This is necessary when printing multiple columns from a single file.
1892 Lines are stored consecutively in buff, separated by '\0'.
1894 The following doesn't apply any longer - any tuning possible?
1895 (We can't use a fixed offset since with the '-s' flag lines aren't
1896 truncated.)
1898 We maintain a list (line_vector) of pointers to the beginnings
1899 of lines in buff. We allocate one more than the number of lines
1900 because the last entry tells us the index of the last character,
1901 which we need to know in order to print the last line in buff. */
1903 static void
1904 init_store_cols (void)
1906 int total_lines, total_lines_1, chars_per_column_1, chars_if_truncate;
1907 if (INT_MULTIPLY_WRAPV (lines_per_body, columns, &total_lines)
1908 || INT_ADD_WRAPV (total_lines, 1, &total_lines_1)
1909 || INT_ADD_WRAPV (chars_per_column, 1, &chars_per_column_1)
1910 || INT_MULTIPLY_WRAPV (total_lines, chars_per_column_1,
1911 &chars_if_truncate))
1912 integer_overflow ();
1914 free (line_vector);
1915 /* FIXME: here's where it was allocated. */
1916 line_vector = xnmalloc (total_lines_1, sizeof *line_vector);
1918 free (end_vector);
1919 end_vector = xnmalloc (total_lines, sizeof *end_vector);
1921 free (buff);
1922 buff = xnmalloc (chars_if_truncate, use_col_separator + 1);
1923 buff_allocated = chars_if_truncate; /* Tune this. */
1924 buff_allocated *= use_col_separator + 1;
1927 /* Store all but the rightmost column.
1928 (Used when printing a single file in multiple downward columns)
1930 For each column
1931 set p->current_line to be the index in line_vector of the
1932 first line in the column
1933 For each line in the column
1934 store the line in buff
1935 add to line_vector the index of the line's first char
1936 buff_start is the index in buff of the first character in the
1937 current line. */
1939 static void
1940 store_columns (void)
1942 int i, j;
1943 unsigned int line = 0;
1944 unsigned int buff_start;
1945 int last_col; /* The rightmost column which will be saved in buff */
1946 COLUMN *p;
1948 buff_current = 0;
1949 buff_start = 0;
1951 if (balance_columns)
1952 last_col = columns;
1953 else
1954 last_col = columns - 1;
1956 for (i = 1, p = column_vector; i <= last_col; ++i, ++p)
1957 p->lines_stored = 0;
1959 for (i = 1, p = column_vector; i <= last_col && files_ready_to_read;
1960 ++i, ++p)
1962 p->current_line = line;
1963 for (j = lines_per_body; j && files_ready_to_read; --j)
1965 if (p->status == OPEN) /* Redundant. Clean up. */
1967 input_position = 0;
1969 if (!read_line (p))
1970 read_rest_of_line (p);
1972 if (p->status == OPEN
1973 || buff_start != buff_current)
1975 ++p->lines_stored;
1976 line_vector[line] = buff_start;
1977 end_vector[line++] = input_position;
1978 buff_start = buff_current;
1983 /* Keep track of the location of the last char in buff. */
1984 line_vector[line] = buff_start;
1986 if (balance_columns)
1987 balance (line);
1990 static void
1991 balance (int total_stored)
1993 COLUMN *p;
1994 int i, lines;
1995 int first_line = 0;
1997 for (i = 1, p = column_vector; i <= columns; ++i, ++p)
1999 lines = total_stored / columns;
2000 if (i <= total_stored % columns)
2001 ++lines;
2003 p->lines_stored = lines;
2004 p->current_line = first_line;
2006 first_line += lines;
2010 /* Store a character in the buffer. */
2012 static void
2013 store_char (char c)
2015 if (buff_current >= buff_allocated)
2017 /* May be too generous. */
2018 buff = X2REALLOC (buff, &buff_allocated);
2020 buff[buff_current++] = c;
2023 static void
2024 add_line_number (COLUMN *p)
2026 int i;
2027 char *s;
2028 int num_width;
2030 /* Cutting off the higher-order digits is more informative than
2031 lower-order cut off. */
2032 num_width = sprintf (number_buff, "%*d", chars_per_number, line_number);
2033 line_number++;
2034 s = number_buff + (num_width - chars_per_number);
2035 for (i = chars_per_number; i > 0; i--)
2036 (p->char_func) (*s++);
2038 if (columns > 1)
2040 /* Tabification is assumed for multiple columns, also for n-separators,
2041 but 'default n-separator = TAB' hasn't been given priority over
2042 equal column_width also specified by POSIX. */
2043 if (number_separator == '\t')
2045 i = number_width - chars_per_number;
2046 while (i-- > 0)
2047 (p->char_func) (' ');
2049 else
2050 (p->char_func) (number_separator);
2052 else
2053 /* To comply with POSIX, we avoid any expansion of default TAB
2054 separator with a single column output. No column_width requirement
2055 has to be considered. */
2057 (p->char_func) (number_separator);
2058 if (number_separator == '\t')
2059 output_position = POS_AFTER_TAB (chars_per_output_tab,
2060 output_position);
2063 if (truncate_lines && !parallel_files)
2064 input_position += number_width;
2067 /* Print (or store) padding until the current horizontal position
2068 is position. */
2070 static void
2071 pad_across_to (int position)
2073 int h = output_position;
2075 if (tabify_output)
2076 spaces_not_printed = position - output_position;
2077 else
2079 while (++h <= position)
2080 putchar (' ');
2081 output_position = position;
2085 /* Pad to the bottom of the page.
2087 If the user has requested a formfeed, use one.
2088 Otherwise, use newlines. */
2090 static void
2091 pad_down (unsigned int lines)
2093 if (use_form_feed)
2094 putchar ('\f');
2095 else
2096 for (unsigned int i = lines; i; --i)
2097 putchar ('\n');
2100 /* Read the rest of the line.
2102 Read from the current column's file until an end of line is
2103 hit. Used when we've truncated a line and we no longer need
2104 to print or store its characters. */
2106 static void
2107 read_rest_of_line (COLUMN *p)
2109 int c;
2110 FILE *f = p->fp;
2112 while ((c = getc (f)) != '\n')
2114 if (c == '\f')
2116 if ((c = getc (f)) != '\n')
2117 ungetc (c, f);
2118 if (keep_FF)
2119 print_a_FF = true;
2120 hold_file (p);
2121 break;
2123 else if (c == EOF)
2125 close_file (p);
2126 break;
2131 /* Read a line with skip_to_page.
2133 Read from the current column's file until an end of line is
2134 hit. Used when we read full lines to skip pages.
2135 With skip_to_page we have to check for FF-coincidence which is done
2136 in function read_line otherwise.
2137 Count lines of skipped pages to find the line number of 1st page
2138 printed relative to 1st line of input file (start_line_num). */
2140 static void
2141 skip_read (COLUMN *p, int column_number)
2143 int c;
2144 FILE *f = p->fp;
2145 int i;
2146 bool single_ff = false;
2147 COLUMN *q;
2149 /* Read 1st character in a line or any character succeeding a FF */
2150 if ((c = getc (f)) == '\f' && p->full_page_printed)
2151 /* A FF-coincidence with a previous full_page_printed.
2152 To avoid an additional empty page, eliminate the FF */
2153 if ((c = getc (f)) == '\n')
2154 c = getc (f);
2156 p->full_page_printed = false;
2158 /* 1st character a FF means a single FF without any printable
2159 characters. Don't count it as a line with -n option. */
2160 if (c == '\f')
2161 single_ff = true;
2163 /* Preparing for a FF-coincidence: Maybe we finish that page
2164 without a FF found */
2165 if (last_line)
2166 p->full_page_printed = true;
2168 while (c != '\n')
2170 if (c == '\f')
2172 /* No FF-coincidence possible,
2173 no catching up of a FF-coincidence with next page */
2174 if (last_line)
2176 if (!parallel_files)
2177 for (q = column_vector, i = columns; i; ++q, --i)
2178 q->full_page_printed = false;
2179 else
2180 p->full_page_printed = false;
2183 if ((c = getc (f)) != '\n')
2184 ungetc (c, f);
2185 hold_file (p);
2186 break;
2188 else if (c == EOF)
2190 close_file (p);
2191 break;
2193 c = getc (f);
2196 if (skip_count)
2197 if ((!parallel_files || column_number == 1) && !single_ff)
2198 ++line_count;
2201 /* If we're tabifying output,
2203 When print_char encounters white space it keeps track
2204 of our desired horizontal position and delays printing
2205 until this function is called. */
2207 static void
2208 print_white_space (void)
2210 int h_new;
2211 int h_old = output_position;
2212 int goal = h_old + spaces_not_printed;
2214 while (goal - h_old > 1
2215 && (h_new = POS_AFTER_TAB (chars_per_output_tab, h_old)) <= goal)
2217 putchar (output_tab_char);
2218 h_old = h_new;
2220 while (++h_old <= goal)
2221 putchar (' ');
2223 output_position = goal;
2224 spaces_not_printed = 0;
2227 /* Print column separators.
2229 We keep a count until we know that we'll be printing a line,
2230 then print_sep_string() is called. */
2232 static void
2233 print_sep_string (void)
2235 char const *s = col_sep_string;
2236 int l = col_sep_length;
2238 if (separators_not_printed <= 0)
2240 /* We'll be starting a line with chars_per_margin, anything else? */
2241 if (spaces_not_printed > 0)
2242 print_white_space ();
2244 else
2246 for (; separators_not_printed > 0; --separators_not_printed)
2248 while (l-- > 0)
2250 /* 3 types of sep_strings: spaces only, spaces and chars,
2251 chars only */
2252 if (*s == ' ')
2254 /* We're tabifying output; consecutive spaces in
2255 sep_string may have to be converted to tabs */
2256 s++;
2257 ++spaces_not_printed;
2259 else
2261 if (spaces_not_printed > 0)
2262 print_white_space ();
2263 putchar (*s++);
2264 ++output_position;
2267 /* sep_string ends with some spaces */
2268 if (spaces_not_printed > 0)
2269 print_white_space ();
2274 /* Print (or store, depending on p->char_func) a clump of N
2275 characters. */
2277 static void
2278 print_clump (COLUMN *p, int n, char *clump)
2280 while (n--)
2281 (p->char_func) (*clump++);
2284 /* Print a character.
2286 Update the following comment: process-char hasn't been used any
2287 longer.
2288 If we're tabifying, all tabs have been converted to spaces by
2289 process_char(). Keep a count of consecutive spaces, and when
2290 a nonspace is encountered, call print_white_space() to print the
2291 required number of tabs and spaces. */
2293 static void
2294 print_char (char c)
2296 if (tabify_output)
2298 if (c == ' ')
2300 ++spaces_not_printed;
2301 return;
2303 else if (spaces_not_printed > 0)
2304 print_white_space ();
2306 /* Nonprintables are assumed to have width 0, except '\b'. */
2307 if (! isprint (to_uchar (c)))
2309 if (c == '\b')
2310 --output_position;
2312 else
2313 ++output_position;
2315 putchar (c);
2318 /* Skip to page PAGE before printing.
2319 PAGE may be larger than total number of pages. */
2321 static bool
2322 skip_to_page (uintmax_t page)
2324 for (uintmax_t n = 1; n < page; ++n)
2326 COLUMN *p;
2327 int j;
2329 for (int i = 1; i < lines_per_body; ++i)
2331 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
2332 if (p->status == OPEN)
2333 skip_read (p, j);
2335 last_line = true;
2336 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
2337 if (p->status == OPEN)
2338 skip_read (p, j);
2340 if (storing_columns) /* change FF_FOUND to ON_HOLD */
2341 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
2342 if (p->status != CLOSED)
2343 p->status = ON_HOLD;
2345 reset_status ();
2346 last_line = false;
2348 if (files_ready_to_read < 1)
2350 /* It's very helpful, normally the total number of pages is
2351 not known in advance. */
2352 error (0, 0,
2353 _("starting page number %"PRIuMAX
2354 " exceeds page count %"PRIuMAX),
2355 page, n);
2356 break;
2359 return files_ready_to_read > 0;
2362 /* Print a header.
2364 Formfeeds are assumed to use up two lines at the beginning of
2365 the page. */
2367 static void
2368 print_header (void)
2370 char page_text[256 + INT_STRLEN_BOUND (page_number)];
2371 int available_width;
2372 int lhs_spaces;
2373 int rhs_spaces;
2375 output_position = 0;
2376 pad_across_to (chars_per_margin);
2377 print_white_space ();
2379 if (page_number == 0)
2380 die (EXIT_FAILURE, 0, _("page number overflow"));
2382 /* The translator must ensure that formatting the translation of
2383 "Page %"PRIuMAX does not generate more than (sizeof page_text - 1)
2384 bytes. */
2385 sprintf (page_text, _("Page %"PRIuMAX), page_number);
2386 available_width = header_width_available - mbswidth (page_text, 0);
2387 available_width = MAX (0, available_width);
2388 lhs_spaces = available_width >> 1;
2389 rhs_spaces = available_width - lhs_spaces;
2391 printf ("\n\n%*s%s%*s%s%*s%s\n\n\n",
2392 chars_per_margin, "",
2393 date_text, lhs_spaces, " ",
2394 file_text, rhs_spaces, " ", page_text);
2396 print_a_header = false;
2397 output_position = 0;
2400 /* Print (or store, if p->char_func is store_char()) a line.
2402 Read a character to determine whether we have a line or not.
2403 (We may hit EOF, \n, or \f)
2405 Once we know we have a line,
2406 set pad_vertically = true, meaning it's safe
2407 to pad down at the end of the page, since we do have a page.
2408 print a header if needed.
2409 pad across to padding_not_printed if needed.
2410 print any separators which need to be printed.
2411 print a line number if it needs to be printed.
2413 Print the clump which corresponds to the first character.
2415 Enter a loop and keep printing until an end of line condition
2416 exists, or until we exceed chars_per_column.
2418 Return false if we exceed chars_per_column before reading
2419 an end of line character, true otherwise. */
2421 static bool
2422 read_line (COLUMN *p)
2424 int c;
2425 int chars;
2426 int last_input_position;
2427 int j, k;
2428 COLUMN *q;
2430 /* read 1st character in each line or any character succeeding a FF: */
2431 c = getc (p->fp);
2433 last_input_position = input_position;
2435 if (c == '\f' && p->full_page_printed)
2436 if ((c = getc (p->fp)) == '\n')
2437 c = getc (p->fp);
2438 p->full_page_printed = false;
2440 switch (c)
2442 case '\f':
2443 if ((c = getc (p->fp)) != '\n')
2444 ungetc (c, p->fp);
2445 FF_only = true;
2446 if (print_a_header && !storing_columns)
2448 pad_vertically = true;
2449 print_header ();
2451 else if (keep_FF)
2452 print_a_FF = true;
2453 hold_file (p);
2454 return true;
2455 case EOF:
2456 close_file (p);
2457 return true;
2458 case '\n':
2459 break;
2460 default:
2461 chars = char_to_clump (c);
2464 if (truncate_lines && input_position > chars_per_column)
2466 input_position = last_input_position;
2467 return false;
2470 if (p->char_func != store_char)
2472 pad_vertically = true;
2474 if (print_a_header && !storing_columns)
2475 print_header ();
2477 if (parallel_files && align_empty_cols)
2479 /* We have to align empty columns at the beginning of a line. */
2480 k = separators_not_printed;
2481 separators_not_printed = 0;
2482 for (j = 1, q = column_vector; j <= k; ++j, ++q)
2484 align_column (q);
2485 separators_not_printed += 1;
2487 padding_not_printed = p->start_position;
2488 if (truncate_lines)
2489 spaces_not_printed = chars_per_column;
2490 else
2491 spaces_not_printed = 0;
2492 align_empty_cols = false;
2495 if (col_sep_length < padding_not_printed)
2497 pad_across_to (padding_not_printed - col_sep_length);
2498 padding_not_printed = ANYWHERE;
2501 if (use_col_separator)
2502 print_sep_string ();
2505 if (p->numbered)
2506 add_line_number (p);
2508 empty_line = false;
2509 if (c == '\n')
2510 return true;
2512 print_clump (p, chars, clump_buff);
2514 while (true)
2516 c = getc (p->fp);
2518 switch (c)
2520 case '\n':
2521 return true;
2522 case '\f':
2523 if ((c = getc (p->fp)) != '\n')
2524 ungetc (c, p->fp);
2525 if (keep_FF)
2526 print_a_FF = true;
2527 hold_file (p);
2528 return true;
2529 case EOF:
2530 close_file (p);
2531 return true;
2534 last_input_position = input_position;
2535 chars = char_to_clump (c);
2536 if (truncate_lines && input_position > chars_per_column)
2538 input_position = last_input_position;
2539 return false;
2542 print_clump (p, chars, clump_buff);
2546 /* Print a line from buff.
2548 If this function has been called, we know we have "something to
2549 print". But it remains to be seen whether we have a real text page
2550 or an empty page (a single form feed) with/without a header only.
2551 Therefore first we set pad_vertically to true and print a header
2552 if necessary.
2553 If FF_FOUND and we are using -t|-T option we omit any newline by
2554 setting pad_vertically to false (see print_page).
2555 Otherwise we pad across if necessary, print separators if necessary
2556 and text of COLUMN *p.
2558 Return true, meaning there is no need to call read_rest_of_line. */
2560 static bool
2561 print_stored (COLUMN *p)
2563 COLUMN *q;
2565 int line = p->current_line++;
2566 char *first = &buff[line_vector[line]];
2567 /* FIXME
2568 UMR: Uninitialized memory read:
2569 * This is occurring while in:
2570 print_stored [pr.c:2239]
2571 * Reading 4 bytes from 0x5148c in the heap.
2572 * Address 0x5148c is 4 bytes into a malloc'd block at 0x51488 of 676 bytes
2573 * This block was allocated from:
2574 malloc [rtlib.o]
2575 xmalloc [xmalloc.c:94]
2576 init_store_cols [pr.c:1648]
2578 char *last = &buff[line_vector[line + 1]];
2580 pad_vertically = true;
2582 if (print_a_header)
2583 print_header ();
2585 if (p->status == FF_FOUND)
2587 int i;
2588 for (i = 1, q = column_vector; i <= columns; ++i, ++q)
2589 q->status = ON_HOLD;
2590 if (column_vector->lines_to_print <= 0)
2592 if (!extremities)
2593 pad_vertically = false;
2594 return true; /* print a header only */
2598 if (col_sep_length < padding_not_printed)
2600 pad_across_to (padding_not_printed - col_sep_length);
2601 padding_not_printed = ANYWHERE;
2604 if (use_col_separator)
2605 print_sep_string ();
2607 while (first != last)
2608 print_char (*first++);
2610 if (spaces_not_printed == 0)
2612 output_position = p->start_position + end_vector[line];
2613 if (p->start_position - col_sep_length == chars_per_margin)
2614 output_position -= col_sep_length;
2617 return true;
2620 /* Convert a character to the proper format and return the number of
2621 characters in the resulting clump. Increment input_position by
2622 the width of the clump.
2624 Tabs are converted to clumps of spaces.
2625 Nonprintable characters may be converted to clumps of escape
2626 sequences or control prefixes.
2628 Note: the width of a clump is not necessarily equal to the number of
2629 characters in clump_buff. (e.g., the width of '\b' is -1, while the
2630 number of characters is 1.) */
2632 static int
2633 char_to_clump (char c)
2635 unsigned char uc = c;
2636 char *s = clump_buff;
2637 int i;
2638 char esc_buff[4];
2639 int width;
2640 int chars;
2641 int chars_per_c = 8;
2643 if (c == input_tab_char)
2644 chars_per_c = chars_per_input_tab;
2646 if (c == input_tab_char || c == '\t')
2648 width = TAB_WIDTH (chars_per_c, input_position);
2650 if (untabify_input)
2652 for (i = width; i; --i)
2653 *s++ = ' ';
2654 chars = width;
2656 else
2658 *s = c;
2659 chars = 1;
2663 else if (! isprint (uc))
2665 if (use_esc_sequence)
2667 width = 4;
2668 chars = 4;
2669 *s++ = '\\';
2670 sprintf (esc_buff, "%03o", uc);
2671 for (i = 0; i <= 2; ++i)
2672 *s++ = esc_buff[i];
2674 else if (use_cntrl_prefix)
2676 if (uc < 0200)
2678 width = 2;
2679 chars = 2;
2680 *s++ = '^';
2681 *s = c ^ 0100;
2683 else
2685 width = 4;
2686 chars = 4;
2687 *s++ = '\\';
2688 sprintf (esc_buff, "%03o", uc);
2689 for (i = 0; i <= 2; ++i)
2690 *s++ = esc_buff[i];
2693 else if (c == '\b')
2695 width = -1;
2696 chars = 1;
2697 *s = c;
2699 else
2701 width = 0;
2702 chars = 1;
2703 *s = c;
2706 else
2708 width = 1;
2709 chars = 1;
2710 *s = c;
2713 /* Too many backspaces must put us in position 0 -- never negative. */
2714 if (width < 0 && input_position == 0)
2716 chars = 0;
2717 input_position = 0;
2719 else if (width < 0 && input_position <= -width)
2720 input_position = 0;
2721 else
2722 input_position += width;
2724 return chars;
2727 /* We've just printed some files and need to clean up things before
2728 looking for more options and printing the next batch of files.
2730 Free everything we've xmalloc'ed, except 'header'. */
2732 static void
2733 cleanup (void)
2735 free (number_buff);
2736 free (clump_buff);
2737 free (column_vector);
2738 free (line_vector);
2739 free (end_vector);
2740 free (buff);
2743 /* Complain, print a usage message, and die. */
2745 void
2746 usage (int status)
2748 if (status != EXIT_SUCCESS)
2749 emit_try_help ();
2750 else
2752 printf (_("\
2753 Usage: %s [OPTION]... [FILE]...\n\
2755 program_name);
2757 fputs (_("\
2758 Paginate or columnate FILE(s) for printing.\n\
2759 "), stdout);
2761 emit_stdin_note ();
2762 emit_mandatory_arg_note ();
2764 fputs (_("\
2765 +FIRST_PAGE[:LAST_PAGE], --pages=FIRST_PAGE[:LAST_PAGE]\n\
2766 begin [stop] printing with page FIRST_[LAST_]PAGE\n\
2767 -COLUMN, --columns=COLUMN\n\
2768 output COLUMN columns and print columns down,\n\
2769 unless -a is used. Balance number of lines in the\n\
2770 columns on each page\n\
2771 "), stdout);
2772 fputs (_("\
2773 -a, --across print columns across rather than down, used together\n\
2774 with -COLUMN\n\
2775 -c, --show-control-chars\n\
2776 use hat notation (^G) and octal backslash notation\n\
2777 -d, --double-space\n\
2778 double space the output\n\
2779 "), stdout);
2780 fputs (_("\
2781 -D, --date-format=FORMAT\n\
2782 use FORMAT for the header date\n\
2783 -e[CHAR[WIDTH]], --expand-tabs[=CHAR[WIDTH]]\n\
2784 expand input CHARs (TABs) to tab WIDTH (8)\n\
2785 -F, -f, --form-feed\n\
2786 use form feeds instead of newlines to separate pages\n\
2787 (by a 3-line page header with -F or a 5-line header\n\
2788 and trailer without -F)\n\
2789 "), stdout);
2790 fputs (_("\
2791 -h, --header=HEADER\n\
2792 use a centered HEADER instead of filename in page header,\n\
2793 -h \"\" prints a blank line, don't use -h\"\"\n\
2794 -i[CHAR[WIDTH]], --output-tabs[=CHAR[WIDTH]]\n\
2795 replace spaces with CHARs (TABs) to tab WIDTH (8)\n\
2796 -J, --join-lines merge full lines, turns off -W line truncation, no column\n\
2797 alignment, --sep-string[=STRING] sets separators\n\
2798 "), stdout);
2799 fputs (_("\
2800 -l, --length=PAGE_LENGTH\n\
2801 set the page length to PAGE_LENGTH (66) lines\n\
2802 (default number of lines of text 56, and with -F 63).\n\
2803 implies -t if PAGE_LENGTH <= 10\n\
2804 "), stdout);
2805 fputs (_("\
2806 -m, --merge print all files in parallel, one in each column,\n\
2807 truncate lines, but join lines of full length with -J\n\
2808 "), stdout);
2809 fputs (_("\
2810 -n[SEP[DIGITS]], --number-lines[=SEP[DIGITS]]\n\
2811 number lines, use DIGITS (5) digits, then SEP (TAB),\n\
2812 default counting starts with 1st line of input file\n\
2813 -N, --first-line-number=NUMBER\n\
2814 start counting with NUMBER at 1st line of first\n\
2815 page printed (see +FIRST_PAGE)\n\
2816 "), stdout);
2817 fputs (_("\
2818 -o, --indent=MARGIN\n\
2819 offset each line with MARGIN (zero) spaces, do not\n\
2820 affect -w or -W, MARGIN will be added to PAGE_WIDTH\n\
2821 -r, --no-file-warnings\n\
2822 omit warning when a file cannot be opened\n\
2823 "), stdout);
2824 fputs (_("\
2825 -s[CHAR], --separator[=CHAR]\n\
2826 separate columns by a single character, default for CHAR\n\
2827 is the <TAB> character without -w and \'no char\' with -w.\
2829 -s[CHAR] turns off line truncation of all 3 column\n\
2830 options (-COLUMN|-a -COLUMN|-m) except -w is set\n\
2831 "), stdout);
2832 fputs (_("\
2833 -S[STRING], --sep-string[=STRING]\n\
2834 separate columns by STRING,\n\
2835 without -S: Default separator <TAB> with -J and <space>\n\
2836 otherwise (same as -S\" \"), no effect on column options\n\
2837 "), stdout);
2838 fputs (_("\
2839 -t, --omit-header omit page headers and trailers;\n\
2840 implied if PAGE_LENGTH <= 10\n\
2841 "), stdout);
2842 fputs (_("\
2843 -T, --omit-pagination\n\
2844 omit page headers and trailers, eliminate any pagination\n\
2845 by form feeds set in input files\n\
2846 -v, --show-nonprinting\n\
2847 use octal backslash notation\n\
2848 -w, --width=PAGE_WIDTH\n\
2849 set page width to PAGE_WIDTH (72) characters for\n\
2850 multiple text-column output only, -s[char] turns off (72)\n\
2851 "), stdout);
2852 fputs (_("\
2853 -W, --page-width=PAGE_WIDTH\n\
2854 set page width to PAGE_WIDTH (72) characters always,\n\
2855 truncate lines, except -J option is set, no interference\n\
2856 with -S or -s\n\
2857 "), stdout);
2858 fputs (HELP_OPTION_DESCRIPTION, stdout);
2859 fputs (VERSION_OPTION_DESCRIPTION, stdout);
2860 emit_ancillary_info (PROGRAM_NAME);
2862 exit (status);