test: use consistent quoting
[coreutils.git] / src / pr.c
bloba01a0db1c7c7f51523f13030f2925ef2dcbc1da3
1 /* pr -- convert text files for printing.
2 Copyright (C) 1988-2015 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 <http://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.)
311 #include <config.h>
313 #include <getopt.h>
314 #include <sys/types.h>
315 #include "system.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 "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 void getoptnum (const char *n_str, int min, int *num,
429 const char *errfmt);
430 static void getoptarg (char *arg, char switch_char, char *character,
431 int *number);
432 static void print_files (int number_of_files, char **av);
433 static void init_parameters (int number_of_files);
434 static void init_header (char const *filename, int desc);
435 static bool init_fps (int number_of_files, char **av);
436 static void init_funcs (void);
437 static void init_store_cols (void);
438 static void store_columns (void);
439 static void balance (int total_stored);
440 static void store_char (char c);
441 static void pad_down (unsigned int lines);
442 static void read_rest_of_line (COLUMN *p);
443 static void skip_read (COLUMN *p, int column_number);
444 static void print_char (char c);
445 static void cleanup (void);
446 static void print_sep_string (void);
447 static void separator_string (const char *optarg_S);
449 /* All of the columns to print. */
450 static COLUMN *column_vector;
452 /* When printing a single file in multiple downward columns,
453 we store the leftmost columns contiguously in buff.
454 To print a line from buff, get the index of the first character
455 from line_vector[i], and print up to line_vector[i + 1]. */
456 static char *buff;
458 /* Index of the position in buff where the next character
459 will be stored. */
460 static unsigned int buff_current;
462 /* The number of characters in buff.
463 Used for allocation of buff and to detect overflow of buff. */
464 static size_t buff_allocated;
466 /* Array of indices into buff.
467 Each entry is an index of the first character of a line.
468 This is used when storing lines to facilitate shuffling when
469 we do column balancing on the last page. */
470 static int *line_vector;
472 /* Array of horizonal positions.
473 For each line in line_vector, end_vector[line] is the horizontal
474 position we are in after printing that line. We keep track of this
475 so that we know how much we need to pad to prepare for the next
476 column. */
477 static int *end_vector;
479 /* (-m) True means we're printing multiple files in parallel. */
480 static bool parallel_files = false;
482 /* (-m) True means a line starts with some empty columns (some files
483 already CLOSED or ON_HOLD) which we have to align. */
484 static bool align_empty_cols;
486 /* (-m) True means we have not yet found any printable column in a line.
487 align_empty_cols = true has to be maintained. */
488 static bool empty_line;
490 /* (-m) False means printable column output precedes a form feed found.
491 Column alignment is done only once. No additional action with that form
492 feed.
493 True means we found only a form feed in a column. Maybe we have to do
494 some column alignment with that form feed. */
495 static bool FF_only;
497 /* (-[0-9]+) True means we're given an option explicitly specifying
498 number of columns. Used to detect when this option is used with -m
499 and when translating old options to new/long options. */
500 static bool explicit_columns = false;
502 /* (-t|-T) False means we aren't printing headers and footers. */
503 static bool extremities = true;
505 /* (-t) True means we retain all FF set by hand in input files.
506 False is set with -T option. */
507 static bool keep_FF = false;
508 static bool print_a_FF = false;
510 /* True means we need to print a header as soon as we know we've got input
511 to print after it. */
512 static bool print_a_header;
514 /* (-f) True means use formfeeds instead of newlines to separate pages. */
515 static bool use_form_feed = false;
517 /* True means we have read the standard input. */
518 static bool have_read_stdin = false;
520 /* True means the -a flag has been given. */
521 static bool print_across_flag = false;
523 /* True means we're printing one file in multiple (>1) downward columns. */
524 static bool storing_columns = true;
526 /* (-b) True means balance columns on the last page as Sys V does. */
527 /* That's no longer an independent option. With storing_columns = true
528 balance_columns = true is used too (s. function init_parameters).
529 We get a consistent formulation with "FF set by hand" in input files. */
530 static bool balance_columns = false;
532 /* (-l) Number of lines on a page, including header and footer lines. */
533 static int lines_per_page = 66;
535 /* Number of lines in the header and footer can be reset to 0 using
536 the -t flag. */
537 enum { lines_per_header = 5 };
538 static int lines_per_body;
539 enum { lines_per_footer = 5 };
541 /* (-w|-W) Width in characters of the page. Does not include the width of
542 the margin. */
543 static int chars_per_line = 72;
545 /* (-w|W) True means we truncate lines longer than chars_per_column. */
546 static bool truncate_lines = false;
548 /* (-J) True means we join lines without any line truncation. -J
549 dominates -w option. */
550 static bool join_lines = false;
552 /* Number of characters in a column. Based on col_sep_length and
553 page width. */
554 static int chars_per_column;
556 /* (-e) True means convert tabs to spaces on input. */
557 static bool untabify_input = false;
559 /* (-e) The input tab character. */
560 static char input_tab_char = '\t';
562 /* (-e) Tabstops are at chars_per_tab, 2*chars_per_tab, 3*chars_per_tab, ...
563 where the leftmost column is 1. */
564 static int chars_per_input_tab = 8;
566 /* (-i) True means convert spaces to tabs on output. */
567 static bool tabify_output = false;
569 /* (-i) The output tab character. */
570 static char output_tab_char = '\t';
572 /* (-i) The width of the output tab. */
573 static int chars_per_output_tab = 8;
575 /* Keeps track of pending white space. When we hit a nonspace
576 character after some whitespace, we print whitespace, tabbing
577 if necessary to get to output_position + spaces_not_printed. */
578 static int spaces_not_printed;
580 /* (-o) Number of spaces in the left margin (tabs used when possible). */
581 static int chars_per_margin = 0;
583 /* Position where the next character will fall.
584 Leftmost position is 0 + chars_per_margin.
585 Rightmost position is chars_per_margin + chars_per_line - 1.
586 This is important for converting spaces to tabs on output. */
587 static int output_position;
589 /* Horizontal position relative to the current file.
590 (output_position depends on where we are on the page;
591 input_position depends on where we are in the file.)
592 Important for converting tabs to spaces on input. */
593 static int input_position;
595 /* True if there were any failed opens so we can exit with nonzero
596 status. */
597 static bool failed_opens = false;
599 /* The number of spaces taken up if we print a tab character with width
600 c_ from position h_. */
601 #define TAB_WIDTH(c_, h_) ((c_) - ((h_) % (c_)))
603 /* The horizontal position we'll be at after printing a tab character
604 of width c_ from the position h_. */
605 #define POS_AFTER_TAB(c_, h_) ((h_) + TAB_WIDTH (c_, h_))
607 /* (-NNN) Number of columns of text to print. */
608 static int columns = 1;
610 /* (+NNN:MMM) Page numbers on which to begin and stop printing.
611 first_page_number = 0 will be used to check input only. */
612 static uintmax_t first_page_number = 0;
613 static uintmax_t last_page_number = UINTMAX_MAX;
615 /* Number of files open (not closed, not on hold). */
616 static int files_ready_to_read = 0;
618 /* Current page number. Displayed in header. */
619 static uintmax_t page_number;
621 /* Current line number. Displayed when -n flag is specified.
623 When printing files in parallel (-m flag), line numbering is as follows:
624 1 foo goo moo
625 2 hoo too zoo
627 When printing files across (-a flag), ...
628 1 foo 2 moo 3 goo
629 4 hoo 5 too 6 zoo
631 Otherwise, line numbering is as follows:
632 1 foo 3 goo 5 too
633 2 moo 4 hoo 6 zoo */
634 static int line_number;
636 /* (-n) True means lines should be preceded by numbers. */
637 static bool numbered_lines = false;
639 /* (-n) Character which follows each line number. */
640 static char number_separator = '\t';
642 /* (-n) line counting starts with 1st line of input file (not with 1st
643 line of 1st page printed). */
644 static int line_count = 1;
646 /* (-n) True means counting of skipped lines starts with 1st line of
647 input file. False means -N option is used in addition, counting of
648 skipped lines not required. */
649 static bool skip_count = true;
651 /* (-N) Counting starts with start_line_number = NUMBER at 1st line of
652 first page printed, usually not 1st page of input file. */
653 static int start_line_num = 1;
655 /* (-n) Width in characters of a line number. */
656 static int chars_per_number = 5;
658 /* Used when widening the first column to accommodate numbers -- only
659 needed when printing files in parallel. Includes width of both the
660 number and the number_separator. */
661 static int number_width;
663 /* Buffer sprintf uses to format a line number. */
664 static char *number_buff;
666 /* (-v) True means unprintable characters are printed as escape sequences.
667 control-g becomes \007. */
668 static bool use_esc_sequence = false;
670 /* (-c) True means unprintable characters are printed as control prefixes.
671 control-g becomes ^G. */
672 static bool use_cntrl_prefix = false;
674 /* (-d) True means output is double spaced. */
675 static bool double_space = false;
677 /* Number of files opened initially in init_files. Should be 1
678 unless we're printing multiple files in parallel. */
679 static int total_files = 0;
681 /* (-r) True means don't complain if we can't open a file. */
682 static bool ignore_failed_opens = false;
684 /* (-S) True means we separate columns with a specified string.
685 -S option does not affect line truncation nor column alignment. */
686 static bool use_col_separator = false;
688 /* String used to separate columns if the -S option has been specified.
689 Default without -S but together with one of the column options
690 -a|COLUMN|-m is a 'space' and with the -J option a 'tab'. */
691 static char *col_sep_string = (char *) "";
692 static int col_sep_length = 0;
693 static char *column_separator = (char *) " ";
694 static char *line_separator = (char *) "\t";
696 /* Number of separator characters waiting to be printed as soon as we
697 know that we have any input remaining to be printed. */
698 static int separators_not_printed;
700 /* Position we need to pad to, as soon as we know that we have input
701 remaining to be printed. */
702 static int padding_not_printed;
704 /* True means we should pad the end of the page. Remains false until we
705 know we have a page to print. */
706 static bool pad_vertically;
708 /* (-h) String of characters used in place of the filename in the header. */
709 static char *custom_header;
711 /* (-D) Date format for the header. */
712 static char const *date_format;
714 /* Date and file name for the header. */
715 static char *date_text;
716 static char const *file_text;
718 /* Output columns available, not counting the date and file name. */
719 static int header_width_available;
721 static char *clump_buff;
723 /* True means we read the line no. lines_per_body in skip_read
724 called by skip_to_page. That variable controls the coincidence of a
725 "FF set by hand" and "full_page_printed", see above the definition of
726 structure COLUMN. */
727 static bool last_line = false;
729 /* For long options that have no equivalent short option, use a
730 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
731 enum
733 COLUMNS_OPTION = CHAR_MAX + 1,
734 PAGES_OPTION
737 static char const short_options[] =
738 "-0123456789D:FJN:S::TW:abcde::fh:i::l:mn::o:rs::tvw:";
740 static struct option const long_options[] =
742 {"pages", required_argument, NULL, PAGES_OPTION},
743 {"columns", required_argument, NULL, COLUMNS_OPTION},
744 {"across", no_argument, NULL, 'a'},
745 {"show-control-chars", no_argument, NULL, 'c'},
746 {"double-space", no_argument, NULL, 'd'},
747 {"date-format", required_argument, NULL, 'D'},
748 {"expand-tabs", optional_argument, NULL, 'e'},
749 {"form-feed", no_argument, NULL, 'f'},
750 {"header", required_argument, NULL, 'h'},
751 {"output-tabs", optional_argument, NULL, 'i'},
752 {"join-lines", no_argument, NULL, 'J'},
753 {"length", required_argument, NULL, 'l'},
754 {"merge", no_argument, NULL, 'm'},
755 {"number-lines", optional_argument, NULL, 'n'},
756 {"first-line-number", required_argument, NULL, 'N'},
757 {"indent", required_argument, NULL, 'o'},
758 {"no-file-warnings", no_argument, NULL, 'r'},
759 {"separator", optional_argument, NULL, 's'},
760 {"sep-string", optional_argument, NULL, 'S'},
761 {"omit-header", no_argument, NULL, 't'},
762 {"omit-pagination", no_argument, NULL, 'T'},
763 {"show-nonprinting", no_argument, NULL, 'v'},
764 {"width", required_argument, NULL, 'w'},
765 {"page-width", required_argument, NULL, 'W'},
766 {GETOPT_HELP_OPTION_DECL},
767 {GETOPT_VERSION_OPTION_DECL},
768 {NULL, 0, NULL, 0}
771 /* Return the number of columns that have either an open file or
772 stored lines. */
774 static unsigned int _GL_ATTRIBUTE_PURE
775 cols_ready_to_print (void)
777 COLUMN *q;
778 unsigned int i;
779 unsigned int n;
781 n = 0;
782 for (q = column_vector, i = 0; i < columns; ++q, ++i)
783 if (q->status == OPEN
784 || q->status == FF_FOUND /* With -b: To print a header only */
785 || (storing_columns && q->lines_stored > 0 && q->lines_to_print > 0))
786 ++n;
787 return n;
790 /* Estimate first_ / last_page_number
791 using option +FIRST_PAGE:LAST_PAGE */
793 static bool
794 first_last_page (int oi, char c, char const *pages)
796 char *p;
797 uintmax_t first;
798 uintmax_t last = UINTMAX_MAX;
799 strtol_error err = xstrtoumax (pages, &p, 10, &first, "");
800 if (err != LONGINT_OK && err != LONGINT_INVALID_SUFFIX_CHAR)
801 xstrtol_fatal (err, oi, c, long_options, pages);
803 if (p == pages || !first)
804 return false;
806 if (*p == ':')
808 char const *p1 = p + 1;
809 err = xstrtoumax (p1, &p, 10, &last, "");
810 if (err != LONGINT_OK)
811 xstrtol_fatal (err, oi, c, long_options, pages);
812 if (p1 == p || last < first)
813 return false;
816 if (*p)
817 return false;
819 first_page_number = first;
820 last_page_number = last;
821 return true;
824 /* Parse column count string S, and if it's valid (1 or larger and
825 within range of the type of 'columns') set the global variables
826 columns and explicit_columns. Otherwise, exit with a diagnostic. */
828 static void
829 parse_column_count (char const *s)
831 getoptnum (s, 1, &columns, _("invalid number of columns"));
832 explicit_columns = true;
835 /* Estimate length of col_sep_string with option -S. */
837 static void
838 separator_string (const char *optarg_S)
840 col_sep_length = (int) strlen (optarg_S);
841 col_sep_string = xmalloc (col_sep_length + 1);
842 strcpy (col_sep_string, optarg_S);
846 main (int argc, char **argv)
848 int n_files;
849 bool old_options = false;
850 bool old_w = false;
851 bool old_s = false;
852 char **file_names;
854 /* Accumulate the digits of old-style options like -99. */
855 char *column_count_string = NULL;
856 size_t n_digits = 0;
857 size_t n_alloc = 0;
859 initialize_main (&argc, &argv);
860 set_program_name (argv[0]);
861 setlocale (LC_ALL, "");
862 bindtextdomain (PACKAGE, LOCALEDIR);
863 textdomain (PACKAGE);
865 atexit (close_stdout);
867 n_files = 0;
868 file_names = (argc > 1
869 ? xmalloc ((argc - 1) * sizeof (char *))
870 : NULL);
872 while (true)
874 int oi = -1;
875 int c = getopt_long (argc, argv, short_options, long_options, &oi);
876 if (c == -1)
877 break;
879 if (ISDIGIT (c))
881 /* Accumulate column-count digits specified via old-style options. */
882 if (n_digits + 1 >= n_alloc)
883 column_count_string
884 = X2REALLOC (column_count_string, &n_alloc);
885 column_count_string[n_digits++] = c;
886 column_count_string[n_digits] = '\0';
887 continue;
890 n_digits = 0;
892 switch (c)
894 case 1: /* Non-option argument. */
895 /* long option --page dominates old '+FIRST_PAGE ...'. */
896 if (! (first_page_number == 0
897 && *optarg == '+' && first_last_page (-2, '+', optarg + 1)))
898 file_names[n_files++] = optarg;
899 break;
901 case PAGES_OPTION: /* --pages=FIRST_PAGE[:LAST_PAGE] */
902 { /* dominates old opt +... */
903 if (! optarg)
904 error (EXIT_FAILURE, 0,
905 _("'--pages=FIRST_PAGE[:LAST_PAGE]' missing argument"));
906 else if (! first_last_page (oi, 0, optarg))
907 error (EXIT_FAILURE, 0, _("invalid page range %s"),
908 quote (optarg));
909 break;
912 case COLUMNS_OPTION: /* --columns=COLUMN */
914 parse_column_count (optarg);
916 /* If there was a prior column count specified via the
917 short-named option syntax, e.g., -9, ensure that this
918 long-name-specified value overrides it. */
919 free (column_count_string);
920 column_count_string = NULL;
921 n_alloc = 0;
922 break;
925 case 'a':
926 print_across_flag = true;
927 storing_columns = false;
928 break;
929 case 'b':
930 balance_columns = true;
931 break;
932 case 'c':
933 use_cntrl_prefix = true;
934 break;
935 case 'd':
936 double_space = true;
937 break;
938 case 'D':
939 date_format = optarg;
940 break;
941 case 'e':
942 if (optarg)
943 getoptarg (optarg, 'e', &input_tab_char,
944 &chars_per_input_tab);
945 /* Could check tab width > 0. */
946 untabify_input = true;
947 break;
948 case 'f':
949 case 'F':
950 use_form_feed = true;
951 break;
952 case 'h':
953 custom_header = optarg;
954 break;
955 case 'i':
956 if (optarg)
957 getoptarg (optarg, 'i', &output_tab_char,
958 &chars_per_output_tab);
959 /* Could check tab width > 0. */
960 tabify_output = true;
961 break;
962 case 'J':
963 join_lines = true;
964 break;
965 case 'l':
966 getoptnum (optarg, 1, &lines_per_page,
967 _("'-l PAGE_LENGTH' invalid number of lines"));
968 break;
969 case 'm':
970 parallel_files = true;
971 storing_columns = false;
972 break;
973 case 'n':
974 numbered_lines = true;
975 if (optarg)
976 getoptarg (optarg, 'n', &number_separator,
977 &chars_per_number);
978 break;
979 case 'N':
980 skip_count = false;
981 getoptnum (optarg, INT_MIN, &start_line_num,
982 _("'-N NUMBER' invalid starting line number"));
983 break;
984 case 'o':
985 getoptnum (optarg, 0, &chars_per_margin,
986 _("'-o MARGIN' invalid line offset"));
987 break;
988 case 'r':
989 ignore_failed_opens = true;
990 break;
991 case 's':
992 old_options = true;
993 old_s = true;
994 if (!use_col_separator && optarg)
995 separator_string (optarg);
996 break;
997 case 'S':
998 old_s = false;
999 /* Reset an additional input of -s, -S dominates -s */
1000 col_sep_string = bad_cast ("");
1001 col_sep_length = 0;
1002 use_col_separator = true;
1003 if (optarg)
1004 separator_string (optarg);
1005 break;
1006 case 't':
1007 extremities = false;
1008 keep_FF = true;
1009 break;
1010 case 'T':
1011 extremities = false;
1012 keep_FF = false;
1013 break;
1014 case 'v':
1015 use_esc_sequence = true;
1016 break;
1017 case 'w':
1018 old_options = true;
1019 old_w = true;
1021 int tmp_cpl;
1022 getoptnum (optarg, 1, &tmp_cpl,
1023 _("'-w PAGE_WIDTH' invalid number of characters"));
1024 if (! truncate_lines)
1025 chars_per_line = tmp_cpl;
1027 break;
1028 case 'W':
1029 old_w = false; /* dominates -w */
1030 truncate_lines = true;
1031 getoptnum (optarg, 1, &chars_per_line,
1032 _("'-W PAGE_WIDTH' invalid number of characters"));
1033 break;
1034 case_GETOPT_HELP_CHAR;
1035 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1036 default:
1037 usage (EXIT_FAILURE);
1038 break;
1042 if (column_count_string)
1044 parse_column_count (column_count_string);
1045 free (column_count_string);
1048 if (! date_format)
1049 date_format = (getenv ("POSIXLY_CORRECT") && !hard_locale (LC_TIME)
1050 ? "%b %e %H:%M %Y"
1051 : "%Y-%m-%d %H:%M");
1053 /* Now we can set a reasonable initial value: */
1054 if (first_page_number == 0)
1055 first_page_number = 1;
1057 if (parallel_files && explicit_columns)
1058 error (EXIT_FAILURE, 0,
1059 _("cannot specify number of columns when printing in parallel"));
1061 if (parallel_files && print_across_flag)
1062 error (EXIT_FAILURE, 0,
1063 _("cannot specify both printing across and printing in parallel"));
1065 /* Translate some old short options to new/long options.
1066 To meet downward compatibility with other UNIX pr utilities
1067 and some POSIX specifications. */
1069 if (old_options)
1071 if (old_w)
1073 if (parallel_files || explicit_columns)
1075 /* activate -W */
1076 truncate_lines = true;
1077 if (old_s)
1078 /* adapt HP-UX and SunOS: -s = no separator;
1079 activate -S */
1080 use_col_separator = true;
1082 else
1083 /* old -w sets width with columns only
1084 activate -J */
1085 join_lines = true;
1087 else if (!use_col_separator)
1089 /* No -S option read */
1090 if (old_s && (parallel_files || explicit_columns))
1092 if (!truncate_lines)
1094 /* old -s (without -w and -W) annuls column alignment,
1095 uses fields, activate -J */
1096 join_lines = true;
1097 if (col_sep_length > 0)
1098 /* activate -S */
1099 use_col_separator = true;
1101 else
1102 /* with -W */
1103 /* adapt HP-UX and SunOS: -s = no separator;
1104 activate -S */
1105 use_col_separator = true;
1110 for (; optind < argc; optind++)
1112 file_names[n_files++] = argv[optind];
1115 if (n_files == 0)
1117 /* No file arguments specified; read from standard input. */
1118 print_files (0, NULL);
1120 else
1122 if (parallel_files)
1123 print_files (n_files, file_names);
1124 else
1126 unsigned int i;
1127 for (i = 0; i < n_files; i++)
1128 print_files (1, &file_names[i]);
1132 cleanup ();
1133 IF_LINT (free (file_names));
1135 if (have_read_stdin && fclose (stdin) == EOF)
1136 error (EXIT_FAILURE, errno, _("standard input"));
1137 return failed_opens ? EXIT_FAILURE : EXIT_SUCCESS;
1140 /* Parse numeric arguments, ensuring MIN <= number <= INT_MAX. */
1142 static void
1143 getoptnum (const char *n_str, int min, int *num, const char *err)
1145 intmax_t tnum = xdectoimax (n_str, min, INT_MAX, "", err, 0);
1146 *num = tnum;
1149 /* Parse options of the form -scNNN.
1151 Example: -nck, where 'n' is the option, c is the optional number
1152 separator, and k is the optional width of the field used when printing
1153 a number. */
1155 static void
1156 getoptarg (char *arg, char switch_char, char *character, int *number)
1158 if (!ISDIGIT (*arg))
1159 *character = *arg++;
1160 if (*arg)
1162 long int tmp_long;
1163 if (xstrtol (arg, NULL, 10, &tmp_long, "") != LONGINT_OK
1164 || tmp_long <= 0 || INT_MAX < tmp_long)
1166 error (0, INT_MAX < tmp_long ? EOVERFLOW : errno,
1167 _("'-%c' extra characters or invalid number in the argument: %s"),
1168 switch_char, quote (arg));
1169 usage (EXIT_FAILURE);
1171 *number = tmp_long;
1175 /* Set parameters related to formatting. */
1177 static void
1178 init_parameters (int number_of_files)
1180 int chars_used_by_number = 0;
1182 lines_per_body = lines_per_page - lines_per_header - lines_per_footer;
1183 if (lines_per_body <= 0)
1185 extremities = false;
1186 keep_FF = true;
1188 if (extremities == false)
1189 lines_per_body = lines_per_page;
1191 if (double_space)
1192 lines_per_body = lines_per_body / 2;
1194 /* If input is stdin, cannot print parallel files. BSD dumps core
1195 on this. */
1196 if (number_of_files == 0)
1197 parallel_files = false;
1199 if (parallel_files)
1200 columns = number_of_files;
1202 /* One file, multi columns down: -b option is set to get a consistent
1203 formulation with "FF set by hand" in input files. */
1204 if (storing_columns)
1205 balance_columns = true;
1207 /* Tabification is assumed for multiple columns. */
1208 if (columns > 1)
1210 if (!use_col_separator)
1212 /* Use default separator */
1213 if (join_lines)
1214 col_sep_string = line_separator;
1215 else
1216 col_sep_string = column_separator;
1218 col_sep_length = 1;
1219 use_col_separator = true;
1221 /* It's rather pointless to define a TAB separator with column
1222 alignment */
1223 else if (!join_lines && *col_sep_string == '\t')
1224 col_sep_string = column_separator;
1226 truncate_lines = true;
1227 tabify_output = true;
1229 else
1230 storing_columns = false;
1232 /* -J dominates -w in any case */
1233 if (join_lines)
1234 truncate_lines = false;
1236 if (numbered_lines)
1238 int chars_per_default_tab = 8;
1240 line_count = start_line_num;
1242 /* To allow input tab-expansion (-e sensitive) use:
1243 if (number_separator == input_tab_char)
1244 number_width = chars_per_number
1245 + TAB_WIDTH (chars_per_input_tab, chars_per_number); */
1247 /* Estimate chars_per_text without any margin and keep it constant. */
1248 if (number_separator == '\t')
1249 number_width = (chars_per_number
1250 + TAB_WIDTH (chars_per_default_tab, chars_per_number));
1251 else
1252 number_width = chars_per_number + 1;
1254 /* The number is part of the column width unless we are
1255 printing files in parallel. */
1256 if (parallel_files)
1257 chars_used_by_number = number_width;
1260 chars_per_column = (chars_per_line - chars_used_by_number
1261 - (columns - 1) * col_sep_length) / columns;
1263 if (chars_per_column < 1)
1264 error (EXIT_FAILURE, 0, _("page width too narrow"));
1266 if (numbered_lines)
1268 free (number_buff);
1269 number_buff = xmalloc (MAX (chars_per_number,
1270 INT_STRLEN_BOUND (line_number)) + 1);
1273 /* Pick the maximum between the tab width and the width of an
1274 escape sequence.
1275 The width of an escape sequence (4) isn't the lower limit any longer.
1276 We've to use 8 as the lower limit, if we use chars_per_default_tab = 8
1277 to expand a tab which is not an input_tab-char. */
1278 free (clump_buff);
1279 clump_buff = xmalloc (MAX (8, chars_per_input_tab));
1282 /* Open the necessary files,
1283 maintaining a COLUMN structure for each column.
1285 With multiple files, each column p has a different p->fp.
1286 With single files, each column p has the same p->fp.
1287 Return false if (number_of_files > 0) and no files can be opened,
1288 true otherwise.
1290 With each column/file p, p->full_page_printed is initialized,
1291 see also open_file. */
1293 static bool
1294 init_fps (int number_of_files, char **av)
1296 int i, files_left;
1297 COLUMN *p;
1298 FILE *firstfp;
1299 char const *firstname;
1301 total_files = 0;
1303 free (column_vector);
1304 column_vector = xnmalloc (columns, sizeof (COLUMN));
1306 if (parallel_files)
1308 files_left = number_of_files;
1309 for (p = column_vector; files_left--; ++p, ++av)
1311 if (! open_file (*av, p))
1313 --p;
1314 --columns;
1317 if (columns == 0)
1318 return false;
1319 init_header ("", -1);
1321 else
1323 p = column_vector;
1324 if (number_of_files > 0)
1326 if (! open_file (*av, p))
1327 return false;
1328 init_header (*av, fileno (p->fp));
1329 p->lines_stored = 0;
1331 else
1333 p->name = _("standard input");
1334 p->fp = stdin;
1335 have_read_stdin = true;
1336 p->status = OPEN;
1337 p->full_page_printed = false;
1338 ++total_files;
1339 init_header ("", -1);
1340 p->lines_stored = 0;
1343 firstname = p->name;
1344 firstfp = p->fp;
1345 for (i = columns - 1, ++p; i; --i, ++p)
1347 p->name = firstname;
1348 p->fp = firstfp;
1349 p->status = OPEN;
1350 p->full_page_printed = false;
1351 p->lines_stored = 0;
1354 files_ready_to_read = total_files;
1355 return true;
1358 /* Determine print_func and char_func, the functions
1359 used by each column for printing and/or storing.
1361 Determine the horizontal position desired when we begin
1362 printing a column (p->start_position). */
1364 static void
1365 init_funcs (void)
1367 int i, h, h_next;
1368 COLUMN *p;
1370 h = chars_per_margin;
1372 if (!truncate_lines)
1373 h_next = ANYWHERE;
1374 else
1376 /* When numbering lines of parallel files, we enlarge the
1377 first column to accommodate the number. Looks better than
1378 the Sys V approach. */
1379 if (parallel_files && numbered_lines)
1380 h_next = h + chars_per_column + number_width;
1381 else
1382 h_next = h + chars_per_column;
1385 /* Enlarge p->start_position of first column to use the same form of
1386 padding_not_printed with all columns. */
1387 h = h + col_sep_length;
1389 /* This loop takes care of all but the rightmost column. */
1391 for (p = column_vector, i = 1; i < columns; ++p, ++i)
1393 if (storing_columns) /* One file, multi columns down. */
1395 p->char_func = store_char;
1396 p->print_func = print_stored;
1398 else
1399 /* One file, multi columns across; or parallel files. */
1401 p->char_func = print_char;
1402 p->print_func = read_line;
1405 /* Number only the first column when printing files in
1406 parallel. */
1407 p->numbered = numbered_lines && (!parallel_files || i == 1);
1408 p->start_position = h;
1410 /* If we don't truncate lines, all start_positions are
1411 ANYWHERE, except the first column's start_position when
1412 using a margin. */
1414 if (!truncate_lines)
1416 h = ANYWHERE;
1417 h_next = ANYWHERE;
1419 else
1421 h = h_next + col_sep_length;
1422 h_next = h + chars_per_column;
1426 /* The rightmost column.
1428 Doesn't need to be stored unless we intend to balance
1429 columns on the last page. */
1430 if (storing_columns && balance_columns)
1432 p->char_func = store_char;
1433 p->print_func = print_stored;
1435 else
1437 p->char_func = print_char;
1438 p->print_func = read_line;
1441 p->numbered = numbered_lines && (!parallel_files || i == 1);
1442 p->start_position = h;
1445 /* Open a file. Return true if successful.
1447 With each file p, p->full_page_printed is initialized,
1448 see also init_fps. */
1450 static bool
1451 open_file (char *name, COLUMN *p)
1453 if (STREQ (name, "-"))
1455 p->name = _("standard input");
1456 p->fp = stdin;
1457 have_read_stdin = true;
1459 else
1461 p->name = name;
1462 p->fp = fopen (name, "r");
1464 if (p->fp == NULL)
1466 failed_opens = true;
1467 if (!ignore_failed_opens)
1468 error (0, errno, "%s", quotef (name));
1469 return false;
1471 fadvise (p->fp, FADVISE_SEQUENTIAL);
1472 p->status = OPEN;
1473 p->full_page_printed = false;
1474 ++total_files;
1475 return true;
1478 /* Close the file in P.
1480 If we aren't dealing with multiple files in parallel, we change
1481 the status of all columns in the column list to reflect the close. */
1483 static void
1484 close_file (COLUMN *p)
1486 COLUMN *q;
1487 int i;
1489 if (p->status == CLOSED)
1490 return;
1491 if (ferror (p->fp))
1492 error (EXIT_FAILURE, errno, "%s", quotef (p->name));
1493 if (fileno (p->fp) != STDIN_FILENO && fclose (p->fp) != 0)
1494 error (EXIT_FAILURE, errno, "%s", quotef (p->name));
1496 if (!parallel_files)
1498 for (q = column_vector, i = columns; i; ++q, --i)
1500 q->status = CLOSED;
1501 if (q->lines_stored == 0)
1503 q->lines_to_print = 0;
1507 else
1509 p->status = CLOSED;
1510 p->lines_to_print = 0;
1513 --files_ready_to_read;
1516 /* Put a file on hold until we start a new page,
1517 since we've hit a form feed.
1519 If we aren't dealing with parallel files, we must change the
1520 status of all columns in the column list. */
1522 static void
1523 hold_file (COLUMN *p)
1525 COLUMN *q;
1526 int i;
1528 if (!parallel_files)
1529 for (q = column_vector, i = columns; i; ++q, --i)
1531 if (storing_columns)
1532 q->status = FF_FOUND;
1533 else
1534 q->status = ON_HOLD;
1536 else
1537 p->status = ON_HOLD;
1539 p->lines_to_print = 0;
1540 --files_ready_to_read;
1543 /* Undo hold_file -- go through the column list and change any
1544 ON_HOLD columns to OPEN. Used at the end of each page. */
1546 static void
1547 reset_status (void)
1549 int i = columns;
1550 COLUMN *p;
1552 for (p = column_vector; i; --i, ++p)
1553 if (p->status == ON_HOLD)
1555 p->status = OPEN;
1556 files_ready_to_read++;
1559 if (storing_columns)
1561 if (column_vector->status == CLOSED)
1562 /* We use the info to output an error message in skip_to_page. */
1563 files_ready_to_read = 0;
1564 else
1565 files_ready_to_read = 1;
1569 /* Print a single file, or multiple files in parallel.
1571 Set up the list of columns, opening the necessary files.
1572 Allocate space for storing columns, if necessary.
1573 Skip to first_page_number, if user has asked to skip leading pages.
1574 Determine which functions are appropriate to store/print lines
1575 in each column.
1576 Print the file(s). */
1578 static void
1579 print_files (int number_of_files, char **av)
1581 init_parameters (number_of_files);
1582 if (! init_fps (number_of_files, av))
1583 return;
1584 if (storing_columns)
1585 init_store_cols ();
1587 if (first_page_number > 1)
1589 if (!skip_to_page (first_page_number))
1590 return;
1591 else
1592 page_number = first_page_number;
1594 else
1595 page_number = 1;
1597 init_funcs ();
1599 line_number = line_count;
1600 while (print_page ())
1604 /* Initialize header information.
1605 If DESC is non-negative, it is a file descriptor open to
1606 FILENAME for reading. */
1608 static void
1609 init_header (char const *filename, int desc)
1611 char *buf = NULL;
1612 struct stat st;
1613 struct timespec t;
1614 int ns;
1615 struct tm *tm;
1617 /* If parallel files or standard input, use current date. */
1618 if (STREQ (filename, "-"))
1619 desc = -1;
1620 if (0 <= desc && fstat (desc, &st) == 0)
1621 t = get_stat_mtime (&st);
1622 else
1624 static struct timespec timespec;
1625 if (! timespec.tv_sec)
1626 gettime (&timespec);
1627 t = timespec;
1630 ns = t.tv_nsec;
1631 tm = localtime (&t.tv_sec);
1632 if (tm == NULL)
1634 buf = xmalloc (INT_BUFSIZE_BOUND (long int)
1635 + MAX (10, INT_BUFSIZE_BOUND (int)));
1636 sprintf (buf, "%ld.%09d", (long int) t.tv_sec, ns);
1638 else
1640 size_t bufsize = nstrftime (NULL, SIZE_MAX, date_format, tm, 0, ns) + 1;
1641 buf = xmalloc (bufsize);
1642 nstrftime (buf, bufsize, date_format, tm, 0, ns);
1645 free (date_text);
1646 date_text = buf;
1647 file_text = custom_header ? custom_header : desc < 0 ? "" : filename;
1648 header_width_available = (chars_per_line
1649 - mbswidth (date_text, 0)
1650 - mbswidth (file_text, 0));
1653 /* Set things up for printing a page
1655 Scan through the columns ...
1656 Determine which are ready to print
1657 (i.e., which have lines stored or open files)
1658 Set p->lines_to_print appropriately
1659 (to p->lines_stored if we're storing, or lines_per_body
1660 if we're reading straight from the file)
1661 Keep track of this total so we know when to stop printing */
1663 static void
1664 init_page (void)
1666 int j;
1667 COLUMN *p;
1669 if (storing_columns)
1671 store_columns ();
1672 for (j = columns - 1, p = column_vector; j; --j, ++p)
1674 p->lines_to_print = p->lines_stored;
1677 /* Last column. */
1678 if (balance_columns)
1680 p->lines_to_print = p->lines_stored;
1682 /* Since we're not balancing columns, we don't need to store
1683 the rightmost column. Read it straight from the file. */
1684 else
1686 if (p->status == OPEN)
1688 p->lines_to_print = lines_per_body;
1690 else
1691 p->lines_to_print = 0;
1694 else
1695 for (j = columns, p = column_vector; j; --j, ++p)
1696 if (p->status == OPEN)
1698 p->lines_to_print = lines_per_body;
1700 else
1701 p->lines_to_print = 0;
1704 /* Align empty columns and print separators.
1705 Empty columns will be formed by files with status ON_HOLD or CLOSED
1706 when printing multiple files in parallel. */
1708 static void
1709 align_column (COLUMN *p)
1711 padding_not_printed = p->start_position;
1712 if (padding_not_printed - col_sep_length > 0)
1714 pad_across_to (padding_not_printed - col_sep_length);
1715 padding_not_printed = ANYWHERE;
1718 if (use_col_separator)
1719 print_sep_string ();
1721 if (p->numbered)
1722 add_line_number (p);
1725 /* Print one page.
1727 As long as there are lines left on the page and columns ready to print,
1728 Scan across the column list
1729 if the column has stored lines or the file is open
1730 pad to the appropriate spot
1731 print the column
1732 pad the remainder of the page with \n or \f as requested
1733 reset the status of all files -- any files which where on hold because
1734 of formfeeds are now put back into the lineup. */
1736 static bool
1737 print_page (void)
1739 int j;
1740 int lines_left_on_page;
1741 COLUMN *p;
1743 /* Used as an accumulator (with | operator) of successive values of
1744 pad_vertically. The trick is to set pad_vertically
1745 to false before each run through the inner loop, then after that
1746 loop, it tells us whether a line was actually printed (whether a
1747 newline needs to be output -- or two for double spacing). But those
1748 values have to be accumulated (in pv) so we can invoke pad_down
1749 properly after the outer loop completes. */
1750 bool pv;
1752 init_page ();
1754 if (cols_ready_to_print () == 0)
1755 return false;
1757 if (extremities)
1758 print_a_header = true;
1760 /* Don't pad unless we know a page was printed. */
1761 pad_vertically = false;
1762 pv = false;
1764 lines_left_on_page = lines_per_body;
1765 if (double_space)
1766 lines_left_on_page *= 2;
1768 while (lines_left_on_page > 0 && cols_ready_to_print () > 0)
1770 output_position = 0;
1771 spaces_not_printed = 0;
1772 separators_not_printed = 0;
1773 pad_vertically = false;
1774 align_empty_cols = false;
1775 empty_line = true;
1777 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
1779 input_position = 0;
1780 if (p->lines_to_print > 0 || p->status == FF_FOUND)
1782 FF_only = false;
1783 padding_not_printed = p->start_position;
1784 if (!(p->print_func) (p))
1785 read_rest_of_line (p);
1786 pv |= pad_vertically;
1788 --p->lines_to_print;
1789 if (p->lines_to_print <= 0)
1791 if (cols_ready_to_print () == 0)
1792 break;
1795 /* File p changed its status to ON_HOLD or CLOSED */
1796 if (parallel_files && p->status != OPEN)
1798 if (empty_line)
1799 align_empty_cols = true;
1800 else if (p->status == CLOSED
1801 || (p->status == ON_HOLD && FF_only))
1802 align_column (p);
1805 else if (parallel_files)
1807 /* File status ON_HOLD or CLOSED */
1808 if (empty_line)
1809 align_empty_cols = true;
1810 else
1811 align_column (p);
1814 /* We need it also with an empty column */
1815 if (use_col_separator)
1816 ++separators_not_printed;
1819 if (pad_vertically)
1821 putchar ('\n');
1822 --lines_left_on_page;
1825 if (cols_ready_to_print () == 0 && !extremities)
1826 break;
1828 if (double_space && pv)
1830 putchar ('\n');
1831 --lines_left_on_page;
1835 if (lines_left_on_page == 0)
1836 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
1837 if (p->status == OPEN)
1838 p->full_page_printed = true;
1840 pad_vertically = pv;
1842 if (pad_vertically && extremities)
1843 pad_down (lines_left_on_page + lines_per_footer);
1844 else if (keep_FF && print_a_FF)
1846 putchar ('\f');
1847 print_a_FF = false;
1850 if (last_page_number < ++page_number)
1851 return false; /* Stop printing with LAST_PAGE */
1853 reset_status (); /* Change ON_HOLD to OPEN. */
1855 return true; /* More pages to go. */
1858 /* Allocate space for storing columns.
1860 This is necessary when printing multiple columns from a single file.
1861 Lines are stored consecutively in buff, separated by '\0'.
1863 The following doesn't apply any longer - any tuning possible?
1864 (We can't use a fixed offset since with the '-s' flag lines aren't
1865 truncated.)
1867 We maintain a list (line_vector) of pointers to the beginnings
1868 of lines in buff. We allocate one more than the number of lines
1869 because the last entry tells us the index of the last character,
1870 which we need to know in order to print the last line in buff. */
1872 static void
1873 init_store_cols (void)
1875 int total_lines = lines_per_body * columns;
1876 int chars_if_truncate = total_lines * (chars_per_column + 1);
1878 free (line_vector);
1879 /* FIXME: here's where it was allocated. */
1880 line_vector = xmalloc ((total_lines + 1) * sizeof *line_vector);
1882 free (end_vector);
1883 end_vector = xmalloc (total_lines * sizeof *end_vector);
1885 free (buff);
1886 buff_allocated = (use_col_separator
1887 ? 2 * chars_if_truncate
1888 : chars_if_truncate); /* Tune this. */
1889 buff = xmalloc (buff_allocated);
1892 /* Store all but the rightmost column.
1893 (Used when printing a single file in multiple downward columns)
1895 For each column
1896 set p->current_line to be the index in line_vector of the
1897 first line in the column
1898 For each line in the column
1899 store the line in buff
1900 add to line_vector the index of the line's first char
1901 buff_start is the index in buff of the first character in the
1902 current line. */
1904 static void
1905 store_columns (void)
1907 int i, j;
1908 unsigned int line = 0;
1909 unsigned int buff_start;
1910 int last_col; /* The rightmost column which will be saved in buff */
1911 COLUMN *p;
1913 buff_current = 0;
1914 buff_start = 0;
1916 if (balance_columns)
1917 last_col = columns;
1918 else
1919 last_col = columns - 1;
1921 for (i = 1, p = column_vector; i <= last_col; ++i, ++p)
1922 p->lines_stored = 0;
1924 for (i = 1, p = column_vector; i <= last_col && files_ready_to_read;
1925 ++i, ++p)
1927 p->current_line = line;
1928 for (j = lines_per_body; j && files_ready_to_read; --j)
1930 if (p->status == OPEN) /* Redundant. Clean up. */
1932 input_position = 0;
1934 if (!read_line (p))
1935 read_rest_of_line (p);
1937 if (p->status == OPEN
1938 || buff_start != buff_current)
1940 ++p->lines_stored;
1941 line_vector[line] = buff_start;
1942 end_vector[line++] = input_position;
1943 buff_start = buff_current;
1948 /* Keep track of the location of the last char in buff. */
1949 line_vector[line] = buff_start;
1951 if (balance_columns)
1952 balance (line);
1955 static void
1956 balance (int total_stored)
1958 COLUMN *p;
1959 int i, lines;
1960 int first_line = 0;
1962 for (i = 1, p = column_vector; i <= columns; ++i, ++p)
1964 lines = total_stored / columns;
1965 if (i <= total_stored % columns)
1966 ++lines;
1968 p->lines_stored = lines;
1969 p->current_line = first_line;
1971 first_line += lines;
1975 /* Store a character in the buffer. */
1977 static void
1978 store_char (char c)
1980 if (buff_current >= buff_allocated)
1982 /* May be too generous. */
1983 buff = X2REALLOC (buff, &buff_allocated);
1985 buff[buff_current++] = c;
1988 static void
1989 add_line_number (COLUMN *p)
1991 int i;
1992 char *s;
1993 int num_width;
1995 /* Cutting off the higher-order digits is more informative than
1996 lower-order cut off. */
1997 num_width = sprintf (number_buff, "%*d", chars_per_number, line_number);
1998 line_number++;
1999 s = number_buff + (num_width - chars_per_number);
2000 for (i = chars_per_number; i > 0; i--)
2001 (p->char_func) (*s++);
2003 if (columns > 1)
2005 /* Tabification is assumed for multiple columns, also for n-separators,
2006 but 'default n-separator = TAB' hasn't been given priority over
2007 equal column_width also specified by POSIX. */
2008 if (number_separator == '\t')
2010 i = number_width - chars_per_number;
2011 while (i-- > 0)
2012 (p->char_func) (' ');
2014 else
2015 (p->char_func) (number_separator);
2017 else
2018 /* To comply with POSIX, we avoid any expansion of default TAB
2019 separator with a single column output. No column_width requirement
2020 has to be considered. */
2022 (p->char_func) (number_separator);
2023 if (number_separator == '\t')
2024 output_position = POS_AFTER_TAB (chars_per_output_tab,
2025 output_position);
2028 if (truncate_lines && !parallel_files)
2029 input_position += number_width;
2032 /* Print (or store) padding until the current horizontal position
2033 is position. */
2035 static void
2036 pad_across_to (int position)
2038 int h = output_position;
2040 if (tabify_output)
2041 spaces_not_printed = position - output_position;
2042 else
2044 while (++h <= position)
2045 putchar (' ');
2046 output_position = position;
2050 /* Pad to the bottom of the page.
2052 If the user has requested a formfeed, use one.
2053 Otherwise, use newlines. */
2055 static void
2056 pad_down (unsigned int lines)
2058 unsigned int i;
2060 if (use_form_feed)
2061 putchar ('\f');
2062 else
2063 for (i = lines; i; --i)
2064 putchar ('\n');
2067 /* Read the rest of the line.
2069 Read from the current column's file until an end of line is
2070 hit. Used when we've truncated a line and we no longer need
2071 to print or store its characters. */
2073 static void
2074 read_rest_of_line (COLUMN *p)
2076 int c;
2077 FILE *f = p->fp;
2079 while ((c = getc (f)) != '\n')
2081 if (c == '\f')
2083 if ((c = getc (f)) != '\n')
2084 ungetc (c, f);
2085 if (keep_FF)
2086 print_a_FF = true;
2087 hold_file (p);
2088 break;
2090 else if (c == EOF)
2092 close_file (p);
2093 break;
2098 /* Read a line with skip_to_page.
2100 Read from the current column's file until an end of line is
2101 hit. Used when we read full lines to skip pages.
2102 With skip_to_page we have to check for FF-coincidence which is done
2103 in function read_line otherwise.
2104 Count lines of skipped pages to find the line number of 1st page
2105 printed relative to 1st line of input file (start_line_num). */
2107 static void
2108 skip_read (COLUMN *p, int column_number)
2110 int c;
2111 FILE *f = p->fp;
2112 int i;
2113 bool single_ff = false;
2114 COLUMN *q;
2116 /* Read 1st character in a line or any character succeeding a FF */
2117 if ((c = getc (f)) == '\f' && p->full_page_printed)
2118 /* A FF-coincidence with a previous full_page_printed.
2119 To avoid an additional empty page, eliminate the FF */
2120 if ((c = getc (f)) == '\n')
2121 c = getc (f);
2123 p->full_page_printed = false;
2125 /* 1st character a FF means a single FF without any printable
2126 characters. Don't count it as a line with -n option. */
2127 if (c == '\f')
2128 single_ff = true;
2130 /* Preparing for a FF-coincidence: Maybe we finish that page
2131 without a FF found */
2132 if (last_line)
2133 p->full_page_printed = true;
2135 while (c != '\n')
2137 if (c == '\f')
2139 /* No FF-coincidence possible,
2140 no catching up of a FF-coincidence with next page */
2141 if (last_line)
2143 if (!parallel_files)
2144 for (q = column_vector, i = columns; i; ++q, --i)
2145 q->full_page_printed = false;
2146 else
2147 p->full_page_printed = false;
2150 if ((c = getc (f)) != '\n')
2151 ungetc (c, f);
2152 hold_file (p);
2153 break;
2155 else if (c == EOF)
2157 close_file (p);
2158 break;
2160 c = getc (f);
2163 if (skip_count)
2164 if ((!parallel_files || column_number == 1) && !single_ff)
2165 ++line_count;
2168 /* If we're tabifying output,
2170 When print_char encounters white space it keeps track
2171 of our desired horizontal position and delays printing
2172 until this function is called. */
2174 static void
2175 print_white_space (void)
2177 int h_new;
2178 int h_old = output_position;
2179 int goal = h_old + spaces_not_printed;
2181 while (goal - h_old > 1
2182 && (h_new = POS_AFTER_TAB (chars_per_output_tab, h_old)) <= goal)
2184 putchar (output_tab_char);
2185 h_old = h_new;
2187 while (++h_old <= goal)
2188 putchar (' ');
2190 output_position = goal;
2191 spaces_not_printed = 0;
2194 /* Print column separators.
2196 We keep a count until we know that we'll be printing a line,
2197 then print_sep_string() is called. */
2199 static void
2200 print_sep_string (void)
2202 char *s;
2203 int l = col_sep_length;
2205 s = col_sep_string;
2207 if (separators_not_printed <= 0)
2209 /* We'll be starting a line with chars_per_margin, anything else? */
2210 if (spaces_not_printed > 0)
2211 print_white_space ();
2213 else
2215 for (; separators_not_printed > 0; --separators_not_printed)
2217 while (l-- > 0)
2219 /* 3 types of sep_strings: spaces only, spaces and chars,
2220 chars only */
2221 if (*s == ' ')
2223 /* We're tabifying output; consecutive spaces in
2224 sep_string may have to be converted to tabs */
2225 s++;
2226 ++spaces_not_printed;
2228 else
2230 if (spaces_not_printed > 0)
2231 print_white_space ();
2232 putchar (*s++);
2233 ++output_position;
2236 /* sep_string ends with some spaces */
2237 if (spaces_not_printed > 0)
2238 print_white_space ();
2243 /* Print (or store, depending on p->char_func) a clump of N
2244 characters. */
2246 static void
2247 print_clump (COLUMN *p, int n, char *clump)
2249 while (n--)
2250 (p->char_func) (*clump++);
2253 /* Print a character.
2255 Update the following comment: process-char hasn't been used any
2256 longer.
2257 If we're tabifying, all tabs have been converted to spaces by
2258 process_char(). Keep a count of consecutive spaces, and when
2259 a nonspace is encountered, call print_white_space() to print the
2260 required number of tabs and spaces. */
2262 static void
2263 print_char (char c)
2265 if (tabify_output)
2267 if (c == ' ')
2269 ++spaces_not_printed;
2270 return;
2272 else if (spaces_not_printed > 0)
2273 print_white_space ();
2275 /* Nonprintables are assumed to have width 0, except '\b'. */
2276 if (! isprint (to_uchar (c)))
2278 if (c == '\b')
2279 --output_position;
2281 else
2282 ++output_position;
2284 putchar (c);
2287 /* Skip to page PAGE before printing.
2288 PAGE may be larger than total number of pages. */
2290 static bool
2291 skip_to_page (uintmax_t page)
2293 uintmax_t n;
2294 int i;
2295 int j;
2296 COLUMN *p;
2298 for (n = 1; n < page; ++n)
2300 for (i = 1; i < lines_per_body; ++i)
2302 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
2303 if (p->status == OPEN)
2304 skip_read (p, j);
2306 last_line = true;
2307 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
2308 if (p->status == OPEN)
2309 skip_read (p, j);
2311 if (storing_columns) /* change FF_FOUND to ON_HOLD */
2312 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
2313 if (p->status != CLOSED)
2314 p->status = ON_HOLD;
2316 reset_status ();
2317 last_line = false;
2319 if (files_ready_to_read < 1)
2321 /* It's very helpful, normally the total number of pages is
2322 not known in advance. */
2323 error (0, 0,
2324 _("starting page number %"PRIuMAX
2325 " exceeds page count %"PRIuMAX),
2326 page, n);
2327 break;
2330 return files_ready_to_read > 0;
2333 /* Print a header.
2335 Formfeeds are assumed to use up two lines at the beginning of
2336 the page. */
2338 static void
2339 print_header (void)
2341 char page_text[256 + INT_STRLEN_BOUND (page_number)];
2342 int available_width;
2343 int lhs_spaces;
2344 int rhs_spaces;
2346 output_position = 0;
2347 pad_across_to (chars_per_margin);
2348 print_white_space ();
2350 if (page_number == 0)
2351 error (EXIT_FAILURE, 0, _("page number overflow"));
2353 /* The translator must ensure that formatting the translation of
2354 "Page %"PRIuMAX does not generate more than (sizeof page_text - 1)
2355 bytes. */
2356 sprintf (page_text, _("Page %"PRIuMAX), page_number);
2357 available_width = header_width_available - mbswidth (page_text, 0);
2358 available_width = MAX (0, available_width);
2359 lhs_spaces = available_width >> 1;
2360 rhs_spaces = available_width - lhs_spaces;
2362 printf ("\n\n%*s%s%*s%s%*s%s\n\n\n",
2363 chars_per_margin, "",
2364 date_text, lhs_spaces, " ",
2365 file_text, rhs_spaces, " ", page_text);
2367 print_a_header = false;
2368 output_position = 0;
2371 /* Print (or store, if p->char_func is store_char()) a line.
2373 Read a character to determine whether we have a line or not.
2374 (We may hit EOF, \n, or \f)
2376 Once we know we have a line,
2377 set pad_vertically = true, meaning it's safe
2378 to pad down at the end of the page, since we do have a page.
2379 print a header if needed.
2380 pad across to padding_not_printed if needed.
2381 print any separators which need to be printed.
2382 print a line number if it needs to be printed.
2384 Print the clump which corresponds to the first character.
2386 Enter a loop and keep printing until an end of line condition
2387 exists, or until we exceed chars_per_column.
2389 Return false if we exceed chars_per_column before reading
2390 an end of line character, true otherwise. */
2392 static bool
2393 read_line (COLUMN *p)
2395 int c;
2396 int chars IF_LINT ( = 0);
2397 int last_input_position;
2398 int j, k;
2399 COLUMN *q;
2401 /* read 1st character in each line or any character succeeding a FF: */
2402 c = getc (p->fp);
2404 last_input_position = input_position;
2406 if (c == '\f' && p->full_page_printed)
2407 if ((c = getc (p->fp)) == '\n')
2408 c = getc (p->fp);
2409 p->full_page_printed = false;
2411 switch (c)
2413 case '\f':
2414 if ((c = getc (p->fp)) != '\n')
2415 ungetc (c, p->fp);
2416 FF_only = true;
2417 if (print_a_header && !storing_columns)
2419 pad_vertically = true;
2420 print_header ();
2422 else if (keep_FF)
2423 print_a_FF = true;
2424 hold_file (p);
2425 return true;
2426 case EOF:
2427 close_file (p);
2428 return true;
2429 case '\n':
2430 break;
2431 default:
2432 chars = char_to_clump (c);
2435 if (truncate_lines && input_position > chars_per_column)
2437 input_position = last_input_position;
2438 return false;
2441 if (p->char_func != store_char)
2443 pad_vertically = true;
2445 if (print_a_header && !storing_columns)
2446 print_header ();
2448 if (parallel_files && align_empty_cols)
2450 /* We have to align empty columns at the beginning of a line. */
2451 k = separators_not_printed;
2452 separators_not_printed = 0;
2453 for (j = 1, q = column_vector; j <= k; ++j, ++q)
2455 align_column (q);
2456 separators_not_printed += 1;
2458 padding_not_printed = p->start_position;
2459 if (truncate_lines)
2460 spaces_not_printed = chars_per_column;
2461 else
2462 spaces_not_printed = 0;
2463 align_empty_cols = false;
2466 if (padding_not_printed - col_sep_length > 0)
2468 pad_across_to (padding_not_printed - col_sep_length);
2469 padding_not_printed = ANYWHERE;
2472 if (use_col_separator)
2473 print_sep_string ();
2476 if (p->numbered)
2477 add_line_number (p);
2479 empty_line = false;
2480 if (c == '\n')
2481 return true;
2483 print_clump (p, chars, clump_buff);
2485 while (true)
2487 c = getc (p->fp);
2489 switch (c)
2491 case '\n':
2492 return true;
2493 case '\f':
2494 if ((c = getc (p->fp)) != '\n')
2495 ungetc (c, p->fp);
2496 if (keep_FF)
2497 print_a_FF = true;
2498 hold_file (p);
2499 return true;
2500 case EOF:
2501 close_file (p);
2502 return true;
2505 last_input_position = input_position;
2506 chars = char_to_clump (c);
2507 if (truncate_lines && input_position > chars_per_column)
2509 input_position = last_input_position;
2510 return false;
2513 print_clump (p, chars, clump_buff);
2517 /* Print a line from buff.
2519 If this function has been called, we know we have "something to
2520 print". But it remains to be seen whether we have a real text page
2521 or an empty page (a single form feed) with/without a header only.
2522 Therefore first we set pad_vertically to true and print a header
2523 if necessary.
2524 If FF_FOUND and we are using -t|-T option we omit any newline by
2525 setting pad_vertically to false (see print_page).
2526 Otherwise we pad across if necessary, print separators if necessary
2527 and text of COLUMN *p.
2529 Return true, meaning there is no need to call read_rest_of_line. */
2531 static bool
2532 print_stored (COLUMN *p)
2534 COLUMN *q;
2535 int i;
2537 int line = p->current_line++;
2538 char *first = &buff[line_vector[line]];
2539 /* FIXME
2540 UMR: Uninitialized memory read:
2541 * This is occurring while in:
2542 print_stored [pr.c:2239]
2543 * Reading 4 bytes from 0x5148c in the heap.
2544 * Address 0x5148c is 4 bytes into a malloc'd block at 0x51488 of 676 bytes
2545 * This block was allocated from:
2546 malloc [rtlib.o]
2547 xmalloc [xmalloc.c:94]
2548 init_store_cols [pr.c:1648]
2550 char *last = &buff[line_vector[line + 1]];
2552 pad_vertically = true;
2554 if (print_a_header)
2555 print_header ();
2557 if (p->status == FF_FOUND)
2559 for (i = 1, q = column_vector; i <= columns; ++i, ++q)
2560 q->status = ON_HOLD;
2561 if (column_vector->lines_to_print <= 0)
2563 if (!extremities)
2564 pad_vertically = false;
2565 return true; /* print a header only */
2569 if (padding_not_printed - col_sep_length > 0)
2571 pad_across_to (padding_not_printed - col_sep_length);
2572 padding_not_printed = ANYWHERE;
2575 if (use_col_separator)
2576 print_sep_string ();
2578 while (first != last)
2579 print_char (*first++);
2581 if (spaces_not_printed == 0)
2583 output_position = p->start_position + end_vector[line];
2584 if (p->start_position - col_sep_length == chars_per_margin)
2585 output_position -= col_sep_length;
2588 return true;
2591 /* Convert a character to the proper format and return the number of
2592 characters in the resulting clump. Increment input_position by
2593 the width of the clump.
2595 Tabs are converted to clumps of spaces.
2596 Nonprintable characters may be converted to clumps of escape
2597 sequences or control prefixes.
2599 Note: the width of a clump is not necessarily equal to the number of
2600 characters in clump_buff. (e.g, the width of '\b' is -1, while the
2601 number of characters is 1.) */
2603 static int
2604 char_to_clump (char c)
2606 unsigned char uc = c;
2607 char *s = clump_buff;
2608 int i;
2609 char esc_buff[4];
2610 int width;
2611 int chars;
2612 int chars_per_c = 8;
2614 if (c == input_tab_char)
2615 chars_per_c = chars_per_input_tab;
2617 if (c == input_tab_char || c == '\t')
2619 width = TAB_WIDTH (chars_per_c, input_position);
2621 if (untabify_input)
2623 for (i = width; i; --i)
2624 *s++ = ' ';
2625 chars = width;
2627 else
2629 *s = c;
2630 chars = 1;
2634 else if (! isprint (uc))
2636 if (use_esc_sequence)
2638 width = 4;
2639 chars = 4;
2640 *s++ = '\\';
2641 sprintf (esc_buff, "%03o", uc);
2642 for (i = 0; i <= 2; ++i)
2643 *s++ = esc_buff[i];
2645 else if (use_cntrl_prefix)
2647 if (uc < 0200)
2649 width = 2;
2650 chars = 2;
2651 *s++ = '^';
2652 *s = c ^ 0100;
2654 else
2656 width = 4;
2657 chars = 4;
2658 *s++ = '\\';
2659 sprintf (esc_buff, "%03o", uc);
2660 for (i = 0; i <= 2; ++i)
2661 *s++ = esc_buff[i];
2664 else if (c == '\b')
2666 width = -1;
2667 chars = 1;
2668 *s = c;
2670 else
2672 width = 0;
2673 chars = 1;
2674 *s = c;
2677 else
2679 width = 1;
2680 chars = 1;
2681 *s = c;
2684 /* Too many backspaces must put us in position 0 -- never negative. */
2685 if (width < 0 && input_position == 0)
2687 chars = 0;
2688 input_position = 0;
2690 else if (width < 0 && input_position <= -width)
2691 input_position = 0;
2692 else
2693 input_position += width;
2695 return chars;
2698 /* We've just printed some files and need to clean up things before
2699 looking for more options and printing the next batch of files.
2701 Free everything we've xmalloc'ed, except 'header'. */
2703 static void
2704 cleanup (void)
2706 free (number_buff);
2707 free (clump_buff);
2708 free (column_vector);
2709 free (line_vector);
2710 free (end_vector);
2711 free (buff);
2714 /* Complain, print a usage message, and die. */
2716 void
2717 usage (int status)
2719 if (status != EXIT_SUCCESS)
2720 emit_try_help ();
2721 else
2723 printf (_("\
2724 Usage: %s [OPTION]... [FILE]...\n\
2726 program_name);
2728 fputs (_("\
2729 Paginate or columnate FILE(s) for printing.\n\
2730 "), stdout);
2732 emit_stdin_note ();
2733 emit_mandatory_arg_note ();
2735 fputs (_("\
2736 +FIRST_PAGE[:LAST_PAGE], --pages=FIRST_PAGE[:LAST_PAGE]\n\
2737 begin [stop] printing with page FIRST_[LAST_]PAGE\n\
2738 -COLUMN, --columns=COLUMN\n\
2739 output COLUMN columns and print columns down,\n\
2740 unless -a is used. Balance number of lines in the\n\
2741 columns on each page\n\
2742 "), stdout);
2743 fputs (_("\
2744 -a, --across print columns across rather than down, used together\n\
2745 with -COLUMN\n\
2746 -c, --show-control-chars\n\
2747 use hat notation (^G) and octal backslash notation\n\
2748 -d, --double-space\n\
2749 double space the output\n\
2750 "), stdout);
2751 fputs (_("\
2752 -D, --date-format=FORMAT\n\
2753 use FORMAT for the header date\n\
2754 -e[CHAR[WIDTH]], --expand-tabs[=CHAR[WIDTH]]\n\
2755 expand input CHARs (TABs) to tab WIDTH (8)\n\
2756 -F, -f, --form-feed\n\
2757 use form feeds instead of newlines to separate pages\n\
2758 (by a 3-line page header with -F or a 5-line header\n\
2759 and trailer without -F)\n\
2760 "), stdout);
2761 fputs (_("\
2762 -h, --header=HEADER\n\
2763 use a centered HEADER instead of filename in page header,\n\
2764 -h \"\" prints a blank line, don't use -h\"\"\n\
2765 -i[CHAR[WIDTH]], --output-tabs[=CHAR[WIDTH]]\n\
2766 replace spaces with CHARs (TABs) to tab WIDTH (8)\n\
2767 -J, --join-lines merge full lines, turns off -W line truncation, no column\n\
2768 alignment, --sep-string[=STRING] sets separators\n\
2769 "), stdout);
2770 fputs (_("\
2771 -l, --length=PAGE_LENGTH\n\
2772 set the page length to PAGE_LENGTH (66) lines\n\
2773 (default number of lines of text 56, and with -F 63).\n\
2774 implies -t if PAGE_LENGTH <= 10\n\
2775 "), stdout);
2776 fputs (_("\
2777 -m, --merge print all files in parallel, one in each column,\n\
2778 truncate lines, but join lines of full length with -J\n\
2779 "), stdout);
2780 fputs (_("\
2781 -n[SEP[DIGITS]], --number-lines[=SEP[DIGITS]]\n\
2782 number lines, use DIGITS (5) digits, then SEP (TAB),\n\
2783 default counting starts with 1st line of input file\n\
2784 -N, --first-line-number=NUMBER\n\
2785 start counting with NUMBER at 1st line of first\n\
2786 page printed (see +FIRST_PAGE)\n\
2787 "), stdout);
2788 fputs (_("\
2789 -o, --indent=MARGIN\n\
2790 offset each line with MARGIN (zero) spaces, do not\n\
2791 affect -w or -W, MARGIN will be added to PAGE_WIDTH\n\
2792 -r, --no-file-warnings\n\
2793 omit warning when a file cannot be opened\n\
2794 "), stdout);
2795 fputs (_("\
2796 -s[CHAR], --separator[=CHAR]\n\
2797 separate columns by a single character, default for CHAR\n\
2798 is the <TAB> character without -w and \'no char\' with -w.\
2800 -s[CHAR] turns off line truncation of all 3 column\n\
2801 options (-COLUMN|-a -COLUMN|-m) except -w is set\n\
2802 "), stdout);
2803 fputs (_("\
2804 -S[STRING], --sep-string[=STRING]\n\
2805 separate columns by STRING,\n\
2806 without -S: Default separator <TAB> with -J and <space>\n\
2807 otherwise (same as -S\" \"), no effect on column options\n\
2808 "), stdout);
2809 fputs (_("\
2810 -t, --omit-header omit page headers and trailers;\n\
2811 implied if PAGE_LENGTH <= 10\n\
2812 "), stdout);
2813 fputs (_("\
2814 -T, --omit-pagination\n\
2815 omit page headers and trailers, eliminate any pagination\n\
2816 by form feeds set in input files\n\
2817 -v, --show-nonprinting\n\
2818 use octal backslash notation\n\
2819 -w, --width=PAGE_WIDTH\n\
2820 set page width to PAGE_WIDTH (72) characters for\n\
2821 multiple text-column output only, -s[char] turns off (72)\n\
2822 "), stdout);
2823 fputs (_("\
2824 -W, --page-width=PAGE_WIDTH\n\
2825 set page width to PAGE_WIDTH (72) characters always,\n\
2826 truncate lines, except -J option is set, no interference\n\
2827 with -S or -s\n\
2828 "), stdout);
2829 fputs (HELP_OPTION_DESCRIPTION, stdout);
2830 fputs (VERSION_OPTION_DESCRIPTION, stdout);
2831 emit_ancillary_info (PROGRAM_NAME);
2833 exit (status);