1 /* pr -- convert text files for printing.
2 Copyright (C) 1988-2016 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
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.
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
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
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
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
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,
78 options: text form / separator: equivalent new options:
80 --------------------------------------------------------------------
81 1. -- -- columns / space --
82 trunc. to page_width = 72
83 2. -- -s[:] full lines / TAB[:] -J --sep-string[="<TAB>"|:]
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 --------------------------------------------------------------------
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
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
128 will be printed with '-a -3' as
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.
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
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
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
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
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
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
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
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
313 #include <sys/types.h>
317 #include "hard-locale.h"
318 #include "mbswidth.h"
320 #include "stat-time.h"
322 #include "strftime.h"
324 #include "xdectoint.h"
326 /* The official name of this program (e.g., no 'g' prefix). */
327 #define PROGRAM_NAME "pr"
330 proper_name ("Pete TerMaat"), \
331 proper_name ("Roland Huebner")
333 /* Used with start_position in the struct COLUMN described below.
334 If start_position == ANYWHERE, we aren't truncating columns and
335 can begin printing a column anywhere. Otherwise we must pad to
336 the horizontal position start_position. */
339 /* Each column has one of these structures allocated for it.
340 If we're only dealing with one file, fp is the same for all
343 The general strategy is to spend time setting up these column
344 structures (storing columns if necessary), after which printing
345 is a matter of flitting from column to column and calling
348 Parallel files, single files printing across in multiple
349 columns, and single files printing down in multiple columns all
350 fit the same printing loop.
352 print_func Function used to print lines in this column.
353 If we're storing this column it will be
354 print_stored(), Otherwise it will be read_line().
356 char_func Function used to process characters in this column.
357 If we're storing this column it will be store_char(),
358 otherwise it will be print_char().
360 current_line Index of the current entry in line_vector, which
361 contains the index of the first character of the
362 current line in buff[].
364 lines_stored Number of lines in this column which are stored in
367 lines_to_print If we're storing this column, lines_to_print is
368 the number of stored_lines which remain to be
369 printed. Otherwise it is the number of lines
370 we can print without exceeding lines_per_body.
372 start_position The horizontal position we want to be in before we
373 print the first character in this column.
375 numbered True means precede this column with a line number. */
377 /* FIXME: There are many unchecked integer overflows in this file,
378 that will cause this command to misbehave given large inputs or
379 options. Many of the "int" values below should be "size_t" or
380 something else like that. */
385 FILE *fp
; /* Input stream for this column. */
386 char const *name
; /* File name. */
390 FF_FOUND
, /* used with -b option, set with \f, changed
391 to ON_HOLD after print_header */
392 ON_HOLD
, /* Hit a form feed. */
395 status
; /* Status of the file pointer. */
397 /* Func to print lines in this col. */
398 bool (*print_func
) (struct COLUMN
*);
400 /* Func to print/store chars in this col. */
401 void (*char_func
) (char);
403 int current_line
; /* Index of current place in line_vector. */
404 int lines_stored
; /* Number of lines stored in buff. */
405 int lines_to_print
; /* No. lines stored or space left on page. */
406 int start_position
; /* Horizontal position of first char. */
408 bool full_page_printed
; /* True means printed without a FF found. */
410 /* p->full_page_printed controls a special case of "FF set by hand":
411 True means a full page has been printed without FF found. To avoid an
412 additional empty page we have to ignore a FF immediately following in
416 typedef struct COLUMN COLUMN
;
418 static int char_to_clump (char c
);
419 static bool read_line (COLUMN
*p
);
420 static bool print_page (void);
421 static bool print_stored (COLUMN
*p
);
422 static bool open_file (char *name
, COLUMN
*p
);
423 static bool skip_to_page (uintmax_t page
);
424 static void print_header (void);
425 static void pad_across_to (int position
);
426 static void add_line_number (COLUMN
*p
);
427 static void getoptnum (const char *n_str
, int min
, int *num
,
429 static void getoptarg (char *arg
, char switch_char
, char *character
,
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 (const char *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]. */
457 /* Index of the position in buff where the next character
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
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
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. */
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
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
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
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
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:
626 When printing files across (-a flag), ...
630 Otherwise, line numbering is as follows:
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 unprintable characters are printed as escape sequences.
666 control-g becomes \007. */
667 static bool use_esc_sequence
= false;
669 /* (-c) True means unprintable 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 *col_sep_string
= (char *) "";
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 /* Date and file name for the header. */
714 static char *date_text
;
715 static char const *file_text
;
717 /* Output columns available, not counting the date and file name. */
718 static int header_width_available
;
720 static char *clump_buff
;
722 /* True means we read the line no. lines_per_body in skip_read
723 called by skip_to_page. That variable controls the coincidence of a
724 "FF set by hand" and "full_page_printed", see above the definition of
726 static bool last_line
= false;
728 /* For long options that have no equivalent short option, use a
729 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
732 COLUMNS_OPTION
= CHAR_MAX
+ 1,
736 static char const short_options
[] =
737 "-0123456789D:FJN:S::TW:abcde::fh:i::l:mn::o:rs::tvw:";
739 static struct option
const long_options
[] =
741 {"pages", required_argument
, NULL
, PAGES_OPTION
},
742 {"columns", required_argument
, NULL
, COLUMNS_OPTION
},
743 {"across", no_argument
, NULL
, 'a'},
744 {"show-control-chars", no_argument
, NULL
, 'c'},
745 {"double-space", no_argument
, NULL
, 'd'},
746 {"date-format", required_argument
, NULL
, 'D'},
747 {"expand-tabs", optional_argument
, NULL
, 'e'},
748 {"form-feed", no_argument
, NULL
, 'f'},
749 {"header", required_argument
, NULL
, 'h'},
750 {"output-tabs", optional_argument
, NULL
, 'i'},
751 {"join-lines", no_argument
, NULL
, 'J'},
752 {"length", required_argument
, NULL
, 'l'},
753 {"merge", no_argument
, NULL
, 'm'},
754 {"number-lines", optional_argument
, NULL
, 'n'},
755 {"first-line-number", required_argument
, NULL
, 'N'},
756 {"indent", required_argument
, NULL
, 'o'},
757 {"no-file-warnings", no_argument
, NULL
, 'r'},
758 {"separator", optional_argument
, NULL
, 's'},
759 {"sep-string", optional_argument
, NULL
, 'S'},
760 {"omit-header", no_argument
, NULL
, 't'},
761 {"omit-pagination", no_argument
, NULL
, 'T'},
762 {"show-nonprinting", no_argument
, NULL
, 'v'},
763 {"width", required_argument
, NULL
, 'w'},
764 {"page-width", required_argument
, NULL
, 'W'},
765 {GETOPT_HELP_OPTION_DECL
},
766 {GETOPT_VERSION_OPTION_DECL
},
770 /* Return the number of columns that have either an open file or
773 static unsigned int _GL_ATTRIBUTE_PURE
774 cols_ready_to_print (void)
781 for (q
= column_vector
, i
= 0; i
< columns
; ++q
, ++i
)
782 if (q
->status
== OPEN
783 || q
->status
== FF_FOUND
/* With -b: To print a header only */
784 || (storing_columns
&& q
->lines_stored
> 0 && q
->lines_to_print
> 0))
789 /* Estimate first_ / last_page_number
790 using option +FIRST_PAGE:LAST_PAGE */
793 first_last_page (int oi
, char c
, char const *pages
)
797 uintmax_t last
= UINTMAX_MAX
;
798 strtol_error err
= xstrtoumax (pages
, &p
, 10, &first
, "");
799 if (err
!= LONGINT_OK
&& err
!= LONGINT_INVALID_SUFFIX_CHAR
)
800 xstrtol_fatal (err
, oi
, c
, long_options
, pages
);
802 if (p
== pages
|| !first
)
807 char const *p1
= p
+ 1;
808 err
= xstrtoumax (p1
, &p
, 10, &last
, "");
809 if (err
!= LONGINT_OK
)
810 xstrtol_fatal (err
, oi
, c
, long_options
, pages
);
811 if (p1
== p
|| last
< first
)
818 first_page_number
= first
;
819 last_page_number
= last
;
823 /* Parse column count string S, and if it's valid (1 or larger and
824 within range of the type of 'columns') set the global variables
825 columns and explicit_columns. Otherwise, exit with a diagnostic. */
828 parse_column_count (char const *s
)
830 getoptnum (s
, 1, &columns
, _("invalid number of columns"));
831 explicit_columns
= true;
834 /* Estimate length of col_sep_string with option -S. */
837 separator_string (const char *optarg_S
)
839 col_sep_length
= (int) strlen (optarg_S
);
840 col_sep_string
= xmalloc (col_sep_length
+ 1);
841 strcpy (col_sep_string
, optarg_S
);
845 main (int argc
, char **argv
)
848 bool old_options
= false;
853 /* Accumulate the digits of old-style options like -99. */
854 char *column_count_string
= NULL
;
858 initialize_main (&argc
, &argv
);
859 set_program_name (argv
[0]);
860 setlocale (LC_ALL
, "");
861 bindtextdomain (PACKAGE
, LOCALEDIR
);
862 textdomain (PACKAGE
);
864 atexit (close_stdout
);
867 file_names
= (argc
> 1
868 ? xmalloc ((argc
- 1) * sizeof (char *))
874 int c
= getopt_long (argc
, argv
, short_options
, long_options
, &oi
);
880 /* Accumulate column-count digits specified via old-style options. */
881 if (n_digits
+ 1 >= n_alloc
)
883 = X2REALLOC (column_count_string
, &n_alloc
);
884 column_count_string
[n_digits
++] = c
;
885 column_count_string
[n_digits
] = '\0';
893 case 1: /* Non-option argument. */
894 /* long option --page dominates old '+FIRST_PAGE ...'. */
895 if (! (first_page_number
== 0
896 && *optarg
== '+' && first_last_page (-2, '+', optarg
+ 1)))
897 file_names
[n_files
++] = optarg
;
900 case PAGES_OPTION
: /* --pages=FIRST_PAGE[:LAST_PAGE] */
901 { /* dominates old opt +... */
903 error (EXIT_FAILURE
, 0,
904 _("'--pages=FIRST_PAGE[:LAST_PAGE]' missing argument"));
905 else if (! first_last_page (oi
, 0, optarg
))
906 error (EXIT_FAILURE
, 0, _("invalid page range %s"),
911 case COLUMNS_OPTION
: /* --columns=COLUMN */
913 parse_column_count (optarg
);
915 /* If there was a prior column count specified via the
916 short-named option syntax, e.g., -9, ensure that this
917 long-name-specified value overrides it. */
918 free (column_count_string
);
919 column_count_string
= NULL
;
925 print_across_flag
= true;
926 storing_columns
= false;
929 balance_columns
= true;
932 use_cntrl_prefix
= true;
938 date_format
= optarg
;
942 getoptarg (optarg
, 'e', &input_tab_char
,
943 &chars_per_input_tab
);
944 /* Could check tab width > 0. */
945 untabify_input
= true;
949 use_form_feed
= true;
952 custom_header
= optarg
;
956 getoptarg (optarg
, 'i', &output_tab_char
,
957 &chars_per_output_tab
);
958 /* Could check tab width > 0. */
959 tabify_output
= true;
965 getoptnum (optarg
, 1, &lines_per_page
,
966 _("'-l PAGE_LENGTH' invalid number of lines"));
969 parallel_files
= true;
970 storing_columns
= false;
973 numbered_lines
= true;
975 getoptarg (optarg
, 'n', &number_separator
,
980 getoptnum (optarg
, INT_MIN
, &start_line_num
,
981 _("'-N NUMBER' invalid starting line number"));
984 getoptnum (optarg
, 0, &chars_per_margin
,
985 _("'-o MARGIN' invalid line offset"));
988 ignore_failed_opens
= true;
993 if (!use_col_separator
&& optarg
)
994 separator_string (optarg
);
998 /* Reset an additional input of -s, -S dominates -s */
999 col_sep_string
= bad_cast ("");
1001 use_col_separator
= true;
1003 separator_string (optarg
);
1006 extremities
= false;
1010 extremities
= false;
1014 use_esc_sequence
= true;
1021 getoptnum (optarg
, 1, &tmp_cpl
,
1022 _("'-w PAGE_WIDTH' invalid number of characters"));
1023 if (! truncate_lines
)
1024 chars_per_line
= tmp_cpl
;
1028 old_w
= false; /* dominates -w */
1029 truncate_lines
= true;
1030 getoptnum (optarg
, 1, &chars_per_line
,
1031 _("'-W PAGE_WIDTH' invalid number of characters"));
1033 case_GETOPT_HELP_CHAR
;
1034 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
1036 usage (EXIT_FAILURE
);
1041 if (column_count_string
)
1043 parse_column_count (column_count_string
);
1044 free (column_count_string
);
1048 date_format
= (getenv ("POSIXLY_CORRECT") && !hard_locale (LC_TIME
)
1050 : "%Y-%m-%d %H:%M");
1052 /* Now we can set a reasonable initial value: */
1053 if (first_page_number
== 0)
1054 first_page_number
= 1;
1056 if (parallel_files
&& explicit_columns
)
1057 error (EXIT_FAILURE
, 0,
1058 _("cannot specify number of columns when printing in parallel"));
1060 if (parallel_files
&& print_across_flag
)
1061 error (EXIT_FAILURE
, 0,
1062 _("cannot specify both printing across and printing in parallel"));
1064 /* Translate some old short options to new/long options.
1065 To meet downward compatibility with other UNIX pr utilities
1066 and some POSIX specifications. */
1072 if (parallel_files
|| explicit_columns
)
1075 truncate_lines
= true;
1077 /* adapt HP-UX and SunOS: -s = no separator;
1079 use_col_separator
= true;
1082 /* old -w sets width with columns only
1086 else if (!use_col_separator
)
1088 /* No -S option read */
1089 if (old_s
&& (parallel_files
|| explicit_columns
))
1091 if (!truncate_lines
)
1093 /* old -s (without -w and -W) annuls column alignment,
1094 uses fields, activate -J */
1096 if (col_sep_length
> 0)
1098 use_col_separator
= true;
1102 /* adapt HP-UX and SunOS: -s = no separator;
1104 use_col_separator
= true;
1109 for (; optind
< argc
; optind
++)
1111 file_names
[n_files
++] = argv
[optind
];
1116 /* No file arguments specified; read from standard input. */
1117 print_files (0, NULL
);
1122 print_files (n_files
, file_names
);
1126 for (i
= 0; i
< n_files
; i
++)
1127 print_files (1, &file_names
[i
]);
1132 IF_LINT (free (file_names
));
1134 if (have_read_stdin
&& fclose (stdin
) == EOF
)
1135 error (EXIT_FAILURE
, errno
, _("standard input"));
1136 return failed_opens
? EXIT_FAILURE
: EXIT_SUCCESS
;
1139 /* Parse numeric arguments, ensuring MIN <= number <= INT_MAX. */
1142 getoptnum (const char *n_str
, int min
, int *num
, const char *err
)
1144 intmax_t tnum
= xdectoimax (n_str
, min
, INT_MAX
, "", err
, 0);
1148 /* Parse options of the form -scNNN.
1150 Example: -nck, where 'n' is the option, c is the optional number
1151 separator, and k is the optional width of the field used when printing
1155 getoptarg (char *arg
, char switch_char
, char *character
, int *number
)
1157 if (!ISDIGIT (*arg
))
1158 *character
= *arg
++;
1162 if (xstrtol (arg
, NULL
, 10, &tmp_long
, "") != LONGINT_OK
1163 || tmp_long
<= 0 || INT_MAX
< tmp_long
)
1165 error (0, INT_MAX
< tmp_long
? EOVERFLOW
: errno
,
1166 _("'-%c' extra characters or invalid number in the argument: %s"),
1167 switch_char
, quote (arg
));
1168 usage (EXIT_FAILURE
);
1174 /* Set parameters related to formatting. */
1177 init_parameters (int number_of_files
)
1179 int chars_used_by_number
= 0;
1181 lines_per_body
= lines_per_page
- lines_per_header
- lines_per_footer
;
1182 if (lines_per_body
<= 0)
1184 extremities
= false;
1187 if (extremities
== false)
1188 lines_per_body
= lines_per_page
;
1191 lines_per_body
= lines_per_body
/ 2;
1193 /* If input is stdin, cannot print parallel files. BSD dumps core
1195 if (number_of_files
== 0)
1196 parallel_files
= false;
1199 columns
= number_of_files
;
1201 /* One file, multi columns down: -b option is set to get a consistent
1202 formulation with "FF set by hand" in input files. */
1203 if (storing_columns
)
1204 balance_columns
= true;
1206 /* Tabification is assumed for multiple columns. */
1209 if (!use_col_separator
)
1211 /* Use default separator */
1213 col_sep_string
= line_separator
;
1215 col_sep_string
= column_separator
;
1218 use_col_separator
= true;
1220 /* It's rather pointless to define a TAB separator with column
1222 else if (!join_lines
&& *col_sep_string
== '\t')
1223 col_sep_string
= column_separator
;
1225 truncate_lines
= true;
1226 tabify_output
= true;
1229 storing_columns
= false;
1231 /* -J dominates -w in any case */
1233 truncate_lines
= false;
1237 int chars_per_default_tab
= 8;
1239 line_count
= start_line_num
;
1241 /* To allow input tab-expansion (-e sensitive) use:
1242 if (number_separator == input_tab_char)
1243 number_width = chars_per_number
1244 + TAB_WIDTH (chars_per_input_tab, chars_per_number); */
1246 /* Estimate chars_per_text without any margin and keep it constant. */
1247 if (number_separator
== '\t')
1248 number_width
= (chars_per_number
1249 + TAB_WIDTH (chars_per_default_tab
, chars_per_number
));
1251 number_width
= chars_per_number
+ 1;
1253 /* The number is part of the column width unless we are
1254 printing files in parallel. */
1256 chars_used_by_number
= number_width
;
1259 chars_per_column
= (chars_per_line
- chars_used_by_number
1260 - (columns
- 1) * col_sep_length
) / columns
;
1262 if (chars_per_column
< 1)
1263 error (EXIT_FAILURE
, 0, _("page width too narrow"));
1268 number_buff
= xmalloc (MAX (chars_per_number
,
1269 INT_STRLEN_BOUND (line_number
)) + 1);
1272 /* Pick the maximum between the tab width and the width of an
1274 The width of an escape sequence (4) isn't the lower limit any longer.
1275 We've to use 8 as the lower limit, if we use chars_per_default_tab = 8
1276 to expand a tab which is not an input_tab-char. */
1278 clump_buff
= xmalloc (MAX (8, chars_per_input_tab
));
1281 /* Open the necessary files,
1282 maintaining a COLUMN structure for each column.
1284 With multiple files, each column p has a different p->fp.
1285 With single files, each column p has the same p->fp.
1286 Return false if (number_of_files > 0) and no files can be opened,
1289 With each column/file p, p->full_page_printed is initialized,
1290 see also open_file. */
1293 init_fps (int number_of_files
, char **av
)
1298 char const *firstname
;
1302 free (column_vector
);
1303 column_vector
= xnmalloc (columns
, sizeof (COLUMN
));
1307 files_left
= number_of_files
;
1308 for (p
= column_vector
; files_left
--; ++p
, ++av
)
1310 if (! open_file (*av
, p
))
1318 init_header ("", -1);
1323 if (number_of_files
> 0)
1325 if (! open_file (*av
, p
))
1327 init_header (*av
, fileno (p
->fp
));
1328 p
->lines_stored
= 0;
1332 p
->name
= _("standard input");
1334 have_read_stdin
= true;
1336 p
->full_page_printed
= false;
1338 init_header ("", -1);
1339 p
->lines_stored
= 0;
1342 firstname
= p
->name
;
1344 for (i
= columns
- 1, ++p
; i
; --i
, ++p
)
1346 p
->name
= firstname
;
1349 p
->full_page_printed
= false;
1350 p
->lines_stored
= 0;
1353 files_ready_to_read
= total_files
;
1357 /* Determine print_func and char_func, the functions
1358 used by each column for printing and/or storing.
1360 Determine the horizontal position desired when we begin
1361 printing a column (p->start_position). */
1369 h
= chars_per_margin
;
1371 if (!truncate_lines
)
1375 /* When numbering lines of parallel files, we enlarge the
1376 first column to accommodate the number. Looks better than
1377 the Sys V approach. */
1378 if (parallel_files
&& numbered_lines
)
1379 h_next
= h
+ chars_per_column
+ number_width
;
1381 h_next
= h
+ chars_per_column
;
1384 /* Enlarge p->start_position of first column to use the same form of
1385 padding_not_printed with all columns. */
1386 h
= h
+ col_sep_length
;
1388 /* This loop takes care of all but the rightmost column. */
1390 for (p
= column_vector
, i
= 1; i
< columns
; ++p
, ++i
)
1392 if (storing_columns
) /* One file, multi columns down. */
1394 p
->char_func
= store_char
;
1395 p
->print_func
= print_stored
;
1398 /* One file, multi columns across; or parallel files. */
1400 p
->char_func
= print_char
;
1401 p
->print_func
= read_line
;
1404 /* Number only the first column when printing files in
1406 p
->numbered
= numbered_lines
&& (!parallel_files
|| i
== 1);
1407 p
->start_position
= h
;
1409 /* If we don't truncate lines, all start_positions are
1410 ANYWHERE, except the first column's start_position when
1413 if (!truncate_lines
)
1420 h
= h_next
+ col_sep_length
;
1421 h_next
= h
+ chars_per_column
;
1425 /* The rightmost column.
1427 Doesn't need to be stored unless we intend to balance
1428 columns on the last page. */
1429 if (storing_columns
&& balance_columns
)
1431 p
->char_func
= store_char
;
1432 p
->print_func
= print_stored
;
1436 p
->char_func
= print_char
;
1437 p
->print_func
= read_line
;
1440 p
->numbered
= numbered_lines
&& (!parallel_files
|| i
== 1);
1441 p
->start_position
= h
;
1444 /* Open a file. Return true if successful.
1446 With each file p, p->full_page_printed is initialized,
1447 see also init_fps. */
1450 open_file (char *name
, COLUMN
*p
)
1452 if (STREQ (name
, "-"))
1454 p
->name
= _("standard input");
1456 have_read_stdin
= true;
1461 p
->fp
= fopen (name
, "r");
1465 failed_opens
= true;
1466 if (!ignore_failed_opens
)
1467 error (0, errno
, "%s", quotef (name
));
1470 fadvise (p
->fp
, FADVISE_SEQUENTIAL
);
1472 p
->full_page_printed
= false;
1477 /* Close the file in P.
1479 If we aren't dealing with multiple files in parallel, we change
1480 the status of all columns in the column list to reflect the close. */
1483 close_file (COLUMN
*p
)
1488 if (p
->status
== CLOSED
)
1491 error (EXIT_FAILURE
, errno
, "%s", quotef (p
->name
));
1492 if (fileno (p
->fp
) != STDIN_FILENO
&& fclose (p
->fp
) != 0)
1493 error (EXIT_FAILURE
, errno
, "%s", quotef (p
->name
));
1495 if (!parallel_files
)
1497 for (q
= column_vector
, i
= columns
; i
; ++q
, --i
)
1500 if (q
->lines_stored
== 0)
1502 q
->lines_to_print
= 0;
1509 p
->lines_to_print
= 0;
1512 --files_ready_to_read
;
1515 /* Put a file on hold until we start a new page,
1516 since we've hit a form feed.
1518 If we aren't dealing with parallel files, we must change the
1519 status of all columns in the column list. */
1522 hold_file (COLUMN
*p
)
1527 if (!parallel_files
)
1528 for (q
= column_vector
, i
= columns
; i
; ++q
, --i
)
1530 if (storing_columns
)
1531 q
->status
= FF_FOUND
;
1533 q
->status
= ON_HOLD
;
1536 p
->status
= ON_HOLD
;
1538 p
->lines_to_print
= 0;
1539 --files_ready_to_read
;
1542 /* Undo hold_file -- go through the column list and change any
1543 ON_HOLD columns to OPEN. Used at the end of each page. */
1551 for (p
= column_vector
; i
; --i
, ++p
)
1552 if (p
->status
== ON_HOLD
)
1555 files_ready_to_read
++;
1558 if (storing_columns
)
1560 if (column_vector
->status
== CLOSED
)
1561 /* We use the info to output an error message in skip_to_page. */
1562 files_ready_to_read
= 0;
1564 files_ready_to_read
= 1;
1568 /* Print a single file, or multiple files in parallel.
1570 Set up the list of columns, opening the necessary files.
1571 Allocate space for storing columns, if necessary.
1572 Skip to first_page_number, if user has asked to skip leading pages.
1573 Determine which functions are appropriate to store/print lines
1575 Print the file(s). */
1578 print_files (int number_of_files
, char **av
)
1580 init_parameters (number_of_files
);
1581 if (! init_fps (number_of_files
, av
))
1583 if (storing_columns
)
1586 if (first_page_number
> 1)
1588 if (!skip_to_page (first_page_number
))
1591 page_number
= first_page_number
;
1598 line_number
= line_count
;
1599 while (print_page ())
1603 /* Initialize header information.
1604 If DESC is non-negative, it is a file descriptor open to
1605 FILENAME for reading. */
1608 init_header (char const *filename
, int desc
)
1616 /* If parallel files or standard input, use current date. */
1617 if (STREQ (filename
, "-"))
1619 if (0 <= desc
&& fstat (desc
, &st
) == 0)
1620 t
= get_stat_mtime (&st
);
1623 static struct timespec timespec
;
1624 if (! timespec
.tv_sec
)
1625 gettime (×pec
);
1630 tm
= localtime (&t
.tv_sec
);
1633 buf
= xmalloc (INT_BUFSIZE_BOUND (long int)
1634 + MAX (10, INT_BUFSIZE_BOUND (int)));
1635 sprintf (buf
, "%ld.%09d", (long int) t
.tv_sec
, ns
);
1639 size_t bufsize
= nstrftime (NULL
, SIZE_MAX
, date_format
, tm
, 0, ns
) + 1;
1640 buf
= xmalloc (bufsize
);
1641 nstrftime (buf
, bufsize
, date_format
, tm
, 0, ns
);
1646 file_text
= custom_header
? custom_header
: desc
< 0 ? "" : filename
;
1647 header_width_available
= (chars_per_line
1648 - mbswidth (date_text
, 0)
1649 - mbswidth (file_text
, 0));
1652 /* Set things up for printing a page
1654 Scan through the columns ...
1655 Determine which are ready to print
1656 (i.e., which have lines stored or open files)
1657 Set p->lines_to_print appropriately
1658 (to p->lines_stored if we're storing, or lines_per_body
1659 if we're reading straight from the file)
1660 Keep track of this total so we know when to stop printing */
1668 if (storing_columns
)
1671 for (j
= columns
- 1, p
= column_vector
; j
; --j
, ++p
)
1673 p
->lines_to_print
= p
->lines_stored
;
1677 if (balance_columns
)
1679 p
->lines_to_print
= p
->lines_stored
;
1681 /* Since we're not balancing columns, we don't need to store
1682 the rightmost column. Read it straight from the file. */
1685 if (p
->status
== OPEN
)
1687 p
->lines_to_print
= lines_per_body
;
1690 p
->lines_to_print
= 0;
1694 for (j
= columns
, p
= column_vector
; j
; --j
, ++p
)
1695 if (p
->status
== OPEN
)
1697 p
->lines_to_print
= lines_per_body
;
1700 p
->lines_to_print
= 0;
1703 /* Align empty columns and print separators.
1704 Empty columns will be formed by files with status ON_HOLD or CLOSED
1705 when printing multiple files in parallel. */
1708 align_column (COLUMN
*p
)
1710 padding_not_printed
= p
->start_position
;
1711 if (padding_not_printed
- col_sep_length
> 0)
1713 pad_across_to (padding_not_printed
- col_sep_length
);
1714 padding_not_printed
= ANYWHERE
;
1717 if (use_col_separator
)
1718 print_sep_string ();
1721 add_line_number (p
);
1726 As long as there are lines left on the page and columns ready to print,
1727 Scan across the column list
1728 if the column has stored lines or the file is open
1729 pad to the appropriate spot
1731 pad the remainder of the page with \n or \f as requested
1732 reset the status of all files -- any files which where on hold because
1733 of formfeeds are now put back into the lineup. */
1739 int lines_left_on_page
;
1742 /* Used as an accumulator (with | operator) of successive values of
1743 pad_vertically. The trick is to set pad_vertically
1744 to false before each run through the inner loop, then after that
1745 loop, it tells us whether a line was actually printed (whether a
1746 newline needs to be output -- or two for double spacing). But those
1747 values have to be accumulated (in pv) so we can invoke pad_down
1748 properly after the outer loop completes. */
1753 if (cols_ready_to_print () == 0)
1757 print_a_header
= true;
1759 /* Don't pad unless we know a page was printed. */
1760 pad_vertically
= false;
1763 lines_left_on_page
= lines_per_body
;
1765 lines_left_on_page
*= 2;
1767 while (lines_left_on_page
> 0 && cols_ready_to_print () > 0)
1769 output_position
= 0;
1770 spaces_not_printed
= 0;
1771 separators_not_printed
= 0;
1772 pad_vertically
= false;
1773 align_empty_cols
= false;
1776 for (j
= 1, p
= column_vector
; j
<= columns
; ++j
, ++p
)
1779 if (p
->lines_to_print
> 0 || p
->status
== FF_FOUND
)
1782 padding_not_printed
= p
->start_position
;
1783 if (!(p
->print_func
) (p
))
1784 read_rest_of_line (p
);
1785 pv
|= pad_vertically
;
1787 --p
->lines_to_print
;
1788 if (p
->lines_to_print
<= 0)
1790 if (cols_ready_to_print () == 0)
1794 /* File p changed its status to ON_HOLD or CLOSED */
1795 if (parallel_files
&& p
->status
!= OPEN
)
1798 align_empty_cols
= true;
1799 else if (p
->status
== CLOSED
1800 || (p
->status
== ON_HOLD
&& FF_only
))
1804 else if (parallel_files
)
1806 /* File status ON_HOLD or CLOSED */
1808 align_empty_cols
= true;
1813 /* We need it also with an empty column */
1814 if (use_col_separator
)
1815 ++separators_not_printed
;
1821 --lines_left_on_page
;
1824 if (cols_ready_to_print () == 0 && !extremities
)
1827 if (double_space
&& pv
)
1830 --lines_left_on_page
;
1834 if (lines_left_on_page
== 0)
1835 for (j
= 1, p
= column_vector
; j
<= columns
; ++j
, ++p
)
1836 if (p
->status
== OPEN
)
1837 p
->full_page_printed
= true;
1839 pad_vertically
= pv
;
1841 if (pad_vertically
&& extremities
)
1842 pad_down (lines_left_on_page
+ lines_per_footer
);
1843 else if (keep_FF
&& print_a_FF
)
1849 if (last_page_number
< ++page_number
)
1850 return false; /* Stop printing with LAST_PAGE */
1852 reset_status (); /* Change ON_HOLD to OPEN. */
1854 return true; /* More pages to go. */
1857 /* Allocate space for storing columns.
1859 This is necessary when printing multiple columns from a single file.
1860 Lines are stored consecutively in buff, separated by '\0'.
1862 The following doesn't apply any longer - any tuning possible?
1863 (We can't use a fixed offset since with the '-s' flag lines aren't
1866 We maintain a list (line_vector) of pointers to the beginnings
1867 of lines in buff. We allocate one more than the number of lines
1868 because the last entry tells us the index of the last character,
1869 which we need to know in order to print the last line in buff. */
1872 init_store_cols (void)
1874 int total_lines
= lines_per_body
* columns
;
1875 int chars_if_truncate
= total_lines
* (chars_per_column
+ 1);
1878 /* FIXME: here's where it was allocated. */
1879 line_vector
= xmalloc ((total_lines
+ 1) * sizeof *line_vector
);
1882 end_vector
= xmalloc (total_lines
* sizeof *end_vector
);
1885 buff_allocated
= (use_col_separator
1886 ? 2 * chars_if_truncate
1887 : chars_if_truncate
); /* Tune this. */
1888 buff
= xmalloc (buff_allocated
);
1891 /* Store all but the rightmost column.
1892 (Used when printing a single file in multiple downward columns)
1895 set p->current_line to be the index in line_vector of the
1896 first line in the column
1897 For each line in the column
1898 store the line in buff
1899 add to line_vector the index of the line's first char
1900 buff_start is the index in buff of the first character in the
1904 store_columns (void)
1907 unsigned int line
= 0;
1908 unsigned int buff_start
;
1909 int last_col
; /* The rightmost column which will be saved in buff */
1915 if (balance_columns
)
1918 last_col
= columns
- 1;
1920 for (i
= 1, p
= column_vector
; i
<= last_col
; ++i
, ++p
)
1921 p
->lines_stored
= 0;
1923 for (i
= 1, p
= column_vector
; i
<= last_col
&& files_ready_to_read
;
1926 p
->current_line
= line
;
1927 for (j
= lines_per_body
; j
&& files_ready_to_read
; --j
)
1929 if (p
->status
== OPEN
) /* Redundant. Clean up. */
1934 read_rest_of_line (p
);
1936 if (p
->status
== OPEN
1937 || buff_start
!= buff_current
)
1940 line_vector
[line
] = buff_start
;
1941 end_vector
[line
++] = input_position
;
1942 buff_start
= buff_current
;
1947 /* Keep track of the location of the last char in buff. */
1948 line_vector
[line
] = buff_start
;
1950 if (balance_columns
)
1955 balance (int total_stored
)
1961 for (i
= 1, p
= column_vector
; i
<= columns
; ++i
, ++p
)
1963 lines
= total_stored
/ columns
;
1964 if (i
<= total_stored
% columns
)
1967 p
->lines_stored
= lines
;
1968 p
->current_line
= first_line
;
1970 first_line
+= lines
;
1974 /* Store a character in the buffer. */
1979 if (buff_current
>= buff_allocated
)
1981 /* May be too generous. */
1982 buff
= X2REALLOC (buff
, &buff_allocated
);
1984 buff
[buff_current
++] = c
;
1988 add_line_number (COLUMN
*p
)
1994 /* Cutting off the higher-order digits is more informative than
1995 lower-order cut off. */
1996 num_width
= sprintf (number_buff
, "%*d", chars_per_number
, line_number
);
1998 s
= number_buff
+ (num_width
- chars_per_number
);
1999 for (i
= chars_per_number
; i
> 0; i
--)
2000 (p
->char_func
) (*s
++);
2004 /* Tabification is assumed for multiple columns, also for n-separators,
2005 but 'default n-separator = TAB' hasn't been given priority over
2006 equal column_width also specified by POSIX. */
2007 if (number_separator
== '\t')
2009 i
= number_width
- chars_per_number
;
2011 (p
->char_func
) (' ');
2014 (p
->char_func
) (number_separator
);
2017 /* To comply with POSIX, we avoid any expansion of default TAB
2018 separator with a single column output. No column_width requirement
2019 has to be considered. */
2021 (p
->char_func
) (number_separator
);
2022 if (number_separator
== '\t')
2023 output_position
= POS_AFTER_TAB (chars_per_output_tab
,
2027 if (truncate_lines
&& !parallel_files
)
2028 input_position
+= number_width
;
2031 /* Print (or store) padding until the current horizontal position
2035 pad_across_to (int position
)
2037 int h
= output_position
;
2040 spaces_not_printed
= position
- output_position
;
2043 while (++h
<= position
)
2045 output_position
= position
;
2049 /* Pad to the bottom of the page.
2051 If the user has requested a formfeed, use one.
2052 Otherwise, use newlines. */
2055 pad_down (unsigned int lines
)
2062 for (i
= lines
; i
; --i
)
2066 /* Read the rest of the line.
2068 Read from the current column's file until an end of line is
2069 hit. Used when we've truncated a line and we no longer need
2070 to print or store its characters. */
2073 read_rest_of_line (COLUMN
*p
)
2078 while ((c
= getc (f
)) != '\n')
2082 if ((c
= getc (f
)) != '\n')
2097 /* Read a line with skip_to_page.
2099 Read from the current column's file until an end of line is
2100 hit. Used when we read full lines to skip pages.
2101 With skip_to_page we have to check for FF-coincidence which is done
2102 in function read_line otherwise.
2103 Count lines of skipped pages to find the line number of 1st page
2104 printed relative to 1st line of input file (start_line_num). */
2107 skip_read (COLUMN
*p
, int column_number
)
2112 bool single_ff
= false;
2115 /* Read 1st character in a line or any character succeeding a FF */
2116 if ((c
= getc (f
)) == '\f' && p
->full_page_printed
)
2117 /* A FF-coincidence with a previous full_page_printed.
2118 To avoid an additional empty page, eliminate the FF */
2119 if ((c
= getc (f
)) == '\n')
2122 p
->full_page_printed
= false;
2124 /* 1st character a FF means a single FF without any printable
2125 characters. Don't count it as a line with -n option. */
2129 /* Preparing for a FF-coincidence: Maybe we finish that page
2130 without a FF found */
2132 p
->full_page_printed
= true;
2138 /* No FF-coincidence possible,
2139 no catching up of a FF-coincidence with next page */
2142 if (!parallel_files
)
2143 for (q
= column_vector
, i
= columns
; i
; ++q
, --i
)
2144 q
->full_page_printed
= false;
2146 p
->full_page_printed
= false;
2149 if ((c
= getc (f
)) != '\n')
2163 if ((!parallel_files
|| column_number
== 1) && !single_ff
)
2167 /* If we're tabifying output,
2169 When print_char encounters white space it keeps track
2170 of our desired horizontal position and delays printing
2171 until this function is called. */
2174 print_white_space (void)
2177 int h_old
= output_position
;
2178 int goal
= h_old
+ spaces_not_printed
;
2180 while (goal
- h_old
> 1
2181 && (h_new
= POS_AFTER_TAB (chars_per_output_tab
, h_old
)) <= goal
)
2183 putchar (output_tab_char
);
2186 while (++h_old
<= goal
)
2189 output_position
= goal
;
2190 spaces_not_printed
= 0;
2193 /* Print column separators.
2195 We keep a count until we know that we'll be printing a line,
2196 then print_sep_string() is called. */
2199 print_sep_string (void)
2202 int l
= col_sep_length
;
2206 if (separators_not_printed
<= 0)
2208 /* We'll be starting a line with chars_per_margin, anything else? */
2209 if (spaces_not_printed
> 0)
2210 print_white_space ();
2214 for (; separators_not_printed
> 0; --separators_not_printed
)
2218 /* 3 types of sep_strings: spaces only, spaces and chars,
2222 /* We're tabifying output; consecutive spaces in
2223 sep_string may have to be converted to tabs */
2225 ++spaces_not_printed
;
2229 if (spaces_not_printed
> 0)
2230 print_white_space ();
2235 /* sep_string ends with some spaces */
2236 if (spaces_not_printed
> 0)
2237 print_white_space ();
2242 /* Print (or store, depending on p->char_func) a clump of N
2246 print_clump (COLUMN
*p
, int n
, char *clump
)
2249 (p
->char_func
) (*clump
++);
2252 /* Print a character.
2254 Update the following comment: process-char hasn't been used any
2256 If we're tabifying, all tabs have been converted to spaces by
2257 process_char(). Keep a count of consecutive spaces, and when
2258 a nonspace is encountered, call print_white_space() to print the
2259 required number of tabs and spaces. */
2268 ++spaces_not_printed
;
2271 else if (spaces_not_printed
> 0)
2272 print_white_space ();
2274 /* Nonprintables are assumed to have width 0, except '\b'. */
2275 if (! isprint (to_uchar (c
)))
2286 /* Skip to page PAGE before printing.
2287 PAGE may be larger than total number of pages. */
2290 skip_to_page (uintmax_t page
)
2297 for (n
= 1; n
< page
; ++n
)
2299 for (i
= 1; i
< lines_per_body
; ++i
)
2301 for (j
= 1, p
= column_vector
; j
<= columns
; ++j
, ++p
)
2302 if (p
->status
== OPEN
)
2306 for (j
= 1, p
= column_vector
; j
<= columns
; ++j
, ++p
)
2307 if (p
->status
== OPEN
)
2310 if (storing_columns
) /* change FF_FOUND to ON_HOLD */
2311 for (j
= 1, p
= column_vector
; j
<= columns
; ++j
, ++p
)
2312 if (p
->status
!= CLOSED
)
2313 p
->status
= ON_HOLD
;
2318 if (files_ready_to_read
< 1)
2320 /* It's very helpful, normally the total number of pages is
2321 not known in advance. */
2323 _("starting page number %"PRIuMAX
2324 " exceeds page count %"PRIuMAX
),
2329 return files_ready_to_read
> 0;
2334 Formfeeds are assumed to use up two lines at the beginning of
2340 char page_text
[256 + INT_STRLEN_BOUND (page_number
)];
2341 int available_width
;
2345 output_position
= 0;
2346 pad_across_to (chars_per_margin
);
2347 print_white_space ();
2349 if (page_number
== 0)
2350 error (EXIT_FAILURE
, 0, _("page number overflow"));
2352 /* The translator must ensure that formatting the translation of
2353 "Page %"PRIuMAX does not generate more than (sizeof page_text - 1)
2355 sprintf (page_text
, _("Page %"PRIuMAX
), page_number
);
2356 available_width
= header_width_available
- mbswidth (page_text
, 0);
2357 available_width
= MAX (0, available_width
);
2358 lhs_spaces
= available_width
>> 1;
2359 rhs_spaces
= available_width
- lhs_spaces
;
2361 printf ("\n\n%*s%s%*s%s%*s%s\n\n\n",
2362 chars_per_margin
, "",
2363 date_text
, lhs_spaces
, " ",
2364 file_text
, rhs_spaces
, " ", page_text
);
2366 print_a_header
= false;
2367 output_position
= 0;
2370 /* Print (or store, if p->char_func is store_char()) a line.
2372 Read a character to determine whether we have a line or not.
2373 (We may hit EOF, \n, or \f)
2375 Once we know we have a line,
2376 set pad_vertically = true, meaning it's safe
2377 to pad down at the end of the page, since we do have a page.
2378 print a header if needed.
2379 pad across to padding_not_printed if needed.
2380 print any separators which need to be printed.
2381 print a line number if it needs to be printed.
2383 Print the clump which corresponds to the first character.
2385 Enter a loop and keep printing until an end of line condition
2386 exists, or until we exceed chars_per_column.
2388 Return false if we exceed chars_per_column before reading
2389 an end of line character, true otherwise. */
2392 read_line (COLUMN
*p
)
2395 int chars
IF_LINT ( = 0);
2396 int last_input_position
;
2400 /* read 1st character in each line or any character succeeding a FF: */
2403 last_input_position
= input_position
;
2405 if (c
== '\f' && p
->full_page_printed
)
2406 if ((c
= getc (p
->fp
)) == '\n')
2408 p
->full_page_printed
= false;
2413 if ((c
= getc (p
->fp
)) != '\n')
2416 if (print_a_header
&& !storing_columns
)
2418 pad_vertically
= true;
2431 chars
= char_to_clump (c
);
2434 if (truncate_lines
&& input_position
> chars_per_column
)
2436 input_position
= last_input_position
;
2440 if (p
->char_func
!= store_char
)
2442 pad_vertically
= true;
2444 if (print_a_header
&& !storing_columns
)
2447 if (parallel_files
&& align_empty_cols
)
2449 /* We have to align empty columns at the beginning of a line. */
2450 k
= separators_not_printed
;
2451 separators_not_printed
= 0;
2452 for (j
= 1, q
= column_vector
; j
<= k
; ++j
, ++q
)
2455 separators_not_printed
+= 1;
2457 padding_not_printed
= p
->start_position
;
2459 spaces_not_printed
= chars_per_column
;
2461 spaces_not_printed
= 0;
2462 align_empty_cols
= false;
2465 if (padding_not_printed
- col_sep_length
> 0)
2467 pad_across_to (padding_not_printed
- col_sep_length
);
2468 padding_not_printed
= ANYWHERE
;
2471 if (use_col_separator
)
2472 print_sep_string ();
2476 add_line_number (p
);
2482 print_clump (p
, chars
, clump_buff
);
2493 if ((c
= getc (p
->fp
)) != '\n')
2504 last_input_position
= input_position
;
2505 chars
= char_to_clump (c
);
2506 if (truncate_lines
&& input_position
> chars_per_column
)
2508 input_position
= last_input_position
;
2512 print_clump (p
, chars
, clump_buff
);
2516 /* Print a line from buff.
2518 If this function has been called, we know we have "something to
2519 print". But it remains to be seen whether we have a real text page
2520 or an empty page (a single form feed) with/without a header only.
2521 Therefore first we set pad_vertically to true and print a header
2523 If FF_FOUND and we are using -t|-T option we omit any newline by
2524 setting pad_vertically to false (see print_page).
2525 Otherwise we pad across if necessary, print separators if necessary
2526 and text of COLUMN *p.
2528 Return true, meaning there is no need to call read_rest_of_line. */
2531 print_stored (COLUMN
*p
)
2536 int line
= p
->current_line
++;
2537 char *first
= &buff
[line_vector
[line
]];
2539 UMR: Uninitialized memory read:
2540 * This is occurring while in:
2541 print_stored [pr.c:2239]
2542 * Reading 4 bytes from 0x5148c in the heap.
2543 * Address 0x5148c is 4 bytes into a malloc'd block at 0x51488 of 676 bytes
2544 * This block was allocated from:
2546 xmalloc [xmalloc.c:94]
2547 init_store_cols [pr.c:1648]
2549 char *last
= &buff
[line_vector
[line
+ 1]];
2551 pad_vertically
= true;
2556 if (p
->status
== FF_FOUND
)
2558 for (i
= 1, q
= column_vector
; i
<= columns
; ++i
, ++q
)
2559 q
->status
= ON_HOLD
;
2560 if (column_vector
->lines_to_print
<= 0)
2563 pad_vertically
= false;
2564 return true; /* print a header only */
2568 if (padding_not_printed
- col_sep_length
> 0)
2570 pad_across_to (padding_not_printed
- col_sep_length
);
2571 padding_not_printed
= ANYWHERE
;
2574 if (use_col_separator
)
2575 print_sep_string ();
2577 while (first
!= last
)
2578 print_char (*first
++);
2580 if (spaces_not_printed
== 0)
2582 output_position
= p
->start_position
+ end_vector
[line
];
2583 if (p
->start_position
- col_sep_length
== chars_per_margin
)
2584 output_position
-= col_sep_length
;
2590 /* Convert a character to the proper format and return the number of
2591 characters in the resulting clump. Increment input_position by
2592 the width of the clump.
2594 Tabs are converted to clumps of spaces.
2595 Nonprintable characters may be converted to clumps of escape
2596 sequences or control prefixes.
2598 Note: the width of a clump is not necessarily equal to the number of
2599 characters in clump_buff. (e.g, the width of '\b' is -1, while the
2600 number of characters is 1.) */
2603 char_to_clump (char c
)
2605 unsigned char uc
= c
;
2606 char *s
= clump_buff
;
2611 int chars_per_c
= 8;
2613 if (c
== input_tab_char
)
2614 chars_per_c
= chars_per_input_tab
;
2616 if (c
== input_tab_char
|| c
== '\t')
2618 width
= TAB_WIDTH (chars_per_c
, input_position
);
2622 for (i
= width
; i
; --i
)
2633 else if (! isprint (uc
))
2635 if (use_esc_sequence
)
2640 sprintf (esc_buff
, "%03o", uc
);
2641 for (i
= 0; i
<= 2; ++i
)
2644 else if (use_cntrl_prefix
)
2658 sprintf (esc_buff
, "%03o", uc
);
2659 for (i
= 0; i
<= 2; ++i
)
2683 /* Too many backspaces must put us in position 0 -- never negative. */
2684 if (width
< 0 && input_position
== 0)
2689 else if (width
< 0 && input_position
<= -width
)
2692 input_position
+= width
;
2697 /* We've just printed some files and need to clean up things before
2698 looking for more options and printing the next batch of files.
2700 Free everything we've xmalloc'ed, except 'header'. */
2707 free (column_vector
);
2713 /* Complain, print a usage message, and die. */
2718 if (status
!= EXIT_SUCCESS
)
2723 Usage: %s [OPTION]... [FILE]...\n\
2728 Paginate or columnate FILE(s) for printing.\n\
2732 emit_mandatory_arg_note ();
2735 +FIRST_PAGE[:LAST_PAGE], --pages=FIRST_PAGE[:LAST_PAGE]\n\
2736 begin [stop] printing with page FIRST_[LAST_]PAGE\n\
2737 -COLUMN, --columns=COLUMN\n\
2738 output COLUMN columns and print columns down,\n\
2739 unless -a is used. Balance number of lines in the\n\
2740 columns on each page\n\
2743 -a, --across print columns across rather than down, used together\n\
2745 -c, --show-control-chars\n\
2746 use hat notation (^G) and octal backslash notation\n\
2747 -d, --double-space\n\
2748 double space the output\n\
2751 -D, --date-format=FORMAT\n\
2752 use FORMAT for the header date\n\
2753 -e[CHAR[WIDTH]], --expand-tabs[=CHAR[WIDTH]]\n\
2754 expand input CHARs (TABs) to tab WIDTH (8)\n\
2755 -F, -f, --form-feed\n\
2756 use form feeds instead of newlines to separate pages\n\
2757 (by a 3-line page header with -F or a 5-line header\n\
2758 and trailer without -F)\n\
2761 -h, --header=HEADER\n\
2762 use a centered HEADER instead of filename in page header,\n\
2763 -h \"\" prints a blank line, don't use -h\"\"\n\
2764 -i[CHAR[WIDTH]], --output-tabs[=CHAR[WIDTH]]\n\
2765 replace spaces with CHARs (TABs) to tab WIDTH (8)\n\
2766 -J, --join-lines merge full lines, turns off -W line truncation, no column\n\
2767 alignment, --sep-string[=STRING] sets separators\n\
2770 -l, --length=PAGE_LENGTH\n\
2771 set the page length to PAGE_LENGTH (66) lines\n\
2772 (default number of lines of text 56, and with -F 63).\n\
2773 implies -t if PAGE_LENGTH <= 10\n\
2776 -m, --merge print all files in parallel, one in each column,\n\
2777 truncate lines, but join lines of full length with -J\n\
2780 -n[SEP[DIGITS]], --number-lines[=SEP[DIGITS]]\n\
2781 number lines, use DIGITS (5) digits, then SEP (TAB),\n\
2782 default counting starts with 1st line of input file\n\
2783 -N, --first-line-number=NUMBER\n\
2784 start counting with NUMBER at 1st line of first\n\
2785 page printed (see +FIRST_PAGE)\n\
2788 -o, --indent=MARGIN\n\
2789 offset each line with MARGIN (zero) spaces, do not\n\
2790 affect -w or -W, MARGIN will be added to PAGE_WIDTH\n\
2791 -r, --no-file-warnings\n\
2792 omit warning when a file cannot be opened\n\
2795 -s[CHAR], --separator[=CHAR]\n\
2796 separate columns by a single character, default for CHAR\n\
2797 is the <TAB> character without -w and \'no char\' with -w.\
2799 -s[CHAR] turns off line truncation of all 3 column\n\
2800 options (-COLUMN|-a -COLUMN|-m) except -w is set\n\
2803 -S[STRING], --sep-string[=STRING]\n\
2804 separate columns by STRING,\n\
2805 without -S: Default separator <TAB> with -J and <space>\n\
2806 otherwise (same as -S\" \"), no effect on column options\n\
2809 -t, --omit-header omit page headers and trailers;\n\
2810 implied if PAGE_LENGTH <= 10\n\
2813 -T, --omit-pagination\n\
2814 omit page headers and trailers, eliminate any pagination\n\
2815 by form feeds set in input files\n\
2816 -v, --show-nonprinting\n\
2817 use octal backslash notation\n\
2818 -w, --width=PAGE_WIDTH\n\
2819 set page width to PAGE_WIDTH (72) characters for\n\
2820 multiple text-column output only, -s[char] turns off (72)\n\
2823 -W, --page-width=PAGE_WIDTH\n\
2824 set page width to PAGE_WIDTH (72) characters always,\n\
2825 truncate lines, except -J option is set, no interference\n\
2828 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
2829 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
2830 emit_ancillary_info (PROGRAM_NAME
);