printf: add indexed argument support
[coreutils.git] / src / pr.c
blob88a330bc0c34961298b8ebb04b5c29102c40b6e1
1 /* pr -- convert text files for printing.
2 Copyright (C) 1988-2024 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 interference 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 nonprintable 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 nonprintable 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 <ctype.h>
313 #include <getopt.h>
314 #include <sys/types.h>
315 #include "system.h"
316 #include "fadvise.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 #include "xstrtol-error.h"
325 #include "xdectoint.h"
327 /* The official name of this program (e.g., no 'g' prefix). */
328 #define PROGRAM_NAME "pr"
330 #define AUTHORS \
331 proper_name ("Pete TerMaat"), \
332 proper_name ("Roland Huebner")
334 /* Used with start_position in the struct COLUMN described below.
335 If start_position == ANYWHERE, we aren't truncating columns and
336 can begin printing a column anywhere. Otherwise we must pad to
337 the horizontal position start_position. */
338 #define ANYWHERE 0
340 /* Each column has one of these structures allocated for it.
341 If we're only dealing with one file, fp is the same for all
342 columns.
344 The general strategy is to spend time setting up these column
345 structures (storing columns if necessary), after which printing
346 is a matter of flitting from column to column and calling
347 print_func.
349 Parallel files, single files printing across in multiple
350 columns, and single files printing down in multiple columns all
351 fit the same printing loop.
353 print_func Function used to print lines in this column.
354 If we're storing this column it will be
355 print_stored(), Otherwise it will be read_line().
357 char_func Function used to process characters in this column.
358 If we're storing this column it will be store_char(),
359 otherwise it will be print_char().
361 current_line Index of the current entry in line_vector, which
362 contains the index of the first character of the
363 current line in buff[].
365 lines_stored Number of lines in this column which are stored in
366 buff.
368 lines_to_print If we're storing this column, lines_to_print is
369 the number of stored_lines which remain to be
370 printed. Otherwise it is the number of lines
371 we can print without exceeding lines_per_body.
373 start_position The horizontal position we want to be in before we
374 print the first character in this column.
376 numbered True means precede this column with a line number. */
378 /* FIXME: There are many unchecked integer overflows in this file,
379 that will cause this command to misbehave given large inputs or
380 options. Many of the "int" values below should be "size_t" or
381 something else like that. */
383 struct COLUMN;
384 struct COLUMN
386 FILE *fp; /* Input stream for this column. */
387 char const *name; /* File name. */
388 enum
390 OPEN,
391 FF_FOUND, /* used with -b option, set with \f, changed
392 to ON_HOLD after print_header */
393 ON_HOLD, /* Hit a form feed. */
394 CLOSED
396 status; /* Status of the file pointer. */
398 /* Func to print lines in this col. */
399 bool (*print_func) (struct COLUMN *);
401 /* Func to print/store chars in this col. */
402 void (*char_func) (char);
404 int current_line; /* Index of current place in line_vector. */
405 int lines_stored; /* Number of lines stored in buff. */
406 int lines_to_print; /* No. lines stored or space left on page. */
407 int start_position; /* Horizontal position of first char. */
408 bool numbered;
409 bool full_page_printed; /* True means printed without a FF found. */
411 /* p->full_page_printed controls a special case of "FF set by hand":
412 True means a full page has been printed without FF found. To avoid an
413 additional empty page we have to ignore a FF immediately following in
414 the next line. */
417 typedef struct COLUMN COLUMN;
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 int getoptnum (char const *n_str, int min, char const *errfmt);
429 static void getoptarg (char *arg, char switch_char, char *character,
430 int *number);
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 (unsigned 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 (char const *optarg_S);
448 /* All of the columns to print. */
449 static COLUMN *column_vector;
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;
457 /* Index of the position in buff where the next character
458 will be stored. */
459 static unsigned int buff_current;
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;
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;
471 /* Array of horizontal 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;
478 /* (-m) True means we're printing multiple files in parallel. */
479 static bool parallel_files = false;
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;
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;
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;
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;
501 /* (-t|-T) False means we aren't printing headers and footers. */
502 static bool extremities = true;
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;
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;
513 /* (-f) True means use formfeeds instead of newlines to separate pages. */
514 static bool use_form_feed = false;
516 /* True means we have read the standard input. */
517 static bool have_read_stdin = false;
519 /* True means the -a flag has been given. */
520 static bool print_across_flag = false;
522 /* True means we're printing one file in multiple (>1) downward columns. */
523 static bool storing_columns = true;
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;
531 /* (-l) Number of lines on a page, including header and footer lines. */
532 static int lines_per_page = 66;
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 };
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;
544 /* (-w|W) True means we truncate lines longer than chars_per_column. */
545 static bool truncate_lines = false;
547 /* (-J) True means we join lines without any line truncation. -J
548 dominates -w option. */
549 static bool join_lines = false;
551 /* Number of characters in a column. Based on col_sep_length and
552 page width. */
553 static int chars_per_column;
555 /* (-e) True means convert tabs to spaces on input. */
556 static bool untabify_input = false;
558 /* (-e) The input tab character. */
559 static char input_tab_char = '\t';
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;
565 /* (-i) True means convert spaces to tabs on output. */
566 static bool tabify_output = false;
568 /* (-i) The output tab character. */
569 static char output_tab_char = '\t';
571 /* (-i) The width of the output tab. */
572 static int chars_per_output_tab = 8;
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;
579 /* (-o) Number of spaces in the left margin (tabs used when possible). */
580 static int chars_per_margin = 0;
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;
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;
594 /* True if there were any failed opens so we can exit with nonzero
595 status. */
596 static bool failed_opens = false;
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_)))
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_))
606 /* (-NNN) Number of columns of text to print. */
607 static int columns = 1;
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;
614 /* Number of files open (not closed, not on hold). */
615 static int files_ready_to_read = 0;
617 /* Current page number. Displayed in header. */
618 static uintmax_t page_number;
620 /* Current line number. Displayed when -n flag is specified.
622 When printing files in parallel (-m flag), line numbering is as follows:
623 1 foo goo moo
624 2 hoo too zoo
626 When printing files across (-a flag), ...
627 1 foo 2 moo 3 goo
628 4 hoo 5 too 6 zoo
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;
635 /* (-n) True means lines should be preceded by numbers. */
636 static bool numbered_lines = false;
638 /* (-n) Character which follows each line number. */
639 static char number_separator = '\t';
641 /* (-n) line counting starts with 1st line of input file (not with 1st
642 line of 1st page printed). */
643 static int line_count = 1;
645 /* (-n) True means counting of skipped lines starts with 1st line of
646 input file. False means -N option is used in addition, counting of
647 skipped lines not required. */
648 static bool skip_count = true;
650 /* (-N) Counting starts with start_line_number = NUMBER at 1st line of
651 first page printed, usually not 1st page of input file. */
652 static int start_line_num = 1;
654 /* (-n) Width in characters of a line number. */
655 static int chars_per_number = 5;
657 /* Used when widening the first column to accommodate numbers -- only
658 needed when printing files in parallel. Includes width of both the
659 number and the number_separator. */
660 static int number_width;
662 /* Buffer sprintf uses to format a line number. */
663 static char *number_buff;
665 /* (-v) True means nonprintable characters are printed as escape sequences.
666 control-g becomes \007. */
667 static bool use_esc_sequence = false;
669 /* (-c) True means nonprintable characters are printed as control prefixes.
670 control-g becomes ^G. */
671 static bool use_cntrl_prefix = false;
673 /* (-d) True means output is double spaced. */
674 static bool double_space = false;
676 /* Number of files opened initially in init_files. Should be 1
677 unless we're printing multiple files in parallel. */
678 static int total_files = 0;
680 /* (-r) True means don't complain if we can't open a file. */
681 static bool ignore_failed_opens = false;
683 /* (-S) True means we separate columns with a specified string.
684 -S option does not affect line truncation nor column alignment. */
685 static bool use_col_separator = false;
687 /* String used to separate columns if the -S option has been specified.
688 Default without -S but together with one of the column options
689 -a|COLUMN|-m is a 'space' and with the -J option a 'tab'. */
690 static char const *col_sep_string = "";
691 static int col_sep_length = 0;
692 static char *column_separator = (char *) " ";
693 static char *line_separator = (char *) "\t";
695 /* Number of separator characters waiting to be printed as soon as we
696 know that we have any input remaining to be printed. */
697 static int separators_not_printed;
699 /* Position we need to pad to, as soon as we know that we have input
700 remaining to be printed. */
701 static int padding_not_printed;
703 /* True means we should pad the end of the page. Remains false until we
704 know we have a page to print. */
705 static bool pad_vertically;
707 /* (-h) String of characters used in place of the filename in the header. */
708 static char *custom_header;
710 /* (-D) Date format for the header. */
711 static char const *date_format;
713 /* The local time zone rules, as per the TZ environment variable. */
714 static timezone_t localtz;
716 /* Date and file name for the header. */
717 static char *date_text;
718 static char const *file_text;
720 /* Output columns available, not counting the date and file name. */
721 static int header_width_available;
723 static char *clump_buff;
725 /* True means we read the line no. lines_per_body in skip_read
726 called by skip_to_page. That variable controls the coincidence of a
727 "FF set by hand" and "full_page_printed", see above the definition of
728 structure COLUMN. */
729 static bool last_line = false;
731 /* For long options that have no equivalent short option, use a
732 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
733 enum
735 COLUMNS_OPTION = CHAR_MAX + 1,
736 PAGES_OPTION
739 static char const short_options[] =
740 "-0123456789D:FJN:S::TW:abcde::fh:i::l:mn::o:rs::tvw:";
742 static struct option const long_options[] =
744 {"pages", required_argument, nullptr, PAGES_OPTION},
745 {"columns", required_argument, nullptr, COLUMNS_OPTION},
746 {"across", no_argument, nullptr, 'a'},
747 {"show-control-chars", no_argument, nullptr, 'c'},
748 {"double-space", no_argument, nullptr, 'd'},
749 {"date-format", required_argument, nullptr, 'D'},
750 {"expand-tabs", optional_argument, nullptr, 'e'},
751 {"form-feed", no_argument, nullptr, 'f'},
752 {"header", required_argument, nullptr, 'h'},
753 {"output-tabs", optional_argument, nullptr, 'i'},
754 {"join-lines", no_argument, nullptr, 'J'},
755 {"length", required_argument, nullptr, 'l'},
756 {"merge", no_argument, nullptr, 'm'},
757 {"number-lines", optional_argument, nullptr, 'n'},
758 {"first-line-number", required_argument, nullptr, 'N'},
759 {"indent", required_argument, nullptr, 'o'},
760 {"no-file-warnings", no_argument, nullptr, 'r'},
761 {"separator", optional_argument, nullptr, 's'},
762 {"sep-string", optional_argument, nullptr, 'S'},
763 {"omit-header", no_argument, nullptr, 't'},
764 {"omit-pagination", no_argument, nullptr, 'T'},
765 {"show-nonprinting", no_argument, nullptr, 'v'},
766 {"width", required_argument, nullptr, 'w'},
767 {"page-width", required_argument, nullptr, 'W'},
768 {GETOPT_HELP_OPTION_DECL},
769 {GETOPT_VERSION_OPTION_DECL},
770 {nullptr, 0, nullptr, 0}
773 static _Noreturn void
774 integer_overflow (void)
776 error (EXIT_FAILURE, 0, _("integer overflow"));
779 /* Return the number of columns that have either an open file or
780 stored lines. */
782 ATTRIBUTE_PURE
783 static unsigned int
784 cols_ready_to_print (void)
786 COLUMN *q;
787 unsigned int i;
788 unsigned int n;
790 n = 0;
791 for (q = column_vector, i = 0; i < columns; ++q, ++i)
792 if (q->status == OPEN
793 || q->status == FF_FOUND /* With -b: To print a header only */
794 || (storing_columns && q->lines_stored > 0 && q->lines_to_print > 0))
795 ++n;
796 return n;
799 /* Estimate first_ / last_page_number
800 using option +FIRST_PAGE:LAST_PAGE */
802 static bool
803 first_last_page (int oi, char c, char const *pages)
805 char *p;
806 uintmax_t first;
807 uintmax_t last = UINTMAX_MAX;
808 strtol_error err = xstrtoumax (pages, &p, 10, &first, "");
809 if (err != LONGINT_OK && err != LONGINT_INVALID_SUFFIX_CHAR)
810 xstrtol_fatal (err, oi, c, long_options, pages);
812 if (p == pages || !first)
813 return false;
815 if (*p == ':')
817 char const *p1 = p + 1;
818 err = xstrtoumax (p1, &p, 10, &last, "");
819 if (err != LONGINT_OK)
820 xstrtol_fatal (err, oi, c, long_options, pages);
821 if (p1 == p || last < first)
822 return false;
825 if (*p)
826 return false;
828 first_page_number = first;
829 last_page_number = last;
830 return true;
833 /* Parse column count string S, and if it's valid (1 or larger and
834 within range of the type of 'columns') set the global variables
835 columns and explicit_columns. Otherwise, exit with a diagnostic. */
837 static void
838 parse_column_count (char const *s)
840 columns = getoptnum (s, 1, _("invalid number of columns"));
841 explicit_columns = true;
844 /* Estimate length of col_sep_string with option -S. */
846 static void
847 separator_string (char const *optarg_S)
849 size_t len = strlen (optarg_S);
850 if (INT_MAX < len)
851 integer_overflow ();
852 col_sep_length = len;
853 col_sep_string = optarg_S;
857 main (int argc, char **argv)
859 unsigned int n_files;
860 bool old_options = false;
861 bool old_w = false;
862 bool old_s = false;
863 char **file_names;
865 /* Accumulate the digits of old-style options like -99. */
866 char *column_count_string = nullptr;
867 size_t n_digits = 0;
868 size_t n_alloc = 0;
870 initialize_main (&argc, &argv);
871 set_program_name (argv[0]);
872 setlocale (LC_ALL, "");
873 bindtextdomain (PACKAGE, LOCALEDIR);
874 textdomain (PACKAGE);
876 atexit (close_stdout);
878 n_files = 0;
879 file_names = (argc > 1
880 ? xnmalloc (argc - 1, sizeof (char *))
881 : nullptr);
883 while (true)
885 int oi = -1;
886 int c = getopt_long (argc, argv, short_options, long_options, &oi);
887 if (c == -1)
888 break;
890 if (ISDIGIT (c))
892 /* Accumulate column-count digits specified via old-style options. */
893 if (n_digits + 1 >= n_alloc)
894 column_count_string
895 = X2REALLOC (column_count_string, &n_alloc);
896 column_count_string[n_digits++] = c;
897 column_count_string[n_digits] = '\0';
898 continue;
901 n_digits = 0;
903 switch (c)
905 case 1: /* Non-option argument. */
906 /* long option --page dominates old '+FIRST_PAGE ...'. */
907 if (! (first_page_number == 0
908 && *optarg == '+' && first_last_page (-2, '+', optarg + 1)))
909 file_names[n_files++] = optarg;
910 break;
912 case PAGES_OPTION: /* --pages=FIRST_PAGE[:LAST_PAGE] */
913 { /* dominates old opt +... */
914 if (! optarg)
915 error (EXIT_FAILURE, 0,
916 _("'--pages=FIRST_PAGE[:LAST_PAGE]' missing argument"));
917 else if (! first_last_page (oi, 0, optarg))
918 error (EXIT_FAILURE, 0, _("invalid page range %s"),
919 quote (optarg));
920 break;
923 case COLUMNS_OPTION: /* --columns=COLUMN */
925 parse_column_count (optarg);
927 /* If there was a prior column count specified via the
928 short-named option syntax, e.g., -9, ensure that this
929 long-name-specified value overrides it. */
930 free (column_count_string);
931 column_count_string = nullptr;
932 n_alloc = 0;
933 break;
936 case 'a':
937 print_across_flag = true;
938 storing_columns = false;
939 break;
940 case 'b':
941 balance_columns = true;
942 break;
943 case 'c':
944 use_cntrl_prefix = true;
945 break;
946 case 'd':
947 double_space = true;
948 break;
949 case 'D':
950 date_format = optarg;
951 break;
952 case 'e':
953 if (optarg)
954 getoptarg (optarg, 'e', &input_tab_char,
955 &chars_per_input_tab);
956 /* Could check tab width > 0. */
957 untabify_input = true;
958 break;
959 case 'f':
960 case 'F':
961 use_form_feed = true;
962 break;
963 case 'h':
964 custom_header = optarg;
965 break;
966 case 'i':
967 if (optarg)
968 getoptarg (optarg, 'i', &output_tab_char,
969 &chars_per_output_tab);
970 /* Could check tab width > 0. */
971 tabify_output = true;
972 break;
973 case 'J':
974 join_lines = true;
975 break;
976 case 'l':
977 lines_per_page
978 = getoptnum (optarg, 1,
979 _("'-l PAGE_LENGTH' invalid number of lines"));
980 break;
981 case 'm':
982 parallel_files = true;
983 storing_columns = false;
984 break;
985 case 'n':
986 numbered_lines = true;
987 if (optarg)
988 getoptarg (optarg, 'n', &number_separator,
989 &chars_per_number);
990 break;
991 case 'N':
992 skip_count = false;
993 start_line_num
994 = getoptnum (optarg, INT_MIN,
995 _("'-N NUMBER' invalid starting line number"));
996 break;
997 case 'o':
998 chars_per_margin = getoptnum (optarg, 0,
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,
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 chars_per_line
1045 = getoptnum (optarg, 1,
1046 _("'-W PAGE_WIDTH' invalid number of characters"));
1047 break;
1048 case_GETOPT_HELP_CHAR;
1049 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1050 default:
1051 usage (EXIT_FAILURE);
1052 break;
1056 if (column_count_string)
1058 parse_column_count (column_count_string);
1059 free (column_count_string);
1062 if (! date_format)
1063 date_format = (getenv ("POSIXLY_CORRECT") && !hard_locale (LC_TIME)
1064 ? "%b %e %H:%M %Y"
1065 : "%Y-%m-%d %H:%M");
1067 localtz = tzalloc (getenv ("TZ"));
1069 /* Now we can set a reasonable initial value: */
1070 if (first_page_number == 0)
1071 first_page_number = 1;
1073 if (parallel_files && explicit_columns)
1074 error (EXIT_FAILURE, 0,
1075 _("cannot specify number of columns when printing in parallel"));
1077 if (parallel_files && print_across_flag)
1078 error (EXIT_FAILURE, 0,
1079 _("cannot specify both printing across and printing in parallel"));
1081 /* Translate some old short options to new/long options.
1082 To meet downward compatibility with other UNIX pr utilities
1083 and some POSIX specifications. */
1085 if (old_options)
1087 if (old_w)
1089 if (parallel_files || explicit_columns)
1091 /* activate -W */
1092 truncate_lines = true;
1093 if (old_s)
1094 /* adapt HP-UX and SunOS: -s = no separator;
1095 activate -S */
1096 use_col_separator = true;
1098 else
1099 /* old -w sets width with columns only
1100 activate -J */
1101 join_lines = true;
1103 else if (!use_col_separator)
1105 /* No -S option read */
1106 if (old_s && (parallel_files || explicit_columns))
1108 if (!truncate_lines)
1110 /* old -s (without -w and -W) annuls column alignment,
1111 uses fields, activate -J */
1112 join_lines = true;
1113 if (col_sep_length > 0)
1114 /* activate -S */
1115 use_col_separator = true;
1117 else
1118 /* with -W */
1119 /* adapt HP-UX and SunOS: -s = no separator;
1120 activate -S */
1121 use_col_separator = true;
1126 for (; optind < argc; optind++)
1128 file_names[n_files++] = argv[optind];
1131 if (n_files == 0)
1133 /* No file arguments specified; read from standard input. */
1134 print_files (0, nullptr);
1136 else
1138 if (parallel_files)
1139 print_files (n_files, file_names);
1140 else
1142 for (unsigned int i = 0; i < n_files; i++)
1143 print_files (1, &file_names[i]);
1147 cleanup ();
1149 if (have_read_stdin && fclose (stdin) == EOF)
1150 error (EXIT_FAILURE, errno, _("standard input"));
1151 main_exit (failed_opens ? EXIT_FAILURE : EXIT_SUCCESS);
1154 /* Parse numeric arguments, ensuring MIN <= number <= INT_MAX. */
1156 static int
1157 getoptnum (char const *n_str, int min, char const *err)
1159 return xnumtoimax (n_str, 10, min, INT_MAX, "", err, 0,
1160 min <= 0 ? 0 : XTOINT_MIN_RANGE);
1163 /* Parse options of the form -scNNN.
1165 Example: -nck, where 'n' is the option, c is the optional number
1166 separator, and k is the optional width of the field used when printing
1167 a number. */
1169 static void
1170 getoptarg (char *arg, char switch_char, char *character, int *number)
1172 if (!*arg)
1174 error (0, 0, _("'-%c': Invalid argument: %s"), switch_char, quote (arg));
1175 usage (EXIT_FAILURE);
1178 if (!ISDIGIT (*arg))
1179 *character = *arg++;
1180 if (*arg)
1182 long int tmp_long;
1183 strtol_error e = xstrtol (arg, nullptr, 10, &tmp_long, "");
1184 if (e == LONGINT_OK)
1186 if (tmp_long <= 0)
1187 e = LONGINT_INVALID;
1188 else if (INT_MAX < tmp_long)
1189 e = LONGINT_OVERFLOW;
1191 if (e != LONGINT_OK)
1193 error (0, e & LONGINT_OVERFLOW ? EOVERFLOW : 0,
1194 _("'-%c' extra characters or invalid number in the argument: %s"),
1195 switch_char, quote (arg));
1196 usage (EXIT_FAILURE);
1198 *number = tmp_long;
1202 /* Set parameters related to formatting. */
1204 static void
1205 init_parameters (int number_of_files)
1207 int chars_used_by_number = 0;
1209 lines_per_body = lines_per_page - lines_per_header - lines_per_footer;
1210 if (lines_per_body <= 0)
1212 extremities = false;
1213 keep_FF = true;
1215 if (extremities == false)
1216 lines_per_body = lines_per_page;
1218 if (double_space)
1219 lines_per_body = MAX (1, lines_per_body / 2);
1221 /* If input is stdin, cannot print parallel files. BSD dumps core
1222 on this. */
1223 if (number_of_files == 0)
1224 parallel_files = false;
1226 if (parallel_files)
1227 columns = number_of_files;
1229 /* One file, multi columns down: -b option is set to get a consistent
1230 formulation with "FF set by hand" in input files. */
1231 if (storing_columns)
1232 balance_columns = true;
1234 /* Tabification is assumed for multiple columns. */
1235 if (columns > 1)
1237 if (!use_col_separator)
1239 /* Use default separator */
1240 if (join_lines)
1241 col_sep_string = line_separator;
1242 else
1243 col_sep_string = column_separator;
1245 col_sep_length = 1;
1246 use_col_separator = true;
1248 /* It's rather pointless to define a TAB separator with column
1249 alignment */
1250 else if (!join_lines && col_sep_length == 1 && *col_sep_string == '\t')
1251 col_sep_string = column_separator;
1253 truncate_lines = true;
1254 if (! (col_sep_length == 1 && *col_sep_string == '\t'))
1255 untabify_input = true;
1256 tabify_output = true;
1258 else
1259 storing_columns = false;
1261 /* -J dominates -w in any case */
1262 if (join_lines)
1263 truncate_lines = false;
1265 if (numbered_lines)
1267 int chars_per_default_tab = 8;
1269 line_count = start_line_num;
1271 /* To allow input tab-expansion (-e sensitive) use:
1272 if (number_separator == input_tab_char)
1273 number_width = chars_per_number
1274 + TAB_WIDTH (chars_per_input_tab, chars_per_number); */
1276 /* Estimate chars_per_text without any margin and keep it constant. */
1277 if (number_separator == '\t')
1278 number_width = (chars_per_number
1279 + TAB_WIDTH (chars_per_default_tab, chars_per_number));
1280 else
1281 number_width = chars_per_number + 1;
1283 /* The number is part of the column width unless we are
1284 printing files in parallel. */
1285 if (parallel_files)
1286 chars_used_by_number = number_width;
1289 int sep_chars, useful_chars;
1290 if (ckd_mul (&sep_chars, columns - 1, col_sep_length))
1291 sep_chars = INT_MAX;
1292 if (ckd_sub (&useful_chars, chars_per_line - chars_used_by_number,
1293 sep_chars))
1294 useful_chars = 0;
1295 chars_per_column = useful_chars / columns;
1297 if (chars_per_column < 1)
1298 error (EXIT_FAILURE, 0, _("page width too narrow"));
1300 if (numbered_lines)
1302 free (number_buff);
1303 number_buff = xmalloc (MAX (chars_per_number,
1304 INT_STRLEN_BOUND (line_number)) + 1);
1307 /* Pick the maximum between the tab width and the width of an
1308 escape sequence.
1309 The width of an escape sequence (4) isn't the lower limit any longer.
1310 We've to use 8 as the lower limit, if we use chars_per_default_tab = 8
1311 to expand a tab which is not an input_tab-char. */
1312 free (clump_buff);
1313 clump_buff = xmalloc (MAX (8, chars_per_input_tab));
1316 /* Open the necessary files,
1317 maintaining a COLUMN structure for each column.
1319 With multiple files, each column p has a different p->fp.
1320 With single files, each column p has the same p->fp.
1321 Return false if (number_of_files > 0) and no files can be opened,
1322 true otherwise.
1324 With each column/file p, p->full_page_printed is initialized,
1325 see also open_file. */
1327 static bool
1328 init_fps (int number_of_files, char **av)
1330 COLUMN *p;
1332 total_files = 0;
1334 free (column_vector);
1335 column_vector = xnmalloc (columns, sizeof (COLUMN));
1337 if (parallel_files)
1339 int files_left = number_of_files;
1340 for (p = column_vector; files_left--; ++p, ++av)
1342 if (! open_file (*av, p))
1344 --p;
1345 --columns;
1348 if (columns == 0)
1349 return false;
1350 init_header ("", -1);
1352 else
1354 p = column_vector;
1355 if (number_of_files > 0)
1357 if (! open_file (*av, p))
1358 return false;
1359 init_header (*av, fileno (p->fp));
1360 p->lines_stored = 0;
1362 else
1364 p->name = _("standard input");
1365 p->fp = stdin;
1366 have_read_stdin = true;
1367 p->status = OPEN;
1368 p->full_page_printed = false;
1369 ++total_files;
1370 init_header ("", -1);
1371 p->lines_stored = 0;
1374 char const *firstname = p->name;
1375 FILE *firstfp = p->fp;
1376 int i;
1377 for (i = columns - 1, ++p; i; --i, ++p)
1379 p->name = firstname;
1380 p->fp = firstfp;
1381 p->status = OPEN;
1382 p->full_page_printed = false;
1383 p->lines_stored = 0;
1386 files_ready_to_read = total_files;
1387 return true;
1390 /* Determine print_func and char_func, the functions
1391 used by each column for printing and/or storing.
1393 Determine the horizontal position desired when we begin
1394 printing a column (p->start_position). */
1396 static void
1397 init_funcs (void)
1399 int i, h, h_next;
1400 COLUMN *p;
1402 h = chars_per_margin;
1404 if (!truncate_lines)
1405 h_next = ANYWHERE;
1406 else
1408 /* When numbering lines of parallel files, we enlarge the
1409 first column to accommodate the number. Looks better than
1410 the Sys V approach. */
1411 if (parallel_files && numbered_lines)
1412 h_next = h + chars_per_column + number_width;
1413 else
1414 h_next = h + chars_per_column;
1417 /* Enlarge p->start_position of first column to use the same form of
1418 padding_not_printed with all columns. */
1419 h = h + col_sep_length;
1421 /* This loop takes care of all but the rightmost column. */
1423 for (p = column_vector, i = 1; i < columns; ++p, ++i)
1425 if (storing_columns) /* One file, multi columns down. */
1427 p->char_func = store_char;
1428 p->print_func = print_stored;
1430 else
1431 /* One file, multi columns across; or parallel files. */
1433 p->char_func = print_char;
1434 p->print_func = read_line;
1437 /* Number only the first column when printing files in
1438 parallel. */
1439 p->numbered = numbered_lines && (!parallel_files || i == 1);
1440 p->start_position = h;
1442 /* If we don't truncate lines, all start_positions are
1443 ANYWHERE, except the first column's start_position when
1444 using a margin. */
1446 if (!truncate_lines)
1448 h = ANYWHERE;
1449 h_next = ANYWHERE;
1451 else
1453 h = h_next + col_sep_length;
1454 h_next = h + chars_per_column;
1458 /* The rightmost column.
1460 Doesn't need to be stored unless we intend to balance
1461 columns on the last page. */
1462 if (storing_columns && balance_columns)
1464 p->char_func = store_char;
1465 p->print_func = print_stored;
1467 else
1469 p->char_func = print_char;
1470 p->print_func = read_line;
1473 p->numbered = numbered_lines && (!parallel_files || i == 1);
1474 p->start_position = h;
1477 /* Open a file. Return true if successful.
1479 With each file p, p->full_page_printed is initialized,
1480 see also init_fps. */
1482 static bool
1483 open_file (char *name, COLUMN *p)
1485 if (STREQ (name, "-"))
1487 p->name = _("standard input");
1488 p->fp = stdin;
1489 have_read_stdin = true;
1491 else
1493 p->name = name;
1494 p->fp = fopen (name, "r");
1496 if (p->fp == nullptr)
1498 failed_opens = true;
1499 if (!ignore_failed_opens)
1500 error (0, errno, "%s", quotef (name));
1501 return false;
1503 fadvise (p->fp, FADVISE_SEQUENTIAL);
1504 p->status = OPEN;
1505 p->full_page_printed = false;
1506 ++total_files;
1507 return true;
1510 /* Close the file in P.
1512 If we aren't dealing with multiple files in parallel, we change
1513 the status of all columns in the column list to reflect the close. */
1515 static void
1516 close_file (COLUMN *p)
1518 COLUMN *q;
1519 int i;
1521 if (p->status == CLOSED)
1522 return;
1524 int err = errno;
1525 if (!ferror (p->fp))
1526 err = 0;
1527 if (fileno (p->fp) == STDIN_FILENO)
1528 clearerr (p->fp);
1529 else if (fclose (p->fp) != 0 && !err)
1530 err = errno;
1531 if (err)
1532 error (EXIT_FAILURE, err, "%s", quotef (p->name));
1534 if (!parallel_files)
1536 for (q = column_vector, i = columns; i; ++q, --i)
1538 q->status = CLOSED;
1539 if (q->lines_stored == 0)
1541 q->lines_to_print = 0;
1545 else
1547 p->status = CLOSED;
1548 p->lines_to_print = 0;
1551 --files_ready_to_read;
1554 /* Put a file on hold until we start a new page,
1555 since we've hit a form feed.
1557 If we aren't dealing with parallel files, we must change the
1558 status of all columns in the column list. */
1560 static void
1561 hold_file (COLUMN *p)
1563 COLUMN *q;
1564 int i;
1566 if (!parallel_files)
1567 for (q = column_vector, i = columns; i; ++q, --i)
1569 if (storing_columns)
1570 q->status = FF_FOUND;
1571 else
1572 q->status = ON_HOLD;
1574 else
1575 p->status = ON_HOLD;
1577 p->lines_to_print = 0;
1578 --files_ready_to_read;
1581 /* Undo hold_file -- go through the column list and change any
1582 ON_HOLD columns to OPEN. Used at the end of each page. */
1584 static void
1585 reset_status (void)
1587 int i = columns;
1588 COLUMN *p;
1590 for (p = column_vector; i; --i, ++p)
1591 if (p->status == ON_HOLD)
1593 p->status = OPEN;
1594 files_ready_to_read++;
1597 if (storing_columns)
1599 if (column_vector->status == CLOSED)
1600 /* We use the info to output an error message in skip_to_page. */
1601 files_ready_to_read = 0;
1602 else
1603 files_ready_to_read = 1;
1607 /* Print a single file, or multiple files in parallel.
1609 Set up the list of columns, opening the necessary files.
1610 Allocate space for storing columns, if necessary.
1611 Skip to first_page_number, if user has asked to skip leading pages.
1612 Determine which functions are appropriate to store/print lines
1613 in each column.
1614 Print the file(s). */
1616 static void
1617 print_files (int number_of_files, char **av)
1619 init_parameters (number_of_files);
1620 if (! init_fps (number_of_files, av))
1621 return;
1622 if (storing_columns)
1623 init_store_cols ();
1625 if (first_page_number > 1)
1627 if (!skip_to_page (first_page_number))
1628 return;
1629 else
1630 page_number = first_page_number;
1632 else
1633 page_number = 1;
1635 init_funcs ();
1637 line_number = line_count;
1638 while (print_page ())
1642 /* Initialize header information.
1643 If DESC is non-negative, it is a file descriptor open to
1644 FILENAME for reading. */
1646 static void
1647 init_header (char const *filename, int desc)
1649 char *buf = nullptr;
1650 struct stat st;
1651 struct timespec t;
1652 int ns;
1653 struct tm tm;
1655 /* If parallel files or standard input, use current date. */
1656 if (STREQ (filename, "-"))
1657 desc = -1;
1658 if (0 <= desc && fstat (desc, &st) == 0)
1659 t = get_stat_mtime (&st);
1660 else
1662 static struct timespec timespec;
1663 if (! timespec.tv_sec)
1664 gettime (&timespec);
1665 t = timespec;
1668 ns = t.tv_nsec;
1669 if (localtime_rz (localtz, &t.tv_sec, &tm))
1671 size_t bufsize
1672 = nstrftime (nullptr, SIZE_MAX, date_format, &tm, localtz, ns) + 1;
1673 buf = xmalloc (bufsize);
1674 nstrftime (buf, bufsize, date_format, &tm, localtz, ns);
1676 else
1678 char secbuf[INT_BUFSIZE_BOUND (intmax_t)];
1679 buf = xmalloc (sizeof secbuf + MAX (10, INT_BUFSIZE_BOUND (int)));
1680 sprintf (buf, "%s.%09d", timetostr (t.tv_sec, secbuf), ns);
1683 free (date_text);
1684 date_text = buf;
1685 file_text = custom_header ? custom_header : desc < 0 ? "" : filename;
1686 header_width_available = (chars_per_line
1687 - mbswidth (date_text, 0)
1688 - mbswidth (file_text, 0));
1691 /* Set things up for printing a page
1693 Scan through the columns ...
1694 Determine which are ready to print
1695 (i.e., which have lines stored or open files)
1696 Set p->lines_to_print appropriately
1697 (to p->lines_stored if we're storing, or lines_per_body
1698 if we're reading straight from the file)
1699 Keep track of this total so we know when to stop printing */
1701 static void
1702 init_page (void)
1704 int j;
1705 COLUMN *p;
1707 if (storing_columns)
1709 store_columns ();
1710 for (j = columns - 1, p = column_vector; j; --j, ++p)
1712 p->lines_to_print = p->lines_stored;
1715 /* Last column. */
1716 if (balance_columns)
1718 p->lines_to_print = p->lines_stored;
1720 /* Since we're not balancing columns, we don't need to store
1721 the rightmost column. Read it straight from the file. */
1722 else
1724 if (p->status == OPEN)
1726 p->lines_to_print = lines_per_body;
1728 else
1729 p->lines_to_print = 0;
1732 else
1733 for (j = columns, p = column_vector; j; --j, ++p)
1734 if (p->status == OPEN)
1736 p->lines_to_print = lines_per_body;
1738 else
1739 p->lines_to_print = 0;
1742 /* Align empty columns and print separators.
1743 Empty columns will be formed by files with status ON_HOLD or CLOSED
1744 when printing multiple files in parallel. */
1746 static void
1747 align_column (COLUMN *p)
1749 padding_not_printed = p->start_position;
1750 if (col_sep_length < padding_not_printed)
1752 pad_across_to (padding_not_printed - col_sep_length);
1753 padding_not_printed = ANYWHERE;
1756 if (use_col_separator)
1757 print_sep_string ();
1759 if (p->numbered)
1760 add_line_number (p);
1763 /* Print one page.
1765 As long as there are lines left on the page and columns ready to print,
1766 Scan across the column list
1767 if the column has stored lines or the file is open
1768 pad to the appropriate spot
1769 print the column
1770 pad the remainder of the page with \n or \f as requested
1771 reset the status of all files -- any files which where on hold because
1772 of formfeeds are now put back into the lineup. */
1774 static bool
1775 print_page (void)
1777 int j;
1778 int lines_left_on_page;
1779 COLUMN *p;
1781 /* Used as an accumulator (with | operator) of successive values of
1782 pad_vertically. The trick is to set pad_vertically
1783 to false before each run through the inner loop, then after that
1784 loop, it tells us whether a line was actually printed (whether a
1785 newline needs to be output -- or two for double spacing). But those
1786 values have to be accumulated (in pv) so we can invoke pad_down
1787 properly after the outer loop completes. */
1788 bool pv;
1790 init_page ();
1792 if (cols_ready_to_print () == 0)
1793 return false;
1795 if (extremities)
1796 print_a_header = true;
1798 /* Don't pad unless we know a page was printed. */
1799 pad_vertically = false;
1800 pv = false;
1802 lines_left_on_page = lines_per_body;
1803 if (double_space)
1804 lines_left_on_page *= 2;
1806 while (lines_left_on_page > 0 && cols_ready_to_print () > 0)
1808 output_position = 0;
1809 spaces_not_printed = 0;
1810 separators_not_printed = 0;
1811 pad_vertically = false;
1812 align_empty_cols = false;
1813 empty_line = true;
1815 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
1817 input_position = 0;
1818 if (p->lines_to_print > 0 || p->status == FF_FOUND)
1820 FF_only = false;
1821 padding_not_printed = p->start_position;
1822 if (!(p->print_func) (p))
1823 read_rest_of_line (p);
1824 pv |= pad_vertically;
1826 --p->lines_to_print;
1827 if (p->lines_to_print <= 0)
1829 if (cols_ready_to_print () == 0)
1830 break;
1833 /* File p changed its status to ON_HOLD or CLOSED */
1834 if (parallel_files && p->status != OPEN)
1836 if (empty_line)
1837 align_empty_cols = true;
1838 else if (p->status == CLOSED
1839 || (p->status == ON_HOLD && FF_only))
1840 align_column (p);
1843 else if (parallel_files)
1845 /* File status ON_HOLD or CLOSED */
1846 if (empty_line)
1847 align_empty_cols = true;
1848 else
1849 align_column (p);
1852 /* We need it also with an empty column */
1853 if (use_col_separator)
1854 ++separators_not_printed;
1857 if (pad_vertically)
1859 putchar ('\n');
1860 --lines_left_on_page;
1863 if (cols_ready_to_print () == 0 && !extremities)
1864 break;
1866 if (double_space && pv)
1868 putchar ('\n');
1869 --lines_left_on_page;
1873 if (lines_left_on_page == 0)
1874 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
1875 if (p->status == OPEN)
1876 p->full_page_printed = true;
1878 pad_vertically = pv;
1880 if (pad_vertically && extremities)
1881 pad_down (lines_left_on_page + lines_per_footer);
1882 else if (keep_FF && print_a_FF)
1884 putchar ('\f');
1885 print_a_FF = false;
1888 if (last_page_number < ++page_number)
1889 return false; /* Stop printing with LAST_PAGE */
1891 reset_status (); /* Change ON_HOLD to OPEN. */
1893 return true; /* More pages to go. */
1896 /* Allocate space for storing columns.
1898 This is necessary when printing multiple columns from a single file.
1899 Lines are stored consecutively in buff, separated by '\0'.
1901 The following doesn't apply any longer - any tuning possible?
1902 (We can't use a fixed offset since with the '-s' flag lines aren't
1903 truncated.)
1905 We maintain a list (line_vector) of pointers to the beginnings
1906 of lines in buff. We allocate one more than the number of lines
1907 because the last entry tells us the index of the last character,
1908 which we need to know in order to print the last line in buff. */
1910 static void
1911 init_store_cols (void)
1913 int total_lines, total_lines_1, chars_per_column_1, chars_if_truncate;
1914 if (ckd_mul (&total_lines, lines_per_body, columns)
1915 || ckd_add (&total_lines_1, total_lines, 1)
1916 || ckd_add (&chars_per_column_1, chars_per_column, 1)
1917 || ckd_mul (&chars_if_truncate, total_lines, chars_per_column_1))
1918 integer_overflow ();
1920 free (line_vector);
1921 /* FIXME: here's where it was allocated. */
1922 line_vector = xnmalloc (total_lines_1, sizeof *line_vector);
1924 free (end_vector);
1925 end_vector = xnmalloc (total_lines, sizeof *end_vector);
1927 free (buff);
1928 buff = xnmalloc (chars_if_truncate, use_col_separator + 1);
1929 buff_allocated = chars_if_truncate; /* Tune this. */
1930 buff_allocated *= use_col_separator + 1;
1933 /* Store all but the rightmost column.
1934 (Used when printing a single file in multiple downward columns)
1936 For each column
1937 set p->current_line to be the index in line_vector of the
1938 first line in the column
1939 For each line in the column
1940 store the line in buff
1941 add to line_vector the index of the line's first char
1942 buff_start is the index in buff of the first character in the
1943 current line. */
1945 static void
1946 store_columns (void)
1948 int i, j;
1949 unsigned int line = 0;
1950 unsigned int buff_start;
1951 int last_col; /* The rightmost column which will be saved in buff */
1952 COLUMN *p;
1954 buff_current = 0;
1955 buff_start = 0;
1957 if (balance_columns)
1958 last_col = columns;
1959 else
1960 last_col = columns - 1;
1962 for (i = 1, p = column_vector; i <= last_col; ++i, ++p)
1963 p->lines_stored = 0;
1965 for (i = 1, p = column_vector; i <= last_col && files_ready_to_read;
1966 ++i, ++p)
1968 p->current_line = line;
1969 for (j = lines_per_body; j && files_ready_to_read; --j)
1971 if (p->status == OPEN) /* Redundant. Clean up. */
1973 input_position = 0;
1975 if (!read_line (p))
1976 read_rest_of_line (p);
1978 if (p->status == OPEN
1979 || buff_start != buff_current)
1981 ++p->lines_stored;
1982 line_vector[line] = buff_start;
1983 end_vector[line++] = input_position;
1984 buff_start = buff_current;
1989 /* Keep track of the location of the last char in buff. */
1990 line_vector[line] = buff_start;
1992 if (balance_columns)
1993 balance (line);
1996 static void
1997 balance (int total_stored)
1999 COLUMN *p;
2000 int i, lines;
2001 int first_line = 0;
2003 for (i = 1, p = column_vector; i <= columns; ++i, ++p)
2005 lines = total_stored / columns;
2006 if (i <= total_stored % columns)
2007 ++lines;
2009 p->lines_stored = lines;
2010 p->current_line = first_line;
2012 first_line += lines;
2016 /* Store a character in the buffer. */
2018 static void
2019 store_char (char c)
2021 if (buff_current >= buff_allocated)
2023 /* May be too generous. */
2024 buff = X2REALLOC (buff, &buff_allocated);
2026 buff[buff_current++] = c;
2029 static void
2030 add_line_number (COLUMN *p)
2032 int i;
2033 char *s;
2034 int num_width;
2036 /* Cutting off the higher-order digits is more informative than
2037 lower-order cut off. */
2038 num_width = sprintf (number_buff, "%*d", chars_per_number, line_number);
2039 line_number++;
2040 s = number_buff + (num_width - chars_per_number);
2041 for (i = chars_per_number; i > 0; i--)
2042 (p->char_func) (*s++);
2044 if (columns > 1)
2046 /* Tabification is assumed for multiple columns, also for n-separators,
2047 but 'default n-separator = TAB' hasn't been given priority over
2048 equal column_width also specified by POSIX. */
2049 if (number_separator == '\t')
2051 i = number_width - chars_per_number;
2052 while (i-- > 0)
2053 (p->char_func) (' ');
2055 else
2056 (p->char_func) (number_separator);
2058 else
2059 /* To comply with POSIX, we avoid any expansion of default TAB
2060 separator with a single column output. No column_width requirement
2061 has to be considered. */
2063 (p->char_func) (number_separator);
2064 if (number_separator == '\t')
2065 output_position = POS_AFTER_TAB (chars_per_output_tab,
2066 output_position);
2069 if (truncate_lines && !parallel_files)
2070 input_position += number_width;
2073 /* Print (or store) padding until the current horizontal position
2074 is position. */
2076 static void
2077 pad_across_to (int position)
2079 int h = output_position;
2081 if (tabify_output)
2082 spaces_not_printed = position - output_position;
2083 else
2085 while (++h <= position)
2086 putchar (' ');
2087 output_position = position;
2091 /* Pad to the bottom of the page.
2093 If the user has requested a formfeed, use one.
2094 Otherwise, use newlines. */
2096 static void
2097 pad_down (unsigned int lines)
2099 if (use_form_feed)
2100 putchar ('\f');
2101 else
2102 for (unsigned int i = lines; i; --i)
2103 putchar ('\n');
2106 /* Read the rest of the line.
2108 Read from the current column's file until an end of line is
2109 hit. Used when we've truncated a line and we no longer need
2110 to print or store its characters. */
2112 static void
2113 read_rest_of_line (COLUMN *p)
2115 int c;
2116 FILE *f = p->fp;
2118 while ((c = getc (f)) != '\n')
2120 if (c == '\f')
2122 if ((c = getc (f)) != '\n')
2123 ungetc (c, f);
2124 if (keep_FF)
2125 print_a_FF = true;
2126 hold_file (p);
2127 break;
2129 else if (c == EOF)
2131 close_file (p);
2132 break;
2137 /* Read a line with skip_to_page.
2139 Read from the current column's file until an end of line is
2140 hit. Used when we read full lines to skip pages.
2141 With skip_to_page we have to check for FF-coincidence which is done
2142 in function read_line otherwise.
2143 Count lines of skipped pages to find the line number of 1st page
2144 printed relative to 1st line of input file (start_line_num). */
2146 static void
2147 skip_read (COLUMN *p, int column_number)
2149 int c;
2150 FILE *f = p->fp;
2151 int i;
2152 bool single_ff = false;
2153 COLUMN *q;
2155 /* Read 1st character in a line or any character succeeding a FF */
2156 if ((c = getc (f)) == '\f' && p->full_page_printed)
2157 /* A FF-coincidence with a previous full_page_printed.
2158 To avoid an additional empty page, eliminate the FF */
2159 if ((c = getc (f)) == '\n')
2160 c = getc (f);
2162 p->full_page_printed = false;
2164 /* 1st character a FF means a single FF without any printable
2165 characters. Don't count it as a line with -n option. */
2166 if (c == '\f')
2167 single_ff = true;
2169 /* Preparing for a FF-coincidence: Maybe we finish that page
2170 without a FF found */
2171 if (last_line)
2172 p->full_page_printed = true;
2174 while (c != '\n')
2176 if (c == '\f')
2178 /* No FF-coincidence possible,
2179 no catching up of a FF-coincidence with next page */
2180 if (last_line)
2182 if (!parallel_files)
2183 for (q = column_vector, i = columns; i; ++q, --i)
2184 q->full_page_printed = false;
2185 else
2186 p->full_page_printed = false;
2189 if ((c = getc (f)) != '\n')
2190 ungetc (c, f);
2191 hold_file (p);
2192 break;
2194 else if (c == EOF)
2196 close_file (p);
2197 break;
2199 c = getc (f);
2202 if (skip_count)
2203 if ((!parallel_files || column_number == 1) && !single_ff)
2204 ++line_count;
2207 /* If we're tabifying output,
2209 When print_char encounters white space it keeps track
2210 of our desired horizontal position and delays printing
2211 until this function is called. */
2213 static void
2214 print_white_space (void)
2216 int h_new;
2217 int h_old = output_position;
2218 int goal = h_old + spaces_not_printed;
2220 while (goal - h_old > 1
2221 && (h_new = POS_AFTER_TAB (chars_per_output_tab, h_old)) <= goal)
2223 putchar (output_tab_char);
2224 h_old = h_new;
2226 while (++h_old <= goal)
2227 putchar (' ');
2229 output_position = goal;
2230 spaces_not_printed = 0;
2233 /* Print column separators.
2235 We keep a count until we know that we'll be printing a line,
2236 then print_sep_string() is called. */
2238 static void
2239 print_sep_string (void)
2241 char const *s = col_sep_string;
2242 int l = col_sep_length;
2244 if (separators_not_printed <= 0)
2246 /* We'll be starting a line with chars_per_margin, anything else? */
2247 if (spaces_not_printed > 0)
2248 print_white_space ();
2250 else
2252 for (; separators_not_printed > 0; --separators_not_printed)
2254 while (l-- > 0)
2256 /* 3 types of sep_strings: spaces only, spaces and chars,
2257 chars only */
2258 if (*s == ' ')
2260 /* We're tabifying output; consecutive spaces in
2261 sep_string may have to be converted to tabs */
2262 s++;
2263 ++spaces_not_printed;
2265 else
2267 if (spaces_not_printed > 0)
2268 print_white_space ();
2269 putchar (*s++);
2270 ++output_position;
2273 /* sep_string ends with some spaces */
2274 if (spaces_not_printed > 0)
2275 print_white_space ();
2280 /* Print (or store, depending on p->char_func) a clump of N
2281 characters. */
2283 static void
2284 print_clump (COLUMN *p, int n, char *clump)
2286 while (n--)
2287 (p->char_func) (*clump++);
2290 /* Print a character.
2292 Update the following comment: process-char hasn't been used any
2293 longer.
2294 If we're tabifying, all tabs have been converted to spaces by
2295 process_char(). Keep a count of consecutive spaces, and when
2296 a nonspace is encountered, call print_white_space() to print the
2297 required number of tabs and spaces. */
2299 static void
2300 print_char (char c)
2302 if (tabify_output)
2304 if (c == ' ')
2306 ++spaces_not_printed;
2307 return;
2309 else if (spaces_not_printed > 0)
2310 print_white_space ();
2312 /* Nonprintables are assumed to have width 0, except '\b'. */
2313 if (! isprint (to_uchar (c)))
2315 if (c == '\b')
2316 --output_position;
2318 else
2319 ++output_position;
2321 putchar (c);
2324 /* Skip to page PAGE before printing.
2325 PAGE may be larger than total number of pages. */
2327 static bool
2328 skip_to_page (uintmax_t page)
2330 for (uintmax_t n = 1; n < page; ++n)
2332 COLUMN *p;
2333 int j;
2335 for (int i = 1; i < lines_per_body; ++i)
2337 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
2338 if (p->status == OPEN)
2339 skip_read (p, j);
2341 last_line = true;
2342 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
2343 if (p->status == OPEN)
2344 skip_read (p, j);
2346 if (storing_columns) /* change FF_FOUND to ON_HOLD */
2347 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
2348 if (p->status != CLOSED)
2349 p->status = ON_HOLD;
2351 reset_status ();
2352 last_line = false;
2354 if (files_ready_to_read < 1)
2356 /* It's very helpful, normally the total number of pages is
2357 not known in advance. */
2358 error (0, 0,
2359 _("starting page number %ju exceeds page count %ju"),
2360 page, n);
2361 break;
2364 return files_ready_to_read > 0;
2367 /* Print a header.
2369 Formfeeds are assumed to use up two lines at the beginning of
2370 the page. */
2372 static void
2373 print_header (void)
2375 char page_text[256 + INT_STRLEN_BOUND (page_number)];
2376 int available_width;
2377 int lhs_spaces;
2378 int rhs_spaces;
2380 output_position = 0;
2381 pad_across_to (chars_per_margin);
2382 print_white_space ();
2384 if (page_number == 0)
2385 error (EXIT_FAILURE, 0, _("page number overflow"));
2387 /* The translator must ensure that formatting the translation of
2388 "Page %ju" does not generate more than (sizeof page_text - 1)
2389 bytes. */
2390 sprintf (page_text, _("Page %ju"), page_number);
2391 available_width = header_width_available - mbswidth (page_text, 0);
2392 available_width = MAX (0, available_width);
2393 lhs_spaces = available_width >> 1;
2394 rhs_spaces = available_width - lhs_spaces;
2396 printf ("\n\n%*s%s%*s%s%*s%s\n\n\n",
2397 chars_per_margin, "",
2398 date_text, lhs_spaces, " ",
2399 file_text, rhs_spaces, " ", page_text);
2401 print_a_header = false;
2402 output_position = 0;
2405 /* Print (or store, if p->char_func is store_char()) a line.
2407 Read a character to determine whether we have a line or not.
2408 (We may hit EOF, \n, or \f)
2410 Once we know we have a line,
2411 set pad_vertically = true, meaning it's safe
2412 to pad down at the end of the page, since we do have a page.
2413 print a header if needed.
2414 pad across to padding_not_printed if needed.
2415 print any separators which need to be printed.
2416 print a line number if it needs to be printed.
2418 Print the clump which corresponds to the first character.
2420 Enter a loop and keep printing until an end of line condition
2421 exists, or until we exceed chars_per_column.
2423 Return false if we exceed chars_per_column before reading
2424 an end of line character, true otherwise. */
2426 static bool
2427 read_line (COLUMN *p)
2429 int c;
2430 int chars IF_LINT (= 0);
2431 int last_input_position;
2432 int j, k;
2433 COLUMN *q;
2435 /* read 1st character in each line or any character succeeding a FF: */
2436 c = getc (p->fp);
2438 last_input_position = input_position;
2440 if (c == '\f' && p->full_page_printed)
2441 if ((c = getc (p->fp)) == '\n')
2442 c = getc (p->fp);
2443 p->full_page_printed = false;
2445 switch (c)
2447 case '\f':
2448 if ((c = getc (p->fp)) != '\n')
2449 ungetc (c, p->fp);
2450 FF_only = true;
2451 if (print_a_header && !storing_columns)
2453 pad_vertically = true;
2454 print_header ();
2456 else if (keep_FF)
2457 print_a_FF = true;
2458 hold_file (p);
2459 return true;
2460 case EOF:
2461 close_file (p);
2462 return true;
2463 case '\n':
2464 break;
2465 default:
2466 chars = char_to_clump (c);
2469 if (truncate_lines && input_position > chars_per_column)
2471 input_position = last_input_position;
2472 return false;
2475 if (p->char_func != store_char)
2477 pad_vertically = true;
2479 if (print_a_header && !storing_columns)
2480 print_header ();
2482 if (parallel_files && align_empty_cols)
2484 /* We have to align empty columns at the beginning of a line. */
2485 k = separators_not_printed;
2486 separators_not_printed = 0;
2487 for (j = 1, q = column_vector; j <= k; ++j, ++q)
2489 align_column (q);
2490 separators_not_printed += 1;
2492 padding_not_printed = p->start_position;
2493 if (truncate_lines)
2494 spaces_not_printed = chars_per_column;
2495 else
2496 spaces_not_printed = 0;
2497 align_empty_cols = false;
2500 if (col_sep_length < padding_not_printed)
2502 pad_across_to (padding_not_printed - col_sep_length);
2503 padding_not_printed = ANYWHERE;
2506 if (use_col_separator)
2507 print_sep_string ();
2510 if (p->numbered)
2511 add_line_number (p);
2513 empty_line = false;
2514 if (c == '\n')
2515 return true;
2517 print_clump (p, chars, clump_buff);
2519 while (true)
2521 c = getc (p->fp);
2523 switch (c)
2525 case '\n':
2526 return true;
2527 case '\f':
2528 if ((c = getc (p->fp)) != '\n')
2529 ungetc (c, p->fp);
2530 if (keep_FF)
2531 print_a_FF = true;
2532 hold_file (p);
2533 return true;
2534 case EOF:
2535 close_file (p);
2536 return true;
2539 last_input_position = input_position;
2540 chars = char_to_clump (c);
2541 if (truncate_lines && input_position > chars_per_column)
2543 input_position = last_input_position;
2544 return false;
2547 print_clump (p, chars, clump_buff);
2551 /* Print a line from buff.
2553 If this function has been called, we know we have "something to
2554 print". But it remains to be seen whether we have a real text page
2555 or an empty page (a single form feed) with/without a header only.
2556 Therefore first we set pad_vertically to true and print a header
2557 if necessary.
2558 If FF_FOUND and we are using -t|-T option we omit any newline by
2559 setting pad_vertically to false (see print_page).
2560 Otherwise we pad across if necessary, print separators if necessary
2561 and text of COLUMN *p.
2563 Return true, meaning there is no need to call read_rest_of_line. */
2565 static bool
2566 print_stored (COLUMN *p)
2568 COLUMN *q;
2570 int line = p->current_line++;
2571 char *first = &buff[line_vector[line]];
2572 /* FIXME
2573 UMR: Uninitialized memory read:
2574 * This is occurring while in:
2575 print_stored [pr.c:2239]
2576 * Reading 4 bytes from 0x5148c in the heap.
2577 * Address 0x5148c is 4 bytes into a malloc'd block at 0x51488 of 676 bytes
2578 * This block was allocated from:
2579 malloc [rtlib.o]
2580 xmalloc [xmalloc.c:94]
2581 init_store_cols [pr.c:1648]
2583 char *last = &buff[line_vector[line + 1]];
2585 pad_vertically = true;
2587 if (print_a_header)
2588 print_header ();
2590 if (p->status == FF_FOUND)
2592 int i;
2593 for (i = 1, q = column_vector; i <= columns; ++i, ++q)
2594 q->status = ON_HOLD;
2595 if (column_vector->lines_to_print <= 0)
2597 if (!extremities)
2598 pad_vertically = false;
2599 return true; /* print a header only */
2603 if (col_sep_length < padding_not_printed)
2605 pad_across_to (padding_not_printed - col_sep_length);
2606 padding_not_printed = ANYWHERE;
2609 if (use_col_separator)
2610 print_sep_string ();
2612 while (first != last)
2613 print_char (*first++);
2615 if (spaces_not_printed == 0)
2617 output_position = p->start_position + end_vector[line];
2618 if (p->start_position - col_sep_length == chars_per_margin)
2619 output_position -= col_sep_length;
2622 return true;
2625 /* Convert a character to the proper format and return the number of
2626 characters in the resulting clump. Increment input_position by
2627 the width of the clump.
2629 Tabs are converted to clumps of spaces.
2630 Nonprintable characters may be converted to clumps of escape
2631 sequences or control prefixes.
2633 Note: the width of a clump is not necessarily equal to the number of
2634 characters in clump_buff. (e.g., the width of '\b' is -1, while the
2635 number of characters is 1.) */
2637 static int
2638 char_to_clump (char c)
2640 unsigned char uc = c;
2641 char *s = clump_buff;
2642 int i;
2643 char esc_buff[4];
2644 int width;
2645 int chars;
2646 int chars_per_c = 8;
2648 if (c == input_tab_char)
2649 chars_per_c = chars_per_input_tab;
2651 if (c == input_tab_char || c == '\t')
2653 width = TAB_WIDTH (chars_per_c, input_position);
2655 if (untabify_input)
2657 for (i = width; i; --i)
2658 *s++ = ' ';
2659 chars = width;
2661 else
2663 *s = c;
2664 chars = 1;
2668 else if (! isprint (uc))
2670 if (use_esc_sequence)
2672 width = 4;
2673 chars = 4;
2674 *s++ = '\\';
2675 sprintf (esc_buff, "%03o", uc);
2676 for (i = 0; i <= 2; ++i)
2677 *s++ = esc_buff[i];
2679 else if (use_cntrl_prefix)
2681 if (uc < 0200)
2683 width = 2;
2684 chars = 2;
2685 *s++ = '^';
2686 *s = c ^ 0100;
2688 else
2690 width = 4;
2691 chars = 4;
2692 *s++ = '\\';
2693 sprintf (esc_buff, "%03o", uc);
2694 for (i = 0; i <= 2; ++i)
2695 *s++ = esc_buff[i];
2698 else if (c == '\b')
2700 width = -1;
2701 chars = 1;
2702 *s = c;
2704 else
2706 width = 0;
2707 chars = 1;
2708 *s = c;
2711 else
2713 width = 1;
2714 chars = 1;
2715 *s = c;
2718 /* Too many backspaces must put us in position 0 -- never negative. */
2719 if (width < 0 && input_position == 0)
2721 chars = 0;
2722 input_position = 0;
2724 else if (width < 0 && input_position <= -width)
2725 input_position = 0;
2726 else
2727 input_position += width;
2729 return chars;
2732 /* We've just printed some files and need to clean up things before
2733 looking for more options and printing the next batch of files.
2735 Free everything we've xmalloc'ed, except 'header'. */
2737 static void
2738 cleanup (void)
2740 free (number_buff);
2741 free (clump_buff);
2742 free (column_vector);
2743 free (line_vector);
2744 free (end_vector);
2745 free (buff);
2748 /* Complain, print a usage message, and die. */
2750 void
2751 usage (int status)
2753 if (status != EXIT_SUCCESS)
2754 emit_try_help ();
2755 else
2757 printf (_("\
2758 Usage: %s [OPTION]... [FILE]...\n\
2760 program_name);
2762 fputs (_("\
2763 Paginate or columnate FILE(s) for printing.\n\
2764 "), stdout);
2766 emit_stdin_note ();
2767 emit_mandatory_arg_note ();
2769 fputs (_("\
2770 +FIRST_PAGE[:LAST_PAGE], --pages=FIRST_PAGE[:LAST_PAGE]\n\
2771 begin [stop] printing with page FIRST_[LAST_]PAGE\n\
2772 -COLUMN, --columns=COLUMN\n\
2773 output COLUMN columns and print columns down,\n\
2774 unless -a is used. Balance number of lines in the\n\
2775 columns on each page\n\
2776 "), stdout);
2777 fputs (_("\
2778 -a, --across print columns across rather than down, used together\n\
2779 with -COLUMN\n\
2780 -c, --show-control-chars\n\
2781 use hat notation (^G) and octal backslash notation\n\
2782 -d, --double-space\n\
2783 double space the output\n\
2784 "), stdout);
2785 fputs (_("\
2786 -D, --date-format=FORMAT\n\
2787 use FORMAT for the header date\n\
2788 -e[CHAR[WIDTH]], --expand-tabs[=CHAR[WIDTH]]\n\
2789 expand input CHARs (TABs) to tab WIDTH (8)\n\
2790 -F, -f, --form-feed\n\
2791 use form feeds instead of newlines to separate pages\n\
2792 (by a 3-line page header with -F or a 5-line header\n\
2793 and trailer without -F)\n\
2794 "), stdout);
2795 fputs (_("\
2796 -h, --header=HEADER\n\
2797 use a centered HEADER instead of filename in page header,\n\
2798 -h \"\" prints a blank line, don't use -h\"\"\n\
2799 -i[CHAR[WIDTH]], --output-tabs[=CHAR[WIDTH]]\n\
2800 replace spaces with CHARs (TABs) to tab WIDTH (8)\n\
2801 -J, --join-lines merge full lines, turns off -W line truncation, no column\n\
2802 alignment, --sep-string[=STRING] sets separators\n\
2803 "), stdout);
2804 fputs (_("\
2805 -l, --length=PAGE_LENGTH\n\
2806 set the page length to PAGE_LENGTH (66) lines\n\
2807 (default number of lines of text 56, and with -F 63).\n\
2808 implies -t if PAGE_LENGTH <= 10\n\
2809 "), stdout);
2810 fputs (_("\
2811 -m, --merge print all files in parallel, one in each column,\n\
2812 truncate lines, but join lines of full length with -J\n\
2813 "), stdout);
2814 fputs (_("\
2815 -n[SEP[DIGITS]], --number-lines[=SEP[DIGITS]]\n\
2816 number lines, use DIGITS (5) digits, then SEP (TAB),\n\
2817 default counting starts with 1st line of input file\n\
2818 -N, --first-line-number=NUMBER\n\
2819 start counting with NUMBER at 1st line of first\n\
2820 page printed (see +FIRST_PAGE)\n\
2821 "), stdout);
2822 fputs (_("\
2823 -o, --indent=MARGIN\n\
2824 offset each line with MARGIN (zero) spaces, do not\n\
2825 affect -w or -W, MARGIN will be added to PAGE_WIDTH\n\
2826 -r, --no-file-warnings\n\
2827 omit warning when a file cannot be opened\n\
2828 "), stdout);
2829 fputs (_("\
2830 -s[CHAR], --separator[=CHAR]\n\
2831 separate columns by a single character, default for CHAR\n\
2832 is the <TAB> character without -w and \'no char\' with -w.\
2834 -s[CHAR] turns off line truncation of all 3 column\n\
2835 options (-COLUMN|-a -COLUMN|-m) except -w is set\n\
2836 "), stdout);
2837 fputs (_("\
2838 -S[STRING], --sep-string[=STRING]\n\
2839 separate columns by STRING,\n\
2840 without -S: Default separator <TAB> with -J and <space>\n\
2841 otherwise (same as -S\" \"), no effect on column options\n\
2842 "), stdout);
2843 fputs (_("\
2844 -t, --omit-header omit page headers and trailers;\n\
2845 implied if PAGE_LENGTH <= 10\n\
2846 "), stdout);
2847 fputs (_("\
2848 -T, --omit-pagination\n\
2849 omit page headers and trailers, eliminate any pagination\n\
2850 by form feeds set in input files\n\
2851 -v, --show-nonprinting\n\
2852 use octal backslash notation\n\
2853 -w, --width=PAGE_WIDTH\n\
2854 set page width to PAGE_WIDTH (72) characters for\n\
2855 multiple text-column output only, -s[char] turns off (72)\n\
2856 "), stdout);
2857 fputs (_("\
2858 -W, --page-width=PAGE_WIDTH\n\
2859 set page width to PAGE_WIDTH (72) characters always,\n\
2860 truncate lines, except -J option is set, no interference\n\
2861 with -S or -s\n\
2862 "), stdout);
2863 fputs (HELP_OPTION_DESCRIPTION, stdout);
2864 fputs (VERSION_OPTION_DESCRIPTION, stdout);
2865 emit_ancillary_info (PROGRAM_NAME);
2867 exit (status);